Skip to main content

fp_join/
lib.rs

1#![forbid(unsafe_code)]
2#![warn(rustdoc::broken_intra_doc_links)]
3
4//! Merge / join engine for **frankenpandas** — implements
5//! pandas-shape `pd.merge` / `pd.merge_ordered` / `pd.merge_asof`
6//! / `Series.join` for DataFrame and Series operands.
7//!
8//! ## Why a separate crate
9//!
10//! Joins have substantial machinery — hash-build phases, asof
11//! search, validate-mode integrity checks, bumpalo-backed
12//! intermediate buffers — that doesn't belong inside fp-frame's
13//! row/column primitives. fp-join layers on top of fp-columnar /
14//! fp-index / fp-frame and exposes a merge surface matching the
15//! pandas API shape.
16//!
17//! ## Top-level entry points
18//!
19//! - [`join_series`] / [`join_series_with_options`]: pandas
20//!   `Series.join(other, how=...)`. Returns a [`JoinedSeries`].
21//! - [`merge_dataframes`]: index-on-index merge (pandas
22//!   `df.merge(other, left_index=True, right_index=True)`).
23//! - [`merge_dataframes_on`] / [`merge_dataframes_on_with`] /
24//!   [`merge_dataframes_on_with_options`]: column-key merge
25//!   (`pd.merge(left, right, on=...)`). Returns a
26//!   [`MergedDataFrame`].
27//! - [`merge_ordered`]: pandas `pd.merge_ordered(left, right,
28//!   on=...)` — preserves ordering for time-series merges.
29//! - [`merge_asof`] / [`merge_asof_with_options`]: pandas
30//!   `pd.merge_asof(left, right, on=..., direction=...)` for
31//!   nearest-key time-aware merges. [`AsofDirection`] /
32//!   [`MergeAsofOptions`] tune the search.
33//!
34//! ## DataFrame extension trait
35//!
36//! [`DataFrameMergeExt`] adds `df.merge(...)` / `df.join(...)`
37//! method-style entry points so callers get fluent chaining
38//! after `use fp_join::DataFrameMergeExt;`.
39//!
40//! ## Tunables
41//!
42//! - [`JoinType`]: `Inner` / `Left` / `Right` / `Outer` /
43//!   `Cross`.
44//! - [`MergeValidateMode`]: pandas `validate='one_to_one' |
45//!   'one_to_many' | 'many_to_one' | 'many_to_many'` integrity
46//!   check before producing the result.
47//! - [`JoinExecutionOptions`] / [`MergeExecutionOptions`]:
48//!   per-call knobs (suffixes for overlapping columns, indicator
49//!   column, sort policy, ...).
50//!
51//! ## Error reporting
52//!
53//! [`JoinError`] enumerates the failure modes (key column
54//! mismatch, validate-mode violation, dtype mismatch on key
55//! column, ...).
56//!
57//! ## Cross-crate relationships
58//!
59//! - **fp-columnar** ([`Column`], [`ColumnError`]) for column
60//!   storage operations.
61//! - **fp-frame** for the `DataFrame` / `Series` value types.
62//! - **fp-index** for row alignment plans + label types.
63//! - **fp-types** for the underlying scalar machinery.
64
65use std::{
66    cmp::Ordering,
67    collections::{HashMap, HashSet},
68    mem::size_of,
69    sync::{Arc, OnceLock},
70};
71
72use bumpalo::{Bump, collections::Vec as BumpVec};
73use fp_columnar::{
74    Column, ColumnError, Int64DenseCycleWitness, Utf8LowerHexSequence, ValidityMask,
75};
76use fp_frame::{ColumnStore, FrameError, Series};
77use fp_index::{Index, IndexLabel};
78use fp_types::{DType, NullKind, Scalar, TypeError};
79// Join build maps key on &IndexLabel / &CompositeJoinKey and are LOOKUP-only:
80// output row order comes from probe-side iteration and per-key insertion-order
81// position Vecs, never from map iteration. So SipHash -> FxHash (rustc-hash,
82// pure safe Rust) is observationally invisible. SipHash over these label/key
83// byte images is pathologically slow (cf. fp-index dedup 3-4x); FxHash collapses
84// the build+probe hashing cost on the merge hot path.
85use rustc_hash::{FxHashMap, FxHashSet};
86use thiserror::Error;
87
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub enum JoinType {
90    Inner,
91    Left,
92    Right,
93    Outer,
94    Cross,
95}
96
97#[derive(Debug, Clone, Copy, PartialEq, Eq)]
98pub enum MergeValidateMode {
99    OneToOne,
100    OneToMany,
101    ManyToOne,
102    ManyToMany,
103}
104
105impl MergeValidateMode {
106    fn as_str(self) -> &'static str {
107        match self {
108            Self::OneToOne => "one_to_one",
109            Self::OneToMany => "one_to_many",
110            Self::ManyToOne => "many_to_one",
111            Self::ManyToMany => "many_to_many",
112        }
113    }
114}
115
116#[derive(Debug, Clone, PartialEq)]
117pub struct JoinedSeries {
118    pub index: Index,
119    pub left_values: Column,
120    pub right_values: Column,
121}
122
123#[derive(Debug, Error)]
124pub enum JoinError {
125    #[error(transparent)]
126    Frame(#[from] FrameError),
127    #[error(transparent)]
128    Column(#[from] ColumnError),
129}
130
131pub const DEFAULT_ARENA_BUDGET_BYTES: usize = 256 * 1024 * 1024;
132
133#[derive(Debug, Clone, Copy, PartialEq, Eq)]
134pub struct JoinExecutionOptions {
135    pub use_arena: bool,
136    pub arena_budget_bytes: usize,
137}
138
139impl Default for JoinExecutionOptions {
140    fn default() -> Self {
141        Self {
142            use_arena: true,
143            arena_budget_bytes: DEFAULT_ARENA_BUDGET_BYTES,
144        }
145    }
146}
147
148#[derive(Debug, Clone, Default, PartialEq, Eq)]
149pub struct MergeExecutionOptions {
150    pub indicator_name: Option<String>,
151    pub validate_mode: Option<MergeValidateMode>,
152    pub suffixes: Option<[Option<String>; 2]>,
153    pub sort: bool,
154}
155
156#[derive(Debug, Clone, Copy, PartialEq, Eq)]
157struct JoinExecutionTrace {
158    used_arena: bool,
159    output_rows: usize,
160    estimated_bytes: usize,
161}
162
163pub fn join_series(
164    left: &Series,
165    right: &Series,
166    join_type: JoinType,
167) -> Result<JoinedSeries, JoinError> {
168    join_series_with_options(left, right, join_type, JoinExecutionOptions::default())
169}
170
171pub fn join_series_with_options(
172    left: &Series,
173    right: &Series,
174    join_type: JoinType,
175    options: JoinExecutionOptions,
176) -> Result<JoinedSeries, JoinError> {
177    let (joined, _) = join_series_with_trace(left, right, join_type, options)?;
178    Ok(joined)
179}
180
181fn join_series_with_trace(
182    left: &Series,
183    right: &Series,
184    join_type: JoinType,
185    options: JoinExecutionOptions,
186) -> Result<(JoinedSeries, JoinExecutionTrace), JoinError> {
187    // AG-02: borrowed-key HashMap eliminates right-index label clones during build phase.
188    let right_map = if matches!(join_type, JoinType::Right) {
189        FxHashMap::<&IndexLabel, Vec<usize>>::default()
190    } else {
191        let mut m = FxHashMap::<&IndexLabel, Vec<usize>>::default();
192        for (pos, label) in right.index().labels().iter().enumerate() {
193            m.entry(label).or_default().push(pos);
194        }
195        m
196    };
197
198    // For Right/Outer joins, also build a left_map.
199    let left_map = if matches!(join_type, JoinType::Right | JoinType::Outer) {
200        let mut m = FxHashMap::<&IndexLabel, Vec<usize>>::default();
201        for (pos, label) in left.index().labels().iter().enumerate() {
202            m.entry(label).or_default().push(pos);
203        }
204        Some(m)
205    } else {
206        None
207    };
208
209    let output_rows = estimate_output_rows(left, right, &right_map, left_map.as_ref(), join_type);
210    let estimated_bytes = estimate_intermediate_bytes(output_rows);
211    let use_arena = options.use_arena && estimated_bytes <= options.arena_budget_bytes;
212
213    let joined = if use_arena {
214        join_series_with_arena(
215            left,
216            right,
217            join_type,
218            &right_map,
219            left_map.as_ref(),
220            output_rows,
221        )?
222    } else {
223        join_series_with_global_allocator(
224            left,
225            right,
226            join_type,
227            &right_map,
228            left_map.as_ref(),
229            output_rows,
230        )?
231    };
232
233    Ok((
234        joined,
235        JoinExecutionTrace {
236            used_arena: use_arena,
237            output_rows,
238            estimated_bytes,
239        },
240    ))
241}
242
243fn estimate_output_rows(
244    left: &Series,
245    right: &Series,
246    right_map: &FxHashMap<&IndexLabel, Vec<usize>>,
247    left_map: Option<&FxHashMap<&IndexLabel, Vec<usize>>>,
248    join_type: JoinType,
249) -> usize {
250    if matches!(join_type, JoinType::Right) {
251        return right
252            .index()
253            .labels()
254            .iter()
255            .map(|label| match left_map.as_ref().and_then(|m| m.get(label)) {
256                Some(matches) => matches.len(),
257                None => 1,
258            })
259            .sum();
260    }
261
262    let left_matched: usize = left
263        .index()
264        .labels()
265        .iter()
266        .map(|label| match right_map.get(label) {
267            Some(matches) => matches.len(),
268            None if matches!(join_type, JoinType::Left | JoinType::Outer) => 1,
269            None => 0,
270        })
271        .sum();
272
273    match join_type {
274        JoinType::Inner | JoinType::Left => left_matched,
275        JoinType::Right => left_matched,
276        JoinType::Cross => left
277            .index()
278            .labels()
279            .len()
280            .saturating_mul(right.index().labels().len()),
281        JoinType::Outer => {
282            // Left-matched rows + unmatched right rows
283            let right_unmatched: usize = right
284                .index()
285                .labels()
286                .iter()
287                .filter(|label| {
288                    !left_map
289                        .as_ref()
290                        .expect("Outer needs left_map")
291                        .contains_key(*label)
292                })
293                .count();
294            left_matched + right_unmatched
295        }
296    }
297}
298
299fn estimate_intermediate_bytes(output_rows: usize) -> usize {
300    output_rows.saturating_mul(
301        size_of::<Option<usize>>()
302            .saturating_mul(2)
303            .saturating_add(size_of::<IndexLabel>()),
304    )
305}
306
307/// Gather a join/merge output column, applying pandas' widening when the join
308/// INVENTS a gap in it.
309///
310/// MEASURED, live pandas 2.2.3. The rule is driven by whether a gap actually
311/// lands in THIS column, not by the join type:
312///
313/// ```text
314/// l = DataFrame({'l': [10, 20, 30]}, index=[1,2,3]);  r = DataFrame({'r': [200]}, index=[2])
315///   l.join(r, how='left')   -> l int64 [10,20,30]     r float64 [nan, 200.0, nan]
316///   l.join(r, how='outer')  -> l int64 [10,20,30]     r float64 [nan, 200.0, nan]
317///   l.join(r, how='right')  -> l int64 [20]           r int64   [200]
318///   l.join(r, how='inner')  -> l int64 [20]           r int64   [200]
319/// ```
320///
321/// `l` keeps int64 on a LEFT join because it gains no gap; `r` widens on both
322/// left and outer because it does. right/inner invent nothing, so nothing
323/// widens. This function was previously called only for `JoinType::Outer`,
324/// which is why a left merge left `Int64` + `Null(Null)` where pandas has
325/// `float64` + `nan`. (br-frankenpandas-nywa8)
326///
327/// The all-valid guard is the same condition concat needed: a column that
328/// ALREADY carried a missing value is nullable, and a nullable int CAN hold the
329/// gap, so pandas keeps it. Measured:
330///
331/// ```text
332/// rv as numpy int64        , left merge -> float64 [nan, 5.0, 7.0]
333/// rv as nullable  Int64    , left merge -> Int64   [<NA>, 5, <NA>]
334/// ```
335fn reindex_join_column_with_invented_gap(
336    column: &Column,
337    positions: &[Option<usize>],
338) -> Result<Column, JoinError> {
339    if !matches!(
340        column.dtype(),
341        fp_types::DType::Int64 | fp_types::DType::Float64
342    ) {
343        return Ok(reindex_non_numeric_join_column_with_invented_gap(
344            column, positions,
345        )?);
346    }
347
348    let has_missing = positions
349        .iter()
350        .any(|slot| slot.is_none_or(|idx| idx >= column.len()));
351    if !has_missing {
352        return Ok(column.reindex_by_positions(positions)?);
353    }
354
355    // A source that already carries a gap is NULLABLE; pandas keeps the dtype
356    // and fills with NA rather than widening. Only an all-valid numpy column
357    // has to widen to hold the invented gap.
358    if column.values().iter().any(fp_types::Scalar::is_missing) {
359        return Ok(column.reindex_by_positions(positions)?);
360    }
361
362    // Typed Float64-promote gather (br-frankenpandas-1bvcl): all-valid
363    // Int64/Float64 sources skip the per-row Scalar clone + cast +
364    // Column::new revalidation below — bit-identical (see the method's
365    // isomorphism notes in fp-columnar).
366    if let Some(column) = column.reindex_promote_float64_by_optional_positions(positions) {
367        return Ok(column);
368    }
369
370    let values = positions
371        .iter()
372        .map(|slot| match slot {
373            Some(idx) => column
374                .values()
375                .get(*idx)
376                .cloned()
377                .unwrap_or(fp_types::Scalar::Null(fp_types::NullKind::NaN)),
378            None => fp_types::Scalar::Null(fp_types::NullKind::NaN),
379        })
380        .map(|value| {
381            fp_types::cast_scalar_owned(value, fp_types::DType::Float64).map_err(ColumnError::from)
382        })
383        .collect::<Result<Vec<_>, ColumnError>>()?;
384
385    Ok(Column::new(fp_types::DType::Float64, values)?)
386}
387
388/// Gather a NON-numeric join/merge output column, minting the gap marker pandas
389/// uses for that dtype rather than the column's canonical missing.
390///
391/// A merge that invents a gap does NOT get to fill it with the dtype's own
392/// missing value. MEASURED, live pandas 2.2.3, one row invented on each side of
393/// `DataFrame({'id':[1,2,3]}).merge(DataFrame({'id':[2],'w':...}), how='left')`:
394///
395/// ```text
396///   w object/str   -> dtype object          [nan, 'x', nan]        float nan
397///   w bool         -> dtype object          [nan, True, nan]       float nan
398///   w category     -> dtype category        [nan, 'x', nan]        float nan
399///   w datetime64   -> dtype datetime64[ns]  [NaT, Timestamp, NaT]  NaT
400///   w timedelta64  -> dtype timedelta64[ns] [NaT, Timedelta, NaT]  NaT
401/// ```
402///
403/// So the temporal dtypes already agree with `Scalar::missing_for_dtype` (NaT)
404/// and keep the plain gather. The string/bool/categorical lanes do not: their
405/// canonical missing is `Null(Null)`, which is right for a SUPPLIED None
406/// (nywa8 Rule 2 — object is the dtype that can store one) and wrong for a gap
407/// the join INVENTED (Rule 1 — pandas writes a float nan even into an object
408/// column). Only this site knows which it is minting, which is the same reason
409/// the promotion above could not move into `infer_dtype`.
410///
411/// THE TWO RULES MEET INSIDE A SINGLE COLUMN, which is what makes a dtype-level
412/// table unable to express this. Measured on the composite outer merge behind
413/// `fp_p2d_033_dataframe_merge_composite_left_right_alias_outer_hardened`, with
414/// `lk2 = ['a', None, 'c']` against `rk2 = ['a', None, 'd']`:
415///
416/// ```text
417///   lk2 dtype object, kinds ['str', 'NoneType', 'str', 'float']
418///                                     ^ supplied        ^ invented
419/// ```
420///
421/// Row 1's `None` is data and survives; row 3's gap is the join's and is a nan.
422/// Copying the source cell through unchanged and substituting only for an absent
423/// position gives exactly that split, so no all-valid guard belongs here — that
424/// guard governs the numeric WIDENING above, not the marker.
425///
426/// ⚠️ pandas ALSO widens a numpy `bool` lane to object when it takes a gap. That
427/// is a dtype change FrankenPandas does not make (it keeps `DType::Bool` with the
428/// position invalid), and no fixture covers it; only the marker is corrected
429/// here. Left as-is deliberately rather than folded in unmeasured — widening bool
430/// touches br-frankenpandas-lufpu's bool-family contract and needs its own probe.
431///
432/// (br-frankenpandas-nywa8)
433fn reindex_non_numeric_join_column_with_invented_gap(
434    column: &Column,
435    positions: &[Option<usize>],
436) -> Result<Column, ColumnError> {
437    if !matches!(
438        column.dtype(),
439        fp_types::DType::Utf8 | fp_types::DType::Bool | fp_types::DType::Categorical
440    ) {
441        return column.reindex_by_positions(positions);
442    }
443
444    column.reindex_by_positions_with_absent_scalar(
445        positions,
446        fp_types::Scalar::Null(fp_types::NullKind::NaN),
447    )
448}
449
450fn coalesce_utf8_contiguous_key_column(
451    left_key_col: &Column,
452    right_key_col: &Column,
453    left_positions: &[Option<usize>],
454    right_positions: &[Option<usize>],
455) -> Option<Column> {
456    let (left_bytes, left_offsets) = left_key_col.as_utf8_contiguous()?;
457    let (right_bytes, right_offsets) = right_key_col.as_utf8_contiguous()?;
458    if left_positions.len() != right_positions.len() {
459        return None;
460    }
461
462    let mut byte_len = 0usize;
463    for (left_pos, right_pos) in left_positions.iter().zip(right_positions.iter()) {
464        let (bytes, offsets, pos) = match (left_pos, right_pos) {
465            (Some(pos), _) => (left_bytes, left_offsets, *pos),
466            (None, Some(pos)) => (right_bytes, right_offsets, *pos),
467            (None, None) => return None,
468        };
469        let end = pos.checked_add(1)?;
470        let start_offset = *offsets.get(pos)?;
471        let end_offset = *offsets.get(end)?;
472        if end_offset < start_offset || end_offset > bytes.len() {
473            return None;
474        }
475        byte_len = byte_len.checked_add(end_offset - start_offset)?;
476    }
477
478    let mut bytes = Vec::with_capacity(byte_len);
479    let mut offsets = Vec::with_capacity(left_positions.len() + 1);
480    offsets.push(0);
481    for (left_pos, right_pos) in left_positions.iter().zip(right_positions.iter()) {
482        let (source_bytes, source_offsets, pos) = match (left_pos, right_pos) {
483            (Some(pos), _) => (left_bytes, left_offsets, *pos),
484            (None, Some(pos)) => (right_bytes, right_offsets, *pos),
485            (None, None) => return None,
486        };
487        let start = *source_offsets.get(pos)?;
488        let end = *source_offsets.get(pos.checked_add(1)?)?;
489        bytes.extend_from_slice(source_bytes.get(start..end)?);
490        offsets.push(bytes.len());
491    }
492    Some(Column::from_utf8_contiguous(bytes, offsets))
493}
494
495/// Coalesce an all-valid temporal OUTER key directly over raw nanoseconds.
496///
497/// The optional position tapes already define output order and matched-row
498/// precedence. Any malformed tape, nullable input, mixed dtype, out-of-bounds
499/// position, or selected NaT declines to the existing Scalar fallback.
500fn coalesce_temporal_i64_key_column(
501    left_key_col: &Column,
502    right_key_col: &Column,
503    left_positions: &[Option<usize>],
504    right_positions: &[Option<usize>],
505) -> Option<Column> {
506    if left_positions.len() != right_positions.len()
507        || !left_key_col.validity().all()
508        || !right_key_col.validity().all()
509    {
510        return None;
511    }
512
513    let (left_keys, right_keys, nat, datetime_dtype) =
514        match (left_key_col.dtype(), right_key_col.dtype()) {
515            (DType::Datetime64 { tz: left_tz }, DType::Datetime64 { tz: right_tz })
516                if left_tz == right_tz =>
517            {
518                (
519                    left_key_col.as_datetime64_slice()?,
520                    right_key_col.as_datetime64_slice()?,
521                    fp_types::Timestamp::NAT,
522                    Some(DType::Datetime64 { tz: left_tz }),
523                )
524            }
525            (DType::Timedelta64, DType::Timedelta64) => (
526                left_key_col.as_timedelta64_slice()?,
527                right_key_col.as_timedelta64_slice()?,
528                fp_types::Timedelta::NAT,
529                None,
530            ),
531            _ => return None,
532        };
533
534    let mut data = Vec::with_capacity(left_positions.len());
535    for (left_pos, right_pos) in left_positions.iter().zip(right_positions.iter()) {
536        let value = match (*left_pos, *right_pos) {
537            (Some(pos), _) => *left_keys.get(pos)?,
538            (None, Some(pos)) => *right_keys.get(pos)?,
539            (None, None) => return None,
540        };
541        if value == nat {
542            return None;
543        }
544        data.push(value);
545    }
546
547    let validity = ValidityMask::all_valid(data.len());
548    Some(if let Some(dtype) = datetime_dtype {
549        Column::from_datetime64_values_with_validity(data, validity).with_dtype(dtype)
550    } else {
551        Column::from_timedelta64_values_with_validity(data, validity)
552    })
553}
554
555enum SharedOptionalUtf8GatherPlan {
556    NullableRange {
557        null_prefix: usize,
558        source_start: usize,
559        source_len: usize,
560        null_suffix: usize,
561    },
562    Positions {
563        positions: Arc<[usize]>,
564        validity: ValidityMask,
565    },
566}
567
568fn shared_optional_utf8_gather_plan(
569    positions: &[Option<usize>],
570    source_len: usize,
571) -> Option<SharedOptionalUtf8GatherPlan> {
572    let mut first_valid = None;
573    let mut last_valid_exclusive = 0usize;
574    let mut has_missing = false;
575    for (out_idx, slot) in positions.iter().enumerate() {
576        match slot {
577            Some(idx) if *idx < source_len => {
578                first_valid.get_or_insert(out_idx);
579                last_valid_exclusive = out_idx + 1;
580            }
581            _ => has_missing = true,
582        }
583    }
584    if !has_missing {
585        return None;
586    }
587    if let Some(first_valid) = first_valid {
588        let source_start = positions.get(first_valid).copied().flatten()?;
589        let valid_len = last_valid_exclusive - first_valid;
590        let valid_window = positions.get(first_valid..last_valid_exclusive)?;
591        let contiguous = valid_window
592            .iter()
593            .enumerate()
594            .all(|(offset, slot)| *slot == Some(source_start + offset));
595        if contiguous
596            && source_start
597                .checked_add(valid_len)
598                .is_some_and(|end| end <= source_len)
599        {
600            return Some(SharedOptionalUtf8GatherPlan::NullableRange {
601                null_prefix: first_valid,
602                source_start,
603                source_len: valid_len,
604                null_suffix: positions.len() - last_valid_exclusive,
605            });
606        }
607    } else {
608        return Some(SharedOptionalUtf8GatherPlan::NullableRange {
609            null_prefix: positions.len(),
610            source_start: 0,
611            source_len: 0,
612            null_suffix: 0,
613        });
614    }
615
616    let mut plan = Vec::with_capacity(positions.len());
617    let mut words = vec![0_u64; positions.len().div_ceil(64)];
618    for (out_idx, slot) in positions.iter().enumerate() {
619        match slot {
620            Some(idx) if *idx < source_len => {
621                plan.push(*idx);
622                words[out_idx / 64] |= 1_u64 << (out_idx % 64);
623            }
624            _ => plan.push(usize::MAX),
625        }
626    }
627    Some(SharedOptionalUtf8GatherPlan::Positions {
628        positions: Arc::from(plan),
629        validity: ValidityMask::from_words(words, positions.len()),
630    })
631}
632
633fn reindex_with_shared_utf8_plan(
634    column: &Column,
635    positions: &[Option<usize>],
636    plan: Option<&SharedOptionalUtf8GatherPlan>,
637) -> Result<Column, JoinError> {
638    if let Some(column) = plan.and_then(|plan| reindex_eager_utf8_with_plan(column, plan)) {
639        return Ok(column);
640    }
641    // A gap here is one the join invents: NaN, as pandas (it was None;
642    // br-frankenpandas-7u2td).
643    Ok(reindex_non_numeric_join_column_with_invented_gap(
644        column, positions,
645    )?)
646}
647
648fn reindex_outer_with_shared_utf8_plan(
649    column: &Column,
650    positions: &[Option<usize>],
651    plan: Option<&SharedOptionalUtf8GatherPlan>,
652) -> Result<Column, JoinError> {
653    if let Some(column) = plan.and_then(|plan| reindex_eager_utf8_with_plan(column, plan)) {
654        return Ok(column);
655    }
656    reindex_join_column_with_invented_gap(column, positions)
657}
658
659fn reindex_eager_utf8_with_plan(
660    column: &Column,
661    plan: &SharedOptionalUtf8GatherPlan,
662) -> Option<Column> {
663    match plan {
664        SharedOptionalUtf8GatherPlan::NullableRange {
665            null_prefix,
666            source_start,
667            source_len,
668            null_suffix,
669        } => column.reindex_eager_utf8_with_nullable_range(
670            *null_prefix,
671            *source_start,
672            *source_len,
673            *null_suffix,
674        ),
675        SharedOptionalUtf8GatherPlan::Positions {
676            positions,
677            validity,
678        } => column.reindex_eager_utf8_with_shared_plan(Arc::clone(positions), validity.clone()),
679    }
680}
681
682fn sort_outer_join_rows(
683    out_labels: &mut Vec<IndexLabel>,
684    left_positions: &mut [Option<usize>],
685    right_positions: &mut [Option<usize>],
686) {
687    if out_labels.len() <= 1 {
688        return;
689    }
690
691    let mut rows = out_labels
692        .drain(..)
693        .zip(left_positions.iter().copied())
694        .zip(right_positions.iter().copied())
695        .map(|((label, left_pos), right_pos)| (label, left_pos, right_pos))
696        .collect::<Vec<_>>();
697    rows.sort_by(|left, right| left.0.cmp(&right.0));
698
699    for (idx, (label, left_pos, right_pos)) in rows.into_iter().enumerate() {
700        out_labels.push(label);
701        left_positions[idx] = left_pos;
702        right_positions[idx] = right_pos;
703    }
704}
705
706fn join_series_with_global_allocator(
707    left: &Series,
708    right: &Series,
709    join_type: JoinType,
710    right_map: &FxHashMap<&IndexLabel, Vec<usize>>,
711    left_map: Option<&FxHashMap<&IndexLabel, Vec<usize>>>,
712    output_rows: usize,
713) -> Result<JoinedSeries, JoinError> {
714    let mut out_labels = Vec::with_capacity(output_rows);
715    let mut left_positions = Vec::<Option<usize>>::with_capacity(output_rows);
716    let mut right_positions = Vec::<Option<usize>>::with_capacity(output_rows);
717
718    match join_type {
719        JoinType::Inner | JoinType::Left | JoinType::Outer => {
720            // Iterate left labels: emit matches and (for Left/Outer) unmatched left rows.
721            for (left_pos, label) in left.index().labels().iter().enumerate() {
722                if let Some(matches) = right_map.get(label) {
723                    for right_pos in matches {
724                        out_labels.push(label.clone());
725                        left_positions.push(Some(left_pos));
726                        right_positions.push(Some(*right_pos));
727                    }
728                    continue;
729                }
730
731                if matches!(join_type, JoinType::Left | JoinType::Outer) {
732                    out_labels.push(label.clone());
733                    left_positions.push(Some(left_pos));
734                    right_positions.push(None);
735                }
736            }
737
738            // For Outer: append right labels that have no match in left.
739            if matches!(join_type, JoinType::Outer) {
740                let left_map = left_map.as_ref().expect("left_map required for Outer join");
741                for (right_pos, label) in right.index().labels().iter().enumerate() {
742                    if !left_map.contains_key(label) {
743                        out_labels.push(label.clone());
744                        left_positions.push(None);
745                        right_positions.push(Some(right_pos));
746                    }
747                }
748            }
749        }
750        JoinType::Right => {
751            // Iterate right labels: emit matches and unmatched right rows.
752            let left_map = left_map.expect("left_map required for Right join");
753            for (right_pos, label) in right.index().labels().iter().enumerate() {
754                if let Some(matches) = left_map.get(label) {
755                    for left_pos in matches {
756                        out_labels.push(label.clone());
757                        left_positions.push(Some(*left_pos));
758                        right_positions.push(Some(right_pos));
759                    }
760                    continue;
761                }
762
763                out_labels.push(label.clone());
764                left_positions.push(None);
765                right_positions.push(Some(right_pos));
766            }
767        }
768        JoinType::Cross => {
769            for (left_pos, left_label) in left.index().labels().iter().enumerate() {
770                for (right_pos, _) in right.index().labels().iter().enumerate() {
771                    out_labels.push(left_label.clone());
772                    left_positions.push(Some(left_pos));
773                    right_positions.push(Some(right_pos));
774                }
775            }
776        }
777    }
778
779    if matches!(join_type, JoinType::Outer) {
780        sort_outer_join_rows(&mut out_labels, &mut left_positions, &mut right_positions);
781    }
782
783    // Every join type, not just Outer: the widening is caused by a gap landing
784    // in THIS column, and a left join invents gaps on the right side just as an
785    // outer join does. The helper is a no-op when no gap is invented, so
786    // right/inner are unaffected. (br-frankenpandas-nywa8)
787    let left_values = reindex_join_column_with_invented_gap(left.column(), &left_positions)?;
788    let right_values = reindex_join_column_with_invented_gap(right.column(), &right_positions)?;
789
790    // Per br-frankenpandas-wp0n6: pandas Series.join preserves shared
791    // index name (preserved when both operands agree, None when they differ).
792    let shared_name = if left.index().name().eq(&right.index().name()) {
793        left.index().name().cloned()
794    } else {
795        None
796    };
797    Ok(JoinedSeries {
798        index: Index::new(out_labels).rename_index(shared_name),
799        left_values,
800        right_values,
801    })
802}
803
804fn join_series_with_arena(
805    left: &Series,
806    right: &Series,
807    join_type: JoinType,
808    right_map: &FxHashMap<&IndexLabel, Vec<usize>>,
809    left_map: Option<&FxHashMap<&IndexLabel, Vec<usize>>>,
810    output_rows: usize,
811) -> Result<JoinedSeries, JoinError> {
812    let arena = Bump::new();
813    let mut out_labels = Vec::with_capacity(output_rows);
814    let mut left_positions = BumpVec::<Option<usize>>::with_capacity_in(output_rows, &arena);
815    let mut right_positions = BumpVec::<Option<usize>>::with_capacity_in(output_rows, &arena);
816
817    match join_type {
818        JoinType::Inner | JoinType::Left | JoinType::Outer => {
819            for (left_pos, label) in left.index().labels().iter().enumerate() {
820                if let Some(matches) = right_map.get(label) {
821                    for right_pos in matches {
822                        out_labels.push(label.clone());
823                        left_positions.push(Some(left_pos));
824                        right_positions.push(Some(*right_pos));
825                    }
826                    continue;
827                }
828
829                if matches!(join_type, JoinType::Left | JoinType::Outer) {
830                    out_labels.push(label.clone());
831                    left_positions.push(Some(left_pos));
832                    right_positions.push(None);
833                }
834            }
835
836            if matches!(join_type, JoinType::Outer) {
837                let left_map = left_map.as_ref().expect("left_map required for Outer join");
838                for (right_pos, label) in right.index().labels().iter().enumerate() {
839                    if !left_map.contains_key(label) {
840                        out_labels.push(label.clone());
841                        left_positions.push(None);
842                        right_positions.push(Some(right_pos));
843                    }
844                }
845            }
846        }
847        JoinType::Right => {
848            let left_map = left_map.expect("left_map required for Right join");
849            for (right_pos, label) in right.index().labels().iter().enumerate() {
850                if let Some(matches) = left_map.get(label) {
851                    for left_pos in matches {
852                        out_labels.push(label.clone());
853                        left_positions.push(Some(*left_pos));
854                        right_positions.push(Some(right_pos));
855                    }
856                    continue;
857                }
858
859                out_labels.push(label.clone());
860                left_positions.push(None);
861                right_positions.push(Some(right_pos));
862            }
863        }
864        JoinType::Cross => {
865            for (left_pos, left_label) in left.index().labels().iter().enumerate() {
866                for (right_pos, _) in right.index().labels().iter().enumerate() {
867                    out_labels.push(left_label.clone());
868                    left_positions.push(Some(left_pos));
869                    right_positions.push(Some(right_pos));
870                }
871            }
872        }
873    }
874
875    if matches!(join_type, JoinType::Outer) {
876        sort_outer_join_rows(
877            &mut out_labels,
878            left_positions.as_mut_slice(),
879            right_positions.as_mut_slice(),
880        );
881    }
882
883    // Every join type — see the sibling site above (br-frankenpandas-nywa8).
884    let left_values =
885        reindex_join_column_with_invented_gap(left.column(), left_positions.as_slice())?;
886    let right_values =
887        reindex_join_column_with_invented_gap(right.column(), right_positions.as_slice())?;
888
889    // Per br-frankenpandas-ceces: pandas Series.join preserves shared
890    // index name. Sister to join_series fix (wp0n6).
891    let shared_name = if left.index().name().eq(&right.index().name()) {
892        left.index().name().cloned()
893    } else {
894        None
895    };
896    Ok(JoinedSeries {
897        index: Index::new(out_labels).rename_index(shared_name),
898        left_values,
899        right_values,
900    })
901}
902
903/// Result of a DataFrame merge operation.
904#[derive(Debug, Clone, PartialEq)]
905pub struct MergedDataFrame {
906    pub index: Index,
907    /// br-frankenpandas-u387a: a `ColumnStore`, not a `BTreeMap`. Merge suffix
908    /// collisions are one of the pandas cases the duplicate-label work
909    /// (br-frankenpandas-ih4t0) has to support, so a map here would just be
910    /// the same leak one crate over — it cannot represent the repeated labels
911    /// a collision produces.
912    pub columns: ColumnStore,
913    /// Output column order in pandas' convention (key/left columns in their
914    /// source order, then right non-key columns). The `columns` map is sorted,
915    /// so this Vec carries the real order for materialization — br-691lh.
916    pub column_order: Vec<String>,
917}
918
919#[derive(Debug, Clone, PartialEq, Eq, Hash)]
920enum JoinKeyComponent {
921    Present(IndexLabel),
922    FloatBits(u64),
923    Missing,
924}
925
926impl Ord for JoinKeyComponent {
927    fn cmp(&self, other: &Self) -> Ordering {
928        use JoinKeyComponent::{FloatBits, Missing, Present};
929        match (self, other) {
930            (Missing, Missing) => Ordering::Equal,
931            (Missing, _) => Ordering::Greater,
932            (_, Missing) => Ordering::Less,
933            (Present(IndexLabel::Int64(a)), Present(IndexLabel::Int64(b))) => a.cmp(b),
934            (Present(IndexLabel::Utf8(a)), Present(IndexLabel::Utf8(b))) => a.cmp(b),
935            (Present(IndexLabel::Timedelta64(a)), Present(IndexLabel::Timedelta64(b))) => a.cmp(b),
936            (Present(IndexLabel::Datetime64(a)), Present(IndexLabel::Datetime64(b))) => a.cmp(b),
937            // Typed-null labels sort after every concrete label (nulls-last,
938            // consistent with the derived IndexLabel Ord) but before Missing.
939            // Unreachable today: join key extraction maps missing to Missing,
940            // never Present(Null).
941            (Present(IndexLabel::Null(a)), Present(IndexLabel::Null(b))) => a.cmp(b),
942            (Present(IndexLabel::Null(_)), Present(_)) => Ordering::Greater,
943            (Present(_), Present(IndexLabel::Null(_))) => Ordering::Less,
944            (Present(IndexLabel::Null(_)), FloatBits(_)) => Ordering::Greater,
945            (FloatBits(_), Present(IndexLabel::Null(_))) => Ordering::Less,
946            (Present(IndexLabel::Int64(_)), Present(IndexLabel::Utf8(_))) => Ordering::Less,
947            (Present(IndexLabel::Utf8(_)), Present(IndexLabel::Int64(_))) => Ordering::Greater,
948            (Present(IndexLabel::Timedelta64(_)), Present(IndexLabel::Int64(_))) => {
949                Ordering::Greater
950            }
951            (Present(IndexLabel::Timedelta64(_)), Present(IndexLabel::Utf8(_))) => {
952                Ordering::Greater
953            }
954            (Present(IndexLabel::Int64(_)), Present(IndexLabel::Timedelta64(_))) => Ordering::Less,
955            (Present(IndexLabel::Utf8(_)), Present(IndexLabel::Timedelta64(_))) => Ordering::Less,
956            (Present(IndexLabel::Datetime64(_)), Present(IndexLabel::Int64(_))) => {
957                Ordering::Greater
958            }
959            (Present(IndexLabel::Datetime64(_)), Present(IndexLabel::Utf8(_))) => Ordering::Greater,
960            (Present(IndexLabel::Datetime64(_)), Present(IndexLabel::Timedelta64(_))) => {
961                Ordering::Greater
962            }
963            (Present(IndexLabel::Int64(_)), Present(IndexLabel::Datetime64(_))) => Ordering::Less,
964            (Present(IndexLabel::Utf8(_)), Present(IndexLabel::Datetime64(_))) => Ordering::Less,
965            (Present(IndexLabel::Timedelta64(_)), Present(IndexLabel::Datetime64(_))) => {
966                Ordering::Less
967            }
968            (Present(IndexLabel::Int64(a)), FloatBits(bits)) => {
969                let ord = (*a as f64).total_cmp(&f64::from_bits(*bits));
970                if ord == Ordering::Equal {
971                    Ordering::Less
972                } else {
973                    ord
974                }
975            }
976            (FloatBits(bits), Present(IndexLabel::Int64(a))) => {
977                let ord = f64::from_bits(*bits).total_cmp(&(*a as f64));
978                if ord == Ordering::Equal {
979                    Ordering::Greater
980                } else {
981                    ord
982                }
983            }
984            (Present(IndexLabel::Timedelta64(a)), FloatBits(bits)) => {
985                let ord = (*a as f64).total_cmp(&f64::from_bits(*bits));
986                if ord == Ordering::Equal {
987                    Ordering::Less
988                } else {
989                    ord
990                }
991            }
992            (FloatBits(bits), Present(IndexLabel::Timedelta64(a))) => {
993                let ord = f64::from_bits(*bits).total_cmp(&(*a as f64));
994                if ord == Ordering::Equal {
995                    Ordering::Greater
996                } else {
997                    ord
998                }
999            }
1000            (Present(IndexLabel::Datetime64(a)), FloatBits(bits)) => {
1001                let ord = (*a as f64).total_cmp(&f64::from_bits(*bits));
1002                if ord == Ordering::Equal {
1003                    Ordering::Less
1004                } else {
1005                    ord
1006                }
1007            }
1008            (FloatBits(bits), Present(IndexLabel::Datetime64(a))) => {
1009                let ord = f64::from_bits(*bits).total_cmp(&(*a as f64));
1010                if ord == Ordering::Equal {
1011                    Ordering::Greater
1012                } else {
1013                    ord
1014                }
1015            }
1016            (FloatBits(a_bits), FloatBits(b_bits)) => {
1017                f64::from_bits(*a_bits).total_cmp(&f64::from_bits(*b_bits))
1018            }
1019            (FloatBits(_), Present(IndexLabel::Utf8(_))) => Ordering::Less,
1020            (Present(IndexLabel::Utf8(_)), FloatBits(_)) => Ordering::Greater,
1021            // Float64/Bool index labels (br-frankenpandas-i10en). Join key
1022            // extraction maps float keys to FloatBits and bool keys to Int64, so
1023            // a Present(Float64)/Present(Bool) join key is unreachable today;
1024            // these arms only keep the manual `Ord` total (same-variant compares
1025            // by value, cross-variant by a stable variant rank).
1026            (Present(IndexLabel::Float64(a)), Present(IndexLabel::Float64(b))) => a.cmp(b),
1027            (Present(IndexLabel::Bool(a)), Present(IndexLabel::Bool(b))) => a.cmp(b),
1028            (Present(IndexLabel::Object(a)), Present(IndexLabel::Object(b))) => a.cmp(b),
1029            (a, b) => join_component_rank(a).cmp(&join_component_rank(b)),
1030        }
1031    }
1032}
1033
1034/// Stable per-variant rank used only as the cross-variant fallback for the
1035/// (unreachable) Float64/Bool join-key cases above, keeping `Ord` total.
1036fn join_component_rank(c: &JoinKeyComponent) -> u8 {
1037    use JoinKeyComponent::{FloatBits, Missing, Present};
1038    match c {
1039        Present(IndexLabel::Int64(_)) => 0,
1040        Present(IndexLabel::Float64(_)) => 1,
1041        Present(IndexLabel::Bool(_)) => 2,
1042        Present(IndexLabel::Utf8(_)) => 3,
1043        Present(IndexLabel::Timedelta64(_)) => 4,
1044        Present(IndexLabel::Datetime64(_)) => 5,
1045        Present(IndexLabel::Object(_)) => 6,
1046        Present(IndexLabel::Period(_)) => 7,
1047        Present(IndexLabel::Interval(_)) => 8,
1048        Present(IndexLabel::Null(_)) => 9,
1049        FloatBits(_) => 10,
1050        Missing => 11,
1051    }
1052}
1053
1054impl PartialOrd for JoinKeyComponent {
1055    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1056        Some(self.cmp(other))
1057    }
1058}
1059
1060fn scalar_to_key_component(s: &fp_types::Scalar) -> JoinKeyComponent {
1061    match s {
1062        fp_types::Scalar::Int64(v) => JoinKeyComponent::Present(IndexLabel::Int64(*v)),
1063        fp_types::Scalar::Float64(v) if !v.is_nan() => {
1064            if *v == v.trunc() && *v >= i64::MIN as f64 && *v < 9223372036854775808.0 {
1065                JoinKeyComponent::Present(IndexLabel::Int64(*v as i64))
1066            } else {
1067                JoinKeyComponent::FloatBits(v.to_bits())
1068            }
1069        }
1070        fp_types::Scalar::Utf8(v) => JoinKeyComponent::Present(IndexLabel::Utf8(v.clone())),
1071        fp_types::Scalar::Bool(b) => JoinKeyComponent::Present(IndexLabel::Int64(i64::from(*b))),
1072        fp_types::Scalar::Timedelta64(v) if *v != fp_types::Timedelta::NAT => {
1073            JoinKeyComponent::Present(IndexLabel::Timedelta64(*v))
1074        }
1075        fp_types::Scalar::Datetime64(v) if *v != fp_types::Timestamp::NAT => {
1076            JoinKeyComponent::Present(IndexLabel::Datetime64(*v))
1077        }
1078        fp_types::Scalar::Object(object @ fp_types::ObjectValue::Bytes(_)) => {
1079            JoinKeyComponent::Present(IndexLabel::Object(object.clone()))
1080        }
1081        _ => JoinKeyComponent::Missing, // Null, NaN, NaT
1082    }
1083}
1084
1085/// A row's composite join key. Inline storage for the single-key case (the
1086/// overwhelmingly common join shape) avoids a heap allocation per row during
1087/// key extraction; multi-column keys spill to the heap as before. `SmallVec`
1088/// shares `Vec`'s `Hash`/`Eq`/`Ord`/`Deref<[T]>` semantics, so the join result
1089/// (key equality, grouping, output order) is bit-identical.
1090type CompositeJoinKey = smallvec::SmallVec<[JoinKeyComponent; 1]>;
1091
1092/// `(left_positions, right_positions, out_row_keys)` produced by the merge
1093/// position-computation phase. `out_row_keys` is `Some` only when the rows must
1094/// be reordered by join key (sort or outer join).
1095type MergeRowPositions = (
1096    Vec<Option<usize>>,
1097    Vec<Option<usize>>,
1098    Option<Vec<CompositeJoinKey>>,
1099);
1100type JoinPositionBucket = smallvec::SmallVec<[usize; 1]>;
1101
1102/// Unsupported object keys must fail before either a typed fast path or the
1103/// generic key collector can mistake them for missing values. Matching the
1104/// variant avoids calling an opaque host object's repr, hash or equality.
1105fn validate_object_join_keys(column: &Column) -> Result<(), JoinError> {
1106    // These representations hold only text and missing markers. Preserve the
1107    // typed string fast paths without allocating a Scalar/String per key.
1108    if column.as_utf8_window().is_some() || column.as_nullable_utf8_contiguous().is_some() {
1109        return Ok(());
1110    }
1111    if matches!(column.dtype(), DType::Utf8 | DType::Categorical)
1112        && column.values().iter().any(|value| {
1113            matches!(
1114                value,
1115                Scalar::Object(fp_types::ObjectValue::List(_) | fp_types::ObjectValue::Host(_))
1116            )
1117        })
1118    {
1119        return Err(JoinError::Frame(FrameError::CompatibilityRejected(
1120            "list and host object join keys are unsupported; bytes keys are supported".to_owned(),
1121        )));
1122    }
1123    Ok(())
1124}
1125
1126fn collect_join_key_columns<'a>(
1127    frame: &'a fp_frame::DataFrame,
1128    on: &[&str],
1129    side: &str,
1130) -> Result<Vec<&'a Column>, JoinError> {
1131    let mut key_columns = Vec::with_capacity(on.len());
1132    for key_name in on {
1133        let key_column = frame.column(key_name).ok_or_else(|| {
1134            JoinError::Frame(FrameError::CompatibilityRejected(format!(
1135                "{side} DataFrame missing key column '{key_name}'"
1136            )))
1137        })?;
1138        validate_object_join_keys(key_column)?;
1139        key_columns.push(key_column);
1140    }
1141    Ok(key_columns)
1142}
1143
1144fn collect_composite_keys(key_columns: &[&Column]) -> Vec<CompositeJoinKey> {
1145    let row_count = key_columns.first().map_or(0, |column| column.len());
1146    let mut out = Vec::with_capacity(row_count);
1147
1148    for row in 0..row_count {
1149        let mut parts: CompositeJoinKey = smallvec::SmallVec::with_capacity(key_columns.len());
1150        for column in key_columns {
1151            parts.push(scalar_to_key_component(&column.values()[row]));
1152        }
1153        out.push(parts);
1154    }
1155
1156    out
1157}
1158
1159fn collect_single_join_keys(column: &Column) -> Vec<JoinKeyComponent> {
1160    column
1161        .values()
1162        .iter()
1163        .map(scalar_to_key_component)
1164        .collect()
1165}
1166
1167fn has_duplicate_composite_keys(keys: &[CompositeJoinKey]) -> bool {
1168    let mut seen = FxHashSet::with_capacity_and_hasher(keys.len(), Default::default());
1169    for key in keys {
1170        if !seen.insert(key) {
1171            return true;
1172        }
1173    }
1174    false
1175}
1176
1177/// validate='one_to_one' with repeated keys on both sides, which pandas
1178/// reports as 'not unique in either left or right dataset'.
1179const ONE_TO_ONE_BOTH_SIDES_DUPLICATED: &str =
1180    "merge validate='one_to_one' failed: left and right keys are not unique";
1181
1182fn validate_merge_cardinality(
1183    validate_mode: MergeValidateMode,
1184    left_keys: &[CompositeJoinKey],
1185    right_keys: &[CompositeJoinKey],
1186) -> Result<(), JoinError> {
1187    let fail = |message: &str| {
1188        Err(JoinError::Frame(FrameError::CompatibilityRejected(
1189            message.to_owned(),
1190        )))
1191    };
1192
1193    match validate_mode {
1194        MergeValidateMode::OneToOne => {
1195            // pandas names both sides when neither is unique ('not unique in
1196            // either left or right dataset'), else the one that is not (the
1197            // left failure was reported first whatever the right held;
1198            // br-frankenpandas-z6jxh).
1199            match (
1200                has_duplicate_composite_keys(left_keys),
1201                has_duplicate_composite_keys(right_keys),
1202            ) {
1203                (true, true) => return fail(ONE_TO_ONE_BOTH_SIDES_DUPLICATED),
1204                (true, false) => {
1205                    return fail("merge validate='one_to_one' failed: left keys are not unique");
1206                }
1207                (false, true) => {
1208                    return fail("merge validate='one_to_one' failed: right keys are not unique");
1209                }
1210                (false, false) => {}
1211            }
1212        }
1213        MergeValidateMode::OneToMany => {
1214            if has_duplicate_composite_keys(left_keys) {
1215                return fail("merge validate='one_to_many' failed: left keys are not unique");
1216            }
1217        }
1218        MergeValidateMode::ManyToOne => {
1219            if has_duplicate_composite_keys(right_keys) {
1220                return fail("merge validate='many_to_one' failed: right keys are not unique");
1221            }
1222        }
1223        MergeValidateMode::ManyToMany => {}
1224    }
1225
1226    Ok(())
1227}
1228
1229fn validate_mode_allows_fast_positions(validate_mode: Option<MergeValidateMode>) -> bool {
1230    matches!(validate_mode, None | Some(MergeValidateMode::ManyToMany))
1231}
1232
1233/// Duplicate detection straight off a single all-valid `Int64` key buffer.
1234///
1235/// br-frankenpandas-uza04. `has_duplicate_composite_keys` needs a
1236/// `Vec<CompositeJoinKey>`, which `collect_composite_keys` builds by reading
1237/// `column.values()[row]` — the 32 B/elem `Scalar` spine plus a `SmallVec` per
1238/// row. For one all-valid Int64 column the same question is an `FxHashSet<i64>`
1239/// over the contiguous buffer, pre-sized so the build side never rehashes.
1240///
1241/// Returns `None` when this shape does not apply (more than one key column, a
1242/// non-`Int64` dtype, or any missing value — `as_i64_slice` answers only for
1243/// all-valid `DType::Int64`), and the caller keeps the generic path, which is
1244/// also where null-key duplicate semantics stay owned.
1245fn typed_single_int64_key_has_duplicates(key_columns: &[&Column]) -> Option<bool> {
1246    let [column] = key_columns else {
1247        return None;
1248    };
1249    let data = column.as_i64_slice()?;
1250    let mut seen = FxHashSet::with_capacity_and_hasher(data.len(), Default::default());
1251    Some(!data.iter().all(|&key| seen.insert(key)))
1252}
1253
1254/// Typed sibling of [`validate_merge_cardinality`]: enforce the mode off raw
1255/// key buffers, and report whether it was able to.
1256///
1257/// `Ok(true)` means the mode was fully enforced here and PASSED, so the caller
1258/// may use the fast positions paths. `Ok(false)` means this shape is not
1259/// covered and the generic path must still run `validate_merge_cardinality`.
1260/// `Err` is a real validation failure and carries the SAME message the generic
1261/// checker produces, because the two must be indistinguishable to a caller.
1262///
1263/// Precedence matters and is preserved: `OneToOne` reports a left-side failure
1264/// before looking at the right, exactly as the generic checker does. It also
1265/// declines outright unless BOTH sides are typed, so it can never report a
1266/// right-side failure that the generic checker would have pre-empted with a
1267/// left-side one it could not see.
1268fn typed_validate_merge_cardinality(
1269    validate_mode: MergeValidateMode,
1270    left_key_columns: &[&Column],
1271    right_key_columns: &[&Column],
1272) -> Result<bool, JoinError> {
1273    let fail = |message: &str| {
1274        Err(JoinError::Frame(FrameError::CompatibilityRejected(
1275            message.to_owned(),
1276        )))
1277    };
1278
1279    match validate_mode {
1280        MergeValidateMode::ManyToMany => Ok(true),
1281        MergeValidateMode::OneToMany => {
1282            match typed_single_int64_key_has_duplicates(left_key_columns) {
1283                Some(true) => fail("merge validate='one_to_many' failed: left keys are not unique"),
1284                Some(false) => Ok(true),
1285                None => Ok(false),
1286            }
1287        }
1288        MergeValidateMode::ManyToOne => {
1289            match typed_single_int64_key_has_duplicates(right_key_columns) {
1290                Some(true) => {
1291                    fail("merge validate='many_to_one' failed: right keys are not unique")
1292                }
1293                Some(false) => Ok(true),
1294                None => Ok(false),
1295            }
1296        }
1297        MergeValidateMode::OneToOne => {
1298            // Both sides must be typed before deciding anything: the failure
1299            // names each side that repeats, so answering from one side alone
1300            // could surface the wrong message.
1301            let Some(left_duplicated) = typed_single_int64_key_has_duplicates(left_key_columns)
1302            else {
1303                return Ok(false);
1304            };
1305            let Some(right_duplicated) = typed_single_int64_key_has_duplicates(right_key_columns)
1306            else {
1307                return Ok(false);
1308            };
1309            match (left_duplicated, right_duplicated) {
1310                (true, true) => fail(ONE_TO_ONE_BOTH_SIDES_DUPLICATED),
1311                (true, false) => {
1312                    fail("merge validate='one_to_one' failed: left keys are not unique")
1313                }
1314                (false, true) => {
1315                    fail("merge validate='one_to_one' failed: right keys are not unique")
1316                }
1317                (false, false) => Ok(true),
1318            }
1319        }
1320    }
1321}
1322
1323fn reorder_vec_by_index<T: Clone>(values: &mut Vec<T>, order: &[usize]) {
1324    let existing = values.clone();
1325    values.clear();
1326    values.reserve(order.len());
1327    for &idx in order {
1328        values.push(existing[idx].clone());
1329    }
1330}
1331
1332fn sort_merge_rows_by_join_keys(
1333    left_keys: &[CompositeJoinKey],
1334    right_keys: &[CompositeJoinKey],
1335    left_positions: &mut Vec<Option<usize>>,
1336    right_positions: &mut Vec<Option<usize>>,
1337) {
1338    let n = left_positions.len();
1339    if n <= 1 {
1340        return;
1341    }
1342    // pandas sorts merge output by the join key. The naive O(n·log n) COMPARISON
1343    // sort re-compares full keys (string compares for Utf8) on every step. Instead
1344    // FACTORIZE the keys to dense ranks (sort only the DISTINCT keys once, d≪n)
1345    // then STABLE counting-sort the rows by rank — O(n + d·log d). Crucially, each
1346    // output row's key is read BY REFERENCE from the already-built left_keys /
1347    // right_keys via its position (matched / unmatched-left rows take the left key,
1348    // unmatched-right rows take the right key — exactly what the removed per-row
1349    // `out_row_keys` clone stored), so the ~n String-owning CompositeJoinKey clones
1350    // that dominated outer merge are gone. Bit-identical to the prior path: same
1351    // per-row key, same `cmp`-ordered ranks (over a superset of distinct keys —
1352    // unused ranks are just empty counting-sort buckets), same stable
1353    // ascending-index emission within each rank.
1354    let mut distinct: Vec<&CompositeJoinKey> = {
1355        let mut set = FxHashSet::default();
1356        left_keys
1357            .iter()
1358            .chain(right_keys.iter())
1359            .filter(|k| set.insert(*k))
1360            .collect()
1361    };
1362    distinct.sort_unstable();
1363    let d = distinct.len();
1364    let mut rank_of: FxHashMap<&CompositeJoinKey, u32> = FxHashMap::default();
1365    rank_of.reserve(d);
1366    for (r, k) in distinct.iter().enumerate() {
1367        rank_of.insert(*k, r as u32);
1368    }
1369    let left_rank: Vec<u32> = left_keys.iter().map(|k| rank_of[k]).collect();
1370    let right_rank: Vec<u32> = right_keys.iter().map(|k| rank_of[k]).collect();
1371    let ranks: Vec<u32> = left_positions
1372        .iter()
1373        .zip(right_positions.iter())
1374        .map(|(lp, rp)| match lp {
1375            Some(p) => left_rank[*p],
1376            None => right_rank[rp.expect("an unmatched merge row has a right position")],
1377        })
1378        .collect();
1379    let mut counts = vec![0usize; d + 1];
1380    for &r in &ranks {
1381        counts[r as usize + 1] += 1;
1382    }
1383    for i in 0..d {
1384        counts[i + 1] += counts[i];
1385    }
1386    // `order[new_slot] = old_idx`, matching the comparison sort's permutation —
1387    // stable because rows are scattered in ascending original-index order.
1388    let mut cursor = counts;
1389    let mut order = vec![0usize; n];
1390    for (i, &r) in ranks.iter().enumerate() {
1391        let slot = cursor[r as usize];
1392        order[slot] = i;
1393        cursor[r as usize] = slot + 1;
1394    }
1395    reorder_vec_by_index(left_positions, &order);
1396    reorder_vec_by_index(right_positions, &order);
1397}
1398
1399fn push_merge_row_key(out_row_keys: &mut Option<Vec<CompositeJoinKey>>, key: &CompositeJoinKey) {
1400    if let Some(out_row_keys) = out_row_keys {
1401        out_row_keys.push(key.clone());
1402    }
1403}
1404
1405#[derive(Debug, Clone, PartialEq, Eq)]
1406struct ResolvedMergeSuffixes {
1407    left: Option<String>,
1408    right: Option<String>,
1409}
1410
1411impl Default for ResolvedMergeSuffixes {
1412    fn default() -> Self {
1413        Self {
1414            left: Some("_x".to_owned()),
1415            right: Some("_y".to_owned()),
1416        }
1417    }
1418}
1419
1420fn resolve_merge_suffixes(suffixes: Option<[Option<String>; 2]>) -> ResolvedMergeSuffixes {
1421    match suffixes {
1422        Some([left, right]) => ResolvedMergeSuffixes { left, right },
1423        None => ResolvedMergeSuffixes::default(),
1424    }
1425}
1426
1427fn suffix_is_present(suffix: Option<&str>) -> bool {
1428    suffix.is_some_and(|value| !value.is_empty())
1429}
1430
1431fn apply_merge_suffix(name: &str, suffix: Option<&str>) -> String {
1432    match suffix {
1433        Some(value) if !value.is_empty() => format!("{name}{value}"),
1434        _ => name.to_owned(),
1435    }
1436}
1437
1438fn collect_overlapping_column_names(
1439    left_col_names: &HashSet<&String>,
1440    right_col_names: &HashSet<&String>,
1441    excluded_names: &HashSet<&str>,
1442) -> Vec<String> {
1443    let mut overlaps = left_col_names
1444        .iter()
1445        .filter(|name| right_col_names.contains(*name) && !excluded_names.contains(name.as_str()))
1446        .map(|name| (*name).clone())
1447        .collect::<Vec<_>>();
1448    overlaps.sort();
1449    overlaps
1450}
1451
1452const SMALL_SCHEMA_LINEAR_COLUMN_LOOKUP_LIMIT: usize = 8;
1453
1454fn column_name_lookup_contains(
1455    names: &[&String],
1456    hashed_names: Option<&HashSet<&str>>,
1457    target: &str,
1458) -> bool {
1459    if let Some(hashed_names) = hashed_names {
1460        hashed_names.contains(target)
1461    } else {
1462        names.iter().any(|name| name.as_str() == target)
1463    }
1464}
1465
1466fn ensure_merge_suffixes_for_overlaps(
1467    overlap_names: &[String],
1468    suffixes: &ResolvedMergeSuffixes,
1469) -> Result<(), JoinError> {
1470    if overlap_names.is_empty() {
1471        return Ok(());
1472    }
1473    if !suffix_is_present(suffixes.left.as_deref()) && !suffix_is_present(suffixes.right.as_deref())
1474    {
1475        return Err(JoinError::Frame(FrameError::CompatibilityRejected(
1476            format!(
1477                "columns overlap but no suffix specified: {}",
1478                overlap_names.join(", ")
1479            ),
1480        )));
1481    }
1482    Ok(())
1483}
1484
1485fn validate_merge_suffixes_intra_frame(
1486    left_cols: &[&String],
1487    right_cols: &[&String],
1488    shared_key_names: &HashSet<&str>,
1489    suffixes: &ResolvedMergeSuffixes,
1490) -> Result<(), JoinError> {
1491    let left_col_names: HashSet<&String> = left_cols.iter().copied().collect();
1492    let right_col_names: HashSet<&String> = right_cols.iter().copied().collect();
1493    let overlap_names =
1494        collect_overlapping_column_names(&left_col_names, &right_col_names, shared_key_names);
1495    ensure_merge_suffixes_for_overlaps(&overlap_names, suffixes)?;
1496
1497    let overlap_set: HashSet<&str> = overlap_names.iter().map(|s| s.as_str()).collect();
1498    let mut dups = Vec::new();
1499
1500    // Check left frame for duplicates caused by suffixes
1501    let mut left_seen_orig = HashSet::new();
1502    let mut left_orig_dups = HashSet::new();
1503    for &name in left_cols {
1504        if !left_seen_orig.insert(name.as_str()) {
1505            left_orig_dups.insert(name.as_str());
1506        }
1507    }
1508
1509    let mut left_renamed_seen = HashSet::new();
1510    for &name in left_cols {
1511        let renamed = if overlap_set.contains(name.as_str()) {
1512            apply_merge_suffix(name, suffixes.left.as_deref())
1513        } else {
1514            name.clone()
1515        };
1516        if !left_renamed_seen.insert(renamed.clone()) && !left_orig_dups.contains(name.as_str()) {
1517            dups.push(renamed);
1518        }
1519    }
1520
1521    // Check right frame for duplicates caused by suffixes (excluding shared keys dropped from right output)
1522    let right_output_cols: Vec<&String> = right_cols
1523        .iter()
1524        .copied()
1525        .filter(|name| !shared_key_names.contains(name.as_str()))
1526        .collect();
1527
1528    let mut right_seen_orig = HashSet::new();
1529    let mut right_orig_dups = HashSet::new();
1530    for &name in &right_output_cols {
1531        if !right_seen_orig.insert(name.as_str()) {
1532            right_orig_dups.insert(name.as_str());
1533        }
1534    }
1535
1536    let mut right_renamed_seen = HashSet::new();
1537    for &name in &right_output_cols {
1538        let renamed = if overlap_set.contains(name.as_str()) {
1539            apply_merge_suffix(name, suffixes.right.as_deref())
1540        } else {
1541            (*name).clone()
1542        };
1543        if !right_renamed_seen.insert(renamed.clone()) && !right_orig_dups.contains(name.as_str()) {
1544            dups.push(renamed);
1545        }
1546    }
1547
1548    if !dups.is_empty() {
1549        dups.sort();
1550        dups.dedup();
1551        let formatted = format!(
1552            "{{{}}}",
1553            dups.iter()
1554                .map(|d| format!("'{d}'"))
1555                .collect::<Vec<_>>()
1556                .join(", ")
1557        );
1558        return Err(JoinError::Frame(FrameError::CompatibilityRejected(
1559            format!("Passing 'suffixes' which cause duplicate columns {formatted} is not allowed."),
1560        )));
1561    }
1562
1563    Ok(())
1564}
1565
1566fn insert_merged_output_column(
1567    output_columns: &mut ColumnStore,
1568    order: &mut Vec<String>,
1569    name: String,
1570    column: Column,
1571) -> Result<(), JoinError> {
1572    order.push(name.clone());
1573    output_columns.push(name, column);
1574    Ok(())
1575}
1576
1577fn ordered_identity_int64_keys_match(left_key: &Column, right_key: &Column) -> bool {
1578    if left_key.len() != right_key.len()
1579        || !matches!(left_key.dtype(), DType::Int64)
1580        || !matches!(right_key.dtype(), DType::Int64)
1581        || !left_key.validity().all()
1582        || !right_key.validity().all()
1583    {
1584        return false;
1585    }
1586
1587    if let (Some(left), Some(right)) = (left_key.as_i64_slice(), right_key.as_i64_slice()) {
1588        let mut previous = None;
1589        let mut strictly_increasing = true;
1590        for (&left_value, &right_value) in left.iter().zip(right) {
1591            if left_value != right_value {
1592                return false;
1593            }
1594            if previous.is_some_and(|previous| left_value <= previous) {
1595                strictly_increasing = false;
1596                break;
1597            }
1598            previous = Some(left_value);
1599        }
1600        if strictly_increasing {
1601            return true;
1602        }
1603    }
1604
1605    // The identity fast path emits a 1:1 positional merge, which is only correct
1606    // when keys are UNIQUE. With duplicate keys pandas multiplies cardinality
1607    // (each duplicate on the left cross-joins every duplicate on the right), so
1608    // identical-but-duplicated keys must fall through to the general cartesian
1609    // path. (br-frankenpandas-jdupk)
1610    let mut seen = FxHashSet::<i64>::with_capacity_and_hasher(left_key.len(), Default::default());
1611    for (left, right) in left_key.values().iter().zip(right_key.values()) {
1612        match (left, right) {
1613            (Scalar::Int64(left), Scalar::Int64(right))
1614                if matches!(left.cmp(right), Ordering::Equal) =>
1615            {
1616                if !seen.insert(*left) {
1617                    return false;
1618                }
1619            }
1620            _ => return false,
1621        }
1622    }
1623    true
1624}
1625
1626fn strictly_increasing_int64_key_values(column: &Column) -> Option<&[Scalar]> {
1627    if column.dtype() != DType::Int64 || !column.validity().all() {
1628        return None;
1629    }
1630
1631    let values = column.values();
1632    let mut previous = None;
1633    for value in values {
1634        let current = match value {
1635            Scalar::Int64(value) => *value,
1636            _ => return None,
1637        };
1638        if previous.is_some_and(|previous| current <= previous) {
1639            return None;
1640        }
1641        previous = Some(current);
1642    }
1643    Some(values)
1644}
1645
1646fn all_valid_int64_key_values(column: &Column) -> Option<&[Scalar]> {
1647    if column.dtype() != DType::Int64 || !column.validity().all() {
1648        return None;
1649    }
1650
1651    let values = column.values();
1652    if values.iter().all(|value| matches!(value, Scalar::Int64(_))) {
1653        Some(values)
1654    } else {
1655        None
1656    }
1657}
1658
1659#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1660struct PositiveAffineI64Witness {
1661    start: i128,
1662    step: i128,
1663    len: usize,
1664}
1665
1666#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1667struct AffineInnerPositionPlan {
1668    left_start: usize,
1669    left_step: usize,
1670    right_start: usize,
1671    right_step: usize,
1672    len: usize,
1673}
1674
1675const AFFINE_I64_INNER_MAX_MORSELS: usize = 64;
1676
1677fn affine_inner_worker_count() -> usize {
1678    fp_columnar::cached_available_parallelism().min(AFFINE_I64_INNER_MAX_MORSELS)
1679}
1680
1681fn balanced_partition(total: usize, index: usize, parts: usize) -> (usize, usize) {
1682    debug_assert!(parts > 0);
1683    debug_assert!(index < parts);
1684    let base = total / parts;
1685    let remainder = total % parts;
1686    let start = index * base + index.min(remainder);
1687    let end = start + base + usize::from(index < remainder);
1688    (start, end)
1689}
1690
1691fn positive_affine_i64_shape(values: &[i64]) -> Option<PositiveAffineI64Witness> {
1692    if values.len() < 2 {
1693        return None;
1694    }
1695    let start = i128::from(values[0]);
1696    let step = i128::from(values[1]) - start;
1697    // Keeping the step within positive i64 makes every CRT intermediate below
1698    // fit i128. Rarer two-point sequences spanning more than i64::MAX retain
1699    // the existing ordered/hash route.
1700    if step <= 0 || step > i128::from(i64::MAX) {
1701        return None;
1702    }
1703    Some(PositiveAffineI64Witness {
1704        start,
1705        step,
1706        len: values.len(),
1707    })
1708}
1709
1710/// Prove two positive affine i64 key sequences with independent row morsels.
1711///
1712/// Every adjacent edge is checked exactly once, including boundaries between
1713/// morsels. A failed proof simply declines the affine route; no result is
1714/// emitted from speculative work. Large ordered joins therefore replace two
1715/// serial O(n) order scans with up to 64 shared-nothing scans while preserving
1716/// the exact strict-unique certificate required by pandas inner-join semantics.
1717fn certify_positive_affine_i64_pair(
1718    left: &[i64],
1719    right: &[i64],
1720) -> Option<(PositiveAffineI64Witness, PositiveAffineI64Witness)> {
1721    let left_shape = positive_affine_i64_shape(left)?;
1722    let right_shape = positive_affine_i64_shape(right)?;
1723    let left_edges = left.len() - 1;
1724    let right_edges = right.len() - 1;
1725    let max_edges = left_edges.max(right_edges);
1726    let worker_count = affine_inner_worker_count().min(max_edges.max(1));
1727
1728    let matches_shape = |values: &[i64], shape: PositiveAffineI64Witness| {
1729        values
1730            .windows(2)
1731            .all(|pair| i128::from(pair[1]) - i128::from(pair[0]) == shape.step)
1732    };
1733    if max_edges < DENSE_I64_INNER_PARALLEL_MIN_VALUES || worker_count < 2 {
1734        return (matches_shape(left, left_shape) && matches_shape(right, right_shape))
1735            .then_some((left_shape, right_shape));
1736    }
1737
1738    let proved = std::thread::scope(|scope| {
1739        let mut handles = Vec::with_capacity(worker_count);
1740        for worker in 0..worker_count {
1741            handles.push(scope.spawn(move || {
1742                let (left_start, left_end) = balanced_partition(left_edges, worker, worker_count);
1743                let (right_start, right_end) =
1744                    balanced_partition(right_edges, worker, worker_count);
1745                let left_ok = (left_start..left_end).all(|idx| {
1746                    i128::from(left[idx + 1]) - i128::from(left[idx]) == left_shape.step
1747                });
1748                let right_ok = (right_start..right_end).all(|idx| {
1749                    i128::from(right[idx + 1]) - i128::from(right[idx]) == right_shape.step
1750                });
1751                left_ok && right_ok
1752            }));
1753        }
1754        handles
1755            .into_iter()
1756            .all(|handle| handle.join().expect("affine join proof worker panicked"))
1757    });
1758    proved.then_some((left_shape, right_shape))
1759}
1760
1761fn positive_i128_gcd(mut left: i128, mut right: i128) -> i128 {
1762    debug_assert!(left > 0 && right > 0);
1763    while right != 0 {
1764        let remainder = left % right;
1765        left = right;
1766        right = remainder;
1767    }
1768    left
1769}
1770
1771fn coprime_mod_inverse(value: i128, modulus: i128) -> Option<i128> {
1772    debug_assert!(value > 0 && modulus > 1);
1773    let (mut old_remainder, mut remainder) = (value, modulus);
1774    let (mut old_coefficient, mut coefficient) = (1i128, 0i128);
1775    while remainder != 0 {
1776        let quotient = old_remainder / remainder;
1777        (old_remainder, remainder) = (
1778            remainder,
1779            old_remainder.checked_sub(quotient.checked_mul(remainder)?)?,
1780        );
1781        (old_coefficient, coefficient) = (
1782            coefficient,
1783            old_coefficient.checked_sub(quotient.checked_mul(coefficient)?)?,
1784        );
1785    }
1786    (old_remainder == 1).then(|| old_coefficient.rem_euclid(modulus))
1787}
1788
1789fn empty_affine_inner_position_plan() -> AffineInnerPositionPlan {
1790    AffineInnerPositionPlan {
1791        left_start: 0,
1792        left_step: 1,
1793        right_start: 0,
1794        right_step: 1,
1795        len: 0,
1796    }
1797}
1798
1799/// Intersect two certified positive affine sequences analytically.
1800///
1801/// The generalized CRT yields the first shared key and the common step. Those
1802/// map back to affine row selections on each input, so the join needs neither
1803/// the serial two-pointer merge nor its two O(matches) position vectors.
1804fn affine_i64_inner_position_plan(
1805    left: PositiveAffineI64Witness,
1806    right: PositiveAffineI64Witness,
1807) -> Option<AffineInnerPositionPlan> {
1808    let left_last = left
1809        .start
1810        .checked_add(left.step.checked_mul(i128::try_from(left.len - 1).ok()?)?)?;
1811    let right_last = right.start.checked_add(
1812        right
1813            .step
1814            .checked_mul(i128::try_from(right.len - 1).ok()?)?,
1815    )?;
1816    let low = left.start.max(right.start);
1817    let high = left_last.min(right_last);
1818    if low > high {
1819        return Some(empty_affine_inner_position_plan());
1820    }
1821
1822    let gcd = positive_i128_gcd(left.step, right.step);
1823    let difference = right.start.checked_sub(left.start)?;
1824    if difference % gcd != 0 {
1825        return Some(empty_affine_inner_position_plan());
1826    }
1827    let left_reduced = left.step / gcd;
1828    let right_reduced = right.step / gcd;
1829    let left_solution = if right_reduced == 1 {
1830        0
1831    } else {
1832        let inverse = coprime_mod_inverse(left_reduced.rem_euclid(right_reduced), right_reduced)?;
1833        difference
1834            .checked_div(gcd)?
1835            .checked_mul(inverse)?
1836            .rem_euclid(right_reduced)
1837    };
1838    let common_step = left.step.checked_mul(right_reduced)?;
1839    let mut first = left
1840        .start
1841        .checked_add(left.step.checked_mul(left_solution)?)?;
1842    if first < low {
1843        let delta = low.checked_sub(first)?;
1844        let jumps = delta
1845            .checked_add(common_step - 1)?
1846            .checked_div(common_step)?;
1847        first = first.checked_add(jumps.checked_mul(common_step)?)?;
1848    }
1849    if first > high {
1850        return Some(empty_affine_inner_position_plan());
1851    }
1852
1853    let len = usize::try_from((high - first) / common_step + 1).ok()?;
1854    let left_start = usize::try_from((first - left.start) / left.step).ok()?;
1855    let right_start = usize::try_from((first - right.start) / right.step).ok()?;
1856    let left_step = usize::try_from(common_step / left.step).ok()?;
1857    let right_step = usize::try_from(common_step / right.step).ok()?;
1858    debug_assert!(
1859        left_start
1860            .checked_add(left_step.saturating_mul(len.saturating_sub(1)))
1861            .is_some_and(|last| last < left.len)
1862    );
1863    debug_assert!(
1864        right_start
1865            .checked_add(right_step.saturating_mul(len.saturating_sub(1)))
1866            .is_some_and(|last| last < right.len)
1867    );
1868    Some(AffineInnerPositionPlan {
1869        left_start,
1870        left_step,
1871        right_start,
1872        right_step,
1873        len,
1874    })
1875}
1876
1877enum AffineInnerOutputLane<'a> {
1878    Int64 {
1879        source: &'a [i64],
1880        start: usize,
1881        step: usize,
1882    },
1883    Built(Box<Column>),
1884}
1885
1886struct AffineInnerOutputSpec<'a> {
1887    name: String,
1888    lane: AffineInnerOutputLane<'a>,
1889}
1890
1891fn affine_selection_positions(start: usize, step: usize, len: usize) -> Vec<usize> {
1892    (0..len).map(|idx| start + idx * step).collect()
1893}
1894
1895fn affine_inner_output_lane<'a>(
1896    column: &'a Column,
1897    start: usize,
1898    step: usize,
1899    len: usize,
1900) -> Option<AffineInnerOutputLane<'a>> {
1901    if let Some(source) = column.as_i64_slice() {
1902        return Some(AffineInnerOutputLane::Int64 {
1903            source,
1904            start,
1905            step,
1906        });
1907    }
1908    column.as_f64_slice()?;
1909    let built = if len == 0 {
1910        Column::from_f64_values(Vec::new())
1911    } else if let Some(view) =
1912        column.take_affine_positions_without_materialized_positions(start, step, len)
1913    {
1914        view
1915    } else {
1916        let positions = affine_selection_positions(start, step, len);
1917        column.take_positions(&positions)
1918    };
1919    Some(AffineInnerOutputLane::Built(Box::new(built)))
1920}
1921
1922/// Zero-copy Int64 output for a unit-stride side of an affine match.
1923///
1924/// Shared inner-join keys are byte-identical on both sides. If either side's
1925/// matched rows form one contiguous range, reuse that immutable Arc-backed
1926/// range as a one-chunk output instead of filling an O(matches) key buffer.
1927fn affine_unit_stride_i64_view(
1928    column: &Column,
1929    start: usize,
1930    step: usize,
1931    len: usize,
1932) -> Option<Column> {
1933    if len == 0 {
1934        return Some(Column::from_i64_values_owned(Vec::new()));
1935    }
1936    if step != 1 {
1937        return None;
1938    }
1939    let (data, base) = column.as_i64_arc_view_source()?;
1940    let view_start = base.checked_add(start)?;
1941    view_start
1942        .checked_add(len)
1943        .filter(|&end| end <= data.len())?;
1944    Some(Column::from_i64_all_valid_chunks(
1945        vec![(data, view_start, len)],
1946        len,
1947    ))
1948}
1949
1950/// Fill all Int64 affine output lanes by row morsel into disjoint buffers.
1951/// Float64 lanes are descriptor-only strided views and never enter this fill.
1952fn build_affine_inner_i64_lanes(sources: &[(&[i64], usize, usize)], len: usize) -> Vec<Vec<i64>> {
1953    let mut output: Vec<Vec<i64>> = sources.iter().map(|_| vec![0i64; len]).collect();
1954    if sources.is_empty() || len == 0 {
1955        return output;
1956    }
1957    let worker_count = affine_inner_worker_count().min(len);
1958    if len < DENSE_I64_INNER_PARALLEL_MIN_VALUES || worker_count < 2 {
1959        for (lane, &(source, start, step)) in output.iter_mut().zip(sources) {
1960            for (row, value) in lane.iter_mut().enumerate() {
1961                *value = source[start + row * step];
1962            }
1963        }
1964        return output;
1965    }
1966
1967    let mut bundles: Vec<Vec<&mut [i64]>> = (0..worker_count)
1968        .map(|_| Vec::with_capacity(output.len()))
1969        .collect();
1970    for lane in &mut output {
1971        let mut remainder = lane.as_mut_slice();
1972        for (worker, bundle) in bundles.iter_mut().enumerate() {
1973            let (row_start, row_end) = balanced_partition(len, worker, worker_count);
1974            let (chunk, tail) = remainder.split_at_mut(row_end - row_start);
1975            bundle.push(chunk);
1976            remainder = tail;
1977        }
1978    }
1979
1980    std::thread::scope(|scope| {
1981        for (worker, mut bundle) in bundles.into_iter().enumerate() {
1982            let (row_start, _) = balanced_partition(len, worker, worker_count);
1983            scope.spawn(move || {
1984                for (lane, &(source, start, step)) in bundle.iter_mut().zip(sources) {
1985                    for (local_row, value) in lane.iter_mut().enumerate() {
1986                        *value = source[start + (row_start + local_row) * step];
1987                    }
1988                }
1989            });
1990        }
1991    });
1992    output
1993}
1994
1995/// Shared-nothing affine Int64 inner merge.
1996///
1997/// This is deliberately narrow but structural: all-valid typed Int64 keys are
1998/// certified as positive affine sequences; every carried lane must be an
1999/// all-valid Int64 or Float64. The match relation is then a pair of affine row
2000/// selections. Float64 payloads become zero-copy strided views, while all
2001/// Int64 lanes are filled together across row morsels. Any unsupported shape
2002/// falls through to the general ordered/dense/hash implementations.
2003fn build_single_key_affine_i64_inner_merge_output(
2004    left: &fp_frame::DataFrame,
2005    right: &fp_frame::DataFrame,
2006    left_on: &[&str],
2007    right_on: &[&str],
2008    left_key: &Column,
2009    right_key: &Column,
2010    suffixes: &ResolvedMergeSuffixes,
2011) -> Result<Option<MergedDataFrame>, JoinError> {
2012    debug_assert_eq!(left_on.len(), 1);
2013    debug_assert_eq!(right_on.len(), 1);
2014    let (Some(left_keys), Some(right_keys)) = (left_key.as_i64_slice(), right_key.as_i64_slice())
2015    else {
2016        return Ok(None);
2017    };
2018    let Some((left_shape, right_shape)) = certify_positive_affine_i64_pair(left_keys, right_keys)
2019    else {
2020        return Ok(None);
2021    };
2022    let Some(plan) = affine_i64_inner_position_plan(left_shape, right_shape) else {
2023        return Ok(None);
2024    };
2025
2026    let left_col_names: HashSet<&String> = left.columns().keys().collect();
2027    let right_col_names: HashSet<&String> = right.columns().keys().collect();
2028    let shared_key_names = if left_on[0] == right_on[0] {
2029        [left_on[0]].into_iter().collect::<HashSet<&str>>()
2030    } else {
2031        HashSet::new()
2032    };
2033    let overlapping_names =
2034        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
2035    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
2036
2037    let mut specs = Vec::<AffineInnerOutputSpec<'_>>::new();
2038    for name in left.column_names() {
2039        let column = left
2040            .columns()
2041            .get(name)
2042            .expect("left column listed in column_names must exist");
2043        let out_name = if name.as_str() == left_on[0] {
2044            name.clone()
2045        } else if right_col_names.contains(name) {
2046            apply_merge_suffix(name, suffixes.left.as_deref())
2047        } else {
2048            name.clone()
2049        };
2050        let shared_key_view = (name.as_str() == left_on[0] && left_on[0] == right_on[0])
2051            .then(|| {
2052                affine_unit_stride_i64_view(left_key, plan.left_start, plan.left_step, plan.len)
2053                    .or_else(|| {
2054                        affine_unit_stride_i64_view(
2055                            right_key,
2056                            plan.right_start,
2057                            plan.right_step,
2058                            plan.len,
2059                        )
2060                    })
2061                    .map(Box::new)
2062                    .map(AffineInnerOutputLane::Built)
2063            })
2064            .flatten();
2065        let Some(lane) = shared_key_view.or_else(|| {
2066            affine_inner_output_lane(column, plan.left_start, plan.left_step, plan.len)
2067        }) else {
2068            return Ok(None);
2069        };
2070        specs.push(AffineInnerOutputSpec {
2071            name: out_name,
2072            lane,
2073        });
2074    }
2075    for name in right.column_names() {
2076        if name.as_str() == right_on[0] && shared_key_names.contains(name.as_str()) {
2077            continue;
2078        }
2079        let column = right
2080            .columns()
2081            .get(name)
2082            .expect("right column listed in column_names must exist");
2083        let out_name = if left_col_names.contains(name) {
2084            apply_merge_suffix(name, suffixes.right.as_deref())
2085        } else {
2086            name.clone()
2087        };
2088        let Some(lane) =
2089            affine_inner_output_lane(column, plan.right_start, plan.right_step, plan.len)
2090        else {
2091            return Ok(None);
2092        };
2093        specs.push(AffineInnerOutputSpec {
2094            name: out_name,
2095            lane,
2096        });
2097    }
2098
2099    let i64_sources: Vec<(&[i64], usize, usize)> = specs
2100        .iter()
2101        .filter_map(|spec| match &spec.lane {
2102            AffineInnerOutputLane::Int64 {
2103                source,
2104                start,
2105                step,
2106            } => Some((*source, *start, *step)),
2107            AffineInnerOutputLane::Built(_) => None,
2108        })
2109        .collect();
2110    let mut i64_lanes = build_affine_inner_i64_lanes(&i64_sources, plan.len).into_iter();
2111    let index = Index::new_known_unique_int64_unit_range(0, plan.len);
2112    let mut columns = ColumnStore::new();
2113    let mut column_order = Vec::with_capacity(specs.len());
2114    for spec in specs {
2115        let column = match spec.lane {
2116            AffineInnerOutputLane::Int64 { .. } => Column::from_i64_values_owned(
2117                i64_lanes
2118                    .next()
2119                    .expect("one filled lane for every affine Int64 output"),
2120            ),
2121            AffineInnerOutputLane::Built(column) => *column,
2122        };
2123        debug_assert_eq!(column.len(), plan.len);
2124        insert_merged_output_column(&mut columns, &mut column_order, spec.name, column)?;
2125    }
2126    Ok(Some(MergedDataFrame {
2127        index,
2128        columns,
2129        column_order,
2130    }))
2131}
2132
2133fn ordered_unique_int64_inner_positions(
2134    left_key: &Column,
2135    right_key: &Column,
2136) -> Option<(Vec<usize>, Vec<usize>)> {
2137    // Typed fast path (see ordered_unique_int64_left_match_positions): walk the
2138    // ordered intersection over raw &[i64] when both keys carry a contiguous
2139    // Int64 backing, skipping the Vec<Scalar> materialization (32 B/elem, ~64 MB
2140    // per merge at 1M rows). Bit-identical: same strictly-increasing gate and
2141    // the same monotone merge emitting the same (left_idx, right_idx) pairs.
2142    if let (Some(left_values), Some(right_values)) = (
2143        strictly_increasing_i64_slice(left_key),
2144        strictly_increasing_i64_slice(right_key),
2145    ) {
2146        let mut left_positions =
2147            Vec::<usize>::with_capacity(left_values.len().min(right_values.len()));
2148        let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
2149        let (mut left_idx, mut right_idx) = (0usize, 0usize);
2150        while left_idx < left_values.len() && right_idx < right_values.len() {
2151            match left_values[left_idx].cmp(&right_values[right_idx]) {
2152                Ordering::Equal => {
2153                    left_positions.push(left_idx);
2154                    right_positions.push(right_idx);
2155                    left_idx += 1;
2156                    right_idx += 1;
2157                }
2158                Ordering::Less => left_idx += 1,
2159                Ordering::Greater => right_idx += 1,
2160            }
2161        }
2162        return Some((left_positions, right_positions));
2163    }
2164
2165    let left_values = strictly_increasing_int64_key_values(left_key)?;
2166    let right_values = strictly_increasing_int64_key_values(right_key)?;
2167
2168    let mut left_positions = Vec::<usize>::with_capacity(left_values.len().min(right_values.len()));
2169    let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
2170    let mut left_idx = 0usize;
2171    let mut right_idx = 0usize;
2172
2173    while left_idx < left_values.len() && right_idx < right_values.len() {
2174        let left_value = match &left_values[left_idx] {
2175            Scalar::Int64(value) => *value,
2176            _ => return None,
2177        };
2178        let right_value = match &right_values[right_idx] {
2179            Scalar::Int64(value) => *value,
2180            _ => return None,
2181        };
2182
2183        match left_value.cmp(&right_value) {
2184            Ordering::Equal => {
2185                left_positions.push(left_idx);
2186                right_positions.push(right_idx);
2187                left_idx += 1;
2188                right_idx += 1;
2189            }
2190            Ordering::Less => left_idx += 1,
2191            Ordering::Greater => right_idx += 1,
2192        }
2193    }
2194
2195    Some((left_positions, right_positions))
2196}
2197
2198fn strictly_increasing_utf8_key_spans(column: &Column) -> Option<(&[u8], &[usize])> {
2199    column.as_strictly_increasing_utf8_contiguous()
2200}
2201
2202fn utf8_span<'a>(bytes: &'a [u8], offsets: &[usize], pos: usize) -> &'a [u8] {
2203    &bytes[offsets[pos]..offsets[pos + 1]]
2204}
2205
2206fn utf8_offsets_are_sorted(bytes: &[u8], offsets: &[usize]) -> bool {
2207    offsets
2208        .windows(3)
2209        .all(|window| bytes[window[0]..window[1]] <= bytes[window[1]..window[2]])
2210}
2211
2212fn sorted_contiguous_utf8_inner_positions(
2213    left_bytes: &[u8],
2214    left_offsets: &[usize],
2215    right_bytes: &[u8],
2216    right_offsets: &[usize],
2217) -> Option<(Vec<usize>, Vec<usize>)> {
2218    if !utf8_offsets_are_sorted(left_bytes, left_offsets)
2219        || !utf8_offsets_are_sorted(right_bytes, right_offsets)
2220    {
2221        return None;
2222    }
2223
2224    let left_n = left_offsets.len() - 1;
2225    let right_n = right_offsets.len() - 1;
2226    let mut left_positions = Vec::<usize>::with_capacity(left_n.min(right_n));
2227    let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
2228    let mut left_pos = 0usize;
2229    let mut right_pos = 0usize;
2230
2231    while left_pos < left_n && right_pos < right_n {
2232        let left_span = utf8_span(left_bytes, left_offsets, left_pos);
2233        let right_span = utf8_span(right_bytes, right_offsets, right_pos);
2234        match left_span.cmp(right_span) {
2235            Ordering::Less => left_pos += 1,
2236            Ordering::Greater => right_pos += 1,
2237            Ordering::Equal => {
2238                let left_start = left_pos;
2239                let right_start = right_pos;
2240                while left_pos < left_n
2241                    && utf8_span(left_bytes, left_offsets, left_pos) == left_span
2242                {
2243                    left_pos += 1;
2244                }
2245                while right_pos < right_n
2246                    && utf8_span(right_bytes, right_offsets, right_pos) == right_span
2247                {
2248                    right_pos += 1;
2249                }
2250                for matched_left in left_start..left_pos {
2251                    for matched_right in right_start..right_pos {
2252                        left_positions.push(matched_left);
2253                        right_positions.push(matched_right);
2254                    }
2255                }
2256            }
2257        }
2258    }
2259
2260    Some((left_positions, right_positions))
2261}
2262
2263fn utf8_span_lower_bound(bytes: &[u8], offsets: &[usize], needle: &[u8]) -> usize {
2264    let mut lo = 0usize;
2265    let mut hi = offsets.len() - 1;
2266    while lo < hi {
2267        let mid = lo + (hi - lo) / 2;
2268        if utf8_span(bytes, offsets, mid) < needle {
2269            lo = mid + 1;
2270        } else {
2271            hi = mid;
2272        }
2273    }
2274    lo
2275}
2276
2277fn ordered_unique_utf8_fixed_width(left_key: &Column, right_key: &Column) -> Option<usize> {
2278    let (_, _, left_width) = left_key.as_fixed_width_strictly_increasing_utf8_contiguous()?;
2279    let (_, _, right_width) = right_key.as_fixed_width_strictly_increasing_utf8_contiguous()?;
2280    (left_width == right_width && left_width > 0).then_some(left_width)
2281}
2282
2283fn ordered_utf8_lower_hex_overlap_len(
2284    left_cert: Utf8LowerHexSequence,
2285    right_cert: Utf8LowerHexSequence,
2286    left_idx: usize,
2287    left_n: usize,
2288    right_idx: usize,
2289    right_n: usize,
2290) -> Option<usize> {
2291    if !left_cert.same_shape(right_cert) {
2292        return None;
2293    }
2294    let left_value = left_cert.value_at(left_idx)?;
2295    let right_value = right_cert.value_at(right_idx)?;
2296    if left_value != right_value {
2297        return None;
2298    }
2299    Some(left_n.saturating_sub(left_idx).min(right_n - right_idx))
2300}
2301
2302fn lower_hex_overlap_plan_from_certificates(
2303    left_key: &Column,
2304    right_key: &Column,
2305) -> Option<InnerPositionPlan> {
2306    let (left_prefix, left_cert, left_n) = left_key.as_lower_hex_sequence_utf8()?;
2307    let (right_prefix, right_cert, right_n) = right_key.as_lower_hex_sequence_utf8()?;
2308    if !left_cert.same_shape(right_cert) {
2309        return None;
2310    }
2311    if left_prefix != right_prefix {
2312        return None;
2313    }
2314
2315    let left_n = u64::try_from(left_n).ok()?;
2316    let right_n = u64::try_from(right_n).ok()?;
2317    if left_n == 0 || right_n == 0 {
2318        return Some(InnerPositionPlan::Gather {
2319            left_positions: Vec::new(),
2320            right_positions: Vec::new(),
2321        });
2322    }
2323
2324    let left_start_value = left_cert.start();
2325    let right_start_value = right_cert.start();
2326    let left_end_value = left_start_value.checked_add(left_n)?;
2327    let right_end_value = right_start_value.checked_add(right_n)?;
2328    let overlap_start = left_start_value.max(right_start_value);
2329    let overlap_end = left_end_value.min(right_end_value);
2330    if overlap_start >= overlap_end {
2331        return Some(InnerPositionPlan::Gather {
2332            left_positions: Vec::new(),
2333            right_positions: Vec::new(),
2334        });
2335    }
2336
2337    let len = usize::try_from(overlap_end.checked_sub(overlap_start)?).ok()?;
2338    let left_start = usize::try_from(overlap_start.checked_sub(left_start_value)?).ok()?;
2339    let right_start = usize::try_from(overlap_start.checked_sub(right_start_value)?).ok()?;
2340    let left_len = usize::try_from(left_n).ok()?;
2341    let right_len = usize::try_from(right_n).ok()?;
2342    let left_end = left_start.checked_add(len)?;
2343    let right_end = right_start.checked_add(len)?;
2344    if left_end > left_len || right_end > right_len {
2345        return None;
2346    }
2347
2348    Some(InnerPositionPlan::ContiguousRanges {
2349        left_start,
2350        right_start,
2351        len,
2352    })
2353}
2354
2355#[derive(Debug, Clone, PartialEq, Eq)]
2356enum InnerPositionPlan {
2357    Gather {
2358        left_positions: Vec<usize>,
2359        right_positions: Vec<usize>,
2360    },
2361    ContiguousRanges {
2362        left_start: usize,
2363        right_start: usize,
2364        len: usize,
2365    },
2366}
2367
2368impl InnerPositionPlan {
2369    #[cfg(test)]
2370    fn into_positions(self) -> (Vec<usize>, Vec<usize>) {
2371        match self {
2372            Self::Gather {
2373                left_positions,
2374                right_positions,
2375            } => (left_positions, right_positions),
2376            Self::ContiguousRanges {
2377                left_start,
2378                right_start,
2379                len,
2380            } => (
2381                (left_start..left_start + len).collect(),
2382                (right_start..right_start + len).collect(),
2383            ),
2384        }
2385    }
2386}
2387
2388/// Hash-free ordered merge for all-valid, strictly increasing contiguous-Utf8
2389/// keys. This is the string-key analogue of
2390/// [`ordered_unique_int64_inner_positions`]: each side is unique and already in
2391/// key order, so a two-cursor byte-span merge emits the exact same 1:1
2392/// `(left_pos, right_pos)` pairs as the hash path while skipping hash table
2393/// build/probe entirely. Duplicate or unsorted inputs fall back to the
2394/// left-major byte-span hash path, preserving pandas row order.
2395fn ordered_unique_utf8_inner_position_plan(
2396    left_key: &Column,
2397    right_key: &Column,
2398) -> Option<InnerPositionPlan> {
2399    if let Some(plan) = lower_hex_overlap_plan_from_certificates(left_key, right_key) {
2400        return Some(plan);
2401    }
2402
2403    let (left_bytes, left_offsets) = strictly_increasing_utf8_key_spans(left_key)?;
2404    let (right_bytes, right_offsets) = strictly_increasing_utf8_key_spans(right_key)?;
2405    let left_n = left_offsets.len() - 1;
2406    let right_n = right_offsets.len() - 1;
2407    let fixed_width = ordered_unique_utf8_fixed_width(left_key, right_key);
2408
2409    if left_n == 0 || right_n == 0 {
2410        return Some(InnerPositionPlan::Gather {
2411            left_positions: Vec::new(),
2412            right_positions: Vec::new(),
2413        });
2414    }
2415
2416    let mut left_positions = Vec::<usize>::with_capacity(left_n.min(right_n));
2417    let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
2418
2419    let first_left = utf8_span(left_bytes, left_offsets, 0);
2420    let last_left = utf8_span(left_bytes, left_offsets, left_n - 1);
2421    let first_right = utf8_span(right_bytes, right_offsets, 0);
2422    let last_right = utf8_span(right_bytes, right_offsets, right_n - 1);
2423    if last_left < first_right || last_right < first_left {
2424        return Some(InnerPositionPlan::Gather {
2425            left_positions,
2426            right_positions,
2427        });
2428    }
2429
2430    let mut left_idx = utf8_span_lower_bound(left_bytes, left_offsets, first_right);
2431    let mut right_idx = if left_idx < left_n {
2432        utf8_span_lower_bound(
2433            right_bytes,
2434            right_offsets,
2435            utf8_span(left_bytes, left_offsets, left_idx),
2436        )
2437    } else {
2438        right_n
2439    };
2440    let mut fixed_width_bulk_attempted = false;
2441
2442    while left_idx < left_n && right_idx < right_n {
2443        let left_span = utf8_span(left_bytes, left_offsets, left_idx);
2444        let right_span = utf8_span(right_bytes, right_offsets, right_idx);
2445
2446        match left_span.cmp(right_span) {
2447            Ordering::Equal => {
2448                if let Some(width) = fixed_width
2449                    && !fixed_width_bulk_attempted
2450                {
2451                    fixed_width_bulk_attempted = true;
2452                    // This branch is reached only after the current left/right
2453                    // key spans compare equal. Matching lower-hex shapes then
2454                    // prove the remaining shifted windows without a full
2455                    // byte-window memcmp.
2456                    let lower_hex_sequences = match (
2457                        left_key.as_lower_hex_sequence_utf8_contiguous(),
2458                        right_key.as_lower_hex_sequence_utf8_contiguous(),
2459                    ) {
2460                        (Some((_, _, left_cert)), Some((_, _, right_cert))) => {
2461                            Some((left_cert, right_cert))
2462                        }
2463                        _ => None,
2464                    };
2465                    if let Some((left_cert, right_cert)) = lower_hex_sequences
2466                        && let Some(run_len) = ordered_utf8_lower_hex_overlap_len(
2467                            left_cert, right_cert, left_idx, left_n, right_idx, right_n,
2468                        )
2469                        && run_len > 1
2470                    {
2471                        if left_positions.is_empty() {
2472                            return Some(InnerPositionPlan::ContiguousRanges {
2473                                left_start: left_idx,
2474                                right_start: right_idx,
2475                                len: run_len,
2476                            });
2477                        }
2478                        left_positions.extend(left_idx..left_idx + run_len);
2479                        right_positions.extend(right_idx..right_idx + run_len);
2480                        left_idx += run_len;
2481                        right_idx += run_len;
2482                        continue;
2483                    }
2484                    let run_len = left_n.saturating_sub(left_idx).min(right_n - right_idx);
2485                    if run_len > 1
2486                        && let Some(byte_len) = run_len.checked_mul(width)
2487                    {
2488                        let left_start = left_offsets[left_idx];
2489                        let right_start = right_offsets[right_idx];
2490                        let left_end = left_start + byte_len;
2491                        let right_end = right_start + byte_len;
2492                        if left_end <= left_bytes.len()
2493                            && right_end <= right_bytes.len()
2494                            && left_bytes[left_start..left_end]
2495                                == right_bytes[right_start..right_end]
2496                        {
2497                            if left_positions.is_empty() {
2498                                return Some(InnerPositionPlan::ContiguousRanges {
2499                                    left_start: left_idx,
2500                                    right_start: right_idx,
2501                                    len: run_len,
2502                                });
2503                            }
2504                            left_positions.extend(left_idx..left_idx + run_len);
2505                            right_positions.extend(right_idx..right_idx + run_len);
2506                            left_idx += run_len;
2507                            right_idx += run_len;
2508                            continue;
2509                        }
2510                    }
2511                }
2512                left_positions.push(left_idx);
2513                right_positions.push(right_idx);
2514                left_idx += 1;
2515                right_idx += 1;
2516            }
2517            Ordering::Less => left_idx += 1,
2518            Ordering::Greater => right_idx += 1,
2519        }
2520    }
2521
2522    Some(InnerPositionPlan::Gather {
2523        left_positions,
2524        right_positions,
2525    })
2526}
2527
2528#[cfg(test)]
2529fn ordered_unique_utf8_inner_positions(
2530    left_key: &Column,
2531    right_key: &Column,
2532) -> Option<(Vec<usize>, Vec<usize>)> {
2533    ordered_unique_utf8_inner_position_plan(left_key, right_key)
2534        .map(InnerPositionPlan::into_positions)
2535}
2536
2537/// Strictly-increasing check over a column's contiguous `&[i64]` backing,
2538/// returning the raw slice. The typed analogue of
2539/// `strictly_increasing_int64_key_values` that skips the `Vec<Scalar>`
2540/// materialization (32 B/elem) — `as_i64_slice` is `Some` only for an
2541/// all-valid contiguous Int64 column, the same gate as the Scalar version
2542/// (dtype Int64 + `validity().all()` + every value `Scalar::Int64`).
2543fn strictly_increasing_i64_slice(column: &Column) -> Option<&[i64]> {
2544    let data = column.as_i64_slice()?;
2545    if data.windows(2).any(|pair| pair[1] <= pair[0]) {
2546        return None;
2547    }
2548    Some(data)
2549}
2550
2551fn ordered_unique_int64_left_match_positions(
2552    left_key: &Column,
2553    right_key: &Column,
2554) -> Option<Vec<Option<usize>>> {
2555    // Typed fast path: both keys carry a contiguous Int64 backing, so run the
2556    // ordered two-pointer match over raw `&[i64]` (8 B/elem, cache-friendly)
2557    // instead of materializing two `Vec<Scalar>` (32 B/elem — ~32 MB per side
2558    // at 1M rows, the tax that left-join paid but the typed inner path did
2559    // not). Bit-identical: same strictly-increasing gate and the same
2560    // monotone walk producing the same `right_idx` per left row.
2561    if let (Some(left_values), Some(right_values)) = (
2562        strictly_increasing_i64_slice(left_key),
2563        strictly_increasing_i64_slice(right_key),
2564    ) {
2565        let mut right_positions = Vec::<Option<usize>>::with_capacity(left_values.len());
2566        let mut right_idx = 0usize;
2567        for &left_value in left_values {
2568            while right_idx < right_values.len() && right_values[right_idx] < left_value {
2569                right_idx += 1;
2570            }
2571            let matched = match right_values.get(right_idx) {
2572                Some(&right_value) if right_value == left_value => Some(right_idx),
2573                _ => None,
2574            };
2575            right_positions.push(matched);
2576        }
2577        return Some(right_positions);
2578    }
2579
2580    let left_values = strictly_increasing_int64_key_values(left_key)?;
2581    let right_values = strictly_increasing_int64_key_values(right_key)?;
2582
2583    let mut right_positions = Vec::<Option<usize>>::with_capacity(left_values.len());
2584    let mut right_idx = 0usize;
2585
2586    for left_value in left_values {
2587        let Scalar::Int64(left_value) = left_value else {
2588            return None;
2589        };
2590        while let Some(Scalar::Int64(right_value)) = right_values.get(right_idx)
2591            && right_value < left_value
2592        {
2593            right_idx += 1;
2594        }
2595
2596        let matched = match right_values.get(right_idx) {
2597            Some(Scalar::Int64(right_value)) if right_value == left_value => Some(right_idx),
2598            Some(Scalar::Int64(_)) | None => None,
2599            Some(_) => return None,
2600        };
2601        right_positions.push(matched);
2602    }
2603
2604    Some(right_positions)
2605}
2606
2607fn ordered_unique_int64_right_match_positions(
2608    left_key: &Column,
2609    right_key: &Column,
2610) -> Option<Vec<Option<usize>>> {
2611    // Typed fast path (mirror of ordered_unique_int64_left_match_positions):
2612    // walk over raw &[i64] when both keys carry a contiguous Int64 backing,
2613    // skipping the Vec<Scalar> materialization (32 B/elem, ~64 MB per merge at
2614    // 1M rows). Bit-identical: same strictly-increasing gate and the same
2615    // monotone walk producing the same left_idx per right row.
2616    if let (Some(left_values), Some(right_values)) = (
2617        strictly_increasing_i64_slice(left_key),
2618        strictly_increasing_i64_slice(right_key),
2619    ) {
2620        let mut left_positions = Vec::<Option<usize>>::with_capacity(right_values.len());
2621        let mut left_idx = 0usize;
2622        for &right_value in right_values {
2623            while left_idx < left_values.len() && left_values[left_idx] < right_value {
2624                left_idx += 1;
2625            }
2626            let matched = match left_values.get(left_idx) {
2627                Some(&left_value) if left_value == right_value => Some(left_idx),
2628                _ => None,
2629            };
2630            left_positions.push(matched);
2631        }
2632        return Some(left_positions);
2633    }
2634
2635    let left_values = strictly_increasing_int64_key_values(left_key)?;
2636    let right_values = strictly_increasing_int64_key_values(right_key)?;
2637
2638    let mut left_positions = Vec::<Option<usize>>::with_capacity(right_values.len());
2639    let mut left_idx = 0usize;
2640
2641    for right_value in right_values {
2642        let Scalar::Int64(right_value) = right_value else {
2643            return None;
2644        };
2645        while let Some(Scalar::Int64(left_value)) = left_values.get(left_idx)
2646            && left_value < right_value
2647        {
2648            left_idx += 1;
2649        }
2650
2651        let matched = match left_values.get(left_idx) {
2652            Some(Scalar::Int64(left_value)) if left_value == right_value => Some(left_idx),
2653            Some(Scalar::Int64(_)) | None => None,
2654            Some(_) => return None,
2655        };
2656        left_positions.push(matched);
2657    }
2658
2659    Some(left_positions)
2660}
2661
2662type OptionalJoinPositions = (Vec<Option<usize>>, Vec<Option<usize>>);
2663
2664/// Direct-address unique-key fast path for a bounded-span Int64 left/inner
2665/// join. When the right keys are *unique* within their value span, the
2666/// counting-sort CSR (count + prefix-sum + scatter + per-bucket emit, over
2667/// several span-sized `usize` arrays) collapses to a single fill pass over one
2668/// compact `u32` table (`pos+1`, `0` == empty) plus a single probe pass — ~14x
2669/// faster at 1M (and faster than open-addressing hashing, no hash/probe).
2670///
2671/// Returns `None` (caller falls back to the CSR path) when: a key column is not
2672/// a contiguous `&[i64]`, the right side is empty, the span exceeds the dense
2673/// gate, the row count would overflow `u32`, or a *duplicate* right key is seen
2674/// (then the CSR path's per-bucket emission is required). For unique right keys
2675/// the emitted `(Some(left_pos), match)` pairs are byte-identical to the CSR
2676/// path: one row per left key in left order, matching the single right position
2677/// in its bucket (or `None` when absent / out of span).
2678fn dense_int64_unique_right_left_positions(
2679    left_key: &Column,
2680    right_key: &Column,
2681) -> Option<OptionalJoinPositions> {
2682    let left_values = left_key.as_i64_slice()?;
2683    let right_values = right_key.as_i64_slice()?;
2684    if right_values.is_empty() || left_values.len() > u32::MAX as usize {
2685        return None;
2686    }
2687
2688    let mut min_key = i64::MAX;
2689    let mut max_key = i64::MIN;
2690    for &key in right_values {
2691        min_key = min_key.min(key);
2692        max_key = max_key.max(key);
2693    }
2694
2695    let span = i128::from(max_key)
2696        .checked_sub(i128::from(min_key))?
2697        .checked_add(1)?;
2698    let row_count = left_values.len().saturating_add(right_values.len());
2699    let max_dense_span = row_count.saturating_mul(4).max(1024);
2700    if span > max_dense_span as i128 {
2701        return None;
2702    }
2703    let span = usize::try_from(span).ok()?;
2704    let span_i128 = i128::try_from(span).ok()?;
2705
2706    // Fill the direct-address table; a non-empty slot means a duplicate right
2707    // key, so bail to the CSR path (which handles many-to-many emission).
2708    let mut table = vec![0u32; span];
2709    for (pos, &key) in right_values.iter().enumerate() {
2710        let bucket = usize::try_from(i128::from(key) - i128::from(min_key)).ok()?;
2711        if table[bucket] != 0 {
2712            return None;
2713        }
2714        table[bucket] = (pos as u32).checked_add(1)?;
2715    }
2716
2717    let mut left_positions = Vec::<Option<usize>>::with_capacity(left_values.len());
2718    let mut right_positions = Vec::<Option<usize>>::with_capacity(left_values.len());
2719    for (left_pos, &key) in left_values.iter().enumerate() {
2720        let offset = i128::from(key) - i128::from(min_key);
2721        let matched = if (0..span_i128).contains(&offset) {
2722            match table[offset as usize] {
2723                0 => None,
2724                slot => Some(slot as usize - 1),
2725            }
2726        } else {
2727            None
2728        };
2729        left_positions.push(Some(left_pos));
2730        right_positions.push(matched);
2731    }
2732
2733    Some((left_positions, right_positions))
2734}
2735
2736fn dense_int64_left_positions(
2737    left_key: &Column,
2738    right_key: &Column,
2739) -> Option<OptionalJoinPositions> {
2740    if let Some(direct) = dense_int64_unique_right_left_positions(left_key, right_key) {
2741        return Some(direct);
2742    }
2743    let left_values = all_valid_int64_key_values(left_key)?;
2744    let right_values = all_valid_int64_key_values(right_key)?;
2745
2746    if right_values.is_empty() {
2747        let left_positions = (0..left_values.len()).map(Some).collect::<Vec<_>>();
2748        let right_positions = vec![None; left_values.len()];
2749        return Some((left_positions, right_positions));
2750    }
2751
2752    let mut min_key = i64::MAX;
2753    let mut max_key = i64::MIN;
2754    for value in right_values {
2755        let Scalar::Int64(key) = value else {
2756            return None;
2757        };
2758        min_key = min_key.min(*key);
2759        max_key = max_key.max(*key);
2760    }
2761
2762    let span = i128::from(max_key)
2763        .checked_sub(i128::from(min_key))?
2764        .checked_add(1)?;
2765    let row_count = left_values.len().saturating_add(right_values.len());
2766    let max_dense_span = row_count.saturating_mul(4).max(1024);
2767    if span > max_dense_span as i128 {
2768        return None;
2769    }
2770    let span = usize::try_from(span).ok()?;
2771    let span_i128 = i128::try_from(span).ok()?;
2772
2773    let mut right_counts = vec![0usize; span];
2774    for value in right_values {
2775        let Scalar::Int64(key) = value else {
2776            return None;
2777        };
2778        let bucket = usize::try_from(i128::from(*key) - i128::from(min_key)).ok()?;
2779        right_counts[bucket] = right_counts[bucket].checked_add(1)?;
2780    }
2781
2782    let mut right_offsets = Vec::<usize>::with_capacity(span + 1);
2783    right_offsets.push(0);
2784    let mut running = 0usize;
2785    for count in &right_counts {
2786        running = running.checked_add(*count)?;
2787        right_offsets.push(running);
2788    }
2789
2790    let mut write_offsets = right_offsets[..span].to_vec();
2791    let mut right_positions_by_bucket = vec![0usize; right_values.len()];
2792    for (pos, value) in right_values.iter().enumerate() {
2793        let Scalar::Int64(key) = value else {
2794            return None;
2795        };
2796        let bucket = usize::try_from(i128::from(*key) - i128::from(min_key)).ok()?;
2797        let write_idx = write_offsets[bucket];
2798        right_positions_by_bucket[write_idx] = pos;
2799        write_offsets[bucket] = write_offsets[bucket].checked_add(1)?;
2800    }
2801
2802    let mut output_len = 0usize;
2803    for value in left_values {
2804        let Scalar::Int64(key) = value else {
2805            return None;
2806        };
2807        let offset = i128::from(*key) - i128::from(min_key);
2808        let bucket_rows = if (0..span_i128).contains(&offset) {
2809            let bucket = usize::try_from(offset).ok()?;
2810            right_counts[bucket].max(1)
2811        } else {
2812            1
2813        };
2814        output_len = output_len.checked_add(bucket_rows)?;
2815    }
2816
2817    let mut left_positions = Vec::<Option<usize>>::with_capacity(output_len);
2818    let mut right_positions = Vec::<Option<usize>>::with_capacity(output_len);
2819    for (left_pos, value) in left_values.iter().enumerate() {
2820        let Scalar::Int64(key) = value else {
2821            return None;
2822        };
2823        let offset = i128::from(*key) - i128::from(min_key);
2824        if (0..span_i128).contains(&offset) {
2825            let bucket = usize::try_from(offset).ok()?;
2826            let start = right_offsets[bucket];
2827            let end = right_offsets[bucket + 1];
2828            if start != end {
2829                for &right_pos in &right_positions_by_bucket[start..end] {
2830                    left_positions.push(Some(left_pos));
2831                    right_positions.push(Some(right_pos));
2832                }
2833                continue;
2834            }
2835        }
2836        left_positions.push(Some(left_pos));
2837        right_positions.push(None);
2838    }
2839
2840    Some((left_positions, right_positions))
2841}
2842
2843/// Direct-address unique-key fast path for a bounded-span Int64 right join —
2844/// the mirror of [`dense_int64_unique_right_left_positions`]. When the *left*
2845/// (build-side) keys are unique within their span, a single fill + single probe
2846/// over one compact `u32` table replaces the CSR. Keeps every right row; bails
2847/// (caller falls back to the CSR path) on a duplicate left key, non-contiguous
2848/// backing, empty left, oversized span, or `u32` row overflow.
2849fn dense_int64_unique_left_right_positions(
2850    left_key: &Column,
2851    right_key: &Column,
2852) -> Option<OptionalJoinPositions> {
2853    let left_values = left_key.as_i64_slice()?;
2854    let right_values = right_key.as_i64_slice()?;
2855    if left_values.is_empty() || left_values.len() > u32::MAX as usize {
2856        return None;
2857    }
2858
2859    let mut min_key = i64::MAX;
2860    let mut max_key = i64::MIN;
2861    for &key in left_values {
2862        min_key = min_key.min(key);
2863        max_key = max_key.max(key);
2864    }
2865
2866    let span = i128::from(max_key)
2867        .checked_sub(i128::from(min_key))?
2868        .checked_add(1)?;
2869    let row_count = left_values.len().saturating_add(right_values.len());
2870    let max_dense_span = row_count.saturating_mul(4).max(1024);
2871    if span > max_dense_span as i128 {
2872        return None;
2873    }
2874    let span = usize::try_from(span).ok()?;
2875    let span_i128 = i128::try_from(span).ok()?;
2876
2877    let mut table = vec![0u32; span];
2878    for (pos, &key) in left_values.iter().enumerate() {
2879        let bucket = usize::try_from(i128::from(key) - i128::from(min_key)).ok()?;
2880        if table[bucket] != 0 {
2881            return None;
2882        }
2883        table[bucket] = (pos as u32).checked_add(1)?;
2884    }
2885
2886    let mut left_positions = Vec::<Option<usize>>::with_capacity(right_values.len());
2887    let mut right_positions = Vec::<Option<usize>>::with_capacity(right_values.len());
2888    for (right_pos, &key) in right_values.iter().enumerate() {
2889        let offset = i128::from(key) - i128::from(min_key);
2890        let matched = if (0..span_i128).contains(&offset) {
2891            match table[offset as usize] {
2892                0 => None,
2893                slot => Some(slot as usize - 1),
2894            }
2895        } else {
2896            None
2897        };
2898        left_positions.push(matched);
2899        right_positions.push(Some(right_pos));
2900    }
2901
2902    Some((left_positions, right_positions))
2903}
2904
2905fn dense_int64_right_positions(
2906    left_key: &Column,
2907    right_key: &Column,
2908) -> Option<OptionalJoinPositions> {
2909    if let Some(direct) = dense_int64_unique_left_right_positions(left_key, right_key) {
2910        return Some(direct);
2911    }
2912    let left_values = all_valid_int64_key_values(left_key)?;
2913    let right_values = all_valid_int64_key_values(right_key)?;
2914
2915    if left_values.is_empty() {
2916        let left_positions = vec![None; right_values.len()];
2917        let right_positions = (0..right_values.len()).map(Some).collect::<Vec<_>>();
2918        return Some((left_positions, right_positions));
2919    }
2920
2921    let mut min_key = i64::MAX;
2922    let mut max_key = i64::MIN;
2923    for value in left_values {
2924        let Scalar::Int64(key) = value else {
2925            return None;
2926        };
2927        min_key = min_key.min(*key);
2928        max_key = max_key.max(*key);
2929    }
2930
2931    let span = i128::from(max_key)
2932        .checked_sub(i128::from(min_key))?
2933        .checked_add(1)?;
2934    let row_count = left_values.len().saturating_add(right_values.len());
2935    let max_dense_span = row_count.saturating_mul(4).max(1024);
2936    if span > max_dense_span as i128 {
2937        return None;
2938    }
2939    let span = usize::try_from(span).ok()?;
2940    let span_i128 = i128::try_from(span).ok()?;
2941
2942    let mut left_counts = vec![0usize; span];
2943    for value in left_values {
2944        let Scalar::Int64(key) = value else {
2945            return None;
2946        };
2947        let bucket = usize::try_from(i128::from(*key) - i128::from(min_key)).ok()?;
2948        left_counts[bucket] = left_counts[bucket].checked_add(1)?;
2949    }
2950
2951    let mut left_offsets = Vec::<usize>::with_capacity(span + 1);
2952    left_offsets.push(0);
2953    let mut running = 0usize;
2954    for count in &left_counts {
2955        running = running.checked_add(*count)?;
2956        left_offsets.push(running);
2957    }
2958
2959    let mut write_offsets = left_offsets[..span].to_vec();
2960    let mut left_positions_by_bucket = vec![0usize; left_values.len()];
2961    for (pos, value) in left_values.iter().enumerate() {
2962        let Scalar::Int64(key) = value else {
2963            return None;
2964        };
2965        let bucket = usize::try_from(i128::from(*key) - i128::from(min_key)).ok()?;
2966        let write_idx = write_offsets[bucket];
2967        left_positions_by_bucket[write_idx] = pos;
2968        write_offsets[bucket] = write_offsets[bucket].checked_add(1)?;
2969    }
2970
2971    let mut output_len = 0usize;
2972    for value in right_values {
2973        let Scalar::Int64(key) = value else {
2974            return None;
2975        };
2976        let offset = i128::from(*key) - i128::from(min_key);
2977        let bucket_rows = if (0..span_i128).contains(&offset) {
2978            let bucket = usize::try_from(offset).ok()?;
2979            left_counts[bucket].max(1)
2980        } else {
2981            1
2982        };
2983        output_len = output_len.checked_add(bucket_rows)?;
2984    }
2985
2986    let mut left_positions = Vec::<Option<usize>>::with_capacity(output_len);
2987    let mut right_positions = Vec::<Option<usize>>::with_capacity(output_len);
2988    for (right_pos, value) in right_values.iter().enumerate() {
2989        let Scalar::Int64(key) = value else {
2990            return None;
2991        };
2992        let offset = i128::from(*key) - i128::from(min_key);
2993        if (0..span_i128).contains(&offset) {
2994            let bucket = usize::try_from(offset).ok()?;
2995            let start = left_offsets[bucket];
2996            let end = left_offsets[bucket + 1];
2997            if start != end {
2998                for &left_pos in &left_positions_by_bucket[start..end] {
2999                    left_positions.push(Some(left_pos));
3000                    right_positions.push(Some(right_pos));
3001                }
3002                continue;
3003            }
3004        }
3005        left_positions.push(None);
3006        right_positions.push(Some(right_pos));
3007    }
3008
3009    Some((left_positions, right_positions))
3010}
3011
3012/// Direct-address unique-key fast path for a bounded-span Int64 full-outer join.
3013/// When BOTH key sides are unique within the joint span, two compact `u32`
3014/// tables (`pos+1`, `0` == empty) plus a single ascending scan over `0..span`
3015/// replace the CSR's `Vec<Vec<usize>>` (one heap `Vec` per bucket — `span`
3016/// allocations) and the `Vec<Scalar>` materialization. Bails (caller falls back
3017/// to the bucket-list CSR) on a duplicate key on either side, non-contiguous
3018/// backing, oversized span, or `u32` row overflow.
3019///
3020/// Bit-identical for unique keys: the CSR emits one row per bucket in ascending
3021/// key (bucket) order — matched `(Some,Some)`, left-only `(Some,None)`,
3022/// right-only `(None,Some)` — which is exactly the per-bucket scan here.
3023fn dense_int64_unique_outer_positions(
3024    left_key: &Column,
3025    right_key: &Column,
3026) -> Option<OptionalJoinPositions> {
3027    let left_values = left_key.as_i64_slice()?;
3028    let right_values = right_key.as_i64_slice()?;
3029    if left_values.len() > u32::MAX as usize || right_values.len() > u32::MAX as usize {
3030        return None;
3031    }
3032
3033    let mut min_key = i64::MAX;
3034    let mut max_key = i64::MIN;
3035    let mut any = false;
3036    for &key in left_values.iter().chain(right_values.iter()) {
3037        min_key = min_key.min(key);
3038        max_key = max_key.max(key);
3039        any = true;
3040    }
3041    if !any {
3042        return Some((Vec::new(), Vec::new()));
3043    }
3044
3045    let span = i128::from(max_key)
3046        .checked_sub(i128::from(min_key))?
3047        .checked_add(1)?;
3048    let row_count = left_values.len().saturating_add(right_values.len());
3049    let max_dense_span = row_count.saturating_mul(4).max(1024);
3050    if span > max_dense_span as i128 {
3051        return None;
3052    }
3053    let span = usize::try_from(span).ok()?;
3054
3055    let mut left_table = vec![0u32; span];
3056    let mut right_table = vec![0u32; span];
3057    for (pos, &key) in left_values.iter().enumerate() {
3058        let bucket = usize::try_from(i128::from(key) - i128::from(min_key)).ok()?;
3059        if left_table[bucket] != 0 {
3060            return None;
3061        }
3062        left_table[bucket] = (pos as u32).checked_add(1)?;
3063    }
3064    for (pos, &key) in right_values.iter().enumerate() {
3065        let bucket = usize::try_from(i128::from(key) - i128::from(min_key)).ok()?;
3066        if right_table[bucket] != 0 {
3067            return None;
3068        }
3069        right_table[bucket] = (pos as u32).checked_add(1)?;
3070    }
3071
3072    let mut left_positions = Vec::<Option<usize>>::new();
3073    let mut right_positions = Vec::<Option<usize>>::new();
3074    for bucket in 0..span {
3075        match (left_table[bucket], right_table[bucket]) {
3076            (0, 0) => {}
3077            (l, 0) => {
3078                left_positions.push(Some(l as usize - 1));
3079                right_positions.push(None);
3080            }
3081            (0, r) => {
3082                left_positions.push(None);
3083                right_positions.push(Some(r as usize - 1));
3084            }
3085            (l, r) => {
3086                left_positions.push(Some(l as usize - 1));
3087                right_positions.push(Some(r as usize - 1));
3088            }
3089        }
3090    }
3091
3092    Some((left_positions, right_positions))
3093}
3094
3095fn dense_int64_outer_positions(
3096    left_key: &Column,
3097    right_key: &Column,
3098) -> Option<OptionalJoinPositions> {
3099    if let Some(direct) = dense_int64_unique_outer_positions(left_key, right_key) {
3100        return Some(direct);
3101    }
3102    let left_values = all_valid_int64_key_values(left_key)?;
3103    let right_values = all_valid_int64_key_values(right_key)?;
3104
3105    let mut min_key = None::<i64>;
3106    let mut max_key = None::<i64>;
3107    for value in left_values.iter().chain(right_values.iter()) {
3108        let Scalar::Int64(key) = value else {
3109            return None;
3110        };
3111        min_key = Some(min_key.map_or(*key, |current| current.min(*key)));
3112        max_key = Some(max_key.map_or(*key, |current| current.max(*key)));
3113    }
3114
3115    let Some(min_key) = min_key else {
3116        return Some((Vec::new(), Vec::new()));
3117    };
3118    let max_key = max_key.expect("max key exists when min key exists");
3119    let span = i128::from(max_key)
3120        .checked_sub(i128::from(min_key))?
3121        .checked_add(1)?;
3122    let row_count = left_values.len().saturating_add(right_values.len());
3123    let max_dense_span = row_count.saturating_mul(4).max(1024);
3124    if span > max_dense_span as i128 {
3125        return None;
3126    }
3127    let span = usize::try_from(span).ok()?;
3128
3129    let mut left_buckets = (0..span).map(|_| Vec::<usize>::new()).collect::<Vec<_>>();
3130    let mut right_buckets = (0..span).map(|_| Vec::<usize>::new()).collect::<Vec<_>>();
3131
3132    for (pos, value) in left_values.iter().enumerate() {
3133        let Scalar::Int64(key) = value else {
3134            return None;
3135        };
3136        let bucket = usize::try_from(i128::from(*key) - i128::from(min_key)).ok()?;
3137        left_buckets[bucket].push(pos);
3138    }
3139    for (pos, value) in right_values.iter().enumerate() {
3140        let Scalar::Int64(key) = value else {
3141            return None;
3142        };
3143        let bucket = usize::try_from(i128::from(*key) - i128::from(min_key)).ok()?;
3144        right_buckets[bucket].push(pos);
3145    }
3146
3147    let mut output_len = 0usize;
3148    for (left_bucket, right_bucket) in left_buckets.iter().zip(right_buckets.iter()) {
3149        let bucket_rows = match (left_bucket.is_empty(), right_bucket.is_empty()) {
3150            (false, false) => left_bucket.len().checked_mul(right_bucket.len())?,
3151            (false, true) => left_bucket.len(),
3152            (true, false) => right_bucket.len(),
3153            (true, true) => 0,
3154        };
3155        output_len = output_len.checked_add(bucket_rows)?;
3156    }
3157
3158    let mut left_positions = Vec::<Option<usize>>::with_capacity(output_len);
3159    let mut right_positions = Vec::<Option<usize>>::with_capacity(output_len);
3160    for (left_bucket, right_bucket) in left_buckets.into_iter().zip(right_buckets) {
3161        match (left_bucket.is_empty(), right_bucket.is_empty()) {
3162            (false, false) => {
3163                for left_pos in left_bucket {
3164                    for &right_pos in &right_bucket {
3165                        left_positions.push(Some(left_pos));
3166                        right_positions.push(Some(right_pos));
3167                    }
3168                }
3169            }
3170            (false, true) => {
3171                for left_pos in left_bucket {
3172                    left_positions.push(Some(left_pos));
3173                    right_positions.push(None);
3174                }
3175            }
3176            (true, false) => {
3177                for right_pos in right_bucket {
3178                    left_positions.push(None);
3179                    right_positions.push(Some(right_pos));
3180                }
3181            }
3182            (true, true) => {}
3183        }
3184    }
3185
3186    Some((left_positions, right_positions))
3187}
3188
3189fn ordered_unique_int64_outer_positions(
3190    left_key: &Column,
3191    right_key: &Column,
3192) -> Option<OptionalJoinPositions> {
3193    // Typed fast path (see ordered_unique_int64_left_match_positions): merge the
3194    // ordered union over raw &[i64] when both keys carry a contiguous Int64
3195    // backing, skipping the Vec<Scalar> materialization (32 B/elem, ~64 MB per
3196    // merge at 1M rows). Bit-identical: same strictly-increasing gate and the
3197    // same three-way merge emitting the same (Option,Option) position pairs and
3198    // the same drain order.
3199    if let (Some(left_values), Some(right_values)) = (
3200        strictly_increasing_i64_slice(left_key),
3201        strictly_increasing_i64_slice(right_key),
3202    ) {
3203        let cap = left_values.len().saturating_add(right_values.len());
3204        let mut left_positions = Vec::<Option<usize>>::with_capacity(cap);
3205        let mut right_positions = Vec::<Option<usize>>::with_capacity(cap);
3206        let (mut left_idx, mut right_idx) = (0usize, 0usize);
3207        while left_idx < left_values.len() && right_idx < right_values.len() {
3208            match left_values[left_idx].cmp(&right_values[right_idx]) {
3209                Ordering::Equal => {
3210                    left_positions.push(Some(left_idx));
3211                    right_positions.push(Some(right_idx));
3212                    left_idx += 1;
3213                    right_idx += 1;
3214                }
3215                Ordering::Less => {
3216                    left_positions.push(Some(left_idx));
3217                    right_positions.push(None);
3218                    left_idx += 1;
3219                }
3220                Ordering::Greater => {
3221                    left_positions.push(None);
3222                    right_positions.push(Some(right_idx));
3223                    right_idx += 1;
3224                }
3225            }
3226        }
3227        while left_idx < left_values.len() {
3228            left_positions.push(Some(left_idx));
3229            right_positions.push(None);
3230            left_idx += 1;
3231        }
3232        while right_idx < right_values.len() {
3233            left_positions.push(None);
3234            right_positions.push(Some(right_idx));
3235            right_idx += 1;
3236        }
3237        return Some((left_positions, right_positions));
3238    }
3239
3240    let left_values = strictly_increasing_int64_key_values(left_key)?;
3241    let right_values = strictly_increasing_int64_key_values(right_key)?;
3242
3243    let mut left_positions =
3244        Vec::<Option<usize>>::with_capacity(left_values.len().saturating_add(right_values.len()));
3245    let mut right_positions = Vec::<Option<usize>>::with_capacity(left_positions.capacity());
3246    let mut left_idx = 0usize;
3247    let mut right_idx = 0usize;
3248
3249    while left_idx < left_values.len() && right_idx < right_values.len() {
3250        let left_value = match &left_values[left_idx] {
3251            Scalar::Int64(value) => *value,
3252            _ => return None,
3253        };
3254        let right_value = match &right_values[right_idx] {
3255            Scalar::Int64(value) => *value,
3256            _ => return None,
3257        };
3258
3259        match left_value.cmp(&right_value) {
3260            Ordering::Equal => {
3261                left_positions.push(Some(left_idx));
3262                right_positions.push(Some(right_idx));
3263                left_idx += 1;
3264                right_idx += 1;
3265            }
3266            Ordering::Less => {
3267                left_positions.push(Some(left_idx));
3268                right_positions.push(None);
3269                left_idx += 1;
3270            }
3271            Ordering::Greater => {
3272                left_positions.push(None);
3273                right_positions.push(Some(right_idx));
3274                right_idx += 1;
3275            }
3276        }
3277    }
3278
3279    while left_idx < left_values.len() {
3280        left_positions.push(Some(left_idx));
3281        right_positions.push(None);
3282        left_idx += 1;
3283    }
3284    while right_idx < right_values.len() {
3285        left_positions.push(None);
3286        right_positions.push(Some(right_idx));
3287        right_idx += 1;
3288    }
3289
3290    Some((left_positions, right_positions))
3291}
3292
3293fn identity_merge_column(
3294    column: &Column,
3295    row_count: usize,
3296    identity_positions: &mut Option<Vec<usize>>,
3297) -> Column {
3298    if column.validity().all() {
3299        return column.clone();
3300    }
3301
3302    let positions = identity_positions.get_or_insert_with(|| (0..row_count).collect());
3303    column.take_positions(positions)
3304}
3305
3306fn resolve_merge_indicator_name(indicator_name: Option<&str>) -> Result<Option<String>, JoinError> {
3307    let Some(name) = indicator_name else {
3308        return Ok(None);
3309    };
3310    if name.trim().is_empty() {
3311        return Err(JoinError::Frame(FrameError::CompatibilityRejected(
3312            "merge indicator column name must be non-empty".to_owned(),
3313        )));
3314    }
3315    Ok(Some(name.to_owned()))
3316}
3317
3318fn build_merge_indicator_column(
3319    left_positions: &[Option<usize>],
3320    right_positions: &[Option<usize>],
3321) -> Result<Column, JoinError> {
3322    let values = left_positions
3323        .iter()
3324        .zip(right_positions.iter())
3325        .map(|(left_pos, right_pos)| match (left_pos, right_pos) {
3326            (Some(_), Some(_)) => fp_types::Scalar::Utf8("both".to_owned()),
3327            (Some(_), None) => fp_types::Scalar::Utf8("left_only".to_owned()),
3328            (None, Some(_)) => fp_types::Scalar::Utf8("right_only".to_owned()),
3329            (None, None) => fp_types::Scalar::Null(fp_types::NullKind::Null),
3330        })
3331        .collect::<Vec<_>>();
3332    // pandas makes `_merge` a category with the fixed categories
3333    // [left_only, right_only, both] - all three, in that order, whichever rows
3334    // appear (br-frankenpandas-hrxn9; it was an object column).
3335    let categories = ["left_only", "right_only", "both"]
3336        .map(|category| fp_types::Scalar::Utf8(category.to_owned()))
3337        .to_vec();
3338    Ok(Column::new(fp_types::DType::Categorical, values)?
3339        .with_categorical(Some(fp_types::CategoricalMetadata::new(categories, false))))
3340}
3341
3342fn ensure_indicator_name_available(
3343    indicator_name: &str,
3344    left_col_names: &HashSet<&String>,
3345    right_col_names: &HashSet<&String>,
3346    output_columns: &ColumnStore,
3347) -> Result<(), JoinError> {
3348    if left_col_names
3349        .iter()
3350        .any(|name| name.as_str() == indicator_name)
3351        || right_col_names
3352            .iter()
3353            .any(|name| name.as_str() == indicator_name)
3354        || output_columns.contains_key(indicator_name)
3355    {
3356        return Err(JoinError::Frame(FrameError::CompatibilityRejected(
3357            format!("merge indicator column '{indicator_name}' conflicts with an existing column"),
3358        )));
3359    }
3360    Ok(())
3361}
3362
3363/// Positional gather that keeps an all-valid Int64 output column TYPED.
3364///
3365/// `Column::take_positions` already typed-fast-paths all-valid Float64 (it
3366/// gathers into a contiguous `Vec<f64>` behind `lazy_all_valid_float64`), but
3367/// for all-valid Int64 it materializes a `Vec<Scalar::Int64>` (32 B/elem). On
3368/// the inner-merge output build — one gather per carried column — that Scalar
3369/// rebuild dominates for integer payloads. Here we gather the contiguous `i64`
3370/// buffer directly and hand it to `from_i64_values`, which yields the same
3371/// lazy-typed all-valid Int64 column.
3372///
3373/// Bit-identical to `take_positions`: for an all-valid Int64 column the latter
3374/// produces `Scalar::Int64(slice[pos])` at every output slot with an all-valid
3375/// mask; `from_i64_values(gathered)` materializes exactly those scalars with the
3376/// same all-valid mask (no NaN coercion path for i64), and `Column` equality
3377/// ignores the internal data cache. `as_i64_slice` returns `Some` only for an
3378/// all-valid, typed-backed Int64 column, so every other dtype / any-missing
3379/// column falls through to the unchanged `take_positions`.
3380fn take_positions_typed(column: &Column, positions: &[usize]) -> Column {
3381    if let Some(slice) = column.as_i64_slice() {
3382        let mut data = Vec::with_capacity(positions.len());
3383        for &pos in positions {
3384            data.push(slice[pos]);
3385        }
3386        return Column::from_i64_values(data);
3387    }
3388    column.take_positions(positions)
3389}
3390
3391#[derive(Clone, Copy)]
3392enum PositionSelection<'a> {
3393    Positions(&'a [usize]),
3394    ContiguousRange { start: usize, len: usize },
3395}
3396
3397impl PositionSelection<'_> {
3398    fn len(self) -> usize {
3399        match self {
3400            Self::Positions(positions) => positions.len(),
3401            Self::ContiguousRange { len, .. } => len,
3402        }
3403    }
3404}
3405
3406fn take_position_selection_typed(column: &Column, selection: PositionSelection<'_>) -> Column {
3407    match selection {
3408        PositionSelection::Positions(positions) => take_positions_typed(column, positions),
3409        PositionSelection::ContiguousRange { start, len } => {
3410            column.take_contiguous_range(start, len)
3411        }
3412    }
3413}
3414
3415fn take_lower_hex_sequence_range(column: &Column, start: usize, len: usize) -> Option<Column> {
3416    let (prefix, certificate, source_len) = column.as_lower_hex_sequence_utf8()?;
3417    let end = start.checked_add(len)?;
3418    if end > source_len {
3419        return None;
3420    }
3421    let start_value = certificate.value_at(start)?;
3422    Column::from_lower_hex_sequence_utf8(prefix, start_value, len, certificate.hex_width())
3423}
3424
3425#[derive(Clone, Copy)]
3426enum FusedInt64Side {
3427    Left,
3428    Right,
3429}
3430
3431struct FusedInt64OutputColumn<'a> {
3432    name: String,
3433    side: FusedInt64Side,
3434    values: &'a [i64],
3435}
3436
3437struct FusedInt64MergeOptions<'a> {
3438    suffixes: &'a ResolvedMergeSuffixes,
3439    require_all_left_keys_matched: bool,
3440}
3441
3442#[cfg(not(test))]
3443const DENSE_I64_INNER_PARALLEL_MIN_VALUES: usize = 1 << 18;
3444#[cfg(test)]
3445const DENSE_I64_INNER_PARALLEL_MIN_VALUES: usize = 1;
3446const DENSE_I64_INNER_PARALLEL_MAX_CHUNKS: usize = 16;
3447
3448fn join_parallel_thread_count() -> usize {
3449    static THREAD_COUNT: OnceLock<usize> = OnceLock::new();
3450    *THREAD_COUNT.get_or_init(|| {
3451        fp_columnar::cached_available_parallelism().min(DENSE_I64_INNER_PARALLEL_MAX_CHUNKS)
3452    })
3453}
3454
3455struct DenseI64InnerOutputPlan<'a> {
3456    left_keys: &'a [i64],
3457    min: i64,
3458    max: i64,
3459    offsets: &'a [usize],
3460    positions: &'a [usize],
3461    output_len: usize,
3462}
3463
3464/// One output lane of the dense i64 inner merge.
3465enum DenseI64LaneData {
3466    /// Left lane carried as per-run values plus a shared run-length descriptor
3467    /// — O(matched) memory, expanded lazily by column consumers
3468    /// (br-frankenpandas-3ad4n, br-frankenpandas-l4adm).
3469    RepeatRunLengths {
3470        values: Vec<i64>,
3471        run_lens: Arc<[usize]>,
3472    },
3473    /// Right lane carried as repeated slices of one bucket-order value tape —
3474    /// O(right + matched) memory until a consumer forces a contiguous view.
3475    RepeatedSlices {
3476        data: Vec<i64>,
3477        segments: Arc<[(usize, usize)]>,
3478    },
3479    /// Fully materialized contiguous values.
3480    Full(Vec<i64>),
3481}
3482
3483/// Row-chunked disjoint-write fill (br-frankenpandas-6bsw3) with lazy
3484/// repeat-run left lanes (br-frankenpandas-3ad4n).
3485///
3486/// One probe walk records every matched left row as `(left_pos,
3487/// bucket_start, run_len)`. Left lanes are pure repeat runs (each left value
3488/// repeated `run_len` times), so when the average fanout is >= 2 they are
3489/// emitted as `(value, run_len)` pairs — O(matched) memory instead of
3490/// O(output) — and expanded only if a downstream consumer reads the values.
3491/// Remaining lanes (right lanes always; left lanes too on low-fanout joins
3492/// where a 16 B run would exceed the expanded bytes) are materialized by the
3493/// 6bsw3 scheme: up to [`DENSE_I64_INNER_PARALLEL_MAX_CHUNKS`] output-size-
3494/// balanced chunks of the matched list, each worker filling its disjoint
3495/// `split_at_mut` slice of every full lane (left repeat-runs via
3496/// `slice::fill`, right bucket ranges via `copy_from_slice` from the shared
3497/// muis1 value tapes).
3498///
3499/// Bit-identical: the matched list IS the left probe order; expanding a
3500/// `RepeatRunLengths` lane reproduces exactly the values the `Full` fill
3501/// writes, and chunks partition the matched list so concatenated output equals
3502/// the single-threaded walk byte for byte.
3503fn build_dense_i64_inner_output_data(
3504    specs: &[FusedInt64OutputColumn<'_>],
3505    plan: &DenseI64InnerOutputPlan<'_>,
3506) -> Vec<DenseI64LaneData> {
3507    // Single probe walk shared by every lane: matched left rows in probe
3508    // order as (left_pos, bucket_start, run_len).
3509    let mut matched: Vec<(usize, usize, usize)> = Vec::new();
3510    for (left_pos, &v) in plan.left_keys.iter().enumerate() {
3511        if v < plan.min || v > plan.max {
3512            continue;
3513        }
3514        let bucket = (v - plan.min) as usize;
3515        if bucket + 1 >= plan.offsets.len() {
3516            continue;
3517        }
3518        let start = plan.offsets[bucket];
3519        let run_len = plan.offsets[bucket + 1] - start;
3520        if run_len == 0 {
3521            continue;
3522        }
3523        matched.push((left_pos, start, run_len));
3524    }
3525    debug_assert_eq!(
3526        matched
3527            .iter()
3528            .map(|&(_, _, run_len)| run_len)
3529            .sum::<usize>(),
3530        plan.output_len
3531    );
3532
3533    // A (value, run_len) pair is 16 B vs 8 B x run_len expanded: repeat runs
3534    // only pay when the average fanout is >= 2 (1:1 joins stay materialized).
3535    let use_repeat_runs = plan.output_len >= matched.len().saturating_mul(2);
3536
3537    let use_repeated_slices = use_repeat_runs;
3538    let repeat_run_lens: Option<Arc<[usize]>> = if use_repeat_runs {
3539        Some(
3540            matched
3541                .iter()
3542                .map(|&(_, _, run_len)| run_len)
3543                .collect::<Vec<_>>()
3544                .into(),
3545        )
3546    } else {
3547        None
3548    };
3549    let repeated_segments: Option<Arc<[(usize, usize)]>> = if use_repeated_slices {
3550        Some(
3551            matched
3552                .iter()
3553                .map(|&(_, start, run_len)| (start, run_len))
3554                .collect::<Vec<_>>()
3555                .into(),
3556        )
3557    } else {
3558        None
3559    };
3560
3561    let full_specs: Vec<usize> = specs
3562        .iter()
3563        .enumerate()
3564        .filter(|(_, spec)| {
3565            !(use_repeat_runs && matches!(spec.side, FusedInt64Side::Left))
3566                && !(use_repeated_slices && matches!(spec.side, FusedInt64Side::Right))
3567        })
3568        .map(|(idx, _)| idx)
3569        .collect();
3570
3571    // Fill the full lanes first (right lanes always; left lanes on
3572    // low-fanout joins).
3573    let mut full_data: Vec<Vec<i64>> = Vec::new();
3574    let thread_count = join_parallel_thread_count();
3575    if !full_specs.is_empty()
3576        && plan.output_len >= DENSE_I64_INNER_PARALLEL_MIN_VALUES
3577        && thread_count > 1
3578    {
3579        // Replay buckets from a value tape per right-side column (one gather
3580        // of right values into bucket order, per br-frankenpandas-muis1),
3581        // shared read-only across all chunk workers.
3582        let tapes: Vec<Option<Vec<i64>>> = full_specs
3583            .iter()
3584            .map(|&spec_idx| match specs[spec_idx].side {
3585                FusedInt64Side::Left => None,
3586                FusedInt64Side::Right => Some(
3587                    plan.positions
3588                        .iter()
3589                        .map(|&right_pos| specs[spec_idx].values[right_pos])
3590                        .collect(),
3591                ),
3592            })
3593            .collect();
3594
3595        // Chunk boundaries (matched_idx, out_pos), balanced by OUTPUT size
3596        // so a few hot buckets cannot starve the other workers.
3597        let target = plan.output_len.div_ceil(thread_count).max(1);
3598        let mut boundaries = vec![(0usize, 0usize)];
3599        let mut cumulative = 0usize;
3600        let mut next_target = target;
3601        for (matched_idx, &(_, _, run_len)) in matched.iter().enumerate() {
3602            cumulative += run_len;
3603            if cumulative >= next_target && matched_idx + 1 < matched.len() {
3604                boundaries.push((matched_idx + 1, cumulative));
3605                next_target = cumulative.saturating_add(target);
3606            }
3607        }
3608        boundaries.push((matched.len(), plan.output_len));
3609        let chunk_count = boundaries.len() - 1;
3610
3611        // Pre-size every full lane, then hand each chunk worker its disjoint
3612        // slice of every lane via progressive split_at_mut.
3613        let mut column_bufs: Vec<Vec<i64>> = full_specs
3614            .iter()
3615            .map(|_| vec![0i64; plan.output_len])
3616            .collect();
3617        let mut bundles: Vec<Vec<&mut [i64]>> = (0..chunk_count)
3618            .map(|_| Vec::with_capacity(full_specs.len()))
3619            .collect();
3620        for buf in &mut column_bufs {
3621            let mut rest: &mut [i64] = buf.as_mut_slice();
3622            let mut prev = 0usize;
3623            for (chunk_idx, window) in boundaries.windows(2).enumerate() {
3624                let (chunk_slice, tail) = rest.split_at_mut(window[1].1 - prev);
3625                prev = window[1].1;
3626                rest = tail;
3627                bundles[chunk_idx].push(chunk_slice);
3628            }
3629        }
3630
3631        let matched = &matched;
3632        let full_specs = &full_specs;
3633        std::thread::scope(|scope| {
3634            let mut handles = Vec::with_capacity(chunk_count);
3635            for (chunk_idx, mut bundle) in bundles.into_iter().enumerate() {
3636                let (matched_start, out_start) = boundaries[chunk_idx];
3637                let (matched_end, out_end) = boundaries[chunk_idx + 1];
3638                let tapes = &tapes;
3639                handles.push(scope.spawn(move || {
3640                    let mut cursor = 0usize;
3641                    for &(left_pos, start, run_len) in &matched[matched_start..matched_end] {
3642                        for (slice, (&spec_idx, tape)) in
3643                            bundle.iter_mut().zip(full_specs.iter().zip(tapes.iter()))
3644                        {
3645                            match specs[spec_idx].side {
3646                                FusedInt64Side::Left => {
3647                                    slice[cursor..cursor + run_len]
3648                                        .fill(specs[spec_idx].values[left_pos]);
3649                                }
3650                                FusedInt64Side::Right => {
3651                                    slice[cursor..cursor + run_len].copy_from_slice(
3652                                        &tape.as_ref().expect("right spec must have a bucket tape")
3653                                            [start..start + run_len],
3654                                    );
3655                                }
3656                            }
3657                        }
3658                        cursor += run_len;
3659                    }
3660                    debug_assert_eq!(cursor, out_end - out_start);
3661                }));
3662            }
3663            for handle in handles {
3664                handle
3665                    .join()
3666                    .expect("dense i64 output worker must not panic");
3667            }
3668        });
3669        full_data = column_bufs;
3670    } else if !full_specs.is_empty() {
3671        full_data = full_specs
3672            .iter()
3673            .map(|_| Vec::<i64>::with_capacity(plan.output_len))
3674            .collect();
3675        for &(left_pos, start, run_len) in &matched {
3676            for (out, &spec_idx) in full_data.iter_mut().zip(full_specs.iter()) {
3677                match specs[spec_idx].side {
3678                    FusedInt64Side::Left => {
3679                        out.resize(out.len() + run_len, specs[spec_idx].values[left_pos]);
3680                    }
3681                    FusedInt64Side::Right => {
3682                        for &right_pos in &plan.positions[start..start + run_len] {
3683                            out.push(specs[spec_idx].values[right_pos]);
3684                        }
3685                    }
3686                }
3687            }
3688        }
3689        debug_assert!(full_data.iter().all(|data| data.len() == plan.output_len));
3690    }
3691
3692    // Assemble lanes in spec order: repeat runs for the lazy left lanes,
3693    // filled buffers for everything else.
3694    let mut full_iter = full_data.into_iter();
3695    specs
3696        .iter()
3697        .map(|spec| {
3698            if use_repeat_runs && matches!(spec.side, FusedInt64Side::Left) {
3699                DenseI64LaneData::RepeatRunLengths {
3700                    values: matched
3701                        .iter()
3702                        .map(|&(left_pos, _, _)| spec.values[left_pos])
3703                        .collect(),
3704                    run_lens: Arc::clone(
3705                        repeat_run_lens
3706                            .as_ref()
3707                            .expect("repeat run lengths must exist"),
3708                    ),
3709                }
3710            } else if use_repeated_slices && matches!(spec.side, FusedInt64Side::Right) {
3711                DenseI64LaneData::RepeatedSlices {
3712                    data: plan
3713                        .positions
3714                        .iter()
3715                        .map(|&right_pos| spec.values[right_pos])
3716                        .collect(),
3717                    segments: Arc::clone(
3718                        repeated_segments
3719                            .as_ref()
3720                            .expect("repeated slice segments must exist"),
3721                    ),
3722                }
3723            } else {
3724                DenseI64LaneData::Full(
3725                    full_iter
3726                        .next()
3727                        .expect("full lane buffer must exist for every non-run spec"),
3728                )
3729            }
3730        })
3731        .collect()
3732}
3733
3734/// Which typed lane an output column of the dense inner merge uses, recorded in
3735/// column-encounter order so the i64 (lazy) and f64 (materialized) builds can be
3736/// re-interleaved into the original column order (br-frankenpandas-jzrem).
3737enum DenseInnerSpecKind {
3738    I64,
3739    F64,
3740}
3741
3742/// One Float64 output lane of the dense inner merge (br-frankenpandas-jzrem).
3743struct FusedF64OutputColumn<'a> {
3744    name: String,
3745    side: FusedInt64Side,
3746    values: &'a [f64],
3747}
3748
3749/// The matched-left-row list `(left_pos, bucket_start, run_len)` in probe order
3750/// — identical to the walk inside [`build_dense_i64_inner_output_data`], so the
3751/// Float64 lanes materialize in the exact same row order as the i64 lanes and
3752/// the flat `take_positions` path.
3753fn dense_inner_matched_runs(plan: &DenseI64InnerOutputPlan<'_>) -> Vec<(usize, usize, usize)> {
3754    let mut matched = Vec::new();
3755    for (left_pos, &v) in plan.left_keys.iter().enumerate() {
3756        if v < plan.min || v > plan.max {
3757            continue;
3758        }
3759        let bucket = (v - plan.min) as usize;
3760        if bucket + 1 >= plan.offsets.len() {
3761            continue;
3762        }
3763        let start = plan.offsets[bucket];
3764        let run_len = plan.offsets[bucket + 1] - start;
3765        if run_len == 0 {
3766            continue;
3767        }
3768        matched.push((left_pos, start, run_len));
3769    }
3770    matched
3771}
3772
3773/// Build one Float64 inner-merge output column as a LAZY representation
3774/// (br-frankenpandas-jzrem) — O(matched + right_len), never the O(output_len)
3775/// materialization:
3776///   * a Left column becomes a repeat-values lane: one value per matched run
3777///     (`values[left_pos]`) over the shared `run_lens` descriptor;
3778///   * a Right column becomes a repeated-slices lane over the bucket-ordered
3779///     value tape (`values` gathered by `positions`, one scattered pass) with
3780///     the shared `segments` descriptor.
3781///
3782/// Both materialize, only when a consumer reads them, to exactly the values
3783/// `take_position_selection_typed` would produce on the flat `(left_positions,
3784/// right_positions)` vectors — same values, same row order (matched-run probe
3785/// order == flat position order). Mirrors the i64 lazy lanes the all-Int64 path
3786/// already emits, so a join whose output is only sized (not consumed) stays
3787/// near-free instead of writing the whole fanned-out column.
3788fn build_dense_inner_f64_column(
3789    side: FusedInt64Side,
3790    values: &[f64],
3791    matched: &[(usize, usize, usize)],
3792    positions: &[usize],
3793    run_lens: &Arc<[usize]>,
3794    segments: &Arc<[(usize, usize)]>,
3795    output_len: usize,
3796) -> Column {
3797    match side {
3798        FusedInt64Side::Left => {
3799            let run_values: Vec<f64> = matched
3800                .iter()
3801                .map(|&(left_pos, _, _)| values[left_pos])
3802                .collect();
3803            Column::from_f64_repeat_values_run_lengths(run_values, Arc::clone(run_lens))
3804        }
3805        FusedInt64Side::Right => {
3806            let tape: Vec<f64> = positions.iter().map(|&p| values[p]).collect();
3807            Column::from_f64_repeated_slices_shared(tape, Arc::clone(segments), output_len)
3808        }
3809    }
3810}
3811
3812/// Build every Float64 inner-merge output column, one worker per column when the
3813/// pool is worth it (the fu8f5 column-parallel pattern). Returns `(name, column)`
3814/// pairs in `specs` order. `run_lens`/`segments` are the shared lazy-lane
3815/// descriptors derived from the matched-run list (one per matched run).
3816fn build_dense_inner_f64_columns(
3817    specs: Vec<FusedF64OutputColumn<'_>>,
3818    matched: &[(usize, usize, usize)],
3819    positions: &[usize],
3820    output_len: usize,
3821) -> Vec<(String, Column)> {
3822    if specs.is_empty() {
3823        return Vec::new();
3824    }
3825    let run_lens: Arc<[usize]> = matched.iter().map(|&(_, _, run_len)| run_len).collect();
3826    let segments: Arc<[(usize, usize)]> = matched
3827        .iter()
3828        .map(|&(_, bucket_start, run_len)| (bucket_start, run_len))
3829        .collect();
3830
3831    let worker_count = join_parallel_thread_count().min(specs.len());
3832    if worker_count < 2 {
3833        return specs
3834            .into_iter()
3835            .map(|s| {
3836                (
3837                    s.name,
3838                    build_dense_inner_f64_column(
3839                        s.side, s.values, matched, positions, &run_lens, &segments, output_len,
3840                    ),
3841                )
3842            })
3843            .collect();
3844    }
3845
3846    let next = std::sync::atomic::AtomicUsize::new(0);
3847    let specs_ref = &specs;
3848    let run_lens_ref = &run_lens;
3849    let segments_ref = &segments;
3850    let built_by_worker = std::thread::scope(|scope| {
3851        let mut handles = Vec::with_capacity(worker_count);
3852        for _ in 0..worker_count {
3853            let next = &next;
3854            handles.push(scope.spawn(move || {
3855                let mut local: Vec<(usize, Column)> = Vec::new();
3856                loop {
3857                    let idx = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3858                    if idx >= specs_ref.len() {
3859                        break;
3860                    }
3861                    let s = &specs_ref[idx];
3862                    local.push((
3863                        idx,
3864                        build_dense_inner_f64_column(
3865                            s.side,
3866                            s.values,
3867                            matched,
3868                            positions,
3869                            run_lens_ref,
3870                            segments_ref,
3871                            output_len,
3872                        ),
3873                    ));
3874                }
3875                local
3876            }));
3877        }
3878        let mut all: Vec<(usize, Column)> = Vec::new();
3879        for handle in handles {
3880            all.extend(
3881                handle
3882                    .join()
3883                    .expect("f64 inner-merge column worker panicked"),
3884            );
3885        }
3886        all
3887    });
3888
3889    let mut built: Vec<Option<Column>> = (0..specs.len()).map(|_| None).collect();
3890    for (idx, column) in built_by_worker {
3891        built[idx] = Some(column);
3892    }
3893    specs
3894        .into_iter()
3895        .zip(built)
3896        .map(|(s, column)| {
3897            (
3898                s.name,
3899                column.expect("every f64 column index is built once"),
3900            )
3901        })
3902        .collect()
3903}
3904
3905fn build_single_key_dense_i64_inner_merge_output(
3906    left: &fp_frame::DataFrame,
3907    right: &fp_frame::DataFrame,
3908    left_on: &[&str],
3909    right_on: &[&str],
3910    left_key: &Column,
3911    right_key: &Column,
3912    options: FusedInt64MergeOptions<'_>,
3913) -> Result<Option<MergedDataFrame>, JoinError> {
3914    debug_assert_eq!(left_on.len(), 1);
3915    debug_assert_eq!(right_on.len(), 1);
3916
3917    let Some(left_keys) = left_key.as_i64_slice() else {
3918        return Ok(None);
3919    };
3920    let Some(right_keys) = right_key.as_i64_slice() else {
3921        return Ok(None);
3922    };
3923
3924    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
3925    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
3926    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
3927    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
3928    let shared_key_names = if left_on[0] == right_on[0] {
3929        [left_on[0]].into_iter().collect::<HashSet<&str>>()
3930    } else {
3931        HashSet::new()
3932    };
3933    let overlapping_names =
3934        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
3935
3936    // Collect output specs in column-encounter order, accepting BOTH typed
3937    // all-valid Int64 and typed all-valid Float64 columns (br-frankenpandas-jzrem).
3938    // Int64 columns keep the lazy repeat-run / repeated-slice representation;
3939    // Float64 columns are materialized cache-efficiently below. Any other dtype,
3940    // a nullable column, or a NaN-bearing Float64 (as_f64_slice gates on
3941    // validity.all()) declines the whole fast path (Ok(None)) and falls back to
3942    // the flat gather, exactly as before.
3943    let mut i64_specs = Vec::<FusedInt64OutputColumn<'_>>::new();
3944    let mut f64_specs = Vec::<FusedF64OutputColumn<'_>>::new();
3945    let mut order_kinds = Vec::<DenseInnerSpecKind>::new();
3946
3947    for name in left.column_names() {
3948        let col = left
3949            .columns()
3950            .get(name)
3951            .expect("left column listed in column_names must exist");
3952        let out_name = if left_key_name_set.contains(name.as_str()) {
3953            name.clone()
3954        } else if right_col_names.contains(name) {
3955            apply_merge_suffix(name, options.suffixes.left.as_deref())
3956        } else {
3957            name.clone()
3958        };
3959        if let Some(values) = col.as_i64_slice() {
3960            i64_specs.push(FusedInt64OutputColumn {
3961                name: out_name,
3962                side: FusedInt64Side::Left,
3963                values,
3964            });
3965            order_kinds.push(DenseInnerSpecKind::I64);
3966        } else if let Some(values) = col.as_f64_slice() {
3967            f64_specs.push(FusedF64OutputColumn {
3968                name: out_name,
3969                side: FusedInt64Side::Left,
3970                values,
3971            });
3972            order_kinds.push(DenseInnerSpecKind::F64);
3973        } else {
3974            return Ok(None);
3975        }
3976    }
3977
3978    for name in right.column_names() {
3979        let col = right
3980            .columns()
3981            .get(name)
3982            .expect("right column listed in column_names must exist");
3983        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
3984            continue;
3985        }
3986        let out_name = if left_col_names.contains(name) {
3987            apply_merge_suffix(name, options.suffixes.right.as_deref())
3988        } else {
3989            name.clone()
3990        };
3991        if let Some(values) = col.as_i64_slice() {
3992            i64_specs.push(FusedInt64OutputColumn {
3993                name: out_name,
3994                side: FusedInt64Side::Right,
3995                values,
3996            });
3997            order_kinds.push(DenseInnerSpecKind::I64);
3998        } else if let Some(values) = col.as_f64_slice() {
3999            f64_specs.push(FusedF64OutputColumn {
4000                name: out_name,
4001                side: FusedInt64Side::Right,
4002                values,
4003            });
4004            order_kinds.push(DenseInnerSpecKind::F64);
4005        } else {
4006            return Ok(None);
4007        }
4008    }
4009
4010    ensure_merge_suffixes_for_overlaps(&overlapping_names, options.suffixes)?;
4011
4012    if left_keys.is_empty() || right_keys.is_empty() {
4013        if options.require_all_left_keys_matched && !left_keys.is_empty() {
4014            return Ok(None);
4015        }
4016        let mut columns = ColumnStore::new();
4017        let mut column_order = Vec::with_capacity(order_kinds.len());
4018        let mut i64_it = i64_specs.into_iter();
4019        let mut f64_it = f64_specs.into_iter();
4020        for kind in &order_kinds {
4021            match kind {
4022                DenseInnerSpecKind::I64 => {
4023                    let spec = i64_it.next().expect("i64 spec for each I64 kind");
4024                    insert_merged_output_column(
4025                        &mut columns,
4026                        &mut column_order,
4027                        spec.name,
4028                        Column::from_i64_values(Vec::new()),
4029                    )?;
4030                }
4031                DenseInnerSpecKind::F64 => {
4032                    let spec = f64_it.next().expect("f64 spec for each F64 kind");
4033                    insert_merged_output_column(
4034                        &mut columns,
4035                        &mut column_order,
4036                        spec.name,
4037                        Column::from_f64_values(Vec::new()),
4038                    )?;
4039                }
4040            }
4041        }
4042        return Ok(Some(MergedDataFrame {
4043            index: Index::new(Vec::new()),
4044            columns,
4045            column_order,
4046        }));
4047    }
4048
4049    let mut min = right_keys[0];
4050    let mut max = right_keys[0];
4051    for &v in right_keys {
4052        if v < min {
4053            min = v;
4054        }
4055        if v > max {
4056            max = v;
4057        }
4058    }
4059    let span = (max as i128) - (min as i128) + 1;
4060    if span > (1i128 << 24) || span > 16 * (right_keys.len() as i128) {
4061        return Ok(None);
4062    }
4063    let range = span as usize;
4064
4065    let mut offsets = vec![0usize; range + 1];
4066    for &v in right_keys {
4067        offsets[(v - min) as usize + 1] += 1;
4068    }
4069    for i in 0..range {
4070        offsets[i + 1] += offsets[i];
4071    }
4072    let mut positions = vec![0usize; right_keys.len()];
4073    let mut cursor = offsets.clone();
4074    for (pos, &v) in right_keys.iter().enumerate() {
4075        let bucket = (v - min) as usize;
4076        positions[cursor[bucket]] = pos;
4077        cursor[bucket] += 1;
4078    }
4079
4080    let mut output_len = 0usize;
4081    for &v in left_keys {
4082        if v < min || v > max {
4083            if options.require_all_left_keys_matched {
4084                return Ok(None);
4085            }
4086            continue;
4087        }
4088        let bucket = (v - min) as usize;
4089        let bucket_len = offsets[bucket + 1] - offsets[bucket];
4090        if bucket_len == 0 {
4091            if options.require_all_left_keys_matched {
4092                return Ok(None);
4093            }
4094            continue;
4095        }
4096        let Some(new_output_len) = output_len.checked_add(bucket_len) else {
4097            return Ok(None);
4098        };
4099        output_len = new_output_len;
4100    }
4101
4102    let output_plan = DenseI64InnerOutputPlan {
4103        left_keys,
4104        min,
4105        max,
4106        offsets: &offsets,
4107        positions: &positions,
4108        output_len,
4109    };
4110    let i64_lanes = build_dense_i64_inner_output_data(&i64_specs, &output_plan);
4111    // Float64 lanes materialized cache-efficiently in the same probe row order
4112    // (br-frankenpandas-jzrem); the matched-run walk is only needed when there
4113    // are Float64 columns to build.
4114    let matched = if f64_specs.is_empty() {
4115        Vec::new()
4116    } else {
4117        dense_inner_matched_runs(&output_plan)
4118    };
4119    let f64_columns = build_dense_inner_f64_columns(f64_specs, &matched, &positions, output_len);
4120
4121    // Lazy unit-range output index: identical labels (0..output_len as
4122    // IndexLabel::Int64, materialized on demand), pre-proven unique and
4123    // ascending — skips the eager Vec<IndexLabel> build for huge join outputs.
4124    let index = Index::new_known_unique_int64_unit_range(0, output_len);
4125    let mut columns = ColumnStore::new();
4126    let mut column_order = Vec::with_capacity(order_kinds.len());
4127    let mut i64_it = i64_specs.into_iter().zip(i64_lanes);
4128    let mut f64_it = f64_columns.into_iter();
4129    for kind in &order_kinds {
4130        match kind {
4131            DenseInnerSpecKind::I64 => {
4132                let (spec, lane) = i64_it.next().expect("i64 lane for each I64 kind");
4133                let column = match lane {
4134                    DenseI64LaneData::RepeatRunLengths { values, run_lens } => {
4135                        Column::from_i64_repeat_values_run_lengths(values, run_lens)
4136                    }
4137                    DenseI64LaneData::RepeatedSlices { data, segments } => {
4138                        Column::from_i64_repeated_slices_shared(data, segments, output_len)
4139                    }
4140                    DenseI64LaneData::Full(data) => Column::from_i64_values(data),
4141                };
4142                debug_assert_eq!(column.len(), output_len);
4143                insert_merged_output_column(&mut columns, &mut column_order, spec.name, column)?;
4144            }
4145            DenseInnerSpecKind::F64 => {
4146                let (name, column) = f64_it.next().expect("f64 column for each F64 kind");
4147                debug_assert_eq!(column.len(), output_len);
4148                insert_merged_output_column(&mut columns, &mut column_order, name, column)?;
4149            }
4150        }
4151    }
4152
4153    Ok(Some(MergedDataFrame {
4154        index,
4155        columns,
4156        column_order,
4157    }))
4158}
4159
4160fn push_join_invalid_range(ranges: &mut Vec<(usize, usize)>, start: usize, len: usize) {
4161    if len == 0 {
4162        return;
4163    }
4164    if let Some((last_start, last_len)) = ranges.last_mut()
4165        && last_start.checked_add(*last_len) == Some(start)
4166    {
4167        *last_len += len;
4168        return;
4169    }
4170    ranges.push((start, len));
4171}
4172
4173fn dense_cycle_key_at(witness: Int64DenseCycleWitness, row: usize) -> Option<i64> {
4174    let offset = i64::try_from(row % witness.period).ok()?;
4175    witness.start.checked_add(offset)
4176}
4177
4178fn dense_cycle_left_join_shape(
4179    left_witness: Int64DenseCycleWitness,
4180    right_witness: Int64DenseCycleWitness,
4181) -> Option<(usize, ValidityMask)> {
4182    let mut output_len = 0usize;
4183    let mut invalid_ranges = Vec::<(usize, usize)>::new();
4184    for left_pos in 0..left_witness.len {
4185        let key = dense_cycle_key_at(left_witness, left_pos)?;
4186        if let Some((_, right_count)) = right_witness.offset_count_for_key(key) {
4187            output_len = output_len.checked_add(right_count)?;
4188        } else {
4189            push_join_invalid_range(&mut invalid_ranges, output_len, 1);
4190            output_len = output_len.checked_add(1)?;
4191        }
4192    }
4193    let right_validity = ValidityMask::from_invalid_ranges(Arc::from(invalid_ranges), output_len);
4194    Some((output_len, right_validity))
4195}
4196
4197/// Dense-cycle LEFT merge builder (br-frankenpandas-yq96z).
4198///
4199/// For certified `key[row] = start + (row % period)` Int64 keys, the previous
4200/// high-fanout left path still built an O(left_rows) plan, right segment tape,
4201/// and one repeat-run descriptor per left lane. This path keeps the same
4202/// left-major pandas order but stores only the two key witnesses:
4203///
4204/// - output length/right validity are derived by scanning the left witness once;
4205/// - left lanes read `source[left_pos]` and repeat by the matching right count;
4206/// - right lanes replay positions `right_offset + k * right_period`;
4207/// - unmatched left rows emit one right null at the same output slot.
4208///
4209/// The route accepts only all-valid Int64 columns. Any other dtype/null shape
4210/// falls back to the existing materialized-plan builder.
4211fn build_single_key_dense_cycle_i64_left_merge_output(
4212    left: &fp_frame::DataFrame,
4213    right: &fp_frame::DataFrame,
4214    left_on: &[&str],
4215    right_on: &[&str],
4216    left_key: &Column,
4217    right_key: &Column,
4218    suffixes: &ResolvedMergeSuffixes,
4219) -> Result<Option<MergedDataFrame>, JoinError> {
4220    debug_assert_eq!(left_on.len(), 1);
4221    debug_assert_eq!(right_on.len(), 1);
4222
4223    let Some(left_witness) = left_key
4224        .int64_dense_cycle_witness()
4225        .filter(|witness| witness.len == left_key.len())
4226    else {
4227        return Ok(None);
4228    };
4229    let Some(right_witness) = right_key
4230        .int64_dense_cycle_witness()
4231        .filter(|witness| witness.len == right_key.len())
4232    else {
4233        return Ok(None);
4234    };
4235    let Some((output_len, right_validity)) =
4236        dense_cycle_left_join_shape(left_witness, right_witness)
4237    else {
4238        return Ok(None);
4239    };
4240    if !right_validity.all() {
4241        // The generic gather promotes all-valid Int64 lanes when this join
4242        // invents a gap. This lazy i64-only representation cannot do so.
4243        return Ok(None);
4244    }
4245
4246    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
4247    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
4248    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
4249    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
4250    let shared_key_names = if left_on[0] == right_on[0] {
4251        [left_on[0]].into_iter().collect::<HashSet<&str>>()
4252    } else {
4253        HashSet::new()
4254    };
4255    let overlapping_names =
4256        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
4257
4258    enum DenseCycleLeftLane {
4259        Left,
4260        Right,
4261    }
4262    let mut spec_names = Vec::<String>::new();
4263    let mut spec_kinds = Vec::<DenseCycleLeftLane>::new();
4264    let mut spec_sources = Vec::<Arc<[i64]>>::new();
4265
4266    for name in left.column_names() {
4267        let col = left
4268            .columns()
4269            .get(name)
4270            .expect("left column listed in column_names must exist");
4271        let Some(source) = col.as_i64_arc() else {
4272            return Ok(None);
4273        };
4274        let out_name = if left_key_name_set.contains(name.as_str()) {
4275            name.clone()
4276        } else if right_col_names.contains(name) {
4277            apply_merge_suffix(name, suffixes.left.as_deref())
4278        } else {
4279            name.clone()
4280        };
4281        spec_names.push(out_name);
4282        spec_kinds.push(DenseCycleLeftLane::Left);
4283        spec_sources.push(source);
4284    }
4285
4286    for name in right.column_names() {
4287        let col = right
4288            .columns()
4289            .get(name)
4290            .expect("right column listed in column_names must exist");
4291        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
4292            continue;
4293        }
4294        let Some(source) = col.as_i64_arc() else {
4295            return Ok(None);
4296        };
4297        let out_name = if left_col_names.contains(name) {
4298            apply_merge_suffix(name, suffixes.right.as_deref())
4299        } else {
4300            name.clone()
4301        };
4302        spec_names.push(out_name);
4303        spec_kinds.push(DenseCycleLeftLane::Right);
4304        spec_sources.push(source);
4305    }
4306    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
4307
4308    let index = Index::new_known_unique_int64_unit_range(0, output_len);
4309    let mut columns = ColumnStore::new();
4310    let mut column_order = Vec::with_capacity(spec_names.len());
4311    for ((name, kind), source) in spec_names.into_iter().zip(spec_kinds).zip(spec_sources) {
4312        let column = match kind {
4313            DenseCycleLeftLane::Left => Column::from_i64_left_join_dense_cycle_left(
4314                source,
4315                left_witness,
4316                right_witness,
4317                output_len,
4318            ),
4319            DenseCycleLeftLane::Right => Column::from_i64_left_join_dense_cycle_right_nullable(
4320                source,
4321                left_witness,
4322                right_witness,
4323                right_validity.clone(),
4324                output_len,
4325            ),
4326        };
4327        debug_assert_eq!(column.len(), output_len);
4328        insert_merged_output_column(&mut columns, &mut column_order, name, column)?;
4329    }
4330
4331    Ok(Some(MergedDataFrame {
4332        index,
4333        columns,
4334        column_order,
4335    }))
4336}
4337
4338/// Fused dense-i64 LEFT merge builder (br-frankenpandas-7wxoc).
4339///
4340/// The partial-match left join previously materialized TWO
4341/// `Vec<Option<usize>>` of output length (16 B/slot each — ~627 MB of
4342/// intermediate on a 19.6M-row join) in `dense_int64_left_positions`, then
4343/// re-walked them per column through `reindex_by_positions`. Here the probe
4344/// emits a compact matched plan (`(left_pos, bucket_start, run_len)`, with
4345/// `usize::MAX` as the bucket sentinel for unmatched left rows that emit one
4346/// null-right row), and the output lanes are built with the proven inner-
4347/// builder machinery: muis1 right value tapes, 6bsw3 row-chunked disjoint
4348/// `split_at_mut` fills, 3ad4n lazy repeat-run left lanes, plus ONE shared
4349/// validity mask for every right lane (the null pattern is identical across
4350/// them — word-wise run fills, cloned per lane).
4351///
4352/// Bit-identical to the position-vector path: the plan is the same left
4353/// probe order; matched runs replay the same CSR bucket ranges; right lanes
4354/// keep dtype Int64 with `Null(NullKind::Null)` at unmatched rows (exactly
4355/// `reindex_by_positions`' missing semantics); left lanes repeat the left
4356/// value `run_len` times as `take_positions` would.
4357fn build_single_key_dense_i64_left_merge_output(
4358    left: &fp_frame::DataFrame,
4359    right: &fp_frame::DataFrame,
4360    left_on: &[&str],
4361    right_on: &[&str],
4362    left_key: &Column,
4363    right_key: &Column,
4364    suffixes: &ResolvedMergeSuffixes,
4365) -> Result<Option<MergedDataFrame>, JoinError> {
4366    debug_assert_eq!(left_on.len(), 1);
4367    debug_assert_eq!(right_on.len(), 1);
4368
4369    let Some(left_keys) = left_key.as_i64_slice() else {
4370        return Ok(None);
4371    };
4372    let Some(right_keys) = right_key.as_i64_slice() else {
4373        return Ok(None);
4374    };
4375    // Empty sides are rare and the position-vector path handles their edge
4376    // semantics; the dense-span gate below also needs a non-empty right.
4377    if left_keys.is_empty() || right_keys.is_empty() {
4378        return Ok(None);
4379    }
4380
4381    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
4382    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
4383    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
4384    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
4385    let shared_key_names = if left_on[0] == right_on[0] {
4386        [left_on[0]].into_iter().collect::<HashSet<&str>>()
4387    } else {
4388        HashSet::new()
4389    };
4390    let overlapping_names =
4391        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
4392
4393    let mut specs = Vec::<FusedInt64OutputColumn<'_>>::new();
4394    let mut sources = Vec::<Arc<[i64]>>::new();
4395    for name in left.column_names() {
4396        let col = left
4397            .columns()
4398            .get(name)
4399            .expect("left column listed in column_names must exist");
4400        let Some(values) = col.as_i64_slice() else {
4401            return Ok(None);
4402        };
4403        let source = col.as_i64_arc().unwrap_or_else(|| Arc::from(values));
4404        let out_name = if left_key_name_set.contains(name.as_str()) {
4405            name.clone()
4406        } else if right_col_names.contains(name) {
4407            apply_merge_suffix(name, suffixes.left.as_deref())
4408        } else {
4409            name.clone()
4410        };
4411        specs.push(FusedInt64OutputColumn {
4412            name: out_name,
4413            side: FusedInt64Side::Left,
4414            values,
4415        });
4416        sources.push(source);
4417    }
4418    for name in right.column_names() {
4419        let col = right
4420            .columns()
4421            .get(name)
4422            .expect("right column listed in column_names must exist");
4423        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
4424            continue;
4425        }
4426        let Some(values) = col.as_i64_slice() else {
4427            return Ok(None);
4428        };
4429        let source = col.as_i64_arc().unwrap_or_else(|| Arc::from(values));
4430        let out_name = if left_col_names.contains(name) {
4431            apply_merge_suffix(name, suffixes.right.as_deref())
4432        } else {
4433            name.clone()
4434        };
4435        specs.push(FusedInt64OutputColumn {
4436            name: out_name,
4437            side: FusedInt64Side::Right,
4438            values,
4439        });
4440        sources.push(source);
4441    }
4442    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
4443
4444    let row_count = left_keys.len().saturating_add(right_keys.len());
4445    let max_dense_span = row_count.saturating_mul(4).max(1024);
4446    let left_witness = left_key
4447        .int64_dense_cycle_witness()
4448        .filter(|witness| witness.len == left_keys.len());
4449    let right_witness = right_key
4450        .int64_dense_cycle_witness()
4451        .filter(|witness| witness.len == right_keys.len());
4452    if let (Some(left_witness), Some(right_witness), Some((right_min, right_max))) = (
4453        left_witness,
4454        right_witness,
4455        right_witness.and_then(dense_cycle_domain),
4456    ) {
4457        let right_span = i128::from(right_max) - i128::from(right_min) + 1;
4458        if right_span <= max_dense_span as i128
4459            && let Some((output_len, right_validity)) =
4460                dense_cycle_probe_output_len_and_validity(left_witness, right_witness)
4461        {
4462            if !right_validity.all() {
4463                // Fall through to the typed gather below, which widens the
4464                // gap-bearing Int64 lanes to Float64 like pandas.
4465            } else {
4466                let index = Index::new_known_unique_int64_unit_range(0, output_len);
4467                let mut columns = ColumnStore::new();
4468                let mut column_order = Vec::with_capacity(specs.len());
4469                for (spec, source) in specs.into_iter().zip(sources) {
4470                    let column = match spec.side {
4471                        FusedInt64Side::Left => Column::from_i64_dense_cycle_probe_repeat(
4472                            source,
4473                            left_witness,
4474                            right_witness,
4475                            output_len,
4476                        ),
4477                        FusedInt64Side::Right => {
4478                            Column::from_i64_nullable_dense_cycle_probe_build_with_sparse_validity(
4479                                source,
4480                                left_witness,
4481                                right_witness,
4482                                right_validity.clone(),
4483                                output_len,
4484                            )
4485                        }
4486                    };
4487                    debug_assert_eq!(column.len(), output_len);
4488                    insert_merged_output_column(
4489                        &mut columns,
4490                        &mut column_order,
4491                        spec.name,
4492                        column,
4493                    )?;
4494                }
4495                return Ok(Some(MergedDataFrame {
4496                    index,
4497                    columns,
4498                    column_order,
4499                }));
4500            }
4501        }
4502    }
4503
4504    // Dense CSR over the RIGHT key range — same gate as the position path
4505    // (span <= 4*(rows)+1024) so routing between fused/fallback matches
4506    // dense_int64_left_positions' accept set.
4507    let mut min_key = right_keys[0];
4508    let mut max_key = right_keys[0];
4509    for &key in right_keys {
4510        min_key = min_key.min(key);
4511        max_key = max_key.max(key);
4512    }
4513    let span = (i128::from(max_key)) - (i128::from(min_key)) + 1;
4514    if span > max_dense_span as i128 {
4515        return Ok(None);
4516    }
4517    let span = usize::try_from(span).expect("span bounded by max_dense_span");
4518
4519    let mut offsets = vec![0usize; span + 1];
4520    for &key in right_keys {
4521        offsets[(key - min_key) as usize + 1] += 1;
4522    }
4523    for i in 0..span {
4524        offsets[i + 1] += offsets[i];
4525    }
4526    let mut positions = vec![0usize; right_keys.len()];
4527    let mut cursor = offsets[..span].to_vec();
4528    for (pos, &key) in right_keys.iter().enumerate() {
4529        let bucket = (key - min_key) as usize;
4530        positions[cursor[bucket]] = pos;
4531        cursor[bucket] += 1;
4532    }
4533
4534    // Matched plan: (left_pos, bucket_start, run_len); bucket_start ==
4535    // usize::MAX marks an unmatched left row (one output row, null right).
4536    const UNMATCHED: usize = usize::MAX;
4537    let mut plan = Vec::<(usize, usize, usize)>::with_capacity(left_keys.len());
4538    let mut output_len = 0usize;
4539    for (left_pos, &key) in left_keys.iter().enumerate() {
4540        let offset = i128::from(key) - i128::from(min_key);
4541        let run = if offset >= 0 && offset < span as i128 {
4542            let bucket = offset as usize;
4543            let start = offsets[bucket];
4544            let len = offsets[bucket + 1] - start;
4545            if len == 0 {
4546                (left_pos, UNMATCHED, 1)
4547            } else {
4548                (left_pos, start, len)
4549            }
4550        } else {
4551            (left_pos, UNMATCHED, 1)
4552        };
4553        let Some(new_len) = output_len.checked_add(run.2) else {
4554            return Ok(None);
4555        };
4556        output_len = new_len;
4557        plan.push(run);
4558    }
4559    if plan.iter().any(|&(_, start, _)| start == UNMATCHED) {
4560        return Ok(None);
4561    }
4562
4563    // Shared right-lane segment descriptor (br-frankenpandas-yiqv5): the plan's
4564    // `(bucket_start, run_len)` pairs are exactly the nullable repeated-slices
4565    // segment format (`bucket_start == usize::MAX` == UNMATCHED ⇒ a null run), so
4566    // every right lane is emitted as a LAZY `LazyNullableRepeatedSlicesInt64`
4567    // over its bucket-order value tape instead of a materialized O(output_len)
4568    // buffer. The validity mask is rebuilt from these segments inside the column
4569    // ctor (matched runs valid, unmatched rows null) — identical to the prior
4570    // word-wise fill.
4571    let right_segments: Arc<[(usize, usize)]> = plan
4572        .iter()
4573        .map(|&(_, start, run_len)| (start, run_len))
4574        .collect();
4575
4576    // Left lanes as lazy repeat runs when the average fanout pays (3ad4n
4577    // gate); unmatched rows are singleton runs so the representation is
4578    // uniform.
4579    let use_repeat_runs = output_len >= plan.len().saturating_mul(2);
4580
4581    // Only LOW-FANOUT LEFT lanes still materialize into O(output_len) buffers;
4582    // right lanes are always lazy (nullable repeated-slices) and high-fanout
4583    // left lanes are lazy repeat runs.
4584    let full_specs: Vec<usize> = specs
4585        .iter()
4586        .enumerate()
4587        .filter(|(_, spec)| matches!(spec.side, FusedInt64Side::Left) && !use_repeat_runs)
4588        .map(|(idx, _)| idx)
4589        .collect();
4590
4591    let mut full_data: Vec<Vec<i64>> = Vec::new();
4592    let thread_count = join_parallel_thread_count();
4593    if !full_specs.is_empty() {
4594        // Right value tapes in bucket order (muis1), shared read-only.
4595        let tapes: Vec<Option<Vec<i64>>> = full_specs
4596            .iter()
4597            .map(|&spec_idx| match specs[spec_idx].side {
4598                FusedInt64Side::Left => None,
4599                FusedInt64Side::Right => Some(
4600                    positions
4601                        .iter()
4602                        .map(|&right_pos| specs[spec_idx].values[right_pos])
4603                        .collect(),
4604                ),
4605            })
4606            .collect();
4607
4608        if output_len >= DENSE_I64_INNER_PARALLEL_MIN_VALUES && thread_count > 1 {
4609            // Output-balanced chunk boundaries over the plan (6bsw3).
4610            let target = output_len.div_ceil(thread_count).max(1);
4611            let mut boundaries = vec![(0usize, 0usize)];
4612            let mut cumulative = 0usize;
4613            let mut next_target = target;
4614            for (plan_idx, &(_, _, run_len)) in plan.iter().enumerate() {
4615                cumulative += run_len;
4616                if cumulative >= next_target && plan_idx + 1 < plan.len() {
4617                    boundaries.push((plan_idx + 1, cumulative));
4618                    next_target = cumulative.saturating_add(target);
4619                }
4620            }
4621            boundaries.push((plan.len(), output_len));
4622            let chunk_count = boundaries.len() - 1;
4623
4624            let mut column_bufs: Vec<Vec<i64>> =
4625                full_specs.iter().map(|_| vec![0i64; output_len]).collect();
4626            let mut bundles: Vec<Vec<&mut [i64]>> = (0..chunk_count)
4627                .map(|_| Vec::with_capacity(full_specs.len()))
4628                .collect();
4629            for buf in &mut column_bufs {
4630                let mut rest: &mut [i64] = buf.as_mut_slice();
4631                let mut prev = 0usize;
4632                for (chunk_idx, window) in boundaries.windows(2).enumerate() {
4633                    let (chunk_slice, tail) = rest.split_at_mut(window[1].1 - prev);
4634                    prev = window[1].1;
4635                    rest = tail;
4636                    bundles[chunk_idx].push(chunk_slice);
4637                }
4638            }
4639
4640            let plan = &plan;
4641            let specs_ref = &specs;
4642            let full_specs_ref = &full_specs;
4643            std::thread::scope(|scope| {
4644                let mut handles = Vec::with_capacity(chunk_count);
4645                for (chunk_idx, mut bundle) in bundles.into_iter().enumerate() {
4646                    let (plan_start, out_start) = boundaries[chunk_idx];
4647                    let (plan_end, out_end) = boundaries[chunk_idx + 1];
4648                    let tapes = &tapes;
4649                    handles.push(scope.spawn(move || {
4650                        let mut cursor = 0usize;
4651                        for &(left_pos, start, run_len) in &plan[plan_start..plan_end] {
4652                            for (slice, (&spec_idx, tape)) in bundle
4653                                .iter_mut()
4654                                .zip(full_specs_ref.iter().zip(tapes.iter()))
4655                            {
4656                                match specs_ref[spec_idx].side {
4657                                    FusedInt64Side::Left => {
4658                                        slice[cursor..cursor + run_len]
4659                                            .fill(specs_ref[spec_idx].values[left_pos]);
4660                                    }
4661                                    FusedInt64Side::Right => {
4662                                        if start != UNMATCHED {
4663                                            slice[cursor..cursor + run_len].copy_from_slice(
4664                                                &tape
4665                                                    .as_ref()
4666                                                    .expect("right spec must have a bucket tape")
4667                                                    [start..start + run_len],
4668                                            );
4669                                        }
4670                                        // Unmatched rows keep the zeroed
4671                                        // datum; the shared validity mask
4672                                        // marks them null.
4673                                    }
4674                                }
4675                            }
4676                            cursor += run_len;
4677                        }
4678                        debug_assert_eq!(cursor, out_end - out_start);
4679                    }));
4680                }
4681                for handle in handles {
4682                    handle
4683                        .join()
4684                        .expect("dense i64 left output worker must not panic");
4685                }
4686            });
4687            full_data = column_bufs;
4688        } else {
4689            full_data = full_specs.iter().map(|_| vec![0i64; output_len]).collect();
4690            let mut cursor = 0usize;
4691            for &(left_pos, start, run_len) in &plan {
4692                for (buf, (&spec_idx, tape)) in full_data
4693                    .iter_mut()
4694                    .zip(full_specs.iter().zip(tapes.iter()))
4695                {
4696                    match specs[spec_idx].side {
4697                        FusedInt64Side::Left => {
4698                            buf[cursor..cursor + run_len].fill(specs[spec_idx].values[left_pos]);
4699                        }
4700                        FusedInt64Side::Right => {
4701                            if start != UNMATCHED {
4702                                buf[cursor..cursor + run_len].copy_from_slice(
4703                                    &tape.as_ref().expect("right spec must have a bucket tape")
4704                                        [start..start + run_len],
4705                                );
4706                            }
4707                        }
4708                    }
4709                }
4710                cursor += run_len;
4711            }
4712            debug_assert_eq!(cursor, output_len);
4713        }
4714    }
4715
4716    // Lazy unit-range output index (see build_single_key_dense_i64 site).
4717    let index = Index::new_known_unique_int64_unit_range(0, output_len);
4718    let mut columns = ColumnStore::new();
4719    let mut column_order = Vec::with_capacity(specs.len());
4720    let mut full_iter = full_data.into_iter();
4721    for spec in specs {
4722        let column = match spec.side {
4723            FusedInt64Side::Right => {
4724                // Lazy nullable repeated-slices over the bucket-order tape
4725                // (br-frankenpandas-yiqv5): O(matched) descriptor, no O(output)
4726                // materialization.
4727                let tape: Vec<i64> = positions
4728                    .iter()
4729                    .map(|&right_pos| spec.values[right_pos])
4730                    .collect();
4731                Column::from_i64_nullable_repeated_slices_shared(
4732                    tape,
4733                    Arc::clone(&right_segments),
4734                    output_len,
4735                )
4736            }
4737            FusedInt64Side::Left if use_repeat_runs => Column::from_i64_repeat_runs(
4738                plan.iter()
4739                    .map(|&(left_pos, _, run_len)| (spec.values[left_pos], run_len))
4740                    .collect(),
4741            ),
4742            FusedInt64Side::Left => {
4743                let data = full_iter
4744                    .next()
4745                    .expect("full lane buffer must exist for every non-run left spec");
4746                Column::from_i64_values(data)
4747            }
4748        };
4749        debug_assert_eq!(column.len(), output_len);
4750        insert_merged_output_column(&mut columns, &mut column_order, spec.name, column)?;
4751    }
4752
4753    Ok(Some(MergedDataFrame {
4754        index,
4755        columns,
4756        column_order,
4757    }))
4758}
4759
4760/// Fused dense-i64 RIGHT merge builder (br-frankenpandas-4p3ie) — the
4761/// side-swapped mirror of [`build_single_key_dense_i64_left_merge_output`]:
4762/// the probe walks RIGHT keys in probe order against a dense CSR over the
4763/// LEFT key range, emitting `(right_pos, left_bucket_start, run_len)` plan
4764/// rows (`usize::MAX` sentinel = unmatched right row, one null-left output
4765/// row). Right lanes (including the shared key column, which pandas fills
4766/// from the RIGHT side under the LEFT name) are all-valid repeat runs; left
4767/// lanes fill from muis1-style left value tapes with ONE shared validity
4768/// mask and keep dtype Int64 with `Null(NullKind::Null)` at unmatched rows
4769/// (`reindex_by_positions` missing semantics — NOT Float64-promoted).
4770fn build_single_key_dense_i64_right_merge_output(
4771    left: &fp_frame::DataFrame,
4772    right: &fp_frame::DataFrame,
4773    left_on: &[&str],
4774    right_on: &[&str],
4775    left_key: &Column,
4776    right_key: &Column,
4777    suffixes: &ResolvedMergeSuffixes,
4778) -> Result<Option<MergedDataFrame>, JoinError> {
4779    debug_assert_eq!(left_on.len(), 1);
4780    debug_assert_eq!(right_on.len(), 1);
4781
4782    let Some(left_keys) = left_key.as_i64_slice() else {
4783        return Ok(None);
4784    };
4785    let Some(right_keys) = right_key.as_i64_slice() else {
4786        return Ok(None);
4787    };
4788    if left_keys.is_empty() || right_keys.is_empty() {
4789        return Ok(None);
4790    }
4791
4792    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
4793    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
4794    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
4795    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
4796    let shared_key_names = if left_on[0] == right_on[0] {
4797        [left_on[0]].into_iter().collect::<HashSet<&str>>()
4798    } else {
4799        HashSet::new()
4800    };
4801    let overlapping_names =
4802        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
4803
4804    // Lane specs in output order. The shared key slot keeps the LEFT name
4805    // but carries RIGHT key values (all output rows have a right row), so it
4806    // is a Right-side lane on right_keys.
4807    let mut specs = Vec::<FusedInt64OutputColumn<'_>>::new();
4808    let mut sources = Vec::<Arc<[i64]>>::new();
4809    for name in left.column_names() {
4810        let col = left
4811            .columns()
4812            .get(name)
4813            .expect("left column listed in column_names must exist");
4814        let Some(values) = col.as_i64_slice() else {
4815            return Ok(None);
4816        };
4817        if left_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
4818            let right_key_col = right
4819                .columns()
4820                .get(right_on[0])
4821                .expect("right key column must exist");
4822            let source = right_key_col
4823                .as_i64_arc()
4824                .unwrap_or_else(|| Arc::from(right_keys));
4825            specs.push(FusedInt64OutputColumn {
4826                name: name.clone(),
4827                side: FusedInt64Side::Right,
4828                values: right_keys,
4829            });
4830            sources.push(source);
4831            continue;
4832        }
4833        let source = col.as_i64_arc().unwrap_or_else(|| Arc::from(values));
4834        let out_name = if left_key_name_set.contains(name.as_str()) {
4835            name.clone()
4836        } else if right_col_names.contains(name) {
4837            apply_merge_suffix(name, suffixes.left.as_deref())
4838        } else {
4839            name.clone()
4840        };
4841        specs.push(FusedInt64OutputColumn {
4842            name: out_name,
4843            side: FusedInt64Side::Left,
4844            values,
4845        });
4846        sources.push(source);
4847    }
4848    for name in right.column_names() {
4849        let col = right
4850            .columns()
4851            .get(name)
4852            .expect("right column listed in column_names must exist");
4853        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
4854            continue;
4855        }
4856        let Some(values) = col.as_i64_slice() else {
4857            return Ok(None);
4858        };
4859        let source = col.as_i64_arc().unwrap_or_else(|| Arc::from(values));
4860        let out_name = if left_col_names.contains(name) {
4861            apply_merge_suffix(name, suffixes.right.as_deref())
4862        } else {
4863            name.clone()
4864        };
4865        specs.push(FusedInt64OutputColumn {
4866            name: out_name,
4867            side: FusedInt64Side::Right,
4868            values,
4869        });
4870        sources.push(source);
4871    }
4872    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
4873
4874    let row_count = left_keys.len().saturating_add(right_keys.len());
4875    let max_dense_span = row_count.saturating_mul(4).max(1024);
4876    let left_witness = left_key
4877        .int64_dense_cycle_witness()
4878        .filter(|witness| witness.len == left_keys.len());
4879    let right_witness = right_key
4880        .int64_dense_cycle_witness()
4881        .filter(|witness| witness.len == right_keys.len());
4882    if let (Some(left_witness), Some(right_witness), Some((left_min, left_max))) = (
4883        left_witness,
4884        right_witness,
4885        left_witness.and_then(dense_cycle_domain),
4886    ) {
4887        let left_span = i128::from(left_max) - i128::from(left_min) + 1;
4888        if left_span <= max_dense_span as i128
4889            && let Some((output_len, left_validity)) =
4890                dense_cycle_probe_output_len_and_validity(right_witness, left_witness)
4891        {
4892            if !left_validity.all() {
4893                // See the LEFT merge mirror: only the typed gather can
4894                // preserve pandas' Int64-to-Float64 widening for a new gap.
4895            } else {
4896                let index = Index::new_known_unique_int64_unit_range(0, output_len);
4897                let mut columns = ColumnStore::new();
4898                let mut column_order = Vec::with_capacity(specs.len());
4899                for (spec, source) in specs.into_iter().zip(sources) {
4900                    let column = match spec.side {
4901                        FusedInt64Side::Left => {
4902                            Column::from_i64_nullable_dense_cycle_probe_build_with_sparse_validity(
4903                                source,
4904                                right_witness,
4905                                left_witness,
4906                                left_validity.clone(),
4907                                output_len,
4908                            )
4909                        }
4910                        FusedInt64Side::Right => Column::from_i64_dense_cycle_probe_repeat(
4911                            source,
4912                            right_witness,
4913                            left_witness,
4914                            output_len,
4915                        ),
4916                    };
4917                    debug_assert_eq!(column.len(), output_len);
4918                    insert_merged_output_column(
4919                        &mut columns,
4920                        &mut column_order,
4921                        spec.name,
4922                        column,
4923                    )?;
4924                }
4925                return Ok(Some(MergedDataFrame {
4926                    index,
4927                    columns,
4928                    column_order,
4929                }));
4930            }
4931        }
4932    }
4933
4934    // Dense CSR over the LEFT key range — same gate as
4935    // dense_int64_right_positions (span <= 4*rows+1024).
4936    let mut min_key = left_keys[0];
4937    let mut max_key = left_keys[0];
4938    for &key in left_keys {
4939        min_key = min_key.min(key);
4940        max_key = max_key.max(key);
4941    }
4942    let span = (i128::from(max_key)) - (i128::from(min_key)) + 1;
4943    if span > max_dense_span as i128 {
4944        return Ok(None);
4945    }
4946    let span = usize::try_from(span).expect("span bounded by max_dense_span");
4947
4948    let mut offsets = vec![0usize; span + 1];
4949    for &key in left_keys {
4950        offsets[(key - min_key) as usize + 1] += 1;
4951    }
4952    for i in 0..span {
4953        offsets[i + 1] += offsets[i];
4954    }
4955    let mut positions = vec![0usize; left_keys.len()];
4956    let mut cursor = offsets[..span].to_vec();
4957    for (pos, &key) in left_keys.iter().enumerate() {
4958        let bucket = (key - min_key) as usize;
4959        positions[cursor[bucket]] = pos;
4960        cursor[bucket] += 1;
4961    }
4962
4963    // Plan over RIGHT probe order: (right_pos, left_bucket_start, run_len);
4964    // usize::MAX = unmatched right row (one null-left output row).
4965    const UNMATCHED: usize = usize::MAX;
4966    let mut plan = Vec::<(usize, usize, usize)>::with_capacity(right_keys.len());
4967    let mut output_len = 0usize;
4968    for (right_pos, &key) in right_keys.iter().enumerate() {
4969        let offset = i128::from(key) - i128::from(min_key);
4970        let run = if offset >= 0 && offset < span as i128 {
4971            let bucket = offset as usize;
4972            let start = offsets[bucket];
4973            let len = offsets[bucket + 1] - start;
4974            if len == 0 {
4975                (right_pos, UNMATCHED, 1)
4976            } else {
4977                (right_pos, start, len)
4978            }
4979        } else {
4980            (right_pos, UNMATCHED, 1)
4981        };
4982        let Some(new_len) = output_len.checked_add(run.2) else {
4983            return Ok(None);
4984        };
4985        output_len = new_len;
4986        plan.push(run);
4987    }
4988    if plan.iter().any(|&(_, start, _)| start == UNMATCHED) {
4989        return Ok(None);
4990    }
4991
4992    // One shared validity mask for every left lane.
4993    // Shared left-lane segment descriptor (br-frankenpandas-yiqv5): mirror of
4994    // the left builder — every null-introduced LEFT lane is a LAZY
4995    // `LazyNullableRepeatedSlicesInt64` over its bucket-order tape (plan's
4996    // `(bucket_start, run_len)`, `usize::MAX` ⇒ null run) instead of a
4997    // materialized O(output_len) buffer; validity rebuilt in the ctor.
4998    let left_segments: Arc<[(usize, usize)]> = plan
4999        .iter()
5000        .map(|&(_, start, run_len)| (start, run_len))
5001        .collect();
5002
5003    // Right lanes (all-valid) as lazy repeat runs when the fanout pays.
5004    let use_repeat_runs = output_len >= plan.len().saturating_mul(2);
5005
5006    // Only LOW-FANOUT RIGHT lanes still materialize; left lanes are always lazy
5007    // (nullable repeated-slices) and high-fanout right lanes are lazy repeat runs.
5008    let full_specs: Vec<usize> = specs
5009        .iter()
5010        .enumerate()
5011        .filter(|(_, spec)| matches!(spec.side, FusedInt64Side::Right) && !use_repeat_runs)
5012        .map(|(idx, _)| idx)
5013        .collect();
5014
5015    let mut full_data: Vec<Vec<i64>> = Vec::new();
5016    let thread_count = join_parallel_thread_count();
5017    if !full_specs.is_empty() {
5018        // LEFT value tapes in bucket order, shared read-only.
5019        let tapes: Vec<Option<Vec<i64>>> = full_specs
5020            .iter()
5021            .map(|&spec_idx| match specs[spec_idx].side {
5022                FusedInt64Side::Right => None,
5023                FusedInt64Side::Left => Some(
5024                    positions
5025                        .iter()
5026                        .map(|&left_pos| specs[spec_idx].values[left_pos])
5027                        .collect(),
5028                ),
5029            })
5030            .collect();
5031
5032        if output_len >= DENSE_I64_INNER_PARALLEL_MIN_VALUES && thread_count > 1 {
5033            let target = output_len.div_ceil(thread_count).max(1);
5034            let mut boundaries = vec![(0usize, 0usize)];
5035            let mut cumulative = 0usize;
5036            let mut next_target = target;
5037            for (plan_idx, &(_, _, run_len)) in plan.iter().enumerate() {
5038                cumulative += run_len;
5039                if cumulative >= next_target && plan_idx + 1 < plan.len() {
5040                    boundaries.push((plan_idx + 1, cumulative));
5041                    next_target = cumulative.saturating_add(target);
5042                }
5043            }
5044            boundaries.push((plan.len(), output_len));
5045            let chunk_count = boundaries.len() - 1;
5046
5047            let mut column_bufs: Vec<Vec<i64>> =
5048                full_specs.iter().map(|_| vec![0i64; output_len]).collect();
5049            let mut bundles: Vec<Vec<&mut [i64]>> = (0..chunk_count)
5050                .map(|_| Vec::with_capacity(full_specs.len()))
5051                .collect();
5052            for buf in &mut column_bufs {
5053                let mut rest: &mut [i64] = buf.as_mut_slice();
5054                let mut prev = 0usize;
5055                for (chunk_idx, window) in boundaries.windows(2).enumerate() {
5056                    let (chunk_slice, tail) = rest.split_at_mut(window[1].1 - prev);
5057                    prev = window[1].1;
5058                    rest = tail;
5059                    bundles[chunk_idx].push(chunk_slice);
5060                }
5061            }
5062
5063            let plan = &plan;
5064            let specs_ref = &specs;
5065            let full_specs_ref = &full_specs;
5066            std::thread::scope(|scope| {
5067                let mut handles = Vec::with_capacity(chunk_count);
5068                for (chunk_idx, mut bundle) in bundles.into_iter().enumerate() {
5069                    let (plan_start, out_start) = boundaries[chunk_idx];
5070                    let (plan_end, out_end) = boundaries[chunk_idx + 1];
5071                    let tapes = &tapes;
5072                    handles.push(scope.spawn(move || {
5073                        let mut cursor = 0usize;
5074                        for &(right_pos, start, run_len) in &plan[plan_start..plan_end] {
5075                            for (slice, (&spec_idx, tape)) in bundle
5076                                .iter_mut()
5077                                .zip(full_specs_ref.iter().zip(tapes.iter()))
5078                            {
5079                                match specs_ref[spec_idx].side {
5080                                    FusedInt64Side::Right => {
5081                                        slice[cursor..cursor + run_len]
5082                                            .fill(specs_ref[spec_idx].values[right_pos]);
5083                                    }
5084                                    FusedInt64Side::Left => {
5085                                        if start != UNMATCHED {
5086                                            slice[cursor..cursor + run_len].copy_from_slice(
5087                                                &tape
5088                                                    .as_ref()
5089                                                    .expect("left spec must have a bucket tape")
5090                                                    [start..start + run_len],
5091                                            );
5092                                        }
5093                                    }
5094                                }
5095                            }
5096                            cursor += run_len;
5097                        }
5098                        debug_assert_eq!(cursor, out_end - out_start);
5099                    }));
5100                }
5101                for handle in handles {
5102                    handle
5103                        .join()
5104                        .expect("dense i64 right output worker must not panic");
5105                }
5106            });
5107            full_data = column_bufs;
5108        } else {
5109            full_data = full_specs.iter().map(|_| vec![0i64; output_len]).collect();
5110            let mut cursor = 0usize;
5111            for &(right_pos, start, run_len) in &plan {
5112                for (buf, (&spec_idx, tape)) in full_data
5113                    .iter_mut()
5114                    .zip(full_specs.iter().zip(tapes.iter()))
5115                {
5116                    match specs[spec_idx].side {
5117                        FusedInt64Side::Right => {
5118                            buf[cursor..cursor + run_len].fill(specs[spec_idx].values[right_pos]);
5119                        }
5120                        FusedInt64Side::Left => {
5121                            if start != UNMATCHED {
5122                                buf[cursor..cursor + run_len].copy_from_slice(
5123                                    &tape.as_ref().expect("left spec must have a bucket tape")
5124                                        [start..start + run_len],
5125                                );
5126                            }
5127                        }
5128                    }
5129                }
5130                cursor += run_len;
5131            }
5132            debug_assert_eq!(cursor, output_len);
5133        }
5134    }
5135
5136    // Lazy unit-range output index (see build_single_key_dense_i64 site).
5137    let index = Index::new_known_unique_int64_unit_range(0, output_len);
5138    let mut columns = ColumnStore::new();
5139    let mut column_order = Vec::with_capacity(specs.len());
5140    let mut full_iter = full_data.into_iter();
5141    for spec in specs {
5142        let column = match spec.side {
5143            FusedInt64Side::Left => {
5144                // Lazy nullable repeated-slices over the left bucket-order tape
5145                // (br-frankenpandas-yiqv5). When no left row is missing the
5146                // segments carry no `usize::MAX` sentinel, so the ctor yields an
5147                // all-valid mask — identical to the prior `from_i64_values`.
5148                let tape: Vec<i64> = positions
5149                    .iter()
5150                    .map(|&left_pos| spec.values[left_pos])
5151                    .collect();
5152                Column::from_i64_nullable_repeated_slices_shared(
5153                    tape,
5154                    Arc::clone(&left_segments),
5155                    output_len,
5156                )
5157            }
5158            FusedInt64Side::Right if use_repeat_runs => Column::from_i64_repeat_runs(
5159                plan.iter()
5160                    .map(|&(right_pos, _, run_len)| (spec.values[right_pos], run_len))
5161                    .collect(),
5162            ),
5163            FusedInt64Side::Right => {
5164                let data = full_iter
5165                    .next()
5166                    .expect("full lane buffer must exist for every non-run right spec");
5167                Column::from_i64_values(data)
5168            }
5169        };
5170        debug_assert_eq!(column.len(), output_len);
5171        insert_merged_output_column(&mut columns, &mut column_order, spec.name, column)?;
5172    }
5173
5174    Ok(Some(MergedDataFrame {
5175        index,
5176        columns,
5177        column_order,
5178    }))
5179}
5180
5181fn dense_cycle_domain(witness: Int64DenseCycleWitness) -> Option<(i64, i64)> {
5182    let last_offset = i64::try_from(witness.period.checked_sub(1)?).ok()?;
5183    Some((witness.start, witness.start.checked_add(last_offset)?))
5184}
5185
5186fn dense_cycle_probe_output_len_and_validity(
5187    probe_witness: Int64DenseCycleWitness,
5188    build_witness: Int64DenseCycleWitness,
5189) -> Option<(usize, ValidityMask)> {
5190    let mut output_len = 0usize;
5191    let mut invalid_ranges = Vec::<(usize, usize)>::new();
5192    for probe_pos in 0..probe_witness.len {
5193        let offset = i64::try_from(probe_pos % probe_witness.period).ok()?;
5194        let key = probe_witness.start.checked_add(offset)?;
5195        let run_len = build_witness
5196            .offset_count_for_key(key)
5197            .map_or(1, |(_, count)| count);
5198        if build_witness.offset_count_for_key(key).is_none() {
5199            push_dense_outer_invalid_range(&mut invalid_ranges, output_len, 1);
5200        }
5201        output_len = output_len.checked_add(run_len)?;
5202    }
5203    Some((
5204        output_len,
5205        ValidityMask::from_invalid_ranges(Arc::from(invalid_ranges), output_len),
5206    ))
5207}
5208
5209struct DenseOuterRunTape {
5210    run_lens: Option<Arc<[usize]>>,
5211    left_run_valid: Option<Arc<[bool]>>,
5212    left_run_positions: Option<Arc<[usize]>>,
5213    right_positions_csr: Option<Arc<[usize]>>,
5214    right_segments: Option<Arc<[(usize, usize)]>>,
5215    key_runs: Vec<(i64, usize)>,
5216    left_sparse_validity: ValidityMask,
5217    right_sparse_validity: ValidityMask,
5218    output_len: usize,
5219    has_left_missing: bool,
5220    has_right_missing: bool,
5221}
5222
5223fn push_dense_outer_invalid_range(ranges: &mut Vec<(usize, usize)>, start: usize, len: usize) {
5224    if len == 0 {
5225        return;
5226    }
5227    if let Some((last_start, last_len)) = ranges.last_mut()
5228        && last_start.checked_add(*last_len) == Some(start)
5229    {
5230        *last_len += len;
5231        return;
5232    }
5233    ranges.push((start, len));
5234}
5235
5236fn append_dense_cycle_positions(
5237    positions: &mut Vec<usize>,
5238    witness: Int64DenseCycleWitness,
5239    key: i64,
5240) -> Option<usize> {
5241    let (mut pos, count) = witness.offset_count_for_key(key)?;
5242    for _ in 0..count {
5243        positions.push(pos);
5244        pos = pos.checked_add(witness.period)?;
5245    }
5246    Some(count)
5247}
5248
5249fn build_dense_cycle_outer_run_tape(
5250    left_witness: Int64DenseCycleWitness,
5251    right_witness: Int64DenseCycleWitness,
5252    min_key: i64,
5253    span: usize,
5254) -> Option<DenseOuterRunTape> {
5255    let mut run_count = 0usize;
5256    let mut active_key_count = 0usize;
5257    let mut output_len = 0usize;
5258    let mut has_left_missing = false;
5259    let mut has_right_missing = false;
5260    for bucket in 0..span {
5261        let key = min_key.checked_add(i64::try_from(bucket).ok()?)?;
5262        let ll = left_witness
5263            .offset_count_for_key(key)
5264            .map_or(0, |(_, count)| count);
5265        let rl = right_witness
5266            .offset_count_for_key(key)
5267            .map_or(0, |(_, count)| count);
5268        let rows = match (ll > 0, rl > 0) {
5269            (true, true) => {
5270                run_count = run_count.checked_add(ll)?;
5271                ll.checked_mul(rl)?
5272            }
5273            (true, false) => {
5274                has_right_missing = true;
5275                run_count = run_count.checked_add(ll)?;
5276                ll
5277            }
5278            (false, true) => {
5279                has_left_missing = true;
5280                run_count = run_count.checked_add(1)?;
5281                rl
5282            }
5283            (false, false) => continue,
5284        };
5285        active_key_count = active_key_count.checked_add(1)?;
5286        output_len = output_len.checked_add(rows)?;
5287    }
5288
5289    let build_left_tape = !has_left_missing;
5290    let mut run_lens = Vec::with_capacity(if build_left_tape { run_count } else { 0 });
5291    let mut left_run_valid = Vec::with_capacity(if build_left_tape { run_count } else { 0 });
5292    let mut left_run_positions = Vec::with_capacity(if build_left_tape { run_count } else { 0 });
5293    let mut right_positions_csr = Vec::with_capacity(right_witness.len);
5294    let mut right_segments = Vec::with_capacity(run_count);
5295    let mut key_runs = Vec::with_capacity(active_key_count);
5296    let mut left_invalid_ranges = Vec::<(usize, usize)>::new();
5297    let mut right_invalid_ranges = Vec::<(usize, usize)>::new();
5298    let mut out_pos = 0usize;
5299    let build_right_tape = !has_right_missing;
5300    for bucket in 0..span {
5301        let key = min_key.checked_add(i64::try_from(bucket).ok()?)?;
5302        let left_span = left_witness.offset_count_for_key(key);
5303        let right_span = right_witness.offset_count_for_key(key);
5304        let ll = left_span.map_or(0, |(_, count)| count);
5305        let rl = right_span.map_or(0, |(_, count)| count);
5306        if ll == 0 && rl == 0 {
5307            continue;
5308        }
5309
5310        let right_start = if rl > 0 {
5311            if build_right_tape {
5312                let start = right_positions_csr.len();
5313                let appended =
5314                    append_dense_cycle_positions(&mut right_positions_csr, right_witness, key)?;
5315                debug_assert_eq!(appended, rl);
5316                start
5317            } else {
5318                0
5319            }
5320        } else {
5321            usize::MAX
5322        };
5323
5324        let rows = match (left_span, right_span) {
5325            (Some((mut left_pos, left_count)), Some((_, right_count))) => {
5326                let rows = left_count.checked_mul(right_count)?;
5327                if build_left_tape {
5328                    run_lens.extend(std::iter::repeat_n(right_count, left_count));
5329                    left_run_valid.extend(std::iter::repeat_n(true, left_count));
5330                }
5331                if build_right_tape {
5332                    right_segments
5333                        .extend(std::iter::repeat_n((right_start, right_count), left_count));
5334                }
5335                if build_left_tape {
5336                    for _ in 0..left_count {
5337                        left_run_positions.push(left_pos);
5338                        left_pos = left_pos.checked_add(left_witness.period)?;
5339                    }
5340                }
5341                rows
5342            }
5343            (Some((mut left_pos, left_count)), None) => {
5344                push_dense_outer_invalid_range(&mut right_invalid_ranges, out_pos, left_count);
5345                if build_left_tape {
5346                    run_lens.extend(std::iter::repeat_n(1, left_count));
5347                    left_run_valid.extend(std::iter::repeat_n(true, left_count));
5348                }
5349                if build_right_tape {
5350                    right_segments.extend(std::iter::repeat_n((usize::MAX, 1), left_count));
5351                }
5352                if build_left_tape {
5353                    for _ in 0..left_count {
5354                        left_run_positions.push(left_pos);
5355                        left_pos = left_pos.checked_add(left_witness.period)?;
5356                    }
5357                }
5358                left_count
5359            }
5360            (None, Some((_, right_count))) => {
5361                push_dense_outer_invalid_range(&mut left_invalid_ranges, out_pos, right_count);
5362                if build_left_tape {
5363                    run_lens.push(right_count);
5364                    left_run_valid.push(false);
5365                    left_run_positions.push(0);
5366                }
5367                if build_right_tape {
5368                    right_segments.push((right_start, right_count));
5369                }
5370                right_count
5371            }
5372            (None, None) => unreachable!("empty buckets are skipped above"),
5373        };
5374        key_runs.push((key, rows));
5375        out_pos = out_pos.checked_add(rows)?;
5376    }
5377    if out_pos != output_len
5378        || (build_left_tape
5379            && (run_lens.len() != run_count
5380                || left_run_valid.len() != run_count
5381                || left_run_positions.len() != run_count))
5382        || (!build_left_tape
5383            && (!run_lens.is_empty()
5384                || !left_run_valid.is_empty()
5385                || !left_run_positions.is_empty()))
5386        || (build_right_tape
5387            && (right_segments.len() != run_count
5388                || right_positions_csr.len() != right_witness.len))
5389        || (!build_right_tape && (!right_segments.is_empty() || !right_positions_csr.is_empty()))
5390    {
5391        return None;
5392    }
5393
5394    Some(DenseOuterRunTape {
5395        run_lens: build_left_tape.then(|| Arc::from(run_lens)),
5396        left_run_valid: build_left_tape.then(|| Arc::from(left_run_valid)),
5397        left_run_positions: build_left_tape.then(|| Arc::from(left_run_positions)),
5398        right_positions_csr: build_right_tape.then(|| Arc::from(right_positions_csr)),
5399        right_segments: build_right_tape.then(|| Arc::from(right_segments)),
5400        key_runs,
5401        left_sparse_validity: ValidityMask::from_invalid_ranges(
5402            Arc::from(left_invalid_ranges),
5403            output_len,
5404        ),
5405        right_sparse_validity: ValidityMask::from_invalid_ranges(
5406            Arc::from(right_invalid_ranges),
5407            output_len,
5408        ),
5409        output_len,
5410        has_left_missing,
5411        has_right_missing,
5412    })
5413}
5414
5415/// Fused dense-i64 OUTER merge builder (br-frankenpandas-343ho).
5416///
5417/// `dense_int64_outer_positions` + the position-vector outer builder cost:
5418/// per-bucket `Vec<Vec<usize>>` heap allocs, two `Vec<Option<usize>>` of
5419/// output length, a per-row Scalar coalesce for the shared key column, and
5420/// per-column reindex walks. Here the bucket walk (ascending key order —
5421/// the dense outer output IS bucket order) emits a compact plan
5422/// (`(left_pos | MAX, right_bucket_start | MAX, run_len)`), and:
5423///
5424/// - the SHARED KEY lane is synthesized as `(min_key + bucket, bucket_rows)`
5425///   repeat runs — every row in a bucket has the bucket's key, whichever
5426///   side it came from, so the coalesce is a closed form (all-valid Int64);
5427/// - left lanes promote to nullable Float64 ONLY when right-only buckets
5428///   exist, right lanes ONLY when left-only rows exist — matching
5429///   `reindex_join_column_with_invented_gap`'s per-positions `has_missing` check (a
5430///   side with no missing rows keeps dtype Int64 via the all-present
5431///   take_positions path);
5432/// - per-side shared validity masks are word-filled once from the plan and
5433///   cloned per lane;
5434/// - lanes fill via the 6bsw3 row-chunked disjoint `split_at_mut` scheme
5435///   (an i64 group and an f64 group, sharing plan/boundaries), with muis1
5436///   right value tapes (i64, plus a once-cast f64 tape for promoted lanes).
5437///
5438/// Bit-identical: bucket walk order == `dense_int64_outer_positions`
5439/// (cross products left-major, then left-only rows, then right-only rows,
5440/// per ascending bucket); promoted slots use `v as f64` + the 0.0-datum
5441/// gap (`Null(NaN)`), preserved slots `Null(NullKind::Null)` — the exact
5442/// eager semantics per br-frankenpandas-1bvcl/lt5qx.
5443fn build_single_key_dense_i64_outer_merge_output(
5444    left: &fp_frame::DataFrame,
5445    right: &fp_frame::DataFrame,
5446    left_on: &[&str],
5447    right_on: &[&str],
5448    left_key: &Column,
5449    right_key: &Column,
5450    suffixes: &ResolvedMergeSuffixes,
5451) -> Result<Option<MergedDataFrame>, JoinError> {
5452    debug_assert_eq!(left_on.len(), 1);
5453    debug_assert_eq!(right_on.len(), 1);
5454
5455    // The closed-form key lane needs the coalesced shared-key shape; the
5456    // non-shared-name variant keeps the position-vector path.
5457    if left_on[0] != right_on[0] {
5458        return Ok(None);
5459    }
5460    let Some(left_keys) = left_key.as_i64_slice() else {
5461        return Ok(None);
5462    };
5463    let Some(right_keys) = right_key.as_i64_slice() else {
5464        return Ok(None);
5465    };
5466    if left_keys.is_empty() || right_keys.is_empty() {
5467        return Ok(None);
5468    }
5469
5470    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
5471    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
5472    let key_name = left_on[0];
5473    let shared_key_names = [key_name].into_iter().collect::<HashSet<&str>>();
5474    let overlapping_names =
5475        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
5476
5477    // Lane specs in output order: left columns (the key slot handled as the
5478    // synthetic coalesced lane), then right non-key columns.
5479    enum OuterLaneKind {
5480        SharedKey,
5481        Lane(FusedInt64Side),
5482    }
5483    let mut spec_names = Vec::<String>::new();
5484    let mut spec_kinds = Vec::<OuterLaneKind>::new();
5485    let mut spec_values = Vec::<&[i64]>::new();
5486    let mut spec_sources = Vec::<Arc<[i64]>>::new();
5487    for name in left.column_names() {
5488        let col = left
5489            .columns()
5490            .get(name)
5491            .expect("left column listed in column_names must exist");
5492        let Some(values) = col.as_i64_slice() else {
5493            return Ok(None);
5494        };
5495        let source = col.as_i64_arc().unwrap_or_else(|| Arc::from(values));
5496        if name.as_str() == key_name {
5497            spec_names.push(name.clone());
5498            spec_kinds.push(OuterLaneKind::SharedKey);
5499            spec_values.push(values);
5500            spec_sources.push(Arc::clone(&source));
5501            continue;
5502        }
5503        let out_name = if right_col_names.contains(name) {
5504            apply_merge_suffix(name, suffixes.left.as_deref())
5505        } else {
5506            name.clone()
5507        };
5508        spec_names.push(out_name);
5509        spec_kinds.push(OuterLaneKind::Lane(FusedInt64Side::Left));
5510        spec_values.push(values);
5511        spec_sources.push(source);
5512    }
5513    for name in right.column_names() {
5514        let col = right
5515            .columns()
5516            .get(name)
5517            .expect("right column listed in column_names must exist");
5518        let Some(values) = col.as_i64_slice() else {
5519            return Ok(None);
5520        };
5521        let source = col.as_i64_arc().unwrap_or_else(|| Arc::from(values));
5522        if name.as_str() == key_name {
5523            continue;
5524        }
5525        let out_name = if left_col_names.contains(name) {
5526            apply_merge_suffix(name, suffixes.right.as_deref())
5527        } else {
5528            name.clone()
5529        };
5530        spec_names.push(out_name);
5531        spec_kinds.push(OuterLaneKind::Lane(FusedInt64Side::Right));
5532        spec_values.push(values);
5533        spec_sources.push(source);
5534    }
5535    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
5536
5537    // Dense span over BOTH key sets (same gate as dense_int64_outer_positions
5538    // so fused/fallback routing matches).
5539    let left_witness = left_key
5540        .int64_dense_cycle_witness()
5541        .filter(|witness| witness.len == left_keys.len());
5542    let right_witness = right_key
5543        .int64_dense_cycle_witness()
5544        .filter(|witness| witness.len == right_keys.len());
5545    let (min_key, max_key) = match (
5546        left_witness.and_then(dense_cycle_domain),
5547        right_witness.and_then(dense_cycle_domain),
5548    ) {
5549        (Some((left_min, left_max)), Some((right_min, right_max))) => {
5550            (left_min.min(right_min), left_max.max(right_max))
5551        }
5552        _ => {
5553            let mut min_key = left_keys[0];
5554            let mut max_key = left_keys[0];
5555            for &key in left_keys.iter().chain(right_keys.iter()) {
5556                min_key = min_key.min(key);
5557                max_key = max_key.max(key);
5558            }
5559            (min_key, max_key)
5560        }
5561    };
5562    let span = (i128::from(max_key)) - (i128::from(min_key)) + 1;
5563    let row_count = left_keys.len().saturating_add(right_keys.len());
5564    let max_dense_span = row_count.saturating_mul(4).max(1024);
5565    if span > max_dense_span as i128 {
5566        return Ok(None);
5567    }
5568    let span = usize::try_from(span).expect("span bounded by max_dense_span");
5569
5570    const NONE_POS: usize = usize::MAX;
5571    let Some(DenseOuterRunTape {
5572        run_lens,
5573        left_run_valid,
5574        left_run_positions,
5575        right_positions_csr,
5576        right_segments,
5577        key_runs,
5578        left_sparse_validity,
5579        right_sparse_validity,
5580        output_len,
5581        has_left_missing,
5582        has_right_missing,
5583    }) = (match (left_witness, right_witness) {
5584        (Some(left_witness), Some(right_witness)) => {
5585            build_dense_cycle_outer_run_tape(left_witness, right_witness, min_key, span)
5586        }
5587        _ => None,
5588    })
5589    .or_else(|| {
5590        // CSR layouts for both sides (replaces the per-bucket Vec<Vec<usize>>).
5591        let build_dense_cycle_csr =
5592            |witness: Int64DenseCycleWitness| -> Option<(Vec<usize>, Vec<usize>)> {
5593                let mut offsets = Vec::with_capacity(span + 1);
5594                offsets.push(0);
5595                let mut total = 0usize;
5596                for bucket in 0..span {
5597                    let key = min_key.checked_add(i64::try_from(bucket).ok()?)?;
5598                    let count = witness
5599                        .offset_count_for_key(key)
5600                        .map_or(0, |(_, count)| count);
5601                    total = total.checked_add(count)?;
5602                    offsets.push(total);
5603                }
5604                if total != witness.len {
5605                    return None;
5606                }
5607                let mut positions = Vec::with_capacity(witness.len);
5608                for bucket in 0..span {
5609                    let key = min_key.checked_add(i64::try_from(bucket).ok()?)?;
5610                    let appended =
5611                        append_dense_cycle_positions(&mut positions, witness, key).unwrap_or(0);
5612                    debug_assert_eq!(
5613                        appended,
5614                        witness
5615                            .offset_count_for_key(key)
5616                            .map_or(0, |(_, count)| count)
5617                    );
5618                }
5619                (positions.len() == witness.len).then_some((offsets, positions))
5620            };
5621        let build_csr = |keys: &[i64], witness: Option<Int64DenseCycleWitness>| {
5622            if let Some(csr) = witness
5623                .filter(|witness| witness.len == keys.len())
5624                .and_then(&build_dense_cycle_csr)
5625            {
5626                return csr;
5627            }
5628            let mut offsets = vec![0usize; span + 1];
5629            for &key in keys {
5630                offsets[(key - min_key) as usize + 1] += 1;
5631            }
5632            for i in 0..span {
5633                offsets[i + 1] += offsets[i];
5634            }
5635            let mut positions = vec![0usize; keys.len()];
5636            let mut cursor = offsets[..span].to_vec();
5637            for (pos, &key) in keys.iter().enumerate() {
5638                let bucket = (key - min_key) as usize;
5639                positions[cursor[bucket]] = pos;
5640                cursor[bucket] += 1;
5641            }
5642            (offsets, positions)
5643        };
5644        let (left_offsets, left_positions_csr) = build_csr(left_keys, left_witness);
5645        let (right_offsets, right_positions_csr) = build_csr(right_keys, right_witness);
5646
5647        // Bucket walk -> compact plan + closed-form key runs + output length.
5648        let mut plan = Vec::<(usize, usize, usize)>::new();
5649        let mut key_runs = Vec::<(i64, usize)>::new();
5650        let mut left_invalid_ranges = Vec::<(usize, usize)>::new();
5651        let mut right_invalid_ranges = Vec::<(usize, usize)>::new();
5652        let mut output_len = 0usize;
5653        let mut has_left_missing = false; // right-only buckets exist
5654        let mut has_right_missing = false; // left-only rows exist
5655        for bucket in 0..span {
5656            let ll = left_offsets[bucket + 1] - left_offsets[bucket];
5657            let rl = right_offsets[bucket + 1] - right_offsets[bucket];
5658            let bucket_rows = match (ll > 0, rl > 0) {
5659                (true, true) => {
5660                    let rows = ll.checked_mul(rl)?;
5661                    let rs = right_offsets[bucket];
5662                    for &lp in &left_positions_csr[left_offsets[bucket]..left_offsets[bucket + 1]] {
5663                        plan.push((lp, rs, rl));
5664                    }
5665                    rows
5666                }
5667                (true, false) => {
5668                    has_right_missing = true;
5669                    push_dense_outer_invalid_range(&mut right_invalid_ranges, output_len, ll);
5670                    for &lp in &left_positions_csr[left_offsets[bucket]..left_offsets[bucket + 1]] {
5671                        plan.push((lp, NONE_POS, 1));
5672                    }
5673                    ll
5674                }
5675                (false, true) => {
5676                    has_left_missing = true;
5677                    push_dense_outer_invalid_range(&mut left_invalid_ranges, output_len, rl);
5678                    plan.push((NONE_POS, right_offsets[bucket], rl));
5679                    rl
5680                }
5681                (false, false) => continue,
5682            };
5683            output_len = output_len.checked_add(bucket_rows)?;
5684            key_runs.push((min_key + bucket as i64, bucket_rows));
5685        }
5686
5687        // Shared lazy-lane descriptors (br-frankenpandas-yiqv5): the plan drives
5688        // every value lane as a LAZY column rather than an O(output_len)
5689        // materialized buffer. The kept side stays all-valid; the promoted
5690        // side becomes the matching nullable lazy lane.
5691        let run_lens: Arc<[usize]> = plan.iter().map(|&(_, _, run_len)| run_len).collect();
5692        let left_run_valid: Arc<[bool]> = plan.iter().map(|&(lp, _, _)| lp < NONE_POS).collect();
5693        let left_run_positions: Arc<[usize]> = plan
5694            .iter()
5695            .map(|&(lp, _, _)| if lp == NONE_POS { 0 } else { lp })
5696            .collect();
5697        let right_segments: Arc<[(usize, usize)]> =
5698            plan.iter().map(|&(_, rs, run_len)| (rs, run_len)).collect();
5699        Some(DenseOuterRunTape {
5700            run_lens: Some(run_lens),
5701            left_run_valid: Some(left_run_valid),
5702            left_run_positions: Some(left_run_positions),
5703            right_positions_csr: Some(Arc::from(right_positions_csr)),
5704            right_segments: Some(right_segments),
5705            key_runs,
5706            left_sparse_validity: ValidityMask::from_invalid_ranges(
5707                Arc::from(left_invalid_ranges),
5708                output_len,
5709            ),
5710            right_sparse_validity: ValidityMask::from_invalid_ranges(
5711                Arc::from(right_invalid_ranges),
5712                output_len,
5713            ),
5714            output_len,
5715            has_left_missing,
5716            has_right_missing,
5717        })
5718    })
5719    else {
5720        return Ok(None);
5721    };
5722
5723    // Promoted (nullable Float64) when that side has missing rows, preserved
5724    // (all-valid Int64) otherwise.
5725    let promoted = |side: FusedInt64Side| match side {
5726        FusedInt64Side::Left => has_left_missing,
5727        FusedInt64Side::Right => has_right_missing,
5728    };
5729
5730    // Left broadcast run values (one per run): i64 (preserved) or f64 (promoted).
5731    let left_run_values_i64 = |idx: usize| -> Option<Vec<i64>> {
5732        Some(
5733            left_run_positions
5734                .as_ref()?
5735                .iter()
5736                .zip(left_run_valid.as_ref()?.iter())
5737                .map(|(&lp, &valid)| if valid { spec_values[idx][lp] } else { 0 })
5738                .collect(),
5739        )
5740    };
5741    // Assemble columns in spec order, each a lazy lane.
5742    let index = Index::new_known_unique_int64_unit_range(0, output_len);
5743    let mut columns = ColumnStore::new();
5744    let mut column_order = Vec::with_capacity(spec_names.len());
5745    for (idx, (name, kind)) in spec_names.into_iter().zip(spec_kinds.iter()).enumerate() {
5746        let column = match kind {
5747            OuterLaneKind::SharedKey => {
5748                // Closed-form coalesced key: all-valid, bucket key repeated in
5749                // ascending bucket order. Lazy repeat-runs when the fanout pays.
5750                if output_len >= key_runs.len().saturating_mul(2) {
5751                    Column::from_i64_repeat_runs(key_runs.clone())
5752                } else {
5753                    let mut data = Vec::with_capacity(output_len);
5754                    for &(key, run_len) in &key_runs {
5755                        data.resize(data.len() + run_len, key);
5756                    }
5757                    Column::from_i64_values(data)
5758                }
5759            }
5760            OuterLaneKind::Lane(side) => match (side, promoted(*side)) {
5761                (FusedInt64Side::Left, false) => {
5762                    let Some(run_lens) = run_lens.as_ref() else {
5763                        return Ok(None);
5764                    };
5765                    let Some(run_values) = left_run_values_i64(idx) else {
5766                        return Ok(None);
5767                    };
5768                    Column::from_i64_repeat_values_run_lengths(run_values, Arc::clone(run_lens))
5769                }
5770                (FusedInt64Side::Left, true) => {
5771                    if left_run_positions.is_none()
5772                        && let (Some(left_witness), Some(right_witness)) =
5773                            (left_witness, right_witness)
5774                    {
5775                        Column::from_i64_nullable_dense_cycle_left_as_f64_with_sparse_validity(
5776                            Arc::clone(&spec_sources[idx]),
5777                            left_witness,
5778                            right_witness,
5779                            min_key,
5780                            span,
5781                            left_sparse_validity.clone(),
5782                            output_len,
5783                        )
5784                    } else {
5785                        let Some(run_lens) = run_lens.as_ref() else {
5786                            return Ok(None);
5787                        };
5788                        let Some(left_run_positions) = left_run_positions.as_ref() else {
5789                            return Ok(None);
5790                        };
5791                        let Some(left_run_valid) = left_run_valid.as_ref() else {
5792                            return Ok(None);
5793                        };
5794                        Column::from_i64_nullable_repeat_positions_as_f64_with_sparse_validity(
5795                            Arc::clone(&spec_sources[idx]),
5796                            Arc::clone(left_run_positions),
5797                            Arc::clone(left_run_valid),
5798                            Arc::clone(run_lens),
5799                            left_sparse_validity.clone(),
5800                            output_len,
5801                        )
5802                    }
5803                }
5804                (FusedInt64Side::Right, false) => {
5805                    let Some(right_positions_csr) = right_positions_csr.as_ref() else {
5806                        return Ok(None);
5807                    };
5808                    let Some(right_segments) = right_segments.as_ref() else {
5809                        return Ok(None);
5810                    };
5811                    let tape_i64 = right_positions_csr
5812                        .iter()
5813                        .map(|&pos| spec_values[idx][pos])
5814                        .collect();
5815                    Column::from_i64_repeated_slices_shared(
5816                        tape_i64,
5817                        Arc::clone(right_segments),
5818                        output_len,
5819                    )
5820                }
5821                (FusedInt64Side::Right, true) => {
5822                    if right_positions_csr.is_none()
5823                        && let (Some(left_witness), Some(right_witness)) =
5824                            (left_witness, right_witness)
5825                    {
5826                        Column::from_i64_nullable_dense_cycle_right_as_f64_with_sparse_validity(
5827                            Arc::clone(&spec_sources[idx]),
5828                            left_witness,
5829                            right_witness,
5830                            min_key,
5831                            span,
5832                            right_sparse_validity.clone(),
5833                            output_len,
5834                        )
5835                    } else {
5836                        let Some(right_positions_csr) = right_positions_csr.as_ref() else {
5837                            return Ok(None);
5838                        };
5839                        let Some(right_segments) = right_segments.as_ref() else {
5840                            return Ok(None);
5841                        };
5842                        Column::from_i64_nullable_repeated_positions_as_f64_with_sparse_validity(
5843                            Arc::clone(&spec_sources[idx]),
5844                            Arc::clone(right_positions_csr),
5845                            Arc::clone(right_segments),
5846                            right_sparse_validity.clone(),
5847                            output_len,
5848                        )
5849                    }
5850                }
5851            },
5852        };
5853        debug_assert_eq!(column.len(), output_len);
5854        insert_merged_output_column(&mut columns, &mut column_order, name, column)?;
5855    }
5856
5857    Ok(Some(MergedDataFrame {
5858        index,
5859        columns,
5860        column_order,
5861    }))
5862}
5863
5864fn build_single_key_dense_i64_right_all_matched_merge_output(
5865    left: &fp_frame::DataFrame,
5866    right: &fp_frame::DataFrame,
5867    left_on: &[&str],
5868    right_on: &[&str],
5869    left_key: &Column,
5870    right_key: &Column,
5871    suffixes: &ResolvedMergeSuffixes,
5872) -> Result<Option<MergedDataFrame>, JoinError> {
5873    debug_assert_eq!(left_on.len(), 1);
5874    debug_assert_eq!(right_on.len(), 1);
5875
5876    let Some(left_keys) = left_key.as_i64_slice() else {
5877        return Ok(None);
5878    };
5879    let Some(right_keys) = right_key.as_i64_slice() else {
5880        return Ok(None);
5881    };
5882
5883    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
5884    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
5885    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
5886    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
5887    let shared_key_names = if left_on[0] == right_on[0] {
5888        [left_on[0]].into_iter().collect::<HashSet<&str>>()
5889    } else {
5890        HashSet::new()
5891    };
5892    let overlapping_names =
5893        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
5894
5895    let mut specs = Vec::<FusedInt64OutputColumn<'_>>::new();
5896    for name in left.column_names() {
5897        let col = left
5898            .columns()
5899            .get(name)
5900            .expect("left column listed in column_names must exist");
5901        let (values, side) = if left_key_name_set.contains(name.as_str())
5902            && shared_key_names.contains(name.as_str())
5903        {
5904            let right_key_col = right
5905                .columns()
5906                .get(right_on[0])
5907                .expect("right key column must exist");
5908            let Some(values) = right_key_col.as_i64_slice() else {
5909                return Ok(None);
5910            };
5911            (values, FusedInt64Side::Right)
5912        } else {
5913            let Some(values) = col.as_i64_slice() else {
5914                return Ok(None);
5915            };
5916            (values, FusedInt64Side::Left)
5917        };
5918        let out_name = if left_key_name_set.contains(name.as_str()) {
5919            name.clone()
5920        } else if right_col_names.contains(name) {
5921            apply_merge_suffix(name, suffixes.left.as_deref())
5922        } else {
5923            name.clone()
5924        };
5925        specs.push(FusedInt64OutputColumn {
5926            name: out_name,
5927            side,
5928            values,
5929        });
5930    }
5931
5932    for name in right.column_names() {
5933        let col = right
5934            .columns()
5935            .get(name)
5936            .expect("right column listed in column_names must exist");
5937        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
5938            continue;
5939        }
5940        let Some(values) = col.as_i64_slice() else {
5941            return Ok(None);
5942        };
5943        let out_name = if left_col_names.contains(name) {
5944            apply_merge_suffix(name, suffixes.right.as_deref())
5945        } else {
5946            name.clone()
5947        };
5948        specs.push(FusedInt64OutputColumn {
5949            name: out_name,
5950            side: FusedInt64Side::Right,
5951            values,
5952        });
5953    }
5954
5955    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
5956
5957    if right_keys.is_empty() {
5958        let mut columns = ColumnStore::new();
5959        let mut column_order = Vec::with_capacity(specs.len());
5960        for spec in specs {
5961            insert_merged_output_column(
5962                &mut columns,
5963                &mut column_order,
5964                spec.name,
5965                Column::from_i64_values(Vec::new()),
5966            )?;
5967        }
5968        return Ok(Some(MergedDataFrame {
5969            index: Index::new(Vec::new()),
5970            columns,
5971            column_order,
5972        }));
5973    }
5974    if left_keys.is_empty() {
5975        return Ok(None);
5976    }
5977
5978    let mut min = left_keys[0];
5979    let mut max = left_keys[0];
5980    for &v in left_keys {
5981        if v < min {
5982            min = v;
5983        }
5984        if v > max {
5985            max = v;
5986        }
5987    }
5988    let span = (max as i128) - (min as i128) + 1;
5989    if span > (1i128 << 24) || span > 16 * (left_keys.len() as i128) {
5990        return Ok(None);
5991    }
5992    let range = span as usize;
5993
5994    let mut offsets = vec![0usize; range + 1];
5995    for &v in left_keys {
5996        offsets[(v - min) as usize + 1] += 1;
5997    }
5998    for i in 0..range {
5999        offsets[i + 1] += offsets[i];
6000    }
6001    let mut positions = vec![0usize; left_keys.len()];
6002    let mut cursor = offsets.clone();
6003    for (pos, &v) in left_keys.iter().enumerate() {
6004        let bucket = (v - min) as usize;
6005        positions[cursor[bucket]] = pos;
6006        cursor[bucket] += 1;
6007    }
6008
6009    let mut output_len = 0usize;
6010    for &v in right_keys {
6011        if v < min || v > max {
6012            return Ok(None);
6013        }
6014        let bucket = (v - min) as usize;
6015        let bucket_len = offsets[bucket + 1] - offsets[bucket];
6016        if bucket_len == 0 {
6017            return Ok(None);
6018        }
6019        let Some(new_output_len) = output_len.checked_add(bucket_len) else {
6020            return Ok(None);
6021        };
6022        output_len = new_output_len;
6023    }
6024
6025    let mut output_data = specs
6026        .iter()
6027        .map(|_| Vec::<i64>::with_capacity(output_len))
6028        .collect::<Vec<_>>();
6029    for (right_pos, &v) in right_keys.iter().enumerate() {
6030        let bucket = (v - min) as usize;
6031        for &left_pos in &positions[offsets[bucket]..offsets[bucket + 1]] {
6032            for (out, spec) in output_data.iter_mut().zip(specs.iter()) {
6033                match spec.side {
6034                    FusedInt64Side::Left => out.push(spec.values[left_pos]),
6035                    FusedInt64Side::Right => out.push(spec.values[right_pos]),
6036                }
6037            }
6038        }
6039    }
6040
6041    // Lazy unit-range output index: identical labels (0..output_len as
6042    // IndexLabel::Int64, materialized on demand), pre-proven unique and
6043    // ascending — skips the eager Vec<IndexLabel> build for huge join outputs.
6044    let index = Index::new_known_unique_int64_unit_range(0, output_len);
6045    let mut columns = ColumnStore::new();
6046    let mut column_order = Vec::with_capacity(specs.len());
6047    for (spec, data) in specs.into_iter().zip(output_data) {
6048        debug_assert_eq!(data.len(), output_len);
6049        insert_merged_output_column(
6050            &mut columns,
6051            &mut column_order,
6052            spec.name,
6053            Column::from_i64_values(data),
6054        )?;
6055    }
6056
6057    Ok(Some(MergedDataFrame {
6058        index,
6059        columns,
6060        column_order,
6061    }))
6062}
6063
6064fn build_single_key_dense_i64_outer_all_matched_merge_output(
6065    left: &fp_frame::DataFrame,
6066    right: &fp_frame::DataFrame,
6067    left_on: &[&str],
6068    right_on: &[&str],
6069    left_key: &Column,
6070    right_key: &Column,
6071    suffixes: &ResolvedMergeSuffixes,
6072) -> Result<Option<MergedDataFrame>, JoinError> {
6073    debug_assert_eq!(left_on.len(), 1);
6074    debug_assert_eq!(right_on.len(), 1);
6075
6076    let Some(left_keys) = left_key.as_i64_slice() else {
6077        return Ok(None);
6078    };
6079    let Some(right_keys) = right_key.as_i64_slice() else {
6080        return Ok(None);
6081    };
6082
6083    if left_keys.is_empty() != right_keys.is_empty() {
6084        return Ok(None);
6085    }
6086    let dense_domain = if left_keys.is_empty() {
6087        None
6088    } else {
6089        let left_witness = left_key
6090            .int64_dense_cycle_witness()
6091            .filter(|witness| witness.len == left_keys.len());
6092        let right_witness = right_key
6093            .int64_dense_cycle_witness()
6094            .filter(|witness| witness.len == right_keys.len());
6095        match (
6096            left_witness.and_then(dense_cycle_domain),
6097            right_witness.and_then(dense_cycle_domain),
6098        ) {
6099            (Some(left_domain), Some(right_domain)) => {
6100                if left_domain != right_domain {
6101                    return Ok(None);
6102                }
6103                Some(left_domain)
6104            }
6105            _ => {
6106                let min_max = |keys: &[i64]| {
6107                    let mut min_key = keys[0];
6108                    let mut max_key = keys[0];
6109                    for &key in &keys[1..] {
6110                        min_key = min_key.min(key);
6111                        max_key = max_key.max(key);
6112                    }
6113                    (min_key, max_key)
6114                };
6115                let (left_min_key, left_max_key) = min_max(left_keys);
6116                let (right_min_key, right_max_key) = min_max(right_keys);
6117                if left_min_key != right_min_key || left_max_key != right_max_key {
6118                    return Ok(None);
6119                }
6120                Some((left_min_key, left_max_key))
6121            }
6122        }
6123    };
6124
6125    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
6126    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
6127    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
6128    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
6129    let shared_key_names = if left_on[0] == right_on[0] {
6130        [left_on[0]].into_iter().collect::<HashSet<&str>>()
6131    } else {
6132        HashSet::new()
6133    };
6134    let overlapping_names =
6135        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
6136
6137    let mut specs = Vec::<FusedInt64OutputColumn<'_>>::new();
6138    for name in left.column_names() {
6139        let col = left
6140            .columns()
6141            .get(name)
6142            .expect("left column listed in column_names must exist");
6143        let Some(values) = col.as_i64_slice() else {
6144            return Ok(None);
6145        };
6146        let out_name = if left_key_name_set.contains(name.as_str()) {
6147            name.clone()
6148        } else if right_col_names.contains(name) {
6149            apply_merge_suffix(name, suffixes.left.as_deref())
6150        } else {
6151            name.clone()
6152        };
6153        specs.push(FusedInt64OutputColumn {
6154            name: out_name,
6155            side: FusedInt64Side::Left,
6156            values,
6157        });
6158    }
6159
6160    for name in right.column_names() {
6161        let col = right
6162            .columns()
6163            .get(name)
6164            .expect("right column listed in column_names must exist");
6165        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
6166            continue;
6167        }
6168        let Some(values) = col.as_i64_slice() else {
6169            return Ok(None);
6170        };
6171        let out_name = if left_col_names.contains(name) {
6172            apply_merge_suffix(name, suffixes.right.as_deref())
6173        } else {
6174            name.clone()
6175        };
6176        specs.push(FusedInt64OutputColumn {
6177            name: out_name,
6178            side: FusedInt64Side::Right,
6179            values,
6180        });
6181    }
6182
6183    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
6184
6185    if left_keys.is_empty() || right_keys.is_empty() {
6186        if !left_keys.is_empty() || !right_keys.is_empty() {
6187            return Ok(None);
6188        }
6189        let mut columns = ColumnStore::new();
6190        let mut column_order = Vec::with_capacity(specs.len());
6191        for spec in specs {
6192            insert_merged_output_column(
6193                &mut columns,
6194                &mut column_order,
6195                spec.name,
6196                Column::from_i64_values(Vec::new()),
6197            )?;
6198        }
6199        return Ok(Some(MergedDataFrame {
6200            index: Index::new(Vec::new()),
6201            columns,
6202            column_order,
6203        }));
6204    }
6205
6206    let (min_key, max_key) = dense_domain.expect("empty dense outer case returned above");
6207
6208    let span = i128::from(max_key)
6209        .checked_sub(i128::from(min_key))
6210        .and_then(|span| span.checked_add(1));
6211    let Some(span) = span else {
6212        return Ok(None);
6213    };
6214    let row_count = left_keys.len().saturating_add(right_keys.len());
6215    let max_dense_span = row_count.saturating_mul(4).max(1024);
6216    if span > max_dense_span as i128 {
6217        return Ok(None);
6218    }
6219    let Ok(span) = usize::try_from(span) else {
6220        return Ok(None);
6221    };
6222
6223    let mut left_buckets = (0..span).map(|_| Vec::<usize>::new()).collect::<Vec<_>>();
6224    let mut right_buckets = (0..span).map(|_| Vec::<usize>::new()).collect::<Vec<_>>();
6225    for (pos, &key) in left_keys.iter().enumerate() {
6226        let Ok(bucket) = usize::try_from(i128::from(key) - i128::from(min_key)) else {
6227            return Ok(None);
6228        };
6229        left_buckets[bucket].push(pos);
6230    }
6231    for (pos, &key) in right_keys.iter().enumerate() {
6232        let Ok(bucket) = usize::try_from(i128::from(key) - i128::from(min_key)) else {
6233            return Ok(None);
6234        };
6235        right_buckets[bucket].push(pos);
6236    }
6237
6238    let mut output_len = 0usize;
6239    for (left_bucket, right_bucket) in left_buckets.iter().zip(right_buckets.iter()) {
6240        match (left_bucket.is_empty(), right_bucket.is_empty()) {
6241            (false, false) => {
6242                let Some(bucket_rows) = left_bucket.len().checked_mul(right_bucket.len()) else {
6243                    return Ok(None);
6244                };
6245                let Some(new_output_len) = output_len.checked_add(bucket_rows) else {
6246                    return Ok(None);
6247                };
6248                output_len = new_output_len;
6249            }
6250            (false, true) | (true, false) => return Ok(None),
6251            (true, true) => {}
6252        }
6253    }
6254
6255    // Lazy unit-range output index: identical labels (0..output_len as
6256    // IndexLabel::Int64, materialized on demand), pre-proven unique and
6257    // ascending — skips the eager Vec<IndexLabel> build for huge join outputs.
6258    let index = Index::new_known_unique_int64_unit_range(0, output_len);
6259    let mut columns = ColumnStore::new();
6260    let mut column_order = Vec::with_capacity(specs.len());
6261    for spec in specs {
6262        let FusedInt64OutputColumn { name, side, values } = spec;
6263        let mut data = Vec::<i64>::with_capacity(output_len);
6264        match side {
6265            FusedInt64Side::Left => {
6266                for (left_bucket, right_bucket) in left_buckets.iter().zip(right_buckets.iter()) {
6267                    if left_bucket.is_empty() {
6268                        continue;
6269                    }
6270                    let repeat_count = right_bucket.len();
6271                    for &left_pos in left_bucket {
6272                        let value = values[left_pos];
6273                        for _ in 0..repeat_count {
6274                            data.push(value);
6275                        }
6276                    }
6277                }
6278            }
6279            FusedInt64Side::Right => {
6280                for (left_bucket, right_bucket) in left_buckets.iter().zip(right_buckets.iter()) {
6281                    if left_bucket.is_empty() {
6282                        continue;
6283                    }
6284                    for _ in left_bucket {
6285                        for &right_pos in right_bucket {
6286                            data.push(values[right_pos]);
6287                        }
6288                    }
6289                }
6290            }
6291        }
6292        debug_assert_eq!(data.len(), output_len);
6293        insert_merged_output_column(
6294            &mut columns,
6295            &mut column_order,
6296            name,
6297            Column::from_i64_values(data),
6298        )?;
6299    }
6300
6301    Ok(Some(MergedDataFrame {
6302        index,
6303        columns,
6304        column_order,
6305    }))
6306}
6307
6308struct FixedDecimalUtf8Domain {
6309    prefix: Vec<u8>,
6310    decimal_width: usize,
6311    start: u64,
6312    len: usize,
6313}
6314
6315impl FixedDecimalUtf8Domain {
6316    fn row_width(&self) -> usize {
6317        self.prefix.len() + self.decimal_width
6318    }
6319}
6320
6321fn trailing_decimal_width(bytes: &[u8]) -> Option<usize> {
6322    let width = bytes
6323        .iter()
6324        .rev()
6325        .take_while(|byte| byte.is_ascii_digit())
6326        .count();
6327    (width > 0).then_some(width)
6328}
6329
6330fn parse_decimal_u64(bytes: &[u8]) -> Option<u64> {
6331    let mut out = 0u64;
6332    for &byte in bytes {
6333        if !byte.is_ascii_digit() {
6334            return None;
6335        }
6336        out = out.checked_mul(10)?.checked_add(u64::from(byte - b'0'))?;
6337    }
6338    Some(out)
6339}
6340
6341fn fixed_decimal_utf8_domain(bytes: &[u8], offsets: &[usize]) -> Option<FixedDecimalUtf8Domain> {
6342    let len = offsets.len().checked_sub(1)?;
6343    if len == 0 {
6344        return None;
6345    }
6346
6347    let first = utf8_span(bytes, offsets, 0);
6348    let decimal_width = trailing_decimal_width(first)?;
6349    let prefix_len = first.len().checked_sub(decimal_width)?;
6350    let prefix = first[..prefix_len].to_vec();
6351    let start = parse_decimal_u64(&first[prefix_len..])?;
6352    let row_width = first.len();
6353
6354    for row in 0..len {
6355        let span = utf8_span(bytes, offsets, row);
6356        if span.len() != row_width || !span.starts_with(&prefix) {
6357            return None;
6358        }
6359        let value = parse_decimal_u64(&span[prefix_len..])?;
6360        if value != start.checked_add(row as u64)? {
6361            return None;
6362        }
6363    }
6364
6365    Some(FixedDecimalUtf8Domain {
6366        prefix,
6367        decimal_width,
6368        start,
6369        len,
6370    })
6371}
6372
6373fn fixed_decimal_utf8_bucket(span: &[u8], domain: &FixedDecimalUtf8Domain) -> Option<usize> {
6374    if span.len() != domain.row_width() || !span.starts_with(&domain.prefix) {
6375        return None;
6376    }
6377    let value = parse_decimal_u64(&span[domain.prefix.len()..])?;
6378    let relative = value.checked_sub(domain.start)?;
6379    let bucket = usize::try_from(relative).ok()?;
6380    (bucket < domain.len).then_some(bucket)
6381}
6382
6383enum FixedDecimalUtf8OuterLane<'a> {
6384    SharedKey,
6385    LeftF64(&'a [f64]),
6386    RightF64(&'a [f64]),
6387    LeftI64(&'a [i64]),
6388    RightI64(&'a [i64]),
6389}
6390
6391fn build_single_key_fixed_decimal_utf8_outer_all_matched_merge_output(
6392    left: &fp_frame::DataFrame,
6393    right: &fp_frame::DataFrame,
6394    left_on: &[&str],
6395    right_on: &[&str],
6396    left_key: &Column,
6397    right_key: &Column,
6398    suffixes: &ResolvedMergeSuffixes,
6399) -> Result<Option<MergedDataFrame>, JoinError> {
6400    debug_assert_eq!(left_on.len(), 1);
6401    debug_assert_eq!(right_on.len(), 1);
6402
6403    if left_on[0] != right_on[0] {
6404        return Ok(None);
6405    }
6406
6407    let Some((left_bytes, left_offsets)) = left_key.as_utf8_contiguous() else {
6408        return Ok(None);
6409    };
6410    let Some((right_bytes, right_offsets)) = right_key.as_utf8_contiguous() else {
6411        return Ok(None);
6412    };
6413    let left_len = left_offsets.len().saturating_sub(1);
6414    let right_len = right_offsets.len().saturating_sub(1);
6415    if left_len == 0 || right_len == 0 {
6416        return Ok(None);
6417    }
6418
6419    let Some(domain) = fixed_decimal_utf8_domain(right_bytes, right_offsets) else {
6420        return Ok(None);
6421    };
6422
6423    let mut counts = vec![0usize; right_len];
6424    let mut left_buckets = Vec::<usize>::with_capacity(left_len);
6425    for left_pos in 0..left_len {
6426        let span = utf8_span(left_bytes, left_offsets, left_pos);
6427        let Some(bucket) = fixed_decimal_utf8_bucket(span, &domain) else {
6428            return Ok(None);
6429        };
6430        counts[bucket] = counts[bucket].checked_add(1).ok_or_else(|| {
6431            JoinError::Frame(FrameError::CompatibilityRejected(
6432                "merge output row count overflowed".to_owned(),
6433            ))
6434        })?;
6435        left_buckets.push(bucket);
6436    }
6437    if counts.contains(&0) {
6438        return Ok(None);
6439    }
6440
6441    let mut offsets = Vec::with_capacity(right_len + 1);
6442    offsets.push(0usize);
6443    for &count in &counts {
6444        offsets.push(offsets.last().copied().unwrap_or(0) + count);
6445    }
6446    let output_len = offsets[right_len];
6447    let mut left_positions = vec![0usize; output_len];
6448    let mut cursor = offsets[..right_len].to_vec();
6449    for (left_pos, &bucket) in left_buckets.iter().enumerate() {
6450        let out = cursor[bucket];
6451        left_positions[out] = left_pos;
6452        cursor[bucket] += 1;
6453    }
6454
6455    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
6456    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
6457    let shared_key_names = [left_on[0]].into_iter().collect::<HashSet<&str>>();
6458    let overlapping_names =
6459        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
6460    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
6461
6462    let mut specs = Vec::<(String, FixedDecimalUtf8OuterLane<'_>)>::new();
6463    for name in left.column_names() {
6464        let col = left
6465            .columns()
6466            .get(name)
6467            .expect("left column listed in column_names must exist");
6468        let lane = if name.as_str() == left_on[0] {
6469            FixedDecimalUtf8OuterLane::SharedKey
6470        } else if let Some(values) = col.as_f64_slice() {
6471            FixedDecimalUtf8OuterLane::LeftF64(values)
6472        } else if let Some(values) = col.as_i64_slice() {
6473            FixedDecimalUtf8OuterLane::LeftI64(values)
6474        } else {
6475            return Ok(None);
6476        };
6477        let out_name = if name.as_str() == left_on[0] {
6478            name.clone()
6479        } else if right_col_names.contains(name) {
6480            apply_merge_suffix(name, suffixes.left.as_deref())
6481        } else {
6482            name.clone()
6483        };
6484        specs.push((out_name, lane));
6485    }
6486    for name in right.column_names() {
6487        if name.as_str() == right_on[0] {
6488            continue;
6489        }
6490        let col = right
6491            .columns()
6492            .get(name)
6493            .expect("right column listed in column_names must exist");
6494        let lane = if let Some(values) = col.as_f64_slice() {
6495            FixedDecimalUtf8OuterLane::RightF64(values)
6496        } else if let Some(values) = col.as_i64_slice() {
6497            FixedDecimalUtf8OuterLane::RightI64(values)
6498        } else {
6499            return Ok(None);
6500        };
6501        let out_name = if left_col_names.contains(name) {
6502            apply_merge_suffix(name, suffixes.right.as_deref())
6503        } else {
6504            name.clone()
6505        };
6506        specs.push((out_name, lane));
6507    }
6508
6509    let run_lens: Arc<[usize]> = Arc::from(counts.clone());
6510    let index = Index::new_known_unique_int64_unit_range(0, output_len);
6511    let mut columns = ColumnStore::new();
6512    let mut column_order = Vec::with_capacity(specs.len());
6513    for (name, lane) in specs {
6514        let column = match lane {
6515            FixedDecimalUtf8OuterLane::SharedKey => {
6516                let row_width = domain.row_width();
6517                let mut bytes = Vec::with_capacity(output_len.saturating_mul(row_width));
6518                let mut out_offsets = Vec::with_capacity(output_len + 1);
6519                out_offsets.push(0);
6520                for (bucket, &count) in counts.iter().enumerate() {
6521                    let span = utf8_span(right_bytes, right_offsets, bucket);
6522                    for _ in 0..count {
6523                        bytes.extend_from_slice(span);
6524                        out_offsets.push(bytes.len());
6525                    }
6526                }
6527                Column::from_utf8_contiguous(bytes, out_offsets)
6528            }
6529            FixedDecimalUtf8OuterLane::LeftF64(values) => {
6530                let data = left_positions.iter().map(|&pos| values[pos]).collect();
6531                Column::from_f64_values_all_valid_unchecked(data)
6532            }
6533            FixedDecimalUtf8OuterLane::RightF64(values) => {
6534                let run_values = (0..right_len).map(|bucket| values[bucket]).collect();
6535                Column::from_f64_repeat_values_run_lengths(run_values, Arc::clone(&run_lens))
6536            }
6537            FixedDecimalUtf8OuterLane::LeftI64(values) => {
6538                let data = left_positions.iter().map(|&pos| values[pos]).collect();
6539                Column::from_i64_values(data)
6540            }
6541            FixedDecimalUtf8OuterLane::RightI64(values) => {
6542                let run_values = (0..right_len).map(|bucket| values[bucket]).collect();
6543                Column::from_i64_repeat_values_run_lengths(run_values, Arc::clone(&run_lens))
6544            }
6545        };
6546        debug_assert_eq!(column.len(), output_len);
6547        insert_merged_output_column(&mut columns, &mut column_order, name, column)?;
6548    }
6549
6550    Ok(Some(MergedDataFrame {
6551        index,
6552        columns,
6553        column_order,
6554    }))
6555}
6556
6557fn build_single_key_inner_merge_output(
6558    left: &fp_frame::DataFrame,
6559    right: &fp_frame::DataFrame,
6560    left_on: &[&str],
6561    right_on: &[&str],
6562    left_positions: &[usize],
6563    right_positions: &[usize],
6564    suffixes: &ResolvedMergeSuffixes,
6565) -> Result<MergedDataFrame, JoinError> {
6566    build_single_key_inner_merge_output_with_selections(
6567        left,
6568        right,
6569        left_on,
6570        right_on,
6571        PositionSelection::Positions(left_positions),
6572        PositionSelection::Positions(right_positions),
6573        suffixes,
6574    )
6575}
6576
6577fn build_single_key_inner_contiguous_no_overlap_output(
6578    left: &fp_frame::DataFrame,
6579    right: &fp_frame::DataFrame,
6580    left_on: &[&str],
6581    right_on: &[&str],
6582    left_positions: PositionSelection<'_>,
6583    right_positions: PositionSelection<'_>,
6584) -> Option<MergedDataFrame> {
6585    let (
6586        PositionSelection::ContiguousRange {
6587            start: left_start,
6588            len,
6589        },
6590        PositionSelection::ContiguousRange {
6591            start: right_start,
6592            len: right_len,
6593        },
6594    ) = (left_positions, right_positions)
6595    else {
6596        return None;
6597    };
6598    if left_on[0] != right_on[0] || len != right_len {
6599        return None;
6600    }
6601
6602    let left_col_names = left.column_names();
6603    let right_col_names = right.column_names();
6604    if left_col_names.iter().any(|left_name| {
6605        left_name.as_str() != left_on[0]
6606            && right_col_names
6607                .iter()
6608                .any(|right_name| right_name.as_str() == left_name.as_str())
6609    }) {
6610        return None;
6611    }
6612
6613    let mut columns = ColumnStore::new();
6614    let mut column_order =
6615        Vec::with_capacity(left_col_names.len() + right_col_names.len().saturating_sub(1));
6616    let left_selection = PositionSelection::ContiguousRange {
6617        start: left_start,
6618        len,
6619    };
6620    let right_selection = PositionSelection::ContiguousRange {
6621        start: right_start,
6622        len,
6623    };
6624
6625    for name in left_col_names.iter().copied() {
6626        let column = left
6627            .columns()
6628            .get(name)
6629            .expect("left column listed in column_names must exist");
6630        let output_column = if name.as_str() == left_on[0] {
6631            take_lower_hex_sequence_range(column, left_start, len)
6632                .unwrap_or_else(|| take_position_selection_typed(column, left_selection))
6633        } else {
6634            take_position_selection_typed(column, left_selection)
6635        };
6636        column_order.push(name.clone());
6637        let previous = columns.insert(name.clone(), output_column);
6638        debug_assert!(previous.is_none());
6639    }
6640    for name in right_col_names.iter().copied() {
6641        if name.as_str() == right_on[0] {
6642            continue;
6643        }
6644        let column = right
6645            .columns()
6646            .get(name)
6647            .expect("right column listed in column_names must exist");
6648        column_order.push(name.clone());
6649        let previous = columns.insert(
6650            name.clone(),
6651            take_position_selection_typed(column, right_selection),
6652        );
6653        debug_assert!(previous.is_none());
6654    }
6655
6656    Some(MergedDataFrame {
6657        index: Index::new_known_unique_int64_unit_range(0, len),
6658        columns,
6659        column_order,
6660    })
6661}
6662
6663fn build_single_key_inner_merge_output_with_selections(
6664    left: &fp_frame::DataFrame,
6665    right: &fp_frame::DataFrame,
6666    left_on: &[&str],
6667    right_on: &[&str],
6668    left_positions: PositionSelection<'_>,
6669    right_positions: PositionSelection<'_>,
6670    suffixes: &ResolvedMergeSuffixes,
6671) -> Result<MergedDataFrame, JoinError> {
6672    debug_assert_eq!(left_on.len(), 1);
6673    debug_assert_eq!(right_on.len(), 1);
6674    debug_assert_eq!(left_positions.len(), right_positions.len());
6675
6676    if let Some(merged) = build_single_key_inner_contiguous_no_overlap_output(
6677        left,
6678        right,
6679        left_on,
6680        right_on,
6681        left_positions,
6682        right_positions,
6683    ) {
6684        return Ok(merged);
6685    }
6686
6687    let n = left_positions.len();
6688    // Lazy unit-range output index (see build_single_key_dense_i64 site).
6689    let index = Index::new_known_unique_int64_unit_range(0, n);
6690
6691    let left_col_names = left.column_names();
6692    let right_col_names = right.column_names();
6693    let use_linear_name_lookup =
6694        left_col_names.len() + right_col_names.len() <= SMALL_SCHEMA_LINEAR_COLUMN_LOOKUP_LIMIT;
6695    let left_hashed_col_names = (!use_linear_name_lookup).then(|| {
6696        left_col_names
6697            .iter()
6698            .map(|name| name.as_str())
6699            .collect::<HashSet<_>>()
6700    });
6701    let right_hashed_col_names = (!use_linear_name_lookup).then(|| {
6702        right_col_names
6703            .iter()
6704            .map(|name| name.as_str())
6705            .collect::<HashSet<_>>()
6706    });
6707    let shared_key_name = (left_on[0] == right_on[0]).then_some(left_on[0]);
6708    let mut overlapping_names = left_col_names
6709        .iter()
6710        .filter_map(|name| {
6711            let name = name.as_str();
6712            (Some(name) != shared_key_name
6713                && column_name_lookup_contains(
6714                    &right_col_names,
6715                    right_hashed_col_names.as_ref(),
6716                    name,
6717                ))
6718            .then(|| name.to_owned())
6719        })
6720        .collect::<Vec<_>>();
6721    overlapping_names.sort();
6722    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
6723
6724    // Resolve output column specs in order (name/suffix resolution is cheap),
6725    // then gather them. Each output column is an independent typed gather over
6726    // the position vector, so wide/large outputs build every column in parallel
6727    // (one column per worker) — the same disjoint-fill pattern as the dense-i64
6728    // fused builder (br-frankenpandas-j3jnd). Bit-identical to the serial loop:
6729    // identical per-column take_positions_typed result, inserted in spec order.
6730    let mut specs: Vec<(String, &Column, PositionSelection<'_>)> = Vec::new();
6731    for name in left_col_names.iter().copied() {
6732        let col = left
6733            .columns()
6734            .get(name)
6735            .expect("left column listed in column_names must exist");
6736        let out_name = if name.as_str() == left_on[0] {
6737            name.clone()
6738        } else if column_name_lookup_contains(
6739            &right_col_names,
6740            right_hashed_col_names.as_ref(),
6741            name.as_str(),
6742        ) {
6743            apply_merge_suffix(name, suffixes.left.as_deref())
6744        } else {
6745            name.clone()
6746        };
6747        specs.push((out_name, col, left_positions));
6748    }
6749    for name in right_col_names.iter().copied() {
6750        if name.as_str() == right_on[0] && shared_key_name == Some(name.as_str()) {
6751            continue;
6752        }
6753        let col = right
6754            .columns()
6755            .get(name)
6756            .expect("right column listed in column_names must exist");
6757        let out_name = if column_name_lookup_contains(
6758            &left_col_names,
6759            left_hashed_col_names.as_ref(),
6760            name.as_str(),
6761        ) {
6762            apply_merge_suffix(name, suffixes.right.as_deref())
6763        } else {
6764            name.clone()
6765        };
6766        specs.push((out_name, col, right_positions));
6767    }
6768
6769    let built: Vec<Column> = {
6770        let thread_count = join_parallel_thread_count();
6771        if specs.len() > 1 && n >= DENSE_I64_INNER_PARALLEL_MIN_VALUES && thread_count > 1 {
6772            let mut slots: Vec<Option<Column>> = (0..specs.len()).map(|_| None).collect();
6773            let chunk = specs.len().div_ceil(thread_count).max(1);
6774            std::thread::scope(|scope| {
6775                for (spec_chunk, slot_chunk) in specs.chunks(chunk).zip(slots.chunks_mut(chunk)) {
6776                    scope.spawn(move || {
6777                        for ((_, col, positions), slot) in spec_chunk.iter().zip(slot_chunk) {
6778                            *slot = Some(take_position_selection_typed(col, *positions));
6779                        }
6780                    });
6781                }
6782            });
6783            slots
6784                .into_iter()
6785                .map(|c| c.expect("every spec column must be built"))
6786                .collect()
6787        } else {
6788            specs
6789                .iter()
6790                .map(|(_, col, positions)| take_position_selection_typed(col, *positions))
6791                .collect()
6792        }
6793    };
6794
6795    let mut columns = ColumnStore::new();
6796    let mut column_order: Vec<String> = Vec::with_capacity(specs.len());
6797    for ((out_name, _, _), column) in specs.into_iter().zip(built) {
6798        insert_merged_output_column(&mut columns, &mut column_order, out_name, column)?;
6799    }
6800
6801    Ok(MergedDataFrame {
6802        index,
6803        columns,
6804        column_order,
6805    })
6806}
6807
6808fn build_single_key_dense_left_merge_output(
6809    left: &fp_frame::DataFrame,
6810    right: &fp_frame::DataFrame,
6811    left_on: &[&str],
6812    right_on: &[&str],
6813    left_positions: &[Option<usize>],
6814    right_positions: &[Option<usize>],
6815    suffixes: &ResolvedMergeSuffixes,
6816) -> Result<MergedDataFrame, JoinError> {
6817    debug_assert_eq!(left_on.len(), 1);
6818    debug_assert_eq!(right_on.len(), 1);
6819    debug_assert_eq!(left_positions.len(), right_positions.len());
6820
6821    let n = left_positions.len();
6822    // Lazy unit-range output index (see build_single_key_dense_i64 site).
6823    let index = Index::new_known_unique_int64_unit_range(0, n);
6824    let mut columns = ColumnStore::new();
6825    let mut column_order: Vec<String> = Vec::new();
6826
6827    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
6828    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
6829    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
6830    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
6831    let shared_key_names = if left_on[0] == right_on[0] {
6832        [left_on[0]].into_iter().collect::<HashSet<&str>>()
6833    } else {
6834        HashSet::new()
6835    };
6836    let overlapping_names =
6837        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
6838    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
6839    for name in left.column_names() {
6840        let col = left
6841            .columns()
6842            .get(name)
6843            .expect("left column listed in column_names must exist");
6844        let out_name = if left_key_name_set.contains(name.as_str()) {
6845            name.clone()
6846        } else if right_col_names.contains(name) {
6847            apply_merge_suffix(name, suffixes.left.as_deref())
6848        } else {
6849            name.clone()
6850        };
6851        let output = col.reindex_by_positions(left_positions)?;
6852        insert_merged_output_column(&mut columns, &mut column_order, out_name, output)?;
6853    }
6854
6855    for name in right.column_names() {
6856        let col = right
6857            .columns()
6858            .get(name)
6859            .expect("right column listed in column_names must exist");
6860        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
6861            continue;
6862        }
6863
6864        let reindexed = reindex_join_column_with_invented_gap(col, right_positions)?;
6865        let out_name = if left_col_names.contains(name) {
6866            apply_merge_suffix(name, suffixes.right.as_deref())
6867        } else {
6868            name.clone()
6869        };
6870        insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
6871    }
6872
6873    Ok(MergedDataFrame {
6874        index,
6875        columns,
6876        column_order,
6877    })
6878}
6879
6880fn build_single_key_ordered_unique_left_merge_output(
6881    left: &fp_frame::DataFrame,
6882    right: &fp_frame::DataFrame,
6883    left_on: &[&str],
6884    right_on: &[&str],
6885    right_positions: &[Option<usize>],
6886    suffixes: &ResolvedMergeSuffixes,
6887) -> Result<MergedDataFrame, JoinError> {
6888    debug_assert_eq!(left_on.len(), 1);
6889    debug_assert_eq!(right_on.len(), 1);
6890    debug_assert_eq!(left.len(), right_positions.len());
6891
6892    let n = left.len();
6893    // Lazy unit-range output index (see build_single_key_dense_i64 site).
6894    let index = Index::new_known_unique_int64_unit_range(0, n);
6895    let mut columns = ColumnStore::new();
6896    let mut column_order: Vec<String> = Vec::new();
6897    let mut identity_positions = None;
6898
6899    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
6900    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
6901    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
6902    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
6903    let shared_key_names = if left_on[0] == right_on[0] {
6904        [left_on[0]].into_iter().collect::<HashSet<&str>>()
6905    } else {
6906        HashSet::new()
6907    };
6908    let overlapping_names =
6909        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
6910    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
6911    // Building the shared Utf8 gather plan is O(output_rows): it scans every
6912    // optional position and, for a non-contiguous match pattern, allocates an
6913    // additional position tape plus validity bitmap. Most ordered Int64 joins
6914    // have only numeric payloads, where every column ignores that plan and uses
6915    // its typed reindexer. Defer the work until the first Utf8 payload actually
6916    // asks for it; subsequent Utf8 columns still share the single immutable
6917    // plan exactly as before.
6918    let right_utf8_plan: OnceLock<Option<SharedOptionalUtf8GatherPlan>> = OnceLock::new();
6919
6920    for name in left.column_names() {
6921        let col = left
6922            .columns()
6923            .get(name)
6924            .expect("left column listed in column_names must exist");
6925        let out_name = if left_key_name_set.contains(name.as_str()) {
6926            name.clone()
6927        } else if right_col_names.contains(name) {
6928            apply_merge_suffix(name, suffixes.left.as_deref())
6929        } else {
6930            name.clone()
6931        };
6932        let output = identity_merge_column(col, n, &mut identity_positions);
6933        insert_merged_output_column(&mut columns, &mut column_order, out_name, output)?;
6934    }
6935
6936    for name in right.column_names() {
6937        let col = right
6938            .columns()
6939            .get(name)
6940            .expect("right column listed in column_names must exist");
6941        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
6942            continue;
6943        }
6944
6945        let reindexed = if col.dtype() == DType::Utf8 {
6946            let utf8_plan = right_utf8_plan
6947                .get_or_init(|| shared_optional_utf8_gather_plan(right_positions, right.len()))
6948                .as_ref();
6949            reindex_with_shared_utf8_plan(col, right_positions, utf8_plan)?
6950        } else {
6951            reindex_join_column_with_invented_gap(col, right_positions)?
6952        };
6953        let out_name = if left_col_names.contains(name) {
6954            apply_merge_suffix(name, suffixes.right.as_deref())
6955        } else {
6956            name.clone()
6957        };
6958        insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
6959    }
6960
6961    Ok(MergedDataFrame {
6962        index,
6963        columns,
6964        column_order,
6965    })
6966}
6967
6968fn build_single_key_ordered_unique_right_merge_output(
6969    left: &fp_frame::DataFrame,
6970    right: &fp_frame::DataFrame,
6971    left_on: &[&str],
6972    right_on: &[&str],
6973    left_positions: &[Option<usize>],
6974    suffixes: &ResolvedMergeSuffixes,
6975) -> Result<MergedDataFrame, JoinError> {
6976    debug_assert_eq!(left_on.len(), 1);
6977    debug_assert_eq!(right_on.len(), 1);
6978    debug_assert_eq!(right.len(), left_positions.len());
6979
6980    let n = right.len();
6981    // Lazy unit-range output index (see build_single_key_dense_i64 site).
6982    let index = Index::new_known_unique_int64_unit_range(0, n);
6983    let mut columns = ColumnStore::new();
6984    let mut column_order: Vec<String> = Vec::new();
6985    let mut identity_positions = None;
6986
6987    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
6988    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
6989    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
6990    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
6991    let shared_key_names = if left_on[0] == right_on[0] {
6992        [left_on[0]].into_iter().collect::<HashSet<&str>>()
6993    } else {
6994        HashSet::new()
6995    };
6996    let overlapping_names =
6997        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
6998    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
6999
7000    for name in left.column_names() {
7001        let col = left
7002            .columns()
7003            .get(name)
7004            .expect("left column listed in column_names must exist");
7005        let out_name = if left_key_name_set.contains(name.as_str()) {
7006            name.clone()
7007        } else if right_col_names.contains(name) {
7008            apply_merge_suffix(name, suffixes.left.as_deref())
7009        } else {
7010            name.clone()
7011        };
7012        let output = if left_key_name_set.contains(name.as_str())
7013            && shared_key_names.contains(name.as_str())
7014        {
7015            let right_key_col = right
7016                .columns()
7017                .get(right_on[0])
7018                .expect("right key column must exist");
7019            identity_merge_column(right_key_col, n, &mut identity_positions)
7020        } else {
7021            reindex_join_column_with_invented_gap(col, left_positions)?
7022        };
7023        insert_merged_output_column(&mut columns, &mut column_order, out_name, output)?;
7024    }
7025
7026    for name in right.column_names() {
7027        let col = right
7028            .columns()
7029            .get(name)
7030            .expect("right column listed in column_names must exist");
7031        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
7032            continue;
7033        }
7034
7035        let reindexed = identity_merge_column(col, n, &mut identity_positions);
7036        let out_name = if left_col_names.contains(name) {
7037            apply_merge_suffix(name, suffixes.right.as_deref())
7038        } else {
7039            name.clone()
7040        };
7041        insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
7042    }
7043
7044    Ok(MergedDataFrame {
7045        index,
7046        columns,
7047        column_order,
7048    })
7049}
7050
7051fn build_single_key_dense_right_merge_output(
7052    left: &fp_frame::DataFrame,
7053    right: &fp_frame::DataFrame,
7054    left_on: &[&str],
7055    right_on: &[&str],
7056    left_positions: &[Option<usize>],
7057    right_positions: &[Option<usize>],
7058    suffixes: &ResolvedMergeSuffixes,
7059) -> Result<MergedDataFrame, JoinError> {
7060    debug_assert_eq!(left_on.len(), 1);
7061    debug_assert_eq!(right_on.len(), 1);
7062    debug_assert_eq!(left_positions.len(), right_positions.len());
7063
7064    let n = left_positions.len();
7065    // Lazy unit-range output index (see build_single_key_dense_i64 site).
7066    let index = Index::new_known_unique_int64_unit_range(0, n);
7067    let mut columns = ColumnStore::new();
7068    let mut column_order: Vec<String> = Vec::new();
7069
7070    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
7071    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
7072    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
7073    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
7074    let shared_key_names = if left_on[0] == right_on[0] {
7075        [left_on[0]].into_iter().collect::<HashSet<&str>>()
7076    } else {
7077        HashSet::new()
7078    };
7079    let overlapping_names =
7080        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
7081    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
7082
7083    for name in left.column_names() {
7084        let col = left
7085            .columns()
7086            .get(name)
7087            .expect("left column listed in column_names must exist");
7088        let out_name = if left_key_name_set.contains(name.as_str()) {
7089            name.clone()
7090        } else if right_col_names.contains(name) {
7091            apply_merge_suffix(name, suffixes.left.as_deref())
7092        } else {
7093            name.clone()
7094        };
7095        let output = if left_key_name_set.contains(name.as_str())
7096            && shared_key_names.contains(name.as_str())
7097        {
7098            let right_key_col = right
7099                .columns()
7100                .get(right_on[0])
7101                .expect("right key column must exist");
7102            right_key_col.reindex_by_positions(right_positions)?
7103        } else {
7104            reindex_join_column_with_invented_gap(col, left_positions)?
7105        };
7106        insert_merged_output_column(&mut columns, &mut column_order, out_name, output)?;
7107    }
7108
7109    for name in right.column_names() {
7110        let col = right
7111            .columns()
7112            .get(name)
7113            .expect("right column listed in column_names must exist");
7114        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
7115            continue;
7116        }
7117
7118        let reindexed = col.reindex_by_positions(right_positions)?;
7119        let out_name = if left_col_names.contains(name) {
7120            apply_merge_suffix(name, suffixes.right.as_deref())
7121        } else {
7122            name.clone()
7123        };
7124        insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
7125    }
7126
7127    Ok(MergedDataFrame {
7128        index,
7129        columns,
7130        column_order,
7131    })
7132}
7133
7134fn build_single_key_ordered_unique_outer_merge_output(
7135    left: &fp_frame::DataFrame,
7136    right: &fp_frame::DataFrame,
7137    left_on: &[&str],
7138    right_on: &[&str],
7139    left_positions: &[Option<usize>],
7140    right_positions: &[Option<usize>],
7141    suffixes: &ResolvedMergeSuffixes,
7142) -> Result<MergedDataFrame, JoinError> {
7143    debug_assert_eq!(left_on.len(), 1);
7144    debug_assert_eq!(right_on.len(), 1);
7145    debug_assert_eq!(left_positions.len(), right_positions.len());
7146
7147    let n = left_positions.len();
7148    // Lazy unit-range output index (see build_single_key_dense_i64 site).
7149    let index = Index::new_known_unique_int64_unit_range(0, n);
7150    let mut columns = ColumnStore::new();
7151    let mut column_order: Vec<String> = Vec::new();
7152
7153    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
7154    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
7155    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
7156    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
7157
7158    let mut shared_name_positions = HashMap::<&str, (usize, usize)>::new();
7159    if left_on[0] == right_on[0] {
7160        shared_name_positions.insert(left_on[0], (0, 0));
7161    }
7162    let shared_key_names = shared_name_positions
7163        .keys()
7164        .copied()
7165        .collect::<HashSet<&str>>();
7166    let overlapping_names =
7167        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
7168    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
7169
7170    let mut left_take_positions = Vec::with_capacity(n);
7171    let mut right_take_positions = Vec::with_capacity(n);
7172    let mut all_positions_present = true;
7173    for (left_pos, right_pos) in left_positions.iter().zip(right_positions.iter()) {
7174        let (Some(left_pos), Some(right_pos)) = (*left_pos, *right_pos) else {
7175            all_positions_present = false;
7176            break;
7177        };
7178        left_take_positions.push(left_pos);
7179        right_take_positions.push(right_pos);
7180    }
7181    let all_present_take_positions =
7182        all_positions_present.then_some((left_take_positions, right_take_positions));
7183    let all_present_left_positions = all_present_take_positions
7184        .as_ref()
7185        .map(|(positions, _)| positions.as_slice());
7186    let all_present_right_positions = all_present_take_positions
7187        .as_ref()
7188        .map(|(_, positions)| positions.as_slice());
7189    let left_has_utf8 = left
7190        .columns()
7191        .values()
7192        .any(|column| column.dtype() == DType::Utf8);
7193    let right_has_utf8 = right
7194        .columns()
7195        .values()
7196        .any(|column| column.dtype() == DType::Utf8);
7197    let left_utf8_plan = (left_has_utf8 && all_present_left_positions.is_none())
7198        .then(|| shared_optional_utf8_gather_plan(left_positions, left.len()))
7199        .flatten();
7200    let right_utf8_plan = (right_has_utf8 && all_present_right_positions.is_none())
7201        .then(|| shared_optional_utf8_gather_plan(right_positions, right.len()))
7202        .flatten();
7203
7204    // Per-column output build is INDEPENDENT across columns and was the serial
7205    // hot phase of the join (~10.5ms of str_outer_join's reindex assembly at
7206    // n=150000, 12 Utf8 value columns). Build an ordered list of column specs
7207    // (cheap), compute each column — the O(output) `reindex_join_column_with_invented_gap`
7208    // gather / take / key-coalesce — across workers, then insert in the SAME
7209    // first-seen order (br-frankenpandas-uza04.102). Byte-identical: each output
7210    // column is the same values in the same row order, inserted in the same
7211    // left-then-right column order, so `columns`/`column_order` are unchanged.
7212    enum ColBuild<'a> {
7213        KeyCoalesce {
7214            left_key_col: &'a Column,
7215            right_key_col: &'a Column,
7216        },
7217        Reindex {
7218            col: &'a Column,
7219            positions: &'a [Option<usize>],
7220            utf8_plan: Option<&'a SharedOptionalUtf8GatherPlan>,
7221        },
7222        Take {
7223            col: &'a Column,
7224            present: &'a [usize],
7225        },
7226    }
7227    let mut jobs: Vec<(String, ColBuild<'_>)> = Vec::new();
7228    for name in left.column_names() {
7229        let col = left
7230            .columns()
7231            .get(name)
7232            .expect("left column listed in column_names must exist");
7233        if left_key_name_set.contains(name.as_str()) {
7234            if let Some((left_key_idx, right_key_idx)) = shared_name_positions.get(name.as_str()) {
7235                let left_key_col = left
7236                    .columns()
7237                    .get(left_on[*left_key_idx])
7238                    .expect("left key column must exist");
7239                let spec = if let Some(positions) = all_present_left_positions {
7240                    ColBuild::Take {
7241                        col: left_key_col,
7242                        present: positions,
7243                    }
7244                } else {
7245                    let right_key_col = right
7246                        .columns()
7247                        .get(right_on[*right_key_idx])
7248                        .expect("right key column must exist");
7249                    ColBuild::KeyCoalesce {
7250                        left_key_col,
7251                        right_key_col,
7252                    }
7253                };
7254                jobs.push((name.clone(), spec));
7255            } else {
7256                let spec = if let Some(positions) = all_present_left_positions {
7257                    ColBuild::Take {
7258                        col,
7259                        present: positions,
7260                    }
7261                } else {
7262                    ColBuild::Reindex {
7263                        col,
7264                        positions: left_positions,
7265                        utf8_plan: left_utf8_plan.as_ref(),
7266                    }
7267                };
7268                jobs.push((name.clone(), spec));
7269            }
7270            continue;
7271        }
7272        let spec = if let Some(positions) = all_present_left_positions {
7273            ColBuild::Take {
7274                col,
7275                present: positions,
7276            }
7277        } else {
7278            ColBuild::Reindex {
7279                col,
7280                positions: left_positions,
7281                utf8_plan: left_utf8_plan.as_ref(),
7282            }
7283        };
7284        let out_name = if right_col_names.contains(name) {
7285            apply_merge_suffix(name, suffixes.left.as_deref())
7286        } else {
7287            name.clone()
7288        };
7289        jobs.push((out_name, spec));
7290    }
7291    for name in right.column_names() {
7292        let col = right
7293            .columns()
7294            .get(name)
7295            .expect("right column listed in column_names must exist");
7296        if right_key_name_set.contains(name.as_str())
7297            && shared_name_positions.contains_key(name.as_str())
7298        {
7299            continue;
7300        }
7301        let spec = if let Some(positions) = all_present_right_positions {
7302            ColBuild::Take {
7303                col,
7304                present: positions,
7305            }
7306        } else {
7307            ColBuild::Reindex {
7308                col,
7309                positions: right_positions,
7310                utf8_plan: right_utf8_plan.as_ref(),
7311            }
7312        };
7313        let out_name = if left_col_names.contains(name) {
7314            apply_merge_suffix(name, suffixes.right.as_deref())
7315        } else {
7316            name.clone()
7317        };
7318        jobs.push((out_name, spec));
7319    }
7320
7321    let compute = |spec: &ColBuild<'_>| -> Result<Column, JoinError> {
7322        match spec {
7323            ColBuild::KeyCoalesce {
7324                left_key_col,
7325                right_key_col,
7326            } => {
7327                if let Some(column) = coalesce_temporal_i64_key_column(
7328                    left_key_col,
7329                    right_key_col,
7330                    left_positions,
7331                    right_positions,
7332                ) {
7333                    return Ok(column);
7334                }
7335                if let (Some(left_keys), Some(right_keys)) =
7336                    (left_key_col.as_i64_slice(), right_key_col.as_i64_slice())
7337                {
7338                    let mut data = Vec::with_capacity(left_positions.len());
7339                    let mut all_positions_valid = true;
7340                    for (left_pos, right_pos) in left_positions.iter().zip(right_positions.iter()) {
7341                        match (*left_pos, *right_pos) {
7342                            (Some(pos), _) if pos < left_keys.len() => data.push(left_keys[pos]),
7343                            (None, Some(pos)) if pos < right_keys.len() => {
7344                                data.push(right_keys[pos])
7345                            }
7346                            _ => {
7347                                all_positions_valid = false;
7348                                break;
7349                            }
7350                        }
7351                    }
7352                    if all_positions_valid {
7353                        return Ok(Column::from_i64_values(data));
7354                    }
7355                }
7356
7357                let values = left_positions
7358                    .iter()
7359                    .zip(right_positions.iter())
7360                    .map(|(left_pos, right_pos)| match (left_pos, right_pos) {
7361                        (Some(pos), _) => left_key_col.values()[*pos].clone(),
7362                        (None, Some(pos)) => right_key_col.values()[*pos].clone(),
7363                        (None, None) => fp_types::Scalar::Null(fp_types::NullKind::Null),
7364                    })
7365                    .collect::<Vec<_>>();
7366                Ok(Column::from_values(values)?)
7367            }
7368            ColBuild::Reindex {
7369                col,
7370                positions,
7371                utf8_plan,
7372            } => reindex_outer_with_shared_utf8_plan(col, positions, *utf8_plan),
7373            ColBuild::Take { col, present } => Ok(take_positions_typed(col, present)),
7374        }
7375    };
7376
7377    let worker_count = fp_columnar::cached_available_parallelism()
7378        .min(64)
7379        .min(jobs.len().max(1));
7380    let computed: Vec<Result<Column, JoinError>> = if worker_count >= 2 && jobs.len() >= 2 {
7381        let next = std::sync::atomic::AtomicUsize::new(0);
7382        let jobs_ref = &jobs;
7383        let compute_ref = &compute;
7384        let mut slots: Vec<Option<Result<Column, JoinError>>> =
7385            (0..jobs.len()).map(|_| None).collect();
7386        let parts = std::thread::scope(|scope| {
7387            let mut handles = Vec::with_capacity(worker_count);
7388            for _ in 0..worker_count {
7389                let next = &next;
7390                handles.push(scope.spawn(move || {
7391                    let mut out: Vec<(usize, Result<Column, JoinError>)> = Vec::new();
7392                    loop {
7393                        let i = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7394                        if i >= jobs_ref.len() {
7395                            break;
7396                        }
7397                        out.push((i, compute_ref(&jobs_ref[i].1)));
7398                    }
7399                    out
7400                }));
7401            }
7402            handles
7403                .into_iter()
7404                .map(|h| h.join().expect("join assembly worker panicked"))
7405                .collect::<Vec<_>>()
7406        });
7407        for part in parts {
7408            for (i, r) in part {
7409                slots[i] = Some(r);
7410            }
7411        }
7412        slots
7413            .into_iter()
7414            .map(|s| s.expect("every output column computed"))
7415            .collect()
7416    } else {
7417        jobs.iter().map(|(_, spec)| compute(spec)).collect()
7418    };
7419
7420    for ((out_name, _), col_res) in jobs.into_iter().zip(computed) {
7421        insert_merged_output_column(&mut columns, &mut column_order, out_name, col_res?)?;
7422    }
7423
7424    Ok(MergedDataFrame {
7425        index,
7426        columns,
7427        column_order,
7428    })
7429}
7430
7431fn build_single_key_ordered_identity_inner_merge_output(
7432    left: &fp_frame::DataFrame,
7433    right: &fp_frame::DataFrame,
7434    left_on: &[&str],
7435    right_on: &[&str],
7436    suffixes: &ResolvedMergeSuffixes,
7437) -> Result<MergedDataFrame, JoinError> {
7438    debug_assert_eq!(left_on.len(), 1);
7439    debug_assert_eq!(right_on.len(), 1);
7440    debug_assert_eq!(left_on[0], right_on[0]);
7441
7442    let n = left.len();
7443    debug_assert_eq!(n, right.len());
7444    // Lazy unit-range output index (see build_single_key_dense_i64 site).
7445    let index = Index::new_known_unique_int64_unit_range(0, n);
7446    let mut columns = ColumnStore::new();
7447    let mut column_order: Vec<String> = Vec::new();
7448    let mut identity_positions = None;
7449
7450    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
7451    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
7452    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
7453    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
7454    let shared_key_names = left_on.iter().copied().collect::<HashSet<&str>>();
7455    let overlapping_names =
7456        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
7457    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
7458
7459    for name in left.column_names() {
7460        let col = left
7461            .columns()
7462            .get(name)
7463            .expect("left column listed in column_names must exist");
7464        let out_name = if left_key_name_set.contains(name.as_str()) {
7465            name.clone()
7466        } else if right_col_names.contains(name) {
7467            apply_merge_suffix(name, suffixes.left.as_deref())
7468        } else {
7469            name.clone()
7470        };
7471        let output = identity_merge_column(col, n, &mut identity_positions);
7472        insert_merged_output_column(&mut columns, &mut column_order, out_name, output)?;
7473    }
7474
7475    for name in right.column_names() {
7476        if right_key_name_set.contains(name.as_str()) {
7477            continue;
7478        }
7479
7480        let col = right
7481            .columns()
7482            .get(name)
7483            .expect("right column listed in column_names must exist");
7484        let out_name = if left_col_names.contains(name) {
7485            apply_merge_suffix(name, suffixes.right.as_deref())
7486        } else {
7487            name.clone()
7488        };
7489        let output = identity_merge_column(col, n, &mut identity_positions);
7490        insert_merged_output_column(&mut columns, &mut column_order, out_name, output)?;
7491    }
7492
7493    Ok(MergedDataFrame {
7494        index,
7495        columns,
7496        column_order,
7497    })
7498}
7499
7500/// Hash-free inner-join position build for two all-valid, bounded-range Int64
7501/// key columns. Replaces the `FxHashMap<&JoinKeyComponent, _>` build+probe with
7502/// a counting-sort / CSR direct-address table indexed by `key - min`.
7503///
7504/// Bit-identical to the hash path's emitted `(left_pos, right_pos)` pairs: the
7505/// hash path buckets right positions in *insertion* order (ascending position),
7506/// and this CSR fill also writes right positions in ascending-position order,
7507/// so for every left row the matched right rows are emitted in the same order;
7508/// left rows are still probed in ascending order. All-valid Int64 keys map to
7509/// `Present(IndexLabel::Int64(v))` in the hash path, whose equality is plain
7510/// `i64 ==`, so membership/equality semantics are identical. A left key outside
7511/// the right key span matches nothing in either path. Returns `None` (caller
7512/// falls back to the hash path) for non-Int64, any-missing, or wide-span keys.
7513fn dense_int64_inner_positions(
7514    left_key: &Column,
7515    right_key: &Column,
7516) -> Option<(Vec<usize>, Vec<usize>)> {
7517    let left = left_key.as_i64_slice()?;
7518    let right = right_key.as_i64_slice()?;
7519    dense_i64_inner_positions_slices(left, right)
7520}
7521
7522/// Typed single-key INNER positions for all-valid temporal columns. Datetime64
7523/// and Timedelta64 both store exact nanoseconds in `i64`; matching those raw
7524/// values is identical to matching their same-variant `IndexLabel` wrappers.
7525///
7526/// The fast path requires equal temporal dtypes and rejects NaT explicitly.
7527/// Ordered inputs validate each newly reached value while intersecting, instead
7528/// of pre-scanning both slices for NaT and strict ordering. Nullable keys
7529/// therefore fall through to the Scalar oracle, preserving its Missing-to-
7530/// Missing join behavior. Output construction still gathers the original
7531/// temporal key column, so dtype and value representation are kept.
7532fn temporal_i64_inner_positions(
7533    left_key: &Column,
7534    right_key: &Column,
7535) -> Option<(Vec<usize>, Vec<usize>)> {
7536    if !left_key.validity().all() || !right_key.validity().all() {
7537        return None;
7538    }
7539
7540    let (left, right, nat) = match (left_key.dtype(), right_key.dtype()) {
7541        (DType::Datetime64 { tz: left_tz }, DType::Datetime64 { tz: right_tz })
7542            if left_tz == right_tz =>
7543        {
7544            (
7545                left_key.as_datetime64_slice()?,
7546                right_key.as_datetime64_slice()?,
7547                fp_types::Timestamp::NAT,
7548            )
7549        }
7550        (DType::Timedelta64, DType::Timedelta64) => (
7551            left_key.as_timedelta64_slice()?,
7552            right_key.as_timedelta64_slice()?,
7553            fp_types::Timedelta::NAT,
7554        ),
7555        _ => return None,
7556    };
7557    let mut left_positions = Vec::with_capacity(left.len().min(right.len()));
7558    let mut right_positions = Vec::with_capacity(left_positions.capacity());
7559    let (mut left_idx, mut right_idx) = (0usize, 0usize);
7560    let mut ordered = newly_reached_temporal_i64_value_is_strict(left, 0, nat)
7561        && newly_reached_temporal_i64_value_is_strict(right, 0, nat);
7562    while ordered && left_idx < left.len() && right_idx < right.len() {
7563        match left[left_idx].cmp(&right[right_idx]) {
7564            Ordering::Equal => {
7565                left_positions.push(left_idx);
7566                right_positions.push(right_idx);
7567                left_idx += 1;
7568                right_idx += 1;
7569                ordered = newly_reached_temporal_i64_value_is_strict(left, left_idx, nat)
7570                    && newly_reached_temporal_i64_value_is_strict(right, right_idx, nat);
7571            }
7572            Ordering::Less => {
7573                left_idx += 1;
7574                ordered = newly_reached_temporal_i64_value_is_strict(left, left_idx, nat);
7575            }
7576            Ordering::Greater => {
7577                right_idx += 1;
7578                ordered = newly_reached_temporal_i64_value_is_strict(right, right_idx, nat);
7579            }
7580        }
7581    }
7582    while ordered && left_idx < left.len() {
7583        left_idx += 1;
7584        ordered = newly_reached_temporal_i64_value_is_strict(left, left_idx, nat);
7585    }
7586    while ordered && right_idx < right.len() {
7587        right_idx += 1;
7588        ordered = newly_reached_temporal_i64_value_is_strict(right, right_idx, nat);
7589    }
7590    if ordered {
7591        return Some((left_positions, right_positions));
7592    }
7593
7594    if left.contains(&nat) || right.contains(&nat) {
7595        return None;
7596    }
7597
7598    dense_i64_inner_positions_slices(left, right)
7599        .or_else(|| Some(hash_i64_inner_positions_slices(left, right)))
7600}
7601
7602/// Typed single-key LEFT positions for all-valid temporal columns. The ordered
7603/// unique case uses a two-pointer match scan; remaining shapes hash the raw
7604/// nanoseconds. Both emit left-major rows and ascending right positions per
7605/// key, exactly matching the generic Scalar planner. Nullable keys and NaT
7606/// retain that planner's Missing-key behavior by declining this path.
7607fn temporal_i64_left_positions(
7608    left_key: &Column,
7609    right_key: &Column,
7610) -> Option<OptionalJoinPositions> {
7611    if !left_key.validity().all() || !right_key.validity().all() {
7612        return None;
7613    }
7614
7615    let (left, right, nat) = match (left_key.dtype(), right_key.dtype()) {
7616        (DType::Datetime64 { tz: left_tz }, DType::Datetime64 { tz: right_tz })
7617            if left_tz == right_tz =>
7618        {
7619            (
7620                left_key.as_datetime64_slice()?,
7621                right_key.as_datetime64_slice()?,
7622                fp_types::Timestamp::NAT,
7623            )
7624        }
7625        (DType::Timedelta64, DType::Timedelta64) => (
7626            left_key.as_timedelta64_slice()?,
7627            right_key.as_timedelta64_slice()?,
7628            fp_types::Timedelta::NAT,
7629        ),
7630        _ => return None,
7631    };
7632    if left.contains(&nat) || right.contains(&nat) {
7633        return None;
7634    }
7635
7636    if left.windows(2).all(|pair| pair[0] < pair[1])
7637        && right.windows(2).all(|pair| pair[0] < pair[1])
7638    {
7639        let left_positions = (0..left.len()).map(Some).collect::<Vec<_>>();
7640        let mut right_positions = Vec::with_capacity(left.len());
7641        let mut right_idx = 0usize;
7642        for &left_value in left {
7643            while right_idx < right.len() && right[right_idx] < left_value {
7644                right_idx += 1;
7645            }
7646            right_positions.push(
7647                (right_idx < right.len()
7648                    && matches!(right[right_idx].cmp(&left_value), Ordering::Equal))
7649                .then_some(right_idx),
7650            );
7651        }
7652        return Some((left_positions, right_positions));
7653    }
7654
7655    if right.is_empty() {
7656        return Some(((0..left.len()).map(Some).collect(), vec![None; left.len()]));
7657    }
7658    let mut right_map = FxHashMap::<i64, JoinPositionBucket>::with_capacity_and_hasher(
7659        right.len(),
7660        Default::default(),
7661    );
7662    for (pos, &key) in right.iter().enumerate() {
7663        right_map.entry(key).or_default().push(pos);
7664    }
7665    let mut left_positions = Vec::<Option<usize>>::with_capacity(left.len());
7666    let mut right_positions = Vec::<Option<usize>>::with_capacity(left.len());
7667    for (left_pos, &key) in left.iter().enumerate() {
7668        if let Some(matches) = right_map.get(&key) {
7669            for &right_pos in matches {
7670                left_positions.push(Some(left_pos));
7671                right_positions.push(Some(right_pos));
7672            }
7673        } else {
7674            left_positions.push(Some(left_pos));
7675            right_positions.push(None);
7676        }
7677    }
7678    Some((left_positions, right_positions))
7679}
7680
7681#[inline]
7682fn newly_reached_temporal_i64_value_is_strict(values: &[i64], idx: usize, nat: i64) -> bool {
7683    let Some(&value) = values.get(idx) else {
7684        return true;
7685    };
7686    value != nat && (idx == 0 || values[idx - 1] < value)
7687}
7688
7689/// Ordered-unique single-key RIGHT matches for all-valid temporal columns.
7690/// Datetime64 and Timedelta64 both store exact nanoseconds in `i64`, so a
7691/// monotone two-pointer scan produces the same optional left position per
7692/// right row as the generic Scalar planner without materializing either key.
7693/// Each newly reached value is validated for NaT and strict ordering during
7694/// that scan, avoiding separate input pre-scans. Nullable, NaT-bearing,
7695/// duplicate, unsorted, or mixed-dtype keys decline.
7696fn ordered_unique_temporal_i64_right_match_positions(
7697    left_key: &Column,
7698    right_key: &Column,
7699) -> Option<Vec<Option<usize>>> {
7700    if !left_key.validity().all() || !right_key.validity().all() {
7701        return None;
7702    }
7703
7704    let (left, right, nat) = match (left_key.dtype(), right_key.dtype()) {
7705        (DType::Datetime64 { tz: left_tz }, DType::Datetime64 { tz: right_tz })
7706            if left_tz == right_tz =>
7707        {
7708            (
7709                left_key.as_datetime64_slice()?,
7710                right_key.as_datetime64_slice()?,
7711                fp_types::Timestamp::NAT,
7712            )
7713        }
7714        (DType::Timedelta64, DType::Timedelta64) => (
7715            left_key.as_timedelta64_slice()?,
7716            right_key.as_timedelta64_slice()?,
7717            fp_types::Timedelta::NAT,
7718        ),
7719        _ => return None,
7720    };
7721    if !newly_reached_temporal_i64_value_is_strict(left, 0, nat) {
7722        return None;
7723    }
7724
7725    let mut left_positions = Vec::with_capacity(right.len());
7726    let mut left_idx = 0usize;
7727    for (right_idx, &right_value) in right.iter().enumerate() {
7728        if !newly_reached_temporal_i64_value_is_strict(right, right_idx, nat) {
7729            return None;
7730        }
7731        while left_idx < left.len() && left[left_idx] < right_value {
7732            left_idx += 1;
7733            if !newly_reached_temporal_i64_value_is_strict(left, left_idx, nat) {
7734                return None;
7735            }
7736        }
7737        left_positions.push(
7738            (left_idx < left.len() && matches!(left[left_idx].cmp(&right_value), Ordering::Equal))
7739                .then_some(left_idx),
7740        );
7741    }
7742    while left_idx < left.len() {
7743        left_idx += 1;
7744        if !newly_reached_temporal_i64_value_is_strict(left, left_idx, nat) {
7745            return None;
7746        }
7747    }
7748    Some(left_positions)
7749}
7750
7751/// Ordered-unique single-key OUTER union for all-valid temporal columns.
7752/// Datetime64 and Timedelta64 ordering is their raw nanosecond ordering, so a
7753/// three-way merge produces the same key-sorted optional position tapes as the
7754/// generic Scalar planner without materializing either input key for position
7755/// planning. Each newly reached value is validated for NaT and strict ordering
7756/// inside that merge, avoiding separate input pre-scans. Nullable, NaT-bearing,
7757/// duplicate, unsorted, or mixed-dtype keys decline.
7758fn ordered_unique_temporal_i64_outer_positions(
7759    left_key: &Column,
7760    right_key: &Column,
7761) -> Option<OptionalJoinPositions> {
7762    if !left_key.validity().all() || !right_key.validity().all() {
7763        return None;
7764    }
7765
7766    let (left, right, nat) = match (left_key.dtype(), right_key.dtype()) {
7767        (DType::Datetime64 { tz: left_tz }, DType::Datetime64 { tz: right_tz })
7768            if left_tz == right_tz =>
7769        {
7770            (
7771                left_key.as_datetime64_slice()?,
7772                right_key.as_datetime64_slice()?,
7773                fp_types::Timestamp::NAT,
7774            )
7775        }
7776        (DType::Timedelta64, DType::Timedelta64) => (
7777            left_key.as_timedelta64_slice()?,
7778            right_key.as_timedelta64_slice()?,
7779            fp_types::Timedelta::NAT,
7780        ),
7781        _ => return None,
7782    };
7783    if !newly_reached_temporal_i64_value_is_strict(left, 0, nat)
7784        || !newly_reached_temporal_i64_value_is_strict(right, 0, nat)
7785    {
7786        return None;
7787    }
7788
7789    let capacity = left.len().saturating_add(right.len());
7790    let mut left_positions = Vec::<Option<usize>>::with_capacity(capacity);
7791    let mut right_positions = Vec::<Option<usize>>::with_capacity(capacity);
7792    let (mut left_idx, mut right_idx) = (0usize, 0usize);
7793    while left_idx < left.len() && right_idx < right.len() {
7794        match left[left_idx].cmp(&right[right_idx]) {
7795            Ordering::Equal => {
7796                left_positions.push(Some(left_idx));
7797                right_positions.push(Some(right_idx));
7798                left_idx += 1;
7799                right_idx += 1;
7800                if !newly_reached_temporal_i64_value_is_strict(left, left_idx, nat)
7801                    || !newly_reached_temporal_i64_value_is_strict(right, right_idx, nat)
7802                {
7803                    return None;
7804                }
7805            }
7806            Ordering::Less => {
7807                left_positions.push(Some(left_idx));
7808                right_positions.push(None);
7809                left_idx += 1;
7810                if !newly_reached_temporal_i64_value_is_strict(left, left_idx, nat) {
7811                    return None;
7812                }
7813            }
7814            Ordering::Greater => {
7815                left_positions.push(None);
7816                right_positions.push(Some(right_idx));
7817                right_idx += 1;
7818                if !newly_reached_temporal_i64_value_is_strict(right, right_idx, nat) {
7819                    return None;
7820                }
7821            }
7822        }
7823    }
7824    while left_idx < left.len() {
7825        left_positions.push(Some(left_idx));
7826        right_positions.push(None);
7827        left_idx += 1;
7828        if !newly_reached_temporal_i64_value_is_strict(left, left_idx, nat) {
7829            return None;
7830        }
7831    }
7832    while right_idx < right.len() {
7833        left_positions.push(None);
7834        right_positions.push(Some(right_idx));
7835        right_idx += 1;
7836        if !newly_reached_temporal_i64_value_is_strict(right, right_idx, nat) {
7837            return None;
7838        }
7839    }
7840    Some((left_positions, right_positions))
7841}
7842
7843/// Core counting-sort/CSR inner-join over two `i64` key slices (see
7844/// [`dense_int64_inner_positions`]). Emits `(left_pos, right_pos)` pairs with
7845/// right positions ascending per left key, left probed ascending — matching the
7846/// hash path's bucket-insertion order. Returns `None` for a span wider than the
7847/// bounded direct-address gate so the caller falls back to hashing.
7848fn dense_i64_inner_positions_slices(
7849    left: &[i64],
7850    right: &[i64],
7851) -> Option<(Vec<usize>, Vec<usize>)> {
7852    if right.is_empty() || left.is_empty() {
7853        return Some((Vec::new(), Vec::new()));
7854    }
7855
7856    let mut min = right[0];
7857    let mut max = right[0];
7858    for &v in right {
7859        if v < min {
7860            min = v;
7861        }
7862        if v > max {
7863            max = v;
7864        }
7865    }
7866    // Bounded-span gate (mirrors the fp-columnar direct-address tally gates):
7867    // the dense table costs O(span) memory, so only take it when the span is
7868    // small in absolute terms AND relative to the build (right) side.
7869    let span = (max as i128) - (min as i128) + 1;
7870    if span > (1i128 << 24) || span > 16 * (right.len() as i128) {
7871        return None;
7872    }
7873    let range = span as usize;
7874
7875    // CSR build over the right side: counts -> exclusive-prefix offsets ->
7876    // positions filled in ascending right-position order.
7877    let mut offsets = vec![0usize; range + 1];
7878    for &v in right {
7879        offsets[(v - min) as usize + 1] += 1;
7880    }
7881    for i in 0..range {
7882        offsets[i + 1] += offsets[i];
7883    }
7884    let mut positions = vec![0usize; right.len()];
7885    let mut cursor = offsets.clone();
7886    for (pos, &v) in right.iter().enumerate() {
7887        let bucket = (v - min) as usize;
7888        positions[cursor[bucket]] = pos;
7889        cursor[bucket] += 1;
7890    }
7891
7892    let mut left_positions = Vec::<usize>::with_capacity(left.len().min(right.len()));
7893    let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
7894    for (left_pos, &v) in left.iter().enumerate() {
7895        if v < min || v > max {
7896            continue;
7897        }
7898        let bucket = (v - min) as usize;
7899        for &right_pos in &positions[offsets[bucket]..offsets[bucket + 1]] {
7900            left_positions.push(left_pos);
7901            right_positions.push(right_pos);
7902        }
7903    }
7904    Some((left_positions, right_positions))
7905}
7906
7907/// Hash inner-join position build for the remaining all-valid Int64 single-key
7908/// shape after ordered/dense witnesses reject. This keeps the generic hash
7909/// path's left-major probe order and right-bucket insertion order, but hashes
7910/// raw `i64` keys instead of materializing `JoinKeyComponent::Present` wrappers.
7911fn hash_int64_inner_positions(
7912    left_key: &Column,
7913    right_key: &Column,
7914) -> Option<(Vec<usize>, Vec<usize>)> {
7915    let left = left_key.as_i64_slice()?;
7916    let right = right_key.as_i64_slice()?;
7917    Some(hash_i64_inner_positions_slices(left, right))
7918}
7919
7920/// LEFT-join positions via a typed `FxHashMap<i64>` build+probe for all-valid
7921/// Int64 keys — the wide/sparse sibling of `dense_int64_left_positions` (whose
7922/// direct-address table bails on a wide key span, dropping the join to the
7923/// generic `JoinKeyComponent` Scalar-materialization path: left merge on a
7924/// wide-i64 key was 0.65x pandas). Build the right key -> ascending-position
7925/// buckets, then emit one output row per (left row, matching right row) in left
7926/// order, or a single (left, None) for an unmatched left row (null-fill).
7927/// Bit-identical to the dense/generic left path: same left iteration order, same
7928/// ascending right positions per key bucket. `None` (falls back) unless BOTH keys
7929/// are all-valid Int64 (a null-bearing key keeps the generic null-matching path).
7930fn hash_int64_left_positions(
7931    left_key: &Column,
7932    right_key: &Column,
7933) -> Option<OptionalJoinPositions> {
7934    let left = left_key.as_i64_slice()?;
7935    let right = right_key.as_i64_slice()?;
7936    if right.is_empty() {
7937        let left_positions = (0..left.len()).map(Some).collect::<Vec<_>>();
7938        let right_positions = vec![None; left.len()];
7939        return Some((left_positions, right_positions));
7940    }
7941    let mut right_map = FxHashMap::<i64, JoinPositionBucket>::with_capacity_and_hasher(
7942        right.len(),
7943        Default::default(),
7944    );
7945    for (pos, &key) in right.iter().enumerate() {
7946        right_map.entry(key).or_default().push(pos);
7947    }
7948    let mut left_positions = Vec::<Option<usize>>::with_capacity(left.len());
7949    let mut right_positions = Vec::<Option<usize>>::with_capacity(left.len());
7950    for (left_pos, &key) in left.iter().enumerate() {
7951        if let Some(matches) = right_map.get(&key) {
7952            for &right_pos in matches {
7953                left_positions.push(Some(left_pos));
7954                right_positions.push(Some(right_pos));
7955            }
7956        } else {
7957            left_positions.push(Some(left_pos));
7958            right_positions.push(None);
7959        }
7960    }
7961    Some((left_positions, right_positions))
7962}
7963
7964/// OUTER positions for wide/sparse Int64 keys. Uses a LIGHT `FxHashMap<i64,u32>`
7965/// key -> gid (first-seen) plus CSR position lists per gid — far cheaper than a
7966/// `FxHashMap<i64,(SmallVec,SmallVec)>` (whose 40-byte value dominated the build
7967/// at ~270ms). Emits per key ASCENDING (gids argsorted by key), left×right cross
7968/// product per key, else unmatched-left/right — bit-identical to
7969/// `dense_int64_outer_positions` (its key-min buckets walk keys ascending with
7970/// the same per-bucket order; the CSR scatter preserves ascending row order per
7971/// key, matching the dense per-bucket push order).
7972fn hash_int64_outer_positions(
7973    left_key: &Column,
7974    right_key: &Column,
7975) -> Option<OptionalJoinPositions> {
7976    let left = left_key.as_i64_slice()?;
7977    let right = right_key.as_i64_slice()?;
7978    let mut gid_of: FxHashMap<i64, u32> = FxHashMap::with_capacity_and_hasher(
7979        left.len().saturating_add(right.len()),
7980        Default::default(),
7981    );
7982    let mut gid_keys: Vec<i64> = Vec::new();
7983    let mut left_gid: Vec<u32> = Vec::with_capacity(left.len());
7984    for &key in left {
7985        let g = *gid_of.entry(key).or_insert_with(|| {
7986            let x = gid_keys.len() as u32;
7987            gid_keys.push(key);
7988            x
7989        });
7990        left_gid.push(g);
7991    }
7992    let mut right_gid: Vec<u32> = Vec::with_capacity(right.len());
7993    for &key in right {
7994        let g = *gid_of.entry(key).or_insert_with(|| {
7995            let x = gid_keys.len() as u32;
7996            gid_keys.push(key);
7997            x
7998        });
7999        right_gid.push(g);
8000    }
8001    let ng = gid_keys.len();
8002    // CSR offsets from per-gid counts.
8003    let mut loff = vec![0u32; ng + 1];
8004    for &g in &left_gid {
8005        loff[g as usize + 1] += 1;
8006    }
8007    let mut roff = vec![0u32; ng + 1];
8008    for &g in &right_gid {
8009        roff[g as usize + 1] += 1;
8010    }
8011    for g in 0..ng {
8012        loff[g + 1] += loff[g];
8013        roff[g + 1] += roff[g];
8014    }
8015    let mut lpos = vec![0u32; left.len()];
8016    let mut lw = loff[..ng].to_vec();
8017    for (i, &g) in left_gid.iter().enumerate() {
8018        let g = g as usize;
8019        lpos[lw[g] as usize] = i as u32;
8020        lw[g] += 1;
8021    }
8022    let mut rpos = vec![0u32; right.len()];
8023    let mut rw = roff[..ng].to_vec();
8024    for (i, &g) in right_gid.iter().enumerate() {
8025        let g = g as usize;
8026        rpos[rw[g] as usize] = i as u32;
8027        rw[g] += 1;
8028    }
8029    let mut order: Vec<u32> = (0..ng as u32).collect();
8030    order.sort_unstable_by_key(|&g| gid_keys[g as usize]);
8031    let mut left_positions = Vec::<Option<usize>>::new();
8032    let mut right_positions = Vec::<Option<usize>>::new();
8033    for &g in &order {
8034        let g = g as usize;
8035        let ls = &lpos[loff[g] as usize..loff[g + 1] as usize];
8036        let rs = &rpos[roff[g] as usize..roff[g + 1] as usize];
8037        match (ls.is_empty(), rs.is_empty()) {
8038            (false, false) => {
8039                for &l in ls {
8040                    for &r in rs {
8041                        left_positions.push(Some(l as usize));
8042                        right_positions.push(Some(r as usize));
8043                    }
8044                }
8045            }
8046            (false, true) => {
8047                for &l in ls {
8048                    left_positions.push(Some(l as usize));
8049                    right_positions.push(None);
8050                }
8051            }
8052            (true, false) => {
8053                for &r in rs {
8054                    left_positions.push(None);
8055                    right_positions.push(Some(r as usize));
8056                }
8057            }
8058            (true, true) => {}
8059        }
8060    }
8061    Some((left_positions, right_positions))
8062}
8063
8064/// Hash build+probe over raw UTF-8 byte spans for all-valid contiguous-Utf8
8065/// keys (br-frankenpandas-i388q). Mirrors the generic `JoinKeyComponent` inner
8066/// path exactly — right positions pushed ascending per key bucket, left probed
8067/// in order — but hashes `&[u8]` spans directly instead of materializing each
8068/// key column to `Vec<Scalar>` and cloning every string into a
8069/// `JoinKeyComponent::Present(IndexLabel::Utf8)` wrapper. Returns `None` unless
8070/// BOTH keys are all-valid contiguous Utf8; null-bearing keys keep the generic
8071/// path (which matches null-to-null — a case `as_utf8_contiguous` excludes).
8072fn contiguous_utf8_inner_positions(
8073    left_key: &Column,
8074    right_key: &Column,
8075) -> Option<(Vec<usize>, Vec<usize>)> {
8076    let (left_bytes, left_offsets) = left_key.as_utf8_contiguous()?;
8077    let (right_bytes, right_offsets) = right_key.as_utf8_contiguous()?;
8078    let left_n = left_offsets.len() - 1;
8079    let right_n = right_offsets.len() - 1;
8080    if left_n == 0 || right_n == 0 {
8081        return Some((Vec::new(), Vec::new()));
8082    }
8083
8084    if let Some(positions) =
8085        sorted_contiguous_utf8_inner_positions(left_bytes, left_offsets, right_bytes, right_offsets)
8086    {
8087        return Some(positions);
8088    }
8089
8090    let mut right_map = FxHashMap::<&[u8], JoinPositionBucket>::with_capacity_and_hasher(
8091        right_n,
8092        Default::default(),
8093    );
8094    for pos in 0..right_n {
8095        let span = &right_bytes[right_offsets[pos]..right_offsets[pos + 1]];
8096        right_map.entry(span).or_default().push(pos);
8097    }
8098
8099    let mut left_positions = Vec::<usize>::with_capacity(left_n.min(right_n));
8100    let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
8101    for left_pos in 0..left_n {
8102        let span = &left_bytes[left_offsets[left_pos]..left_offsets[left_pos + 1]];
8103        if let Some(matches) = right_map.get(span) {
8104            for &right_pos in matches {
8105                left_positions.push(left_pos);
8106                right_positions.push(right_pos);
8107            }
8108        }
8109    }
8110    Some((left_positions, right_positions))
8111}
8112
8113fn collect_contiguous_utf8_position_map<'a>(
8114    bytes: &'a [u8],
8115    offsets: &[usize],
8116) -> FxHashMap<&'a [u8], JoinPositionBucket> {
8117    let n = offsets.len() - 1;
8118    let mut map =
8119        FxHashMap::<&[u8], JoinPositionBucket>::with_capacity_and_hasher(n, Default::default());
8120    for pos in 0..n {
8121        let span = &bytes[offsets[pos]..offsets[pos + 1]];
8122        map.entry(span).or_default().push(pos);
8123    }
8124    map
8125}
8126
8127fn contiguous_utf8_left_positions(
8128    left_key: &Column,
8129    right_key: &Column,
8130) -> Option<OptionalJoinPositions> {
8131    let (left_bytes, left_offsets) = left_key.as_utf8_contiguous()?;
8132    let (right_bytes, right_offsets) = right_key.as_utf8_contiguous()?;
8133    let left_n = left_offsets.len() - 1;
8134    let right_map = collect_contiguous_utf8_position_map(right_bytes, right_offsets);
8135
8136    let mut out_len = 0usize;
8137    for left_pos in 0..left_n {
8138        let span = &left_bytes[left_offsets[left_pos]..left_offsets[left_pos + 1]];
8139        out_len += right_map.get(span).map_or(1, JoinPositionBucket::len);
8140    }
8141
8142    let mut left_positions = Vec::<Option<usize>>::with_capacity(out_len);
8143    let mut right_positions = Vec::<Option<usize>>::with_capacity(out_len);
8144    for left_pos in 0..left_n {
8145        let span = &left_bytes[left_offsets[left_pos]..left_offsets[left_pos + 1]];
8146        if let Some(matches) = right_map.get(span) {
8147            for &right_pos in matches {
8148                left_positions.push(Some(left_pos));
8149                right_positions.push(Some(right_pos));
8150            }
8151        } else {
8152            left_positions.push(Some(left_pos));
8153            right_positions.push(None);
8154        }
8155    }
8156    Some((left_positions, right_positions))
8157}
8158
8159fn contiguous_utf8_outer_positions(
8160    left_key: &Column,
8161    right_key: &Column,
8162) -> Option<OptionalJoinPositions> {
8163    let (left_bytes, left_offsets) = left_key.as_utf8_contiguous()?;
8164    let (right_bytes, right_offsets) = right_key.as_utf8_contiguous()?;
8165    let left_n = left_offsets.len() - 1;
8166    let right_n = right_offsets.len() - 1;
8167
8168    let left_map = collect_contiguous_utf8_position_map(left_bytes, left_offsets);
8169    let right_map = collect_contiguous_utf8_position_map(right_bytes, right_offsets);
8170    let mut seen = FxHashSet::<&[u8]>::with_capacity_and_hasher(
8171        left_map.len() + right_map.len(),
8172        Default::default(),
8173    );
8174    let mut keys = Vec::<&[u8]>::with_capacity(left_map.len() + right_map.len());
8175    for pos in 0..left_n {
8176        let span = &left_bytes[left_offsets[pos]..left_offsets[pos + 1]];
8177        if seen.insert(span) {
8178            keys.push(span);
8179        }
8180    }
8181    for pos in 0..right_n {
8182        let span = &right_bytes[right_offsets[pos]..right_offsets[pos + 1]];
8183        if seen.insert(span) {
8184            keys.push(span);
8185        }
8186    }
8187    keys.sort_unstable();
8188
8189    let mut out_len = 0usize;
8190    for &key in &keys {
8191        out_len += match (left_map.get(key), right_map.get(key)) {
8192            (Some(lefts), Some(rights)) => lefts.len() * rights.len(),
8193            (Some(lefts), None) => lefts.len(),
8194            (None, Some(rights)) => rights.len(),
8195            (None, None) => 0,
8196        };
8197    }
8198
8199    let mut left_positions = Vec::<Option<usize>>::with_capacity(out_len);
8200    let mut right_positions = Vec::<Option<usize>>::with_capacity(out_len);
8201    for key in keys {
8202        match (left_map.get(key), right_map.get(key)) {
8203            (Some(lefts), Some(rights)) => {
8204                for &left_pos in lefts {
8205                    for &right_pos in rights {
8206                        left_positions.push(Some(left_pos));
8207                        right_positions.push(Some(right_pos));
8208                    }
8209                }
8210            }
8211            (Some(lefts), None) => {
8212                for &left_pos in lefts {
8213                    left_positions.push(Some(left_pos));
8214                    right_positions.push(None);
8215                }
8216            }
8217            (None, Some(rights)) => {
8218                for &right_pos in rights {
8219                    left_positions.push(None);
8220                    right_positions.push(Some(right_pos));
8221                }
8222            }
8223            (None, None) => {}
8224        }
8225    }
8226    Some((left_positions, right_positions))
8227}
8228
8229fn scalar_utf8_values(column: &Column) -> Option<&[Scalar]> {
8230    if column.dtype() != DType::Utf8 || !column.validity().all() {
8231        return None;
8232    }
8233    let values = column.values();
8234    values
8235        .iter()
8236        .all(|value| matches!(value, Scalar::Utf8(_)))
8237        .then_some(values)
8238}
8239
8240fn scalar_utf8_span(value: &Scalar) -> Option<&[u8]> {
8241    match value {
8242        Scalar::Utf8(value) => Some(value.as_bytes()),
8243        _ => None,
8244    }
8245}
8246
8247fn collect_scalar_utf8_position_map(
8248    values: &[Scalar],
8249) -> Option<FxHashMap<&[u8], JoinPositionBucket>> {
8250    let mut map = FxHashMap::<&[u8], JoinPositionBucket>::with_capacity_and_hasher(
8251        values.len(),
8252        Default::default(),
8253    );
8254    for (pos, value) in values.iter().enumerate() {
8255        map.entry(scalar_utf8_span(value)?).or_default().push(pos);
8256    }
8257    Some(map)
8258}
8259
8260fn scalar_utf8_inner_positions(
8261    left_key: &Column,
8262    right_key: &Column,
8263) -> Option<(Vec<usize>, Vec<usize>)> {
8264    let left = scalar_utf8_values(left_key)?;
8265    let right = scalar_utf8_values(right_key)?;
8266    if left.is_empty() || right.is_empty() {
8267        return Some((Vec::new(), Vec::new()));
8268    }
8269
8270    let right_map = collect_scalar_utf8_position_map(right)?;
8271    let mut left_positions = Vec::<usize>::with_capacity(left.len().min(right.len()));
8272    let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
8273    for (left_pos, value) in left.iter().enumerate() {
8274        if let Some(matches) = right_map.get(scalar_utf8_span(value)?) {
8275            for &right_pos in matches {
8276                left_positions.push(left_pos);
8277                right_positions.push(right_pos);
8278            }
8279        }
8280    }
8281    Some((left_positions, right_positions))
8282}
8283
8284fn scalar_utf8_left_positions(
8285    left_key: &Column,
8286    right_key: &Column,
8287) -> Option<OptionalJoinPositions> {
8288    let left = scalar_utf8_values(left_key)?;
8289    let right = scalar_utf8_values(right_key)?;
8290    let right_map = collect_scalar_utf8_position_map(right)?;
8291
8292    let mut out_len = 0usize;
8293    for value in left {
8294        out_len += right_map
8295            .get(scalar_utf8_span(value)?)
8296            .map_or(1, JoinPositionBucket::len);
8297    }
8298
8299    let mut left_positions = Vec::<Option<usize>>::with_capacity(out_len);
8300    let mut right_positions = Vec::<Option<usize>>::with_capacity(out_len);
8301    for (left_pos, value) in left.iter().enumerate() {
8302        if let Some(matches) = right_map.get(scalar_utf8_span(value)?) {
8303            for &right_pos in matches {
8304                left_positions.push(Some(left_pos));
8305                right_positions.push(Some(right_pos));
8306            }
8307        } else {
8308            left_positions.push(Some(left_pos));
8309            right_positions.push(None);
8310        }
8311    }
8312    Some((left_positions, right_positions))
8313}
8314
8315fn scalar_utf8_outer_positions(
8316    left_key: &Column,
8317    right_key: &Column,
8318) -> Option<OptionalJoinPositions> {
8319    let left = scalar_utf8_values(left_key)?;
8320    let right = scalar_utf8_values(right_key)?;
8321    let left_map = collect_scalar_utf8_position_map(left)?;
8322    let right_map = collect_scalar_utf8_position_map(right)?;
8323
8324    let mut seen = FxHashSet::<&[u8]>::with_capacity_and_hasher(
8325        left_map.len() + right_map.len(),
8326        Default::default(),
8327    );
8328    let mut keys = Vec::<&[u8]>::with_capacity(left_map.len() + right_map.len());
8329    for value in left {
8330        let span = scalar_utf8_span(value)?;
8331        if seen.insert(span) {
8332            keys.push(span);
8333        }
8334    }
8335    for value in right {
8336        let span = scalar_utf8_span(value)?;
8337        if seen.insert(span) {
8338            keys.push(span);
8339        }
8340    }
8341    keys.sort_unstable();
8342
8343    let mut out_len = 0usize;
8344    for &key in &keys {
8345        out_len += match (left_map.get(key), right_map.get(key)) {
8346            (Some(lefts), Some(rights)) => lefts.len() * rights.len(),
8347            (Some(lefts), None) => lefts.len(),
8348            (None, Some(rights)) => rights.len(),
8349            (None, None) => 0,
8350        };
8351    }
8352
8353    let mut left_positions = Vec::<Option<usize>>::with_capacity(out_len);
8354    let mut right_positions = Vec::<Option<usize>>::with_capacity(out_len);
8355    for key in keys {
8356        match (left_map.get(key), right_map.get(key)) {
8357            (Some(lefts), Some(rights)) => {
8358                for &left_pos in lefts {
8359                    for &right_pos in rights {
8360                        left_positions.push(Some(left_pos));
8361                        right_positions.push(Some(right_pos));
8362                    }
8363                }
8364            }
8365            (Some(lefts), None) => {
8366                for &left_pos in lefts {
8367                    left_positions.push(Some(left_pos));
8368                    right_positions.push(None);
8369                }
8370            }
8371            (None, Some(rights)) => {
8372                for &right_pos in rights {
8373                    left_positions.push(None);
8374                    right_positions.push(Some(right_pos));
8375                }
8376            }
8377            (None, None) => {}
8378        }
8379    }
8380    Some((left_positions, right_positions))
8381}
8382
8383fn hash_i64_inner_positions_slices(left: &[i64], right: &[i64]) -> (Vec<usize>, Vec<usize>) {
8384    if right.is_empty() || left.is_empty() {
8385        return (Vec::new(), Vec::new());
8386    }
8387
8388    let mut right_map = FxHashMap::<i64, JoinPositionBucket>::with_capacity_and_hasher(
8389        right.len(),
8390        Default::default(),
8391    );
8392    for (pos, &key) in right.iter().enumerate() {
8393        right_map.entry(key).or_default().push(pos);
8394    }
8395
8396    let mut left_positions = Vec::<usize>::with_capacity(left.len().min(right.len()));
8397    let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
8398    for (left_pos, &key) in left.iter().enumerate() {
8399        if let Some(matches) = right_map.get(&key) {
8400            for &right_pos in matches {
8401                left_positions.push(left_pos);
8402                right_positions.push(right_pos);
8403            }
8404        }
8405    }
8406    (left_positions, right_positions)
8407}
8408
8409/// Hash-free inner-join positions for a MULTI-column key whose every component
8410/// is an all-valid, bounded-range Int64 column. Packs each row's composite key
8411/// into a single `i64` via a mixed-radix code over the per-column spans
8412/// (`packed = Σ_c (val_c - min_c) · stride_c`, `stride_0 = 1`, `stride_c =
8413/// stride_{c-1}·range_{c-1}`), then runs the dense CSR core on the packed keys.
8414///
8415/// The packing is a bijection on the joint key box (mins/ranges computed over
8416/// BOTH sides so left- and right-side codes are comparable), so two composite
8417/// keys collide under packing IFF every component is equal — identical to the
8418/// `CompositeJoinKey` equality the FxHashMap path uses. Pair order is therefore
8419/// byte-for-byte the same as the hash path. Returns `None` (caller falls back to
8420/// the composite-hash path) for any non-Int64 / any-missing component or when
8421/// the packed span exceeds the bounded direct-address gate.
8422/// Typed INNER/LEFT positions for a 2-column all-valid Int64 composite key that's
8423/// too WIDE for `dense_packed_int64_inner_positions` (its packed mixed-radix span
8424/// exceeds the bounded gate on a high-cardinality component), which otherwise
8425/// dropped multi-key merge to the generic `collect_composite_keys` Scalar path
8426/// (2-i64-key merge was 0.65x inner / 0.69x left pandas). Packs each row's
8427/// `(k0, k1)` into a `u128` — a bijection, so key equality is exact — builds the
8428/// right key -> ascending-position map, and probes left in order: one row per
8429/// (left, matching right), or (for Left) a single `(Some, None)` null-fill for an
8430/// unmatched left row. Bit-identical to the generic `CompositeJoinKey` path (same
8431/// left iteration + ascending-right-per-key emit). Returns `None` for non-Inner/
8432/// Left, non-2-key, or any non-all-valid-Int64 component.
8433fn typed_wide_two_i64_key_positions(
8434    join_type: JoinType,
8435    left_cols: &[&Column],
8436    right_cols: &[&Column],
8437) -> Option<MergeRowPositions> {
8438    if !matches!(
8439        join_type,
8440        JoinType::Inner | JoinType::Left | JoinType::Outer
8441    ) {
8442        return None;
8443    }
8444    if left_cols.len() != 2 || right_cols.len() != 2 {
8445        return None;
8446    }
8447    let l0 = left_cols[0].as_i64_slice()?;
8448    let l1 = left_cols[1].as_i64_slice()?;
8449    let r0 = right_cols[0].as_i64_slice()?;
8450    let r1 = right_cols[1].as_i64_slice()?;
8451    let pack = |a: i64, b: i64| -> u128 { (u128::from(a as u64) << 64) | u128::from(b as u64) };
8452
8453    if matches!(join_type, JoinType::Outer) {
8454        // OUTER: gid-factorize the u128 composite, CSR the per-gid positions, then
8455        // emit key-ASCENDING by the SEMANTIC (i64, i64) tuple (decoded from the
8456        // packed key — u128 order would mis-sort negatives). The typed branch
8457        // returns positions directly (the generic in-block sort is bypassed), so
8458        // they must arrive pre-sorted, matching sort_merge_rows_by_join_keys.
8459        let mut gid_of: FxHashMap<u128, u32> = FxHashMap::with_capacity_and_hasher(
8460            l0.len().saturating_add(r0.len()),
8461            Default::default(),
8462        );
8463        let mut gid_keys: Vec<u128> = Vec::new();
8464        let mut left_gid: Vec<u32> = Vec::with_capacity(l0.len());
8465        for pos in 0..l0.len() {
8466            let key = pack(l0[pos], l1[pos]);
8467            let g = *gid_of.entry(key).or_insert_with(|| {
8468                let x = gid_keys.len() as u32;
8469                gid_keys.push(key);
8470                x
8471            });
8472            left_gid.push(g);
8473        }
8474        let mut right_gid: Vec<u32> = Vec::with_capacity(r0.len());
8475        for pos in 0..r0.len() {
8476            let key = pack(r0[pos], r1[pos]);
8477            let g = *gid_of.entry(key).or_insert_with(|| {
8478                let x = gid_keys.len() as u32;
8479                gid_keys.push(key);
8480                x
8481            });
8482            right_gid.push(g);
8483        }
8484        let ng = gid_keys.len();
8485        let mut loff = vec![0u32; ng + 1];
8486        for &g in &left_gid {
8487            loff[g as usize + 1] += 1;
8488        }
8489        let mut roff = vec![0u32; ng + 1];
8490        for &g in &right_gid {
8491            roff[g as usize + 1] += 1;
8492        }
8493        for g in 0..ng {
8494            loff[g + 1] += loff[g];
8495            roff[g + 1] += roff[g];
8496        }
8497        let mut lpos = vec![0u32; l0.len()];
8498        let mut lw = loff[..ng].to_vec();
8499        for (i, &g) in left_gid.iter().enumerate() {
8500            let g = g as usize;
8501            lpos[lw[g] as usize] = i as u32;
8502            lw[g] += 1;
8503        }
8504        let mut rpos = vec![0u32; r0.len()];
8505        let mut rw = roff[..ng].to_vec();
8506        for (i, &g) in right_gid.iter().enumerate() {
8507            let g = g as usize;
8508            rpos[rw[g] as usize] = i as u32;
8509            rw[g] += 1;
8510        }
8511        // Argsort gids by the SEMANTIC (i64, i64) key (hi = k0, lo = k1).
8512        let decode = |packed: u128| -> (i64, i64) {
8513            (((packed >> 64) as u64) as i64, (packed as u64) as i64)
8514        };
8515        let mut order: Vec<u32> = (0..ng as u32).collect();
8516        order.sort_unstable_by_key(|&g| decode(gid_keys[g as usize]));
8517        let mut left_positions = Vec::<Option<usize>>::new();
8518        let mut right_positions = Vec::<Option<usize>>::new();
8519        for &g in &order {
8520            let g = g as usize;
8521            let ls = &lpos[loff[g] as usize..loff[g + 1] as usize];
8522            let rs = &rpos[roff[g] as usize..roff[g + 1] as usize];
8523            match (ls.is_empty(), rs.is_empty()) {
8524                (false, false) => {
8525                    for &l in ls {
8526                        for &r in rs {
8527                            left_positions.push(Some(l as usize));
8528                            right_positions.push(Some(r as usize));
8529                        }
8530                    }
8531                }
8532                (false, true) => {
8533                    for &l in ls {
8534                        left_positions.push(Some(l as usize));
8535                        right_positions.push(None);
8536                    }
8537                }
8538                (true, false) => {
8539                    for &r in rs {
8540                        left_positions.push(None);
8541                        right_positions.push(Some(r as usize));
8542                    }
8543                }
8544                (true, true) => {}
8545            }
8546        }
8547        return Some((left_positions, right_positions, None));
8548    }
8549
8550    // Inner / Left: right key -> ascending-position map, probe left in order.
8551    let mut right_map = FxHashMap::<u128, JoinPositionBucket>::with_capacity_and_hasher(
8552        r0.len(),
8553        Default::default(),
8554    );
8555    for pos in 0..r0.len() {
8556        right_map
8557            .entry(pack(r0[pos], r1[pos]))
8558            .or_default()
8559            .push(pos);
8560    }
8561    let is_left = matches!(join_type, JoinType::Left);
8562    let mut left_positions = Vec::<Option<usize>>::new();
8563    let mut right_positions = Vec::<Option<usize>>::new();
8564    for left_pos in 0..l0.len() {
8565        let key = pack(l0[left_pos], l1[left_pos]);
8566        if let Some(matches) = right_map.get(&key) {
8567            for &right_pos in matches {
8568                left_positions.push(Some(left_pos));
8569                right_positions.push(Some(right_pos));
8570            }
8571        } else if is_left {
8572            left_positions.push(Some(left_pos));
8573            right_positions.push(None);
8574        }
8575    }
8576    Some((left_positions, right_positions, None))
8577}
8578
8579/// General K-key (K >= 3) sibling of `typed_wide_two_i64_key_positions` for wide
8580/// Int64 key columns that overflow `dense_packed_int64_inner_positions` and exceed
8581/// the 2-key u128 packer. Factorizes each key column over left ∪ right into dense
8582/// gids (first-seen), then packs each row's per-column gids into a single u128
8583/// (column 0 most-significant) — a bijection whenever the summed gid bit-widths
8584/// fit 127 bits (else `None` → generic Scalar composite path). With the composite
8585/// as one integer, this reuses the exact same inner/left/outer emit as the 2-key
8586/// path. OUTER argsorts groups by the SEMANTIC original (i64,..,i64) tuple captured
8587/// at gid creation (packed-gid order is first-seen, not sorted). Bit-identical to
8588/// the `CompositeJoinKey` path (same left-order probe + ascending-right-per-key emit
8589/// for inner/left; same key-ascending group emit for outer). Returns `None` for
8590/// non-Inner/Left/Outer, K < 3, unequal K, any non-all-valid-Int64 component, or a
8591/// composite too wide for u128.
8592fn typed_wide_multi_i64_key_positions(
8593    join_type: JoinType,
8594    left_cols: &[&Column],
8595    right_cols: &[&Column],
8596) -> Option<MergeRowPositions> {
8597    if !matches!(
8598        join_type,
8599        JoinType::Inner | JoinType::Left | JoinType::Outer
8600    ) {
8601        return None;
8602    }
8603    let k = left_cols.len();
8604    if k < 3 || right_cols.len() != k {
8605        return None;
8606    }
8607    let mut ls: Vec<&[i64]> = Vec::with_capacity(k);
8608    let mut rs: Vec<&[i64]> = Vec::with_capacity(k);
8609    for c in 0..k {
8610        ls.push(left_cols[c].as_i64_slice()?);
8611        rs.push(right_cols[c].as_i64_slice()?);
8612    }
8613    let nl = ls[0].len();
8614    let nr = rs[0].len();
8615    if ls.iter().any(|s| s.len() != nl) || rs.iter().any(|s| s.len() != nr) {
8616        return None;
8617    }
8618
8619    // Factorize each key column over left ∪ right into dense first-seen gids.
8620    let mut lgid: Vec<Vec<u32>> = Vec::with_capacity(k);
8621    let mut rgid: Vec<Vec<u32>> = Vec::with_capacity(k);
8622    let mut cards: Vec<u64> = Vec::with_capacity(k);
8623    for c in 0..k {
8624        let mut m: FxHashMap<i64, u32> =
8625            FxHashMap::with_capacity_and_hasher(nl + nr, Default::default());
8626        let mut next: u32 = 0;
8627        let mut lg = Vec::with_capacity(nl);
8628        for &v in ls[c] {
8629            let g = *m.entry(v).or_insert_with(|| {
8630                let x = next;
8631                next += 1;
8632                x
8633            });
8634            lg.push(g);
8635        }
8636        let mut rg = Vec::with_capacity(nr);
8637        for &v in rs[c] {
8638            let g = *m.entry(v).or_insert_with(|| {
8639                let x = next;
8640                next += 1;
8641                x
8642            });
8643            rg.push(g);
8644        }
8645        cards.push(next as u64);
8646        lgid.push(lg);
8647        rgid.push(rg);
8648    }
8649
8650    // Per-column bit widths; bail if the packed composite exceeds u128.
8651    let mut bits: Vec<u32> = Vec::with_capacity(k);
8652    let mut total: u32 = 0;
8653    for &card in &cards {
8654        let b = if card <= 1 {
8655            0
8656        } else {
8657            64 - (card - 1).leading_zeros()
8658        };
8659        bits.push(b);
8660        total += b;
8661    }
8662    if total > 127 {
8663        return None;
8664    }
8665
8666    let pack = |gids: &[Vec<u32>], row: usize| -> u128 {
8667        let mut p: u128 = 0;
8668        for c in 0..k {
8669            p = (p << bits[c]) | u128::from(gids[c][row]);
8670        }
8671        p
8672    };
8673
8674    if matches!(join_type, JoinType::Outer) {
8675        let mut gid_of: FxHashMap<u128, u32> =
8676            FxHashMap::with_capacity_and_hasher(nl.saturating_add(nr), Default::default());
8677        // Semantic original tuple per composite gid (for the key-ascending sort).
8678        let mut gid_tuple: Vec<Vec<i64>> = Vec::new();
8679        let mut left_g: Vec<u32> = Vec::with_capacity(nl);
8680        for (row, _) in ls[0].iter().enumerate().take(nl) {
8681            let key = pack(&lgid, row);
8682            let g = *gid_of.entry(key).or_insert_with(|| {
8683                let x = gid_tuple.len() as u32;
8684                gid_tuple.push((0..k).map(|c| ls[c][row]).collect());
8685                x
8686            });
8687            left_g.push(g);
8688        }
8689        let mut right_g: Vec<u32> = Vec::with_capacity(nr);
8690        for (row, _) in rs[0].iter().enumerate().take(nr) {
8691            let key = pack(&rgid, row);
8692            let g = *gid_of.entry(key).or_insert_with(|| {
8693                let x = gid_tuple.len() as u32;
8694                gid_tuple.push((0..k).map(|c| rs[c][row]).collect());
8695                x
8696            });
8697            right_g.push(g);
8698        }
8699        let ng = gid_tuple.len();
8700        let mut loff = vec![0u32; ng + 1];
8701        for &g in &left_g {
8702            loff[g as usize + 1] += 1;
8703        }
8704        let mut roff = vec![0u32; ng + 1];
8705        for &g in &right_g {
8706            roff[g as usize + 1] += 1;
8707        }
8708        for g in 0..ng {
8709            loff[g + 1] += loff[g];
8710            roff[g + 1] += roff[g];
8711        }
8712        let mut lpos = vec![0u32; nl];
8713        let mut lw = loff[..ng].to_vec();
8714        for (i, &g) in left_g.iter().enumerate() {
8715            let g = g as usize;
8716            lpos[lw[g] as usize] = i as u32;
8717            lw[g] += 1;
8718        }
8719        let mut rpos = vec![0u32; nr];
8720        let mut rw = roff[..ng].to_vec();
8721        for (i, &g) in right_g.iter().enumerate() {
8722            let g = g as usize;
8723            rpos[rw[g] as usize] = i as u32;
8724            rw[g] += 1;
8725        }
8726        let mut order: Vec<u32> = (0..ng as u32).collect();
8727        order.sort_unstable_by(|&a, &b| gid_tuple[a as usize].cmp(&gid_tuple[b as usize]));
8728        let mut left_positions = Vec::<Option<usize>>::new();
8729        let mut right_positions = Vec::<Option<usize>>::new();
8730        for &g in &order {
8731            let g = g as usize;
8732            let lsl = &lpos[loff[g] as usize..loff[g + 1] as usize];
8733            let rsl = &rpos[roff[g] as usize..roff[g + 1] as usize];
8734            match (lsl.is_empty(), rsl.is_empty()) {
8735                (false, false) => {
8736                    for &l in lsl {
8737                        for &r in rsl {
8738                            left_positions.push(Some(l as usize));
8739                            right_positions.push(Some(r as usize));
8740                        }
8741                    }
8742                }
8743                (false, true) => {
8744                    for &l in lsl {
8745                        left_positions.push(Some(l as usize));
8746                        right_positions.push(None);
8747                    }
8748                }
8749                (true, false) => {
8750                    for &r in rsl {
8751                        left_positions.push(None);
8752                        right_positions.push(Some(r as usize));
8753                    }
8754                }
8755                (true, true) => {}
8756            }
8757        }
8758        return Some((left_positions, right_positions, None));
8759    }
8760
8761    // Inner / Left: right composite -> ascending-position map, probe left in order.
8762    let mut right_map =
8763        FxHashMap::<u128, JoinPositionBucket>::with_capacity_and_hasher(nr, Default::default());
8764    for pos in 0..nr {
8765        right_map.entry(pack(&rgid, pos)).or_default().push(pos);
8766    }
8767    let is_left = matches!(join_type, JoinType::Left);
8768    let mut left_positions = Vec::<Option<usize>>::new();
8769    let mut right_positions = Vec::<Option<usize>>::new();
8770    for left_pos in 0..nl {
8771        let key = pack(&lgid, left_pos);
8772        if let Some(matches) = right_map.get(&key) {
8773            for &right_pos in matches {
8774                left_positions.push(Some(left_pos));
8775                right_positions.push(Some(right_pos));
8776            }
8777        } else if is_left {
8778            left_positions.push(Some(left_pos));
8779            right_positions.push(None);
8780        }
8781    }
8782    Some((left_positions, right_positions, None))
8783}
8784
8785/// K-key (K >= 3) INNER/LEFT positions for all-valid BOUNDED-range Int64 keys
8786/// whose joint mixed-radix span fits an `i64` — even when that span exceeds the
8787/// direct-address gate of `dense_packed_int64_inner_positions` (2^24). Packs each
8788/// row's composite into one `i64` (`Σ_c (val_c - min_c)·stride_c`, `stride_0 = 1`,
8789/// `stride_c = stride_{c-1}·range_{c-1}`; a bijection on the joint key box, so
8790/// composite equality IFF every component equal) and runs the SINGLE-key i64 hash
8791/// merge on it — skipping the K per-column factorization `FxHashMap`s that
8792/// `typed_wide_multi_i64_key_positions` builds (the khash-floor cost that left
8793/// 3-key merge at 0.43-0.57x pandas). Bit-identical to that path / the generic
8794/// Scalar composite path: same left iteration order, same ascending right position
8795/// per composite bucket, same unmatched-left null-fill. Returns `None` (caller
8796/// falls back to the factorize path) unless every key is an all-valid Int64 slice
8797/// and the joint span fits `i64` — Outer bails (its key-ascending emit is handled
8798/// by the factorize path's semantic gid sort).
8799fn bounded_composite_multi_i64_key_positions(
8800    join_type: JoinType,
8801    left_cols: &[&Column],
8802    right_cols: &[&Column],
8803) -> Option<MergeRowPositions> {
8804    if !matches!(join_type, JoinType::Inner | JoinType::Left) {
8805        return None;
8806    }
8807    let k = left_cols.len();
8808    if k < 3 || right_cols.len() != k {
8809        return None;
8810    }
8811    let mut ls: Vec<&[i64]> = Vec::with_capacity(k);
8812    let mut rs: Vec<&[i64]> = Vec::with_capacity(k);
8813    for c in 0..k {
8814        ls.push(left_cols[c].as_i64_slice()?);
8815        rs.push(right_cols[c].as_i64_slice()?);
8816    }
8817    let nl = ls[0].len();
8818    let nr = rs[0].len();
8819    if ls.iter().any(|s| s.len() != nl) || rs.iter().any(|s| s.len() != nr) {
8820        return None;
8821    }
8822    if nl == 0 || nr == 0 {
8823        // Let the generic/factorize path handle degenerate empties (its
8824        // left-null-fill / empty-output shape is already validated there).
8825        return None;
8826    }
8827
8828    // Per-column min + span over left ∪ right; bail if the joint mixed-radix
8829    // product overflows i64 (a truly wide key keeps the factorize path).
8830    let mut mins = vec![0i64; k];
8831    let mut ranges = vec![0u128; k];
8832    for c in 0..k {
8833        let mut mn = i64::MAX;
8834        let mut mx = i64::MIN;
8835        for &v in ls[c] {
8836            if v < mn {
8837                mn = v;
8838            }
8839            if v > mx {
8840                mx = v;
8841            }
8842        }
8843        for &v in rs[c] {
8844            if v < mn {
8845                mn = v;
8846            }
8847            if v > mx {
8848                mx = v;
8849            }
8850        }
8851        mins[c] = mn;
8852        ranges[c] = (mx as i128 - mn as i128 + 1) as u128;
8853    }
8854    // strides[0] = 1, strides[c] = strides[c-1] * ranges[c-1]; bail on overflow.
8855    let mut strides = vec![1i64; k];
8856    let mut acc: u128 = 1;
8857    for c in 0..k {
8858        strides[c] = acc as i64;
8859        acc = acc.checked_mul(ranges[c])?;
8860        if acc > i64::MAX as u128 {
8861            return None;
8862        }
8863    }
8864    let comp = |s: &[&[i64]], row: usize| -> i64 {
8865        let mut p: i64 = 0;
8866        for c in 0..k {
8867            // (val - min) < range_c and range product fits i64 ⇒ no overflow.
8868            p += (s[c][row] - mins[c]) * strides[c];
8869        }
8870        p
8871    };
8872    let lcomp: Vec<i64> = (0..nl).map(|r| comp(&ls, r)).collect();
8873    let rcomp: Vec<i64> = (0..nr).map(|r| comp(&rs, r)).collect();
8874
8875    if matches!(join_type, JoinType::Inner) {
8876        let (lp, rp) = hash_i64_inner_positions_slices(&lcomp, &rcomp);
8877        return Some((
8878            lp.into_iter().map(Some).collect(),
8879            rp.into_iter().map(Some).collect(),
8880            None,
8881        ));
8882    }
8883
8884    // LEFT: right composite -> ascending-position buckets, probe left in order
8885    // (mirror of hash_int64_left_positions on the composite slices).
8886    let mut right_map =
8887        FxHashMap::<i64, JoinPositionBucket>::with_capacity_and_hasher(nr, Default::default());
8888    for (pos, &key) in rcomp.iter().enumerate() {
8889        right_map.entry(key).or_default().push(pos);
8890    }
8891    let mut left_positions = Vec::<Option<usize>>::with_capacity(nl);
8892    let mut right_positions = Vec::<Option<usize>>::with_capacity(nl);
8893    for (left_pos, &key) in lcomp.iter().enumerate() {
8894        if let Some(matches) = right_map.get(&key) {
8895            for &right_pos in matches {
8896                left_positions.push(Some(left_pos));
8897                right_positions.push(Some(right_pos));
8898            }
8899        } else {
8900            left_positions.push(Some(left_pos));
8901            right_positions.push(None);
8902        }
8903    }
8904    Some((left_positions, right_positions, None))
8905}
8906
8907fn dense_packed_int64_inner_positions(
8908    left_cols: &[&Column],
8909    right_cols: &[&Column],
8910) -> Option<(Vec<usize>, Vec<usize>)> {
8911    let k = left_cols.len();
8912    if k == 0 || k != right_cols.len() {
8913        return None;
8914    }
8915
8916    let left_slices: Vec<&[i64]> = left_cols
8917        .iter()
8918        .map(|c| c.as_i64_slice())
8919        .collect::<Option<Vec<_>>>()?;
8920    let right_slices: Vec<&[i64]> = right_cols
8921        .iter()
8922        .map(|c| c.as_i64_slice())
8923        .collect::<Option<Vec<_>>>()?;
8924
8925    let n_left = left_slices[0].len();
8926    let n_right = right_slices[0].len();
8927    if n_left == 0 || n_right == 0 {
8928        return Some((Vec::new(), Vec::new()));
8929    }
8930
8931    // Per-column min and span over BOTH sides; product = joint packed span.
8932    let mut mins = vec![0i64; k];
8933    let mut strides = vec![1i128; k];
8934    let mut total: i128 = 1;
8935    for c in 0..k {
8936        let mut mn = right_slices[c][0];
8937        let mut mx = right_slices[c][0];
8938        for &v in left_slices[c].iter().chain(right_slices[c].iter()) {
8939            if v < mn {
8940                mn = v;
8941            }
8942            if v > mx {
8943                mx = v;
8944            }
8945        }
8946        mins[c] = mn;
8947        let range = (mx as i128) - (mn as i128) + 1;
8948        strides[c] = total;
8949        total = total.checked_mul(range)?;
8950        // Gate the packed span the same way the single-key core does, up front
8951        // (the product can overflow the bounded table for wide multi-keys).
8952        if total > (1i128 << 24) {
8953            return None;
8954        }
8955    }
8956    if total > 16 * ((n_left + n_right) as i128) {
8957        return None;
8958    }
8959
8960    let pack = |slices: &[&[i64]], n: usize| -> Vec<i64> {
8961        (0..n)
8962            .map(|row| {
8963                let mut acc: i128 = 0;
8964                for c in 0..k {
8965                    acc += ((slices[c][row] as i128) - (mins[c] as i128)) * strides[c];
8966                }
8967                acc as i64
8968            })
8969            .collect()
8970    };
8971    let packed_left = pack(&left_slices, n_left);
8972    let packed_right = pack(&right_slices, n_right);
8973
8974    dense_i64_inner_positions_slices(&packed_left, &packed_right)
8975}
8976
8977fn merge_single_key_inner_unsorted(
8978    left: &fp_frame::DataFrame,
8979    right: &fp_frame::DataFrame,
8980    left_on: &[&str],
8981    right_on: &[&str],
8982    left_key_columns: &[&Column],
8983    right_key_columns: &[&Column],
8984    suffixes: &ResolvedMergeSuffixes,
8985) -> Result<MergedDataFrame, JoinError> {
8986    debug_assert_eq!(left_key_columns.len(), 1);
8987    debug_assert_eq!(right_key_columns.len(), 1);
8988
8989    if left_on[0] == right_on[0]
8990        && ordered_identity_int64_keys_match(left_key_columns[0], right_key_columns[0])
8991    {
8992        return build_single_key_ordered_identity_inner_merge_output(
8993            left, right, left_on, right_on, suffixes,
8994        );
8995    }
8996    if let Some(merged) = build_single_key_affine_i64_inner_merge_output(
8997        left,
8998        right,
8999        left_on,
9000        right_on,
9001        left_key_columns[0],
9002        right_key_columns[0],
9003        suffixes,
9004    )? {
9005        return Ok(merged);
9006    }
9007    if let Some((left_positions, right_positions)) =
9008        ordered_unique_int64_inner_positions(left_key_columns[0], right_key_columns[0])
9009    {
9010        return build_single_key_inner_merge_output(
9011            left,
9012            right,
9013            left_on,
9014            right_on,
9015            &left_positions,
9016            &right_positions,
9017            suffixes,
9018        );
9019    }
9020
9021    if let Some(merged) = build_single_key_dense_i64_inner_merge_output(
9022        left,
9023        right,
9024        left_on,
9025        right_on,
9026        left_key_columns[0],
9027        right_key_columns[0],
9028        FusedInt64MergeOptions {
9029            suffixes,
9030            require_all_left_keys_matched: false,
9031        },
9032    )? {
9033        return Ok(merged);
9034    }
9035
9036    // Datetime64/Timedelta64 keys are physically i64 nanoseconds. For the
9037    // all-valid, same-dtype case, plan positions directly over that backing
9038    // instead of materializing one Scalar + JoinKeyComponent per row. Nullable
9039    // temporal keys deliberately keep the generic path below, where NaT joins
9040    // use the existing Missing-key semantics.
9041    if let Some((left_positions, right_positions)) =
9042        temporal_i64_inner_positions(left_key_columns[0], right_key_columns[0])
9043    {
9044        return build_single_key_inner_merge_output(
9045            left,
9046            right,
9047            left_on,
9048            right_on,
9049            &left_positions,
9050            &right_positions,
9051            suffixes,
9052        );
9053    }
9054
9055    // Hash-free dense direct-address build+probe for bounded all-valid Int64
9056    // keys (the common low-cardinality join-key shape). Bit-identical pairs.
9057    if let Some((left_positions, right_positions)) =
9058        dense_int64_inner_positions(left_key_columns[0], right_key_columns[0])
9059    {
9060        return build_single_key_inner_merge_output(
9061            left,
9062            right,
9063            left_on,
9064            right_on,
9065            &left_positions,
9066            &right_positions,
9067            suffixes,
9068        );
9069    }
9070    if let Some((left_positions, right_positions)) =
9071        hash_int64_inner_positions(left_key_columns[0], right_key_columns[0])
9072    {
9073        return build_single_key_inner_merge_output(
9074            left,
9075            right,
9076            left_on,
9077            right_on,
9078            &left_positions,
9079            &right_positions,
9080            suffixes,
9081        );
9082    }
9083
9084    if let Some(position_plan) =
9085        ordered_unique_utf8_inner_position_plan(left_key_columns[0], right_key_columns[0])
9086    {
9087        return match position_plan {
9088            InnerPositionPlan::Gather {
9089                left_positions,
9090                right_positions,
9091            } => build_single_key_inner_merge_output(
9092                left,
9093                right,
9094                left_on,
9095                right_on,
9096                &left_positions,
9097                &right_positions,
9098                suffixes,
9099            ),
9100            InnerPositionPlan::ContiguousRanges {
9101                left_start,
9102                right_start,
9103                len,
9104            } => build_single_key_inner_merge_output_with_selections(
9105                left,
9106                right,
9107                left_on,
9108                right_on,
9109                PositionSelection::ContiguousRange {
9110                    start: left_start,
9111                    len,
9112                },
9113                PositionSelection::ContiguousRange {
9114                    start: right_start,
9115                    len,
9116                },
9117                suffixes,
9118            ),
9119        };
9120    }
9121
9122    // Byte-span build+probe for all-valid contiguous-Utf8 string keys
9123    // (br-frankenpandas-i388q): skips the per-row String clone + Scalar
9124    // materialization of the JoinKeyComponent path. Same pairing -> same output.
9125    if let Some((left_positions, right_positions)) =
9126        contiguous_utf8_inner_positions(left_key_columns[0], right_key_columns[0])
9127    {
9128        return build_single_key_inner_merge_output(
9129            left,
9130            right,
9131            left_on,
9132            right_on,
9133            &left_positions,
9134            &right_positions,
9135            suffixes,
9136        );
9137    }
9138    if let Some((left_positions, right_positions)) =
9139        scalar_utf8_inner_positions(left_key_columns[0], right_key_columns[0])
9140    {
9141        return build_single_key_inner_merge_output(
9142            left,
9143            right,
9144            left_on,
9145            right_on,
9146            &left_positions,
9147            &right_positions,
9148            suffixes,
9149        );
9150    }
9151
9152    let left_keys = collect_single_join_keys(left_key_columns[0]);
9153    let right_keys = collect_single_join_keys(right_key_columns[0]);
9154    let mut right_map =
9155        FxHashMap::<&JoinKeyComponent, JoinPositionBucket>::with_capacity_and_hasher(
9156            right_keys.len(),
9157            Default::default(),
9158        );
9159    for (pos, key) in right_keys.iter().enumerate() {
9160        right_map.entry(key).or_default().push(pos);
9161    }
9162
9163    let mut left_positions = Vec::<usize>::with_capacity(left_keys.len().min(right_keys.len()));
9164    let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
9165    for (left_pos, key) in left_keys.iter().enumerate() {
9166        if let Some(matches) = right_map.get(key) {
9167            for &right_pos in matches {
9168                left_positions.push(left_pos);
9169                right_positions.push(right_pos);
9170            }
9171        }
9172    }
9173
9174    build_single_key_inner_merge_output(
9175        left,
9176        right,
9177        left_on,
9178        right_on,
9179        &left_positions,
9180        &right_positions,
9181        suffixes,
9182    )
9183}
9184
9185/// Merge two DataFrames on one or more key columns.
9186///
9187/// Matches `pd.merge(left, right, left_on=left_keys, right_on=right_keys, how=join_type)`.
9188/// - Key columns are used for matching rows (hash join).
9189/// - Non-key columns are carried through and reindexed.
9190/// - Column name conflicts use configurable suffixes (default `_x`/`_y`).
9191/// - The output index is auto-generated (0..n RangeIndex-style).
9192pub fn merge_dataframes_on_with(
9193    left: &fp_frame::DataFrame,
9194    right: &fp_frame::DataFrame,
9195    left_on: &[&str],
9196    right_on: &[&str],
9197    join_type: JoinType,
9198) -> Result<MergedDataFrame, JoinError> {
9199    merge_dataframes_on_with_options(
9200        left,
9201        right,
9202        left_on,
9203        right_on,
9204        join_type,
9205        MergeExecutionOptions::default(),
9206    )
9207}
9208
9209/// Merge two DataFrames on one or more key columns with execution options.
9210pub fn merge_dataframes_on_with_options(
9211    left: &fp_frame::DataFrame,
9212    right: &fp_frame::DataFrame,
9213    left_on: &[&str],
9214    right_on: &[&str],
9215    join_type: JoinType,
9216    options: MergeExecutionOptions,
9217) -> Result<MergedDataFrame, JoinError> {
9218    let suffixes = resolve_merge_suffixes(options.suffixes.clone());
9219    let indicator_name = resolve_merge_indicator_name(options.indicator_name.as_deref())?;
9220    // A column key a side repeats (['a', 'a']; not a join key) rides through
9221    // the merge under stand-in keys and comes back under its own name, each
9222    // column its own - by name every copy read the first column (i17d4). A
9223    // name the other side also has takes each side's suffix, as pandas'
9224    // (a_x, a_x beside a_y).
9225    let left_stand_in = stand_in_repeated_keys(left, left_on, 'l')?;
9226    let right_stand_in = stand_in_repeated_keys(right, right_on, 'r')?;
9227    let merged = merge_dataframes_on_with_options_storage(
9228        left_stand_in.as_ref().map_or(left, |(frame, _)| frame),
9229        right_stand_in.as_ref().map_or(right, |(frame, _)| frame),
9230        left_on,
9231        right_on,
9232        join_type,
9233        options,
9234    )?;
9235    let merged = keeping_source_widths(
9236        merged,
9237        left,
9238        right,
9239        left_on,
9240        right_on,
9241        join_type,
9242        indicator_name.as_deref(),
9243    )?;
9244    let suffixed = |name: &str, suffix: Option<&String>| {
9245        format!("{name}{}", suffix.map_or("", String::as_str))
9246    };
9247    let mut restored: FxHashMap<String, String> = FxHashMap::default();
9248    for (stand_in, own_suffix, other, other_on, other_suffix) in [
9249        (
9250            &left_stand_in,
9251            suffixes.left.as_ref(),
9252            right,
9253            right_on,
9254            suffixes.right.as_ref(),
9255        ),
9256        (
9257            &right_stand_in,
9258            suffixes.right.as_ref(),
9259            left,
9260            left_on,
9261            suffixes.left.as_ref(),
9262        ),
9263    ] {
9264        for (key, name) in stand_in.iter().flat_map(|(_, names)| names) {
9265            if other.column_occurrences(name) == 0 || other_on.contains(&name.as_str()) {
9266                restored.insert(key.clone(), name.clone());
9267                continue;
9268            }
9269            restored.insert(key.clone(), suffixed(name, own_suffix));
9270            // The other side's own (not stood-in) copy keeps its name in the
9271            // merge: it takes that side's suffix.
9272            restored
9273                .entry(name.clone())
9274                .or_insert_with(|| suffixed(name, other_suffix));
9275        }
9276    }
9277    let merged = if restored.is_empty() {
9278        merged
9279    } else {
9280        let restore = |name: &str| {
9281            restored
9282                .get(name)
9283                .map_or_else(|| name.to_owned(), Clone::clone)
9284        };
9285        MergedDataFrame {
9286            index: merged.index,
9287            columns: ColumnStore::from_pairs(
9288                merged
9289                    .columns
9290                    .iter_positional()
9291                    .map(|(name, column)| (restore(name), column.clone())),
9292            ),
9293            column_order: merged
9294                .column_order
9295                .iter()
9296                .map(|name| restore(name))
9297                .collect(),
9298        }
9299    };
9300    Ok(merged)
9301}
9302
9303/// A frame keyed by stand-ins and each stand-in with the name it stands for.
9304type StoodIn = (fp_frame::DataFrame, Vec<(String, String)>);
9305
9306/// `frame` with each column under a repeated key (not one of `on`) keyed by
9307/// a stand-in, and the stand-ins with their names; None when no key repeats
9308/// so.
9309fn stand_in_repeated_keys(
9310    frame: &fp_frame::DataFrame,
9311    on: &[&str],
9312    side: char,
9313) -> Result<Option<StoodIn>, JoinError> {
9314    let names = frame.column_names();
9315    let repeated = |name: &str| frame.column_occurrences(name) > 1 && !on.contains(&name);
9316    if !names.iter().any(|name| repeated(name)) {
9317        return Ok(None);
9318    }
9319    let mut stand_ins = Vec::new();
9320    let keys = names
9321        .iter()
9322        .enumerate()
9323        .map(|(position, name)| {
9324            if repeated(name) {
9325                let key = format!("\u{1}i17d4-{side}{position}");
9326                stand_ins.push((key.clone(), (*name).clone()));
9327                key
9328            } else {
9329                (*name).clone()
9330            }
9331        })
9332        .collect();
9333    Ok(Some((frame.with_column_keys(keys)?, stand_ins)))
9334}
9335
9336/// Restore widths by the output projection: all left positions followed by
9337/// right positions, excluding shared keys. Display names can repeat or
9338/// collide across suffixes and therefore cannot identify a source column.
9339/// Shared numeric keys retain the width of the rows supplying their values.
9340/// Only mixed-width right/outer keys need a complete-tuple origin scan.
9341fn keeping_source_widths(
9342    mut merged: MergedDataFrame,
9343    left: &fp_frame::DataFrame,
9344    right: &fp_frame::DataFrame,
9345    left_on: &[&str],
9346    right_on: &[&str],
9347    join_type: JoinType,
9348    indicator_name: Option<&str>,
9349) -> Result<MergedDataFrame, JoinError> {
9350    let shared = |name: &str| {
9351        !matches!(join_type, JoinType::Cross)
9352            && left_on
9353                .iter()
9354                .zip(right_on)
9355                .any(|(l, r)| l == r && *l == name)
9356    };
9357    let mut sources = Vec::with_capacity(left.num_columns() + right.num_columns());
9358    let fail = || {
9359        JoinError::Frame(FrameError::CompatibilityRejected(
9360            "merge output projection does not match source positions".to_owned(),
9361        ))
9362    };
9363    for position in 0..left.num_columns() {
9364        let name = left.column_name_at(position).ok_or_else(fail)?;
9365        let source = left.column_at(position).ok_or_else(fail)?;
9366        let partner = if shared(&name) {
9367            Some(right.column(&name).ok_or_else(fail)?)
9368        } else {
9369            None
9370        };
9371        sources.push((source, partner));
9372    }
9373    for position in 0..right.num_columns() {
9374        let name = right.column_name_at(position).ok_or_else(fail)?;
9375        if !shared(&name) {
9376            sources.push((right.column_at(position).ok_or_else(fail)?, None));
9377        }
9378    }
9379    if merged.columns.len() != sources.len() + usize::from(indicator_name.is_some()) {
9380        return Err(fail());
9381    }
9382    if let Some(indicator) = indicator_name
9383        && merged.columns.name_at(sources.len()) != Some(indicator)
9384    {
9385        return Err(fail());
9386    }
9387    let needs_origins = matches!(join_type, JoinType::Right | JoinType::Outer)
9388        && sources.iter().any(|(source, partner)| {
9389            partner.is_some_and(|partner| {
9390                source.width() != partner.width()
9391                    && fp_types::NumpyNumeric::of(&source.dtype(), source.width()).is_some()
9392                    && fp_types::NumpyNumeric::of(&partner.dtype(), partner.width()).is_some()
9393            })
9394        });
9395    let origins = if needs_origins {
9396        let left_keys = collect_composite_keys(&collect_join_key_columns(left, left_on, "left")?);
9397        let left_keys: FxHashSet<_> = left_keys.into_iter().collect();
9398        let right_keys =
9399            collect_composite_keys(&collect_join_key_columns(right, right_on, "right")?);
9400        let mut has_match = false;
9401        let mut has_right_only = false;
9402        for key in right_keys {
9403            if left_keys.contains(&key) {
9404                has_match = true;
9405            } else {
9406                has_right_only = true;
9407            }
9408        }
9409        let has_left = if matches!(join_type, JoinType::Outer) {
9410            !left.is_empty()
9411        } else {
9412            has_match
9413        };
9414        Some((has_left, has_right_only))
9415    } else {
9416        None
9417    };
9418    for (position, (source, partner)) in sources.into_iter().enumerate() {
9419        let column = merged.columns.column_at_mut(position).ok_or_else(fail)?;
9420        if let Some(partner) = partner {
9421            let numeric = fp_types::NumpyNumeric::of(&source.dtype(), source.width()).zip(
9422                fp_types::NumpyNumeric::of(&partner.dtype(), partner.width()),
9423            );
9424            let Some((left_numeric, right_numeric)) = numeric else {
9425                continue;
9426            };
9427            // Every inner/left shared key comes from a present left row.
9428            // Its width must not depend on an unmatched right payload row.
9429            if matches!(join_type, JoinType::Inner | JoinType::Left) {
9430                *column = column.clone().keeping_dtype_of(source);
9431                continue;
9432            }
9433            if let Some((has_left, has_right_only)) = origins {
9434                // No right-only tuples includes empty output: pandas keeps
9435                // the left dtype. Right-only output keeps the right dtype.
9436                if !has_right_only {
9437                    *column = column.clone().keeping_dtype_of(source);
9438                    continue;
9439                }
9440                if !has_left {
9441                    *column = column.clone().keeping_dtype_of(partner);
9442                    continue;
9443                }
9444            } else if column.width().is_some() {
9445                continue;
9446            }
9447            // Both origins require the common width, including clearing a
9448            // stale narrow tag on an already typed builder's output.
9449            if let Some(width) = left_numeric.result_type(right_numeric).width() {
9450                let nullable = column.dtype().is_nullable();
9451                if width.fits_storage(&column.dtype())
9452                    && (width.is_float() || nullable || !column.has_nulls())
9453                    && column.width() != Some(width)
9454                {
9455                    *column = column.cast_to_width(width, nullable)?;
9456                }
9457            } else if column.width().is_some() {
9458                *column = column.astype(column.dtype())?;
9459            }
9460        } else if source.width().is_some() {
9461            *column = column.clone().narrowed_like(source);
9462        }
9463    }
9464    Ok(merged)
9465}
9466
9467fn merge_dataframes_on_with_options_storage(
9468    left: &fp_frame::DataFrame,
9469    right: &fp_frame::DataFrame,
9470    left_on: &[&str],
9471    right_on: &[&str],
9472    join_type: JoinType,
9473    options: MergeExecutionOptions,
9474) -> Result<MergedDataFrame, JoinError> {
9475    let MergeExecutionOptions {
9476        indicator_name,
9477        validate_mode,
9478        suffixes,
9479        sort,
9480    } = options;
9481    let indicator_name = resolve_merge_indicator_name(indicator_name.as_deref())?;
9482    let suffixes = resolve_merge_suffixes(suffixes);
9483
9484    if matches!(join_type, JoinType::Cross) {
9485        if let Some(validate_mode) = validate_mode
9486            && !matches!(validate_mode, MergeValidateMode::ManyToMany)
9487        {
9488            return Err(JoinError::Frame(FrameError::CompatibilityRejected(
9489                format!(
9490                    "merge validate='{}' is not supported for cross join",
9491                    validate_mode.as_str()
9492                ),
9493            )));
9494        }
9495        validate_merge_suffixes_intra_frame(
9496            &left.column_names(),
9497            &right.column_names(),
9498            &HashSet::new(),
9499            &suffixes,
9500        )?;
9501        return merge_dataframes_cross(left, right, indicator_name.as_deref(), &suffixes);
9502    }
9503
9504    if left_on.is_empty() || right_on.is_empty() {
9505        return Err(JoinError::Frame(FrameError::CompatibilityRejected(
9506            "merge requires at least one key column".to_owned(),
9507        )));
9508    }
9509    if left_on.len() != right_on.len() {
9510        return Err(JoinError::Frame(FrameError::CompatibilityRejected(
9511            "merge requires left_on and right_on key lists with equal length".to_owned(),
9512        )));
9513    }
9514
9515    let mut seen_left_keys = HashSet::new();
9516    for key_name in left_on {
9517        if !seen_left_keys.insert(*key_name) {
9518            return Err(JoinError::Frame(FrameError::CompatibilityRejected(
9519                format!("merge left key column '{key_name}' is duplicated"),
9520            )));
9521        }
9522    }
9523    let mut seen_right_keys = HashSet::new();
9524    for key_name in right_on {
9525        if !seen_right_keys.insert(*key_name) {
9526            return Err(JoinError::Frame(FrameError::CompatibilityRejected(
9527                format!("merge right key column '{key_name}' is duplicated"),
9528            )));
9529        }
9530    }
9531
9532    let left_key_columns = collect_join_key_columns(left, left_on, "left")?;
9533    let right_key_columns = collect_join_key_columns(right, right_on, "right")?;
9534
9535    let shared_key_names = if left_on == right_on {
9536        left_on.iter().copied().collect::<HashSet<&str>>()
9537    } else {
9538        HashSet::new()
9539    };
9540    validate_merge_suffixes_intra_frame(
9541        &left.column_names(),
9542        &right.column_names(),
9543        &shared_key_names,
9544        &suffixes,
9545    )?;
9546
9547    // br-frankenpandas-uza04: settle `validate=` HERE, off the raw typed key
9548    // buffer, instead of letting it drag the whole merge onto the generic
9549    // Scalar path.
9550    //
9551    // `validate_merge_cardinality` is called in exactly ONE place — the generic
9552    // `collect_composite_keys` branch at the bottom of this function — so
9553    // `validate_mode_allows_fast_positions` had to return false for every
9554    // enforcing mode purely to *route execution there*. The cost of asking for
9555    // a cardinality guarantee was therefore the entire fast-path family:
9556    // `dense_packed_int64_inner_positions`, `typed_wide_two_i64_key_positions`,
9557    // `bounded_composite_multi_i64_key_positions`,
9558    // `typed_wide_multi_i64_key_positions` and the single-key inner/left
9559    // shortcuts, all disabled, plus a `Vec<CompositeJoinKey>` built by reading
9560    // `column.values()[row]` — 32 B/elem of `Scalar` spine and a `SmallVec` per
9561    // row — on both sides.
9562    //
9563    // A single all-valid Int64 key needs none of that: duplicate detection is
9564    // an `FxHashSet<i64>` over `as_i64_slice`. When that check applies AND
9565    // passes, the merge is free to take exactly the path it would have taken
9566    // with no `validate=` at all, because a passing validation adds nothing to
9567    // the output — it only decides whether the merge is allowed to happen.
9568    //
9569    // Semantics preserved exactly: same messages, same left-before-right
9570    // precedence, same modes checked on the same sides. Moving the check
9571    // earlier is unobservable because nothing between this point and the old
9572    // call site can fail — every fast-path helper in between returns `Option`,
9573    // never `Err`.
9574    let typed_validation_settled = match validate_mode {
9575        Some(mode) => {
9576            typed_validate_merge_cardinality(mode, &left_key_columns, &right_key_columns)?
9577        }
9578        None => false,
9579    };
9580    let validate_allows_fast_positions =
9581        validate_mode_allows_fast_positions(validate_mode) || typed_validation_settled;
9582
9583    if matches!(join_type, JoinType::Inner)
9584        && left_on.len() == 1
9585        && right_on.len() == 1
9586        && !sort
9587        && indicator_name.is_none()
9588        && validate_allows_fast_positions
9589    {
9590        return merge_single_key_inner_unsorted(
9591            left,
9592            right,
9593            left_on,
9594            right_on,
9595            &left_key_columns,
9596            &right_key_columns,
9597            &suffixes,
9598        );
9599    }
9600    if matches!(join_type, JoinType::Left)
9601        && left_on.len() == 1
9602        && right_on.len() == 1
9603        && !sort
9604        && indicator_name.is_none()
9605        && validate_allows_fast_positions
9606        && let Some(right_positions) =
9607            ordered_unique_int64_left_match_positions(left_key_columns[0], right_key_columns[0])
9608    {
9609        return build_single_key_ordered_unique_left_merge_output(
9610            left,
9611            right,
9612            left_on,
9613            right_on,
9614            &right_positions,
9615            &suffixes,
9616        );
9617    }
9618    if matches!(join_type, JoinType::Left)
9619        && left_on.len() == 1
9620        && right_on.len() == 1
9621        && !sort
9622        && indicator_name.is_none()
9623        && validate_allows_fast_positions
9624        && let Some((left_positions, right_positions)) =
9625            temporal_i64_left_positions(left_key_columns[0], right_key_columns[0])
9626    {
9627        return build_single_key_dense_left_merge_output(
9628            left,
9629            right,
9630            left_on,
9631            right_on,
9632            &left_positions,
9633            &right_positions,
9634            &suffixes,
9635        );
9636    }
9637    if matches!(join_type, JoinType::Left)
9638        && left_on.len() == 1
9639        && right_on.len() == 1
9640        && !sort
9641        && indicator_name.is_none()
9642        && validate_allows_fast_positions
9643        && let Some(merged) = build_single_key_dense_cycle_i64_left_merge_output(
9644            left,
9645            right,
9646            left_on,
9647            right_on,
9648            left_key_columns[0],
9649            right_key_columns[0],
9650            &suffixes,
9651        )?
9652    {
9653        return Ok(merged);
9654    }
9655    if matches!(join_type, JoinType::Left)
9656        && left_on.len() == 1
9657        && right_on.len() == 1
9658        && !sort
9659        && indicator_name.is_none()
9660        && validate_allows_fast_positions
9661        && let Some(merged) = build_single_key_dense_i64_inner_merge_output(
9662            left,
9663            right,
9664            left_on,
9665            right_on,
9666            left_key_columns[0],
9667            right_key_columns[0],
9668            FusedInt64MergeOptions {
9669                suffixes: &suffixes,
9670                require_all_left_keys_matched: true,
9671            },
9672        )?
9673    {
9674        return Ok(merged);
9675    }
9676    if matches!(join_type, JoinType::Left)
9677        && left_on.len() == 1
9678        && right_on.len() == 1
9679        && !sort
9680        && indicator_name.is_none()
9681        && validate_allows_fast_positions
9682        && let Some(merged) = build_single_key_dense_i64_left_merge_output(
9683            left,
9684            right,
9685            left_on,
9686            right_on,
9687            left_key_columns[0],
9688            right_key_columns[0],
9689            &suffixes,
9690        )?
9691    {
9692        return Ok(merged);
9693    }
9694    if matches!(join_type, JoinType::Left)
9695        && left_on.len() == 1
9696        && right_on.len() == 1
9697        && !sort
9698        && indicator_name.is_none()
9699        && validate_allows_fast_positions
9700        && let Some((left_positions, right_positions)) =
9701            dense_int64_left_positions(left_key_columns[0], right_key_columns[0])
9702    {
9703        return build_single_key_dense_left_merge_output(
9704            left,
9705            right,
9706            left_on,
9707            right_on,
9708            &left_positions,
9709            &right_positions,
9710            &suffixes,
9711        );
9712    }
9713    if matches!(join_type, JoinType::Left)
9714        && left_on.len() == 1
9715        && right_on.len() == 1
9716        && !sort
9717        && indicator_name.is_none()
9718        && validate_allows_fast_positions
9719        && let Some((left_positions, right_positions)) =
9720            hash_int64_left_positions(left_key_columns[0], right_key_columns[0])
9721    {
9722        return build_single_key_dense_left_merge_output(
9723            left,
9724            right,
9725            left_on,
9726            right_on,
9727            &left_positions,
9728            &right_positions,
9729            &suffixes,
9730        );
9731    }
9732    if matches!(join_type, JoinType::Left)
9733        && left_on.len() == 1
9734        && right_on.len() == 1
9735        && !sort
9736        && indicator_name.is_none()
9737        && validate_allows_fast_positions
9738        && let Some((left_positions, right_positions)) =
9739            contiguous_utf8_left_positions(left_key_columns[0], right_key_columns[0])
9740    {
9741        return build_single_key_dense_left_merge_output(
9742            left,
9743            right,
9744            left_on,
9745            right_on,
9746            &left_positions,
9747            &right_positions,
9748            &suffixes,
9749        );
9750    }
9751    if matches!(join_type, JoinType::Left)
9752        && left_on.len() == 1
9753        && right_on.len() == 1
9754        && !sort
9755        && indicator_name.is_none()
9756        && validate_allows_fast_positions
9757        && let Some((left_positions, right_positions)) =
9758            scalar_utf8_left_positions(left_key_columns[0], right_key_columns[0])
9759    {
9760        return build_single_key_dense_left_merge_output(
9761            left,
9762            right,
9763            left_on,
9764            right_on,
9765            &left_positions,
9766            &right_positions,
9767            &suffixes,
9768        );
9769    }
9770    if matches!(join_type, JoinType::Right)
9771        && left_on.len() == 1
9772        && right_on.len() == 1
9773        && !sort
9774        && indicator_name.is_none()
9775        && validate_allows_fast_positions
9776        && let Some(left_positions) =
9777            ordered_unique_int64_right_match_positions(left_key_columns[0], right_key_columns[0])
9778    {
9779        return build_single_key_ordered_unique_right_merge_output(
9780            left,
9781            right,
9782            left_on,
9783            right_on,
9784            &left_positions,
9785            &suffixes,
9786        );
9787    }
9788    if matches!(join_type, JoinType::Right)
9789        && left_on.len() == 1
9790        && right_on.len() == 1
9791        && !sort
9792        && indicator_name.is_none()
9793        && validate_allows_fast_positions
9794        && let Some(left_positions) = ordered_unique_temporal_i64_right_match_positions(
9795            left_key_columns[0],
9796            right_key_columns[0],
9797        )
9798    {
9799        return build_single_key_ordered_unique_right_merge_output(
9800            left,
9801            right,
9802            left_on,
9803            right_on,
9804            &left_positions,
9805            &suffixes,
9806        );
9807    }
9808    if matches!(join_type, JoinType::Right)
9809        && left_on.len() == 1
9810        && right_on.len() == 1
9811        && !sort
9812        && indicator_name.is_none()
9813        && validate_allows_fast_positions
9814        && let Some(merged) = build_single_key_dense_i64_right_all_matched_merge_output(
9815            left,
9816            right,
9817            left_on,
9818            right_on,
9819            left_key_columns[0],
9820            right_key_columns[0],
9821            &suffixes,
9822        )?
9823    {
9824        return Ok(merged);
9825    }
9826    if matches!(join_type, JoinType::Right)
9827        && left_on.len() == 1
9828        && right_on.len() == 1
9829        && !sort
9830        && indicator_name.is_none()
9831        && validate_allows_fast_positions
9832        && let Some(merged) = build_single_key_dense_i64_right_merge_output(
9833            left,
9834            right,
9835            left_on,
9836            right_on,
9837            left_key_columns[0],
9838            right_key_columns[0],
9839            &suffixes,
9840        )?
9841    {
9842        return Ok(merged);
9843    }
9844    if matches!(join_type, JoinType::Right)
9845        && left_on.len() == 1
9846        && right_on.len() == 1
9847        && !sort
9848        && indicator_name.is_none()
9849        && validate_allows_fast_positions
9850        && let Some((left_positions, right_positions)) =
9851            dense_int64_right_positions(left_key_columns[0], right_key_columns[0])
9852    {
9853        return build_single_key_dense_right_merge_output(
9854            left,
9855            right,
9856            left_on,
9857            right_on,
9858            &left_positions,
9859            &right_positions,
9860            &suffixes,
9861        );
9862    }
9863    if matches!(join_type, JoinType::Outer)
9864        && left_on.len() == 1
9865        && right_on.len() == 1
9866        && !sort
9867        && indicator_name.is_none()
9868        && validate_allows_fast_positions
9869        && let Some((left_positions, right_positions)) =
9870            ordered_unique_temporal_i64_outer_positions(left_key_columns[0], right_key_columns[0])
9871    {
9872        return build_single_key_ordered_unique_outer_merge_output(
9873            left,
9874            right,
9875            left_on,
9876            right_on,
9877            &left_positions,
9878            &right_positions,
9879            &suffixes,
9880        );
9881    }
9882    if matches!(join_type, JoinType::Outer)
9883        && left_on.len() == 1
9884        && right_on.len() == 1
9885        && !sort
9886        && indicator_name.is_none()
9887        && validate_allows_fast_positions
9888        && let Some((left_positions, right_positions)) =
9889            ordered_unique_int64_outer_positions(left_key_columns[0], right_key_columns[0])
9890    {
9891        return build_single_key_ordered_unique_outer_merge_output(
9892            left,
9893            right,
9894            left_on,
9895            right_on,
9896            &left_positions,
9897            &right_positions,
9898            &suffixes,
9899        );
9900    }
9901    if matches!(join_type, JoinType::Outer)
9902        && left_on.len() == 1
9903        && right_on.len() == 1
9904        && !sort
9905        && indicator_name.is_none()
9906        && validate_allows_fast_positions
9907        && let Some(merged) = build_single_key_dense_i64_outer_all_matched_merge_output(
9908            left,
9909            right,
9910            left_on,
9911            right_on,
9912            left_key_columns[0],
9913            right_key_columns[0],
9914            &suffixes,
9915        )?
9916    {
9917        return Ok(merged);
9918    }
9919    if matches!(join_type, JoinType::Outer)
9920        && left_on.len() == 1
9921        && right_on.len() == 1
9922        && !sort
9923        && indicator_name.is_none()
9924        && validate_allows_fast_positions
9925        && let Some(merged) = build_single_key_dense_i64_outer_merge_output(
9926            left,
9927            right,
9928            left_on,
9929            right_on,
9930            left_key_columns[0],
9931            right_key_columns[0],
9932            &suffixes,
9933        )?
9934    {
9935        return Ok(merged);
9936    }
9937    if matches!(join_type, JoinType::Outer)
9938        && left_on.len() == 1
9939        && right_on.len() == 1
9940        && !sort
9941        && indicator_name.is_none()
9942        && validate_allows_fast_positions
9943        && let Some((left_positions, right_positions)) =
9944            dense_int64_outer_positions(left_key_columns[0], right_key_columns[0])
9945    {
9946        return build_single_key_ordered_unique_outer_merge_output(
9947            left,
9948            right,
9949            left_on,
9950            right_on,
9951            &left_positions,
9952            &right_positions,
9953            &suffixes,
9954        );
9955    }
9956    if matches!(join_type, JoinType::Outer)
9957        && left_on.len() == 1
9958        && right_on.len() == 1
9959        && !sort
9960        && indicator_name.is_none()
9961        && validate_allows_fast_positions
9962        && let Some((left_positions, right_positions)) =
9963            hash_int64_outer_positions(left_key_columns[0], right_key_columns[0])
9964    {
9965        return build_single_key_ordered_unique_outer_merge_output(
9966            left,
9967            right,
9968            left_on,
9969            right_on,
9970            &left_positions,
9971            &right_positions,
9972            &suffixes,
9973        );
9974    }
9975    if matches!(join_type, JoinType::Outer)
9976        && left_on.len() == 1
9977        && right_on.len() == 1
9978        && !sort
9979        && indicator_name.is_none()
9980        && validate_allows_fast_positions
9981        && let Some(merged) = build_single_key_fixed_decimal_utf8_outer_all_matched_merge_output(
9982            left,
9983            right,
9984            left_on,
9985            right_on,
9986            left_key_columns[0],
9987            right_key_columns[0],
9988            &suffixes,
9989        )?
9990    {
9991        return Ok(merged);
9992    }
9993    if matches!(join_type, JoinType::Outer)
9994        && left_on.len() == 1
9995        && right_on.len() == 1
9996        && !sort
9997        && indicator_name.is_none()
9998        && validate_allows_fast_positions
9999        && let Some((left_positions, right_positions)) =
10000            contiguous_utf8_outer_positions(left_key_columns[0], right_key_columns[0])
10001    {
10002        return build_single_key_ordered_unique_outer_merge_output(
10003            left,
10004            right,
10005            left_on,
10006            right_on,
10007            &left_positions,
10008            &right_positions,
10009            &suffixes,
10010        );
10011    }
10012    if matches!(join_type, JoinType::Outer)
10013        && left_on.len() == 1
10014        && right_on.len() == 1
10015        && !sort
10016        && indicator_name.is_none()
10017        && validate_allows_fast_positions
10018        && let Some((left_positions, right_positions)) =
10019            scalar_utf8_outer_positions(left_key_columns[0], right_key_columns[0])
10020    {
10021        return build_single_key_ordered_unique_outer_merge_output(
10022            left,
10023            right,
10024            left_on,
10025            right_on,
10026            &left_positions,
10027            &right_positions,
10028            &suffixes,
10029        );
10030    }
10031
10032    let needs_key_order = sort || matches!(join_type, JoinType::Outer);
10033
10034    // Hash-free fast path: a plain inner join on all-valid bounded-Int64 key
10035    // column(s) packs the composite key into one i64 and runs the dense CSR
10036    // core, skipping CompositeJoinKey materialization + FxHashMap build/probe.
10037    // Gated to inner joins with no sort/indicator/enforcing validate, where the
10038    // emitted (left,right) pairs are byte-for-byte identical to the hash path.
10039    let packed_inner = if matches!(join_type, JoinType::Inner)
10040        && !sort
10041        && validate_allows_fast_positions
10042        && indicator_name.is_none()
10043    {
10044        dense_packed_int64_inner_positions(&left_key_columns, &right_key_columns)
10045    } else {
10046        None
10047    };
10048
10049    // Typed wide 2-i64-key INNER/LEFT positions (bypasses the Scalar composite
10050    // path when a component is too wide for the packed dense gate). Same fast-path
10051    // gates as packed_inner (no sort/indicator, validate allows fast positions).
10052    let typed_two_key = if !sort
10053        && indicator_name.is_none()
10054        && validate_allows_fast_positions
10055        && packed_inner.is_none()
10056    {
10057        typed_wide_two_i64_key_positions(join_type, &left_key_columns, &right_key_columns)
10058    } else {
10059        None
10060    };
10061
10062    // Typed K-key (K >= 3) BOUNDED-Int64 INNER/LEFT positions: pack the composite
10063    // into one i64 + single-key i64 hash merge, skipping the K per-column
10064    // factorization maps the factorize path below builds (3-key merge was
10065    // 0.43-0.57x pandas — the khash floor of those maps). Same fast-path gates.
10066    let composite_multi_key = if !sort
10067        && indicator_name.is_none()
10068        && validate_allows_fast_positions
10069        && packed_inner.is_none()
10070        && typed_two_key.is_none()
10071    {
10072        bounded_composite_multi_i64_key_positions(join_type, &left_key_columns, &right_key_columns)
10073    } else {
10074        None
10075    };
10076
10077    // Typed general K-key (K >= 3) wide-Int64 positions: factorize-to-gid + u128
10078    // pack, bypassing the Scalar collect_composite_keys path. Same fast-path gates.
10079    let typed_multi_key = if !sort
10080        && indicator_name.is_none()
10081        && validate_allows_fast_positions
10082        && packed_inner.is_none()
10083        && typed_two_key.is_none()
10084        && composite_multi_key.is_none()
10085    {
10086        typed_wide_multi_i64_key_positions(join_type, &left_key_columns, &right_key_columns)
10087    } else {
10088        None
10089    };
10090
10091    let (left_positions, right_positions, _out_row_keys): MergeRowPositions =
10092        if let Some((lp, rp)) = packed_inner {
10093            (
10094                lp.into_iter().map(Some).collect(),
10095                rp.into_iter().map(Some).collect(),
10096                None,
10097            )
10098        } else if let Some(typed) = typed_two_key {
10099            typed
10100        } else if let Some(typed) = composite_multi_key {
10101            typed
10102        } else if let Some(typed) = typed_multi_key {
10103            typed
10104        } else {
10105            // Convert key columns to hashable composite keys.
10106            let left_keys = collect_composite_keys(&left_key_columns);
10107            let right_keys = collect_composite_keys(&right_key_columns);
10108            // Skip when the typed checker above already enforced this mode
10109            // (br-frankenpandas-uza04) — re-running it here would be a second
10110            // full pass over both key sides for an answer already known. A
10111            // shape the typed checker declined still lands here and is checked
10112            // exactly as before.
10113            if let Some(validate_mode) = validate_mode
10114                && !typed_validation_settled
10115            {
10116                validate_merge_cardinality(validate_mode, &left_keys, &right_keys)?;
10117            }
10118
10119            // Build only the probe maps required by the selected join direction.
10120            let right_map = if matches!(
10121                join_type,
10122                JoinType::Inner | JoinType::Left | JoinType::Outer | JoinType::Right
10123            ) {
10124                let mut m =
10125                    FxHashMap::<&CompositeJoinKey, JoinPositionBucket>::with_capacity_and_hasher(
10126                        right_keys.len(),
10127                        Default::default(),
10128                    );
10129                for (pos, key) in right_keys.iter().enumerate() {
10130                    m.entry(key).or_default().push(pos);
10131                }
10132                Some(m)
10133            } else {
10134                None
10135            };
10136
10137            // Right no longer needs a left_map: its branch below probes the small
10138            // right_map with a single left pass (O(right) build, not O(left)).
10139            let left_map = if matches!(join_type, JoinType::Outer) {
10140                let mut m =
10141                    FxHashMap::<&CompositeJoinKey, JoinPositionBucket>::with_capacity_and_hasher(
10142                        left_keys.len(),
10143                        Default::default(),
10144                    );
10145                for (pos, key) in left_keys.iter().enumerate() {
10146                    m.entry(key).or_default().push(pos);
10147                }
10148                Some(m)
10149            } else {
10150                None
10151            };
10152
10153            // Compute row position mappings.
10154            let row_capacity = match join_type {
10155                JoinType::Inner => left_keys.len().min(right_keys.len()),
10156                JoinType::Left => left_keys.len(),
10157                JoinType::Right => right_keys.len(),
10158                JoinType::Outer => left_keys.len().saturating_add(right_keys.len()),
10159                JoinType::Cross => left_keys.len().saturating_mul(right_keys.len()),
10160            };
10161            let mut left_positions = Vec::<Option<usize>>::with_capacity(row_capacity);
10162            let mut right_positions = Vec::<Option<usize>>::with_capacity(row_capacity);
10163            // No longer materialized: the post-position sort reads each row's key by
10164            // reference from left_keys/right_keys via its position, so the per-row
10165            // push_merge_row_key calls below no-op (no String-owning key clones).
10166            let mut out_row_keys: Option<Vec<CompositeJoinKey>> = None;
10167
10168            match join_type {
10169                JoinType::Inner | JoinType::Left | JoinType::Outer => {
10170                    let right_map = right_map
10171                        .as_ref()
10172                        .expect("right_map required for Inner, Left, and Outer joins");
10173                    for (left_pos, key) in left_keys.iter().enumerate() {
10174                        if let Some(matches) = right_map.get(key) {
10175                            for &right_pos in matches {
10176                                push_merge_row_key(&mut out_row_keys, key);
10177                                left_positions.push(Some(left_pos));
10178                                right_positions.push(Some(right_pos));
10179                            }
10180                            continue;
10181                        }
10182
10183                        if matches!(join_type, JoinType::Left | JoinType::Outer) {
10184                            push_merge_row_key(&mut out_row_keys, key);
10185                            left_positions.push(Some(left_pos));
10186                            right_positions.push(None);
10187                        }
10188                    }
10189
10190                    if matches!(join_type, JoinType::Outer) {
10191                        let left_map = left_map.as_ref().expect("left_map required for Outer join");
10192                        for (right_pos, key) in right_keys.iter().enumerate() {
10193                            if !left_map.contains_key(key) {
10194                                push_merge_row_key(&mut out_row_keys, key);
10195                                left_positions.push(None);
10196                                right_positions.push(Some(right_pos));
10197                            }
10198                        }
10199                    }
10200                }
10201                JoinType::Right => {
10202                    // Probe the SMALL right_map with a single left pass instead of
10203                    // building a left_map over every left row (the prior path —
10204                    // O(left) hash build; for a 1M⋈10k merge that was ~2.4x slower
10205                    // than the symmetric Left join). Bucket each matching left
10206                    // position under its right row; `left_by_right[r]` collects in
10207                    // left-iteration order, and we then emit right rows in order —
10208                    // byte-for-byte identical (left,right) pairs to the left_map
10209                    // path (right-row order outer, left-position order inner),
10210                    // including duplicate right keys and unmatched right rows.
10211                    let right_map = right_map
10212                        .as_ref()
10213                        .expect("right_map required for Right join");
10214                    let mut left_by_right: Vec<Vec<usize>> = vec![Vec::new(); right_keys.len()];
10215                    for (left_pos, key) in left_keys.iter().enumerate() {
10216                        if let Some(right_rows) = right_map.get(key) {
10217                            for &right_pos in right_rows {
10218                                left_by_right[right_pos].push(left_pos);
10219                            }
10220                        }
10221                    }
10222                    for (right_pos, key) in right_keys.iter().enumerate() {
10223                        let lefts = &left_by_right[right_pos];
10224                        if lefts.is_empty() {
10225                            push_merge_row_key(&mut out_row_keys, key);
10226                            left_positions.push(None);
10227                            right_positions.push(Some(right_pos));
10228                        } else {
10229                            for &left_pos in lefts {
10230                                push_merge_row_key(&mut out_row_keys, key);
10231                                left_positions.push(Some(left_pos));
10232                                right_positions.push(Some(right_pos));
10233                            }
10234                        }
10235                    }
10236                }
10237                JoinType::Cross => {
10238                    return Err(JoinError::Frame(FrameError::CompatibilityRejected(
10239                        "cross join must be handled by merge_dataframes_cross".to_owned(),
10240                    )));
10241                }
10242            }
10243
10244            // Sort the output rows by join key in-place while left_keys/right_keys
10245            // are in scope (read by reference per row — no out_row_keys clone).
10246            if needs_key_order {
10247                sort_merge_rows_by_join_keys(
10248                    &left_keys,
10249                    &right_keys,
10250                    &mut left_positions,
10251                    &mut right_positions,
10252                );
10253            }
10254            (left_positions, right_positions, out_row_keys)
10255        };
10256
10257    let all_positions_present = matches!(join_type, JoinType::Inner)
10258        || (matches!(
10259            join_type,
10260            JoinType::Left | JoinType::Right | JoinType::Outer
10261        ) && left_positions.iter().all(Option::is_some)
10262            && right_positions.iter().all(Option::is_some));
10263    let all_present_take_positions = all_positions_present.then(|| {
10264        let left = left_positions
10265            .iter()
10266            .map(|position| position.expect("all-present join emits left positions for every row"))
10267            .collect::<Vec<_>>();
10268        let right = right_positions
10269            .iter()
10270            .map(|position| position.expect("all-present join emits right positions for every row"))
10271            .collect::<Vec<_>>();
10272        (left, right)
10273    });
10274    let all_present_left_positions = all_present_take_positions
10275        .as_ref()
10276        .map(|(positions, _)| positions.as_slice());
10277    let all_present_right_positions = all_present_take_positions
10278        .as_ref()
10279        .map(|(_, positions)| positions.as_slice());
10280
10281    // Build output columns by reindexing.
10282    let n = left_positions.len();
10283    // Lazy unit-range output index (see build_single_key_dense_i64 site).
10284    let index = Index::new_known_unique_int64_unit_range(0, n);
10285    let mut columns = ColumnStore::new();
10286    let mut column_order: Vec<String> = Vec::new();
10287
10288    // Collect column names to handle conflicts.
10289    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
10290    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
10291    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
10292    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
10293
10294    // Track positional pairs where left_on[i] and right_on[i] share the same key name.
10295    let mut shared_name_positions = HashMap::<&str, (usize, usize)>::new();
10296    for (idx, (left_key_name, right_key_name)) in left_on.iter().zip(right_on.iter()).enumerate() {
10297        if left_key_name == right_key_name {
10298            shared_name_positions.insert(*left_key_name, (idx, idx));
10299        }
10300    }
10301    let shared_key_names = shared_name_positions
10302        .keys()
10303        .copied()
10304        .collect::<HashSet<&str>>();
10305    let overlapping_names =
10306        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
10307    ensure_merge_suffixes_for_overlaps(&overlapping_names, &suffixes)?;
10308
10309    // Add left columns (including left key columns) in the left frame's own
10310    // column order (pandas preserves it; the BTreeMap would re-sort) — br-691lh.
10311    for name in left.column_names() {
10312        let col = left
10313            .columns()
10314            .get(name)
10315            .expect("left column listed in column_names must exist");
10316        if left_key_name_set.contains(name.as_str()) {
10317            if let Some((left_key_idx, right_key_idx)) = shared_name_positions.get(name.as_str()) {
10318                // Shared key name: for rows emitted from right-only keys, source key values from
10319                // the right frame instead of leaving them null.
10320                let left_key_col = left_key_columns[*left_key_idx];
10321                let key_column = if let Some(positions) = all_present_left_positions {
10322                    take_positions_typed(left_key_col, positions)
10323                } else {
10324                    let right_key_col = right_key_columns[*right_key_idx];
10325                    coalesce_utf8_contiguous_key_column(
10326                        left_key_col,
10327                        right_key_col,
10328                        &left_positions,
10329                        &right_positions,
10330                    )
10331                    .map(Ok)
10332                    .unwrap_or_else(|| {
10333                        let values = left_positions
10334                            .iter()
10335                            .zip(right_positions.iter())
10336                            .map(|(left_pos, right_pos)| match (left_pos, right_pos) {
10337                                (Some(pos), _) => left_key_col.values()[*pos].clone(),
10338                                (None, Some(pos)) => right_key_col.values()[*pos].clone(),
10339                                (None, None) => fp_types::Scalar::Null(fp_types::NullKind::Null),
10340                            })
10341                            .collect::<Vec<_>>();
10342                        Column::from_values(values)
10343                    })?
10344                };
10345                insert_merged_output_column(
10346                    &mut columns,
10347                    &mut column_order,
10348                    name.clone(),
10349                    key_column,
10350                )?;
10351            } else {
10352                let key_column = if let Some(positions) = all_present_left_positions {
10353                    take_positions_typed(col, positions)
10354                } else {
10355                    reindex_join_column_with_invented_gap(col, &left_positions)?
10356                };
10357                insert_merged_output_column(
10358                    &mut columns,
10359                    &mut column_order,
10360                    name.clone(),
10361                    key_column,
10362                )?;
10363            }
10364            continue;
10365        }
10366        let reindexed = if let Some(positions) = all_present_left_positions {
10367            take_positions_typed(col, positions)
10368        } else {
10369            reindex_join_column_with_invented_gap(col, &left_positions)?
10370        };
10371        let out_name = if right_col_names.contains(name) {
10372            apply_merge_suffix(name, suffixes.left.as_deref())
10373        } else {
10374            name.clone()
10375        };
10376        insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
10377    }
10378
10379    // Add right non-key columns in the right frame's own column order — br-691lh.
10380    for name in right.column_names() {
10381        let col = right
10382            .columns()
10383            .get(name)
10384            .expect("right column listed in column_names must exist");
10385        if right_key_name_set.contains(name.as_str())
10386            && shared_name_positions.contains_key(name.as_str())
10387        {
10388            // Shared same-name key already emitted from the left side.
10389            continue;
10390        }
10391        let reindexed = if let Some(positions) = all_present_right_positions {
10392            take_positions_typed(col, positions)
10393        } else {
10394            reindex_join_column_with_invented_gap(col, &right_positions)?
10395        };
10396        let out_name = if left_col_names.contains(name) {
10397            apply_merge_suffix(name, suffixes.right.as_deref())
10398        } else {
10399            name.clone()
10400        };
10401        insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
10402    }
10403
10404    if let Some(indicator_name) = indicator_name.as_deref() {
10405        ensure_indicator_name_available(
10406            indicator_name,
10407            &left_col_names,
10408            &right_col_names,
10409            &columns,
10410        )?;
10411        let indicator_col = build_merge_indicator_column(&left_positions, &right_positions)?;
10412        insert_merged_output_column(
10413            &mut columns,
10414            &mut column_order,
10415            indicator_name.to_owned(),
10416            indicator_col,
10417        )?;
10418    }
10419
10420    Ok(MergedDataFrame {
10421        index,
10422        columns,
10423        column_order,
10424    })
10425}
10426
10427/// Merge two DataFrames on one or more key columns with identical key names.
10428///
10429/// Matches `pd.merge(left, right, on=keys, how=join_type)`.
10430pub fn merge_dataframes_on(
10431    left: &fp_frame::DataFrame,
10432    right: &fp_frame::DataFrame,
10433    on: &[&str],
10434    join_type: JoinType,
10435) -> Result<MergedDataFrame, JoinError> {
10436    merge_dataframes_on_with(left, right, on, on, join_type)
10437}
10438
10439/// Merge two DataFrames on a single key column.
10440pub fn merge_dataframes(
10441    left: &fp_frame::DataFrame,
10442    right: &fp_frame::DataFrame,
10443    on: &str,
10444    join_type: JoinType,
10445) -> Result<MergedDataFrame, JoinError> {
10446    if matches!(join_type, JoinType::Inner) {
10447        let left_key = left.column(on).ok_or_else(|| {
10448            JoinError::Frame(FrameError::CompatibilityRejected(format!(
10449                "left DataFrame missing key column '{on}'"
10450            )))
10451        })?;
10452        let right_key = right.column(on).ok_or_else(|| {
10453            JoinError::Frame(FrameError::CompatibilityRejected(format!(
10454                "right DataFrame missing key column '{on}'"
10455            )))
10456        })?;
10457        validate_object_join_keys(left_key)?;
10458        validate_object_join_keys(right_key)?;
10459        let suffixes = ResolvedMergeSuffixes::default();
10460        return merge_single_key_inner_unsorted(
10461            left,
10462            right,
10463            &[on],
10464            &[on],
10465            &[left_key],
10466            &[right_key],
10467            &suffixes,
10468        );
10469    }
10470    merge_dataframes_on(left, right, &[on], join_type)
10471}
10472
10473fn merge_dataframes_cross(
10474    left: &fp_frame::DataFrame,
10475    right: &fp_frame::DataFrame,
10476    indicator_name: Option<&str>,
10477    suffixes: &ResolvedMergeSuffixes,
10478) -> Result<MergedDataFrame, JoinError> {
10479    let left_rows = left.index().len();
10480    let right_rows = right.index().len();
10481    let out_rows = left_rows.saturating_mul(right_rows);
10482
10483    let mut left_positions = Vec::<Option<usize>>::with_capacity(out_rows);
10484    let mut right_positions = Vec::<Option<usize>>::with_capacity(out_rows);
10485    for left_pos in 0..left_rows {
10486        for right_pos in 0..right_rows {
10487            left_positions.push(Some(left_pos));
10488            right_positions.push(Some(right_pos));
10489        }
10490    }
10491
10492    let index = Index::new((0..out_rows as i64).map(IndexLabel::from).collect());
10493    let mut columns = ColumnStore::new();
10494    let mut column_order: Vec<String> = Vec::new();
10495
10496    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
10497    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
10498    let overlapping_names =
10499        collect_overlapping_column_names(&left_col_names, &right_col_names, &HashSet::new());
10500    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
10501
10502    // Each side's columns in its own order, as pandas (the store iterates
10503    // them by name, so the right side's came back sorted; buwrx).
10504    for position in 0..left.num_columns() {
10505        let (Some(name), Some(col)) = (left.column_name_at(position), left.column_at(position))
10506        else {
10507            continue;
10508        };
10509        let reindexed = col.reindex_by_positions(&left_positions)?;
10510        let out_name = if right_col_names.contains(&name) {
10511            apply_merge_suffix(&name, suffixes.left.as_deref())
10512        } else {
10513            name
10514        };
10515        insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
10516    }
10517
10518    for position in 0..right.num_columns() {
10519        let (Some(name), Some(col)) = (right.column_name_at(position), right.column_at(position))
10520        else {
10521            continue;
10522        };
10523        let reindexed = col.reindex_by_positions(&right_positions)?;
10524        let out_name = if left_col_names.contains(&name) {
10525            apply_merge_suffix(&name, suffixes.right.as_deref())
10526        } else {
10527            name
10528        };
10529        insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
10530    }
10531
10532    if let Some(indicator_name) = indicator_name {
10533        ensure_indicator_name_available(
10534            indicator_name,
10535            &left_col_names,
10536            &right_col_names,
10537            &columns,
10538        )?;
10539        let indicator_col = build_merge_indicator_column(&left_positions, &right_positions)?;
10540        insert_merged_output_column(
10541            &mut columns,
10542            &mut column_order,
10543            indicator_name.to_owned(),
10544            indicator_col,
10545        )?;
10546    }
10547
10548    Ok(MergedDataFrame {
10549        index,
10550        columns,
10551        column_order,
10552    })
10553}
10554
10555/// Extension trait adding `.merge()` and `.join()` instance methods to `DataFrame`.
10556///
10557/// Import this trait to get pandas-style `df.merge(other, ...)` and `df.join(other, ...)`
10558/// as instance methods.
10559pub trait DataFrameMergeExt {
10560    /// Merge this DataFrame with another on shared key columns.
10561    ///
10562    /// Matches `pd.DataFrame.merge(other, on=keys, how=join_type)`.
10563    fn merge(
10564        &self,
10565        other: &fp_frame::DataFrame,
10566        on: &[&str],
10567        how: JoinType,
10568    ) -> Result<MergedDataFrame, JoinError>;
10569
10570    /// Merge with separate left/right key columns and execution options.
10571    ///
10572    /// Matches `pd.DataFrame.merge(other, left_on=..., right_on=..., how=...)`.
10573    fn merge_with_options(
10574        &self,
10575        other: &fp_frame::DataFrame,
10576        left_on: &[&str],
10577        right_on: &[&str],
10578        how: JoinType,
10579        options: MergeExecutionOptions,
10580    ) -> Result<MergedDataFrame, JoinError>;
10581
10582    /// Join another DataFrame on the index.
10583    ///
10584    /// Matches `pd.DataFrame.join(other, how=join_type)` (index-based join).
10585    fn join_on_index(
10586        &self,
10587        other: &fp_frame::DataFrame,
10588        how: JoinType,
10589    ) -> Result<MergedDataFrame, JoinError>;
10590
10591    /// pandas-named alias for [`Self::join_on_index`]. Matches
10592    /// `pd.DataFrame.join(other, how=...)` directly. Per br-frankenpandas-nk54a.
10593    ///
10594    /// Default impl delegates to `join_on_index`. Implementors that already
10595    /// have an optimized index-based join can leave this default.
10596    fn join(
10597        &self,
10598        other: &fp_frame::DataFrame,
10599        how: JoinType,
10600    ) -> Result<MergedDataFrame, JoinError> {
10601        self.join_on_index(other, how)
10602    }
10603
10604    /// Perform an asof merge (nearest-match join) on a sorted key column.
10605    ///
10606    /// Matches `pd.merge_asof(left, right, on=key)`. Both DataFrames must
10607    /// be sorted by the key column. For each row in `left`, finds the last
10608    /// row in `right` where `right[on] <= left[on]` (backward direction)
10609    /// or the nearest row in the specified direction.
10610    ///
10611    /// `direction`: "backward" (default), "forward", "nearest".
10612    fn merge_asof(
10613        &self,
10614        other: &fp_frame::DataFrame,
10615        on: &str,
10616        direction: &str,
10617    ) -> Result<MergedDataFrame, JoinError>;
10618
10619    /// Perform an asof merge with additional options.
10620    ///
10621    /// Matches `pd.merge_asof(left, right, on=key, direction=...,
10622    /// allow_exact_matches=..., tolerance=..., by=...)`.
10623    ///
10624    /// # Parameters
10625    /// - `other`: Right DataFrame to merge with
10626    /// - `on`: Column name to merge on (must be numeric and sorted)
10627    /// - `direction`: "backward", "forward", or "nearest"
10628    /// - `options`: Additional options (allow_exact_matches, tolerance, by)
10629    fn merge_asof_with_options(
10630        &self,
10631        other: &fp_frame::DataFrame,
10632        on: &str,
10633        direction: &str,
10634        options: MergeAsofOptions,
10635    ) -> Result<MergedDataFrame, JoinError>;
10636
10637    /// Perform an ordered merge (outer join + sort by keys).
10638    ///
10639    /// Matches `pd.merge_ordered(left, right, on=keys, fill_method=...)`.
10640    fn merge_ordered(
10641        &self,
10642        other: &fp_frame::DataFrame,
10643        on: &[&str],
10644        fill_method: Option<&str>,
10645    ) -> Result<MergedDataFrame, JoinError>;
10646}
10647
10648/// Perform an ordered merge of two DataFrames.
10649///
10650/// Matches `pd.merge_ordered(left, right, on=keys, fill_method=...)`.
10651/// Performs an outer join and ensures the result is sorted by the join keys.
10652pub fn merge_ordered(
10653    left: &fp_frame::DataFrame,
10654    right: &fp_frame::DataFrame,
10655    on: &[&str],
10656    fill_method: Option<&str>,
10657) -> Result<MergedDataFrame, JoinError> {
10658    let options = MergeExecutionOptions {
10659        sort: true,
10660        ..MergeExecutionOptions::default()
10661    };
10662    let merged = merge_dataframes_on_with_options(left, right, on, on, JoinType::Outer, options)?;
10663
10664    if let Some(method) = fill_method {
10665        // Convert to DataFrame to apply fill
10666        let mut df = fp_frame::DataFrame::new_with_column_order(
10667            merged.index.clone(),
10668            merged.columns.clone(),
10669            merged.column_order.clone(),
10670        )
10671        .map_err(JoinError::Frame)?;
10672
10673        df = match method {
10674            "ffill" => df.ffill(None).map_err(JoinError::Frame)?,
10675            _ => {
10676                return Err(JoinError::Frame(FrameError::CompatibilityRejected(
10677                    format!("merge_ordered: fill_method must be 'ffill' or None, got '{method}'"),
10678                )));
10679            }
10680        };
10681        // pandas forward-fills the join's row indexers, not the values: a
10682        // column the fill leaves whole keeps its side's dtype (an int
10683        // column stayed float64 after the outer join's NaN), one with a
10684        // leading gap is still float64 NaN there.
10685        let names: Vec<String> = df.column_names().into_iter().cloned().collect();
10686        for name in names {
10687            let Some(source) = source_column_dtype(left, right, &name) else {
10688                continue;
10689            };
10690            let Some(filled) = df.column(&name) else {
10691                continue;
10692            };
10693            if filled.dtype() != source
10694                && matches!(source, DType::Int64 | DType::Bool)
10695                && !filled.values().iter().any(Scalar::is_missing)
10696            {
10697                let restored = filled.astype(source).map_err(|err| {
10698                    JoinError::Frame(FrameError::CompatibilityRejected(err.to_string()))
10699                })?;
10700                df = df.with_column(name, restored).map_err(JoinError::Frame)?;
10701            }
10702        }
10703
10704        let column_order = df.column_names().into_iter().cloned().collect();
10705        Ok(MergedDataFrame {
10706            index: df.index().clone(),
10707            columns: df.columns().clone(),
10708            column_order,
10709        })
10710    } else {
10711        Ok(merged)
10712    }
10713}
10714
10715/// The dtype of the input column a merged column `name` came from: the
10716/// left's or the right's of that name, else (an overlap) the left's for a
10717/// `_x` suffix and the right's for a `_y` one.
10718fn source_column_dtype(
10719    left: &fp_frame::DataFrame,
10720    right: &fp_frame::DataFrame,
10721    name: &str,
10722) -> Option<DType> {
10723    let dtype = |frame: &fp_frame::DataFrame, name: &str| frame.column(name).map(Column::dtype);
10724    match (left.column(name), right.column(name)) {
10725        (Some(column), None) | (None, Some(column)) => Some(column.dtype()),
10726        (Some(_), Some(_)) => None,
10727        (None, None) => name
10728            .strip_suffix("_x")
10729            .and_then(|stem| dtype(left, stem))
10730            .or_else(|| name.strip_suffix("_y").and_then(|stem| dtype(right, stem))),
10731    }
10732}
10733
10734/// Direction for asof merge matching.
10735#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10736pub enum AsofDirection {
10737    Backward,
10738    Forward,
10739    Nearest,
10740}
10741
10742/// Options for asof merge operations.
10743///
10744/// Matches pandas `merge_asof` parameters:
10745/// - `allow_exact_matches`: If true (default), allow matching with same key value
10746/// - `tolerance`: Maximum distance between keys for a match
10747/// - `by`: Columns to match exactly before asof matching
10748#[derive(Debug, Clone, Default)]
10749pub struct MergeAsofOptions {
10750    /// If true (default), allow matching with the same 'on' value.
10751    /// If false, don't match rows where left key == right key exactly.
10752    pub allow_exact_matches: bool,
10753    /// Maximum distance between left and right keys for a valid match.
10754    /// None means no tolerance limit.
10755    pub tolerance: Option<f64>,
10756    /// Columns to match exactly before performing asof merge.
10757    /// Acts like an equi-join on these columns first.
10758    pub by: Option<Vec<String>>,
10759}
10760
10761impl MergeAsofOptions {
10762    /// Create options with defaults matching pandas behavior.
10763    pub fn new() -> Self {
10764        Self {
10765            allow_exact_matches: true,
10766            tolerance: None,
10767            by: None,
10768        }
10769    }
10770
10771    /// Set whether exact matches are allowed.
10772    pub fn allow_exact_matches(mut self, allow: bool) -> Self {
10773        self.allow_exact_matches = allow;
10774        self
10775    }
10776
10777    /// Set the tolerance for matching.
10778    pub fn tolerance(mut self, tol: f64) -> Self {
10779        self.tolerance = Some(tol);
10780        self
10781    }
10782
10783    /// Set the columns to match exactly before asof merge.
10784    pub fn by(mut self, cols: Vec<String>) -> Self {
10785        self.by = Some(cols);
10786        self
10787    }
10788}
10789
10790/// When BOTH `on` keys are Datetime64, extract them as f64 SHIFTED by the global
10791/// minimum ns so the values fit f64's 2^53 integer precision exactly. A raw
10792/// Datetime64->ns->f64 cast collapses ns (~1.6e18) to garbage (>2^53), so
10793/// merge_asof previously REJECTED datetime keys ("must be numeric") — the primary
10794/// time-series asof case. Shifting is order- and difference-preserving (both sides
10795/// by the same min), so the f64 asof match + tolerance stay exact whenever the ns
10796/// RANGE fits 2^53 (~104 days). Returns:
10797/// - `None`: not both Datetime64 → caller uses the f64 numeric path unchanged.
10798/// - `Some(Err)`: range too wide for exact f64 → clean rejection (better than the
10799///   silently-wrong result a lossy cast would give).
10800/// - `Some(Ok((left,right)))`: shifted f64 keys, NaT/null → NaN.
10801type ShiftedDatetimeAsofKeys = (Vec<f64>, Vec<f64>);
10802
10803fn try_asof_datetime_shift(
10804    left_key: &Column,
10805    right_key: &Column,
10806    on: &str,
10807) -> Option<Result<ShiftedDatetimeAsofKeys, JoinError>> {
10808    if !matches!(
10809        (left_key.dtype(), right_key.dtype()),
10810        (DType::Datetime64 { tz: left_tz }, DType::Datetime64 { tz: right_tz }) if left_tz == right_tz
10811    ) {
10812        return None;
10813    }
10814    let ld = left_key.as_datetime64_slice()?;
10815    let rd = right_key.as_datetime64_slice()?;
10816    let lv = left_key.validity();
10817    let rv = right_key.validity();
10818    // All-valid fast path: when a side has no null bits, the per-element
10819    // ValidityMask::get bit-test is skipped in both the min-scan and the shift
10820    // (only the cheap NaT sentinel compare remains, which vectorizes). NaT/null
10821    // are rare in an asof `on` key, so this is the hot path.
10822    let l_all = lv.all();
10823    let r_all = rv.all();
10824    let is_valid = |data: &[i64], v: &fp_columnar::ValidityMask, all: bool, i: usize| -> bool {
10825        (all || v.get(i)) && data[i] != fp_types::Timestamp::NAT
10826    };
10827    // Global min/max over the valid (non-NaT) ns of both sides.
10828    let mut lo = i64::MAX;
10829    let mut hi = i64::MIN;
10830    let mut any = false;
10831    for i in 0..ld.len() {
10832        if is_valid(ld, lv, l_all, i) {
10833            lo = lo.min(ld[i]);
10834            hi = hi.max(ld[i]);
10835            any = true;
10836        }
10837    }
10838    for i in 0..rd.len() {
10839        if is_valid(rd, rv, r_all, i) {
10840            lo = lo.min(rd[i]);
10841            hi = hi.max(rd[i]);
10842            any = true;
10843        }
10844    }
10845    if !any {
10846        // All-NaT/empty: every shifted value is NaN; produce that directly.
10847        return Some(Ok((vec![f64::NAN; ld.len()], vec![f64::NAN; rd.len()])));
10848    }
10849    if (hi as i128 - lo as i128) >= (1i128 << 53) {
10850        return Some(Err(JoinError::Frame(FrameError::CompatibilityRejected(
10851            format!(
10852                "merge_asof: Datetime64 key '{on}' spans more than ~104 days of nanoseconds, \
10853             which exceeds f64 asof precision; not yet supported"
10854            ),
10855        ))));
10856    }
10857    let shift = |data: &[i64], v: &fp_columnar::ValidityMask, all: bool| -> Vec<f64> {
10858        (0..data.len())
10859            .map(|i| {
10860                if is_valid(data, v, all, i) {
10861                    (data[i] - lo) as f64
10862                } else {
10863                    f64::NAN
10864                }
10865            })
10866            .collect()
10867    };
10868    Some(Ok((shift(ld, lv, l_all), shift(rd, rv, r_all))))
10869}
10870
10871#[derive(Clone, Copy)]
10872struct Datetime64AsofKey<'a> {
10873    data: &'a [i64],
10874    validity: &'a ValidityMask,
10875    all_valid: bool,
10876}
10877
10878impl Datetime64AsofKey<'_> {
10879    #[inline]
10880    fn is_valid(self, i: usize) -> bool {
10881        (self.all_valid || self.validity.get(i)) && self.data[i] != fp_types::Timestamp::NAT
10882    }
10883}
10884
10885fn datetime64_key_parts(column: &Column) -> Option<Datetime64AsofKey<'_>> {
10886    let data = column.as_datetime64_slice()?;
10887    let validity = column.validity();
10888    Some(Datetime64AsofKey {
10889        data,
10890        validity,
10891        all_valid: validity.all(),
10892    })
10893}
10894
10895fn ensure_sorted_non_decreasing_datetime64(
10896    key: Datetime64AsofKey<'_>,
10897    side: &str,
10898    on: &str,
10899) -> Result<(), JoinError> {
10900    let mut prev: Option<i64> = None;
10901    for i in 0..key.data.len() {
10902        if !key.is_valid(i) {
10903            continue;
10904        }
10905        let value = key.data[i];
10906        if let Some(prev_value) = prev
10907            && value < prev_value
10908        {
10909            return Err(JoinError::Frame(FrameError::CompatibilityRejected(
10910                format!("merge_asof: {side} column '{on}' must be sorted"),
10911            )));
10912        }
10913        prev = Some(value);
10914    }
10915    Ok(())
10916}
10917
10918fn within_datetime64_tolerance(left: i64, right: i64, tolerance: Option<f64>) -> bool {
10919    match tolerance {
10920        Some(tol) => ((left as i128 - right as i128).abs() as f64) <= tol,
10921        None => true,
10922    }
10923}
10924
10925fn compute_asof_matches_datetime64(
10926    left: Datetime64AsofKey<'_>,
10927    right: Datetime64AsofKey<'_>,
10928    direction: AsofDirection,
10929    allow_exact_matches: bool,
10930    tolerance: Option<f64>,
10931) -> Vec<Option<usize>> {
10932    let mut filtered_values = Vec::new();
10933    let mut filtered_positions = Vec::new();
10934    let (right_valid_values, right_valid_positions) =
10935        if right.all_valid && !right.data.contains(&fp_types::Timestamp::NAT) {
10936            (right.data, None)
10937        } else {
10938            for i in 0..right.data.len() {
10939                if right.is_valid(i) {
10940                    filtered_values.push(right.data[i]);
10941                    filtered_positions.push(i);
10942                }
10943            }
10944            (
10945                filtered_values.as_slice(),
10946                Some(filtered_positions.as_slice()),
10947            )
10948        };
10949
10950    compute_asof_matches_datetime64_prepared(
10951        left,
10952        right_valid_values,
10953        right_valid_positions,
10954        direction,
10955        allow_exact_matches,
10956        tolerance,
10957    )
10958}
10959
10960fn compute_asof_matches_datetime64_prepared(
10961    left: Datetime64AsofKey<'_>,
10962    right_valid_values: &[i64],
10963    right_valid_positions: Option<&[usize]>,
10964    direction: AsofDirection,
10965    allow_exact_matches: bool,
10966    tolerance: Option<f64>,
10967) -> Vec<Option<usize>> {
10968    let right_source_position =
10969        |position: usize| right_valid_positions.map_or(position, |positions| positions[position]);
10970
10971    let mut right_matches = Vec::with_capacity(left.data.len());
10972
10973    match direction {
10974        AsofDirection::Backward => {
10975            let mut best: Option<usize> = None;
10976            let mut best_val: Option<i64> = None;
10977            let mut j = 0usize;
10978            for i in 0..left.data.len() {
10979                if !left.is_valid(i) {
10980                    right_matches.push(None);
10981                    continue;
10982                }
10983                let lv = left.data[i];
10984                while j < right_valid_values.len() {
10985                    let rv = right_valid_values[j];
10986                    let should_include = if allow_exact_matches {
10987                        rv <= lv
10988                    } else {
10989                        rv < lv
10990                    };
10991                    if !should_include {
10992                        break;
10993                    }
10994                    best = Some(right_source_position(j));
10995                    best_val = Some(rv);
10996                    j += 1;
10997                }
10998
10999                let matched = match (best, best_val) {
11000                    (Some(idx), Some(rv)) if within_datetime64_tolerance(lv, rv, tolerance) => {
11001                        Some(idx)
11002                    }
11003                    _ => None,
11004                };
11005                right_matches.push(matched);
11006            }
11007        }
11008        AsofDirection::Forward => {
11009            let mut j = 0usize;
11010            for i in 0..left.data.len() {
11011                if !left.is_valid(i) {
11012                    right_matches.push(None);
11013                    continue;
11014                }
11015                let lv = left.data[i];
11016                while j < right_valid_values.len() {
11017                    let rv = right_valid_values[j];
11018                    let should_skip = if allow_exact_matches {
11019                        rv < lv
11020                    } else {
11021                        rv <= lv
11022                    };
11023                    if !should_skip {
11024                        break;
11025                    }
11026                    j += 1;
11027                }
11028
11029                if j < right_valid_values.len() {
11030                    let rv = right_valid_values[j];
11031                    if within_datetime64_tolerance(lv, rv, tolerance) {
11032                        right_matches.push(Some(right_source_position(j)));
11033                    } else {
11034                        right_matches.push(None);
11035                    }
11036                } else {
11037                    right_matches.push(None);
11038                }
11039            }
11040        }
11041        AsofDirection::Nearest => {
11042            for i in 0..left.data.len() {
11043                if !left.is_valid(i) {
11044                    right_matches.push(None);
11045                    continue;
11046                }
11047                if right_valid_values.is_empty() {
11048                    right_matches.push(None);
11049                    continue;
11050                }
11051
11052                let lv = left.data[i];
11053                let (lower, upper) = if allow_exact_matches {
11054                    let lo = right_valid_values.partition_point(|rv| *rv <= lv);
11055                    let up = right_valid_values.partition_point(|rv| *rv < lv);
11056                    (
11057                        if lo > 0 { Some(lo - 1) } else { None },
11058                        if up < right_valid_values.len() {
11059                            Some(up)
11060                        } else {
11061                            None
11062                        },
11063                    )
11064                } else {
11065                    let lo = right_valid_values.partition_point(|rv| *rv < lv);
11066                    let up = right_valid_values.partition_point(|rv| *rv <= lv);
11067                    (
11068                        if lo > 0 { Some(lo - 1) } else { None },
11069                        if up < right_valid_values.len() {
11070                            Some(up)
11071                        } else {
11072                            None
11073                        },
11074                    )
11075                };
11076
11077                let chosen = match (lower, upper) {
11078                    (Some(l), Some(u)) => {
11079                        let lower_dist = (right_valid_values[l] as i128 - lv as i128).abs();
11080                        let upper_dist = (right_valid_values[u] as i128 - lv as i128).abs();
11081                        if upper_dist < lower_dist {
11082                            Some(u)
11083                        } else {
11084                            Some(l)
11085                        }
11086                    }
11087                    (Some(l), None) => Some(l),
11088                    (None, Some(u)) => Some(u),
11089                    (None, None) => None,
11090                };
11091
11092                let matched = match chosen {
11093                    Some(idx)
11094                        if within_datetime64_tolerance(lv, right_valid_values[idx], tolerance) =>
11095                    {
11096                        Some(right_source_position(idx))
11097                    }
11098                    _ => None,
11099                };
11100                right_matches.push(matched);
11101            }
11102        }
11103    }
11104
11105    right_matches
11106}
11107
11108fn try_asof_datetime_matches(
11109    left_key: &Column,
11110    right_key: &Column,
11111    on: &str,
11112    direction: AsofDirection,
11113    allow_exact_matches: bool,
11114    tolerance: Option<f64>,
11115) -> Option<Result<Vec<Option<usize>>, JoinError>> {
11116    if !matches!(
11117        (left_key.dtype(), right_key.dtype()),
11118        (DType::Datetime64 { tz: left_tz }, DType::Datetime64 { tz: right_tz }) if left_tz == right_tz
11119    ) {
11120        return None;
11121    }
11122    let left = datetime64_key_parts(left_key)?;
11123    let right = datetime64_key_parts(right_key)?;
11124
11125    Some((|| {
11126        ensure_sorted_non_decreasing_datetime64(left, "left", on)?;
11127        ensure_sorted_non_decreasing_datetime64(right, "right", on)?;
11128
11129        Ok(compute_asof_matches_datetime64(
11130            left,
11131            right,
11132            direction,
11133            allow_exact_matches,
11134            tolerance,
11135        ))
11136    })())
11137}
11138
11139fn asof_numeric_values(column: &Column, side: &str, on: &str) -> Result<Vec<f64>, JoinError> {
11140    // Typed fast path: an all-valid Int64/Float64 key column reads the raw slice
11141    // directly, skipping the per-cell values() Scalar materialization + to_f64
11142    // dispatch (merge_asof key extraction was ~0.83x pandas). Bit-identical:
11143    // as_i64_slice/as_f64_slice are all-valid (no missing → no NaN-fill branch),
11144    // and Scalar::Int64(v).to_f64() == v as f64, Scalar::Float64(v).to_f64() == v.
11145    // Nullable / Timedelta64 / Datetime64 keys fall through to the Scalar loop.
11146    if let Some(data) = column.as_i64_slice() {
11147        return Ok(data.iter().map(|&v| v as f64).collect());
11148    }
11149    if let Some(data) = column.as_f64_slice() {
11150        return Ok(data.to_vec());
11151    }
11152    let mut out = Vec::with_capacity(column.len());
11153    for value in column.values() {
11154        // pandas merge_asof accepts Timedelta64 (and datetime) `on` columns
11155        // and orders them by ns count. Scalar::Timedelta64.to_f64() returns
11156        // NonNumericValue, so the default branch would reject the join.
11157        // Extract ns directly for non-NaT Timedelta values; treat NaT as NaN
11158        // (matches the ValueIsMissing arm below).
11159        if let Scalar::Timedelta64(ns) = value {
11160            if *ns == fp_types::Timedelta::NAT {
11161                out.push(f64::NAN);
11162            } else {
11163                out.push(*ns as f64);
11164            }
11165            continue;
11166        }
11167        match value.to_f64() {
11168            Ok(v) => out.push(v),
11169            Err(TypeError::ValueIsMissing { .. }) => out.push(f64::NAN),
11170            Err(_) => {
11171                return Err(JoinError::Frame(FrameError::CompatibilityRejected(
11172                    format!("merge_asof: {side} column '{on}' must be numeric"),
11173                )));
11174            }
11175        }
11176    }
11177    Ok(out)
11178}
11179
11180/// `merge_asof` compares ordering keys rather than coercing them to a common
11181/// numeric representation.  Converting both sides to `f64` before validating
11182/// their dtypes makes an `int64` key appear compatible with a `float64` key,
11183/// which pandas rejects even when every finite value is exactly representable.
11184fn ensure_matching_asof_key_dtypes(
11185    left_key: &Column,
11186    right_key: &Column,
11187    on: &str,
11188) -> Result<(), JoinError> {
11189    if left_key.dtype() != right_key.dtype() {
11190        return Err(JoinError::Frame(FrameError::CompatibilityRejected(
11191            format!(
11192                "merge_asof: incompatible merge keys [0] for '{on}': left dtype('{}'), right dtype('{}'), must be the same type",
11193                left_key.dtype().name(),
11194                right_key.dtype().name(),
11195            ),
11196        )));
11197    }
11198    Ok(())
11199}
11200
11201fn ensure_sorted_non_decreasing(values: &[f64], side: &str, on: &str) -> Result<(), JoinError> {
11202    let mut prev: Option<f64> = None;
11203    for &value in values {
11204        if value.is_nan() {
11205            continue;
11206        }
11207        if let Some(prev_value) = prev
11208            && value < prev_value
11209        {
11210            return Err(JoinError::Frame(FrameError::CompatibilityRejected(
11211                format!("merge_asof: {side} column '{on}' must be sorted"),
11212            )));
11213        }
11214        prev = Some(value);
11215    }
11216    Ok(())
11217}
11218
11219/// Perform an asof merge between two DataFrames.
11220pub fn merge_asof(
11221    left: &fp_frame::DataFrame,
11222    right: &fp_frame::DataFrame,
11223    on: &str,
11224    direction: AsofDirection,
11225) -> Result<MergedDataFrame, JoinError> {
11226    merge_asof_with_options(left, right, on, direction, MergeAsofOptions::new())
11227}
11228
11229/// Perform an asof merge between two DataFrames with additional options.
11230///
11231/// # Parameters
11232/// - `left`: Left DataFrame
11233/// - `right`: Right DataFrame
11234/// - `on`: Column name to merge on (must be numeric and sorted)
11235/// - `direction`: Match direction (Backward, Forward, Nearest)
11236/// - `options`: Additional merge options (allow_exact_matches, tolerance, by)
11237pub fn merge_asof_with_options(
11238    left: &fp_frame::DataFrame,
11239    right: &fp_frame::DataFrame,
11240    on: &str,
11241    direction: AsofDirection,
11242    options: MergeAsofOptions,
11243) -> Result<MergedDataFrame, JoinError> {
11244    // If `by` columns are specified, we need to do grouped asof merge
11245    if let Some(ref by_cols) = options.by {
11246        return merge_asof_grouped(left, right, on, direction, &options, by_cols);
11247    }
11248
11249    merge_asof_simple(left, right, on, direction, &options)
11250}
11251
11252/// Simple asof merge without grouping.
11253fn merge_asof_simple(
11254    left: &fp_frame::DataFrame,
11255    right: &fp_frame::DataFrame,
11256    on: &str,
11257    direction: AsofDirection,
11258    options: &MergeAsofOptions,
11259) -> Result<MergedDataFrame, JoinError> {
11260    let left_key = left.columns().get(on).ok_or_else(|| {
11261        JoinError::Frame(FrameError::CompatibilityRejected(format!(
11262            "merge_asof: column '{on}' not found in left"
11263        )))
11264    })?;
11265    let right_key = right.columns().get(on).ok_or_else(|| {
11266        JoinError::Frame(FrameError::CompatibilityRejected(format!(
11267            "merge_asof: column '{on}' not found in right"
11268        )))
11269    })?;
11270
11271    ensure_matching_asof_key_dtypes(left_key, right_key, on)?;
11272
11273    if let Some(datetime_matches) = try_asof_datetime_matches(
11274        left_key,
11275        right_key,
11276        on,
11277        direction,
11278        options.allow_exact_matches,
11279        options.tolerance,
11280    ) {
11281        let right_matches = datetime_matches?;
11282        return build_asof_output(left, right, on, &right_matches, None);
11283    }
11284
11285    // Non-Datetime64 keys: use the f64 numeric path. The grouped Datetime64
11286    // route below still uses the old shift-to-f64 bridge until it gets its own
11287    // i64 grouped path.
11288    let (left_vals, right_vals) = match try_asof_datetime_shift(left_key, right_key, on) {
11289        Some(shifted) => shifted?,
11290        None => (
11291            asof_numeric_values(left_key, "left", on)?,
11292            asof_numeric_values(right_key, "right", on)?,
11293        ),
11294    };
11295
11296    // With matching key dtypes, pandas accepts NaN keys: the NaN row gets a
11297    // null in the joined columns (no match). Dtype incompatibility is rejected
11298    // above before this value-level rule is reached.
11299    ensure_sorted_non_decreasing(&left_vals, "left", on)?;
11300    ensure_sorted_non_decreasing(&right_vals, "right", on)?;
11301
11302    let right_matches = compute_asof_matches(
11303        &left_vals,
11304        &right_vals,
11305        direction,
11306        options.allow_exact_matches,
11307        options.tolerance,
11308    );
11309
11310    build_asof_output(left, right, on, &right_matches, None)
11311}
11312
11313/// Grouped asof merge: match on `by` columns first, then asof within groups.
11314fn merge_asof_grouped(
11315    left: &fp_frame::DataFrame,
11316    right: &fp_frame::DataFrame,
11317    on: &str,
11318    direction: AsofDirection,
11319    options: &MergeAsofOptions,
11320    by_cols: &[String],
11321) -> Result<MergedDataFrame, JoinError> {
11322    // Validate by columns exist
11323    for col in by_cols {
11324        let left_column = left.columns().get(col).ok_or_else(|| {
11325            JoinError::Frame(FrameError::CompatibilityRejected(format!(
11326                "merge_asof: 'by' column '{col}' not found in left"
11327            )))
11328        })?;
11329        let right_column = right.columns().get(col).ok_or_else(|| {
11330            JoinError::Frame(FrameError::CompatibilityRejected(format!(
11331                "merge_asof: 'by' column '{col}' not found in right"
11332            )))
11333        })?;
11334        validate_object_join_keys(left_column)?;
11335        validate_object_join_keys(right_column)?;
11336    }
11337
11338    let left_key = left.columns().get(on).ok_or_else(|| {
11339        JoinError::Frame(FrameError::CompatibilityRejected(format!(
11340            "merge_asof: column '{on}' not found in left"
11341        )))
11342    })?;
11343    let right_key = right.columns().get(on).ok_or_else(|| {
11344        JoinError::Frame(FrameError::CompatibilityRejected(format!(
11345            "merge_asof: column '{on}' not found in right"
11346        )))
11347    })?;
11348
11349    ensure_matching_asof_key_dtypes(left_key, right_key, on)?;
11350
11351    // Datetime64 keys: shift-to-f64 (exact for <~104-day ns ranges) instead of the
11352    // rejected/precision-lossy direct cast. Falls back to the f64 numeric path.
11353    let (left_vals, right_vals) = match try_asof_datetime_shift(left_key, right_key, on) {
11354        Some(shifted) => shifted?,
11355        None => (
11356            asof_numeric_values(left_key, "left", on)?,
11357            asof_numeric_values(right_key, "right", on)?,
11358        ),
11359    };
11360
11361    // With matching key dtypes, pandas accepts NaN keys: the NaN row gets a
11362    // null in the joined columns (no match). Dtype incompatibility is rejected
11363    // above before this value-level rule is reached.
11364    ensure_sorted_non_decreasing(&left_vals, "left", on)?;
11365    ensure_sorted_non_decreasing(&right_vals, "right", on)?;
11366
11367    // Dense u32 group ids over the `by` columns (shared id space for left and
11368    // right). The single non-float `by` column case factorizes the column's
11369    // scalars with a borrowed typed key — no per-row `format!`/`Vec<String>`
11370    // allocation — and is bit-identical to the Debug-string grouping (see
11371    // `build_group_ids`). Everything else falls back to the string path.
11372    let (left_ids, right_ids) = build_group_ids(left, right, by_cols)?;
11373
11374    // Group right rows by their `by` group id for asof matching (looked up by
11375    // `.get()` per left group below). No per-group sort validation is needed:
11376    // the global `ensure_sorted_non_decreasing` checks above already require the
11377    // `on` column to be non-decreasing over the whole frame, and every
11378    // per-group subsequence of a sorted column is itself sorted — so the old
11379    // per-group checks were unreachable (the global check fires first on any
11380    // unsorted input). FxHashMap (vs std SipHash) speeds the build.
11381    let mut right_groups: FxHashMap<u32, Vec<usize>> = FxHashMap::default();
11382    for (idx, &id) in right_ids.iter().enumerate() {
11383        right_groups.entry(id).or_default().push(idx);
11384    }
11385
11386    // Group LEFT rows by their `by` group id (preserving the globally-sorted
11387    // order within each group), then run the monotonic two-pointer asof sweep
11388    // ONCE per group over all of the group's left values — instead of rebuilding
11389    // the group's right-value vector and re-scanning it from scratch for every
11390    // individual left row (the old O(L·R) per group). compute_asof_matches
11391    // already drives a single left array with a monotonic cursor and handles
11392    // NaN left keys (→ None, cursor unchanged); because every per-group left
11393    // subsequence is sorted (the global `on` column is non-decreasing), the
11394    // grouped sweep yields the identical match for each left row as the old
11395    // fresh-per-row scan. Results are scattered by absolute left index, so the
11396    // output order is independent of group-iteration order.
11397    let mut left_groups: FxHashMap<u32, Vec<usize>> = FxHashMap::default();
11398    for (left_idx, &id) in left_ids.iter().enumerate() {
11399        left_groups.entry(id).or_default().push(left_idx);
11400    }
11401
11402    let mut right_matches: Vec<Option<usize>> = vec![None; left_vals.len()];
11403    for (group_id, left_positions) in &left_groups {
11404        let Some(group_indices) = right_groups.get(group_id) else {
11405            continue; // no right rows for this group -> all matches stay None
11406        };
11407        let group_right_vals: Vec<f64> = group_indices.iter().map(|&i| right_vals[i]).collect();
11408        let group_left_vals: Vec<f64> = left_positions.iter().map(|&i| left_vals[i]).collect();
11409
11410        let group_matches = compute_asof_matches(
11411            &group_left_vals,
11412            &group_right_vals,
11413            direction,
11414            options.allow_exact_matches,
11415            options.tolerance,
11416        );
11417
11418        for (k, &left_idx) in left_positions.iter().enumerate() {
11419            if let Some(Some(group_idx)) = group_matches.get(k) {
11420                right_matches[left_idx] = Some(group_indices[*group_idx]);
11421            }
11422        }
11423    }
11424
11425    build_asof_output(left, right, on, &right_matches, Some(by_cols))
11426}
11427
11428/// Borrowed, allocation-free `by`-key for the single-column factorize fast
11429/// path. Each variant is the typed payload of a `Scalar` whose *derived*
11430/// `Debug` is injective and equality-consistent — so two scalars share a
11431/// `ByKey` iff their `format!("{val:?}")` strings (the legacy group key) are
11432/// equal. `Float64` (`-0.0` vs `0.0`, `NaN`) and `Interval` Debug strings
11433/// disagree with value equality, so `from_scalar` returns `None` for them and
11434/// the caller falls back to the string path.
11435#[derive(PartialEq, Eq, Hash)]
11436enum ByKey<'a> {
11437    Null(u8),
11438    Bool(bool),
11439    Int(i64),
11440    Str(&'a str),
11441    Timedelta(i64),
11442    Datetime(i64),
11443    Period(i64),
11444}
11445
11446impl<'a> ByKey<'a> {
11447    fn from_scalar(s: &'a Scalar) -> Option<Self> {
11448        Some(match s {
11449            Scalar::Null(NullKind::Null) => ByKey::Null(0),
11450            Scalar::Null(NullKind::NaN) => ByKey::Null(1),
11451            Scalar::Null(NullKind::NaT) => ByKey::Null(2),
11452            Scalar::Bool(b) => ByKey::Bool(*b),
11453            Scalar::Int64(v) => ByKey::Int(*v),
11454            Scalar::Utf8(s) => ByKey::Str(s.as_str()),
11455            Scalar::Timedelta64(v) => ByKey::Timedelta(*v),
11456            Scalar::Datetime64(v) => ByKey::Datetime(*v),
11457            Scalar::Period(v) => ByKey::Period(v.ordinal),
11458            Scalar::Float64(_) | Scalar::Interval(_) | Scalar::Object(_) => return None,
11459        })
11460    }
11461}
11462
11463/// Factorize a single `by` column over both frames into a shared u32 id space.
11464/// Returns `None` (caller falls back to the string path) if any value is a
11465/// `Float64`/`Interval` whose Debug string would not agree with typed equality.
11466fn try_factorize_typed<'a>(
11467    left: &'a [Scalar],
11468    right: &'a [Scalar],
11469) -> Option<(Vec<u32>, Vec<u32>)> {
11470    let mut codes: FxHashMap<ByKey<'a>, u32> = FxHashMap::default();
11471    let mut next = 0u32;
11472    let mut left_ids = Vec::with_capacity(left.len());
11473    for v in left {
11474        let id = *codes.entry(ByKey::from_scalar(v)?).or_insert_with(|| {
11475            let i = next;
11476            next += 1;
11477            i
11478        });
11479        left_ids.push(id);
11480    }
11481    let mut right_ids = Vec::with_capacity(right.len());
11482    for v in right {
11483        let id = *codes.entry(ByKey::from_scalar(v)?).or_insert_with(|| {
11484            let i = next;
11485            next += 1;
11486            i
11487        });
11488        right_ids.push(id);
11489    }
11490    Some((left_ids, right_ids))
11491}
11492
11493/// Build dense u32 group ids for the left and right frames over the `by`
11494/// columns, sharing one id space. Returns `(left_ids, right_ids)`.
11495///
11496/// Fast path (a single non-float `by` column): factorize the column's scalars
11497/// directly with the borrowed typed [`ByKey`] — zero per-row string formatting
11498/// or allocation. Bit-identical to the `format!("{val:?}")` grouping because
11499/// the typed key induces the exact same equality classes. Multi-column or
11500/// float/interval `by` keys route to the original Debug-string builder, whose
11501/// per-row composite keys are then interned to u32 (one clone per *distinct*
11502/// group, not per row).
11503fn build_group_ids(
11504    left: &fp_frame::DataFrame,
11505    right: &fp_frame::DataFrame,
11506    by_cols: &[String],
11507) -> Result<(Vec<u32>, Vec<u32>), JoinError> {
11508    if by_cols.len() == 1
11509        && let (Some(lcol), Some(rcol)) = (
11510            left.columns().get(&by_cols[0]),
11511            right.columns().get(&by_cols[0]),
11512        )
11513        && let Some(ids) = try_factorize_typed(lcol.values(), rcol.values())
11514    {
11515        return Ok(ids);
11516    }
11517
11518    let left_keys = build_group_keys(left, by_cols)?;
11519    let right_keys = build_group_keys(right, by_cols)?;
11520    let mut codes: FxHashMap<Vec<String>, u32> = FxHashMap::default();
11521    let mut next = 0u32;
11522    let mut intern = |k: &Vec<String>, codes: &mut FxHashMap<Vec<String>, u32>| -> u32 {
11523        if let Some(&id) = codes.get(k) {
11524            id
11525        } else {
11526            let id = next;
11527            next += 1;
11528            codes.insert(k.clone(), id);
11529            id
11530        }
11531    };
11532    let left_ids = left_keys.iter().map(|k| intern(k, &mut codes)).collect();
11533    let right_ids = right_keys.iter().map(|k| intern(k, &mut codes)).collect();
11534    Ok((left_ids, right_ids))
11535}
11536
11537/// Build group keys from the `by` columns.
11538fn build_group_keys(
11539    df: &fp_frame::DataFrame,
11540    by_cols: &[String],
11541) -> Result<Vec<Vec<String>>, JoinError> {
11542    let n = df.len();
11543    let mut keys = vec![Vec::with_capacity(by_cols.len()); n];
11544
11545    for col_name in by_cols {
11546        let col = df.columns().get(col_name).ok_or_else(|| {
11547            JoinError::Frame(FrameError::CompatibilityRejected(format!(
11548                "merge_asof: column '{col_name}' not found"
11549            )))
11550        })?;
11551        for (i, val) in col.values().iter().enumerate() {
11552            keys[i].push(format!("{val:?}"));
11553        }
11554    }
11555
11556    Ok(keys)
11557}
11558
11559/// Compute asof matches for a single group or the whole dataset.
11560fn compute_asof_matches(
11561    left_vals: &[f64],
11562    right_vals: &[f64],
11563    direction: AsofDirection,
11564    allow_exact_matches: bool,
11565    tolerance: Option<f64>,
11566) -> Vec<Option<usize>> {
11567    let mut right_non_nan_values = Vec::new();
11568    let mut right_non_nan_positions = Vec::new();
11569    for (pos, &rv) in right_vals.iter().enumerate() {
11570        if !rv.is_nan() {
11571            right_non_nan_values.push(rv);
11572            right_non_nan_positions.push(pos);
11573        }
11574    }
11575
11576    let mut right_matches: Vec<Option<usize>> = Vec::with_capacity(left_vals.len());
11577
11578    match direction {
11579        AsofDirection::Backward => {
11580            let mut best: Option<usize> = None;
11581            let mut best_val: Option<f64> = None;
11582            let mut j = 0usize;
11583            for &lv in left_vals {
11584                if lv.is_nan() {
11585                    right_matches.push(None);
11586                    continue;
11587                }
11588                // Advance while right <= left (or right < left if !allow_exact_matches)
11589                while j < right_non_nan_values.len() {
11590                    let rv = right_non_nan_values[j];
11591                    let should_include = if allow_exact_matches {
11592                        rv <= lv
11593                    } else {
11594                        rv < lv
11595                    };
11596                    if !should_include {
11597                        break;
11598                    }
11599                    best = Some(right_non_nan_positions[j]);
11600                    best_val = Some(rv);
11601                    j += 1;
11602                }
11603
11604                // Check tolerance
11605                let matched = match (best, best_val, tolerance) {
11606                    (Some(idx), Some(rv), Some(tol)) if (lv - rv).abs() <= tol => Some(idx),
11607                    (Some(idx), _, None) => Some(idx),
11608                    _ => None,
11609                };
11610                right_matches.push(matched);
11611            }
11612        }
11613        AsofDirection::Forward => {
11614            let mut j = 0usize;
11615            for &lv in left_vals {
11616                if lv.is_nan() {
11617                    right_matches.push(None);
11618                    continue;
11619                }
11620                // Advance while right < left (or right <= left if !allow_exact_matches)
11621                while j < right_non_nan_values.len() {
11622                    let rv = right_non_nan_values[j];
11623                    let should_skip = if allow_exact_matches {
11624                        rv < lv
11625                    } else {
11626                        rv <= lv
11627                    };
11628                    if !should_skip {
11629                        break;
11630                    }
11631                    j += 1;
11632                }
11633
11634                if j < right_non_nan_values.len() {
11635                    let rv = right_non_nan_values[j];
11636                    // Check tolerance
11637                    let matched = match tolerance {
11638                        Some(tol) if (rv - lv).abs() <= tol => Some(right_non_nan_positions[j]),
11639                        None => Some(right_non_nan_positions[j]),
11640                        _ => None,
11641                    };
11642                    right_matches.push(matched);
11643                } else {
11644                    right_matches.push(None);
11645                }
11646            }
11647        }
11648        AsofDirection::Nearest => {
11649            for &lv in left_vals {
11650                if lv.is_nan() {
11651                    right_matches.push(None);
11652                    continue;
11653                }
11654                if right_non_nan_values.is_empty() {
11655                    right_matches.push(None);
11656                    continue;
11657                }
11658
11659                // For nearest, pick the closest neighbor on each side. The
11660                // candidate window depends on whether exact (equal) keys may
11661                // match:
11662                //   allow_exact:  lower = last value <= lv, upper = first value >= lv
11663                //   !allow_exact: lower = last value <  lv, upper = first value >  lv
11664                // Selecting the window up front (rather than excluding exact
11665                // matches after the fact) skips over runs of exact-equal keys
11666                // when they are disallowed, so a nearer non-equal key beyond
11667                // the run is still found — matching pandas merge_asof.
11668                let (lower, upper) = if allow_exact_matches {
11669                    let lo = right_non_nan_values.partition_point(|rv| *rv <= lv);
11670                    let up = right_non_nan_values.partition_point(|rv| *rv < lv);
11671                    (
11672                        if lo > 0 { Some(lo - 1) } else { None },
11673                        if up < right_non_nan_values.len() {
11674                            Some(up)
11675                        } else {
11676                            None
11677                        },
11678                    )
11679                } else {
11680                    let lo = right_non_nan_values.partition_point(|rv| *rv < lv);
11681                    let up = right_non_nan_values.partition_point(|rv| *rv <= lv);
11682                    (
11683                        if lo > 0 { Some(lo - 1) } else { None },
11684                        if up < right_non_nan_values.len() {
11685                            Some(up)
11686                        } else {
11687                            None
11688                        },
11689                    )
11690                };
11691
11692                let chosen = match (lower, upper) {
11693                    (Some(l), Some(u)) => {
11694                        let lower_dist = (right_non_nan_values[l] - lv).abs();
11695                        let upper_dist = (right_non_nan_values[u] - lv).abs();
11696                        // Ties go to the lower (backward) neighbor, like pandas.
11697                        if upper_dist < lower_dist {
11698                            Some(u)
11699                        } else {
11700                            Some(l)
11701                        }
11702                    }
11703                    (Some(l), None) => Some(l),
11704                    (None, Some(u)) => Some(u),
11705                    (None, None) => None,
11706                };
11707
11708                // Apply tolerance check
11709                let matched = match chosen {
11710                    Some(idx) => {
11711                        let rv = right_non_nan_values[idx];
11712                        match tolerance {
11713                            Some(tol) if (lv - rv).abs() <= tol => {
11714                                Some(right_non_nan_positions[idx])
11715                            }
11716                            None => Some(right_non_nan_positions[idx]),
11717                            _ => None,
11718                        }
11719                    }
11720                    None => None,
11721                };
11722                right_matches.push(matched);
11723            }
11724        }
11725    }
11726
11727    right_matches
11728}
11729
11730/// Build the output DataFrame from computed matches.
11731/// One output column of `build_asof_output`: left columns are present for every
11732/// row (clone), right columns are gathered by the asof match positions.
11733enum AsofOutputTask<'a> {
11734    LeftClone(&'a Column),
11735    RightGather(&'a Column),
11736}
11737
11738fn build_asof_output(
11739    left: &fp_frame::DataFrame,
11740    right: &fp_frame::DataFrame,
11741    on: &str,
11742    right_matches: &[Option<usize>],
11743    by_cols: Option<&[String]>,
11744) -> Result<MergedDataFrame, JoinError> {
11745    let right_n = right.len();
11746
11747    let left_col_names: Vec<String> = left.column_names().iter().map(|s| s.to_string()).collect();
11748    let right_col_names_all: Vec<String> =
11749        right.column_names().iter().map(|s| s.to_string()).collect();
11750
11751    // Exclude the `on` column and `by` columns from right output
11752    let excluded_cols: HashSet<&str> = {
11753        let mut s = HashSet::new();
11754        s.insert(on);
11755        if let Some(by) = by_cols {
11756            for c in by {
11757                s.insert(c.as_str());
11758            }
11759        }
11760        s
11761    };
11762
11763    let right_col_names: Vec<String> = right_col_names_all
11764        .iter()
11765        .filter(|c| !excluded_cols.contains(c.as_str()))
11766        .cloned()
11767        .collect();
11768
11769    let left_name_set: HashSet<&String> = left_col_names.iter().collect();
11770    let right_name_set: HashSet<&String> = right_col_names_all.iter().collect();
11771    let mut excluded_names = HashSet::new();
11772    excluded_names.insert(on);
11773    // `by` columns are equi-join keys: pandas emits them once, unsuffixed,
11774    // exactly like `on`. They were left out of this set, so a `by` column
11775    // present on both sides counted as an overlap and the LEFT copy came out
11776    // as `group_x` (the right copy is excluded above), where pandas 2.2.3
11777    // returns `group` (br-frankenpandas-fkiu9, live-oracle
11778    // merge_asof_by_group_and_no_exact_matches).
11779    if let Some(by) = by_cols {
11780        for column in by {
11781            excluded_names.insert(column.as_str());
11782        }
11783    }
11784    let overlap_names =
11785        collect_overlapping_column_names(&left_name_set, &right_name_set, &excluded_names);
11786    let overlap_set: HashSet<String> = overlap_names.iter().cloned().collect();
11787    let suffixes = ResolvedMergeSuffixes::default();
11788    ensure_merge_suffixes_for_overlaps(&overlap_names, &suffixes)?;
11789
11790    let n_out = left.len();
11791    let mut out_columns = ColumnStore::new();
11792    let mut column_order: Vec<String> = Vec::new();
11793
11794    // Resolve every output column (name + build task) in order, then build the
11795    // columns — left columns clone all rows, right columns gather matched-or-null
11796    // values. Each output column is independent, so wide/large outputs build all
11797    // columns across a worker pool (br-frankenpandas-fu8f5; same disjoint-fill
11798    // pattern as the dense-i64/inner-merge builders). Bit-identical to the serial
11799    // loops: identical per-column result (left clone; right Scalar gather with
11800    // Null(NullKind::NaN) on unmatched, then Column::new with the source dtype),
11801    // inserted in the same order.
11802    let mut specs: Vec<(String, AsofOutputTask<'_>)> = Vec::new();
11803    for col_name in &left_col_names {
11804        let col = left.columns().get(col_name).ok_or_else(|| {
11805            JoinError::Frame(FrameError::CompatibilityRejected(format!(
11806                "merge_asof: left column '{col_name}' not found"
11807            )))
11808        })?;
11809        let output_name = if overlap_set.contains(col_name) {
11810            apply_merge_suffix(col_name, suffixes.left.as_deref())
11811        } else {
11812            col_name.clone()
11813        };
11814        specs.push((output_name, AsofOutputTask::LeftClone(col)));
11815    }
11816    for col_name in &right_col_names {
11817        let right_col = right.columns().get(col_name).ok_or_else(|| {
11818            JoinError::Frame(FrameError::CompatibilityRejected(format!(
11819                "merge_asof: right column '{col_name}' not found"
11820            )))
11821        })?;
11822        let output_name = if overlap_set.contains(col_name) {
11823            apply_merge_suffix(col_name, suffixes.right.as_deref())
11824        } else {
11825            col_name.clone()
11826        };
11827        specs.push((output_name, AsofOutputTask::RightGather(right_col)));
11828    }
11829
11830    let build_one = |task: &AsofOutputTask<'_>| -> Result<Column, JoinError> {
11831        match task {
11832            AsofOutputTask::LeftClone(col) => Ok((*col).clone()),
11833            AsofOutputTask::RightGather(right_col) => {
11834                // Typed all-valid-Float64 gather (br-frankenpandas asof typed
11835                // output): an `as_f64_slice` source is all-valid, so it carries
11836                // NO NaN values (Float64 validity marks NaN invalid, and the
11837                // slice is gated on `validity.all()`). Gather matched data into a
11838                // contiguous f64 buffer + validity bitset instead of cloning a
11839                // 32 B Scalar per row and re-validating in Column::new. Bit-
11840                // identical to the Scalar path: a matched slot is a finite
11841                // `Float64(src[j])` (valid bit), an unmatched slot is
11842                // `Null(NullKind::NaN)` (cleared bit) — exactly what the Scalar
11843                // gather + Column::new produce, with no matched-NaN ambiguity
11844                // because the source has none.
11845                if let Some(src) = right_col.as_f64_slice() {
11846                    let mut data = Vec::with_capacity(n_out);
11847                    let mut validity = fp_columnar::ValidityMask::all_valid(n_out);
11848                    for (i, m) in right_matches.iter().enumerate() {
11849                        match m {
11850                            Some(j) if *j < right_n => data.push(src[*j]),
11851                            _ => {
11852                                // 0.0 datum + cleared bit is the gap convention:
11853                                // LazyNullableFloat64 materializes Null(NaN) only
11854                                // when the datum is NOT NaN, so an unmatched slot
11855                                // must use 0.0 (a NaN datum would materialize a
11856                                // present Float64(NaN) instead).
11857                                data.push(0.0);
11858                                validity.set(i, false);
11859                            }
11860                        }
11861                    }
11862                    return Ok(Column::from_f64_values_with_validity(data, validity));
11863                }
11864                // A right column that gains an UNMATCHED row gains a gap, and an
11865                // all-valid numpy int64 cannot hold one — pandas widens it to
11866                // float64, exactly as it does for the join family. This used to
11867                // be a hand-rolled gather ending in
11868                // `Column::new(right_col.dtype(), vals)`, which kept Int64 and
11869                // left the present values pinned as ints beside a NaN.
11870                //
11871                // MEASURED, live pandas 2.2.3:
11872                //   L = DataFrame({'time':[1,5,10], 'left_val':[10,50,100]})
11873                //   R = DataFrame({'time':[2,6],    'right_val':[20,60]})
11874                //   pd.merge_asof(L, R, on='time', direction='forward')
11875                //     right_val -> [20.0, 60.0, NaN]   dtype float64
11876                //     time and left_val stay int64 — they gain no gap
11877                //   with every left row matched, right_val stays int64
11878                //
11879                // Note the rule here is PER COLUMN, unlike Series.unstack where
11880                // a gap widens the whole frame: merge builds each output column
11881                // independently, so only the column that gains the gap moves.
11882                //
11883                // reindex_join_column_with_invented_gap is the helper the nywa8
11884                // join sweep already built for this, including the guard that a
11885                // source ALREADY carrying a missing value is nullable and keeps
11886                // its dtype. merge_asof was the sibling that sweep did not
11887                // reach; calling it rather than re-deriving the rule here.
11888                Ok(reindex_join_column_with_invented_gap(
11889                    right_col,
11890                    right_matches,
11891                )?)
11892            }
11893        }
11894    };
11895
11896    let built: Vec<Result<Column, JoinError>> = {
11897        let thread_count = join_parallel_thread_count();
11898        if specs.len() > 1 && n_out >= DENSE_I64_INNER_PARALLEL_MIN_VALUES && thread_count > 1 {
11899            let mut slots: Vec<Option<Result<Column, JoinError>>> =
11900                (0..specs.len()).map(|_| None).collect();
11901            let chunk = specs.len().div_ceil(thread_count).max(1);
11902            let build_one = &build_one;
11903            std::thread::scope(|scope| {
11904                for (spec_chunk, slot_chunk) in specs.chunks(chunk).zip(slots.chunks_mut(chunk)) {
11905                    scope.spawn(move || {
11906                        for ((_, task), slot) in spec_chunk.iter().zip(slot_chunk) {
11907                            *slot = Some(build_one(task));
11908                        }
11909                    });
11910                }
11911            });
11912            slots
11913                .into_iter()
11914                .map(|c| c.expect("every asof output column must be built"))
11915                .collect()
11916        } else {
11917            specs.iter().map(|(_, task)| build_one(task)).collect()
11918        }
11919    };
11920
11921    for ((output_name, _), column) in specs.into_iter().zip(built) {
11922        insert_merged_output_column(&mut out_columns, &mut column_order, output_name, column?)?;
11923    }
11924
11925    Ok(MergedDataFrame {
11926        index: left.index().clone(),
11927        columns: out_columns,
11928        column_order,
11929    })
11930}
11931
11932impl DataFrameMergeExt for fp_frame::DataFrame {
11933    fn merge(
11934        &self,
11935        other: &fp_frame::DataFrame,
11936        on: &[&str],
11937        how: JoinType,
11938    ) -> Result<MergedDataFrame, JoinError> {
11939        merge_dataframes_on(self, other, on, how)
11940    }
11941
11942    fn merge_with_options(
11943        &self,
11944        other: &fp_frame::DataFrame,
11945        left_on: &[&str],
11946        right_on: &[&str],
11947        how: JoinType,
11948        options: MergeExecutionOptions,
11949    ) -> Result<MergedDataFrame, JoinError> {
11950        merge_dataframes_on_with_options(self, other, left_on, right_on, how, options)
11951    }
11952
11953    fn join_on_index(
11954        &self,
11955        other: &fp_frame::DataFrame,
11956        how: JoinType,
11957    ) -> Result<MergedDataFrame, JoinError> {
11958        let left = self.reset_index(false)?;
11959        let right = other.reset_index(false)?;
11960        merge_dataframes_on(&left, &right, &["index"], how)
11961    }
11962
11963    fn merge_asof(
11964        &self,
11965        other: &fp_frame::DataFrame,
11966        on: &str,
11967        direction: &str,
11968    ) -> Result<MergedDataFrame, JoinError> {
11969        self.merge_asof_with_options(other, on, direction, MergeAsofOptions::new())
11970    }
11971
11972    fn merge_asof_with_options(
11973        &self,
11974        other: &fp_frame::DataFrame,
11975        on: &str,
11976        direction: &str,
11977        options: MergeAsofOptions,
11978    ) -> Result<MergedDataFrame, JoinError> {
11979        let dir = match direction {
11980            "backward" => AsofDirection::Backward,
11981            "forward" => AsofDirection::Forward,
11982            "nearest" => AsofDirection::Nearest,
11983            _ => {
11984                return Err(JoinError::Frame(FrameError::CompatibilityRejected(
11985                    format!("merge_asof: invalid direction '{direction}'"),
11986                )));
11987            }
11988        };
11989        crate::merge_asof_with_options(self, other, on, dir, options)
11990    }
11991
11992    fn merge_ordered(
11993        &self,
11994        other: &fp_frame::DataFrame,
11995        on: &[&str],
11996        fill_method: Option<&str>,
11997    ) -> Result<MergedDataFrame, JoinError> {
11998        crate::merge_ordered(self, other, on, fill_method)
11999    }
12000}
12001
12002#[cfg(test)]
12003mod tests {
12004    use fp_columnar::{Column, ValidityMask};
12005    use fp_frame::{ColumnStore, Series};
12006    use fp_index::{Index, IndexLabel};
12007    use fp_types::{DType, NullKind, Scalar};
12008
12009    use super::{
12010        DataFrameMergeExt, DenseI64InnerOutputPlan, DenseI64LaneData, FusedInt64OutputColumn,
12011        FusedInt64Side, InnerPositionPlan, JoinExecutionOptions, JoinType, PositionSelection,
12012        ResolvedMergeSuffixes, build_dense_i64_inner_output_data,
12013        build_single_key_dense_cycle_i64_left_merge_output,
12014        build_single_key_dense_i64_left_merge_output,
12015        build_single_key_dense_i64_right_merge_output,
12016        build_single_key_inner_contiguous_no_overlap_output, join_series, join_series_with_options,
12017        join_series_with_trace, lower_hex_overlap_plan_from_certificates,
12018        ordered_unique_utf8_inner_position_plan, ordered_unique_utf8_inner_positions,
12019        ordered_utf8_lower_hex_overlap_len, scalar_utf8_left_positions,
12020        scalar_utf8_outer_positions, sorted_contiguous_utf8_inner_positions,
12021        strictly_increasing_utf8_key_spans, utf8_span_lower_bound,
12022    };
12023
12024    fn contiguous_utf8_column(values: &[&str]) -> Column {
12025        let mut bytes = Vec::new();
12026        let mut offsets = Vec::with_capacity(values.len() + 1);
12027        offsets.push(0);
12028        for value in values {
12029            bytes.extend_from_slice(value.as_bytes());
12030            offsets.push(bytes.len());
12031        }
12032        Column::from_utf8_contiguous(bytes, offsets)
12033    }
12034
12035    fn utf8_key_merge_frame(keys: &[&str], value_name: &str, base: i64) -> DataFrame {
12036        let index = Index::new(
12037            (0..keys.len())
12038                .map(|row| IndexLabel::Int64(row as i64))
12039                .collect(),
12040        );
12041        let mut columns = ColumnStore::new();
12042        columns.insert("id".to_owned(), contiguous_utf8_column(keys));
12043        columns.insert(
12044            value_name.to_owned(),
12045            Column::from_i64_values((0..keys.len()).map(|row| base + row as i64).collect()),
12046        );
12047        DataFrame::new_with_column_order(
12048            index,
12049            columns,
12050            vec!["id".to_owned(), value_name.to_owned()],
12051        )
12052        .expect("utf8 key frame")
12053    }
12054
12055    fn scalar_utf8_column(values: &[&str]) -> Column {
12056        Column::from_values(
12057            values
12058                .iter()
12059                .map(|value| Scalar::Utf8((*value).to_owned()))
12060                .collect(),
12061        )
12062        .expect("scalar utf8 column")
12063    }
12064
12065    #[test]
12066    fn scalar_utf8_left_positions_preserve_duplicate_order_blackthrush() {
12067        let left = scalar_utf8_column(&["b", "a", "b", "x"]);
12068        let right = scalar_utf8_column(&["a", "b", "b"]);
12069
12070        let (left_positions, right_positions) =
12071            scalar_utf8_left_positions(&left, &right).expect("scalar utf8 left positions");
12072
12073        assert_eq!(
12074            left_positions,
12075            vec![Some(0), Some(0), Some(1), Some(2), Some(2), Some(3)]
12076        );
12077        assert_eq!(
12078            right_positions,
12079            vec![Some(1), Some(2), Some(0), Some(1), Some(2), None]
12080        );
12081    }
12082
12083    #[test]
12084    fn scalar_utf8_outer_positions_sort_keys_and_keep_unmatched_blackthrush() {
12085        let left = scalar_utf8_column(&["b", "a", "b", "x"]);
12086        let right = scalar_utf8_column(&["a", "b", "b", "z"]);
12087
12088        let (left_positions, right_positions) =
12089            scalar_utf8_outer_positions(&left, &right).expect("scalar utf8 outer positions");
12090
12091        assert_eq!(
12092            left_positions,
12093            vec![Some(1), Some(0), Some(0), Some(2), Some(2), Some(3), None,]
12094        );
12095        assert_eq!(
12096            right_positions,
12097            vec![Some(0), Some(1), Some(2), Some(1), Some(2), None, Some(3),]
12098        );
12099    }
12100
12101    #[test]
12102    fn inner_join_multiplies_cardinality_for_duplicates() {
12103        let left = Series::from_values(
12104            "left",
12105            vec!["k".into(), "k".into(), "x".into()],
12106            vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
12107        )
12108        .expect("left");
12109
12110        let right = Series::from_values(
12111            "right",
12112            vec!["k".into(), "k".into()],
12113            vec![Scalar::Int64(10), Scalar::Int64(20)],
12114        )
12115        .expect("right");
12116
12117        let out = join_series(&left, &right, JoinType::Inner).expect("join");
12118        assert_eq!(out.index.labels().len(), 4);
12119        assert_eq!(
12120            out.left_values.values(),
12121            &[
12122                Scalar::Int64(1),
12123                Scalar::Int64(1),
12124                Scalar::Int64(2),
12125                Scalar::Int64(2)
12126            ]
12127        );
12128    }
12129
12130    #[test]
12131    fn left_join_injects_missing_for_unmatched_right_rows() {
12132        let left = Series::from_values(
12133            "left",
12134            vec!["a".into(), "b".into()],
12135            vec![Scalar::Int64(1), Scalar::Int64(2)],
12136        )
12137        .expect("left");
12138        let right =
12139            Series::from_values("right", vec!["a".into()], vec![Scalar::Int64(10)]).expect("right");
12140
12141        let out = join_series(&left, &right, JoinType::Left).expect("join");
12142        // The right side gains a gap, so pandas widens it to float64 and the
12143        // gap is a NaN — on a LEFT join exactly as on an outer one. MEASURED,
12144        // live pandas 2.2.3, l=[10,20,30]@[1,2,3] joined with r=[200]@[2]:
12145        //   how='left'  -> l int64 [10,20,30]   r float64 [nan, 200.0, nan]
12146        //   how='outer' -> same
12147        // This assertion previously pinned Int64 + Null(Null), which was
12148        // FrankenPandas' own pre-fix answer. (br-frankenpandas-nywa8)
12149        assert_eq!(
12150            out.right_values.values(),
12151            &[Scalar::Float64(10.0), Scalar::Null(NullKind::NaN)]
12152        );
12153    }
12154
12155    #[test]
12156    fn arena_join_matches_global_allocator_behavior() {
12157        let left = Series::from_values(
12158            "left",
12159            vec!["k".into(), "k".into(), "x".into()],
12160            vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
12161        )
12162        .expect("left");
12163
12164        let right = Series::from_values(
12165            "right",
12166            vec!["k".into(), "k".into()],
12167            vec![Scalar::Int64(10), Scalar::Int64(20)],
12168        )
12169        .expect("right");
12170
12171        let global = join_series_with_options(
12172            &left,
12173            &right,
12174            JoinType::Inner,
12175            JoinExecutionOptions {
12176                use_arena: false,
12177                arena_budget_bytes: 0,
12178            },
12179        )
12180        .expect("global join");
12181
12182        let arena = join_series_with_options(
12183            &left,
12184            &right,
12185            JoinType::Inner,
12186            JoinExecutionOptions::default(),
12187        )
12188        .expect("arena join");
12189
12190        assert_eq!(arena, global);
12191    }
12192
12193    #[test]
12194    fn arena_join_falls_back_when_budget_is_too_small() {
12195        let left = Series::from_values(
12196            "left",
12197            vec!["a".into(), "a".into(), "a".into()],
12198            vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
12199        )
12200        .expect("left");
12201        let right = Series::from_values(
12202            "right",
12203            vec!["a".into(), "a".into()],
12204            vec![Scalar::Int64(10), Scalar::Int64(20)],
12205        )
12206        .expect("right");
12207
12208        let options = JoinExecutionOptions {
12209            use_arena: true,
12210            arena_budget_bytes: 1,
12211        };
12212        let (fallback_out, trace) =
12213            join_series_with_trace(&left, &right, JoinType::Inner, options).expect("fallback join");
12214        let global_out = join_series_with_options(
12215            &left,
12216            &right,
12217            JoinType::Inner,
12218            JoinExecutionOptions {
12219                use_arena: false,
12220                arena_budget_bytes: 0,
12221            },
12222        )
12223        .expect("global join");
12224
12225        assert_eq!(fallback_out, global_out);
12226        assert!(!trace.used_arena);
12227        assert!(trace.estimated_bytes > options.arena_budget_bytes);
12228    }
12229
12230    #[test]
12231    fn arena_join_is_stable_across_many_small_operations() {
12232        let left = Series::from_values(
12233            "left",
12234            vec!["a".into(), "b".into()],
12235            vec![Scalar::Int64(1), Scalar::Int64(2)],
12236        )
12237        .expect("left");
12238        let right = Series::from_values(
12239            "right",
12240            vec!["a".into(), "b".into()],
12241            vec![Scalar::Int64(10), Scalar::Int64(20)],
12242        )
12243        .expect("right");
12244
12245        let options = JoinExecutionOptions::default();
12246        for _ in 0..1_000 {
12247            let out = join_series_with_options(&left, &right, JoinType::Inner, options)
12248                .expect("arena join");
12249            assert_eq!(out.index.labels().len(), 2);
12250            assert_eq!(
12251                out.right_values.values(),
12252                &[Scalar::Int64(10), Scalar::Int64(20)]
12253            );
12254        }
12255    }
12256
12257    /// AG-06-T test #8: 100K-row inner join with arena -> correct output, no OOM.
12258    #[test]
12259    fn arena_large_join_100k_rows() {
12260        let n = 100_000;
12261        let labels: Vec<IndexLabel> = (0..n).map(|i| IndexLabel::Int64(i as i64 % 1000)).collect();
12262        let values: Vec<Scalar> = (0..n).map(|i| Scalar::Int64(i as i64)).collect();
12263
12264        let left = Series::from_values("left", labels.clone(), values.clone()).expect("left");
12265        let right = Series::from_values("right", labels, values).expect("right");
12266
12267        let out = join_series_with_options(
12268            &left,
12269            &right,
12270            JoinType::Inner,
12271            JoinExecutionOptions::default(),
12272        )
12273        .expect("100K arena join");
12274
12275        // With 1000 distinct keys, each appearing 100 times on each side,
12276        // inner join produces 100 * 100 * 1000 = 10M rows.
12277        // But that's too large; use a budget that forces fallback.
12278        let out_fallback = join_series_with_options(
12279            &left,
12280            &right,
12281            JoinType::Inner,
12282            JoinExecutionOptions {
12283                use_arena: true,
12284                arena_budget_bytes: 1,
12285            },
12286        )
12287        .expect("100K fallback join");
12288
12289        assert_eq!(out.index.labels().len(), out_fallback.index.labels().len());
12290    }
12291
12292    #[test]
12293    fn right_join_contains_all_right_labels() {
12294        let left = Series::from_values(
12295            "left",
12296            vec!["a".into(), "b".into()],
12297            vec![Scalar::Int64(1), Scalar::Int64(2)],
12298        )
12299        .expect("left");
12300        let right = Series::from_values(
12301            "right",
12302            vec!["b".into(), "c".into()],
12303            vec![Scalar::Int64(20), Scalar::Int64(30)],
12304        )
12305        .expect("right");
12306
12307        let out = join_series(&left, &right, JoinType::Right).expect("join");
12308        // Right join: all right labels preserved. "b" matches, "c" unmatched.
12309        assert_eq!(out.index.labels().len(), 2);
12310        assert_eq!(
12311            out.index.labels(),
12312            &[IndexLabel::Utf8("b".into()), IndexLabel::Utf8("c".into())]
12313        );
12314        // "b" matched -> left=2, right=20. "c" unmatched -> left is a gap, so
12315        // the LEFT lane widens to float64 with a NaN (br-frankenpandas-nywa8;
12316        // the widening follows the invented gap, not the join type).
12317        assert_eq!(
12318            out.left_values.values(),
12319            &[Scalar::Float64(2.0), Scalar::Null(NullKind::NaN)]
12320        );
12321        assert_eq!(
12322            out.right_values.values(),
12323            &[Scalar::Int64(20), Scalar::Int64(30)]
12324        );
12325    }
12326
12327    #[test]
12328    fn right_join_multiplies_cardinality_for_duplicates() {
12329        let left = Series::from_values(
12330            "left",
12331            vec!["k".into(), "k".into()],
12332            vec![Scalar::Int64(1), Scalar::Int64(2)],
12333        )
12334        .expect("left");
12335        let right = Series::from_values(
12336            "right",
12337            vec!["k".into(), "x".into()],
12338            vec![Scalar::Int64(10), Scalar::Int64(30)],
12339        )
12340        .expect("right");
12341
12342        let out = join_series(&left, &right, JoinType::Right).expect("join");
12343        // "k" in right matches 2 left rows -> 2 output rows for "k", plus 1 for "x" unmatched.
12344        assert_eq!(out.index.labels().len(), 3);
12345        assert_eq!(
12346            out.right_values.values(),
12347            &[Scalar::Int64(10), Scalar::Int64(10), Scalar::Int64(30)]
12348        );
12349    }
12350
12351    #[test]
12352    fn outer_join_contains_all_labels_from_both_sides() {
12353        let left = Series::from_values(
12354            "left",
12355            vec!["a".into(), "b".into()],
12356            vec![Scalar::Int64(1), Scalar::Int64(2)],
12357        )
12358        .expect("left");
12359        let right = Series::from_values(
12360            "right",
12361            vec!["b".into(), "c".into()],
12362            vec![Scalar::Int64(20), Scalar::Int64(30)],
12363        )
12364        .expect("right");
12365
12366        let out = join_series(&left, &right, JoinType::Outer).expect("join");
12367        // Outer: "a" (left only), "b" (both), "c" (right only) -> 3 rows
12368        assert_eq!(out.index.labels().len(), 3);
12369        assert_eq!(
12370            out.left_values.values(),
12371            &[
12372                Scalar::Float64(1.0),
12373                Scalar::Float64(2.0),
12374                Scalar::Null(NullKind::NaN)
12375            ]
12376        );
12377        assert_eq!(
12378            out.right_values.values(),
12379            &[
12380                Scalar::Null(NullKind::NaN),
12381                Scalar::Float64(20.0),
12382                Scalar::Float64(30.0)
12383            ]
12384        );
12385    }
12386
12387    #[test]
12388    fn outer_join_sorts_union_labels_like_pandas() {
12389        let left = Series::from_values(
12390            "left",
12391            vec!["a".into(), "c".into()],
12392            vec![Scalar::Int64(1), Scalar::Int64(3)],
12393        )
12394        .expect("left");
12395        let right = Series::from_values(
12396            "right",
12397            vec!["b".into(), "c".into()],
12398            vec![Scalar::Int64(20), Scalar::Int64(30)],
12399        )
12400        .expect("right");
12401
12402        let out = join_series(&left, &right, JoinType::Outer).expect("join");
12403        assert_eq!(
12404            out.index.labels(),
12405            &[
12406                IndexLabel::Utf8("a".into()),
12407                IndexLabel::Utf8("b".into()),
12408                IndexLabel::Utf8("c".into())
12409            ]
12410        );
12411        assert_eq!(
12412            out.left_values.values(),
12413            &[
12414                Scalar::Float64(1.0),
12415                Scalar::Null(NullKind::NaN),
12416                Scalar::Float64(3.0)
12417            ]
12418        );
12419        assert_eq!(
12420            out.right_values.values(),
12421            &[
12422                Scalar::Null(NullKind::NaN),
12423                Scalar::Float64(20.0),
12424                Scalar::Float64(30.0)
12425            ]
12426        );
12427    }
12428
12429    #[test]
12430    fn outer_join_with_duplicates() {
12431        let left = Series::from_values(
12432            "left",
12433            vec!["k".into(), "k".into(), "a".into()],
12434            vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
12435        )
12436        .expect("left");
12437        let right = Series::from_values(
12438            "right",
12439            vec!["k".into(), "z".into()],
12440            vec![Scalar::Int64(10), Scalar::Int64(99)],
12441        )
12442        .expect("right");
12443
12444        let out = join_series(&left, &right, JoinType::Outer).expect("join");
12445        // "k" x "k": 2 matched rows. "a": left-only (1 row). "z": right-only (1 row).
12446        assert_eq!(out.index.labels().len(), 4);
12447    }
12448
12449    #[test]
12450    fn arena_right_join_matches_global() {
12451        let left = Series::from_values(
12452            "left",
12453            vec!["a".into(), "b".into()],
12454            vec![Scalar::Int64(1), Scalar::Int64(2)],
12455        )
12456        .expect("left");
12457        let right = Series::from_values(
12458            "right",
12459            vec!["b".into(), "c".into()],
12460            vec![Scalar::Int64(20), Scalar::Int64(30)],
12461        )
12462        .expect("right");
12463
12464        let global = join_series_with_options(
12465            &left,
12466            &right,
12467            JoinType::Right,
12468            JoinExecutionOptions {
12469                use_arena: false,
12470                arena_budget_bytes: 0,
12471            },
12472        )
12473        .expect("global");
12474        let arena = join_series_with_options(
12475            &left,
12476            &right,
12477            JoinType::Right,
12478            JoinExecutionOptions::default(),
12479        )
12480        .expect("arena");
12481        assert_eq!(arena, global);
12482    }
12483
12484    #[test]
12485    fn arena_outer_join_matches_global() {
12486        let left = Series::from_values(
12487            "left",
12488            vec!["a".into(), "b".into()],
12489            vec![Scalar::Int64(1), Scalar::Int64(2)],
12490        )
12491        .expect("left");
12492        let right = Series::from_values(
12493            "right",
12494            vec!["b".into(), "c".into()],
12495            vec![Scalar::Int64(20), Scalar::Int64(30)],
12496        )
12497        .expect("right");
12498
12499        let global = join_series_with_options(
12500            &left,
12501            &right,
12502            JoinType::Outer,
12503            JoinExecutionOptions {
12504                use_arena: false,
12505                arena_budget_bytes: 0,
12506            },
12507        )
12508        .expect("global");
12509        let arena = join_series_with_options(
12510            &left,
12511            &right,
12512            JoinType::Outer,
12513            JoinExecutionOptions::default(),
12514        )
12515        .expect("arena");
12516        assert_eq!(arena, global);
12517    }
12518
12519    /// AG-06-T test #6: arena is scoped per-operation. Two sequential
12520    /// operations each get their own arena (verified by both succeeding).
12521    #[test]
12522    fn arena_reset_between_operations() {
12523        let left = Series::from_values(
12524            "left",
12525            vec!["a".into(), "b".into()],
12526            vec![Scalar::Int64(1), Scalar::Int64(2)],
12527        )
12528        .expect("left");
12529        let right = Series::from_values(
12530            "right",
12531            vec!["a".into(), "c".into()],
12532            vec![Scalar::Int64(10), Scalar::Int64(30)],
12533        )
12534        .expect("right");
12535
12536        // Operation 1: inner join
12537        let out1 = join_series_with_options(
12538            &left,
12539            &right,
12540            JoinType::Inner,
12541            JoinExecutionOptions::default(),
12542        )
12543        .expect("op1");
12544        assert_eq!(out1.index.labels().len(), 1);
12545
12546        // Operation 2: left join (arena from op1 was freed)
12547        let out2 = join_series_with_options(
12548            &left,
12549            &right,
12550            JoinType::Left,
12551            JoinExecutionOptions::default(),
12552        )
12553        .expect("op2");
12554        assert_eq!(out2.index.labels().len(), 2);
12555    }
12556
12557    // ---- DataFrame merge tests (bd-2gi.17) ----
12558
12559    use fp_frame::{DataFrame, FrameError};
12560
12561    use super::{
12562        JoinError, MergeExecutionOptions, MergeValidateMode, MergedDataFrame,
12563        build_single_key_dense_right_merge_output, dense_int64_right_positions, merge_dataframes,
12564        merge_dataframes_on, merge_dataframes_on_with, merge_dataframes_on_with_options,
12565        ordered_identity_int64_keys_match, resolve_merge_suffixes,
12566    };
12567
12568    fn make_left_df() -> DataFrame {
12569        DataFrame::from_dict(
12570            &["id", "val_a"],
12571            vec![
12572                (
12573                    "id",
12574                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
12575                ),
12576                (
12577                    "val_a",
12578                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
12579                ),
12580            ],
12581        )
12582        .unwrap()
12583    }
12584
12585    fn make_right_df() -> DataFrame {
12586        DataFrame::from_dict(
12587            &["id", "val_b"],
12588            vec![
12589                (
12590                    "id",
12591                    vec![Scalar::Int64(2), Scalar::Int64(3), Scalar::Int64(4)],
12592                ),
12593                (
12594                    "val_b",
12595                    vec![Scalar::Int64(200), Scalar::Int64(300), Scalar::Int64(400)],
12596                ),
12597            ],
12598        )
12599        .unwrap()
12600    }
12601
12602    #[test]
12603    fn merge_preserves_pandas_column_order_for_nonalphabetical_names() {
12604        // br-frankenpandas-691lh: output columns follow pandas order — key/left
12605        // columns in the LEFT frame's source order, then right non-key columns —
12606        // not alphabetical (the columns map is a BTreeMap). Verified vs pandas
12607        // 2.2.3: merge(left[k,zebra,apple], right[k,mango], on=k)
12608        //   -> [k, zebra, apple, mango].
12609        let left = DataFrame::from_dict(
12610            &["k", "zebra", "apple"],
12611            vec![
12612                ("k", vec![Scalar::Int64(1), Scalar::Int64(2)]),
12613                ("zebra", vec![Scalar::Int64(10), Scalar::Int64(20)]),
12614                ("apple", vec![Scalar::Int64(30), Scalar::Int64(40)]),
12615            ],
12616        )
12617        .unwrap();
12618        let right = DataFrame::from_dict(
12619            &["k", "mango"],
12620            vec![
12621                ("k", vec![Scalar::Int64(1), Scalar::Int64(2)]),
12622                ("mango", vec![Scalar::Int64(50), Scalar::Int64(60)]),
12623            ],
12624        )
12625        .unwrap();
12626        let merged = merge_dataframes(&left, &right, "k", JoinType::Inner).unwrap();
12627        let order: Vec<&str> = merged.column_order.iter().map(String::as_str).collect();
12628        assert_eq!(order, ["k", "zebra", "apple", "mango"]);
12629    }
12630
12631    #[test]
12632    fn merge_outer_gap_widens_int64_and_keeps_int64_nullable_4qg5w_11() {
12633        // DISC-011's merge row (pandas 2.2.3): the row an outer merge invents
12634        // is float64 NaN in a numpy int64 column and NA in a nullable Int64.
12635        let frame = |key: &str, keys: &[i64], name: &str, dtype: DType, values: &[i64]| {
12636            let ints = |xs: &[i64]| xs.iter().map(|x| Scalar::Int64(*x)).collect::<Vec<_>>();
12637            let labels = (0..keys.len() as i64).map(IndexLabel::Int64).collect();
12638            let columns = std::collections::BTreeMap::from([
12639                (
12640                    key.to_owned(),
12641                    Column::new(DType::Int64, ints(keys)).unwrap(),
12642                ),
12643                (name.to_owned(), Column::new(dtype, ints(values)).unwrap()),
12644            ]);
12645            DataFrame::new_with_column_order(
12646                Index::new(labels),
12647                columns,
12648                vec![key.to_owned(), name.to_owned()],
12649            )
12650            .unwrap()
12651        };
12652        for (dtype, widened) in [
12653            (DType::Int64, DType::Float64),
12654            (DType::Int64Nullable, DType::Int64Nullable),
12655        ] {
12656            let left = frame("k", &[1, 2], "v", dtype.clone(), &[7, 8]);
12657            let right = frame("k", &[2, 3], "w", dtype.clone(), &[5, 6]);
12658            let merged = merge_dataframes(&left, &right, "k", JoinType::Outer).unwrap();
12659            let v = merged.columns.get("v").unwrap();
12660            assert_eq!(v.dtype(), widened, "{dtype:?}");
12661            match widened {
12662                DType::Float64 => {
12663                    assert_eq!(v.values()[0], Scalar::Float64(7.0));
12664                    assert_eq!(v.values()[2], Scalar::Null(NullKind::NaN));
12665                }
12666                _ => {
12667                    assert_eq!(v.values()[0], Scalar::Int64(7));
12668                    assert!(v.values()[2].is_missing(), "{dtype:?}: {:?}", v.values());
12669                }
12670            }
12671        }
12672    }
12673
12674    #[test]
12675    fn join_row_count_lattice_n8npw() {
12676        // Invariant (br-frankenpandas-n8npw): inner<=left<=outer and inner<=right<=outer
12677        // by row count. Seeded LCG, no mocks.
12678        let mut s: u64 = 0x4e57_0b1c_2d3e_4f55;
12679        let mut next = || {
12680            s = s
12681                .wrapping_mul(6_364_136_223_846_793_005)
12682                .wrapping_add(1_442_695_040_888_963_407);
12683            (s >> 33) as u32
12684        };
12685        for iter in 0..300u32 {
12686            let ln = (next() % 6) as usize + 1;
12687            let rn = (next() % 6) as usize + 1;
12688            let lk: Vec<Scalar> = (0..ln)
12689                .map(|_| Scalar::Int64((next() % 4) as i64))
12690                .collect();
12691            let rk: Vec<Scalar> = (0..rn)
12692                .map(|_| Scalar::Int64((next() % 4) as i64))
12693                .collect();
12694            let left = DataFrame::from_dict(
12695                &["k", "lv"],
12696                vec![
12697                    ("k", lk),
12698                    ("lv", (0..ln).map(|i| Scalar::Int64(i as i64)).collect()),
12699                ],
12700            )
12701            .unwrap();
12702            let right = DataFrame::from_dict(
12703                &["k", "rv"],
12704                vec![
12705                    ("k", rk),
12706                    ("rv", (0..rn).map(|i| Scalar::Int64(i as i64)).collect()),
12707                ],
12708            )
12709            .unwrap();
12710            let rows = |jt| {
12711                let m = merge_dataframes(&left, &right, "k", jt).unwrap();
12712                merged_values(&m, "k").unwrap().len()
12713            };
12714            let inner = rows(JoinType::Inner);
12715            let lj = rows(JoinType::Left);
12716            let rj = rows(JoinType::Right);
12717            let outer = rows(JoinType::Outer);
12718            assert!(
12719                inner <= lj && lj <= outer,
12720                "inner<=left<=outer iter={iter}: {inner} {lj} {outer}"
12721            );
12722            assert!(
12723                inner <= rj && rj <= outer,
12724                "inner<=right<=outer iter={iter}: {inner} {rj} {outer}"
12725            );
12726        }
12727    }
12728
12729    #[test]
12730    fn right_join_null_fill_multiset_7je8m() {
12731        use std::collections::HashMap;
12732        // Differential (br-frankenpandas-7je8m): RIGHT join preserves every right row;
12733        // matched left payload cross-product else null. (key, lv-or-None, rv) multiset
12734        // vs oracle. Seeded LCG, no mocks.
12735        let mut s: u64 = 0x4e57_0b1c_2d3e_4f54;
12736        let mut next = || {
12737            s = s
12738                .wrapping_mul(6_364_136_223_846_793_005)
12739                .wrapping_add(1_442_695_040_888_963_407);
12740            (s >> 33) as u32
12741        };
12742        for iter in 0..300u32 {
12743            let ln = (next() % 6) as usize + 1;
12744            let rn = (next() % 6) as usize + 1;
12745            let lk: Vec<i64> = (0..ln).map(|_| (next() % 4) as i64).collect();
12746            let lv: Vec<i64> = (0..ln).map(|i| i as i64).collect();
12747            let rk: Vec<i64> = (0..rn).map(|_| (next() % 4) as i64).collect();
12748            let rv: Vec<i64> = (0..rn).map(|i| 100 + i as i64).collect();
12749            let left = DataFrame::from_dict(
12750                &["k", "lv"],
12751                vec![
12752                    ("k", lk.iter().map(|&x| Scalar::Int64(x)).collect()),
12753                    ("lv", lv.iter().map(|&x| Scalar::Int64(x)).collect()),
12754                ],
12755            )
12756            .unwrap();
12757            let right = DataFrame::from_dict(
12758                &["k", "rv"],
12759                vec![
12760                    ("k", rk.iter().map(|&x| Scalar::Int64(x)).collect()),
12761                    ("rv", rv.iter().map(|&x| Scalar::Int64(x)).collect()),
12762                ],
12763            )
12764            .unwrap();
12765            let merged = merge_dataframes(&left, &right, "k", JoinType::Right).unwrap();
12766
12767            let ks = merged_values(&merged, "k").unwrap();
12768            let lvs = merged_values(&merged, "lv").unwrap();
12769            let rvs = merged_values(&merged, "rv").unwrap();
12770            let ki = |v: &Scalar| -> i64 {
12771                match v {
12772                    Scalar::Int64(x) => *x,
12773                    Scalar::Float64(x) => *x as i64,
12774                    _ => i64::MIN,
12775                }
12776            };
12777            let kopt =
12778                |v: &Scalar| -> Option<i64> { if v.is_missing() { None } else { Some(ki(v)) } };
12779            let mut got: Vec<(i64, Option<i64>, i64)> = (0..ks.len())
12780                .map(|i| (ki(&ks[i]), kopt(&lvs[i]), ki(&rvs[i])))
12781                .collect();
12782            // Oracle.
12783            let mut lby: HashMap<i64, Vec<i64>> = HashMap::new();
12784            for i in 0..ln {
12785                lby.entry(lk[i]).or_default().push(lv[i]);
12786            }
12787            let mut exp: Vec<(i64, Option<i64>, i64)> = Vec::new();
12788            for i in 0..rn {
12789                match lby.get(&rk[i]) {
12790                    Some(lvals) => {
12791                        for &a in lvals {
12792                            exp.push((rk[i], Some(a), rv[i]));
12793                        }
12794                    }
12795                    None => exp.push((rk[i], None, rv[i])),
12796                }
12797            }
12798            got.sort();
12799            exp.sort();
12800            assert_eq!(got, exp, "right join multiset iter={iter}");
12801        }
12802    }
12803
12804    #[test]
12805    fn inner_join_utf8_value_multiset_fr4ns() {
12806        use std::collections::HashMap;
12807        // Differential (br-frankenpandas-fr4ns): inner join on Utf8 keys; the (key,
12808        // lv, rv) multiset == per-key cross-product (5foyp was int/dense; jlf8d a
12809        // single case). Seeded LCG, no mocks.
12810        let mut s: u64 = 0x4e57_0b1c_2d3e_4f51;
12811        let mut next = || {
12812            s = s
12813                .wrapping_mul(6_364_136_223_846_793_005)
12814                .wrapping_add(1_442_695_040_888_963_407);
12815            (s >> 33) as u32
12816        };
12817        let key = |n: u32| Scalar::Utf8(format!("{}", (b'a' + (n % 4) as u8) as char));
12818        for iter in 0..300u32 {
12819            let ln = (next() % 6) as usize + 1;
12820            let rn = (next() % 6) as usize + 1;
12821            let lk: Vec<Scalar> = (0..ln).map(|_| key(next())).collect();
12822            let lv: Vec<i64> = (0..ln).map(|i| i as i64).collect();
12823            let rk: Vec<Scalar> = (0..rn).map(|_| key(next())).collect();
12824            let rv: Vec<i64> = (0..rn).map(|i| 100 + i as i64).collect();
12825            let left = DataFrame::from_dict(
12826                &["k", "lv"],
12827                vec![
12828                    ("k", lk.clone()),
12829                    ("lv", lv.iter().map(|&x| Scalar::Int64(x)).collect()),
12830                ],
12831            )
12832            .unwrap();
12833            let right = DataFrame::from_dict(
12834                &["k", "rv"],
12835                vec![
12836                    ("k", rk.clone()),
12837                    ("rv", rv.iter().map(|&x| Scalar::Int64(x)).collect()),
12838                ],
12839            )
12840            .unwrap();
12841            let merged = merge_dataframes(&left, &right, "k", JoinType::Inner).unwrap();
12842
12843            let ks = merged_values(&merged, "k").unwrap();
12844            let lvs = merged_values(&merged, "lv").unwrap();
12845            let rvs = merged_values(&merged, "rv").unwrap();
12846            let kstr = |v: &Scalar| -> String {
12847                match v {
12848                    Scalar::Utf8(x) => x.clone(),
12849                    _ => String::new(),
12850                }
12851            };
12852            let ki = |v: &Scalar| -> i64 {
12853                match v {
12854                    Scalar::Int64(x) => *x,
12855                    _ => i64::MIN,
12856                }
12857            };
12858            let mut got: Vec<(String, i64, i64)> = (0..ks.len())
12859                .map(|i| (kstr(&ks[i]), ki(&lvs[i]), ki(&rvs[i])))
12860                .collect();
12861            // Oracle: per-key cross product.
12862            let mut lby: HashMap<String, Vec<i64>> = HashMap::new();
12863            for i in 0..ln {
12864                lby.entry(kstr(&lk[i])).or_default().push(lv[i]);
12865            }
12866            let mut rby: HashMap<String, Vec<i64>> = HashMap::new();
12867            for i in 0..rn {
12868                rby.entry(kstr(&rk[i])).or_default().push(rv[i]);
12869            }
12870            let mut exp: Vec<(String, i64, i64)> = Vec::new();
12871            for (k, lvals) in &lby {
12872                if let Some(rvals) = rby.get(k) {
12873                    for &a in lvals {
12874                        for &b in rvals {
12875                            exp.push((k.clone(), a, b));
12876                        }
12877                    }
12878                }
12879            }
12880            got.sort();
12881            exp.sort();
12882            assert_eq!(got, exp, "inner Utf8 multiset iter={iter}");
12883        }
12884    }
12885
12886    #[test]
12887    fn inner_join_utf8_keys_jlf8d() {
12888        use std::collections::HashMap;
12889        // br-frankenpandas-jlf8d: inner join on Utf8 keys (general/hash path).
12890        let s = |v: &str| Scalar::Utf8(v.to_owned());
12891        let left = DataFrame::from_dict(
12892            &["k", "lv"],
12893            vec![
12894                ("k", vec![s("a"), s("b"), s("c")]),
12895                (
12896                    "lv",
12897                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
12898                ),
12899            ],
12900        )
12901        .expect("left");
12902        let right = DataFrame::from_dict(
12903            &["k", "rv"],
12904            vec![
12905                ("k", vec![s("b"), s("c"), s("d")]),
12906                (
12907                    "rv",
12908                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
12909                ),
12910            ],
12911        )
12912        .expect("right");
12913        let merged = merge_dataframes(&left, &right, "k", JoinType::Inner).expect("merge");
12914
12915        let keys = merged_values(&merged, "k").expect("k");
12916        let lv = merged_values(&merged, "lv").expect("lv");
12917        let rv = merged_values(&merged, "rv").expect("rv");
12918        let exp_lv: HashMap<&str, i64> = [("b", 2), ("c", 3)].into_iter().collect();
12919        let exp_rv: HashMap<&str, i64> = [("b", 10), ("c", 20)].into_iter().collect();
12920        assert_eq!(keys.len(), 2, "inner keys = {{b,c}}");
12921        for i in 0..keys.len() {
12922            let k = match &keys[i] {
12923                Scalar::Utf8(x) => x.as_str(),
12924                _ => "?",
12925            };
12926            let geti = |s: &Scalar| match s {
12927                Scalar::Int64(v) => *v,
12928                _ => i64::MIN,
12929            };
12930            assert_eq!(geti(&lv[i]), exp_lv[k], "lv at {k}");
12931            assert_eq!(geti(&rv[i]), exp_rv[k], "rv at {k}");
12932        }
12933    }
12934
12935    #[test]
12936    fn merge_indicator_column_d3ec6() {
12937        use std::collections::BTreeSet;
12938        // br-frankenpandas-d3ec6: outer-join indicator marks left_only/both/right_only.
12939        let left = DataFrame::from_dict(
12940            &["k"],
12941            vec![(
12942                "k",
12943                vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
12944            )],
12945        )
12946        .expect("left");
12947        let right = DataFrame::from_dict(
12948            &["k"],
12949            vec![(
12950                "k",
12951                vec![Scalar::Int64(2), Scalar::Int64(3), Scalar::Int64(4)],
12952            )],
12953        )
12954        .expect("right");
12955        let opts = super::MergeExecutionOptions {
12956            indicator_name: Some("_merge".to_owned()),
12957            ..Default::default()
12958        };
12959        let m = super::merge_dataframes_on_with_options(
12960            &left,
12961            &right,
12962            &["k"],
12963            &["k"],
12964            JoinType::Outer,
12965            opts,
12966        )
12967        .expect("merge");
12968
12969        let keys = merged_values(&m, "k").expect("k");
12970        let ind = merged_values(&m, "_merge").expect("_merge present");
12971        let lset: BTreeSet<i64> = [1, 2, 3].into_iter().collect();
12972        let rset: BTreeSet<i64> = [2, 3, 4].into_iter().collect();
12973        assert_eq!(keys.len(), 4, "outer keys = union");
12974        for i in 0..keys.len() {
12975            let k = match &keys[i] {
12976                Scalar::Int64(v) => *v,
12977                _ => i64::MIN,
12978            };
12979            let exp = match (lset.contains(&k), rset.contains(&k)) {
12980                (true, true) => "both",
12981                (true, false) => "left_only",
12982                (false, true) => "right_only",
12983                (false, false) => "??",
12984            };
12985            assert_eq!(ind[i], Scalar::Utf8(exp.to_owned()), "indicator at key {k}");
12986        }
12987    }
12988
12989    #[test]
12990    fn merge_overlapping_columns_suffixed_vb10q() {
12991        // br-frankenpandas-vb10q: a non-key column present in both frames is
12992        // suffixed _x (left) / _y (right) on merge.
12993        let mk = |vfactor: i64| {
12994            DataFrame::from_dict(
12995                &["k", "v"],
12996                vec![
12997                    (
12998                        "k",
12999                        vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
13000                    ),
13001                    (
13002                        "v",
13003                        vec![
13004                            Scalar::Int64(vfactor),
13005                            Scalar::Int64(2 * vfactor),
13006                            Scalar::Int64(3 * vfactor),
13007                        ],
13008                    ),
13009                ],
13010            )
13011            .expect("frame")
13012        };
13013        let left = mk(10); // v = k*10
13014        let right = mk(100); // v = k*100
13015        let merged = merge_dataframes(&left, &right, "k", JoinType::Inner).expect("merge");
13016
13017        let keys = merged_values(&merged, "k").expect("k");
13018        let vx = merged_values(&merged, "v_x").expect("v_x present");
13019        let vy = merged_values(&merged, "v_y").expect("v_y present");
13020        assert_eq!(keys.len(), 3);
13021        for i in 0..keys.len() {
13022            let k = match &keys[i] {
13023                Scalar::Int64(x) => *x,
13024                _ => i64::MIN,
13025            };
13026            assert_eq!(vx[i], Scalar::Int64(k * 10), "v_x at key {k}");
13027            assert_eq!(vy[i], Scalar::Int64(k * 100), "v_y at key {k}");
13028        }
13029    }
13030
13031    #[test]
13032    fn int64_join_row_count_matches_cardinality_invariant_ya1po() {
13033        use std::collections::BTreeMap;
13034
13035        // Metamorphic harness (br-frankenpandas-ya1po): merge_dataframes row count
13036        // must equal the pandas-standard cardinality per join type — an
13037        // ordering-independent invariant guarding the dense/direct-address Int64
13038        // join fast paths. Deterministic seeded LCG — no rand crate, no mocks.
13039        let mut state: u64 = 0xa5a5_5a5a_dead_beef;
13040        let mut next = || {
13041            state = state
13042                .wrapping_mul(6_364_136_223_846_793_005)
13043                .wrapping_add(1_442_695_040_888_963_407);
13044            (state >> 33) as u32
13045        };
13046
13047        let build = |keys: &[i64], payload_name: &str| {
13048            let n = keys.len();
13049            DataFrame::from_dict(
13050                &["k", payload_name],
13051                vec![
13052                    (
13053                        "k",
13054                        keys.iter().copied().map(Scalar::Int64).collect::<Vec<_>>(),
13055                    ),
13056                    (
13057                        payload_name,
13058                        (0..n as i64).map(Scalar::Int64).collect::<Vec<_>>(),
13059                    ),
13060                ],
13061            )
13062            .expect("frame")
13063        };
13064
13065        for iter in 0..1500u32 {
13066            let nl = (next() % 9) as usize + 1;
13067            let nr = (next() % 9) as usize + 1;
13068            // Small key range so many-to-many (duplicate-key) joins are common.
13069            let lk: Vec<i64> = (0..nl).map(|_| (next() % 4) as i64).collect();
13070            let rk: Vec<i64> = (0..nr).map(|_| (next() % 4) as i64).collect();
13071            let left = build(&lk, "lv");
13072            let right = build(&rk, "rv");
13073
13074            let mut lc: BTreeMap<i64, i64> = BTreeMap::new();
13075            let mut rc: BTreeMap<i64, i64> = BTreeMap::new();
13076            for &k in &lk {
13077                *lc.entry(k).or_default() += 1;
13078            }
13079            for &k in &rk {
13080                *rc.entry(k).or_default() += 1;
13081            }
13082            let mut all_keys: Vec<i64> = lc.keys().chain(rc.keys()).copied().collect();
13083            all_keys.sort_unstable();
13084            all_keys.dedup();
13085
13086            let g = |k: i64, m: &BTreeMap<i64, i64>| m.get(&k).copied().unwrap_or(0);
13087            let inner: i64 = all_keys.iter().map(|&k| g(k, &lc) * g(k, &rc)).sum();
13088            let left_exp: i64 = lc.iter().map(|(&k, &l)| l * g(k, &rc).max(1)).sum();
13089            let right_exp: i64 = rc.iter().map(|(&k, &r)| r * g(k, &lc).max(1)).sum();
13090            let outer: i64 = all_keys
13091                .iter()
13092                .map(|&k| {
13093                    let (l, r) = (g(k, &lc), g(k, &rc));
13094                    if l > 0 && r > 0 { l * r } else { l + r }
13095                })
13096                .sum();
13097
13098            let ctx = format!("iter={iter} lk={lk:?} rk={rk:?}");
13099            for (jt, exp) in [
13100                (JoinType::Inner, inner),
13101                (JoinType::Left, left_exp),
13102                (JoinType::Right, right_exp),
13103                (JoinType::Outer, outer),
13104            ] {
13105                let merged = merge_dataframes(&left, &right, "k", jt).expect("merge");
13106                let rows = merged_values(&merged, "k").expect("key col").len() as i64;
13107                assert_eq!(rows, exp, "{jt:?} row count {ctx}");
13108            }
13109        }
13110    }
13111
13112    #[test]
13113    fn inner_join_value_multiset_matches_crossproduct_oracle_5foyp() {
13114        use std::collections::BTreeMap;
13115
13116        // Value-level oracle (br-frankenpandas-5foyp): an inner join must pair the
13117        // CORRECT rows, not merely produce the right count. Assert the multiset of
13118        // output (key, left_payload, right_payload) triples equals the
13119        // independently-computed per-key cross product. Ordering-independent
13120        // (sorted-vector compare). Deterministic seeded LCG — no rand, no mocks.
13121        let mut state: u64 = 0x0ddc_0ffe_e0dd_f00d;
13122        let mut next = || {
13123            state = state
13124                .wrapping_mul(6_364_136_223_846_793_005)
13125                .wrapping_add(1_442_695_040_888_963_407);
13126            (state >> 33) as u32
13127        };
13128
13129        let build = |keys: &[i64], pname: &str| {
13130            let n = keys.len();
13131            DataFrame::from_dict(
13132                &["k", pname],
13133                vec![
13134                    (
13135                        "k",
13136                        keys.iter().copied().map(Scalar::Int64).collect::<Vec<_>>(),
13137                    ),
13138                    // Distinct per-row payload (= row index) so mis-pairings are visible.
13139                    (pname, (0..n as i64).map(Scalar::Int64).collect::<Vec<_>>()),
13140                ],
13141            )
13142            .expect("frame")
13143        };
13144        // Extract i64; a non-Int64 maps to a sentinel that will never equal a
13145        // real row index/key, so any dtype regression still fails the multiset
13146        // assert below (no panic — keeps the helper side-effect-free).
13147        let geti = |s: &Scalar| match s {
13148            Scalar::Int64(v) => *v,
13149            _ => i64::MIN,
13150        };
13151
13152        for iter in 0..1500u32 {
13153            let nl = (next() % 9) as usize + 1;
13154            let nr = (next() % 9) as usize + 1;
13155            let lk: Vec<i64> = (0..nl).map(|_| (next() % 4) as i64).collect();
13156            let rk: Vec<i64> = (0..nr).map(|_| (next() % 4) as i64).collect();
13157            let left = build(&lk, "lv");
13158            let right = build(&rk, "rv");
13159
13160            let merged = merge_dataframes(&left, &right, "k", JoinType::Inner).expect("merge");
13161            let ks = merged_values(&merged, "k").expect("k");
13162            let lvs = merged_values(&merged, "lv").expect("lv");
13163            let rvs = merged_values(&merged, "rv").expect("rv");
13164            let mut got: Vec<(i64, i64, i64)> = (0..ks.len())
13165                .map(|i| (geti(&ks[i]), geti(&lvs[i]), geti(&rvs[i])))
13166                .collect();
13167            got.sort_unstable();
13168
13169            // Independent oracle: per-key cross product of left/right row payloads.
13170            let mut lg: BTreeMap<i64, Vec<i64>> = BTreeMap::new();
13171            let mut rg: BTreeMap<i64, Vec<i64>> = BTreeMap::new();
13172            for (i, &k) in lk.iter().enumerate() {
13173                lg.entry(k).or_default().push(i as i64);
13174            }
13175            for (i, &k) in rk.iter().enumerate() {
13176                rg.entry(k).or_default().push(i as i64);
13177            }
13178            let mut exp: Vec<(i64, i64, i64)> = Vec::new();
13179            for (&k, lps) in &lg {
13180                if let Some(rps) = rg.get(&k) {
13181                    for &a in lps {
13182                        for &b in rps {
13183                            exp.push((k, a, b));
13184                        }
13185                    }
13186                }
13187            }
13188            exp.sort_unstable();
13189
13190            assert_eq!(
13191                got, exp,
13192                "inner join value multiset iter={iter} lk={lk:?} rk={rk:?}"
13193            );
13194        }
13195    }
13196
13197    #[test]
13198    fn left_outer_join_nullfill_value_oracle_kaj3t() {
13199        use std::collections::BTreeMap;
13200
13201        // Value oracle for LEFT/OUTER null-fill (br-frankenpandas-kaj3t): unmatched
13202        // rows get NULL-filled on the absent side — the subtlest join behavior.
13203        // NULL is represented by the i64::MIN sentinel (payloads are 0..n and keys
13204        // 0..3, so a sentinel never collides with a real value). Deterministic
13205        // seeded LCG — no rand crate, no mocks.
13206        const NUL: i64 = i64::MIN;
13207        let mut state: u64 = 0xfeed_face_cafe_b0ba;
13208        let mut next = || {
13209            state = state
13210                .wrapping_mul(6_364_136_223_846_793_005)
13211                .wrapping_add(1_442_695_040_888_963_407);
13212            (state >> 33) as u32
13213        };
13214
13215        let build = |keys: &[i64], pname: &str| {
13216            let n = keys.len();
13217            DataFrame::from_dict(
13218                &["k", pname],
13219                vec![
13220                    (
13221                        "k",
13222                        keys.iter().copied().map(Scalar::Int64).collect::<Vec<_>>(),
13223                    ),
13224                    (pname, (0..n as i64).map(Scalar::Int64).collect::<Vec<_>>()),
13225                ],
13226            )
13227            .expect("frame")
13228        };
13229        // Int64 -> value. Left/outer joins upcast Int64 payload columns to
13230        // Float64 when null-fill introduces missing values (pandas parity: Int64
13231        // can't hold NaN), so accept finite Float64 too. NULL / NaN -> NUL
13232        // sentinel. Payloads are small whole numbers, so f64 -> i64 is exact.
13233        let geti = |s: &Scalar| match s {
13234            Scalar::Int64(v) => *v,
13235            Scalar::Float64(v) if v.is_finite() => *v as i64,
13236            _ => NUL,
13237        };
13238
13239        for iter in 0..1500u32 {
13240            let nl = (next() % 9) as usize + 1;
13241            let nr = (next() % 9) as usize + 1;
13242            let lk: Vec<i64> = (0..nl).map(|_| (next() % 4) as i64).collect();
13243            let rk: Vec<i64> = (0..nr).map(|_| (next() % 4) as i64).collect();
13244            let left = build(&lk, "lv");
13245            let right = build(&rk, "rv");
13246
13247            // Right rows grouped by key (payload = row index).
13248            let mut rg: BTreeMap<i64, Vec<i64>> = BTreeMap::new();
13249            for (j, &k) in rk.iter().enumerate() {
13250                rg.entry(k).or_default().push(j as i64);
13251            }
13252            let lkeys: std::collections::BTreeSet<i64> = lk.iter().copied().collect();
13253
13254            let read = |jt: JoinType| -> Vec<(i64, i64, i64)> {
13255                let merged = merge_dataframes(&left, &right, "k", jt).expect("merge");
13256                let ks = merged_values(&merged, "k").expect("k");
13257                let lvs = merged_values(&merged, "lv").expect("lv");
13258                let rvs = merged_values(&merged, "rv").expect("rv");
13259                let mut got: Vec<(i64, i64, i64)> = (0..ks.len())
13260                    .map(|i| (geti(&ks[i]), geti(&lvs[i]), geti(&rvs[i])))
13261                    .collect();
13262                got.sort_unstable();
13263                got
13264            };
13265
13266            // LEFT oracle: every left row appears; matched -> one row per right
13267            // match, unmatched -> NULL right payload (key still the left key).
13268            let mut exp_left: Vec<(i64, i64, i64)> = Vec::new();
13269            for (i, &k) in lk.iter().enumerate() {
13270                match rg.get(&k) {
13271                    Some(rps) => {
13272                        for &j in rps {
13273                            exp_left.push((k, i as i64, j));
13274                        }
13275                    }
13276                    None => exp_left.push((k, i as i64, NUL)),
13277                }
13278            }
13279            exp_left.sort_unstable();
13280            assert_eq!(
13281                read(JoinType::Left),
13282                exp_left,
13283                "left join value oracle iter={iter} lk={lk:?} rk={rk:?}"
13284            );
13285
13286            // OUTER oracle: LEFT plus right-only rows (no left match) with NULL
13287            // left payload and the coalesced key.
13288            let mut exp_outer = exp_left.clone();
13289            for (j, &k) in rk.iter().enumerate() {
13290                if !lkeys.contains(&k) {
13291                    exp_outer.push((k, NUL, j as i64));
13292                }
13293            }
13294            exp_outer.sort_unstable();
13295            assert_eq!(
13296                read(JoinType::Outer),
13297                exp_outer,
13298                "outer join value oracle iter={iter} lk={lk:?} rk={rk:?}"
13299            );
13300        }
13301    }
13302
13303    #[test]
13304    fn left_join_value_multiset_matches_unmatched_oracle_gp0ik() {
13305        use std::collections::BTreeMap;
13306
13307        // Value-level LEFT join oracle (br-frankenpandas-gp0ik): matched keys
13308        // emit the left/right cross product; unmatched left rows emit exactly one
13309        // row with a missing right payload. Ordering-independent sorted multiset.
13310        let mut state: u64 = 0x51de_cafe_2026_0618;
13311        let mut next = || {
13312            state = state
13313                .wrapping_mul(6_364_136_223_846_793_005)
13314                .wrapping_add(1_442_695_040_888_963_407);
13315            (state >> 33) as u32
13316        };
13317
13318        let build = |keys: &[i64], pname: &str| {
13319            let n = keys.len();
13320            DataFrame::from_dict(
13321                &["k", pname],
13322                vec![
13323                    (
13324                        "k",
13325                        keys.iter().copied().map(Scalar::Int64).collect::<Vec<_>>(),
13326                    ),
13327                    (pname, (0..n as i64).map(Scalar::Int64).collect::<Vec<_>>()),
13328                ],
13329            )
13330            .expect("frame")
13331        };
13332        let geti = |s: &Scalar| match s {
13333            Scalar::Int64(v) => *v,
13334            _ => i64::MIN,
13335        };
13336        let get_optional_i64 = |s: &Scalar| match s {
13337            Scalar::Int64(v) => Some(*v),
13338            Scalar::Float64(v) if v.is_finite() && v.fract() == 0.0 => Some(*v as i64),
13339            value if value.is_missing() => None,
13340            _ => Some(i64::MIN),
13341        };
13342
13343        for iter in 0..1500u32 {
13344            let nl = (next() % 9) as usize + 1;
13345            let nr = (next() % 9) as usize + 1;
13346            let lk: Vec<i64> = (0..nl).map(|_| (next() % 5) as i64).collect();
13347            let rk: Vec<i64> = (0..nr).map(|_| (next() % 3) as i64).collect();
13348            let left = build(&lk, "lv");
13349            let right = build(&rk, "rv");
13350
13351            let merged = merge_dataframes(&left, &right, "k", JoinType::Left).expect("merge");
13352            let ks = merged_values(&merged, "k").expect("k");
13353            let lvs = merged_values(&merged, "lv").expect("lv");
13354            let rvs = merged_values(&merged, "rv").expect("rv");
13355            let mut got: Vec<(i64, i64, Option<i64>)> = (0..ks.len())
13356                .map(|i| (geti(&ks[i]), geti(&lvs[i]), get_optional_i64(&rvs[i])))
13357                .collect();
13358            got.sort_unstable();
13359
13360            let mut rg: BTreeMap<i64, Vec<i64>> = BTreeMap::new();
13361            for (i, &k) in rk.iter().enumerate() {
13362                rg.entry(k).or_default().push(i as i64);
13363            }
13364            let mut exp: Vec<(i64, i64, Option<i64>)> = Vec::new();
13365            for (left_pos, &k) in lk.iter().enumerate() {
13366                if let Some(right_positions) = rg.get(&k) {
13367                    for &right_pos in right_positions {
13368                        exp.push((k, left_pos as i64, Some(right_pos)));
13369                    }
13370                } else {
13371                    exp.push((k, left_pos as i64, None));
13372                }
13373            }
13374            exp.sort_unstable();
13375
13376            assert_eq!(
13377                got, exp,
13378                "left join value multiset iter={iter} lk={lk:?} rk={rk:?}"
13379            );
13380        }
13381    }
13382
13383    #[test]
13384    fn right_join_value_multiset_matches_unmatched_oracle_pd1h5() {
13385        use std::collections::BTreeMap;
13386
13387        // Value-level RIGHT join oracle (br-frankenpandas-pd1h5): matched keys
13388        // emit the left/right cross product; unmatched right rows emit exactly one
13389        // row with a missing left payload. Ordering-independent sorted multiset.
13390        let mut state: u64 = 0x7191_2026_0618_a015;
13391        let mut next = || {
13392            state = state
13393                .wrapping_mul(6_364_136_223_846_793_005)
13394                .wrapping_add(1_442_695_040_888_963_407);
13395            (state >> 33) as u32
13396        };
13397
13398        let build = |keys: &[i64], pname: &str| {
13399            let n = keys.len();
13400            DataFrame::from_dict(
13401                &["k", pname],
13402                vec![
13403                    (
13404                        "k",
13405                        keys.iter().copied().map(Scalar::Int64).collect::<Vec<_>>(),
13406                    ),
13407                    (pname, (0..n as i64).map(Scalar::Int64).collect::<Vec<_>>()),
13408                ],
13409            )
13410            .expect("frame")
13411        };
13412        let geti = |s: &Scalar| match s {
13413            Scalar::Int64(v) => *v,
13414            Scalar::Float64(v) if v.is_finite() => *v as i64,
13415            _ => i64::MIN,
13416        };
13417        let get_optional_i64 = |s: &Scalar| match s {
13418            Scalar::Int64(v) => Some(*v),
13419            Scalar::Float64(v) if v.is_finite() => Some(*v as i64),
13420            value if value.is_missing() => None,
13421            _ => Some(i64::MIN),
13422        };
13423
13424        for iter in 0..1500u32 {
13425            let nl = (next() % 9) as usize + 1;
13426            let nr = (next() % 9) as usize + 1;
13427            let lk: Vec<i64> = (0..nl).map(|_| (next() % 4) as i64).collect();
13428            let rk: Vec<i64> = (0..nr).map(|_| (next() % 5) as i64).collect();
13429            let left = build(&lk, "lv");
13430            let right = build(&rk, "rv");
13431
13432            let merged = merge_dataframes(&left, &right, "k", JoinType::Right).expect("merge");
13433            let ks = merged_values(&merged, "k").expect("k");
13434            let lvs = merged_values(&merged, "lv").expect("lv");
13435            let rvs = merged_values(&merged, "rv").expect("rv");
13436            let mut got: Vec<(i64, Option<i64>, i64)> = (0..ks.len())
13437                .map(|i| (geti(&ks[i]), get_optional_i64(&lvs[i]), geti(&rvs[i])))
13438                .collect();
13439            got.sort_unstable();
13440
13441            let mut lg: BTreeMap<i64, Vec<i64>> = BTreeMap::new();
13442            for (i, &k) in lk.iter().enumerate() {
13443                lg.entry(k).or_default().push(i as i64);
13444            }
13445            let mut exp: Vec<(i64, Option<i64>, i64)> = Vec::new();
13446            for (right_pos, &k) in rk.iter().enumerate() {
13447                if let Some(left_positions) = lg.get(&k) {
13448                    for &left_pos in left_positions {
13449                        exp.push((k, Some(left_pos), right_pos as i64));
13450                    }
13451                } else {
13452                    exp.push((k, None, right_pos as i64));
13453                }
13454            }
13455            exp.sort_unstable();
13456
13457            assert_eq!(
13458                got, exp,
13459                "right join value multiset iter={iter} lk={lk:?} rk={rk:?}"
13460            );
13461        }
13462    }
13463
13464    fn merged_values<'a>(
13465        merged: &'a MergedDataFrame,
13466        name: &str,
13467    ) -> Result<&'a [Scalar], JoinError> {
13468        Ok(merged
13469            .columns
13470            .get(name)
13471            .ok_or_else(|| {
13472                JoinError::Frame(FrameError::CompatibilityRejected(format!(
13473                    "missing merged column '{name}'"
13474                )))
13475            })?
13476            .values())
13477    }
13478
13479    #[test]
13480    fn temporal_i64_inner_positions_match_scalar_oracle_with_duplicates_b2hwb() {
13481        let build_positions_from_scalar_oracle = |left: &Column, right: &Column| {
13482            let left_keys = super::collect_single_join_keys(left);
13483            let right_keys = super::collect_single_join_keys(right);
13484            let mut left_positions = Vec::new();
13485            let mut right_positions = Vec::new();
13486            for (left_pos, left_key) in left_keys.iter().enumerate() {
13487                for (right_pos, right_key) in right_keys.iter().enumerate() {
13488                    if left_key == right_key {
13489                        left_positions.push(left_pos);
13490                        right_positions.push(right_pos);
13491                    }
13492                }
13493            }
13494            (left_positions, right_positions)
13495        };
13496
13497        let left_ns = [30, 10, 20, 10];
13498        let right_ns = [10, 30, 10, 40];
13499        for temporal in [DType::datetime64_naive(), DType::Timedelta64] {
13500            let scalar = |ns| match &temporal {
13501                DType::Datetime64 { .. } => Scalar::Datetime64(ns),
13502                DType::Timedelta64 => Scalar::Timedelta64(ns),
13503                _ => unreachable!("test iterates only temporal dtypes"),
13504            };
13505            let left = Column::from_values(left_ns.into_iter().map(scalar).collect())
13506                .expect("left temporal key");
13507            let right = Column::from_values(right_ns.into_iter().map(scalar).collect())
13508                .expect("right temporal key");
13509
13510            assert_eq!(
13511                super::temporal_i64_inner_positions(&left, &right),
13512                Some(build_positions_from_scalar_oracle(&left, &right)),
13513                "raw-nanosecond planner must preserve scalar-oracle pair order for {temporal:?}"
13514            );
13515        }
13516
13517        let nat = fp_types::Timestamp::NAT;
13518        let ordered = Column::from_datetime64_values(vec![1, 2, 3, 4]);
13519        let nat_middle = Column::from_datetime64_values(vec![1, 2, nat, 4]);
13520        let nat_tail = Column::from_datetime64_values(vec![1, 2, 3, nat]);
13521        let single_nat = Column::from_datetime64_values(vec![nat]);
13522        for (left, right) in [
13523            (&nat_middle, &ordered),
13524            (&ordered, &nat_tail),
13525            (&single_nat, &ordered),
13526        ] {
13527            assert!(
13528                super::temporal_i64_inner_positions(left, right).is_none(),
13529                "NaT anywhere must retain the scalar INNER fallback",
13530            );
13531        }
13532    }
13533
13534    #[test]
13535    #[ignore = "foreground performance probe"]
13536    fn bench_temporal_i64_inner_validation_fusion_71kgc() {
13537        let n = 400_000_i64;
13538        let input_len = usize::try_from(n).expect("positive benchmark length");
13539        let left = Column::from_datetime64_values_with_validity(
13540            (0..n).collect(),
13541            ValidityMask::all_valid(input_len),
13542        );
13543        let right = Column::from_datetime64_values_with_validity(
13544            (0..n).map(|value| value * 2).collect(),
13545            ValidityMask::all_valid(input_len),
13546        );
13547
13548        // Exact pre-71kgc ordered body: separate NaT and strict-order scans
13549        // followed by the same two-pointer intersection.
13550        let former = || {
13551            if !left.validity().all() || !right.validity().all() {
13552                return None;
13553            }
13554            let left_raw = left.as_datetime64_slice()?;
13555            let right_raw = right.as_datetime64_slice()?;
13556            let nat = fp_types::Timestamp::NAT;
13557            if left_raw.contains(&nat) || right_raw.contains(&nat) {
13558                return None;
13559            }
13560            if left_raw.windows(2).any(|pair| pair[0] >= pair[1])
13561                || right_raw.windows(2).any(|pair| pair[0] >= pair[1])
13562            {
13563                return None;
13564            }
13565
13566            let mut left_positions = Vec::with_capacity(left_raw.len().min(right_raw.len()));
13567            let mut right_positions = Vec::with_capacity(left_positions.capacity());
13568            let (mut left_idx, mut right_idx) = (0usize, 0usize);
13569            while left_idx < left_raw.len() && right_idx < right_raw.len() {
13570                match left_raw[left_idx].cmp(&right_raw[right_idx]) {
13571                    std::cmp::Ordering::Equal => {
13572                        left_positions.push(left_idx);
13573                        right_positions.push(right_idx);
13574                        left_idx += 1;
13575                        right_idx += 1;
13576                    }
13577                    std::cmp::Ordering::Less => left_idx += 1,
13578                    std::cmp::Ordering::Greater => right_idx += 1,
13579                }
13580            }
13581            Some((left_positions, right_positions))
13582        };
13583        let candidate = || super::temporal_i64_inner_positions(&left, &right);
13584
13585        let former_output = former().expect("former temporal INNER positions");
13586        let candidate_output = candidate().expect("temporal INNER positions");
13587        assert_eq!(candidate_output, former_output);
13588        assert_eq!(candidate_output.0.len(), input_len.div_ceil(2));
13589        drop((former_output, candidate_output));
13590        for _ in 0..2 {
13591            std::hint::black_box(former());
13592            std::hint::black_box(candidate());
13593        }
13594
13595        type InnerPositions = Option<(Vec<usize>, Vec<usize>)>;
13596        let sample = |plan: &dyn Fn() -> InnerPositions| {
13597            let start = std::time::Instant::now();
13598            let output = std::hint::black_box(plan()).expect("supported temporal INNER plan");
13599            assert_eq!(std::hint::black_box(output.0.len()), input_len.div_ceil(2));
13600            drop(output);
13601            start.elapsed().as_secs_f64() * 1_000.0
13602        };
13603        let mut former_a = Vec::with_capacity(15);
13604        let mut former_b = Vec::with_capacity(15);
13605        let mut candidate_a = Vec::with_capacity(15);
13606        let mut candidate_b = Vec::with_capacity(15);
13607        for round in 0..15 {
13608            if round % 2 == 0 {
13609                former_a.push(sample(&former));
13610                candidate_a.push(sample(&candidate));
13611                candidate_b.push(sample(&candidate));
13612                former_b.push(sample(&former));
13613            } else {
13614                former_b.push(sample(&former));
13615                candidate_b.push(sample(&candidate));
13616                candidate_a.push(sample(&candidate));
13617                former_a.push(sample(&former));
13618            }
13619        }
13620
13621        let report = |label: &str, mut samples: Vec<f64>| {
13622            samples.sort_by(f64::total_cmp);
13623            let p50 = samples[samples.len() / 2];
13624            let p95_idx = samples
13625                .len()
13626                .saturating_mul(95)
13627                .div_ceil(100)
13628                .saturating_sub(1);
13629            println!(
13630                "{label}: p50={p50:.3} ms p95={:.3} ms max={:.3} ms",
13631                samples[p95_idx],
13632                samples[samples.len() - 1],
13633            );
13634        };
13635        report("inner_plan_three_pass_former_a", former_a);
13636        report("inner_plan_three_pass_former_b", former_b);
13637        report("inner_plan_fused_candidate_a", candidate_a);
13638        report("inner_plan_fused_candidate_b", candidate_b);
13639    }
13640
13641    #[test]
13642    fn merge_datetime_inner_preserves_dtype_order_and_nat_fallback_b2hwb() -> Result<(), JoinError>
13643    {
13644        let left = DataFrame::from_dict(
13645            &["key", "lv"],
13646            vec![
13647                (
13648                    "key",
13649                    vec![
13650                        Scalar::Datetime64(30),
13651                        Scalar::Datetime64(10),
13652                        Scalar::Datetime64(20),
13653                        Scalar::Datetime64(10),
13654                    ],
13655                ),
13656                (
13657                    "lv",
13658                    vec![
13659                        Scalar::Int64(0),
13660                        Scalar::Int64(1),
13661                        Scalar::Int64(2),
13662                        Scalar::Int64(3),
13663                    ],
13664                ),
13665            ],
13666        )?;
13667        let right = DataFrame::from_dict(
13668            &["key", "rv"],
13669            vec![
13670                (
13671                    "key",
13672                    vec![
13673                        Scalar::Datetime64(10),
13674                        Scalar::Datetime64(30),
13675                        Scalar::Datetime64(10),
13676                        Scalar::Datetime64(40),
13677                    ],
13678                ),
13679                (
13680                    "rv",
13681                    vec![
13682                        Scalar::Int64(100),
13683                        Scalar::Int64(101),
13684                        Scalar::Int64(102),
13685                        Scalar::Int64(103),
13686                    ],
13687                ),
13688            ],
13689        )?;
13690        let merged = merge_dataframes_on(&left, &right, &["key"], JoinType::Inner)?;
13691        assert_eq!(merged.columns["key"].dtype(), DType::datetime64_naive());
13692        assert_eq!(
13693            merged_values(&merged, "key")?,
13694            &[
13695                Scalar::Datetime64(30),
13696                Scalar::Datetime64(10),
13697                Scalar::Datetime64(10),
13698                Scalar::Datetime64(10),
13699                Scalar::Datetime64(10),
13700            ]
13701        );
13702        assert_eq!(
13703            merged_values(&merged, "lv")?,
13704            &[
13705                Scalar::Int64(0),
13706                Scalar::Int64(1),
13707                Scalar::Int64(1),
13708                Scalar::Int64(3),
13709                Scalar::Int64(3),
13710            ]
13711        );
13712        assert_eq!(
13713            merged_values(&merged, "rv")?,
13714            &[
13715                Scalar::Int64(101),
13716                Scalar::Int64(100),
13717                Scalar::Int64(102),
13718                Scalar::Int64(100),
13719                Scalar::Int64(102),
13720            ]
13721        );
13722
13723        let nat = fp_types::Timestamp::NAT;
13724        let nat_left = DataFrame::from_dict(
13725            &["key", "lv"],
13726            vec![
13727                ("key", vec![Scalar::Datetime64(nat), Scalar::Datetime64(5)]),
13728                ("lv", vec![Scalar::Int64(0), Scalar::Int64(1)]),
13729            ],
13730        )?;
13731        let nat_right = DataFrame::from_dict(
13732            &["key", "rv"],
13733            vec![
13734                ("key", vec![Scalar::Datetime64(nat), Scalar::Datetime64(5)]),
13735                ("rv", vec![Scalar::Int64(10), Scalar::Int64(11)]),
13736            ],
13737        )?;
13738        assert!(
13739            super::temporal_i64_inner_positions(
13740                nat_left.column("key").expect("left NaT key"),
13741                nat_right.column("key").expect("right NaT key")
13742            )
13743            .is_none(),
13744            "NaT must retain the scalar Missing-key fallback"
13745        );
13746        let nat_merged = merge_dataframes_on(&nat_left, &nat_right, &["key"], JoinType::Inner)?;
13747        assert_eq!(nat_merged.columns["key"].dtype(), DType::datetime64_naive());
13748        assert_eq!(nat_merged.index.len(), 2);
13749        assert!(merged_values(&nat_merged, "key")?[0].is_missing());
13750        assert_eq!(
13751            &merged_values(&nat_merged, "key")?[1..],
13752            &[Scalar::Datetime64(5)]
13753        );
13754
13755        Ok(())
13756    }
13757
13758    #[test]
13759    fn temporal_i64_left_positions_match_scalar_oracle_with_duplicates_lw0qg() {
13760        let build_positions_from_scalar_oracle = |left: &Column, right: &Column| {
13761            let left_keys = super::collect_single_join_keys(left);
13762            let right_keys = super::collect_single_join_keys(right);
13763            let mut left_positions = Vec::new();
13764            let mut right_positions = Vec::new();
13765            for (left_pos, left_key) in left_keys.iter().enumerate() {
13766                let mut matched = false;
13767                for (right_pos, right_key) in right_keys.iter().enumerate() {
13768                    if left_key == right_key {
13769                        left_positions.push(Some(left_pos));
13770                        right_positions.push(Some(right_pos));
13771                        matched = true;
13772                    }
13773                }
13774                if !matched {
13775                    left_positions.push(Some(left_pos));
13776                    right_positions.push(None);
13777                }
13778            }
13779            (left_positions, right_positions)
13780        };
13781
13782        let left_ns = [30, 10, 20, 10, 50];
13783        let right_ns = [10, 30, 10, 40];
13784        for temporal in [DType::datetime64_naive(), DType::Timedelta64] {
13785            let scalar = |ns| match &temporal {
13786                DType::Datetime64 { .. } => Scalar::Datetime64(ns),
13787                DType::Timedelta64 => Scalar::Timedelta64(ns),
13788                _ => unreachable!("test iterates only temporal dtypes"),
13789            };
13790            let left = Column::from_values(left_ns.into_iter().map(scalar).collect())
13791                .expect("left temporal key");
13792            let right = Column::from_values(right_ns.into_iter().map(scalar).collect())
13793                .expect("right temporal key");
13794
13795            assert_eq!(
13796                super::temporal_i64_left_positions(&left, &right),
13797                Some(build_positions_from_scalar_oracle(&left, &right)),
13798                "raw-nanosecond LEFT planner must preserve scalar-oracle row order for {temporal:?}"
13799            );
13800        }
13801    }
13802
13803    #[test]
13804    fn merge_datetime_left_preserves_dtype_order_and_nat_fallback_lw0qg() -> Result<(), JoinError> {
13805        let left = DataFrame::from_dict(
13806            &["key", "lv"],
13807            vec![
13808                (
13809                    "key",
13810                    vec![
13811                        Scalar::Datetime64(30),
13812                        Scalar::Datetime64(10),
13813                        Scalar::Datetime64(20),
13814                        Scalar::Datetime64(10),
13815                        Scalar::Datetime64(50),
13816                    ],
13817                ),
13818                (
13819                    "lv",
13820                    vec![
13821                        Scalar::Int64(0),
13822                        Scalar::Int64(1),
13823                        Scalar::Int64(2),
13824                        Scalar::Int64(3),
13825                        Scalar::Int64(4),
13826                    ],
13827                ),
13828            ],
13829        )?;
13830        let right = DataFrame::from_dict(
13831            &["key", "rv"],
13832            vec![
13833                (
13834                    "key",
13835                    vec![
13836                        Scalar::Datetime64(10),
13837                        Scalar::Datetime64(30),
13838                        Scalar::Datetime64(10),
13839                        Scalar::Datetime64(40),
13840                    ],
13841                ),
13842                (
13843                    "rv",
13844                    vec![
13845                        Scalar::Int64(100),
13846                        Scalar::Int64(101),
13847                        Scalar::Int64(102),
13848                        Scalar::Int64(103),
13849                    ],
13850                ),
13851            ],
13852        )?;
13853        let merged = merge_dataframes_on(&left, &right, &["key"], JoinType::Left)?;
13854        assert_eq!(merged.columns["key"].dtype(), DType::datetime64_naive());
13855        assert_eq!(
13856            merged_values(&merged, "key")?,
13857            &[
13858                Scalar::Datetime64(30),
13859                Scalar::Datetime64(10),
13860                Scalar::Datetime64(10),
13861                Scalar::Datetime64(20),
13862                Scalar::Datetime64(10),
13863                Scalar::Datetime64(10),
13864                Scalar::Datetime64(50),
13865            ]
13866        );
13867        assert_eq!(
13868            merged_values(&merged, "lv")?,
13869            &[
13870                Scalar::Int64(0),
13871                Scalar::Int64(1),
13872                Scalar::Int64(1),
13873                Scalar::Int64(2),
13874                Scalar::Int64(3),
13875                Scalar::Int64(3),
13876                Scalar::Int64(4),
13877            ]
13878        );
13879        let right_values = merged_values(&merged, "rv")?;
13880        assert_eq!(right_values.len(), 7);
13881        assert_eq!(right_values[0], Scalar::Float64(101.0));
13882        assert_eq!(
13883            &right_values[1..3],
13884            &[Scalar::Float64(100.0), Scalar::Float64(102.0)]
13885        );
13886        assert!(right_values[3].is_missing());
13887        assert_eq!(
13888            &right_values[4..6],
13889            &[Scalar::Float64(100.0), Scalar::Float64(102.0)]
13890        );
13891        assert!(right_values[6].is_missing());
13892
13893        let nat = fp_types::Timestamp::NAT;
13894        let nat_left = DataFrame::from_dict(
13895            &["key", "lv"],
13896            vec![
13897                (
13898                    "key",
13899                    vec![
13900                        Scalar::Datetime64(nat),
13901                        Scalar::Datetime64(5),
13902                        Scalar::Datetime64(7),
13903                    ],
13904                ),
13905                (
13906                    "lv",
13907                    vec![Scalar::Int64(0), Scalar::Int64(1), Scalar::Int64(2)],
13908                ),
13909            ],
13910        )?;
13911        let nat_right = DataFrame::from_dict(
13912            &["key", "rv"],
13913            vec![
13914                ("key", vec![Scalar::Datetime64(nat), Scalar::Datetime64(5)]),
13915                ("rv", vec![Scalar::Int64(10), Scalar::Int64(11)]),
13916            ],
13917        )?;
13918        assert!(
13919            super::temporal_i64_left_positions(
13920                nat_left.column("key").expect("left NaT key"),
13921                nat_right.column("key").expect("right NaT key")
13922            )
13923            .is_none(),
13924            "NaT must retain the scalar Missing-key fallback"
13925        );
13926        let nat_merged = merge_dataframes_on(&nat_left, &nat_right, &["key"], JoinType::Left)?;
13927        assert_eq!(nat_merged.columns["key"].dtype(), DType::datetime64_naive());
13928        assert_eq!(nat_merged.index.len(), 3);
13929        assert!(merged_values(&nat_merged, "key")?[0].is_missing());
13930        assert_eq!(
13931            &merged_values(&nat_merged, "key")?[1..],
13932            &[Scalar::Datetime64(5), Scalar::Datetime64(7)]
13933        );
13934        let nat_right_values = merged_values(&nat_merged, "rv")?;
13935        assert_eq!(
13936            &nat_right_values[..2],
13937            &[Scalar::Float64(10.0), Scalar::Float64(11.0)]
13938        );
13939        assert!(nat_right_values[2].is_missing());
13940
13941        Ok(())
13942    }
13943
13944    #[test]
13945    fn temporal_i64_right_positions_match_scalar_oracle_and_reject_unsupported_8tf5c() {
13946        let scalar_oracle = |left: &Column, right: &Column| {
13947            let left_keys = super::collect_single_join_keys(left);
13948            let right_keys = super::collect_single_join_keys(right);
13949            right_keys
13950                .iter()
13951                .map(|right_key| left_keys.iter().position(|left_key| left_key == right_key))
13952                .collect::<Vec<_>>()
13953        };
13954
13955        let left_ns = [-20, 10, 30, 50];
13956        let right_ns = [-30, -20, 20, 30, 60];
13957        for temporal in [DType::datetime64_naive(), DType::Timedelta64] {
13958            let scalar = |ns| match &temporal {
13959                DType::Datetime64 { .. } => Scalar::Datetime64(ns),
13960                DType::Timedelta64 => Scalar::Timedelta64(ns),
13961                _ => unreachable!("test iterates only temporal dtypes"),
13962            };
13963            let left = Column::from_values(left_ns.into_iter().map(scalar).collect())
13964                .expect("left temporal key");
13965            let right = Column::from_values(right_ns.into_iter().map(scalar).collect())
13966                .expect("right temporal key");
13967            assert_eq!(
13968                super::ordered_unique_temporal_i64_right_match_positions(&left, &right),
13969                Some(scalar_oracle(&left, &right)),
13970                "raw-nanosecond RIGHT planner must preserve right-major scalar matches for {temporal:?}",
13971            );
13972        }
13973
13974        let empty_left = Column::from_datetime64_values(Vec::new());
13975        let ordered_right = Column::from_datetime64_values(vec![1, 2, 3]);
13976        assert_eq!(
13977            super::ordered_unique_temporal_i64_right_match_positions(&empty_left, &ordered_right,),
13978            Some(vec![None; 3]),
13979        );
13980
13981        let nat = fp_types::Timestamp::NAT;
13982        let nat_left = Column::from_datetime64_values(vec![nat, 1, 2]);
13983        let nat_middle_left = Column::from_datetime64_values(vec![1, nat, 3]);
13984        let nat_tail_right = Column::from_datetime64_values(vec![1, 2, nat]);
13985        let single_nat = Column::from_datetime64_values(vec![nat]);
13986        let duplicate_left = Column::from_datetime64_values(vec![1, 1, 2]);
13987        let late_duplicate_left = Column::from_datetime64_values(vec![1, 2, 3, 3]);
13988        let unsorted_right = Column::from_datetime64_values(vec![2, 1, 3]);
13989        let late_unsorted_right = Column::from_datetime64_values(vec![1, 2, 4, 3]);
13990        let mixed_right =
13991            Column::from_values([1, 2, 3].into_iter().map(Scalar::Timedelta64).collect())
13992                .expect("mixed timedelta key");
13993        let mut validity = ValidityMask::all_valid(3);
13994        validity.set(1, false);
13995        let nullable_left = Column::from_datetime64_values_with_validity(vec![1, 2, 3], validity);
13996        for (left, right) in [
13997            (&nat_left, &ordered_right),
13998            (&nat_middle_left, &ordered_right),
13999            (&ordered_right, &nat_tail_right),
14000            (&single_nat, &ordered_right),
14001            (&duplicate_left, &ordered_right),
14002            (&late_duplicate_left, &ordered_right),
14003            (&ordered_right, &unsorted_right),
14004            (&ordered_right, &late_unsorted_right),
14005            (&ordered_right, &mixed_right),
14006            (&nullable_left, &ordered_right),
14007        ] {
14008            assert!(
14009                super::ordered_unique_temporal_i64_right_match_positions(left, right).is_none(),
14010                "unsupported temporal RIGHT shape must retain the scalar fallback",
14011            );
14012        }
14013    }
14014
14015    #[test]
14016    #[ignore = "foreground performance probe"]
14017    fn bench_temporal_i64_right_validation_fusion_69e0m() {
14018        let n = 400_000_i64;
14019        let input_len = usize::try_from(n).expect("positive benchmark length");
14020        let left = Column::from_datetime64_values_with_validity(
14021            (0..n).collect(),
14022            ValidityMask::all_valid(input_len),
14023        );
14024        let right = Column::from_datetime64_values_with_validity(
14025            (0..n).map(|value| value * 2).collect(),
14026            ValidityMask::all_valid(input_len),
14027        );
14028
14029        // Exact pre-69e0m body: separate NaT and strict-order scans followed
14030        // by the same right-major two-pointer match.
14031        let former = || {
14032            if !left.validity().all() || !right.validity().all() {
14033                return None;
14034            }
14035            let left_raw = left.as_datetime64_slice()?;
14036            let right_raw = right.as_datetime64_slice()?;
14037            let nat = fp_types::Timestamp::NAT;
14038            if left_raw.contains(&nat) || right_raw.contains(&nat) {
14039                return None;
14040            }
14041            if left_raw.windows(2).any(|pair| pair[0] >= pair[1])
14042                || right_raw.windows(2).any(|pair| pair[0] >= pair[1])
14043            {
14044                return None;
14045            }
14046
14047            let mut left_positions = Vec::with_capacity(right_raw.len());
14048            let mut left_idx = 0usize;
14049            for &right_value in right_raw {
14050                while left_idx < left_raw.len() && left_raw[left_idx] < right_value {
14051                    left_idx += 1;
14052                }
14053                left_positions.push(
14054                    (left_idx < left_raw.len()
14055                        && matches!(
14056                            left_raw[left_idx].cmp(&right_value),
14057                            std::cmp::Ordering::Equal
14058                        ))
14059                    .then_some(left_idx),
14060                );
14061            }
14062            Some(left_positions)
14063        };
14064        let candidate = || super::ordered_unique_temporal_i64_right_match_positions(&left, &right);
14065
14066        let former_output = former().expect("former temporal RIGHT positions");
14067        let candidate_output = candidate().expect("fused temporal RIGHT positions");
14068        assert_eq!(candidate_output, former_output);
14069        assert_eq!(candidate_output.len(), input_len);
14070        drop((former_output, candidate_output));
14071        for _ in 0..2 {
14072            std::hint::black_box(former());
14073            std::hint::black_box(candidate());
14074        }
14075
14076        let sample = |plan: &dyn Fn() -> Option<Vec<Option<usize>>>| {
14077            let start = std::time::Instant::now();
14078            let output = std::hint::black_box(plan()).expect("supported temporal RIGHT plan");
14079            assert_eq!(std::hint::black_box(output.len()), input_len);
14080            drop(output);
14081            start.elapsed().as_secs_f64() * 1_000.0
14082        };
14083        let mut former_a = Vec::with_capacity(15);
14084        let mut former_b = Vec::with_capacity(15);
14085        let mut candidate_a = Vec::with_capacity(15);
14086        let mut candidate_b = Vec::with_capacity(15);
14087        for round in 0..15 {
14088            if round % 2 == 0 {
14089                former_a.push(sample(&former));
14090                candidate_a.push(sample(&candidate));
14091                candidate_b.push(sample(&candidate));
14092                former_b.push(sample(&former));
14093            } else {
14094                former_b.push(sample(&former));
14095                candidate_b.push(sample(&candidate));
14096                candidate_a.push(sample(&candidate));
14097                former_a.push(sample(&former));
14098            }
14099        }
14100
14101        let report = |label: &str, mut samples: Vec<f64>| {
14102            samples.sort_by(f64::total_cmp);
14103            let p50 = samples[samples.len() / 2];
14104            let p95_idx = samples
14105                .len()
14106                .saturating_mul(95)
14107                .div_ceil(100)
14108                .saturating_sub(1);
14109            println!(
14110                "{label}: p50={p50:.3} ms p95={:.3} ms max={:.3} ms",
14111                samples[p95_idx],
14112                samples[samples.len() - 1],
14113            );
14114        };
14115        report("right_plan_three_pass_former_a", former_a);
14116        report("right_plan_three_pass_former_b", former_b);
14117        report("right_plan_fused_candidate_a", candidate_a);
14118        report("right_plan_fused_candidate_b", candidate_b);
14119    }
14120
14121    #[test]
14122    fn merge_datetime_right_preserves_dtype_order_and_nat_fallback_8tf5c() -> Result<(), JoinError>
14123    {
14124        let left = DataFrame::from_dict(
14125            &["key", "lv"],
14126            vec![
14127                (
14128                    "key",
14129                    vec![
14130                        Scalar::Datetime64(10),
14131                        Scalar::Datetime64(30),
14132                        Scalar::Datetime64(50),
14133                    ],
14134                ),
14135                (
14136                    "lv",
14137                    vec![Scalar::Int64(0), Scalar::Int64(1), Scalar::Int64(2)],
14138                ),
14139            ],
14140        )?;
14141        let right = DataFrame::from_dict(
14142            &["key", "rv"],
14143            vec![
14144                (
14145                    "key",
14146                    vec![
14147                        Scalar::Datetime64(0),
14148                        Scalar::Datetime64(10),
14149                        Scalar::Datetime64(40),
14150                        Scalar::Datetime64(50),
14151                        Scalar::Datetime64(60),
14152                    ],
14153                ),
14154                (
14155                    "rv",
14156                    vec![
14157                        Scalar::Int64(100),
14158                        Scalar::Int64(101),
14159                        Scalar::Int64(102),
14160                        Scalar::Int64(103),
14161                        Scalar::Int64(104),
14162                    ],
14163                ),
14164            ],
14165        )?;
14166        let merged = merge_dataframes_on(&left, &right, &["key"], JoinType::Right)?;
14167        assert_eq!(merged.columns["key"].dtype(), DType::datetime64_naive());
14168        assert_eq!(
14169            merged_values(&merged, "key")?,
14170            &[
14171                Scalar::Datetime64(0),
14172                Scalar::Datetime64(10),
14173                Scalar::Datetime64(40),
14174                Scalar::Datetime64(50),
14175                Scalar::Datetime64(60),
14176            ],
14177        );
14178        assert_eq!(
14179            merged_values(&merged, "rv")?,
14180            &[
14181                Scalar::Int64(100),
14182                Scalar::Int64(101),
14183                Scalar::Int64(102),
14184                Scalar::Int64(103),
14185                Scalar::Int64(104),
14186            ],
14187        );
14188        let left_values = merged_values(&merged, "lv")?;
14189        assert_eq!(left_values.len(), 5);
14190        assert!(left_values[0].is_missing());
14191        assert_eq!(left_values[1], Scalar::Float64(0.0));
14192        assert!(left_values[2].is_missing());
14193        assert_eq!(left_values[3], Scalar::Float64(2.0));
14194        assert!(left_values[4].is_missing());
14195
14196        let nat = fp_types::Timestamp::NAT;
14197        let nat_left = DataFrame::from_dict(
14198            &["key", "lv"],
14199            vec![
14200                ("key", vec![Scalar::Datetime64(nat), Scalar::Datetime64(5)]),
14201                ("lv", vec![Scalar::Int64(0), Scalar::Int64(1)]),
14202            ],
14203        )?;
14204        let nat_right = DataFrame::from_dict(
14205            &["key", "rv"],
14206            vec![
14207                (
14208                    "key",
14209                    vec![
14210                        Scalar::Datetime64(nat),
14211                        Scalar::Datetime64(5),
14212                        Scalar::Datetime64(7),
14213                    ],
14214                ),
14215                (
14216                    "rv",
14217                    vec![Scalar::Int64(10), Scalar::Int64(11), Scalar::Int64(12)],
14218                ),
14219            ],
14220        )?;
14221        assert!(
14222            super::ordered_unique_temporal_i64_right_match_positions(
14223                nat_left.column("key").expect("left NaT key"),
14224                nat_right.column("key").expect("right NaT key"),
14225            )
14226            .is_none(),
14227            "NaT must retain the scalar Missing-key fallback",
14228        );
14229        let nat_merged = merge_dataframes_on(&nat_left, &nat_right, &["key"], JoinType::Right)?;
14230        assert_eq!(nat_merged.columns["key"].dtype(), DType::datetime64_naive());
14231        assert_eq!(nat_merged.index.len(), 3);
14232        assert!(merged_values(&nat_merged, "key")?[0].is_missing());
14233        assert_eq!(
14234            &merged_values(&nat_merged, "key")?[1..],
14235            &[Scalar::Datetime64(5), Scalar::Datetime64(7)],
14236        );
14237        let nat_left_values = merged_values(&nat_merged, "lv")?;
14238        assert_eq!(
14239            &nat_left_values[..2],
14240            &[Scalar::Float64(0.0), Scalar::Float64(1.0)]
14241        );
14242        assert!(nat_left_values[2].is_missing());
14243
14244        Ok(())
14245    }
14246
14247    #[test]
14248    fn temporal_i64_outer_key_coalesce_matches_scalar_and_declines_unsupported_i4gzc() {
14249        let left_positions = [None, Some(0), Some(1), None, Some(2), Some(3), None];
14250        let right_positions = [Some(0), Some(1), None, Some(2), Some(3), None, Some(4)];
14251        let left_ns = vec![-20, 10, 30, 50];
14252        let right_ns = vec![-30, -20, 20, 30, 60];
14253        let union_ns = [-30, -20, 10, 20, 30, 50, 60];
14254        let temporal_column = |dtype: &DType, values: Vec<i64>| {
14255            let len = values.len();
14256            match dtype {
14257                DType::Datetime64 { .. } => Column::from_datetime64_values_with_validity(
14258                    values,
14259                    ValidityMask::all_valid(len),
14260                ),
14261                DType::Timedelta64 => Column::from_timedelta64_values_with_validity(
14262                    values,
14263                    ValidityMask::all_valid(len),
14264                ),
14265                _ => unreachable!("test iterates only temporal dtypes"),
14266            }
14267        };
14268
14269        for temporal in [DType::datetime64_naive(), DType::Timedelta64] {
14270            let left = temporal_column(&temporal, left_ns.clone());
14271            let right = temporal_column(&temporal, right_ns.clone());
14272            let candidate = super::coalesce_temporal_i64_key_column(
14273                &left,
14274                &right,
14275                &left_positions,
14276                &right_positions,
14277            )
14278            .expect("supported temporal key coalesce");
14279            assert_eq!(candidate.dtype(), temporal);
14280            assert!(candidate.validity().all());
14281            let candidate_ns = match &temporal {
14282                DType::Datetime64 { .. } => candidate.as_datetime64_slice(),
14283                DType::Timedelta64 => candidate.as_timedelta64_slice(),
14284                _ => unreachable!("test iterates only temporal dtypes"),
14285            };
14286            assert_eq!(candidate_ns, Some(union_ns.as_slice()));
14287
14288            let reference_values = left_positions
14289                .iter()
14290                .zip(right_positions.iter())
14291                .map(|(left_pos, right_pos)| match (left_pos, right_pos) {
14292                    (Some(pos), _) => left.values()[*pos].clone(),
14293                    (None, Some(pos)) => right.values()[*pos].clone(),
14294                    (None, None) => Scalar::Null(NullKind::Null),
14295                })
14296                .collect::<Vec<_>>();
14297            let reference = Column::from_values(reference_values).expect("scalar reference");
14298            assert_eq!(candidate, reference);
14299        }
14300
14301        let naive_datetime = DType::datetime64_naive();
14302        let datetime_left = temporal_column(&naive_datetime, left_ns);
14303        let datetime_right = temporal_column(&naive_datetime, right_ns);
14304        let timedelta_right = temporal_column(&DType::Timedelta64, vec![-30, -20, 20, 30, 60]);
14305        let mut nullable_validity = ValidityMask::all_valid(datetime_left.len());
14306        nullable_validity.set(1, false);
14307        let nullable_left =
14308            Column::from_datetime64_values_with_validity(vec![-20, 10, 30, 50], nullable_validity);
14309        let nat_left = Column::from_datetime64_values_with_validity(
14310            vec![fp_types::Timestamp::NAT, 10, 30, 50],
14311            ValidityMask::all_valid(4),
14312        );
14313        for (left, right, left_tape, right_tape) in [
14314            (
14315                &nullable_left,
14316                &datetime_right,
14317                left_positions.as_slice(),
14318                right_positions.as_slice(),
14319            ),
14320            (
14321                &datetime_left,
14322                &timedelta_right,
14323                left_positions.as_slice(),
14324                right_positions.as_slice(),
14325            ),
14326            (&nat_left, &datetime_right, &[Some(0)], &[Some(0)]),
14327            (&datetime_left, &datetime_right, &[Some(0)], &[]),
14328            (&datetime_left, &datetime_right, &[Some(99)], &[None]),
14329            (&datetime_left, &datetime_right, &[None], &[None]),
14330        ] {
14331            assert!(
14332                super::coalesce_temporal_i64_key_column(left, right, left_tape, right_tape,)
14333                    .is_none(),
14334                "unsupported temporal key coalesce must retain Scalar fallback",
14335            );
14336        }
14337    }
14338
14339    #[test]
14340    #[ignore = "foreground performance probe"]
14341    fn bench_temporal_i64_outer_key_coalesce_i4gzc() {
14342        let n = 200_000_i64;
14343        let input_len = usize::try_from(n).expect("positive benchmark length");
14344        let left = Column::from_datetime64_values_with_validity(
14345            (0..n).collect(),
14346            ValidityMask::all_valid(input_len),
14347        );
14348        let right = Column::from_datetime64_values_with_validity(
14349            (0..n).map(|value| value * 2).collect(),
14350            ValidityMask::all_valid(input_len),
14351        );
14352        let (left_positions, right_positions) =
14353            super::ordered_unique_temporal_i64_outer_positions(&left, &right)
14354                .expect("ordered temporal position tapes");
14355        let expected_rows = 300_000usize;
14356        assert_eq!(left_positions.len(), expected_rows);
14357
14358        let former = || {
14359            let values = left_positions
14360                .iter()
14361                .zip(right_positions.iter())
14362                .map(|(left_pos, right_pos)| match (left_pos, right_pos) {
14363                    (Some(pos), _) => left.values()[*pos].clone(),
14364                    (None, Some(pos)) => right.values()[*pos].clone(),
14365                    (None, None) => Scalar::Null(NullKind::Null),
14366                })
14367                .collect::<Vec<_>>();
14368            Column::from_values(values).expect("former Scalar key coalesce")
14369        };
14370        let candidate = || {
14371            super::coalesce_temporal_i64_key_column(
14372                &left,
14373                &right,
14374                &left_positions,
14375                &right_positions,
14376            )
14377            .expect("typed temporal key coalesce")
14378        };
14379
14380        let former_output = former();
14381        let candidate_output = candidate();
14382        assert_eq!(candidate_output, former_output);
14383        drop((former_output, candidate_output));
14384        for _ in 0..2 {
14385            std::hint::black_box(former());
14386            std::hint::black_box(candidate());
14387        }
14388
14389        let sample = |build: &dyn Fn() -> Column| {
14390            let start = std::time::Instant::now();
14391            let output = std::hint::black_box(build());
14392            assert_eq!(std::hint::black_box(output.len()), expected_rows);
14393            drop(output);
14394            start.elapsed().as_secs_f64() * 1_000.0
14395        };
14396        let mut former_a = Vec::with_capacity(15);
14397        let mut former_b = Vec::with_capacity(15);
14398        let mut candidate_a = Vec::with_capacity(15);
14399        let mut candidate_b = Vec::with_capacity(15);
14400        for round in 0..15 {
14401            if round % 2 == 0 {
14402                former_a.push(sample(&former));
14403                candidate_a.push(sample(&candidate));
14404                candidate_b.push(sample(&candidate));
14405                former_b.push(sample(&former));
14406            } else {
14407                former_b.push(sample(&former));
14408                candidate_b.push(sample(&candidate));
14409                candidate_a.push(sample(&candidate));
14410                former_a.push(sample(&former));
14411            }
14412        }
14413
14414        let report = |label: &str, mut samples: Vec<f64>| {
14415            samples.sort_by(f64::total_cmp);
14416            let p50 = samples[samples.len() / 2];
14417            let p95_idx = samples
14418                .len()
14419                .saturating_mul(95)
14420                .div_ceil(100)
14421                .saturating_sub(1);
14422            println!(
14423                "{label}: p50={p50:.3} ms p95={:.3} ms max={:.3} ms",
14424                samples[p95_idx],
14425                samples[samples.len() - 1],
14426            );
14427        };
14428        report("outer_key_scalar_former_a", former_a);
14429        report("outer_key_scalar_former_b", former_b);
14430        report("outer_key_typed_candidate_a", candidate_a);
14431        report("outer_key_typed_candidate_b", candidate_b);
14432    }
14433
14434    #[test]
14435    fn temporal_i64_outer_positions_match_ordered_union_and_reject_unsupported_rvb6u() {
14436        let left_ns = [-20, 10, 30, 50];
14437        let right_ns = [-30, -20, 20, 30, 60];
14438        let expected = (
14439            vec![None, Some(0), Some(1), None, Some(2), Some(3), None],
14440            vec![Some(0), Some(1), None, Some(2), Some(3), None, Some(4)],
14441        );
14442        for temporal in [DType::datetime64_naive(), DType::Timedelta64] {
14443            let scalar = |ns| match &temporal {
14444                DType::Datetime64 { .. } => Scalar::Datetime64(ns),
14445                DType::Timedelta64 => Scalar::Timedelta64(ns),
14446                _ => unreachable!("test iterates only temporal dtypes"),
14447            };
14448            let left = Column::from_values(left_ns.into_iter().map(scalar).collect())
14449                .expect("left temporal key");
14450            let right = Column::from_values(right_ns.into_iter().map(scalar).collect())
14451                .expect("right temporal key");
14452            assert_eq!(
14453                super::ordered_unique_temporal_i64_outer_positions(&left, &right),
14454                Some(expected.clone()),
14455                "raw-nanosecond OUTER planner must preserve key-sorted optional positions for {temporal:?}",
14456            );
14457        }
14458
14459        let empty_left = Column::from_datetime64_values(Vec::new());
14460        let ordered_right = Column::from_datetime64_values(vec![1, 2, 3]);
14461        assert_eq!(
14462            super::ordered_unique_temporal_i64_outer_positions(&empty_left, &ordered_right),
14463            Some((vec![None; 3], vec![Some(0), Some(1), Some(2)])),
14464        );
14465
14466        let nat = fp_types::Timestamp::NAT;
14467        let nat_left = Column::from_datetime64_values(vec![nat, 1, 2]);
14468        let duplicate_left = Column::from_datetime64_values(vec![1, 1, 2]);
14469        let unsorted_right = Column::from_datetime64_values(vec![2, 1, 3]);
14470        let mixed_right =
14471            Column::from_values([1, 2, 3].into_iter().map(Scalar::Timedelta64).collect())
14472                .expect("mixed timedelta key");
14473        let mut validity = ValidityMask::all_valid(3);
14474        validity.set(1, false);
14475        let nullable_left = Column::from_datetime64_values_with_validity(vec![1, 2, 3], validity);
14476        for (left, right) in [
14477            (&nat_left, &ordered_right),
14478            (&duplicate_left, &ordered_right),
14479            (&ordered_right, &unsorted_right),
14480            (&ordered_right, &mixed_right),
14481            (&nullable_left, &ordered_right),
14482        ] {
14483            assert!(
14484                super::ordered_unique_temporal_i64_outer_positions(left, right).is_none(),
14485                "unsupported temporal OUTER shape must retain the scalar fallback",
14486            );
14487        }
14488    }
14489
14490    #[test]
14491    #[ignore = "foreground performance probe"]
14492    fn bench_temporal_i64_outer_validation_fusion_pizud() {
14493        let n = 400_000_i64;
14494        let input_len = usize::try_from(n).expect("positive benchmark length");
14495        let left = Column::from_datetime64_values_with_validity(
14496            (0..n).collect(),
14497            ValidityMask::all_valid(input_len),
14498        );
14499        let right = Column::from_datetime64_values_with_validity(
14500            (0..n).map(|value| value * 2).collect(),
14501            ValidityMask::all_valid(input_len),
14502        );
14503        let expected_rows = 600_000usize;
14504
14505        // Exact pre-pizud body: separate NaT and strict-order scans followed by
14506        // the same three-way optional-position union.
14507        let former = || {
14508            if !left.validity().all() || !right.validity().all() {
14509                return None;
14510            }
14511            let left_raw = left.as_datetime64_slice()?;
14512            let right_raw = right.as_datetime64_slice()?;
14513            let nat = fp_types::Timestamp::NAT;
14514            if left_raw.contains(&nat) || right_raw.contains(&nat) {
14515                return None;
14516            }
14517            if left_raw.windows(2).any(|pair| pair[0] >= pair[1])
14518                || right_raw.windows(2).any(|pair| pair[0] >= pair[1])
14519            {
14520                return None;
14521            }
14522
14523            let capacity = left_raw.len().saturating_add(right_raw.len());
14524            let mut left_positions = Vec::<Option<usize>>::with_capacity(capacity);
14525            let mut right_positions = Vec::<Option<usize>>::with_capacity(capacity);
14526            let (mut left_idx, mut right_idx) = (0usize, 0usize);
14527            while left_idx < left_raw.len() && right_idx < right_raw.len() {
14528                match left_raw[left_idx].cmp(&right_raw[right_idx]) {
14529                    std::cmp::Ordering::Equal => {
14530                        left_positions.push(Some(left_idx));
14531                        right_positions.push(Some(right_idx));
14532                        left_idx += 1;
14533                        right_idx += 1;
14534                    }
14535                    std::cmp::Ordering::Less => {
14536                        left_positions.push(Some(left_idx));
14537                        right_positions.push(None);
14538                        left_idx += 1;
14539                    }
14540                    std::cmp::Ordering::Greater => {
14541                        left_positions.push(None);
14542                        right_positions.push(Some(right_idx));
14543                        right_idx += 1;
14544                    }
14545                }
14546            }
14547            while left_idx < left_raw.len() {
14548                left_positions.push(Some(left_idx));
14549                right_positions.push(None);
14550                left_idx += 1;
14551            }
14552            while right_idx < right_raw.len() {
14553                left_positions.push(None);
14554                right_positions.push(Some(right_idx));
14555                right_idx += 1;
14556            }
14557            Some((left_positions, right_positions))
14558        };
14559        let candidate = || super::ordered_unique_temporal_i64_outer_positions(&left, &right);
14560
14561        let former_output = former().expect("former temporal union");
14562        let candidate_output = candidate().expect("fused temporal union");
14563        assert_eq!(candidate_output, former_output);
14564        assert_eq!(candidate_output.0.len(), expected_rows);
14565        drop((former_output, candidate_output));
14566        for _ in 0..2 {
14567            std::hint::black_box(former());
14568            std::hint::black_box(candidate());
14569        }
14570
14571        let sample = |plan: &dyn Fn() -> Option<super::OptionalJoinPositions>| {
14572            let start = std::time::Instant::now();
14573            let output = std::hint::black_box(plan()).expect("supported temporal union");
14574            assert_eq!(std::hint::black_box(output.0.len()), expected_rows);
14575            drop(output);
14576            start.elapsed().as_secs_f64() * 1_000.0
14577        };
14578        let mut former_a = Vec::with_capacity(15);
14579        let mut former_b = Vec::with_capacity(15);
14580        let mut candidate_a = Vec::with_capacity(15);
14581        let mut candidate_b = Vec::with_capacity(15);
14582        for round in 0..15 {
14583            if round % 2 == 0 {
14584                former_a.push(sample(&former));
14585                candidate_a.push(sample(&candidate));
14586                candidate_b.push(sample(&candidate));
14587                former_b.push(sample(&former));
14588            } else {
14589                former_b.push(sample(&former));
14590                candidate_b.push(sample(&candidate));
14591                candidate_a.push(sample(&candidate));
14592                former_a.push(sample(&former));
14593            }
14594        }
14595
14596        let report = |label: &str, mut samples: Vec<f64>| {
14597            samples.sort_by(f64::total_cmp);
14598            let p50 = samples[samples.len() / 2];
14599            let p95_idx = samples
14600                .len()
14601                .saturating_mul(95)
14602                .div_ceil(100)
14603                .saturating_sub(1);
14604            println!(
14605                "{label}: p50={p50:.3} ms p95={:.3} ms max={:.3} ms",
14606                samples[p95_idx],
14607                samples[samples.len() - 1],
14608            );
14609        };
14610        report("outer_plan_three_pass_former_a", former_a);
14611        report("outer_plan_three_pass_former_b", former_b);
14612        report("outer_plan_fused_candidate_a", candidate_a);
14613        report("outer_plan_fused_candidate_b", candidate_b);
14614    }
14615
14616    #[test]
14617    fn merge_temporal_outer_matches_generic_dtype_order_and_null_fill_rvb6u()
14618    -> Result<(), JoinError> {
14619        let left_ns = [-20, 10, 30, 50];
14620        let right_ns = [-30, -20, 20, 30, 60];
14621        let union_ns = [-30, -20, 10, 20, 30, 50, 60];
14622        for temporal in [DType::datetime64_naive(), DType::Timedelta64] {
14623            let scalar = |ns| match &temporal {
14624                DType::Datetime64 { .. } => Scalar::Datetime64(ns),
14625                DType::Timedelta64 => Scalar::Timedelta64(ns),
14626                _ => unreachable!("test iterates only temporal dtypes"),
14627            };
14628            let left = DataFrame::from_dict(
14629                &["key", "lv"],
14630                vec![
14631                    ("key", left_ns.into_iter().map(scalar).collect()),
14632                    (
14633                        "lv",
14634                        vec![
14635                            Scalar::Int64(100),
14636                            Scalar::Int64(101),
14637                            Scalar::Int64(102),
14638                            Scalar::Int64(103),
14639                        ],
14640                    ),
14641                ],
14642            )?;
14643            let right = DataFrame::from_dict(
14644                &["key", "rv"],
14645                vec![
14646                    ("key", right_ns.into_iter().map(scalar).collect()),
14647                    (
14648                        "rv",
14649                        vec![
14650                            Scalar::Int64(200),
14651                            Scalar::Int64(201),
14652                            Scalar::Int64(202),
14653                            Scalar::Int64(203),
14654                            Scalar::Int64(204),
14655                        ],
14656                    ),
14657                ],
14658            )?;
14659            let candidate = merge_dataframes_on(&left, &right, &["key"], JoinType::Outer)?;
14660            let generic = merge_dataframes_on_with_options(
14661                &left,
14662                &right,
14663                &["key"],
14664                &["key"],
14665                JoinType::Outer,
14666                MergeExecutionOptions {
14667                    sort: true,
14668                    ..MergeExecutionOptions::default()
14669                },
14670            )?;
14671            assert_eq!(candidate, generic, "{temporal:?} OUTER output parity");
14672            assert_eq!(candidate.columns["key"].dtype(), temporal);
14673            assert_eq!(
14674                merged_values(&candidate, "key")?,
14675                union_ns
14676                    .into_iter()
14677                    .map(scalar)
14678                    .collect::<Vec<_>>()
14679                    .as_slice(),
14680            );
14681
14682            let left_values = merged_values(&candidate, "lv")?;
14683            assert!(left_values[0].is_missing());
14684            assert_eq!(left_values[1], Scalar::Float64(100.0));
14685            assert_eq!(left_values[2], Scalar::Float64(101.0));
14686            assert!(left_values[3].is_missing());
14687            assert_eq!(left_values[4], Scalar::Float64(102.0));
14688            assert_eq!(left_values[5], Scalar::Float64(103.0));
14689            assert!(left_values[6].is_missing());
14690
14691            let right_values = merged_values(&candidate, "rv")?;
14692            assert_eq!(right_values[0], Scalar::Float64(200.0));
14693            assert_eq!(right_values[1], Scalar::Float64(201.0));
14694            assert!(right_values[2].is_missing());
14695            assert_eq!(right_values[3], Scalar::Float64(202.0));
14696            assert_eq!(right_values[4], Scalar::Float64(203.0));
14697            assert!(right_values[5].is_missing());
14698            assert_eq!(right_values[6], Scalar::Float64(204.0));
14699        }
14700
14701        let nat = fp_types::Timestamp::NAT;
14702        let nat_left = DataFrame::from_dict(
14703            &["key", "lv"],
14704            vec![
14705                ("key", vec![Scalar::Datetime64(nat), Scalar::Datetime64(5)]),
14706                ("lv", vec![Scalar::Int64(0), Scalar::Int64(1)]),
14707            ],
14708        )?;
14709        let nat_right = DataFrame::from_dict(
14710            &["key", "rv"],
14711            vec![
14712                (
14713                    "key",
14714                    vec![
14715                        Scalar::Datetime64(nat),
14716                        Scalar::Datetime64(5),
14717                        Scalar::Datetime64(7),
14718                    ],
14719                ),
14720                (
14721                    "rv",
14722                    vec![Scalar::Int64(10), Scalar::Int64(11), Scalar::Int64(12)],
14723                ),
14724            ],
14725        )?;
14726        assert!(
14727            super::ordered_unique_temporal_i64_outer_positions(
14728                nat_left.column("key").expect("left NaT key"),
14729                nat_right.column("key").expect("right NaT key"),
14730            )
14731            .is_none(),
14732            "NaT must retain the scalar Missing-key fallback",
14733        );
14734        let nat_candidate = merge_dataframes_on(&nat_left, &nat_right, &["key"], JoinType::Outer)?;
14735        let nat_generic = merge_dataframes_on_with_options(
14736            &nat_left,
14737            &nat_right,
14738            &["key"],
14739            &["key"],
14740            JoinType::Outer,
14741            MergeExecutionOptions {
14742                sort: true,
14743                ..MergeExecutionOptions::default()
14744            },
14745        )?;
14746        assert_eq!(nat_candidate, nat_generic);
14747        assert_eq!(
14748            nat_candidate.columns["key"].dtype(),
14749            DType::datetime64_naive()
14750        );
14751        assert!(
14752            merged_values(&nat_candidate, "key")?
14753                .iter()
14754                .any(Scalar::is_missing),
14755        );
14756
14757        Ok(())
14758    }
14759
14760    #[test]
14761    fn merge_composite_datetime_component_is_honored_not_missing_j0in7() -> Result<(), JoinError> {
14762        // A COMPOSITE join key [Utf8, Datetime64] declines the single-key temporal
14763        // fast path (`temporal_i64_inner_positions`) and routes through the generic
14764        // Scalar/`scalar_to_key_component` path. The Datetime64 (and Timedelta64)
14765        // component must map to a Present key by value — NOT collapse to `Missing`.
14766        // If it collapsed to Missing, rows sharing the Utf8 component would match
14767        // regardless of timestamp (Missing == Missing), over-matching. Left has two
14768        // "a" rows at ts=10/20; right has "a" at ts=10/99. Honoring the datetime,
14769        // the only equal composite keys are ("a",10) and ("b",10) => exactly 2 rows.
14770        // Under the old Missing-collapse this would be 5 rows.
14771        let left = DataFrame::from_dict(
14772            &["region", "ts", "lv"],
14773            vec![
14774                (
14775                    "region",
14776                    vec![
14777                        Scalar::Utf8("a".to_owned()),
14778                        Scalar::Utf8("a".to_owned()),
14779                        Scalar::Utf8("b".to_owned()),
14780                    ],
14781                ),
14782                (
14783                    "ts",
14784                    vec![
14785                        Scalar::Datetime64(10),
14786                        Scalar::Datetime64(20),
14787                        Scalar::Datetime64(10),
14788                    ],
14789                ),
14790                (
14791                    "lv",
14792                    vec![Scalar::Int64(0), Scalar::Int64(1), Scalar::Int64(2)],
14793                ),
14794            ],
14795        )?;
14796        let right = DataFrame::from_dict(
14797            &["region", "ts", "rv"],
14798            vec![
14799                (
14800                    "region",
14801                    vec![
14802                        Scalar::Utf8("a".to_owned()),
14803                        Scalar::Utf8("a".to_owned()),
14804                        Scalar::Utf8("b".to_owned()),
14805                    ],
14806                ),
14807                (
14808                    "ts",
14809                    vec![
14810                        Scalar::Datetime64(10),
14811                        Scalar::Datetime64(99),
14812                        Scalar::Datetime64(10),
14813                    ],
14814                ),
14815                (
14816                    "rv",
14817                    vec![Scalar::Int64(100), Scalar::Int64(101), Scalar::Int64(102)],
14818                ),
14819            ],
14820        )?;
14821        let merged = merge_dataframes_on(&left, &right, &["region", "ts"], JoinType::Inner)?;
14822        assert_eq!(
14823            merged.index.len(),
14824            2,
14825            "datetime composite component must discriminate, not collapse to Missing"
14826        );
14827        assert_eq!(merged.columns["ts"].dtype(), DType::datetime64_naive());
14828        // Pair (lv, rv) up per output row, order-independently.
14829        let mut pairs: Vec<(i64, i64)> = merged_values(&merged, "lv")?
14830            .iter()
14831            .zip(merged_values(&merged, "rv")?)
14832            .map(|(l, r)| match (l, r) {
14833                (Scalar::Int64(a), Scalar::Int64(b)) => (*a, *b),
14834                _ => panic!("unexpected non-Int64 value column"),
14835            })
14836            .collect();
14837        pairs.sort_unstable();
14838        assert_eq!(pairs, vec![(0, 100), (2, 102)]);
14839
14840        // The Timedelta64 sibling arm must behave identically.
14841        let ltd = DataFrame::from_dict(
14842            &["region", "td", "lv"],
14843            vec![
14844                (
14845                    "region",
14846                    vec![Scalar::Utf8("a".to_owned()), Scalar::Utf8("a".to_owned())],
14847                ),
14848                ("td", vec![Scalar::Timedelta64(10), Scalar::Timedelta64(20)]),
14849                ("lv", vec![Scalar::Int64(0), Scalar::Int64(1)]),
14850            ],
14851        )?;
14852        let rtd = DataFrame::from_dict(
14853            &["region", "td", "rv"],
14854            vec![
14855                (
14856                    "region",
14857                    vec![Scalar::Utf8("a".to_owned()), Scalar::Utf8("a".to_owned())],
14858                ),
14859                ("td", vec![Scalar::Timedelta64(10), Scalar::Timedelta64(99)]),
14860                ("rv", vec![Scalar::Int64(100), Scalar::Int64(101)]),
14861            ],
14862        )?;
14863        let merged_td = merge_dataframes_on(&ltd, &rtd, &["region", "td"], JoinType::Inner)?;
14864        assert_eq!(
14865            merged_td.index.len(),
14866            1,
14867            "timedelta composite component must discriminate, not collapse to Missing"
14868        );
14869        assert_eq!(merged_values(&merged_td, "lv")?, &[Scalar::Int64(0)]);
14870        assert_eq!(merged_values(&merged_td, "rv")?, &[Scalar::Int64(100)]);
14871
14872        Ok(())
14873    }
14874
14875    fn merged_values_where_indicator(
14876        merged: &MergedDataFrame,
14877        column_name: &str,
14878        indicator_name: &str,
14879        indicator_value: &str,
14880    ) -> Result<Vec<Scalar>, JoinError> {
14881        let values = merged_values(merged, column_name)?;
14882        let indicators = merged_values(merged, indicator_name)?;
14883        Ok(values
14884            .iter()
14885            .zip(indicators.iter())
14886            .filter_map(|(value, indicator)| {
14887                if matches!(indicator, Scalar::Utf8(v) if v == indicator_value) {
14888                    Some(value.clone())
14889                } else {
14890                    None
14891                }
14892            })
14893            .collect())
14894    }
14895
14896    #[test]
14897    fn merge_inner_basic() {
14898        let left = make_left_df();
14899        let right = make_right_df();
14900        let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
14901
14902        assert_eq!(merged.columns.get("id").unwrap().len(), 2);
14903        assert_eq!(
14904            merged.columns.get("id").unwrap().values(),
14905            &[Scalar::Int64(2), Scalar::Int64(3)]
14906        );
14907        assert_eq!(
14908            merged.columns.get("val_a").unwrap().values(),
14909            &[Scalar::Int64(20), Scalar::Int64(30)]
14910        );
14911        assert_eq!(
14912            merged.columns.get("val_b").unwrap().values(),
14913            &[Scalar::Int64(200), Scalar::Int64(300)]
14914        );
14915    }
14916
14917    #[test]
14918    fn merge_inner_single_key_preserves_duplicate_probe_order() {
14919        let left = DataFrame::from_dict(
14920            &["id", "left_value"],
14921            vec![
14922                (
14923                    "id",
14924                    vec![Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(2)],
14925                ),
14926                (
14927                    "left_value",
14928                    vec![Scalar::Int64(20), Scalar::Int64(10), Scalar::Int64(21)],
14929                ),
14930            ],
14931        )
14932        .unwrap();
14933        let right = DataFrame::from_dict(
14934            &["id", "right_value"],
14935            vec![
14936                (
14937                    "id",
14938                    vec![Scalar::Int64(2), Scalar::Int64(2), Scalar::Int64(1)],
14939                ),
14940                (
14941                    "right_value",
14942                    vec![Scalar::Int64(200), Scalar::Int64(201), Scalar::Int64(100)],
14943                ),
14944            ],
14945        )
14946        .unwrap();
14947
14948        let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
14949
14950        assert_eq!(
14951            merged.columns.get("id").unwrap().values(),
14952            &[
14953                Scalar::Int64(2),
14954                Scalar::Int64(2),
14955                Scalar::Int64(1),
14956                Scalar::Int64(2),
14957                Scalar::Int64(2),
14958            ]
14959        );
14960        assert_eq!(
14961            merged.columns.get("left_value").unwrap().values(),
14962            &[
14963                Scalar::Int64(20),
14964                Scalar::Int64(20),
14965                Scalar::Int64(10),
14966                Scalar::Int64(21),
14967                Scalar::Int64(21),
14968            ]
14969        );
14970        assert_eq!(
14971            merged.columns.get("right_value").unwrap().values(),
14972            &[
14973                Scalar::Int64(200),
14974                Scalar::Int64(201),
14975                Scalar::Int64(100),
14976                Scalar::Int64(200),
14977                Scalar::Int64(201),
14978            ]
14979        );
14980    }
14981
14982    #[test]
14983    fn merge_inner_wide_sparse_int64_hash_matches_generic_validated_route() {
14984        let stride = 1_i64 << 30;
14985        let left = DataFrame::from_dict(
14986            &["id", "left_value"],
14987            vec![
14988                (
14989                    "id",
14990                    vec![3, 1, 3, 0, 2]
14991                        .into_iter()
14992                        .map(|v| Scalar::Int64(v * stride))
14993                        .collect(),
14994                ),
14995                (
14996                    "left_value",
14997                    vec![
14998                        Scalar::Int64(10),
14999                        Scalar::Int64(11),
15000                        Scalar::Int64(12),
15001                        Scalar::Int64(13),
15002                        Scalar::Int64(14),
15003                    ],
15004                ),
15005            ],
15006        )
15007        .unwrap();
15008        let right = DataFrame::from_dict(
15009            &["id", "right_value"],
15010            vec![
15011                (
15012                    "id",
15013                    vec![3, 2, 3, 1]
15014                        .into_iter()
15015                        .map(|v| Scalar::Int64(v * stride))
15016                        .collect(),
15017                ),
15018                (
15019                    "right_value",
15020                    vec![
15021                        Scalar::Int64(100),
15022                        Scalar::Int64(101),
15023                        Scalar::Int64(102),
15024                        Scalar::Int64(103),
15025                    ],
15026                ),
15027            ],
15028        )
15029        .unwrap();
15030
15031        let fast = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
15032        let generic = merge_dataframes_on_with_options(
15033            &left,
15034            &right,
15035            &["id"],
15036            &["id"],
15037            JoinType::Inner,
15038            MergeExecutionOptions {
15039                validate_mode: Some(MergeValidateMode::ManyToMany),
15040                ..MergeExecutionOptions::default()
15041            },
15042        )
15043        .unwrap();
15044
15045        assert_eq!(fast.index, generic.index);
15046        assert_eq!(fast.column_order, generic.column_order);
15047        assert_eq!(fast.columns, generic.columns);
15048        assert_eq!(
15049            fast.columns.get("id").unwrap().values(),
15050            &[
15051                Scalar::Int64(3 * stride),
15052                Scalar::Int64(3 * stride),
15053                Scalar::Int64(stride),
15054                Scalar::Int64(3 * stride),
15055                Scalar::Int64(3 * stride),
15056                Scalar::Int64(2 * stride),
15057            ]
15058        );
15059        assert_eq!(
15060            fast.columns.get("left_value").unwrap().values(),
15061            &[
15062                Scalar::Int64(10),
15063                Scalar::Int64(10),
15064                Scalar::Int64(11),
15065                Scalar::Int64(12),
15066                Scalar::Int64(12),
15067                Scalar::Int64(14),
15068            ]
15069        );
15070        assert_eq!(
15071            fast.columns.get("right_value").unwrap().values(),
15072            &[
15073                Scalar::Int64(100),
15074                Scalar::Int64(102),
15075                Scalar::Int64(103),
15076                Scalar::Int64(100),
15077                Scalar::Int64(102),
15078                Scalar::Int64(101),
15079            ]
15080        );
15081    }
15082
15083    #[test]
15084    fn dense_i64_inner_parallel_output_data_preserves_row_major_order() {
15085        let left_keys = vec![-1, 2, 1, 2, 3, 9];
15086        let min = 1;
15087        let max = 3;
15088        let offsets = vec![0, 2, 3, 5];
15089        let positions = vec![1usize, 4, 0, 2, 3];
15090        let left_values = vec![10, 20, 30, 40, 50, 60];
15091        let right_values = vec![100, 101, 102, 103, 104];
15092        let specs = vec![
15093            FusedInt64OutputColumn {
15094                name: "left".to_string(),
15095                side: FusedInt64Side::Left,
15096                values: &left_values,
15097            },
15098            FusedInt64OutputColumn {
15099                name: "right".to_string(),
15100                side: FusedInt64Side::Right,
15101                values: &right_values,
15102            },
15103        ];
15104
15105        let plan = DenseI64InnerOutputPlan {
15106            left_keys: &left_keys,
15107            min,
15108            max,
15109            offsets: &offsets,
15110            positions: &positions,
15111            output_len: 6,
15112        };
15113        let actual = build_dense_i64_inner_output_data(&specs, &plan);
15114
15115        // 4 matched left rows -> 6 output rows: avg fanout < 2, so the left
15116        // lane stays fully materialized alongside the right lane.
15117        assert_eq!(lane_expanded(&actual[0]), vec![20, 30, 30, 40, 50, 50]);
15118        assert_eq!(
15119            lane_expanded(&actual[1]),
15120            vec![100, 101, 104, 100, 102, 103]
15121        );
15122        assert!(matches!(actual[0], DenseI64LaneData::Full(_)));
15123        assert!(matches!(actual[1], DenseI64LaneData::Full(_)));
15124    }
15125
15126    fn lane_expanded(lane: &DenseI64LaneData) -> Vec<i64> {
15127        match lane {
15128            DenseI64LaneData::RepeatRunLengths { values, run_lens } => {
15129                let mut out = Vec::new();
15130                for (&value, &run_len) in values.iter().zip(run_lens.iter()) {
15131                    out.resize(out.len() + run_len, value);
15132                }
15133                out
15134            }
15135            DenseI64LaneData::RepeatedSlices { data, segments } => {
15136                let mut out = Vec::new();
15137                for &(start, len) in segments.iter() {
15138                    out.extend_from_slice(&data[start..start + len]);
15139                }
15140                out
15141            }
15142            DenseI64LaneData::Full(data) => data.clone(),
15143        }
15144    }
15145
15146    #[test]
15147    fn dense_i64_inner_high_fanout_emits_repeat_run_left_lanes() {
15148        // 2 matched left rows, each matching 3 right rows -> avg fanout 3:
15149        // left lane must come back as repeat runs and the right lane as
15150        // repeated slices. Their expansion equals the old full fill.
15151        let left_keys = vec![1, 7, 2];
15152        let min = 1;
15153        let max = 2;
15154        let offsets = vec![0, 3, 6];
15155        let positions = vec![0usize, 2, 4, 1, 3, 5];
15156        let left_values = vec![10, 20, 30];
15157        let right_values = vec![100, 101, 102, 103, 104, 105];
15158        let specs = vec![
15159            FusedInt64OutputColumn {
15160                name: "left".to_string(),
15161                side: FusedInt64Side::Left,
15162                values: &left_values,
15163            },
15164            FusedInt64OutputColumn {
15165                name: "right".to_string(),
15166                side: FusedInt64Side::Right,
15167                values: &right_values,
15168            },
15169        ];
15170
15171        let plan = DenseI64InnerOutputPlan {
15172            left_keys: &left_keys,
15173            min,
15174            max,
15175            offsets: &offsets,
15176            positions: &positions,
15177            output_len: 6,
15178        };
15179        let actual = build_dense_i64_inner_output_data(&specs, &plan);
15180
15181        assert!(matches!(
15182            actual[0],
15183            DenseI64LaneData::RepeatRunLengths { .. }
15184        ));
15185        assert!(matches!(actual[1], DenseI64LaneData::RepeatedSlices { .. }));
15186        assert_eq!(lane_expanded(&actual[0]), vec![10, 10, 10, 30, 30, 30]);
15187        assert_eq!(
15188            lane_expanded(&actual[1]),
15189            vec![100, 102, 104, 101, 103, 105]
15190        );
15191
15192        // The lazy Column built from shared run lengths is indistinguishable
15193        // from the eagerly materialized one (values, slice view, length,
15194        // equality).
15195        let lazy = fp_columnar::Column::from_i64_repeat_values_run_lengths(
15196            vec![10, 30],
15197            std::sync::Arc::from([3usize, 3]),
15198        );
15199        let eager = fp_columnar::Column::from_i64_values(vec![10, 10, 10, 30, 30, 30]);
15200        assert_eq!(lazy.len(), eager.len());
15201        assert_eq!(lazy.as_i64_slice(), eager.as_i64_slice());
15202        assert_eq!(lazy.values(), eager.values());
15203        assert_eq!(lazy, eager);
15204    }
15205
15206    #[test]
15207    fn dense_cycle_left_join_declines_invented_gaps_66wab() {
15208        let left = DataFrame::from_dict(
15209            &["id", "v"],
15210            vec![
15211                (
15212                    "id",
15213                    vec![
15214                        Scalar::Int64(0),
15215                        Scalar::Int64(1),
15216                        Scalar::Int64(2),
15217                        Scalar::Int64(0),
15218                        Scalar::Int64(1),
15219                        Scalar::Int64(2),
15220                        Scalar::Int64(0),
15221                    ],
15222                ),
15223                (
15224                    "v",
15225                    vec![
15226                        Scalar::Int64(10),
15227                        Scalar::Int64(11),
15228                        Scalar::Int64(12),
15229                        Scalar::Int64(13),
15230                        Scalar::Int64(14),
15231                        Scalar::Int64(15),
15232                        Scalar::Int64(16),
15233                    ],
15234                ),
15235            ],
15236        )
15237        .unwrap();
15238        let right = DataFrame::from_dict(
15239            &["id", "rv"],
15240            vec![
15241                (
15242                    "id",
15243                    vec![
15244                        Scalar::Int64(1),
15245                        Scalar::Int64(2),
15246                        Scalar::Int64(1),
15247                        Scalar::Int64(2),
15248                    ],
15249                ),
15250                (
15251                    "rv",
15252                    vec![
15253                        Scalar::Int64(100),
15254                        Scalar::Int64(200),
15255                        Scalar::Int64(101),
15256                        Scalar::Int64(201),
15257                    ],
15258                ),
15259            ],
15260        )
15261        .unwrap();
15262        let suffixes = ResolvedMergeSuffixes::default();
15263        let left_key = left.column("id").unwrap();
15264        let right_key = right.column("id").unwrap();
15265
15266        let dense_cycle = build_single_key_dense_cycle_i64_left_merge_output(
15267            &left,
15268            &right,
15269            &["id"],
15270            &["id"],
15271            left_key,
15272            right_key,
15273            &suffixes,
15274        )
15275        .unwrap();
15276        assert!(dense_cycle.is_none());
15277        assert!(
15278            build_single_key_dense_i64_left_merge_output(
15279                &left,
15280                &right,
15281                &["id"],
15282                &["id"],
15283                left_key,
15284                right_key,
15285                &suffixes,
15286            )
15287            .unwrap()
15288            .is_none()
15289        );
15290    }
15291
15292    #[test]
15293    fn merge_inner_ordered_identity_matches_generic_validated_route() {
15294        let left = DataFrame::from_dict(
15295            &["id", "v"],
15296            vec![
15297                (
15298                    "id",
15299                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
15300                ),
15301                (
15302                    "v",
15303                    vec![
15304                        Scalar::Int64(10),
15305                        Scalar::Null(NullKind::Null),
15306                        Scalar::Int64(30),
15307                    ],
15308                ),
15309            ],
15310        )
15311        .unwrap();
15312        let right = DataFrame::from_dict(
15313            &["id", "w"],
15314            vec![
15315                (
15316                    "id",
15317                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
15318                ),
15319                (
15320                    "w",
15321                    vec![Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(300)],
15322                ),
15323            ],
15324        )
15325        .unwrap();
15326
15327        let fast = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
15328        let generic = merge_dataframes_on_with_options(
15329            &left,
15330            &right,
15331            &["id"],
15332            &["id"],
15333            JoinType::Inner,
15334            MergeExecutionOptions {
15335                validate_mode: Some(MergeValidateMode::OneToOne),
15336                ..MergeExecutionOptions::default()
15337            },
15338        )
15339        .unwrap();
15340
15341        assert_eq!(fast.index, generic.index);
15342        assert_eq!(fast.column_order, generic.column_order);
15343        assert_eq!(fast.columns, generic.columns);
15344    }
15345
15346    #[test]
15347    fn merge_inner_dense_int64_fused_materialization_matches_generic_route() {
15348        let left = DataFrame::from_dict(
15349            &["id", "v", "overlap"],
15350            vec![
15351                (
15352                    "id",
15353                    vec![
15354                        Scalar::Int64(2),
15355                        Scalar::Int64(1),
15356                        Scalar::Int64(2),
15357                        Scalar::Int64(3),
15358                    ],
15359                ),
15360                (
15361                    "v",
15362                    vec![
15363                        Scalar::Int64(20),
15364                        Scalar::Int64(10),
15365                        Scalar::Int64(21),
15366                        Scalar::Int64(30),
15367                    ],
15368                ),
15369                (
15370                    "overlap",
15371                    vec![
15372                        Scalar::Int64(200),
15373                        Scalar::Int64(100),
15374                        Scalar::Int64(201),
15375                        Scalar::Int64(300),
15376                    ],
15377                ),
15378            ],
15379        )
15380        .unwrap();
15381        let right = DataFrame::from_dict(
15382            &["id", "w", "overlap"],
15383            vec![
15384                (
15385                    "id",
15386                    vec![
15387                        Scalar::Int64(2),
15388                        Scalar::Int64(2),
15389                        Scalar::Int64(1),
15390                        Scalar::Int64(4),
15391                    ],
15392                ),
15393                (
15394                    "w",
15395                    vec![
15396                        Scalar::Int64(2000),
15397                        Scalar::Int64(2001),
15398                        Scalar::Int64(1000),
15399                        Scalar::Int64(4000),
15400                    ],
15401                ),
15402                (
15403                    "overlap",
15404                    vec![
15405                        Scalar::Int64(20_000),
15406                        Scalar::Int64(20_001),
15407                        Scalar::Int64(10_000),
15408                        Scalar::Int64(40_000),
15409                    ],
15410                ),
15411            ],
15412        )
15413        .unwrap();
15414
15415        let fast = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
15416        let generic = merge_dataframes_on_with_options(
15417            &left,
15418            &right,
15419            &["id"],
15420            &["id"],
15421            JoinType::Inner,
15422            MergeExecutionOptions {
15423                validate_mode: Some(MergeValidateMode::ManyToMany),
15424                ..MergeExecutionOptions::default()
15425            },
15426        )
15427        .unwrap();
15428
15429        assert_eq!(fast.index, generic.index);
15430        assert_eq!(fast.column_order, generic.column_order);
15431        assert_eq!(fast.columns, generic.columns);
15432        assert_eq!(
15433            fast.column_order,
15434            ["id", "v", "overlap_x", "w", "overlap_y"]
15435        );
15436        assert_eq!(
15437            fast.columns.get("id").unwrap().values(),
15438            &[
15439                Scalar::Int64(2),
15440                Scalar::Int64(2),
15441                Scalar::Int64(1),
15442                Scalar::Int64(2),
15443                Scalar::Int64(2),
15444            ]
15445        );
15446        assert_eq!(
15447            fast.columns.get("w").unwrap().values(),
15448            &[
15449                Scalar::Int64(2000),
15450                Scalar::Int64(2001),
15451                Scalar::Int64(1000),
15452                Scalar::Int64(2000),
15453                Scalar::Int64(2001),
15454            ]
15455        );
15456        assert!(
15457            fast.columns
15458                .values()
15459                .all(|column| column.as_i64_slice().is_some())
15460        );
15461    }
15462
15463    #[test]
15464    fn merge_inner_ordered_unique_int64_subset_matches_generic_validated_route() {
15465        let left = DataFrame::from_dict(
15466            &["id", "v"],
15467            vec![
15468                (
15469                    "id",
15470                    vec![
15471                        Scalar::Int64(0),
15472                        Scalar::Int64(1),
15473                        Scalar::Int64(2),
15474                        Scalar::Int64(3),
15475                        Scalar::Int64(4),
15476                    ],
15477                ),
15478                (
15479                    "v",
15480                    vec![
15481                        Scalar::Int64(10),
15482                        Scalar::Int64(11),
15483                        Scalar::Int64(12),
15484                        Scalar::Int64(13),
15485                        Scalar::Int64(14),
15486                    ],
15487                ),
15488            ],
15489        )
15490        .unwrap();
15491        let right = DataFrame::from_dict(
15492            &["id", "w"],
15493            vec![
15494                (
15495                    "id",
15496                    vec![
15497                        Scalar::Int64(0),
15498                        Scalar::Int64(2),
15499                        Scalar::Int64(4),
15500                        Scalar::Int64(6),
15501                    ],
15502                ),
15503                (
15504                    "w",
15505                    vec![
15506                        Scalar::Int64(100),
15507                        Scalar::Int64(200),
15508                        Scalar::Int64(300),
15509                        Scalar::Int64(400),
15510                    ],
15511                ),
15512            ],
15513        )
15514        .unwrap();
15515
15516        let fast = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
15517        let generic = merge_dataframes_on_with_options(
15518            &left,
15519            &right,
15520            &["id"],
15521            &["id"],
15522            JoinType::Inner,
15523            MergeExecutionOptions {
15524                validate_mode: Some(MergeValidateMode::OneToOne),
15525                ..MergeExecutionOptions::default()
15526            },
15527        )
15528        .unwrap();
15529
15530        assert_eq!(fast.index, generic.index);
15531        assert_eq!(fast.column_order, generic.column_order);
15532        assert_eq!(fast.columns, generic.columns);
15533        assert_eq!(
15534            fast.columns.get("id").unwrap().values(),
15535            &[Scalar::Int64(0), Scalar::Int64(2), Scalar::Int64(4)]
15536        );
15537        assert_eq!(
15538            fast.columns.get("v").unwrap().values(),
15539            &[Scalar::Int64(10), Scalar::Int64(12), Scalar::Int64(14)]
15540        );
15541        assert_eq!(
15542            fast.columns.get("w").unwrap().values(),
15543            &[Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(300)]
15544        );
15545    }
15546
15547    #[test]
15548    fn merge_inner_ordered_identity_falls_back_for_non_identity_keys() {
15549        let cases = [
15550            (
15551                vec![Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(4)],
15552                vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
15553            ),
15554            (
15555                vec![
15556                    Scalar::Int64(1),
15557                    Scalar::Null(NullKind::Null),
15558                    Scalar::Int64(3),
15559                ],
15560                vec![
15561                    Scalar::Int64(1),
15562                    Scalar::Null(NullKind::Null),
15563                    Scalar::Int64(3),
15564                ],
15565            ),
15566        ];
15567
15568        for (left_keys, right_keys) in cases {
15569            let left = DataFrame::from_dict(
15570                &["id", "v"],
15571                vec![
15572                    ("id", left_keys),
15573                    (
15574                        "v",
15575                        vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
15576                    ),
15577                ],
15578            )
15579            .unwrap();
15580            let right = DataFrame::from_dict(
15581                &["id", "w"],
15582                vec![
15583                    ("id", right_keys),
15584                    (
15585                        "w",
15586                        vec![Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(300)],
15587                    ),
15588                ],
15589            )
15590            .unwrap();
15591
15592            let maybe_fast = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
15593            let generic = merge_dataframes_on_with_options(
15594                &left,
15595                &right,
15596                &["id"],
15597                &["id"],
15598                JoinType::Inner,
15599                MergeExecutionOptions {
15600                    validate_mode: Some(MergeValidateMode::OneToOne),
15601                    ..MergeExecutionOptions::default()
15602                },
15603            )
15604            .unwrap();
15605
15606            assert_eq!(maybe_fast.index, generic.index);
15607            assert_eq!(maybe_fast.column_order, generic.column_order);
15608            assert_eq!(maybe_fast.columns, generic.columns);
15609        }
15610    }
15611
15612    #[test]
15613    fn merge_default_suffixes_match_pandas() {
15614        // Overlapping non-key column "v" gets pandas default _x/_y suffixes.
15615        // Verified vs pandas 2.2.3: left{k:[1,2,3],v:[10,20,30]} merged inner on
15616        // k with right{k:[2,3,4],v:[200,300,400]} -> cols [k,v_x,v_y],
15617        // k=[2,3], v_x=[20,30], v_y=[200,300].
15618        let idx: Vec<_> = (0..3).map(|i| (i as i64).into()).collect();
15619        let left = fp_frame::DataFrame::from_series(vec![
15620            fp_frame::Series::from_values(
15621                "k",
15622                idx.clone(),
15623                vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
15624            )
15625            .unwrap(),
15626            fp_frame::Series::from_values(
15627                "v",
15628                idx.clone(),
15629                vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
15630            )
15631            .unwrap(),
15632        ])
15633        .unwrap();
15634        let right = fp_frame::DataFrame::from_series(vec![
15635            fp_frame::Series::from_values(
15636                "k",
15637                idx.clone(),
15638                vec![Scalar::Int64(2), Scalar::Int64(3), Scalar::Int64(4)],
15639            )
15640            .unwrap(),
15641            fp_frame::Series::from_values(
15642                "v",
15643                idx,
15644                vec![Scalar::Int64(200), Scalar::Int64(300), Scalar::Int64(400)],
15645            )
15646            .unwrap(),
15647        ])
15648        .unwrap();
15649        let merged = merge_dataframes(&left, &right, "k", JoinType::Inner).unwrap();
15650
15651        assert_eq!(
15652            merged.columns.get("k").unwrap().values(),
15653            &[Scalar::Int64(2), Scalar::Int64(3)],
15654            "k"
15655        );
15656        assert_eq!(
15657            merged.columns.get("v_x").unwrap().values(),
15658            &[Scalar::Int64(20), Scalar::Int64(30)],
15659            "v_x"
15660        );
15661        assert_eq!(
15662            merged.columns.get("v_y").unwrap().values(),
15663            &[Scalar::Int64(200), Scalar::Int64(300)],
15664            "v_y"
15665        );
15666        assert!(
15667            !merged.columns.contains_key("v"),
15668            "bare 'v' should be suffixed away"
15669        );
15670    }
15671
15672    #[test]
15673    fn merge_left_preserves_all_left_rows() {
15674        let left = make_left_df();
15675        let right = make_right_df();
15676        let merged = merge_dataframes(&left, &right, "id", JoinType::Left).unwrap();
15677
15678        assert_eq!(merged.columns.get("id").unwrap().len(), 3);
15679        assert_eq!(
15680            merged.columns.get("val_a").unwrap().values(),
15681            &[Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)]
15682        );
15683        // val_b widens to Float64 because id=1 invents a missing value.
15684        assert_eq!(merged.columns.get("val_b").unwrap().dtype(), DType::Float64);
15685        assert_eq!(
15686            merged.columns.get("val_b").unwrap().values()[0],
15687            Scalar::Null(NullKind::NaN)
15688        );
15689        assert_eq!(
15690            merged.columns.get("val_b").unwrap().values()[1],
15691            Scalar::Float64(200.0)
15692        );
15693        assert_eq!(
15694            merged.columns.get("val_b").unwrap().values()[2],
15695            Scalar::Float64(300.0)
15696        );
15697    }
15698
15699    #[test]
15700    fn merge_left_ordered_unique_int64_subset_matches_generic_validated_route() {
15701        let left = DataFrame::from_dict(
15702            &["id", "v"],
15703            vec![
15704                (
15705                    "id",
15706                    vec![
15707                        Scalar::Int64(0),
15708                        Scalar::Int64(1),
15709                        Scalar::Int64(2),
15710                        Scalar::Int64(3),
15711                        Scalar::Int64(4),
15712                    ],
15713                ),
15714                (
15715                    "v",
15716                    vec![
15717                        Scalar::Int64(10),
15718                        Scalar::Int64(11),
15719                        Scalar::Int64(12),
15720                        Scalar::Int64(13),
15721                        Scalar::Int64(14),
15722                    ],
15723                ),
15724            ],
15725        )
15726        .unwrap();
15727        let right = DataFrame::from_dict(
15728            &["id", "w"],
15729            vec![
15730                (
15731                    "id",
15732                    vec![
15733                        Scalar::Int64(0),
15734                        Scalar::Int64(2),
15735                        Scalar::Int64(4),
15736                        Scalar::Int64(6),
15737                    ],
15738                ),
15739                (
15740                    "w",
15741                    vec![
15742                        Scalar::Int64(100),
15743                        Scalar::Int64(200),
15744                        Scalar::Int64(300),
15745                        Scalar::Int64(400),
15746                    ],
15747                ),
15748            ],
15749        )
15750        .unwrap();
15751
15752        let fast = merge_dataframes(&left, &right, "id", JoinType::Left).unwrap();
15753        let generic = merge_dataframes_on_with_options(
15754            &left,
15755            &right,
15756            &["id"],
15757            &["id"],
15758            JoinType::Left,
15759            MergeExecutionOptions {
15760                validate_mode: Some(MergeValidateMode::OneToOne),
15761                ..MergeExecutionOptions::default()
15762            },
15763        )
15764        .unwrap();
15765
15766        assert_eq!(fast.index, generic.index);
15767        assert_eq!(fast.column_order, generic.column_order);
15768        assert_eq!(fast.columns, generic.columns);
15769        assert_eq!(
15770            fast.columns.get("id").unwrap().values(),
15771            &[
15772                Scalar::Int64(0),
15773                Scalar::Int64(1),
15774                Scalar::Int64(2),
15775                Scalar::Int64(3),
15776                Scalar::Int64(4)
15777            ]
15778        );
15779        let right_values = fast.columns.get("w").unwrap().values();
15780        assert_eq!(right_values[0], Scalar::Float64(100.0));
15781        assert!(right_values[1].is_missing());
15782        assert_eq!(right_values[2], Scalar::Float64(200.0));
15783        assert!(right_values[3].is_missing());
15784        assert_eq!(right_values[4], Scalar::Float64(300.0));
15785    }
15786
15787    #[test]
15788    fn merge_left_ordered_unique_int64_retains_lazy_utf8_payload_plan() {
15789        let left = DataFrame::from_dict(
15790            &["id", "v"],
15791            vec![
15792                ("id", (0..5_i64).map(Scalar::Int64).collect::<Vec<_>>()),
15793                ("v", (10..15_i64).map(Scalar::Int64).collect::<Vec<_>>()),
15794            ],
15795        )
15796        .unwrap();
15797        let right = DataFrame::from_dict(
15798            &["id", "tag"],
15799            vec![
15800                (
15801                    "id",
15802                    [0_i64, 2, 4, 6].into_iter().map(Scalar::Int64).collect(),
15803                ),
15804                (
15805                    "tag",
15806                    ["zero", "two", "four", "six"]
15807                        .into_iter()
15808                        .map(|value| Scalar::Utf8(value.to_owned()))
15809                        .collect(),
15810                ),
15811            ],
15812        )
15813        .unwrap();
15814
15815        let merged = merge_dataframes(&left, &right, "id", JoinType::Left).unwrap();
15816        let tags = merged.columns.get("tag").unwrap().values();
15817        assert_eq!(tags[0], Scalar::Utf8("zero".to_owned()));
15818        assert!(tags[1].is_missing());
15819        assert_eq!(tags[2], Scalar::Utf8("two".to_owned()));
15820        assert!(tags[3].is_missing());
15821        assert_eq!(tags[4], Scalar::Utf8("four".to_owned()));
15822    }
15823
15824    #[test]
15825    fn merge_left_dense_int64_duplicates_matches_generic_validated_route() {
15826        let left = DataFrame::from_dict(
15827            &["id", "v"],
15828            vec![
15829                (
15830                    "id",
15831                    vec![
15832                        Scalar::Int64(2),
15833                        Scalar::Int64(0),
15834                        Scalar::Int64(2),
15835                        Scalar::Int64(1),
15836                        Scalar::Int64(5),
15837                    ],
15838                ),
15839                (
15840                    "v",
15841                    vec![
15842                        Scalar::Int64(10),
15843                        Scalar::Int64(11),
15844                        Scalar::Int64(12),
15845                        Scalar::Int64(13),
15846                        Scalar::Int64(15),
15847                    ],
15848                ),
15849            ],
15850        )
15851        .unwrap();
15852        let right = DataFrame::from_dict(
15853            &["id", "w"],
15854            vec![
15855                (
15856                    "id",
15857                    vec![
15858                        Scalar::Int64(2),
15859                        Scalar::Int64(2),
15860                        Scalar::Int64(3),
15861                        Scalar::Int64(0),
15862                    ],
15863                ),
15864                (
15865                    "w",
15866                    vec![
15867                        Scalar::Int64(200),
15868                        Scalar::Int64(201),
15869                        Scalar::Int64(300),
15870                        Scalar::Int64(400),
15871                    ],
15872                ),
15873            ],
15874        )
15875        .unwrap();
15876
15877        let fast = merge_dataframes(&left, &right, "id", JoinType::Left).unwrap();
15878        let generic = merge_dataframes_on_with_options(
15879            &left,
15880            &right,
15881            &["id"],
15882            &["id"],
15883            JoinType::Left,
15884            MergeExecutionOptions {
15885                validate_mode: Some(MergeValidateMode::ManyToMany),
15886                ..MergeExecutionOptions::default()
15887            },
15888        )
15889        .unwrap();
15890
15891        assert_eq!(fast.index, generic.index);
15892        assert_eq!(fast.column_order, generic.column_order);
15893        assert_eq!(fast.columns, generic.columns);
15894        assert_eq!(
15895            fast.columns.get("id").unwrap().values(),
15896            &[
15897                Scalar::Int64(2),
15898                Scalar::Int64(2),
15899                Scalar::Int64(0),
15900                Scalar::Int64(2),
15901                Scalar::Int64(2),
15902                Scalar::Int64(1),
15903                Scalar::Int64(5),
15904            ]
15905        );
15906        let left_values = fast.columns.get("v").unwrap().values();
15907        assert_eq!(left_values[0], Scalar::Int64(10));
15908        assert_eq!(left_values[1], Scalar::Int64(10));
15909        assert_eq!(left_values[2], Scalar::Int64(11));
15910        assert_eq!(left_values[4], Scalar::Int64(12));
15911        assert_eq!(left_values[6], Scalar::Int64(15));
15912        let right_values = fast.columns.get("w").unwrap().values();
15913        assert_eq!(right_values[0], Scalar::Float64(200.0));
15914        assert_eq!(right_values[1], Scalar::Float64(201.0));
15915        assert_eq!(right_values[2], Scalar::Float64(400.0));
15916        assert!(right_values[5].is_missing());
15917        assert!(right_values[6].is_missing());
15918    }
15919
15920    #[test]
15921    fn merge_left_dense_cycle_probe_declines_invented_gaps_66wab() {
15922        let left = DataFrame::from_dict(
15923            &["id", "v"],
15924            vec![
15925                (
15926                    "id",
15927                    vec![
15928                        Scalar::Int64(0),
15929                        Scalar::Int64(1),
15930                        Scalar::Int64(2),
15931                        Scalar::Int64(0),
15932                        Scalar::Int64(1),
15933                    ],
15934                ),
15935                (
15936                    "v",
15937                    vec![
15938                        Scalar::Int64(10),
15939                        Scalar::Int64(11),
15940                        Scalar::Int64(12),
15941                        Scalar::Int64(13),
15942                        Scalar::Int64(14),
15943                    ],
15944                ),
15945            ],
15946        )
15947        .unwrap();
15948        let right = DataFrame::from_dict(
15949            &["id", "w"],
15950            vec![
15951                (
15952                    "id",
15953                    vec![
15954                        Scalar::Int64(1),
15955                        Scalar::Int64(2),
15956                        Scalar::Int64(1),
15957                        Scalar::Int64(2),
15958                    ],
15959                ),
15960                (
15961                    "w",
15962                    vec![
15963                        Scalar::Int64(100),
15964                        Scalar::Int64(200),
15965                        Scalar::Int64(101),
15966                        Scalar::Int64(201),
15967                    ],
15968                ),
15969            ],
15970        )
15971        .unwrap();
15972        let left_key = left.columns().get("id").unwrap();
15973        let right_key = right.columns().get("id").unwrap();
15974        assert!(left_key.int64_dense_cycle_witness().is_some());
15975        assert!(right_key.int64_dense_cycle_witness().is_some());
15976        let suffixes = resolve_merge_suffixes(None);
15977
15978        let fused = build_single_key_dense_i64_left_merge_output(
15979            &left,
15980            &right,
15981            &["id"],
15982            &["id"],
15983            left_key,
15984            right_key,
15985            &suffixes,
15986        )
15987        .unwrap();
15988        assert!(fused.is_none());
15989    }
15990
15991    #[test]
15992    fn partial_int64_merges_promote_invented_gaps_66wab() {
15993        let left = DataFrame::from_dict(
15994            &["id", "v"],
15995            vec![
15996                (
15997                    "id",
15998                    vec![
15999                        Scalar::Int64(0),
16000                        Scalar::Int64(1),
16001                        Scalar::Int64(2),
16002                        Scalar::Int64(0),
16003                        Scalar::Int64(1),
16004                    ],
16005                ),
16006                (
16007                    "v",
16008                    vec![
16009                        Scalar::Int64(10),
16010                        Scalar::Int64(11),
16011                        Scalar::Int64(12),
16012                        Scalar::Int64(13),
16013                        Scalar::Int64(14),
16014                    ],
16015                ),
16016            ],
16017        )
16018        .unwrap();
16019        let right = DataFrame::from_dict(
16020            &["id", "w"],
16021            vec![
16022                (
16023                    "id",
16024                    vec![
16025                        Scalar::Int64(1),
16026                        Scalar::Int64(2),
16027                        Scalar::Int64(1),
16028                        Scalar::Int64(2),
16029                    ],
16030                ),
16031                (
16032                    "w",
16033                    vec![
16034                        Scalar::Int64(100),
16035                        Scalar::Int64(200),
16036                        Scalar::Int64(101),
16037                        Scalar::Int64(201),
16038                    ],
16039                ),
16040            ],
16041        )
16042        .unwrap();
16043
16044        let left_join = merge_dataframes(&left, &right, "id", JoinType::Left).unwrap();
16045        let left_gap_column = left_join.columns.get("w").unwrap();
16046        assert_eq!(left_gap_column.dtype(), DType::Float64);
16047        assert_eq!(left_gap_column.values()[0], Scalar::Null(NullKind::NaN));
16048        assert_eq!(left_gap_column.values()[1], Scalar::Float64(100.0));
16049
16050        let right_join = merge_dataframes(&right, &left, "id", JoinType::Right).unwrap();
16051        let right_gap_column = right_join.columns.get("w").unwrap();
16052        assert_eq!(right_gap_column.dtype(), DType::Float64);
16053        assert_eq!(right_gap_column.values()[0], Scalar::Null(NullKind::NaN));
16054        assert_eq!(right_gap_column.values()[1], Scalar::Float64(100.0));
16055    }
16056
16057    /// A missing value FrankenPandas spells two ways on a float lane: the
16058    /// `Null(NaN)` marker, and a present `Float64` whose bits are NaN (typed
16059    /// kernels emit the latter directly). pandas has ONE representation — the
16060    /// NaN bit pattern in the float64 array — and the fixture format writes
16061    /// either as `na_n`, so a null-kind assertion on a float lane must accept
16062    /// both or it fails on a legitimate representation change. What it must
16063    /// still reject is a carried-over generic `Null(Null)` or a `NaT`.
16064    ///
16065    /// br-frankenpandas-nywa8; the trap is WindyHare's window/derived slice.
16066    fn assert_nan_flavoured(value: &Scalar, what: &str) {
16067        let ok = match value {
16068            Scalar::Null(NullKind::NaN) => true,
16069            Scalar::Float64(v) => v.is_nan(),
16070            _ => false,
16071        };
16072        assert!(
16073            ok,
16074            "{what}: expected a NaN-flavoured missing, got {value:?}"
16075        );
16076    }
16077
16078    /// The four merge fixtures that were the last structural rows on
16079    /// br-frankenpandas-nywa8, run through the SAME entry point the conformance
16080    /// harness uses (`merge_dataframes_on_with_options`) on their exact
16081    /// payloads.
16082    ///
16083    /// THE RULE, and every line of it MEASURED against live pandas 2.2.3 rather
16084    /// than inferred from the differ: a lane widens iff the merge INVENTS a gap
16085    /// in THAT lane. The join type is irrelevant, and a lane that gains no gap
16086    /// keeps int64.
16087    ///
16088    /// ```text
16089    ///   l={'id':[1,2,3],'left_v':[10,20,30],'shared':[1,2,3]}
16090    ///   r={'id':[2],'right_v':[200],'shared':[9]}
16091    ///   l.merge(r, on='id', how='left')
16092    ///     id int64  left_v int64  shared_x int64      no gap  -> unchanged
16093    ///     right_v float64 [nan,200.0,nan]
16094    ///     shared_y float64 [nan,9.0,nan]              gap     -> widened
16095    ///
16096    ///   l={'id':[1,2],'left_v':[11,22]}  r={'id':[2,3],'right_v':[220,330]}
16097    ///   l.merge(r, on='id', how='right')
16098    ///     left_v float64 [22.0,nan]   right_v int64 [220,330]   id int64
16099    ///
16100    ///   l.merge(r, on='id', how='right', sort=True) over id l=[3,1] r=[2,1,3]
16101    ///     id int64 [1,2,3]  left_v float64 [10.0,nan,30.0]  right_v int64
16102    /// ```
16103    ///
16104    /// THE COMPOSITE OUTER CASE IS THE ONE WORTH THE TEST, because a single
16105    /// object column carries nywa8's two rules side by side. Measured on
16106    /// `lk2 = ['a', None, 'c']` outer-merged against `rk2 = ['a', None, 'd']`:
16107    ///
16108    /// ```text
16109    ///   lk2 dtype object, kinds ['str', 'NoneType', 'str', 'float']
16110    ///                                     ^ RULE 2          ^ RULE 1
16111    /// ```
16112    ///
16113    /// Row 1's `None` was SUPPLIED and object can store it, so pandas keeps it.
16114    /// Row 3's gap was INVENTED by the outer join, and pandas writes a float nan
16115    /// there even though the column is object. That is why the rule cannot be
16116    /// "derive the marker from the column dtype" — the same column answers
16117    /// differently per cell, and only the site that invents the gap knows which.
16118    #[test]
16119    fn merge_widens_only_the_lane_that_gains_an_invented_gap_nywa8() {
16120        // FP-P2D-014 dataframe_merge_column_left_missing_hardened
16121        let left = DataFrame::from_dict(
16122            &["id", "left_v", "shared"],
16123            vec![
16124                (
16125                    "id",
16126                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
16127                ),
16128                (
16129                    "left_v",
16130                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
16131                ),
16132                (
16133                    "shared",
16134                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
16135                ),
16136            ],
16137        )
16138        .unwrap();
16139        let right = DataFrame::from_dict(
16140            &["id", "right_v", "shared"],
16141            vec![
16142                ("id", vec![Scalar::Int64(2)]),
16143                ("right_v", vec![Scalar::Int64(200)]),
16144                ("shared", vec![Scalar::Int64(9)]),
16145            ],
16146        )
16147        .unwrap();
16148        let merged = merge_dataframes_on_with_options(
16149            &left,
16150            &right,
16151            &["id"],
16152            &["id"],
16153            JoinType::Left,
16154            MergeExecutionOptions::default(),
16155        )
16156        .unwrap();
16157        for gapless in ["id", "left_v", "shared_x"] {
16158            assert_eq!(
16159                merged.columns.get(gapless).unwrap().dtype(),
16160                DType::Int64,
16161                "{gapless} gains no gap and must stay int64"
16162            );
16163        }
16164        for gapped in ["right_v", "shared_y"] {
16165            let column = merged.columns.get(gapped).unwrap();
16166            assert_eq!(column.dtype(), DType::Float64, "{gapped} gains a gap");
16167            assert_nan_flavoured(&column.values()[0], gapped);
16168            assert_nan_flavoured(&column.values()[2], gapped);
16169        }
16170        assert_eq!(
16171            merged.columns.get("right_v").unwrap().values()[1],
16172            Scalar::Float64(200.0)
16173        );
16174        assert_eq!(
16175            merged.columns.get("shared_y").unwrap().values()[1],
16176            Scalar::Float64(9.0)
16177        );
16178
16179        // FP-P2D-014 dataframe_merge_column_right_order_strict
16180        let left = DataFrame::from_dict(
16181            &["id", "left_v"],
16182            vec![
16183                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
16184                ("left_v", vec![Scalar::Int64(11), Scalar::Int64(22)]),
16185            ],
16186        )
16187        .unwrap();
16188        let right = DataFrame::from_dict(
16189            &["id", "right_v"],
16190            vec![
16191                ("id", vec![Scalar::Int64(2), Scalar::Int64(3)]),
16192                ("right_v", vec![Scalar::Int64(220), Scalar::Int64(330)]),
16193            ],
16194        )
16195        .unwrap();
16196        let merged = merge_dataframes_on_with_options(
16197            &left,
16198            &right,
16199            &["id"],
16200            &["id"],
16201            JoinType::Right,
16202            MergeExecutionOptions::default(),
16203        )
16204        .unwrap();
16205        assert_eq!(merged.columns.get("id").unwrap().dtype(), DType::Int64);
16206        assert_eq!(merged.columns.get("right_v").unwrap().dtype(), DType::Int64);
16207        let left_v = merged.columns.get("left_v").unwrap();
16208        assert_eq!(left_v.dtype(), DType::Float64);
16209        assert_eq!(left_v.values()[0], Scalar::Float64(22.0));
16210        assert_nan_flavoured(&left_v.values()[1], "left_v");
16211
16212        // FP-P2D-037 dataframe_merge_sort_true_right_hardened
16213        let left = DataFrame::from_dict(
16214            &["id", "left_v"],
16215            vec![
16216                ("id", vec![Scalar::Int64(3), Scalar::Int64(1)]),
16217                ("left_v", vec![Scalar::Int64(30), Scalar::Int64(10)]),
16218            ],
16219        )
16220        .unwrap();
16221        let right = DataFrame::from_dict(
16222            &["id", "right_v"],
16223            vec![
16224                (
16225                    "id",
16226                    vec![Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(3)],
16227                ),
16228                (
16229                    "right_v",
16230                    vec![Scalar::Int64(200), Scalar::Int64(100), Scalar::Int64(300)],
16231                ),
16232            ],
16233        )
16234        .unwrap();
16235        let merged = merge_dataframes_on_with_options(
16236            &left,
16237            &right,
16238            &["id"],
16239            &["id"],
16240            JoinType::Right,
16241            MergeExecutionOptions {
16242                sort: true,
16243                ..MergeExecutionOptions::default()
16244            },
16245        )
16246        .unwrap();
16247        assert_eq!(merged.columns.get("id").unwrap().dtype(), DType::Int64);
16248        assert_eq!(merged.columns.get("right_v").unwrap().dtype(), DType::Int64);
16249        let left_v = merged.columns.get("left_v").unwrap();
16250        assert_eq!(left_v.dtype(), DType::Float64);
16251        assert_eq!(left_v.values()[0], Scalar::Float64(10.0));
16252        assert_nan_flavoured(&left_v.values()[1], "left_v");
16253        assert_eq!(left_v.values()[2], Scalar::Float64(30.0));
16254
16255        // FP-P2D-033 dataframe_merge_composite_left_right_alias_outer_hardened
16256        let left = DataFrame::from_dict(
16257            &["lk1", "lk2", "left_v"],
16258            vec![
16259                (
16260                    "lk1",
16261                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
16262                ),
16263                (
16264                    "lk2",
16265                    vec![
16266                        Scalar::Utf8("a".to_owned()),
16267                        Scalar::Null(NullKind::Null),
16268                        Scalar::Utf8("c".to_owned()),
16269                    ],
16270                ),
16271                (
16272                    "left_v",
16273                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
16274                ),
16275            ],
16276        )
16277        .unwrap();
16278        let right = DataFrame::from_dict(
16279            &["rk1", "rk2", "right_v"],
16280            vec![
16281                (
16282                    "rk1",
16283                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(4)],
16284                ),
16285                (
16286                    "rk2",
16287                    vec![
16288                        Scalar::Utf8("a".to_owned()),
16289                        Scalar::Null(NullKind::Null),
16290                        Scalar::Utf8("d".to_owned()),
16291                    ],
16292                ),
16293                (
16294                    "right_v",
16295                    vec![Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(400)],
16296                ),
16297            ],
16298        )
16299        .unwrap();
16300        let merged = merge_dataframes_on_with_options(
16301            &left,
16302            &right,
16303            &["lk1", "lk2"],
16304            &["rk1", "rk2"],
16305            JoinType::Outer,
16306            MergeExecutionOptions::default(),
16307        )
16308        .unwrap();
16309        // Every numeric lane gains a gap under this outer merge, so all four widen.
16310        for numeric in ["lk1", "rk1", "left_v", "right_v"] {
16311            assert_eq!(
16312                merged.columns.get(numeric).unwrap().dtype(),
16313                DType::Float64,
16314                "{numeric} gains a gap under the outer merge"
16315            );
16316        }
16317        assert_nan_flavoured(&merged.columns.get("lk1").unwrap().values()[3], "lk1");
16318        assert_nan_flavoured(&merged.columns.get("left_v").unwrap().values()[3], "left_v");
16319        assert_nan_flavoured(&merged.columns.get("rk1").unwrap().values()[2], "rk1");
16320        assert_nan_flavoured(
16321            &merged.columns.get("right_v").unwrap().values()[2],
16322            "right_v",
16323        );
16324
16325        // The object lanes are the point: SUPPLIED None survives, INVENTED gap
16326        // is a nan, in the same column.
16327        let lk2 = merged.columns.get("lk2").unwrap();
16328        assert_eq!(lk2.values()[0], Scalar::Utf8("a".to_owned()));
16329        assert_eq!(
16330            lk2.values()[1],
16331            Scalar::Null(NullKind::Null),
16332            "lk2[1]'s None was SUPPLIED and object can hold it (nywa8 Rule 2)"
16333        );
16334        assert_eq!(lk2.values()[2], Scalar::Utf8("c".to_owned()));
16335        assert_nan_flavoured(&lk2.values()[3], "lk2[3] is an INVENTED gap (nywa8 Rule 1)");
16336
16337        let rk2 = merged.columns.get("rk2").unwrap();
16338        assert_eq!(rk2.values()[0], Scalar::Utf8("a".to_owned()));
16339        assert_eq!(
16340            rk2.values()[1],
16341            Scalar::Null(NullKind::Null),
16342            "rk2[1]'s None was SUPPLIED and object can hold it (nywa8 Rule 2)"
16343        );
16344        assert_nan_flavoured(&rk2.values()[2], "rk2[2] is an INVENTED gap (nywa8 Rule 1)");
16345        assert_eq!(rk2.values()[3], Scalar::Utf8("d".to_owned()));
16346    }
16347
16348    #[test]
16349    fn merge_left_all_matched_dense_int64_fused_output_matches_sorted_generic_route() {
16350        let left = DataFrame::from_dict(
16351            &["id", "v"],
16352            vec![
16353                (
16354                    "id",
16355                    vec![
16356                        Scalar::Int64(0),
16357                        Scalar::Int64(0),
16358                        Scalar::Int64(1),
16359                        Scalar::Int64(1),
16360                        Scalar::Int64(2),
16361                    ],
16362                ),
16363                (
16364                    "v",
16365                    vec![
16366                        Scalar::Int64(10),
16367                        Scalar::Int64(11),
16368                        Scalar::Int64(20),
16369                        Scalar::Int64(21),
16370                        Scalar::Int64(30),
16371                    ],
16372                ),
16373            ],
16374        )
16375        .unwrap();
16376        let right = DataFrame::from_dict(
16377            &["id", "w"],
16378            vec![
16379                (
16380                    "id",
16381                    vec![
16382                        Scalar::Int64(0),
16383                        Scalar::Int64(0),
16384                        Scalar::Int64(1),
16385                        Scalar::Int64(2),
16386                        Scalar::Int64(2),
16387                    ],
16388                ),
16389                (
16390                    "w",
16391                    vec![
16392                        Scalar::Int64(100),
16393                        Scalar::Int64(101),
16394                        Scalar::Int64(200),
16395                        Scalar::Int64(300),
16396                        Scalar::Int64(301),
16397                    ],
16398                ),
16399            ],
16400        )
16401        .unwrap();
16402
16403        let fast = merge_dataframes(&left, &right, "id", JoinType::Left).unwrap();
16404        let generic = merge_dataframes_on_with_options(
16405            &left,
16406            &right,
16407            &["id"],
16408            &["id"],
16409            JoinType::Left,
16410            MergeExecutionOptions {
16411                sort: true,
16412                ..MergeExecutionOptions::default()
16413            },
16414        )
16415        .unwrap();
16416
16417        assert_eq!(fast.index, generic.index);
16418        assert_eq!(fast.column_order, generic.column_order);
16419        assert_eq!(fast.columns, generic.columns);
16420        assert_eq!(
16421            fast.columns.get("id").unwrap().values(),
16422            &[
16423                Scalar::Int64(0),
16424                Scalar::Int64(0),
16425                Scalar::Int64(0),
16426                Scalar::Int64(0),
16427                Scalar::Int64(1),
16428                Scalar::Int64(1),
16429                Scalar::Int64(2),
16430                Scalar::Int64(2),
16431            ]
16432        );
16433        assert_eq!(
16434            fast.columns.get("v").unwrap().values(),
16435            &[
16436                Scalar::Int64(10),
16437                Scalar::Int64(10),
16438                Scalar::Int64(11),
16439                Scalar::Int64(11),
16440                Scalar::Int64(20),
16441                Scalar::Int64(21),
16442                Scalar::Int64(30),
16443                Scalar::Int64(30),
16444            ]
16445        );
16446        assert_eq!(
16447            fast.columns.get("w").unwrap().values(),
16448            &[
16449                Scalar::Int64(100),
16450                Scalar::Int64(101),
16451                Scalar::Int64(100),
16452                Scalar::Int64(101),
16453                Scalar::Int64(200),
16454                Scalar::Int64(200),
16455                Scalar::Int64(300),
16456                Scalar::Int64(301),
16457            ]
16458        );
16459    }
16460
16461    #[test]
16462    fn merge_outer_ordered_unique_int64_subset_matches_generic_validated_route() {
16463        let left = DataFrame::from_dict(
16464            &["id", "v"],
16465            vec![
16466                (
16467                    "id",
16468                    vec![Scalar::Int64(0), Scalar::Int64(1), Scalar::Int64(3)],
16469                ),
16470                (
16471                    "v",
16472                    vec![Scalar::Int64(10), Scalar::Int64(11), Scalar::Int64(13)],
16473                ),
16474            ],
16475        )
16476        .unwrap();
16477        let right = DataFrame::from_dict(
16478            &["id", "w"],
16479            vec![
16480                (
16481                    "id",
16482                    vec![
16483                        Scalar::Int64(0),
16484                        Scalar::Int64(2),
16485                        Scalar::Int64(3),
16486                        Scalar::Int64(5),
16487                    ],
16488                ),
16489                (
16490                    "w",
16491                    vec![
16492                        Scalar::Int64(100),
16493                        Scalar::Int64(200),
16494                        Scalar::Int64(300),
16495                        Scalar::Int64(500),
16496                    ],
16497                ),
16498            ],
16499        )
16500        .unwrap();
16501
16502        let fast = merge_dataframes(&left, &right, "id", JoinType::Outer).unwrap();
16503        let generic = merge_dataframes_on_with_options(
16504            &left,
16505            &right,
16506            &["id"],
16507            &["id"],
16508            JoinType::Outer,
16509            MergeExecutionOptions {
16510                validate_mode: Some(MergeValidateMode::OneToOne),
16511                ..MergeExecutionOptions::default()
16512            },
16513        )
16514        .unwrap();
16515
16516        assert_eq!(fast.index, generic.index);
16517        assert_eq!(fast.column_order, generic.column_order);
16518        assert_eq!(fast.columns, generic.columns);
16519        assert_eq!(
16520            fast.columns.get("id").unwrap().values(),
16521            &[
16522                Scalar::Int64(0),
16523                Scalar::Int64(1),
16524                Scalar::Int64(2),
16525                Scalar::Int64(3),
16526                Scalar::Int64(5)
16527            ]
16528        );
16529        let left_values = fast.columns.get("v").unwrap().values();
16530        assert_eq!(left_values[0], Scalar::Float64(10.0));
16531        assert_eq!(left_values[1], Scalar::Float64(11.0));
16532        assert!(left_values[2].is_missing());
16533        assert_eq!(left_values[3], Scalar::Float64(13.0));
16534        assert!(left_values[4].is_missing());
16535        let right_values = fast.columns.get("w").unwrap().values();
16536        assert_eq!(right_values[0], Scalar::Float64(100.0));
16537        assert!(right_values[1].is_missing());
16538        assert_eq!(right_values[2], Scalar::Float64(200.0));
16539        assert_eq!(right_values[3], Scalar::Float64(300.0));
16540        assert_eq!(right_values[4], Scalar::Float64(500.0));
16541    }
16542
16543    #[test]
16544    fn merge_outer_dense_int64_duplicates_matches_generic_validated_route() {
16545        let left = DataFrame::from_dict(
16546            &["id", "v"],
16547            vec![
16548                (
16549                    "id",
16550                    vec![
16551                        Scalar::Int64(2),
16552                        Scalar::Int64(0),
16553                        Scalar::Int64(2),
16554                        Scalar::Int64(1),
16555                        Scalar::Int64(5),
16556                    ],
16557                ),
16558                (
16559                    "v",
16560                    vec![
16561                        Scalar::Int64(10),
16562                        Scalar::Int64(11),
16563                        Scalar::Int64(12),
16564                        Scalar::Int64(13),
16565                        Scalar::Int64(15),
16566                    ],
16567                ),
16568            ],
16569        )
16570        .unwrap();
16571        let right = DataFrame::from_dict(
16572            &["id", "w"],
16573            vec![
16574                (
16575                    "id",
16576                    vec![
16577                        Scalar::Int64(2),
16578                        Scalar::Int64(2),
16579                        Scalar::Int64(3),
16580                        Scalar::Int64(0),
16581                    ],
16582                ),
16583                (
16584                    "w",
16585                    vec![
16586                        Scalar::Int64(200),
16587                        Scalar::Int64(201),
16588                        Scalar::Int64(300),
16589                        Scalar::Int64(400),
16590                    ],
16591                ),
16592            ],
16593        )
16594        .unwrap();
16595
16596        let fast = merge_dataframes(&left, &right, "id", JoinType::Outer).unwrap();
16597        let generic = merge_dataframes_on_with_options(
16598            &left,
16599            &right,
16600            &["id"],
16601            &["id"],
16602            JoinType::Outer,
16603            MergeExecutionOptions {
16604                validate_mode: Some(MergeValidateMode::ManyToMany),
16605                ..MergeExecutionOptions::default()
16606            },
16607        )
16608        .unwrap();
16609
16610        assert_eq!(fast.index, generic.index);
16611        assert_eq!(fast.column_order, generic.column_order);
16612        assert_eq!(fast.columns, generic.columns);
16613        assert_eq!(
16614            fast.columns.get("id").unwrap().values(),
16615            &[
16616                Scalar::Int64(0),
16617                Scalar::Int64(1),
16618                Scalar::Int64(2),
16619                Scalar::Int64(2),
16620                Scalar::Int64(2),
16621                Scalar::Int64(2),
16622                Scalar::Int64(3),
16623                Scalar::Int64(5),
16624            ]
16625        );
16626        let left_values = fast.columns.get("v").unwrap().values();
16627        assert_eq!(left_values[0], Scalar::Float64(11.0));
16628        assert_eq!(left_values[1], Scalar::Float64(13.0));
16629        assert_eq!(left_values[2], Scalar::Float64(10.0));
16630        assert_eq!(left_values[5], Scalar::Float64(12.0));
16631        assert!(left_values[6].is_missing());
16632        assert_eq!(left_values[7], Scalar::Float64(15.0));
16633        let right_values = fast.columns.get("w").unwrap().values();
16634        assert_eq!(right_values[0], Scalar::Float64(400.0));
16635        assert!(right_values[1].is_missing());
16636        assert_eq!(right_values[2], Scalar::Float64(200.0));
16637        assert_eq!(right_values[3], Scalar::Float64(201.0));
16638        assert!(right_values[7].is_missing());
16639    }
16640
16641    #[test]
16642    fn merge_outer_all_matched_dense_int64_duplicates_matches_generic_validated_route() {
16643        let left = DataFrame::from_dict(
16644            &["id", "v"],
16645            vec![
16646                (
16647                    "id",
16648                    vec![
16649                        Scalar::Int64(2),
16650                        Scalar::Int64(1),
16651                        Scalar::Int64(2),
16652                        Scalar::Int64(1),
16653                    ],
16654                ),
16655                (
16656                    "v",
16657                    vec![
16658                        Scalar::Int64(20),
16659                        Scalar::Int64(10),
16660                        Scalar::Int64(21),
16661                        Scalar::Int64(11),
16662                    ],
16663                ),
16664            ],
16665        )
16666        .unwrap();
16667        let right = DataFrame::from_dict(
16668            &["id", "w"],
16669            vec![
16670                (
16671                    "id",
16672                    vec![
16673                        Scalar::Int64(1),
16674                        Scalar::Int64(2),
16675                        Scalar::Int64(1),
16676                        Scalar::Int64(2),
16677                    ],
16678                ),
16679                (
16680                    "w",
16681                    vec![
16682                        Scalar::Int64(100),
16683                        Scalar::Int64(200),
16684                        Scalar::Int64(101),
16685                        Scalar::Int64(201),
16686                    ],
16687                ),
16688            ],
16689        )
16690        .unwrap();
16691
16692        let fast = merge_dataframes(&left, &right, "id", JoinType::Outer).unwrap();
16693        let generic = merge_dataframes_on_with_options(
16694            &left,
16695            &right,
16696            &["id"],
16697            &["id"],
16698            JoinType::Outer,
16699            MergeExecutionOptions {
16700                validate_mode: Some(MergeValidateMode::ManyToMany),
16701                ..MergeExecutionOptions::default()
16702            },
16703        )
16704        .unwrap();
16705
16706        assert_eq!(fast.index, generic.index);
16707        assert_eq!(fast.column_order, generic.column_order);
16708        assert_eq!(fast.columns, generic.columns);
16709        assert_eq!(
16710            generic.columns.get("id").unwrap().values(),
16711            &[
16712                Scalar::Int64(1),
16713                Scalar::Int64(1),
16714                Scalar::Int64(1),
16715                Scalar::Int64(1),
16716                Scalar::Int64(2),
16717                Scalar::Int64(2),
16718                Scalar::Int64(2),
16719                Scalar::Int64(2),
16720            ]
16721        );
16722        assert!(
16723            generic
16724                .columns
16725                .values()
16726                .all(|column| column.as_i64_slice().is_some())
16727        );
16728    }
16729
16730    #[test]
16731    fn merge_outer_all_matched_dense_int64_fused_output_matches_sorted_generic_route() {
16732        let left = DataFrame::from_dict(
16733            &["id", "v"],
16734            vec![
16735                (
16736                    "id",
16737                    vec![
16738                        Scalar::Int64(2),
16739                        Scalar::Int64(1),
16740                        Scalar::Int64(2),
16741                        Scalar::Int64(1),
16742                    ],
16743                ),
16744                (
16745                    "v",
16746                    vec![
16747                        Scalar::Int64(20),
16748                        Scalar::Int64(10),
16749                        Scalar::Int64(21),
16750                        Scalar::Int64(11),
16751                    ],
16752                ),
16753            ],
16754        )
16755        .unwrap();
16756        let right = DataFrame::from_dict(
16757            &["id", "w"],
16758            vec![
16759                (
16760                    "id",
16761                    vec![
16762                        Scalar::Int64(1),
16763                        Scalar::Int64(2),
16764                        Scalar::Int64(1),
16765                        Scalar::Int64(2),
16766                    ],
16767                ),
16768                (
16769                    "w",
16770                    vec![
16771                        Scalar::Int64(100),
16772                        Scalar::Int64(200),
16773                        Scalar::Int64(101),
16774                        Scalar::Int64(201),
16775                    ],
16776                ),
16777            ],
16778        )
16779        .unwrap();
16780
16781        let fused = merge_dataframes(&left, &right, "id", JoinType::Outer).unwrap();
16782        let generic = merge_dataframes_on_with_options(
16783            &left,
16784            &right,
16785            &["id"],
16786            &["id"],
16787            JoinType::Outer,
16788            MergeExecutionOptions {
16789                validate_mode: Some(MergeValidateMode::ManyToMany),
16790                sort: true,
16791                ..MergeExecutionOptions::default()
16792            },
16793        )
16794        .unwrap();
16795
16796        assert_eq!(fused.index, generic.index);
16797        assert_eq!(fused.column_order, generic.column_order);
16798        assert_eq!(fused.columns, generic.columns);
16799    }
16800
16801    #[test]
16802    fn merge_left_contiguous_utf8_duplicates_matches_sorted_generic_route() {
16803        let s = |v: &str| Scalar::Utf8(v.to_owned());
16804        let left = DataFrame::from_dict(
16805            &["id", "v"],
16806            vec![
16807                ("id", vec![s("a"), s("a"), s("b"), s("c")]),
16808                (
16809                    "v",
16810                    vec![
16811                        Scalar::Int64(10),
16812                        Scalar::Int64(11),
16813                        Scalar::Int64(20),
16814                        Scalar::Int64(30),
16815                    ],
16816                ),
16817            ],
16818        )
16819        .unwrap();
16820        let right = DataFrame::from_dict(
16821            &["id", "w"],
16822            vec![
16823                ("id", vec![s("a"), s("a"), s("c")]),
16824                (
16825                    "w",
16826                    vec![Scalar::Int64(100), Scalar::Int64(101), Scalar::Int64(300)],
16827                ),
16828            ],
16829        )
16830        .unwrap();
16831
16832        let fast = merge_dataframes(&left, &right, "id", JoinType::Left).unwrap();
16833        let generic = merge_dataframes_on_with_options(
16834            &left,
16835            &right,
16836            &["id"],
16837            &["id"],
16838            JoinType::Left,
16839            MergeExecutionOptions {
16840                sort: true,
16841                ..MergeExecutionOptions::default()
16842            },
16843        )
16844        .unwrap();
16845
16846        assert_eq!(fast.index, generic.index);
16847        assert_eq!(fast.column_order, generic.column_order);
16848        assert_eq!(fast.columns, generic.columns);
16849        assert_eq!(
16850            fast.columns.get("id").unwrap().values(),
16851            &[s("a"), s("a"), s("a"), s("a"), s("b"), s("c")]
16852        );
16853        assert!(fast.columns.get("w").unwrap().values()[4].is_missing());
16854    }
16855
16856    #[test]
16857    fn merge_outer_object_gaps_are_nan_and_supplied_none_stays_7u2td() {
16858        // pandas 2.2.3: DataFrame({'k':['a','b'],'s':[None,'y']}).merge(
16859        //   DataFrame({'k2':['b','c'],'t':['p','q']}), left_on='k',
16860        //   right_on='k2', how='outer')
16861        //   -> k [a, b, nan]  s [None, y, nan]  k2 [nan, b, c]  t [nan, p, q]
16862        let text = |t: &str| Scalar::Utf8(t.to_owned());
16863        let nan = Scalar::Null(NullKind::NaN);
16864        let left = DataFrame::from_dict(
16865            &["k", "s"],
16866            vec![
16867                ("k", vec![text("a"), text("b")]),
16868                ("s", vec![Scalar::Null(NullKind::Null), text("y")]),
16869            ],
16870        )
16871        .unwrap();
16872        let right = DataFrame::from_dict(
16873            &["k2", "t"],
16874            vec![
16875                ("k2", vec![text("b"), text("c")]),
16876                ("t", vec![text("p"), text("q")]),
16877            ],
16878        )
16879        .unwrap();
16880        let merged = merge_dataframes_on_with_options(
16881            &left,
16882            &right,
16883            &["k"],
16884            &["k2"],
16885            JoinType::Outer,
16886            MergeExecutionOptions::default(),
16887        )
16888        .unwrap();
16889        let column = |name: &str| merged.columns.get(name).unwrap().values().to_vec();
16890        assert_eq!(column("k"), vec![text("a"), text("b"), nan.clone()]);
16891        assert_eq!(column("k2"), vec![nan.clone(), text("b"), text("c")]);
16892        assert_eq!(column("t"), vec![nan.clone(), text("p"), text("q")]);
16893        // NEGATIVE: the supplied None is kept beside the invented NaN.
16894        assert_eq!(
16895            column("s"),
16896            vec![Scalar::Null(NullKind::Null), text("y"), nan]
16897        );
16898    }
16899
16900    #[test]
16901    fn merge_outer_contiguous_utf8_duplicates_matches_sorted_generic_route() {
16902        let s = |v: &str| Scalar::Utf8(v.to_owned());
16903        let left = DataFrame::from_dict(
16904            &["id", "v"],
16905            vec![
16906                ("id", vec![s("a"), s("a"), s("b"), s("d")]),
16907                (
16908                    "v",
16909                    vec![
16910                        Scalar::Int64(10),
16911                        Scalar::Int64(11),
16912                        Scalar::Int64(20),
16913                        Scalar::Int64(40),
16914                    ],
16915                ),
16916            ],
16917        )
16918        .unwrap();
16919        let right = DataFrame::from_dict(
16920            &["id", "w"],
16921            vec![
16922                ("id", vec![s("a"), s("c"), s("a")]),
16923                (
16924                    "w",
16925                    vec![Scalar::Int64(100), Scalar::Int64(300), Scalar::Int64(101)],
16926                ),
16927            ],
16928        )
16929        .unwrap();
16930
16931        let fast = merge_dataframes(&left, &right, "id", JoinType::Outer).unwrap();
16932        let generic = merge_dataframes_on_with_options(
16933            &left,
16934            &right,
16935            &["id"],
16936            &["id"],
16937            JoinType::Outer,
16938            MergeExecutionOptions {
16939                sort: true,
16940                ..MergeExecutionOptions::default()
16941            },
16942        )
16943        .unwrap();
16944
16945        assert_eq!(fast.index, generic.index);
16946        assert_eq!(fast.column_order, generic.column_order);
16947        assert_eq!(fast.columns, generic.columns);
16948        assert_eq!(
16949            fast.columns.get("id").unwrap().values(),
16950            &[s("a"), s("a"), s("a"), s("a"), s("b"), s("c"), s("d")]
16951        );
16952        assert!(fast.columns.get("v").unwrap().values()[5].is_missing());
16953        assert!(fast.columns.get("w").unwrap().values()[4].is_missing());
16954        assert!(fast.columns.get("w").unwrap().values()[6].is_missing());
16955    }
16956
16957    #[test]
16958    fn merge_outer_fixed_decimal_utf8_all_matched_fuses_sorted_output_wikcu() {
16959        let s = |v: &str| Scalar::Utf8(v.to_owned());
16960        let left = DataFrame::from_dict(
16961            &["id", "lv"],
16962            vec![
16963                (
16964                    "id",
16965                    vec![
16966                        s("k00000002"),
16967                        s("k00000000"),
16968                        s("k00000002"),
16969                        s("k00000001"),
16970                    ],
16971                ),
16972                (
16973                    "lv",
16974                    vec![
16975                        Scalar::Float64(20.0),
16976                        Scalar::Float64(0.0),
16977                        Scalar::Float64(21.0),
16978                        Scalar::Float64(10.0),
16979                    ],
16980                ),
16981            ],
16982        )
16983        .unwrap();
16984        let right = DataFrame::from_dict(
16985            &["id", "rv"],
16986            vec![
16987                ("id", vec![s("k00000000"), s("k00000001"), s("k00000002")]),
16988                (
16989                    "rv",
16990                    vec![
16991                        Scalar::Float64(100.0),
16992                        Scalar::Float64(110.0),
16993                        Scalar::Float64(120.0),
16994                    ],
16995                ),
16996            ],
16997        )
16998        .unwrap();
16999
17000        let fast = merge_dataframes(&left, &right, "id", JoinType::Outer).unwrap();
17001        let generic = merge_dataframes_on_with_options(
17002            &left,
17003            &right,
17004            &["id"],
17005            &["id"],
17006            JoinType::Outer,
17007            MergeExecutionOptions {
17008                sort: true,
17009                ..MergeExecutionOptions::default()
17010            },
17011        )
17012        .unwrap();
17013
17014        assert_eq!(fast.index, generic.index);
17015        assert_eq!(fast.column_order, generic.column_order);
17016        assert_eq!(fast.columns, generic.columns);
17017        assert_eq!(
17018            fast.columns.get("id").unwrap().values(),
17019            &[
17020                s("k00000000"),
17021                s("k00000001"),
17022                s("k00000002"),
17023                s("k00000002")
17024            ]
17025        );
17026        assert_eq!(
17027            fast.columns.get("lv").unwrap().values(),
17028            &[
17029                Scalar::Float64(0.0),
17030                Scalar::Float64(10.0),
17031                Scalar::Float64(20.0),
17032                Scalar::Float64(21.0),
17033            ]
17034        );
17035    }
17036
17037    #[test]
17038    fn merge_right_dense_int64_duplicates_matches_generic_validated_route() {
17039        let left = DataFrame::from_dict(
17040            &["id", "v"],
17041            vec![
17042                (
17043                    "id",
17044                    vec![
17045                        Scalar::Int64(2),
17046                        Scalar::Int64(0),
17047                        Scalar::Int64(2),
17048                        Scalar::Int64(1),
17049                        Scalar::Int64(5),
17050                    ],
17051                ),
17052                (
17053                    "v",
17054                    vec![
17055                        Scalar::Int64(10),
17056                        Scalar::Int64(11),
17057                        Scalar::Int64(12),
17058                        Scalar::Int64(13),
17059                        Scalar::Int64(15),
17060                    ],
17061                ),
17062            ],
17063        )
17064        .unwrap();
17065        let right = DataFrame::from_dict(
17066            &["id", "w"],
17067            vec![
17068                (
17069                    "id",
17070                    vec![
17071                        Scalar::Int64(2),
17072                        Scalar::Int64(2),
17073                        Scalar::Int64(3),
17074                        Scalar::Int64(0),
17075                    ],
17076                ),
17077                (
17078                    "w",
17079                    vec![
17080                        Scalar::Int64(200),
17081                        Scalar::Int64(201),
17082                        Scalar::Int64(300),
17083                        Scalar::Int64(400),
17084                    ],
17085                ),
17086            ],
17087        )
17088        .unwrap();
17089
17090        let fast = merge_dataframes(&left, &right, "id", JoinType::Right).unwrap();
17091        let generic = merge_dataframes_on_with_options(
17092            &left,
17093            &right,
17094            &["id"],
17095            &["id"],
17096            JoinType::Right,
17097            MergeExecutionOptions {
17098                validate_mode: Some(MergeValidateMode::ManyToMany),
17099                ..MergeExecutionOptions::default()
17100            },
17101        )
17102        .unwrap();
17103
17104        assert_eq!(fast.index, generic.index);
17105        assert_eq!(fast.column_order, generic.column_order);
17106        assert_eq!(fast.columns, generic.columns);
17107        assert_eq!(
17108            fast.columns.get("id").unwrap().values(),
17109            &[
17110                Scalar::Int64(2),
17111                Scalar::Int64(2),
17112                Scalar::Int64(2),
17113                Scalar::Int64(2),
17114                Scalar::Int64(3),
17115                Scalar::Int64(0),
17116            ]
17117        );
17118        let left_values = fast.columns.get("v").unwrap().values();
17119        assert_eq!(left_values[0], Scalar::Float64(10.0));
17120        assert_eq!(left_values[1], Scalar::Float64(12.0));
17121        assert_eq!(left_values[2], Scalar::Float64(10.0));
17122        assert_eq!(left_values[3], Scalar::Float64(12.0));
17123        assert!(left_values[4].is_missing());
17124        assert_eq!(left_values[5], Scalar::Float64(11.0));
17125        let right_values = fast.columns.get("w").unwrap().values();
17126        assert_eq!(right_values[0], Scalar::Int64(200));
17127        assert_eq!(right_values[1], Scalar::Int64(200));
17128        assert_eq!(right_values[2], Scalar::Int64(201));
17129        assert_eq!(right_values[3], Scalar::Int64(201));
17130        assert_eq!(right_values[4], Scalar::Int64(300));
17131        assert_eq!(right_values[5], Scalar::Int64(400));
17132    }
17133
17134    #[test]
17135    fn merge_right_dense_cycle_probe_declines_invented_gaps_66wab() {
17136        let left = DataFrame::from_dict(
17137            &["id", "v"],
17138            vec![
17139                (
17140                    "id",
17141                    vec![
17142                        Scalar::Int64(1),
17143                        Scalar::Int64(2),
17144                        Scalar::Int64(1),
17145                        Scalar::Int64(2),
17146                    ],
17147                ),
17148                (
17149                    "v",
17150                    vec![
17151                        Scalar::Int64(100),
17152                        Scalar::Int64(200),
17153                        Scalar::Int64(101),
17154                        Scalar::Int64(201),
17155                    ],
17156                ),
17157            ],
17158        )
17159        .unwrap();
17160        let right = DataFrame::from_dict(
17161            &["id", "w"],
17162            vec![
17163                (
17164                    "id",
17165                    vec![
17166                        Scalar::Int64(0),
17167                        Scalar::Int64(1),
17168                        Scalar::Int64(2),
17169                        Scalar::Int64(0),
17170                        Scalar::Int64(1),
17171                    ],
17172                ),
17173                (
17174                    "w",
17175                    vec![
17176                        Scalar::Int64(10),
17177                        Scalar::Int64(11),
17178                        Scalar::Int64(12),
17179                        Scalar::Int64(13),
17180                        Scalar::Int64(14),
17181                    ],
17182                ),
17183            ],
17184        )
17185        .unwrap();
17186        let left_key = left.columns().get("id").unwrap();
17187        let right_key = right.columns().get("id").unwrap();
17188        assert!(left_key.int64_dense_cycle_witness().is_some());
17189        assert!(right_key.int64_dense_cycle_witness().is_some());
17190        let suffixes = resolve_merge_suffixes(None);
17191
17192        let fused = build_single_key_dense_i64_right_merge_output(
17193            &left,
17194            &right,
17195            &["id"],
17196            &["id"],
17197            left_key,
17198            right_key,
17199            &suffixes,
17200        )
17201        .unwrap();
17202        assert!(fused.is_none());
17203    }
17204
17205    #[test]
17206    fn merge_left_right_all_matched_dense_int64_duplicates_match_generic_validated_route() {
17207        let left = DataFrame::from_dict(
17208            &["id", "v"],
17209            vec![
17210                (
17211                    "id",
17212                    vec![
17213                        Scalar::Int64(2),
17214                        Scalar::Int64(1),
17215                        Scalar::Int64(2),
17216                        Scalar::Int64(1),
17217                    ],
17218                ),
17219                (
17220                    "v",
17221                    vec![
17222                        Scalar::Int64(20),
17223                        Scalar::Int64(10),
17224                        Scalar::Int64(21),
17225                        Scalar::Int64(11),
17226                    ],
17227                ),
17228            ],
17229        )
17230        .unwrap();
17231        let right = DataFrame::from_dict(
17232            &["id", "w"],
17233            vec![
17234                (
17235                    "id",
17236                    vec![
17237                        Scalar::Int64(1),
17238                        Scalar::Int64(2),
17239                        Scalar::Int64(1),
17240                        Scalar::Int64(2),
17241                    ],
17242                ),
17243                (
17244                    "w",
17245                    vec![
17246                        Scalar::Int64(100),
17247                        Scalar::Int64(200),
17248                        Scalar::Int64(101),
17249                        Scalar::Int64(201),
17250                    ],
17251                ),
17252            ],
17253        )
17254        .unwrap();
17255
17256        for join_type in [JoinType::Left, JoinType::Right] {
17257            let fast = merge_dataframes(&left, &right, "id", join_type).unwrap();
17258            let generic = merge_dataframes_on_with_options(
17259                &left,
17260                &right,
17261                &["id"],
17262                &["id"],
17263                join_type,
17264                MergeExecutionOptions {
17265                    validate_mode: Some(MergeValidateMode::ManyToMany),
17266                    ..MergeExecutionOptions::default()
17267                },
17268            )
17269            .unwrap();
17270
17271            assert_eq!(fast.index, generic.index);
17272            assert_eq!(fast.column_order, generic.column_order);
17273            assert_eq!(fast.columns, generic.columns);
17274            assert!(
17275                generic
17276                    .columns
17277                    .values()
17278                    .all(|column| column.as_i64_slice().is_some())
17279            );
17280        }
17281    }
17282
17283    #[test]
17284    fn merge_right_all_matched_dense_int64_fused_output_matches_dense_materialization() {
17285        let left = DataFrame::from_dict(
17286            &["id", "v"],
17287            vec![
17288                (
17289                    "id",
17290                    vec![
17291                        Scalar::Int64(2),
17292                        Scalar::Int64(1),
17293                        Scalar::Int64(2),
17294                        Scalar::Int64(1),
17295                    ],
17296                ),
17297                (
17298                    "v",
17299                    vec![
17300                        Scalar::Int64(20),
17301                        Scalar::Int64(10),
17302                        Scalar::Int64(21),
17303                        Scalar::Int64(11),
17304                    ],
17305                ),
17306            ],
17307        )
17308        .unwrap();
17309        let right = DataFrame::from_dict(
17310            &["id", "w"],
17311            vec![
17312                (
17313                    "id",
17314                    vec![
17315                        Scalar::Int64(1),
17316                        Scalar::Int64(2),
17317                        Scalar::Int64(1),
17318                        Scalar::Int64(2),
17319                    ],
17320                ),
17321                (
17322                    "w",
17323                    vec![
17324                        Scalar::Int64(100),
17325                        Scalar::Int64(200),
17326                        Scalar::Int64(101),
17327                        Scalar::Int64(201),
17328                    ],
17329                ),
17330            ],
17331        )
17332        .unwrap();
17333
17334        let fused = merge_dataframes(&left, &right, "id", JoinType::Right).unwrap();
17335        let left_key = left.columns().get("id").unwrap();
17336        let right_key = right.columns().get("id").unwrap();
17337        let (left_positions, right_positions) =
17338            dense_int64_right_positions(left_key, right_key).unwrap();
17339        let suffixes = resolve_merge_suffixes(None);
17340        let materialized = build_single_key_dense_right_merge_output(
17341            &left,
17342            &right,
17343            &["id"],
17344            &["id"],
17345            &left_positions,
17346            &right_positions,
17347            &suffixes,
17348        )
17349        .unwrap();
17350
17351        assert_eq!(fused.index, materialized.index);
17352        assert_eq!(fused.column_order, materialized.column_order);
17353        assert_eq!(fused.columns, materialized.columns);
17354        assert_eq!(
17355            fused.columns.get("id").unwrap().values(),
17356            &[
17357                Scalar::Int64(1),
17358                Scalar::Int64(1),
17359                Scalar::Int64(2),
17360                Scalar::Int64(2),
17361                Scalar::Int64(1),
17362                Scalar::Int64(1),
17363                Scalar::Int64(2),
17364                Scalar::Int64(2),
17365            ]
17366        );
17367        assert!(
17368            fused
17369                .columns
17370                .values()
17371                .all(|column| column.as_i64_slice().is_some())
17372        );
17373    }
17374
17375    #[test]
17376    fn merge_right_ordered_unique_int64_subset_matches_generic_validated_route() {
17377        let left = DataFrame::from_dict(
17378            &["id", "v"],
17379            vec![
17380                (
17381                    "id",
17382                    vec![Scalar::Int64(0), Scalar::Int64(1), Scalar::Int64(3)],
17383                ),
17384                (
17385                    "v",
17386                    vec![Scalar::Int64(10), Scalar::Int64(11), Scalar::Int64(13)],
17387                ),
17388            ],
17389        )
17390        .unwrap();
17391        let right = DataFrame::from_dict(
17392            &["id", "w"],
17393            vec![
17394                (
17395                    "id",
17396                    vec![
17397                        Scalar::Int64(0),
17398                        Scalar::Int64(2),
17399                        Scalar::Int64(3),
17400                        Scalar::Int64(5),
17401                    ],
17402                ),
17403                (
17404                    "w",
17405                    vec![
17406                        Scalar::Int64(100),
17407                        Scalar::Int64(200),
17408                        Scalar::Int64(300),
17409                        Scalar::Int64(500),
17410                    ],
17411                ),
17412            ],
17413        )
17414        .unwrap();
17415
17416        let fast = merge_dataframes(&left, &right, "id", JoinType::Right).unwrap();
17417        let generic = merge_dataframes_on_with_options(
17418            &left,
17419            &right,
17420            &["id"],
17421            &["id"],
17422            JoinType::Right,
17423            MergeExecutionOptions {
17424                validate_mode: Some(MergeValidateMode::OneToOne),
17425                ..MergeExecutionOptions::default()
17426            },
17427        )
17428        .unwrap();
17429
17430        assert_eq!(fast.index, generic.index);
17431        assert_eq!(fast.column_order, generic.column_order);
17432        assert_eq!(fast.columns, generic.columns);
17433        assert_eq!(
17434            fast.columns.get("id").unwrap().values(),
17435            &[
17436                Scalar::Int64(0),
17437                Scalar::Int64(2),
17438                Scalar::Int64(3),
17439                Scalar::Int64(5)
17440            ]
17441        );
17442        let left_values = fast.columns.get("v").unwrap().values();
17443        assert_eq!(left_values[0], Scalar::Float64(10.0));
17444        assert!(left_values[1].is_missing());
17445        assert_eq!(left_values[2], Scalar::Float64(13.0));
17446        assert!(left_values[3].is_missing());
17447        let right_values = fast.columns.get("w").unwrap().values();
17448        assert_eq!(right_values[0], Scalar::Int64(100));
17449        assert_eq!(right_values[1], Scalar::Int64(200));
17450        assert_eq!(right_values[2], Scalar::Int64(300));
17451        assert_eq!(right_values[3], Scalar::Int64(500));
17452    }
17453
17454    #[test]
17455    fn merge_right_preserves_all_right_rows() {
17456        let left = make_left_df();
17457        let right = make_right_df();
17458        let merged = merge_dataframes(&left, &right, "id", JoinType::Right).unwrap();
17459
17460        assert_eq!(merged.columns.get("id").unwrap().len(), 3);
17461        assert_eq!(
17462            merged.columns.get("val_b").unwrap().values(),
17463            &[Scalar::Int64(200), Scalar::Int64(300), Scalar::Int64(400)]
17464        );
17465        // val_a widens to Float64 because id=4 invents a missing value.
17466        assert_eq!(merged.columns.get("val_a").unwrap().dtype(), DType::Float64);
17467        assert_eq!(
17468            merged.columns.get("val_a").unwrap().values()[0],
17469            Scalar::Float64(20.0)
17470        );
17471        assert_eq!(
17472            merged.columns.get("val_a").unwrap().values()[1],
17473            Scalar::Float64(30.0)
17474        );
17475        assert_eq!(
17476            merged.columns.get("val_a").unwrap().values()[2],
17477            Scalar::Null(NullKind::NaN)
17478        );
17479    }
17480
17481    #[test]
17482    fn merge_outer_contains_all_rows() {
17483        let left = make_left_df();
17484        let right = make_right_df();
17485        let merged = merge_dataframes(&left, &right, "id", JoinType::Outer).unwrap();
17486
17487        // ids: 1, 2, 3 from left + 4 from right = 4 rows
17488        assert_eq!(merged.columns.get("id").unwrap().len(), 4);
17489    }
17490
17491    #[test]
17492    fn merge_inner_sort_false_preserves_left_key_order() {
17493        let left = DataFrame::from_dict(
17494            &["id", "left_v"],
17495            vec![
17496                (
17497                    "id",
17498                    vec![Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(2)],
17499                ),
17500                (
17501                    "left_v",
17502                    vec![Scalar::Int64(20), Scalar::Int64(10), Scalar::Int64(21)],
17503                ),
17504            ],
17505        )
17506        .expect("left");
17507        let right = DataFrame::from_dict(
17508            &["id", "right_v"],
17509            vec![
17510                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
17511                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
17512            ],
17513        )
17514        .expect("right");
17515
17516        let merged = merge_dataframes_on_with_options(
17517            &left,
17518            &right,
17519            &["id"],
17520            &["id"],
17521            JoinType::Inner,
17522            MergeExecutionOptions::default(),
17523        )
17524        .expect("merge");
17525        assert_eq!(
17526            merged.columns.get("id").expect("id").values(),
17527            &[Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(2)]
17528        );
17529        assert_eq!(
17530            merged.columns.get("left_v").expect("left_v").values(),
17531            &[Scalar::Int64(20), Scalar::Int64(10), Scalar::Int64(21)]
17532        );
17533        assert_eq!(
17534            merged.columns.get("right_v").expect("right_v").values(),
17535            &[Scalar::Int64(200), Scalar::Int64(100), Scalar::Int64(200)]
17536        );
17537    }
17538
17539    #[test]
17540    fn merge_inner_sort_true_orders_join_keys_lexicographically() {
17541        let left = DataFrame::from_dict(
17542            &["id", "left_v"],
17543            vec![
17544                (
17545                    "id",
17546                    vec![Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(2)],
17547                ),
17548                (
17549                    "left_v",
17550                    vec![Scalar::Int64(20), Scalar::Int64(10), Scalar::Int64(21)],
17551                ),
17552            ],
17553        )
17554        .expect("left");
17555        let right = DataFrame::from_dict(
17556            &["id", "right_v"],
17557            vec![
17558                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
17559                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
17560            ],
17561        )
17562        .expect("right");
17563
17564        let merged = merge_dataframes_on_with_options(
17565            &left,
17566            &right,
17567            &["id"],
17568            &["id"],
17569            JoinType::Inner,
17570            MergeExecutionOptions {
17571                sort: true,
17572                ..MergeExecutionOptions::default()
17573            },
17574        )
17575        .expect("merge");
17576        assert_eq!(
17577            merged.columns.get("id").expect("id").values(),
17578            &[Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(2)]
17579        );
17580        assert_eq!(
17581            merged.columns.get("left_v").expect("left_v").values(),
17582            &[Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(21)]
17583        );
17584        assert_eq!(
17585            merged.columns.get("right_v").expect("right_v").values(),
17586            &[Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(200)]
17587        );
17588    }
17589
17590    #[test]
17591    fn merge_inner_sort_true_orders_float_keys_numerically() {
17592        let left = DataFrame::from_dict(
17593            &["id", "left_v"],
17594            vec![
17595                (
17596                    "id",
17597                    vec![
17598                        Scalar::Float64(1.5),
17599                        Scalar::Float64(-2.5),
17600                        Scalar::Float64(0.25),
17601                    ],
17602                ),
17603                (
17604                    "left_v",
17605                    vec![Scalar::Int64(15), Scalar::Int64(-25), Scalar::Int64(2)],
17606                ),
17607            ],
17608        )
17609        .expect("left");
17610        let right = DataFrame::from_dict(
17611            &["id", "right_v"],
17612            vec![
17613                (
17614                    "id",
17615                    vec![
17616                        Scalar::Float64(-2.5),
17617                        Scalar::Float64(0.25),
17618                        Scalar::Float64(1.5),
17619                    ],
17620                ),
17621                (
17622                    "right_v",
17623                    vec![Scalar::Int64(250), Scalar::Int64(25), Scalar::Int64(150)],
17624                ),
17625            ],
17626        )
17627        .expect("right");
17628
17629        let merged = merge_dataframes_on_with_options(
17630            &left,
17631            &right,
17632            &["id"],
17633            &["id"],
17634            JoinType::Inner,
17635            MergeExecutionOptions {
17636                sort: true,
17637                ..MergeExecutionOptions::default()
17638            },
17639        )
17640        .expect("merge");
17641
17642        assert_eq!(
17643            merged.columns.get("id").expect("id").values(),
17644            &[
17645                Scalar::Float64(-2.5),
17646                Scalar::Float64(0.25),
17647                Scalar::Float64(1.5)
17648            ]
17649        );
17650        assert_eq!(
17651            merged.columns.get("left_v").expect("left_v").values(),
17652            &[Scalar::Int64(-25), Scalar::Int64(2), Scalar::Int64(15)]
17653        );
17654        assert_eq!(
17655            merged.columns.get("right_v").expect("right_v").values(),
17656            &[Scalar::Int64(250), Scalar::Int64(25), Scalar::Int64(150)]
17657        );
17658    }
17659
17660    #[test]
17661    fn merge_right_sort_true_orders_join_keys_lexicographically() {
17662        let left = DataFrame::from_dict(
17663            &["id", "left_v"],
17664            vec![
17665                ("id", vec![Scalar::Int64(3), Scalar::Int64(1)]),
17666                ("left_v", vec![Scalar::Int64(30), Scalar::Int64(10)]),
17667            ],
17668        )
17669        .expect("left");
17670        let right = DataFrame::from_dict(
17671            &["id", "right_v"],
17672            vec![
17673                (
17674                    "id",
17675                    vec![Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(3)],
17676                ),
17677                (
17678                    "right_v",
17679                    vec![Scalar::Int64(200), Scalar::Int64(100), Scalar::Int64(300)],
17680                ),
17681            ],
17682        )
17683        .expect("right");
17684
17685        let merged = merge_dataframes_on_with_options(
17686            &left,
17687            &right,
17688            &["id"],
17689            &["id"],
17690            JoinType::Right,
17691            MergeExecutionOptions {
17692                sort: true,
17693                ..MergeExecutionOptions::default()
17694            },
17695        )
17696        .expect("merge");
17697        assert_eq!(
17698            merged.columns.get("id").expect("id").values(),
17699            &[Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)]
17700        );
17701        assert_eq!(
17702            merged.columns.get("left_v").expect("left_v").values(),
17703            &[
17704                Scalar::Float64(10.0),
17705                Scalar::Null(NullKind::NaN),
17706                Scalar::Float64(30.0)
17707            ]
17708        );
17709        assert_eq!(
17710            merged.columns.get("right_v").expect("right_v").values(),
17711            &[Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(300)]
17712        );
17713    }
17714
17715    #[test]
17716    fn merge_column_name_conflict_adds_suffixes() {
17717        let left = DataFrame::from_dict(
17718            &["id", "val"],
17719            vec![
17720                ("id", vec![Scalar::Int64(1)]),
17721                ("val", vec![Scalar::Int64(10)]),
17722            ],
17723        )
17724        .unwrap();
17725        let right = DataFrame::from_dict(
17726            &["id", "val"],
17727            vec![
17728                ("id", vec![Scalar::Int64(1)]),
17729                ("val", vec![Scalar::Int64(99)]),
17730            ],
17731        )
17732        .unwrap();
17733
17734        let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
17735        assert!(merged.columns.contains_key("val_x"));
17736        assert!(merged.columns.contains_key("val_y"));
17737        assert_eq!(
17738            merged.columns.get("val_x").unwrap().values(),
17739            &[Scalar::Int64(10)]
17740        );
17741        assert_eq!(
17742            merged.columns.get("val_y").unwrap().values(),
17743            &[Scalar::Int64(99)]
17744        );
17745    }
17746
17747    #[test]
17748    fn merge_column_name_conflict_honors_custom_suffixes() {
17749        let left = DataFrame::from_dict(
17750            &["id", "val"],
17751            vec![
17752                ("id", vec![Scalar::Int64(1)]),
17753                ("val", vec![Scalar::Int64(10)]),
17754            ],
17755        )
17756        .expect("left");
17757        let right = DataFrame::from_dict(
17758            &["id", "val"],
17759            vec![
17760                ("id", vec![Scalar::Int64(1)]),
17761                ("val", vec![Scalar::Int64(99)]),
17762            ],
17763        )
17764        .expect("right");
17765
17766        let merged = merge_dataframes_on_with_options(
17767            &left,
17768            &right,
17769            &["id"],
17770            &["id"],
17771            JoinType::Inner,
17772            MergeExecutionOptions {
17773                suffixes: Some([Some("_L".to_owned()), Some("_R".to_owned())]),
17774                ..MergeExecutionOptions::default()
17775            },
17776        )
17777        .expect("merge");
17778        assert!(merged.columns.contains_key("val_L"));
17779        assert!(merged.columns.contains_key("val_R"));
17780        assert_eq!(
17781            merged.columns.get("val_L").expect("left suffixed").values(),
17782            &[Scalar::Int64(10)]
17783        );
17784        assert_eq!(
17785            merged
17786                .columns
17787                .get("val_R")
17788                .expect("right suffixed")
17789                .values(),
17790            &[Scalar::Int64(99)]
17791        );
17792    }
17793
17794    #[test]
17795    fn merge_column_name_conflict_allows_one_sided_suffix() {
17796        let left = DataFrame::from_dict(
17797            &["id", "val"],
17798            vec![
17799                ("id", vec![Scalar::Int64(1)]),
17800                ("val", vec![Scalar::Int64(10)]),
17801            ],
17802        )
17803        .expect("left");
17804        let right = DataFrame::from_dict(
17805            &["id", "val"],
17806            vec![
17807                ("id", vec![Scalar::Int64(1)]),
17808                ("val", vec![Scalar::Int64(99)]),
17809            ],
17810        )
17811        .expect("right");
17812
17813        let merged = merge_dataframes_on_with_options(
17814            &left,
17815            &right,
17816            &["id"],
17817            &["id"],
17818            JoinType::Inner,
17819            MergeExecutionOptions {
17820                suffixes: Some([None, Some("_r".to_owned())]),
17821                ..MergeExecutionOptions::default()
17822            },
17823        )
17824        .expect("merge");
17825        assert!(merged.columns.contains_key("val"));
17826        assert!(merged.columns.contains_key("val_r"));
17827        assert_eq!(
17828            merged.columns.get("val").expect("left unsuffixed").values(),
17829            &[Scalar::Int64(10)]
17830        );
17831        assert_eq!(
17832            merged
17833                .columns
17834                .get("val_r")
17835                .expect("right suffixed")
17836                .values(),
17837            &[Scalar::Int64(99)]
17838        );
17839    }
17840
17841    #[test]
17842    fn merge_column_name_conflict_rejects_missing_suffixes_for_overlap() {
17843        let left = DataFrame::from_dict(
17844            &["id", "val"],
17845            vec![
17846                ("id", vec![Scalar::Int64(1)]),
17847                ("val", vec![Scalar::Int64(10)]),
17848            ],
17849        )
17850        .expect("left");
17851        let right = DataFrame::from_dict(
17852            &["id", "val"],
17853            vec![
17854                ("id", vec![Scalar::Int64(1)]),
17855                ("val", vec![Scalar::Int64(99)]),
17856            ],
17857        )
17858        .expect("right");
17859
17860        let err = merge_dataframes_on_with_options(
17861            &left,
17862            &right,
17863            &["id"],
17864            &["id"],
17865            JoinType::Inner,
17866            MergeExecutionOptions {
17867                suffixes: Some([Some(String::new()), Some(String::new())]),
17868                ..MergeExecutionOptions::default()
17869            },
17870        )
17871        .expect_err("merge should reject overlapping columns without suffixes");
17872        assert!(format!("{err}").contains("columns overlap but no suffix specified"));
17873    }
17874
17875    #[test]
17876    fn merge_column_name_conflict_rejects_duplicate_output_columns_from_suffixes() {
17877        let left = DataFrame::from_dict(
17878            &["id", "val", "val_L"],
17879            vec![
17880                ("id", vec![Scalar::Int64(1)]),
17881                ("val", vec![Scalar::Int64(10)]),
17882                ("val_L", vec![Scalar::Int64(77)]),
17883            ],
17884        )
17885        .expect("left");
17886        let right = DataFrame::from_dict(
17887            &["id", "val"],
17888            vec![
17889                ("id", vec![Scalar::Int64(1)]),
17890                ("val", vec![Scalar::Int64(99)]),
17891            ],
17892        )
17893        .expect("right");
17894
17895        let err = merge_dataframes_on_with_options(
17896            &left,
17897            &right,
17898            &["id"],
17899            &["id"],
17900            JoinType::Inner,
17901            MergeExecutionOptions {
17902                suffixes: Some([Some("_L".to_owned()), Some("_R".to_owned())]),
17903                ..MergeExecutionOptions::default()
17904            },
17905        )
17906        .expect_err("merge should reject duplicate output names caused by suffixes");
17907        assert!(format!("{err}").contains("duplicate column"));
17908    }
17909
17910    #[test]
17911    fn merge_missing_key_column_errors() {
17912        let left = make_left_df();
17913        let right = make_right_df();
17914        let err = merge_dataframes(&left, &right, "nonexistent", JoinType::Inner)
17915            .expect_err("should fail");
17916        assert!(format!("{err}").contains("nonexistent"));
17917    }
17918
17919    #[test]
17920    fn merge_duplicate_keys_multiply_cardinality() {
17921        let left = DataFrame::from_dict(
17922            &["id", "a"],
17923            vec![
17924                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
17925                ("a", vec![Scalar::Int64(10), Scalar::Int64(20)]),
17926            ],
17927        )
17928        .unwrap();
17929        let right = DataFrame::from_dict(
17930            &["id", "b"],
17931            vec![
17932                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
17933                ("b", vec![Scalar::Int64(100), Scalar::Int64(200)]),
17934            ],
17935        )
17936        .unwrap();
17937
17938        let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
17939        // 2 left × 2 right = 4 rows
17940        assert_eq!(merged.columns.get("id").unwrap().len(), 4);
17941    }
17942
17943    #[test]
17944    fn ordered_identity_int64_guard_uses_strict_unique_certificate() {
17945        let left = fp_columnar::Column::from_i64_values(vec![1, 2, 3, 4]);
17946        let right = fp_columnar::Column::from_i64_values(vec![1, 2, 3, 4]);
17947        assert!(ordered_identity_int64_keys_match(&left, &right));
17948
17949        let duplicate_left = fp_columnar::Column::from_i64_values(vec![1, 1, 2]);
17950        let duplicate_right = fp_columnar::Column::from_i64_values(vec![1, 1, 2]);
17951        assert!(!ordered_identity_int64_keys_match(
17952            &duplicate_left,
17953            &duplicate_right
17954        ));
17955
17956        let unsorted_left = fp_columnar::Column::from_i64_values(vec![2, 1, 3]);
17957        let unsorted_right = fp_columnar::Column::from_i64_values(vec![2, 1, 3]);
17958        assert!(ordered_identity_int64_keys_match(
17959            &unsorted_left,
17960            &unsorted_right
17961        ));
17962    }
17963
17964    #[test]
17965    fn affine_i64_inner_plan_solves_nontrivial_stride_intersection() {
17966        let left = super::PositiveAffineI64Witness {
17967            start: -3,
17968            step: 4,
17969            len: 8,
17970        };
17971        let right = super::PositiveAffineI64Witness {
17972            start: 1,
17973            step: 6,
17974            len: 6,
17975        };
17976        assert_eq!(
17977            super::affine_i64_inner_position_plan(left, right),
17978            Some(super::AffineInnerPositionPlan {
17979                left_start: 1,
17980                left_step: 3,
17981                right_start: 0,
17982                right_step: 2,
17983                len: 3,
17984            })
17985        );
17986    }
17987
17988    #[test]
17989    fn affine_i64_inner_plan_matches_brute_force_small_domain() {
17990        const LENGTHS: [usize; 4] = [2, 3, 7, 11];
17991        for left_start in -8i128..=8 {
17992            for right_start in -8i128..=8 {
17993                for left_step in 1i128..=7 {
17994                    for right_step in 1i128..=7 {
17995                        for left_len in LENGTHS {
17996                            for right_len in LENGTHS {
17997                                let left = super::PositiveAffineI64Witness {
17998                                    start: left_start,
17999                                    step: left_step,
18000                                    len: left_len,
18001                                };
18002                                let right = super::PositiveAffineI64Witness {
18003                                    start: right_start,
18004                                    step: right_step,
18005                                    len: right_len,
18006                                };
18007                                let plan = super::affine_i64_inner_position_plan(left, right)
18008                                    .expect("small affine sequences cannot overflow");
18009                                let expected = (0..left_len)
18010                                    .flat_map(|left_row| {
18011                                        (0..right_len).filter_map(move |right_row| {
18012                                            let left_key = left_start
18013                                                + left_step * i128::try_from(left_row).unwrap();
18014                                            let right_key = right_start
18015                                                + right_step * i128::try_from(right_row).unwrap();
18016                                            (left_key == right_key).then_some((left_row, right_row))
18017                                        })
18018                                    })
18019                                    .collect::<Vec<_>>();
18020                                let actual = (0..plan.len)
18021                                    .map(|row| {
18022                                        (
18023                                            plan.left_start + row * plan.left_step,
18024                                            plan.right_start + row * plan.right_step,
18025                                        )
18026                                    })
18027                                    .collect::<Vec<_>>();
18028                                assert_eq!(actual, expected);
18029                            }
18030                        }
18031                    }
18032                }
18033            }
18034        }
18035    }
18036
18037    #[test]
18038    fn affine_i64_inner_merge_matches_left_major_values() {
18039        let left_keys = vec![-3, 1, 5, 9, 13, 17, 21, 25];
18040        let right_keys = vec![1, 7, 13, 19, 25, 31];
18041        let mut left_columns = std::collections::BTreeMap::new();
18042        left_columns.insert("id".to_owned(), Column::from_i64_values(left_keys));
18043        left_columns.insert(
18044            "left_value".to_owned(),
18045            Column::from_f64_values((0..8).map(|row| row as f64 + 0.5).collect()),
18046        );
18047        let left = DataFrame::new_with_column_order(
18048            Index::new_known_unique_int64_unit_range(0, 8),
18049            left_columns,
18050            vec!["id".to_owned(), "left_value".to_owned()],
18051        )
18052        .unwrap();
18053        let mut right_columns = std::collections::BTreeMap::new();
18054        right_columns.insert("id".to_owned(), Column::from_i64_values(right_keys));
18055        right_columns.insert(
18056            "right_value".to_owned(),
18057            Column::from_i64_values((100..106).collect()),
18058        );
18059        let right = DataFrame::new_with_column_order(
18060            Index::new_known_unique_int64_unit_range(0, 6),
18061            right_columns,
18062            vec!["id".to_owned(), "right_value".to_owned()],
18063        )
18064        .unwrap();
18065        let suffixes = resolve_merge_suffixes(None);
18066        let merged = super::build_single_key_affine_i64_inner_merge_output(
18067            &left,
18068            &right,
18069            &["id"],
18070            &["id"],
18071            left.columns().get("id").unwrap(),
18072            right.columns().get("id").unwrap(),
18073            &suffixes,
18074        )
18075        .unwrap()
18076        .expect("certified affine typed inputs must use the fast path");
18077
18078        assert_eq!(
18079            merged.columns.get("id").unwrap().values(),
18080            &[Scalar::Int64(1), Scalar::Int64(13), Scalar::Int64(25)]
18081        );
18082        assert_eq!(
18083            merged.columns.get("left_value").unwrap().values(),
18084            &[
18085                Scalar::Float64(1.5),
18086                Scalar::Float64(4.5),
18087                Scalar::Float64(7.5),
18088            ]
18089        );
18090        assert_eq!(
18091            merged.columns.get("right_value").unwrap().values(),
18092            &[Scalar::Int64(100), Scalar::Int64(102), Scalar::Int64(104)]
18093        );
18094    }
18095
18096    #[test]
18097    fn merge_identical_duplicate_keys_cross_join_values_jdupk() {
18098        // Identical left/right key columns that contain duplicates must NOT take
18099        // the identity 1:1 fast path: pandas cross-joins each duplicate, so a=10
18100        // and a=20 each pair with b=100 and b=200. (br-frankenpandas-jdupk)
18101        let left = DataFrame::from_dict(
18102            &["id", "a"],
18103            vec![
18104                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
18105                ("a", vec![Scalar::Int64(10), Scalar::Int64(20)]),
18106            ],
18107        )
18108        .unwrap();
18109        let right = DataFrame::from_dict(
18110            &["id", "b"],
18111            vec![
18112                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
18113                ("b", vec![Scalar::Int64(100), Scalar::Int64(200)]),
18114            ],
18115        )
18116        .unwrap();
18117
18118        let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
18119        assert_eq!(
18120            merged.columns.get("a").unwrap().values(),
18121            &[
18122                Scalar::Int64(10),
18123                Scalar::Int64(10),
18124                Scalar::Int64(20),
18125                Scalar::Int64(20)
18126            ]
18127        );
18128        assert_eq!(
18129            merged.columns.get("b").unwrap().values(),
18130            &[
18131                Scalar::Int64(100),
18132                Scalar::Int64(200),
18133                Scalar::Int64(100),
18134                Scalar::Int64(200)
18135            ]
18136        );
18137    }
18138
18139    #[test]
18140    fn ordered_unique_utf8_inner_positions_match_left_major_hash_order_53lat() {
18141        let left = contiguous_utf8_column(&["a", "b", "d", "f"]);
18142        let right = contiguous_utf8_column(&["b", "c", "f"]);
18143        let (left_positions, right_positions) =
18144            ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
18145
18146        assert_eq!(left_positions, vec![1, 3]);
18147        assert_eq!(right_positions, vec![0, 2]);
18148
18149        let merged = merge_dataframes(
18150            &utf8_key_merge_frame(&["a", "b", "d", "f"], "lv", 10),
18151            &utf8_key_merge_frame(&["b", "c", "f"], "rv", 20),
18152            "id",
18153            JoinType::Inner,
18154        )
18155        .unwrap();
18156        assert_eq!(
18157            merged.columns.get("lv").unwrap().values(),
18158            &[Scalar::Int64(11), Scalar::Int64(13)]
18159        );
18160        assert_eq!(
18161            merged.columns.get("rv").unwrap().values(),
18162            &[Scalar::Int64(20), Scalar::Int64(22)]
18163        );
18164    }
18165
18166    #[test]
18167    fn sorted_contiguous_utf8_inner_positions_preserves_duplicate_order_codb() {
18168        let left = contiguous_utf8_column(&["a", "a", "b", "d"]);
18169        let right = contiguous_utf8_column(&["a", "a", "c", "d"]);
18170        let (left_bytes, left_offsets) = left.as_utf8_contiguous().expect("left contiguous");
18171        let (right_bytes, right_offsets) = right.as_utf8_contiguous().expect("right contiguous");
18172
18173        let (left_positions, right_positions) = sorted_contiguous_utf8_inner_positions(
18174            left_bytes,
18175            left_offsets,
18176            right_bytes,
18177            right_offsets,
18178        )
18179        .expect("sorted spans should use two-pointer merge");
18180
18181        assert_eq!(left_positions, vec![0, 0, 1, 1, 3]);
18182        assert_eq!(right_positions, vec![0, 1, 0, 1, 3]);
18183    }
18184
18185    #[test]
18186    fn sorted_contiguous_utf8_inner_positions_rejects_unsorted_input_codb() {
18187        let left = contiguous_utf8_column(&["b", "a"]);
18188        let right = contiguous_utf8_column(&["a", "b"]);
18189        let (left_bytes, left_offsets) = left.as_utf8_contiguous().expect("left contiguous");
18190        let (right_bytes, right_offsets) = right.as_utf8_contiguous().expect("right contiguous");
18191
18192        assert!(
18193            sorted_contiguous_utf8_inner_positions(
18194                left_bytes,
18195                left_offsets,
18196                right_bytes,
18197                right_offsets,
18198            )
18199            .is_none()
18200        );
18201    }
18202
18203    #[test]
18204    fn ordered_unique_utf8_seek_bound_preserves_late_overlap_lr52z() {
18205        let left = contiguous_utf8_column(&["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]);
18206        let right = contiguous_utf8_column(&["h", "i", "j", "k"]);
18207        let (left_bytes, left_offsets) =
18208            strictly_increasing_utf8_key_spans(&left).expect("sorted left");
18209
18210        assert_eq!(utf8_span_lower_bound(left_bytes, left_offsets, b"h"), 7);
18211
18212        let (left_positions, right_positions) =
18213            ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
18214        assert_eq!(left_positions, vec![7, 8, 9]);
18215        assert_eq!(right_positions, vec![0, 1, 2]);
18216
18217        let disjoint_left = contiguous_utf8_column(&["a", "b"]);
18218        let disjoint_right = contiguous_utf8_column(&["c", "d"]);
18219        let (left_positions, right_positions) =
18220            ordered_unique_utf8_inner_positions(&disjoint_left, &disjoint_right)
18221                .expect("ordered disjoint utf8 positions");
18222        assert!(left_positions.is_empty());
18223        assert!(right_positions.is_empty());
18224    }
18225
18226    #[test]
18227    fn ordered_unique_utf8_bulk_fixed_width_window_jbyuc11() {
18228        let left = contiguous_utf8_column(&["k000", "k001", "k002", "k003", "k004"]);
18229        let right = contiguous_utf8_column(&["k002", "k003", "k004", "k005"]);
18230
18231        let (left_positions, right_positions) =
18232            ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
18233        assert_eq!(left_positions, vec![2, 3, 4]);
18234        assert_eq!(right_positions, vec![0, 1, 2]);
18235    }
18236
18237    #[test]
18238    fn ordered_unique_utf8_bulk_window_returns_range_plan_jbyuc11111() {
18239        let left = contiguous_utf8_column(&["k000", "k001", "k002", "k003", "k004"]);
18240        let right = contiguous_utf8_column(&["k002", "k003", "k004", "k005"]);
18241
18242        let plan =
18243            ordered_unique_utf8_inner_position_plan(&left, &right).expect("ordered utf8 plan");
18244
18245        assert_eq!(
18246            plan,
18247            InnerPositionPlan::ContiguousRanges {
18248                left_start: 2,
18249                right_start: 0,
18250                len: 3
18251            }
18252        );
18253    }
18254
18255    #[test]
18256    fn ordered_unique_utf8_lower_hex_certificate_returns_range_plan_jbyuc111111() {
18257        let left =
18258            contiguous_utf8_column(&["id_0000000a", "id_0000000b", "id_0000000c", "id_0000000d"]);
18259        let right = contiguous_utf8_column(&["id_0000000c", "id_0000000d", "id_0000000e"]);
18260        let (_, _, left_cert) = left
18261            .as_lower_hex_sequence_utf8_contiguous()
18262            .expect("left sequence certificate");
18263        let (_, _, right_cert) = right
18264            .as_lower_hex_sequence_utf8_contiguous()
18265            .expect("right sequence certificate");
18266
18267        assert_eq!(
18268            ordered_utf8_lower_hex_overlap_len(left_cert, right_cert, 2, 4, 0, 3),
18269            Some(2)
18270        );
18271        assert_eq!(
18272            lower_hex_overlap_plan_from_certificates(&left, &right),
18273            Some(InnerPositionPlan::ContiguousRanges {
18274                left_start: 2,
18275                right_start: 0,
18276                len: 2
18277            })
18278        );
18279        let plan =
18280            ordered_unique_utf8_inner_position_plan(&left, &right).expect("ordered utf8 plan");
18281        assert_eq!(
18282            plan,
18283            InnerPositionPlan::ContiguousRanges {
18284                left_start: 2,
18285                right_start: 0,
18286                len: 2
18287            }
18288        );
18289    }
18290
18291    #[test]
18292    fn ordered_unique_utf8_lower_hex_arithmetic_empty_overlap_jbyuc1111111111() {
18293        let left = contiguous_utf8_column(&["id_00000001", "id_00000002", "id_00000003"]);
18294        let right = contiguous_utf8_column(&["id_00000008", "id_00000009"]);
18295
18296        assert_eq!(
18297            lower_hex_overlap_plan_from_certificates(&left, &right),
18298            Some(InnerPositionPlan::Gather {
18299                left_positions: Vec::new(),
18300                right_positions: Vec::new(),
18301            })
18302        );
18303        let (left_positions, right_positions) =
18304            ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
18305        assert!(left_positions.is_empty());
18306        assert!(right_positions.is_empty());
18307    }
18308
18309    #[test]
18310    fn ordered_unique_utf8_lower_hex_prefix_mismatch_falls_back_jbyuc1111111111() {
18311        let left = contiguous_utf8_column(&["aa_00000001", "aa_00000002", "aa_00000003"]);
18312        let right = contiguous_utf8_column(&["bb_00000001", "bb_00000002", "bb_00000003"]);
18313
18314        assert!(
18315            lower_hex_overlap_plan_from_certificates(&left, &right).is_none(),
18316            "matching lower-hex counters with different prefixes must not use arithmetic overlap"
18317        );
18318        let (left_positions, right_positions) =
18319            ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
18320        assert!(left_positions.is_empty());
18321        assert!(right_positions.is_empty());
18322    }
18323
18324    #[test]
18325    fn ordered_utf8_contiguous_no_overlap_output_fast_path_jbyuc111111111() -> Result<(), String> {
18326        let left = utf8_key_merge_frame(
18327            &["id_00000000", "id_00000001", "id_00000002", "id_00000003"],
18328            "lv",
18329            10,
18330        );
18331        let right = utf8_key_merge_frame(&["id_00000002", "id_00000003", "id_00000004"], "rv", 100);
18332        let plan = ordered_unique_utf8_inner_position_plan(
18333            left.columns()
18334                .get("id")
18335                .ok_or_else(|| "left key column missing".to_owned())?,
18336            right
18337                .columns()
18338                .get("id")
18339                .ok_or_else(|| "right key column missing".to_owned())?,
18340        )
18341        .ok_or_else(|| "ordered utf8 plan unavailable".to_owned())?;
18342        let InnerPositionPlan::ContiguousRanges {
18343            left_start,
18344            right_start,
18345            len,
18346        } = plan
18347        else {
18348            return Err("expected contiguous range plan".to_owned());
18349        };
18350
18351        let merged = build_single_key_inner_contiguous_no_overlap_output(
18352            &left,
18353            &right,
18354            &["id"],
18355            &["id"],
18356            PositionSelection::ContiguousRange {
18357                start: left_start,
18358                len,
18359            },
18360            PositionSelection::ContiguousRange {
18361                start: right_start,
18362                len,
18363            },
18364        )
18365        .ok_or_else(|| "no-overlap contiguous output fast path missed".to_owned())?;
18366
18367        assert_eq!(merged.column_order, ["id", "lv", "rv"]);
18368        let id_output = merged
18369            .columns
18370            .get("id")
18371            .ok_or_else(|| "id output missing".to_owned())?;
18372        let (prefix, certificate, certificate_len) = id_output
18373            .as_lower_hex_sequence_utf8()
18374            .ok_or_else(|| "id output lost lower-hex sequence witness".to_owned())?;
18375        assert_eq!(prefix, b"id_");
18376        assert_eq!(certificate.start(), 2);
18377        assert_eq!(certificate.hex_width(), 8);
18378        assert_eq!(certificate_len, 2);
18379        assert_eq!(
18380            id_output.values(),
18381            &[
18382                Scalar::Utf8("id_00000002".to_owned()),
18383                Scalar::Utf8("id_00000003".to_owned())
18384            ]
18385        );
18386        assert_eq!(
18387            merged
18388                .columns
18389                .get("lv")
18390                .ok_or_else(|| "lv output missing".to_owned())?
18391                .values(),
18392            &[Scalar::Int64(12), Scalar::Int64(13)]
18393        );
18394        assert_eq!(
18395            merged
18396                .columns
18397                .get("rv")
18398                .ok_or_else(|| "rv output missing".to_owned())?
18399                .values(),
18400            &[Scalar::Int64(100), Scalar::Int64(101)]
18401        );
18402
18403        let overlapping_right =
18404            utf8_key_merge_frame(&["id_00000002", "id_00000003", "id_00000004"], "lv", 100);
18405        assert!(
18406            build_single_key_inner_contiguous_no_overlap_output(
18407                &left,
18408                &overlapping_right,
18409                &["id"],
18410                &["id"],
18411                PositionSelection::ContiguousRange {
18412                    start: left_start,
18413                    len,
18414                },
18415                PositionSelection::ContiguousRange {
18416                    start: right_start,
18417                    len,
18418                },
18419            )
18420            .is_none(),
18421            "overlapping non-key columns must keep the suffix/error generic path"
18422        );
18423        Ok(())
18424    }
18425
18426    #[test]
18427    fn ordered_unique_utf8_uncertified_fixed_width_still_matches_jbyuc111111() {
18428        let left = contiguous_utf8_column(&["k00A", "k00B", "k00C", "k00D"]);
18429        let right = contiguous_utf8_column(&["k00B", "k00D"]);
18430
18431        assert!(left.as_lower_hex_sequence_utf8_contiguous().is_none());
18432        assert!(right.as_lower_hex_sequence_utf8_contiguous().is_none());
18433        let (left_positions, right_positions) =
18434            ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
18435        assert_eq!(left_positions, vec![1, 3]);
18436        assert_eq!(right_positions, vec![0, 1]);
18437    }
18438
18439    #[test]
18440    fn ordered_unique_utf8_fixed_width_gap_falls_back_jbyuc11() {
18441        let left = contiguous_utf8_column(&["k000", "k001", "k003", "k004"]);
18442        let right = contiguous_utf8_column(&["k001", "k002", "k004"]);
18443
18444        let (left_positions, right_positions) =
18445            ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
18446        assert_eq!(left_positions, vec![1, 3]);
18447        assert_eq!(right_positions, vec![0, 2]);
18448    }
18449
18450    #[test]
18451    fn ordered_unique_utf8_rejects_unsorted_or_duplicate_keys_53lat() {
18452        let unsorted_left = contiguous_utf8_column(&["b", "a", "b"]);
18453        let duplicate_right = contiguous_utf8_column(&["b", "b", "a"]);
18454        assert!(ordered_unique_utf8_inner_positions(&unsorted_left, &duplicate_right).is_none());
18455
18456        let left = utf8_key_merge_frame(&["b", "a", "b"], "lv", 10);
18457        let right = utf8_key_merge_frame(&["b", "b", "a"], "rv", 20);
18458        let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
18459
18460        assert_eq!(
18461            merged.columns.get("lv").unwrap().values(),
18462            &[
18463                Scalar::Int64(10),
18464                Scalar::Int64(10),
18465                Scalar::Int64(11),
18466                Scalar::Int64(12),
18467                Scalar::Int64(12)
18468            ]
18469        );
18470        assert_eq!(
18471            merged.columns.get("rv").unwrap().values(),
18472            &[
18473                Scalar::Int64(20),
18474                Scalar::Int64(21),
18475                Scalar::Int64(22),
18476                Scalar::Int64(20),
18477                Scalar::Int64(21)
18478            ]
18479        );
18480    }
18481
18482    #[test]
18483    fn merge_inner_int64_fast_paths_match_naive_reference_fuzz_jdupk() {
18484        // Differential guard: merge_dataframes dispatches int64 single-key inner
18485        // merges to ordered/identity/dense fast paths. Each MUST equal a naive
18486        // left-major nested-loop join for arbitrary int64 keys (sorted/unsorted,
18487        // unique/duplicate, overlapping/disjoint, negative). This is the
18488        // isomorphism proof those perf paths owe; it caught the identity-path
18489        // row-loss bug. (br-frankenpandas-rw0r5)
18490        let mut state: u64 = 0x9E37_79B9_7F4A_7C15;
18491        let mut next = || {
18492            state = state
18493                .wrapping_mul(6_364_136_223_846_793_005)
18494                .wrapping_add(1_442_695_040_888_963_407);
18495            state >> 33
18496        };
18497        for _ in 0..400 {
18498            let nl = (next() % 6 + 1) as usize;
18499            let nr = (next() % 6 + 1) as usize;
18500            // small key range forces collisions; offset gives negatives too
18501            let lk: Vec<i64> = (0..nl).map(|_| (next() % 5) as i64 - 2).collect();
18502            let rk: Vec<i64> = (0..nr).map(|_| (next() % 5) as i64 - 2).collect();
18503
18504            let left = DataFrame::from_dict(
18505                &["id", "a"],
18506                vec![
18507                    ("id", lk.iter().map(|&k| Scalar::Int64(k)).collect()),
18508                    (
18509                        "a",
18510                        (0..nl).map(|i| Scalar::Int64(i as i64 + 1000)).collect(),
18511                    ),
18512                ],
18513            )
18514            .unwrap();
18515            let right = DataFrame::from_dict(
18516                &["id", "b"],
18517                vec![
18518                    ("id", rk.iter().map(|&k| Scalar::Int64(k)).collect()),
18519                    (
18520                        "b",
18521                        (0..nr).map(|j| Scalar::Int64(j as i64 + 2000)).collect(),
18522                    ),
18523                ],
18524            )
18525            .unwrap();
18526
18527            let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
18528
18529            // Naive reference: pandas inner merge is left-major, right-minor.
18530            let mut exp_a = Vec::new();
18531            let mut exp_b = Vec::new();
18532            for (i, &left_value) in lk.iter().enumerate() {
18533                for (j, &right_value) in rk.iter().enumerate() {
18534                    if left_value == right_value {
18535                        exp_a.push(Scalar::Int64(i as i64 + 1000));
18536                        exp_b.push(Scalar::Int64(j as i64 + 2000));
18537                    }
18538                }
18539            }
18540            assert_eq!(
18541                merged.columns.get("a").unwrap().values(),
18542                exp_a.as_slice(),
18543                "left payload mismatch for lk={lk:?} rk={rk:?}"
18544            );
18545            assert_eq!(
18546                merged.columns.get("b").unwrap().values(),
18547                exp_b.as_slice(),
18548                "right payload mismatch for lk={lk:?} rk={rk:?}"
18549            );
18550
18551            // Cardinality guard for left/right/outer (dtype/order independent —
18552            // catches the row-loss class regardless of int->float promotion).
18553            let inner_pairs = exp_a.len();
18554            let left_only = lk.iter().filter(|&key| !rk.contains(key)).count();
18555            let right_only = rk.iter().filter(|&key| !lk.contains(key)).count();
18556            for (how, expected_rows) in [
18557                (JoinType::Left, inner_pairs + left_only),
18558                (JoinType::Right, inner_pairs + right_only),
18559                (JoinType::Outer, inner_pairs + left_only + right_only),
18560            ] {
18561                let m = merge_dataframes(&left, &right, "id", how).unwrap();
18562                assert_eq!(
18563                    m.columns.get("id").unwrap().len(),
18564                    expected_rows,
18565                    "{how:?} cardinality mismatch for lk={lk:?} rk={rk:?}"
18566                );
18567            }
18568        }
18569    }
18570
18571    #[test]
18572    fn merge_null_nan_keys_metamorphic_unmatched_rows_do_not_disturb_inner_tn6qb8()
18573    -> Result<(), JoinError> {
18574        let left = DataFrame::from_dict(
18575            &["id", "left_v"],
18576            vec![
18577                (
18578                    "id",
18579                    vec![
18580                        Scalar::Float64(1.0),
18581                        Scalar::Null(NullKind::NaN),
18582                        Scalar::Null(NullKind::Null),
18583                        Scalar::Float64(2.0),
18584                    ],
18585                ),
18586                (
18587                    "left_v",
18588                    vec![
18589                        Scalar::Int64(10),
18590                        Scalar::Int64(20),
18591                        Scalar::Int64(21),
18592                        Scalar::Int64(30),
18593                    ],
18594                ),
18595            ],
18596        )?;
18597        let right = DataFrame::from_dict(
18598            &["id", "right_v"],
18599            vec![
18600                (
18601                    "id",
18602                    vec![
18603                        Scalar::Null(NullKind::Null),
18604                        Scalar::Float64(2.0),
18605                        Scalar::Float64(f64::NAN),
18606                    ],
18607                ),
18608                (
18609                    "right_v",
18610                    vec![Scalar::Int64(200), Scalar::Int64(300), Scalar::Int64(201)],
18611                ),
18612            ],
18613        )?;
18614
18615        let baseline = merge_dataframes(&left, &right, "id", JoinType::Inner)?;
18616
18617        let left_with_unmatched = DataFrame::from_dict(
18618            &["id", "left_v"],
18619            vec![
18620                (
18621                    "id",
18622                    vec![
18623                        Scalar::Float64(1.0),
18624                        Scalar::Null(NullKind::NaN),
18625                        Scalar::Null(NullKind::Null),
18626                        Scalar::Float64(2.0),
18627                        Scalar::Float64(99.0),
18628                    ],
18629                ),
18630                (
18631                    "left_v",
18632                    vec![
18633                        Scalar::Int64(10),
18634                        Scalar::Int64(20),
18635                        Scalar::Int64(21),
18636                        Scalar::Int64(30),
18637                        Scalar::Int64(990),
18638                    ],
18639                ),
18640            ],
18641        )?;
18642        let right_with_unmatched = DataFrame::from_dict(
18643            &["id", "right_v"],
18644            vec![
18645                (
18646                    "id",
18647                    vec![
18648                        Scalar::Null(NullKind::Null),
18649                        Scalar::Float64(2.0),
18650                        Scalar::Float64(f64::NAN),
18651                        Scalar::Float64(100.0),
18652                    ],
18653                ),
18654                (
18655                    "right_v",
18656                    vec![
18657                        Scalar::Int64(200),
18658                        Scalar::Int64(300),
18659                        Scalar::Int64(201),
18660                        Scalar::Int64(1000),
18661                    ],
18662                ),
18663            ],
18664        )?;
18665
18666        let transformed = merge_dataframes(
18667            &left_with_unmatched,
18668            &right_with_unmatched,
18669            "id",
18670            JoinType::Inner,
18671        )?;
18672
18673        assert_eq!(
18674            merged_values(&baseline, "left_v")?,
18675            merged_values(&transformed, "left_v")?
18676        );
18677        assert_eq!(
18678            merged_values(&baseline, "right_v")?,
18679            merged_values(&transformed, "right_v")?
18680        );
18681        assert_eq!(
18682            merged_values(&baseline, "left_v")?,
18683            &[
18684                Scalar::Int64(20),
18685                Scalar::Int64(20),
18686                Scalar::Int64(21),
18687                Scalar::Int64(21),
18688                Scalar::Int64(30),
18689            ]
18690        );
18691        assert_eq!(
18692            merged_values(&baseline, "right_v")?,
18693            &[
18694                Scalar::Int64(200),
18695                Scalar::Int64(201),
18696                Scalar::Int64(200),
18697                Scalar::Int64(201),
18698                Scalar::Int64(300),
18699            ]
18700        );
18701
18702        Ok(())
18703    }
18704
18705    #[test]
18706    fn merge_mixed_dtype_missing_keys_metamorphic_outer_both_equals_inner_tn6qb8()
18707    -> Result<(), JoinError> {
18708        let left = DataFrame::from_dict(
18709            &["id", "left_v"],
18710            vec![
18711                (
18712                    "id",
18713                    vec![
18714                        Scalar::Int64(1),
18715                        Scalar::Int64(2),
18716                        Scalar::Null(NullKind::NaN),
18717                        Scalar::Int64(3),
18718                    ],
18719                ),
18720                (
18721                    "left_v",
18722                    vec![
18723                        Scalar::Float64(10.0),
18724                        Scalar::Float64(20.0),
18725                        Scalar::Float64(30.0),
18726                        Scalar::Float64(40.0),
18727                    ],
18728                ),
18729            ],
18730        )?;
18731        let right = DataFrame::from_dict(
18732            &["id", "right_v"],
18733            vec![
18734                (
18735                    "id",
18736                    vec![
18737                        Scalar::Float64(1.0),
18738                        Scalar::Float64(2.5),
18739                        Scalar::Null(NullKind::Null),
18740                        Scalar::Float64(3.0),
18741                    ],
18742                ),
18743                (
18744                    "right_v",
18745                    vec![
18746                        Scalar::Float64(100.0),
18747                        Scalar::Float64(250.0),
18748                        Scalar::Float64(300.0),
18749                        Scalar::Float64(400.0),
18750                    ],
18751                ),
18752            ],
18753        )?;
18754        let options = MergeExecutionOptions {
18755            indicator_name: Some("_merge".to_owned()),
18756            sort: true,
18757            ..MergeExecutionOptions::default()
18758        };
18759
18760        let inner = merge_dataframes_on_with_options(
18761            &left,
18762            &right,
18763            &["id"],
18764            &["id"],
18765            JoinType::Inner,
18766            options.clone(),
18767        )?;
18768        let outer = merge_dataframes_on_with_options(
18769            &left,
18770            &right,
18771            &["id"],
18772            &["id"],
18773            JoinType::Outer,
18774            options,
18775        )?;
18776
18777        assert_eq!(
18778            merged_values(&inner, "left_v")?,
18779            merged_values_where_indicator(&outer, "left_v", "_merge", "both")?
18780        );
18781        assert_eq!(
18782            merged_values(&inner, "right_v")?,
18783            merged_values_where_indicator(&outer, "right_v", "_merge", "both")?
18784        );
18785        assert_eq!(
18786            merged_values(&inner, "left_v")?,
18787            &[
18788                Scalar::Float64(10.0),
18789                Scalar::Float64(40.0),
18790                Scalar::Float64(30.0)
18791            ]
18792        );
18793        assert_eq!(
18794            merged_values(&inner, "right_v")?,
18795            &[
18796                Scalar::Float64(100.0),
18797                Scalar::Float64(400.0),
18798                Scalar::Float64(300.0)
18799            ]
18800        );
18801        assert_eq!(
18802            merged_values(&outer, "_merge")?,
18803            &[
18804                Scalar::Utf8("both".to_owned()),
18805                Scalar::Utf8("left_only".to_owned()),
18806                Scalar::Utf8("right_only".to_owned()),
18807                Scalar::Utf8("both".to_owned()),
18808                Scalar::Utf8("both".to_owned()),
18809            ]
18810        );
18811
18812        Ok(())
18813    }
18814
18815    #[test]
18816    fn merge_cross_cartesian_product() {
18817        let left = make_left_df();
18818        let right = make_right_df();
18819
18820        let merged = merge_dataframes(&left, &right, "unused_key", JoinType::Cross).unwrap();
18821
18822        assert_eq!(merged.columns.get("id_x").unwrap().len(), 9);
18823        assert_eq!(
18824            &merged.columns.get("id_x").unwrap().values()[0..3],
18825            &[Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(1)]
18826        );
18827        assert_eq!(
18828            &merged.columns.get("id_y").unwrap().values()[0..3],
18829            &[Scalar::Int64(2), Scalar::Int64(3), Scalar::Int64(4)]
18830        );
18831        assert_eq!(
18832            &merged.columns.get("val_a").unwrap().values()[0..3],
18833            &[Scalar::Int64(10), Scalar::Int64(10), Scalar::Int64(10)]
18834        );
18835        assert_eq!(
18836            &merged.columns.get("val_b").unwrap().values()[0..3],
18837            &[Scalar::Int64(200), Scalar::Int64(300), Scalar::Int64(400)]
18838        );
18839    }
18840
18841    #[test]
18842    fn merge_cross_does_not_require_on_column() {
18843        let left = make_left_df();
18844        let right = make_right_df();
18845
18846        let merged =
18847            merge_dataframes(&left, &right, "definitely_missing", JoinType::Cross).unwrap();
18848        assert_eq!(merged.columns.get("id_x").unwrap().len(), 9);
18849    }
18850
18851    #[test]
18852    fn merge_cross_with_empty_side_yields_empty_rows() {
18853        let left = DataFrame::from_dict(
18854            &["l"],
18855            vec![("l", vec![Scalar::Int64(1), Scalar::Int64(2)])],
18856        )
18857        .unwrap();
18858        let right = DataFrame::from_dict(&["r"], vec![("r", vec![])]).unwrap();
18859
18860        let merged = merge_dataframes(&left, &right, "ignored", JoinType::Cross).unwrap();
18861        assert_eq!(merged.index.labels().len(), 0);
18862        assert!(merged.columns.get("l").unwrap().values().is_empty());
18863        assert!(merged.columns.get("r").unwrap().values().is_empty());
18864    }
18865
18866    /// A cross merge keeps each side's own column order, as pandas (the
18867    /// columns came back sorted by name; buwrx).
18868    #[test]
18869    fn merge_cross_keeps_each_sides_column_order_buwrx() {
18870        let ints = |values: [i64; 2]| values.map(Scalar::Int64).to_vec();
18871        let left = DataFrame::from_dict(
18872            &["z", "k", "a"],
18873            vec![
18874                ("z", ints([1, 2])),
18875                ("k", ints([3, 4])),
18876                ("a", ints([5, 6])),
18877            ],
18878        )
18879        .unwrap();
18880        let right = DataFrame::from_dict(
18881            &["k", "w", "b"],
18882            vec![
18883                ("k", ints([7, 8])),
18884                ("w", ints([9, 10])),
18885                ("b", ints([11, 12])),
18886            ],
18887        )
18888        .unwrap();
18889        let merged = merge_dataframes(&left, &right, "ignored", JoinType::Cross).unwrap();
18890        assert_eq!(merged.column_order, ["z", "k_x", "a", "k_y", "w", "b"]);
18891        assert_eq!(
18892            merged.columns.get("w").unwrap().values(),
18893            [9, 10, 9, 10].map(Scalar::Int64)
18894        );
18895        // NEGATIVE: the rows are still left-major.
18896        assert_eq!(
18897            merged.columns.get("z").unwrap().values(),
18898            [1, 1, 2, 2].map(Scalar::Int64)
18899        );
18900    }
18901
18902    #[test]
18903    fn merge_composite_inner_multiplies_cardinality_for_duplicates() {
18904        let left = DataFrame::from_dict(
18905            &["k1", "k2", "left_v"],
18906            vec![
18907                (
18908                    "k1",
18909                    vec![Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(1)],
18910                ),
18911                (
18912                    "k2",
18913                    vec![
18914                        Scalar::Utf8("a".to_owned()),
18915                        Scalar::Utf8("a".to_owned()),
18916                        Scalar::Utf8("b".to_owned()),
18917                    ],
18918                ),
18919                (
18920                    "left_v",
18921                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
18922                ),
18923            ],
18924        )
18925        .unwrap();
18926        let right = DataFrame::from_dict(
18927            &["k1", "k2", "right_v"],
18928            vec![
18929                (
18930                    "k1",
18931                    vec![Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(1)],
18932                ),
18933                (
18934                    "k2",
18935                    vec![
18936                        Scalar::Utf8("a".to_owned()),
18937                        Scalar::Utf8("a".to_owned()),
18938                        Scalar::Utf8("c".to_owned()),
18939                    ],
18940                ),
18941                (
18942                    "right_v",
18943                    vec![Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(300)],
18944                ),
18945            ],
18946        )
18947        .unwrap();
18948
18949        let merged = merge_dataframes_on(&left, &right, &["k1", "k2"], JoinType::Inner).unwrap();
18950        assert_eq!(merged.columns.get("k1").unwrap().len(), 4);
18951        assert_eq!(
18952            merged.columns.get("k1").unwrap().values(),
18953            &[
18954                Scalar::Int64(1),
18955                Scalar::Int64(1),
18956                Scalar::Int64(1),
18957                Scalar::Int64(1)
18958            ]
18959        );
18960        assert_eq!(
18961            merged.columns.get("k2").unwrap().values(),
18962            &[
18963                Scalar::Utf8("a".to_owned()),
18964                Scalar::Utf8("a".to_owned()),
18965                Scalar::Utf8("a".to_owned()),
18966                Scalar::Utf8("a".to_owned())
18967            ]
18968        );
18969        assert_eq!(
18970            merged.columns.get("left_v").unwrap().values(),
18971            &[
18972                Scalar::Int64(10),
18973                Scalar::Int64(10),
18974                Scalar::Int64(20),
18975                Scalar::Int64(20)
18976            ]
18977        );
18978        assert_eq!(
18979            merged.columns.get("right_v").unwrap().values(),
18980            &[
18981                Scalar::Int64(100),
18982                Scalar::Int64(200),
18983                Scalar::Int64(100),
18984                Scalar::Int64(200)
18985            ]
18986        );
18987    }
18988
18989    #[test]
18990    fn merge_composite_outer_sorts_join_keys_lexicographically() {
18991        let left = DataFrame::from_dict(
18992            &["k1", "k2", "left_v"],
18993            vec![
18994                ("k1", vec![Scalar::Int64(2), Scalar::Int64(1)]),
18995                (
18996                    "k2",
18997                    vec![Scalar::Utf8("y".to_owned()), Scalar::Utf8("x".to_owned())],
18998                ),
18999                ("left_v", vec![Scalar::Int64(20), Scalar::Int64(10)]),
19000            ],
19001        )
19002        .unwrap();
19003        let right = DataFrame::from_dict(
19004            &["k1", "k2", "right_v"],
19005            vec![
19006                ("k1", vec![Scalar::Int64(2), Scalar::Int64(3)]),
19007                (
19008                    "k2",
19009                    vec![Scalar::Utf8("y".to_owned()), Scalar::Utf8("z".to_owned())],
19010                ),
19011                ("right_v", vec![Scalar::Int64(200), Scalar::Int64(300)]),
19012            ],
19013        )
19014        .unwrap();
19015
19016        let merged = merge_dataframes_on(&left, &right, &["k1", "k2"], JoinType::Outer).unwrap();
19017        assert_eq!(
19018            merged.columns.get("k1").unwrap().values(),
19019            &[Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)]
19020        );
19021        assert_eq!(
19022            merged.columns.get("k2").unwrap().values(),
19023            &[
19024                Scalar::Utf8("x".to_owned()),
19025                Scalar::Utf8("y".to_owned()),
19026                Scalar::Utf8("z".to_owned())
19027            ]
19028        );
19029        assert_eq!(
19030            merged.columns.get("left_v").unwrap().values(),
19031            &[
19032                Scalar::Float64(10.0),
19033                Scalar::Float64(20.0),
19034                Scalar::Null(NullKind::NaN)
19035            ]
19036        );
19037        assert_eq!(
19038            merged.columns.get("right_v").unwrap().values(),
19039            &[
19040                Scalar::Null(NullKind::NaN),
19041                Scalar::Float64(200.0),
19042                Scalar::Float64(300.0)
19043            ]
19044        );
19045    }
19046
19047    #[test]
19048    fn merge_composite_outer_contiguous_utf8_key_coalesce_matches_scalar_route_blackthrush() {
19049        let contiguous_frame =
19050            |k1: &[&str], k2: &[&str], value_name: &str, values: &[i64]| -> DataFrame {
19051                let index = Index::new(
19052                    (0..k1.len())
19053                        .map(|row| IndexLabel::Int64(row as i64))
19054                        .collect(),
19055                );
19056                let mut columns = ColumnStore::new();
19057                columns.insert("k1".to_owned(), contiguous_utf8_column(k1));
19058                columns.insert("k2".to_owned(), contiguous_utf8_column(k2));
19059                columns.insert(
19060                    value_name.to_owned(),
19061                    Column::from_i64_values(values.to_vec()),
19062                );
19063                DataFrame::new_with_column_order(
19064                    index,
19065                    columns,
19066                    vec!["k1".to_owned(), "k2".to_owned(), value_name.to_owned()],
19067                )
19068                .expect("contiguous frame")
19069            };
19070        let scalar_frame =
19071            |k1: &[&str], k2: &[&str], value_name: &str, values: &[i64]| -> DataFrame {
19072                DataFrame::from_dict(
19073                    &["k1", "k2", value_name],
19074                    vec![
19075                        (
19076                            "k1",
19077                            k1.iter()
19078                                .map(|value| Scalar::Utf8((*value).to_owned()))
19079                                .collect(),
19080                        ),
19081                        (
19082                            "k2",
19083                            k2.iter()
19084                                .map(|value| Scalar::Utf8((*value).to_owned()))
19085                                .collect(),
19086                        ),
19087                        (
19088                            value_name,
19089                            values.iter().copied().map(Scalar::Int64).collect(),
19090                        ),
19091                    ],
19092                )
19093                .expect("scalar frame")
19094            };
19095
19096        let left_fast =
19097            contiguous_frame(&["b", "a", "c"], &["y", "x", "z"], "left_v", &[20, 10, 30]);
19098        let right_fast = contiguous_frame(&["b", "d"], &["y", "w"], "right_v", &[200, 400]);
19099        let left_scalar = scalar_frame(&["b", "a", "c"], &["y", "x", "z"], "left_v", &[20, 10, 30]);
19100        let right_scalar = scalar_frame(&["b", "d"], &["y", "w"], "right_v", &[200, 400]);
19101
19102        let fast =
19103            merge_dataframes_on(&left_fast, &right_fast, &["k1", "k2"], JoinType::Outer).unwrap();
19104        let scalar =
19105            merge_dataframes_on(&left_scalar, &right_scalar, &["k1", "k2"], JoinType::Outer)
19106                .unwrap();
19107
19108        for name in ["k1", "k2", "left_v", "right_v"] {
19109            assert_eq!(
19110                fast.columns.get(name).unwrap().values(),
19111                scalar.columns.get(name).unwrap().values(),
19112                "column {name}"
19113            );
19114        }
19115        assert!(
19116            fast.columns
19117                .get("k1")
19118                .unwrap()
19119                .as_utf8_contiguous()
19120                .is_some()
19121        );
19122        assert!(
19123            fast.columns
19124                .get("k2")
19125                .unwrap()
19126                .as_utf8_contiguous()
19127                .is_some()
19128        );
19129    }
19130
19131    #[test]
19132    fn merge_composite_inner_matches_missing_key_components() {
19133        let left = DataFrame::from_dict(
19134            &["k1", "k2", "left_v"],
19135            vec![
19136                ("k1", vec![Scalar::Int64(1), Scalar::Int64(1)]),
19137                (
19138                    "k2",
19139                    vec![Scalar::Null(NullKind::Null), Scalar::Utf8("a".to_owned())],
19140                ),
19141                ("left_v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
19142            ],
19143        )
19144        .unwrap();
19145        let right = DataFrame::from_dict(
19146            &["k1", "k2", "right_v"],
19147            vec![
19148                (
19149                    "k1",
19150                    vec![Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(2)],
19151                ),
19152                (
19153                    "k2",
19154                    vec![
19155                        Scalar::Null(NullKind::Null),
19156                        Scalar::Utf8("a".to_owned()),
19157                        Scalar::Null(NullKind::Null),
19158                    ],
19159                ),
19160                (
19161                    "right_v",
19162                    vec![Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(300)],
19163                ),
19164            ],
19165        )
19166        .unwrap();
19167
19168        let merged = merge_dataframes_on(&left, &right, &["k1", "k2"], JoinType::Inner).unwrap();
19169        assert_eq!(
19170            merged.columns.get("k1").unwrap().values(),
19171            &[Scalar::Int64(1), Scalar::Int64(1)]
19172        );
19173        assert_eq!(
19174            merged.columns.get("k2").unwrap().values(),
19175            &[Scalar::Null(NullKind::Null), Scalar::Utf8("a".to_owned())]
19176        );
19177        assert_eq!(
19178            merged.columns.get("left_v").unwrap().values(),
19179            &[Scalar::Int64(10), Scalar::Int64(20)]
19180        );
19181        assert_eq!(
19182            merged.columns.get("right_v").unwrap().values(),
19183            &[Scalar::Int64(100), Scalar::Int64(200)]
19184        );
19185    }
19186
19187    #[test]
19188    fn merge_composite_outer_keeps_right_only_rows_with_missing_keys() {
19189        let left = DataFrame::from_dict(
19190            &["k1", "k2", "left_v"],
19191            vec![
19192                ("k1", vec![Scalar::Int64(1)]),
19193                ("k2", vec![Scalar::Null(NullKind::Null)]),
19194                ("left_v", vec![Scalar::Int64(10)]),
19195            ],
19196        )
19197        .unwrap();
19198        let right = DataFrame::from_dict(
19199            &["k1", "k2", "right_v"],
19200            vec![
19201                ("k1", vec![Scalar::Int64(1), Scalar::Int64(2)]),
19202                (
19203                    "k2",
19204                    vec![Scalar::Null(NullKind::Null), Scalar::Null(NullKind::Null)],
19205                ),
19206                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
19207            ],
19208        )
19209        .unwrap();
19210
19211        let merged = merge_dataframes_on(&left, &right, &["k1", "k2"], JoinType::Outer).unwrap();
19212        assert_eq!(
19213            merged.columns.get("k1").unwrap().values(),
19214            &[Scalar::Int64(1), Scalar::Int64(2)]
19215        );
19216        assert_eq!(
19217            merged.columns.get("k2").unwrap().values(),
19218            &[Scalar::Null(NullKind::Null), Scalar::Null(NullKind::Null)]
19219        );
19220        assert_eq!(
19221            merged.columns.get("left_v").unwrap().values(),
19222            &[Scalar::Float64(10.0), Scalar::Null(NullKind::NaN)]
19223        );
19224        assert_eq!(
19225            merged.columns.get("right_v").unwrap().values(),
19226            &[Scalar::Int64(100), Scalar::Int64(200)]
19227        );
19228    }
19229
19230    #[test]
19231    fn merge_composite_missing_key_column_errors() {
19232        let left = DataFrame::from_dict(
19233            &["k1", "k2", "left_v"],
19234            vec![
19235                ("k1", vec![Scalar::Int64(1)]),
19236                ("k2", vec![Scalar::Utf8("x".to_owned())]),
19237                ("left_v", vec![Scalar::Int64(10)]),
19238            ],
19239        )
19240        .unwrap();
19241        let right = DataFrame::from_dict(
19242            &["k1", "right_v"],
19243            vec![
19244                ("k1", vec![Scalar::Int64(1)]),
19245                ("right_v", vec![Scalar::Int64(100)]),
19246            ],
19247        )
19248        .unwrap();
19249
19250        let err = merge_dataframes_on(&left, &right, &["k1", "k2"], JoinType::Inner)
19251            .expect_err("should fail");
19252        assert!(format!("{err}").contains("right DataFrame missing key column 'k2'"));
19253    }
19254
19255    #[test]
19256    fn merge_composite_key_alias_inner_keeps_both_key_sets() {
19257        let left = DataFrame::from_dict(
19258            &["lk1", "lk2", "left_v"],
19259            vec![
19260                (
19261                    "lk1",
19262                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
19263                ),
19264                (
19265                    "lk2",
19266                    vec![
19267                        Scalar::Utf8("a".to_owned()),
19268                        Scalar::Utf8("b".to_owned()),
19269                        Scalar::Utf8("c".to_owned()),
19270                    ],
19271                ),
19272                (
19273                    "left_v",
19274                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
19275                ),
19276            ],
19277        )
19278        .unwrap();
19279        let right = DataFrame::from_dict(
19280            &["rk1", "rk2", "right_v"],
19281            vec![
19282                (
19283                    "rk1",
19284                    vec![Scalar::Int64(2), Scalar::Int64(3), Scalar::Int64(4)],
19285                ),
19286                (
19287                    "rk2",
19288                    vec![
19289                        Scalar::Utf8("b".to_owned()),
19290                        Scalar::Utf8("c".to_owned()),
19291                        Scalar::Utf8("d".to_owned()),
19292                    ],
19293                ),
19294                (
19295                    "right_v",
19296                    vec![Scalar::Int64(200), Scalar::Int64(300), Scalar::Int64(400)],
19297                ),
19298            ],
19299        )
19300        .unwrap();
19301
19302        let merged = merge_dataframes_on_with(
19303            &left,
19304            &right,
19305            &["lk1", "lk2"],
19306            &["rk1", "rk2"],
19307            JoinType::Inner,
19308        )
19309        .unwrap();
19310        assert_eq!(
19311            merged.columns.get("lk1").unwrap().values(),
19312            &[Scalar::Int64(2), Scalar::Int64(3)]
19313        );
19314        assert_eq!(
19315            merged.columns.get("lk2").unwrap().values(),
19316            &[Scalar::Utf8("b".to_owned()), Scalar::Utf8("c".to_owned())]
19317        );
19318        assert_eq!(
19319            merged.columns.get("left_v").unwrap().values(),
19320            &[Scalar::Int64(20), Scalar::Int64(30)]
19321        );
19322        assert_eq!(
19323            merged.columns.get("rk1").unwrap().values(),
19324            &[Scalar::Int64(2), Scalar::Int64(3)]
19325        );
19326        assert_eq!(
19327            merged.columns.get("rk2").unwrap().values(),
19328            &[Scalar::Utf8("b".to_owned()), Scalar::Utf8("c".to_owned())]
19329        );
19330        assert_eq!(
19331            merged.columns.get("right_v").unwrap().values(),
19332            &[Scalar::Int64(200), Scalar::Int64(300)]
19333        );
19334    }
19335
19336    #[test]
19337    fn merge_composite_key_alias_outer_propagates_missing_per_side() {
19338        let left = DataFrame::from_dict(
19339            &["lk1", "lk2", "left_v"],
19340            vec![
19341                (
19342                    "lk1",
19343                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
19344                ),
19345                (
19346                    "lk2",
19347                    vec![
19348                        Scalar::Utf8("a".to_owned()),
19349                        Scalar::Null(NullKind::Null),
19350                        Scalar::Utf8("c".to_owned()),
19351                    ],
19352                ),
19353                (
19354                    "left_v",
19355                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
19356                ),
19357            ],
19358        )
19359        .unwrap();
19360        let right = DataFrame::from_dict(
19361            &["rk1", "rk2", "right_v"],
19362            vec![
19363                (
19364                    "rk1",
19365                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(4)],
19366                ),
19367                (
19368                    "rk2",
19369                    vec![
19370                        Scalar::Utf8("a".to_owned()),
19371                        Scalar::Null(NullKind::Null),
19372                        Scalar::Utf8("d".to_owned()),
19373                    ],
19374                ),
19375                (
19376                    "right_v",
19377                    vec![Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(400)],
19378                ),
19379            ],
19380        )
19381        .unwrap();
19382
19383        let merged = merge_dataframes_on_with(
19384            &left,
19385            &right,
19386            &["lk1", "lk2"],
19387            &["rk1", "rk2"],
19388            JoinType::Outer,
19389        )
19390        .unwrap();
19391
19392        assert_eq!(
19393            merged.columns.get("lk1").unwrap().values(),
19394            &[
19395                Scalar::Float64(1.0),
19396                Scalar::Float64(2.0),
19397                Scalar::Float64(3.0),
19398                Scalar::Null(NullKind::NaN)
19399            ]
19400        );
19401        assert_eq!(
19402            merged.columns.get("rk1").unwrap().values(),
19403            &[
19404                Scalar::Float64(1.0),
19405                Scalar::Float64(2.0),
19406                Scalar::Null(NullKind::NaN),
19407                Scalar::Float64(4.0)
19408            ]
19409        );
19410        assert_eq!(
19411            merged.columns.get("left_v").unwrap().values(),
19412            &[
19413                Scalar::Float64(10.0),
19414                Scalar::Float64(20.0),
19415                Scalar::Float64(30.0),
19416                Scalar::Null(NullKind::NaN)
19417            ]
19418        );
19419        assert_eq!(
19420            merged.columns.get("right_v").unwrap().values(),
19421            &[
19422                Scalar::Float64(100.0),
19423                Scalar::Float64(200.0),
19424                Scalar::Null(NullKind::NaN),
19425                Scalar::Float64(400.0)
19426            ]
19427        );
19428    }
19429
19430    #[test]
19431    fn merge_key_alias_lists_must_have_equal_lengths() {
19432        let left = make_left_df();
19433        let right = make_right_df();
19434        let err = merge_dataframes_on_with(&left, &right, &["id", "id"], &["id"], JoinType::Inner)
19435            .expect_err("should fail");
19436        assert!(format!("{err}").contains("equal length"));
19437    }
19438
19439    #[test]
19440    fn merge_indicator_default_name_tracks_row_provenance() {
19441        let left = make_left_df();
19442        let right = make_right_df();
19443
19444        let merged = merge_dataframes_on_with_options(
19445            &left,
19446            &right,
19447            &["id"],
19448            &["id"],
19449            JoinType::Outer,
19450            MergeExecutionOptions {
19451                indicator_name: Some("_merge".to_owned()),
19452                ..MergeExecutionOptions::default()
19453            },
19454        )
19455        .expect("merge");
19456
19457        let indicator = merged.columns.get("_merge").expect("indicator");
19458        assert_eq!(
19459            indicator.values(),
19460            &[
19461                Scalar::Utf8("left_only".to_owned()),
19462                Scalar::Utf8("both".to_owned()),
19463                Scalar::Utf8("both".to_owned()),
19464                Scalar::Utf8("right_only".to_owned())
19465            ]
19466        );
19467        // pandas 2.2.3: _merge is a category over the fixed [left_only,
19468        // right_only, both] (br-frankenpandas-hrxn9), not an object column.
19469        assert_eq!(indicator.dtype(), fp_types::DType::Categorical);
19470        assert_eq!(
19471            indicator.categorical().map(|meta| meta.categories.clone()),
19472            Some(
19473                ["left_only", "right_only", "both"]
19474                    .map(|c| Scalar::Utf8(c.to_owned()))
19475                    .to_vec()
19476            )
19477        );
19478    }
19479
19480    #[test]
19481    fn merge_indicator_custom_name_preserves_suffix_behavior() {
19482        let left = DataFrame::from_dict(
19483            &["id", "val"],
19484            vec![
19485                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
19486                ("val", vec![Scalar::Int64(10), Scalar::Int64(20)]),
19487            ],
19488        )
19489        .unwrap();
19490        let right = DataFrame::from_dict(
19491            &["id", "val"],
19492            vec![
19493                ("id", vec![Scalar::Int64(2), Scalar::Int64(3)]),
19494                ("val", vec![Scalar::Int64(200), Scalar::Int64(300)]),
19495            ],
19496        )
19497        .unwrap();
19498
19499        let merged = merge_dataframes_on_with_options(
19500            &left,
19501            &right,
19502            &["id"],
19503            &["id"],
19504            JoinType::Outer,
19505            MergeExecutionOptions {
19506                indicator_name: Some("origin".to_owned()),
19507                ..MergeExecutionOptions::default()
19508            },
19509        )
19510        .expect("merge");
19511
19512        assert!(merged.columns.contains_key("val_x"));
19513        assert!(merged.columns.contains_key("val_y"));
19514        assert_eq!(
19515            merged.columns.get("origin").expect("indicator").values(),
19516            &[
19517                Scalar::Utf8("left_only".to_owned()),
19518                Scalar::Utf8("both".to_owned()),
19519                Scalar::Utf8("right_only".to_owned())
19520            ]
19521        );
19522    }
19523
19524    #[test]
19525    fn merge_indicator_rejects_conflicting_column_name() {
19526        let left = make_left_df();
19527        let right = make_right_df();
19528
19529        let err = merge_dataframes_on_with_options(
19530            &left,
19531            &right,
19532            &["id"],
19533            &["id"],
19534            JoinType::Inner,
19535            MergeExecutionOptions {
19536                indicator_name: Some("id".to_owned()),
19537                ..MergeExecutionOptions::default()
19538            },
19539        )
19540        .expect_err("expected indicator name conflict");
19541        assert!(format!("{err}").contains("conflicts with an existing column"));
19542    }
19543
19544    #[test]
19545    fn merge_cross_indicator_marks_all_rows_both() {
19546        // Restored after br-frankenpandas-glsam revert: pandas 2.2.3
19547        // supports `how='cross', indicator=...` and emits "both" for every
19548        // cross-product row (verified against FP-P2D-039 fixture provenance
19549        // pandas_version=2.2.3). The Explore-agent claim that pandas raises
19550        // was incorrect; this test locks in the actual pandas behavior.
19551        let left = DataFrame::from_dict(
19552            &["l"],
19553            vec![("l", vec![Scalar::Int64(1), Scalar::Int64(2)])],
19554        )
19555        .unwrap();
19556        let right = DataFrame::from_dict(&["r"], vec![("r", vec![Scalar::Int64(9)])]).unwrap();
19557
19558        let merged = merge_dataframes_on_with_options(
19559            &left,
19560            &right,
19561            &["ignored"],
19562            &["ignored"],
19563            JoinType::Cross,
19564            MergeExecutionOptions {
19565                indicator_name: Some("_merge".to_owned()),
19566                ..MergeExecutionOptions::default()
19567            },
19568        )
19569        .expect("cross merge");
19570        assert_eq!(
19571            merged.columns.get("_merge").expect("indicator").values(),
19572            &[
19573                Scalar::Utf8("both".to_owned()),
19574                Scalar::Utf8("both".to_owned())
19575            ]
19576        );
19577    }
19578
19579    #[test]
19580    fn merge_cross_validate_mode_contract_ohb5f() {
19581        let left = DataFrame::from_dict(
19582            &["l"],
19583            vec![("l", vec![Scalar::Int64(1), Scalar::Int64(2)])],
19584        )
19585        .expect("left");
19586        let right = DataFrame::from_dict(
19587            &["r"],
19588            vec![("r", vec![Scalar::Int64(10), Scalar::Int64(20)])],
19589        )
19590        .expect("right");
19591
19592        let many_to_many = merge_dataframes_on_with_options(
19593            &left,
19594            &right,
19595            &["missing_left_key"],
19596            &["missing_right_key"],
19597            JoinType::Cross,
19598            MergeExecutionOptions {
19599                validate_mode: Some(MergeValidateMode::ManyToMany),
19600                ..MergeExecutionOptions::default()
19601            },
19602        )
19603        .expect("cross merge validate=many_to_many");
19604        assert_eq!(many_to_many.index.len(), 4);
19605
19606        for validate_mode in [
19607            MergeValidateMode::OneToOne,
19608            MergeValidateMode::OneToMany,
19609            MergeValidateMode::ManyToOne,
19610        ] {
19611            let err = merge_dataframes_on_with_options(
19612                &left,
19613                &right,
19614                &["missing_left_key"],
19615                &["missing_right_key"],
19616                JoinType::Cross,
19617                MergeExecutionOptions {
19618                    validate_mode: Some(validate_mode),
19619                    ..MergeExecutionOptions::default()
19620                },
19621            )
19622            .expect_err("enforcing validate modes are not meaningful for cross joins");
19623            let message = format!("{err}");
19624            assert!(message.contains(validate_mode.as_str()));
19625            assert!(message.contains("not supported for cross join"));
19626        }
19627    }
19628
19629    #[test]
19630    fn merge_validate_one_to_one_rejects_duplicate_left_keys() {
19631        let left = DataFrame::from_dict(
19632            &["id", "left_v"],
19633            vec![
19634                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
19635                ("left_v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
19636            ],
19637        )
19638        .expect("left frame");
19639        let right = DataFrame::from_dict(
19640            &["id", "right_v"],
19641            vec![
19642                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
19643                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
19644            ],
19645        )
19646        .expect("right frame");
19647
19648        let err = merge_dataframes_on_with_options(
19649            &left,
19650            &right,
19651            &["id"],
19652            &["id"],
19653            JoinType::Inner,
19654            MergeExecutionOptions {
19655                validate_mode: Some(MergeValidateMode::OneToOne),
19656                ..MergeExecutionOptions::default()
19657            },
19658        )
19659        .expect_err("one_to_one must reject duplicate left keys");
19660        assert!(format!("{err}").contains("left keys are not unique"));
19661    }
19662
19663    #[test]
19664    fn repeated_non_key_columns_keep_their_own_data_through_merge_i17d4() {
19665        // pandas 2.2.3: merging a frame whose columns are ['a', 'a', 'k'] on
19666        // 'k' keeps both 'a' columns, each its own data (the first was read
19667        // for both); when the other side has an 'a' too, each copy takes its
19668        // side's suffix (a_x, a_x beside a_y).
19669        let f = Scalar::Float64;
19670        let column = |values: [f64; 2]| {
19671            Column::new(DType::Float64, values.iter().map(|v| f(*v)).collect()).expect("column")
19672        };
19673        let left = DataFrame::new_with_column_order(
19674            Index::new(vec![0_i64.into(), 1_i64.into()]),
19675            ColumnStore::from_pairs(vec![
19676                ("a".to_owned(), column([1.0, 4.0])),
19677                ("a".to_owned(), column([5.75, 2.25])),
19678                ("k".to_owned(), column([1.0, 2.0])),
19679            ]),
19680            vec!["a".to_owned(), "a".to_owned(), "k".to_owned()],
19681        )
19682        .expect("left frame");
19683        let right = |other: &str| {
19684            DataFrame::from_dict(
19685                &["k", other],
19686                vec![("k", vec![f(1.0), f(2.0)]), (other, vec![f(5.0), f(6.0)])],
19687            )
19688            .expect("right frame")
19689        };
19690        let merge = |right: &DataFrame| {
19691            merge_dataframes_on_with_options(
19692                &left,
19693                right,
19694                &["k"],
19695                &["k"],
19696                JoinType::Inner,
19697                MergeExecutionOptions::default(),
19698            )
19699            .expect("merge")
19700        };
19701        let merged = merge(&right("z"));
19702        assert_eq!(merged.column_order, vec!["a", "a", "k", "z"]);
19703        let second_a = merged.columns.get_all("a").nth(1).expect("second a");
19704        assert_eq!(second_a.values(), &[f(5.75), f(2.25)]);
19705
19706        let suffixed = merge(&right("a"));
19707        assert_eq!(suffixed.column_order, vec!["a_x", "a_x", "k", "a_y"]);
19708        let second_x = suffixed.columns.get_all("a_x").nth(1).expect("second a_x");
19709        assert_eq!(second_x.values(), &[f(5.75), f(2.25)]);
19710        let right_a = suffixed.columns.get("a_y").expect("a_y");
19711        assert_eq!(right_a.values(), &[f(5.0), f(6.0)]);
19712
19713        // NEGATIVE: unique keys merge under their own names, unsuffixed.
19714        let plain = merge_dataframes_on_with_options(
19715            &right("q"),
19716            &right("z"),
19717            &["k"],
19718            &["k"],
19719            JoinType::Inner,
19720            MergeExecutionOptions::default(),
19721        )
19722        .expect("plain merge");
19723        assert_eq!(plain.column_order, vec!["k", "q", "z"]);
19724    }
19725
19726    #[test]
19727    fn merge_validate_one_to_one_names_both_sides_when_both_duplicate_z6jxh() {
19728        let left = DataFrame::from_dict(
19729            &["id", "left_v"],
19730            vec![
19731                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
19732                ("left_v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
19733            ],
19734        )
19735        .expect("left frame");
19736        let right = DataFrame::from_dict(
19737            &["id", "right_v"],
19738            vec![
19739                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
19740                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
19741            ],
19742        )
19743        .expect("right frame");
19744
19745        let err = merge_dataframes_on_with_options(
19746            &left,
19747            &right,
19748            &["id"],
19749            &["id"],
19750            JoinType::Inner,
19751            MergeExecutionOptions {
19752                validate_mode: Some(MergeValidateMode::OneToOne),
19753                ..MergeExecutionOptions::default()
19754            },
19755        )
19756        .expect_err("one_to_one must reject keys repeated on both sides");
19757        // pandas 2.2.3: 'Merge keys are not unique in either left or right
19758        // dataset' - both sides named, not the left first (z6jxh).
19759        assert!(format!("{err}").contains("left and right keys are not unique"));
19760
19761        // The composite-key path (text keys) answers alike; NEGATIVE: with
19762        // only the right side repeating, only the right is named.
19763        let text_keys = |values: [&str; 2]| {
19764            DataFrame::from_dict(
19765                &["id"],
19766                vec![(
19767                    "id",
19768                    values.iter().map(|v| Scalar::Utf8((*v).into())).collect(),
19769                )],
19770            )
19771            .expect("text-keyed frame")
19772        };
19773        let validate = |left: &DataFrame, right: &DataFrame| {
19774            merge_dataframes_on_with_options(
19775                left,
19776                right,
19777                &["id"],
19778                &["id"],
19779                JoinType::Inner,
19780                MergeExecutionOptions {
19781                    validate_mode: Some(MergeValidateMode::OneToOne),
19782                    ..MergeExecutionOptions::default()
19783                },
19784            )
19785            .expect_err("one_to_one must reject a repeated key")
19786            .to_string()
19787        };
19788        let both = validate(&text_keys(["a", "a"]), &text_keys(["a", "a"]));
19789        assert!(
19790            both.contains("left and right keys are not unique"),
19791            "{both}"
19792        );
19793        let right_only = validate(&text_keys(["a", "b"]), &text_keys(["a", "a"]));
19794        assert!(
19795            right_only.contains(": right keys are not unique"),
19796            "{right_only}"
19797        );
19798    }
19799
19800    #[test]
19801    fn merge_validate_one_to_many_allows_duplicate_right_keys() {
19802        let left = DataFrame::from_dict(
19803            &["id", "left_v"],
19804            vec![
19805                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
19806                ("left_v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
19807            ],
19808        )
19809        .expect("left frame");
19810        let right = DataFrame::from_dict(
19811            &["id", "right_v"],
19812            vec![
19813                (
19814                    "id",
19815                    vec![Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(2)],
19816                ),
19817                (
19818                    "right_v",
19819                    vec![Scalar::Int64(100), Scalar::Int64(101), Scalar::Int64(200)],
19820                ),
19821            ],
19822        )
19823        .expect("right frame");
19824
19825        let merged = merge_dataframes_on_with_options(
19826            &left,
19827            &right,
19828            &["id"],
19829            &["id"],
19830            JoinType::Inner,
19831            MergeExecutionOptions {
19832                validate_mode: Some(MergeValidateMode::OneToMany),
19833                ..MergeExecutionOptions::default()
19834            },
19835        )
19836        .expect("one_to_many should allow duplicate right keys");
19837        assert_eq!(merged.columns.get("id").expect("id").values().len(), 3);
19838    }
19839
19840    #[test]
19841    fn merge_validate_one_to_many_rejects_duplicate_left_keys_9hsb3() {
19842        let left = DataFrame::from_dict(
19843            &["id", "left_v"],
19844            vec![
19845                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
19846                ("left_v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
19847            ],
19848        )
19849        .expect("left frame");
19850        let right = DataFrame::from_dict(
19851            &["id", "right_v"],
19852            vec![
19853                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
19854                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
19855            ],
19856        )
19857        .expect("right frame");
19858
19859        let err = merge_dataframes_on_with_options(
19860            &left,
19861            &right,
19862            &["id"],
19863            &["id"],
19864            JoinType::Inner,
19865            MergeExecutionOptions {
19866                validate_mode: Some(MergeValidateMode::OneToMany),
19867                ..MergeExecutionOptions::default()
19868            },
19869        )
19870        .expect_err("one_to_many must reject duplicate left keys");
19871        assert!(format!("{err}").contains("left keys are not unique"));
19872    }
19873
19874    #[test]
19875    fn merge_validate_many_to_one_rejects_duplicate_right_keys() {
19876        let left = DataFrame::from_dict(
19877            &["id", "left_v"],
19878            vec![
19879                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
19880                ("left_v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
19881            ],
19882        )
19883        .expect("left frame");
19884        let right = DataFrame::from_dict(
19885            &["id", "right_v"],
19886            vec![
19887                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
19888                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(101)]),
19889            ],
19890        )
19891        .expect("right frame");
19892
19893        let err = merge_dataframes_on_with_options(
19894            &left,
19895            &right,
19896            &["id"],
19897            &["id"],
19898            JoinType::Inner,
19899            MergeExecutionOptions {
19900                validate_mode: Some(MergeValidateMode::ManyToOne),
19901                ..MergeExecutionOptions::default()
19902            },
19903        )
19904        .expect_err("many_to_one must reject duplicate right keys");
19905        assert!(format!("{err}").contains("right keys are not unique"));
19906    }
19907
19908    #[test]
19909    fn merge_validate_many_to_one_allows_duplicate_left_keys_9hsb3() {
19910        let left = DataFrame::from_dict(
19911            &["id", "left_v"],
19912            vec![
19913                (
19914                    "id",
19915                    vec![Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(2)],
19916                ),
19917                (
19918                    "left_v",
19919                    vec![Scalar::Int64(10), Scalar::Int64(11), Scalar::Int64(20)],
19920                ),
19921            ],
19922        )
19923        .expect("left frame");
19924        let right = DataFrame::from_dict(
19925            &["id", "right_v"],
19926            vec![
19927                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
19928                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
19929            ],
19930        )
19931        .expect("right frame");
19932
19933        let merged = merge_dataframes_on_with_options(
19934            &left,
19935            &right,
19936            &["id"],
19937            &["id"],
19938            JoinType::Inner,
19939            MergeExecutionOptions {
19940                validate_mode: Some(MergeValidateMode::ManyToOne),
19941                ..MergeExecutionOptions::default()
19942            },
19943        )
19944        .expect("many_to_one should allow duplicate left keys");
19945        assert_eq!(merged.columns.get("id").expect("id").values().len(), 3);
19946    }
19947
19948    #[test]
19949    fn merge_validate_many_to_many_allows_duplicates_on_both_sides() {
19950        let left = DataFrame::from_dict(
19951            &["id", "left_v"],
19952            vec![
19953                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
19954                ("left_v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
19955            ],
19956        )
19957        .expect("left frame");
19958        let right = DataFrame::from_dict(
19959            &["id", "right_v"],
19960            vec![
19961                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
19962                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
19963            ],
19964        )
19965        .expect("right frame");
19966
19967        let merged = merge_dataframes_on_with_options(
19968            &left,
19969            &right,
19970            &["id"],
19971            &["id"],
19972            JoinType::Inner,
19973            MergeExecutionOptions {
19974                validate_mode: Some(MergeValidateMode::ManyToMany),
19975                ..MergeExecutionOptions::default()
19976            },
19977        )
19978        .expect("many_to_many should allow duplicate keys on both sides");
19979        assert_eq!(merged.columns.get("id").expect("id").values().len(), 4);
19980    }
19981
19982    #[test]
19983    fn join_series_cross_cartesian_product() {
19984        let left = Series::from_values(
19985            "left",
19986            vec!["a".into(), "b".into()],
19987            vec![Scalar::Int64(1), Scalar::Int64(2)],
19988        )
19989        .unwrap();
19990        let right = Series::from_values(
19991            "right",
19992            vec!["x".into(), "y".into()],
19993            vec![Scalar::Int64(10), Scalar::Int64(20)],
19994        )
19995        .unwrap();
19996
19997        let out = join_series(&left, &right, JoinType::Cross).unwrap();
19998        assert_eq!(out.index.labels().len(), 4);
19999        assert_eq!(
20000            out.left_values.values(),
20001            &[
20002                Scalar::Int64(1),
20003                Scalar::Int64(1),
20004                Scalar::Int64(2),
20005                Scalar::Int64(2)
20006            ]
20007        );
20008        assert_eq!(
20009            out.right_values.values(),
20010            &[
20011                Scalar::Int64(10),
20012                Scalar::Int64(20),
20013                Scalar::Int64(10),
20014                Scalar::Int64(20)
20015            ]
20016        );
20017    }
20018
20019    // ── DataFrameMergeExt trait tests ──
20020
20021    #[test]
20022    fn dataframe_merge_via_trait() {
20023        use fp_frame::DataFrame;
20024
20025        use super::{DataFrameMergeExt, merge_dataframes_on};
20026
20027        let left = DataFrame::from_series(vec![
20028            Series::from_values(
20029                "key",
20030                vec![0_i64.into(), 1_i64.into()],
20031                vec![Scalar::Int64(1), Scalar::Int64(2)],
20032            )
20033            .unwrap(),
20034            Series::from_values(
20035                "val_l",
20036                vec![0_i64.into(), 1_i64.into()],
20037                vec![Scalar::Int64(10), Scalar::Int64(20)],
20038            )
20039            .unwrap(),
20040        ])
20041        .unwrap();
20042
20043        let right = DataFrame::from_series(vec![
20044            Series::from_values(
20045                "key",
20046                vec![0_i64.into(), 1_i64.into()],
20047                vec![Scalar::Int64(1), Scalar::Int64(3)],
20048            )
20049            .unwrap(),
20050            Series::from_values(
20051                "val_r",
20052                vec![0_i64.into(), 1_i64.into()],
20053                vec![Scalar::Int64(100), Scalar::Int64(300)],
20054            )
20055            .unwrap(),
20056        ])
20057        .unwrap();
20058
20059        // Instance method
20060        let result = left.merge(&right, &["key"], JoinType::Inner).unwrap();
20061        assert_eq!(result.index.len(), 1); // only key=1 matches
20062
20063        // Standalone function should give same result
20064        let result2 = merge_dataframes_on(&left, &right, &["key"], JoinType::Inner).unwrap();
20065        assert_eq!(result.index.len(), result2.index.len());
20066    }
20067
20068    // ── merge_asof tests ──
20069
20070    fn compute_asof_matches_datetime64_former_nsslz(
20071        left: super::Datetime64AsofKey<'_>,
20072        right: super::Datetime64AsofKey<'_>,
20073        direction: super::AsofDirection,
20074        allow_exact_matches: bool,
20075        tolerance: Option<f64>,
20076    ) -> Vec<Option<usize>> {
20077        let mut right_valid_values = Vec::new();
20078        let mut right_valid_positions = Vec::new();
20079        for i in 0..right.data.len() {
20080            if right.is_valid(i) {
20081                right_valid_values.push(right.data[i]);
20082                right_valid_positions.push(i);
20083            }
20084        }
20085        super::compute_asof_matches_datetime64_prepared(
20086            left,
20087            &right_valid_values,
20088            Some(&right_valid_positions),
20089            direction,
20090            allow_exact_matches,
20091            tolerance,
20092        )
20093    }
20094
20095    #[test]
20096    fn merge_asof_datetime64_borrowed_dense_right_matches_former_nsslz() {
20097        let dense_left = Column::from_datetime64_values_with_validity(
20098            vec![-15, -10, -5, 0, 5, 30, 35],
20099            ValidityMask::all_valid(7),
20100        );
20101        let dense_right = Column::from_datetime64_values_with_validity(
20102            vec![-10, 0, 10, 20, 30],
20103            ValidityMask::all_valid(5),
20104        );
20105
20106        let nat_right = Column::from_datetime64_values_with_validity(
20107            vec![fp_types::Timestamp::NAT, -10, 0, 20, 30],
20108            ValidityMask::all_valid(5),
20109        );
20110        let nat_left = Column::from_datetime64_values_with_validity(
20111            vec![fp_types::Timestamp::NAT, -10, -5, 0, 5, 30, 35],
20112            ValidityMask::all_valid(7),
20113        );
20114
20115        for (left, right) in [
20116            (&dense_left, &dense_right),
20117            (&dense_left, &nat_right),
20118            (&nat_left, &dense_right),
20119        ] {
20120            let left_key = super::datetime64_key_parts(left).expect("Datetime64 left key");
20121            let right_key = super::datetime64_key_parts(right).expect("Datetime64 right key");
20122            for direction in [
20123                super::AsofDirection::Backward,
20124                super::AsofDirection::Forward,
20125                super::AsofDirection::Nearest,
20126            ] {
20127                for allow_exact_matches in [false, true] {
20128                    for tolerance in [None, Some(7.0)] {
20129                        assert_eq!(
20130                            super::compute_asof_matches_datetime64(
20131                                left_key,
20132                                right_key,
20133                                direction,
20134                                allow_exact_matches,
20135                                tolerance,
20136                            ),
20137                            compute_asof_matches_datetime64_former_nsslz(
20138                                left_key,
20139                                right_key,
20140                                direction,
20141                                allow_exact_matches,
20142                                tolerance,
20143                            ),
20144                            "direction={direction:?} exact={allow_exact_matches} tolerance={tolerance:?}",
20145                        );
20146                    }
20147                }
20148            }
20149        }
20150    }
20151
20152    #[test]
20153    #[ignore = "foreground release A/B only"]
20154    fn datetime64_asof_borrowed_dense_right_ab_nsslz() {
20155        use std::{hint::black_box, time::Instant};
20156
20157        const ITEMS: usize = 131_072;
20158        const SAMPLES: usize = 10;
20159
20160        fn elapsed(run: impl FnOnce() -> Vec<Option<usize>>) -> u128 {
20161            let started = Instant::now();
20162            let output = black_box(run());
20163            black_box(output.len());
20164            let elapsed = started.elapsed().as_nanos();
20165            drop(output);
20166            elapsed
20167        }
20168
20169        let left = Column::from_datetime64_values_with_validity(
20170            (0..ITEMS).map(|i| i as i64 * 4 + 1).collect(),
20171            ValidityMask::all_valid(ITEMS),
20172        );
20173        let right = Column::from_datetime64_values_with_validity(
20174            (0..ITEMS).map(|i| i as i64 * 4).collect(),
20175            ValidityMask::all_valid(ITEMS),
20176        );
20177        let left_key = super::datetime64_key_parts(&left).expect("Datetime64 left key");
20178        let right_key = super::datetime64_key_parts(&right).expect("Datetime64 right key");
20179        let former = || {
20180            compute_asof_matches_datetime64_former_nsslz(
20181                left_key,
20182                right_key,
20183                super::AsofDirection::Backward,
20184                true,
20185                None,
20186            )
20187        };
20188        let candidate = || {
20189            super::compute_asof_matches_datetime64(
20190                left_key,
20191                right_key,
20192                super::AsofDirection::Backward,
20193                true,
20194                None,
20195            )
20196        };
20197
20198        assert_eq!(candidate(), former());
20199        black_box(former());
20200        black_box(candidate());
20201
20202        let mut former_ns = Vec::with_capacity(SAMPLES);
20203        let mut candidate_ns = Vec::with_capacity(SAMPLES);
20204        for sample in 0..SAMPLES {
20205            if sample.is_multiple_of(2) {
20206                former_ns.push(elapsed(former));
20207                candidate_ns.push(elapsed(candidate));
20208            } else {
20209                candidate_ns.push(elapsed(candidate));
20210                former_ns.push(elapsed(former));
20211            }
20212        }
20213        former_ns.sort_unstable();
20214        candidate_ns.sort_unstable();
20215        let former_p50 = former_ns[SAMPLES / 2];
20216        let candidate_p50 = candidate_ns[SAMPLES / 2];
20217        println!(
20218            "datetime64_asof_borrowed_dense_right_ab items={ITEMS} samples={SAMPLES} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} speedup={:.6}x",
20219            former_p50 as f64 / candidate_p50 as f64,
20220        );
20221        println!("former_samples_ns={former_ns:?}");
20222        println!("candidate_samples_ns={candidate_ns:?}");
20223    }
20224
20225    #[test]
20226    fn merge_asof_backward() {
20227        use super::DataFrameMergeExt;
20228
20229        // Left: trades at times 1, 3, 5, 7
20230        let left = fp_frame::DataFrame::from_dict(
20231            &["time", "price"],
20232            vec![
20233                (
20234                    "time",
20235                    vec![
20236                        Scalar::Int64(1),
20237                        Scalar::Int64(3),
20238                        Scalar::Int64(5),
20239                        Scalar::Int64(7),
20240                    ],
20241                ),
20242                (
20243                    "price",
20244                    vec![
20245                        Scalar::Float64(100.0),
20246                        Scalar::Float64(101.0),
20247                        Scalar::Float64(102.0),
20248                        Scalar::Float64(103.0),
20249                    ],
20250                ),
20251            ],
20252        )
20253        .unwrap();
20254
20255        // Right: quotes at times 2, 4, 6
20256        let right = fp_frame::DataFrame::from_dict(
20257            &["time", "bid"],
20258            vec![
20259                (
20260                    "time",
20261                    vec![Scalar::Int64(2), Scalar::Int64(4), Scalar::Int64(6)],
20262                ),
20263                (
20264                    "bid",
20265                    vec![
20266                        Scalar::Float64(99.5),
20267                        Scalar::Float64(100.5),
20268                        Scalar::Float64(101.5),
20269                    ],
20270                ),
20271            ],
20272        )
20273        .unwrap();
20274
20275        let result = left.merge_asof(&right, "time", "backward").unwrap();
20276        // For time=1: no right row <= 1, so bid=NaN
20277        // For time=3: last right row <= 3 is time=2 → bid=99.5
20278        // For time=5: last right row <= 5 is time=4 → bid=100.5
20279        // For time=7: last right row <= 7 is time=6 → bid=101.5
20280        let bid_col = result.columns.get("bid").unwrap();
20281        assert!(bid_col.values()[0].is_missing());
20282        assert_eq!(bid_col.values()[1], Scalar::Float64(99.5));
20283        assert_eq!(bid_col.values()[2], Scalar::Float64(100.5));
20284        assert_eq!(bid_col.values()[3], Scalar::Float64(101.5));
20285    }
20286
20287    /// A right column that gains an UNMATCHED row gains a gap, and an all-valid
20288    /// numpy int64 cannot hold one — pandas widens that column to float64,
20289    /// exactly as it does across the join family.
20290    ///
20291    /// Measured, live pandas 2.2.3:
20292    /// ```text
20293    ///   L = DataFrame({'time':[1,5,10], 'left_val':[10,50,100]})
20294    ///   R = DataFrame({'time':[2,6],    'right_val':[20,60]})
20295    ///   pd.merge_asof(L, R, on='time', direction='forward')
20296    ///     right_val -> [20.0, 60.0, NaN]  dtype float64
20297    ///     dtypes: time int64, left_val int64, right_val float64
20298    ///
20299    ///   L2 = DataFrame({'time':[1,5]}, ...); R2 = DataFrame({'time':[2,4]}, ...)
20300    ///   pd.merge_asof(L2, R2, on='time', direction='backward')
20301    ///     right_val -> [NaN, 40.0]        dtype float64
20302    ///
20303    ///   with every left row matched (times 3,7 against 2,4)
20304    ///     right_val -> [20, 40]           dtype int64
20305    /// ```
20306    /// The rule is PER COLUMN here — `time` and `left_val` gain no gap and stay
20307    /// int64 — unlike `Series.unstack`, where a gap widens the whole frame
20308    /// because it reshapes one block. Both fixtures on FP-P2D-056 pinned the
20309    /// present values as int64 beside the NaN, which is FrankenPandas' own
20310    /// pre-fix answer.
20311    #[test]
20312    fn merge_asof_unmatched_row_widens_that_column_to_float64() {
20313        use super::DataFrameMergeExt;
20314
20315        let int_frame = |name: &str, times: Vec<i64>, vals: Vec<i64>| {
20316            fp_frame::DataFrame::from_dict(
20317                &["time", name],
20318                vec![
20319                    (
20320                        "time",
20321                        times.into_iter().map(Scalar::Int64).collect::<Vec<_>>(),
20322                    ),
20323                    (
20324                        name,
20325                        vals.into_iter().map(Scalar::Int64).collect::<Vec<_>>(),
20326                    ),
20327                ],
20328            )
20329            .unwrap()
20330        };
20331
20332        let left = int_frame("left_val", vec![1, 5, 10], vec![10, 50, 100]);
20333        let right = int_frame("right_val", vec![2, 6], vec![20, 60]);
20334        let forward = left.merge_asof(&right, "time", "forward").unwrap();
20335        assert_eq!(
20336            forward.columns.get("right_val").unwrap().values(),
20337            &[
20338                Scalar::Float64(20.0),
20339                Scalar::Float64(60.0),
20340                Scalar::Null(NullKind::NaN),
20341            ]
20342        );
20343        // The columns that gain NO gap keep int64 — this is per column, not
20344        // frame-wide.
20345        assert_eq!(
20346            forward.columns.get("left_val").unwrap().values(),
20347            &[Scalar::Int64(10), Scalar::Int64(50), Scalar::Int64(100)]
20348        );
20349        assert_eq!(
20350            forward.columns.get("time").unwrap().dtype(),
20351            fp_types::DType::Int64
20352        );
20353
20354        let backward = int_frame("left_val", vec![1, 5], vec![10, 50])
20355            .merge_asof(
20356                &int_frame("right_val", vec![2, 4], vec![20, 40]),
20357                "time",
20358                "backward",
20359            )
20360            .unwrap();
20361        assert_eq!(
20362            backward.columns.get("right_val").unwrap().values(),
20363            &[Scalar::Null(NullKind::NaN), Scalar::Float64(40.0)]
20364        );
20365
20366        // The control that this is about the GAP and not about merge_asof always
20367        // widening: with every left row matched, right_val stays int64.
20368        let matched = int_frame("left_val", vec![3, 7], vec![10, 50])
20369            .merge_asof(
20370                &int_frame("right_val", vec![2, 4], vec![20, 40]),
20371                "time",
20372                "backward",
20373            )
20374            .unwrap();
20375        assert_eq!(
20376            matched.columns.get("right_val").unwrap().values(),
20377            &[Scalar::Int64(20), Scalar::Int64(40)]
20378        );
20379    }
20380
20381    #[test]
20382    fn merge_asof_forward() {
20383        use super::AsofDirection;
20384
20385        let left = fp_frame::DataFrame::from_dict(
20386            &["time", "val"],
20387            vec![
20388                ("time", vec![Scalar::Int64(1), Scalar::Int64(3)]),
20389                ("val", vec![Scalar::Float64(10.0), Scalar::Float64(30.0)]),
20390            ],
20391        )
20392        .unwrap();
20393
20394        let right = fp_frame::DataFrame::from_dict(
20395            &["time", "quote"],
20396            vec![
20397                ("time", vec![Scalar::Int64(2), Scalar::Int64(5)]),
20398                ("quote", vec![Scalar::Float64(20.0), Scalar::Float64(50.0)]),
20399            ],
20400        )
20401        .unwrap();
20402
20403        let result = super::merge_asof(&left, &right, "time", AsofDirection::Forward).unwrap();
20404        // time=1: first right >= 1 is time=2 → quote=20
20405        // time=3: first right >= 3 is time=5 → quote=50
20406        let quote_col = result.columns.get("quote").unwrap();
20407        assert_eq!(quote_col.values()[0], Scalar::Float64(20.0));
20408        assert_eq!(quote_col.values()[1], Scalar::Float64(50.0));
20409    }
20410
20411    #[test]
20412    fn merge_asof_nearest() {
20413        use super::AsofDirection;
20414
20415        let left = fp_frame::DataFrame::from_dict(
20416            &["time", "val"],
20417            vec![
20418                ("time", vec![Scalar::Int64(3), Scalar::Int64(7)]),
20419                ("val", vec![Scalar::Float64(1.0), Scalar::Float64(2.0)]),
20420            ],
20421        )
20422        .unwrap();
20423
20424        let right = fp_frame::DataFrame::from_dict(
20425            &["time", "ref_val"],
20426            vec![
20427                (
20428                    "time",
20429                    vec![Scalar::Int64(1), Scalar::Int64(5), Scalar::Int64(10)],
20430                ),
20431                (
20432                    "ref_val",
20433                    vec![
20434                        Scalar::Float64(100.0),
20435                        Scalar::Float64(500.0),
20436                        Scalar::Float64(1000.0),
20437                    ],
20438                ),
20439            ],
20440        )
20441        .unwrap();
20442
20443        let result = super::merge_asof(&left, &right, "time", AsofDirection::Nearest).unwrap();
20444        // time=3: nearest is 1(dist=2) or 5(dist=2), first found = 1 → ref_val=100
20445        // Actually: for nearest, it finds the one with smallest dist. dist(3,1)=2, dist(3,5)=2
20446        // ties go to first found, so ref_val = 100
20447        // time=7: nearest is 5(dist=2) or 10(dist=3) → ref_val=500
20448        let ref_col = result.columns.get("ref_val").unwrap();
20449        assert_eq!(ref_col.values()[1], Scalar::Float64(500.0)); // time=7 → 5 is nearest
20450    }
20451
20452    #[test]
20453    fn merge_asof_nearest_excludes_exact_finds_neighbor() {
20454        // Regression: with direction=nearest and allow_exact_matches=false,
20455        // an exact-equal key must be skipped over to reach the nearest
20456        // non-equal key, rather than yielding no match. Verified against
20457        // pandas 2.2.3: merge_asof(left=5, right=[3,5,5], nearest,
20458        // allow_exact_matches=False) -> matches value 3.
20459        use super::{AsofDirection, MergeAsofOptions};
20460
20461        let left = fp_frame::DataFrame::from_dict(
20462            &["time", "val"],
20463            vec![
20464                ("time", vec![Scalar::Int64(5)]),
20465                ("val", vec![Scalar::Int64(1)]),
20466            ],
20467        )
20468        .unwrap();
20469        let right = fp_frame::DataFrame::from_dict(
20470            &["time", "ref_val"],
20471            vec![
20472                (
20473                    "time",
20474                    vec![Scalar::Int64(3), Scalar::Int64(5), Scalar::Int64(5)],
20475                ),
20476                (
20477                    "ref_val",
20478                    vec![
20479                        Scalar::Float64(10.0),
20480                        Scalar::Float64(20.0),
20481                        Scalar::Float64(30.0),
20482                    ],
20483                ),
20484            ],
20485        )
20486        .unwrap();
20487
20488        let opts = MergeAsofOptions::new().allow_exact_matches(false);
20489        let result =
20490            super::merge_asof_with_options(&left, &right, "time", AsofDirection::Nearest, opts)
20491                .unwrap();
20492        let ref_col = result.columns.get("ref_val").unwrap();
20493        assert_eq!(ref_col.values()[0], Scalar::Float64(10.0)); // value 3 is nearest non-exact
20494    }
20495
20496    #[test]
20497    fn merge_asof_exact_match() {
20498        use super::AsofDirection;
20499
20500        let left = fp_frame::DataFrame::from_dict(
20501            &["time", "val"],
20502            vec![
20503                ("time", vec![Scalar::Int64(2), Scalar::Int64(4)]),
20504                ("val", vec![Scalar::Float64(1.0), Scalar::Float64(2.0)]),
20505            ],
20506        )
20507        .unwrap();
20508
20509        let right = fp_frame::DataFrame::from_dict(
20510            &["time", "quote"],
20511            vec![
20512                ("time", vec![Scalar::Int64(2), Scalar::Int64(4)]),
20513                ("quote", vec![Scalar::Float64(20.0), Scalar::Float64(40.0)]),
20514            ],
20515        )
20516        .unwrap();
20517
20518        // Backward: exact match should work (right_val <= left_val includes ==).
20519        let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
20520        assert_eq!(
20521            result.columns.get("quote").unwrap().values()[0],
20522            Scalar::Float64(20.0)
20523        );
20524        assert_eq!(
20525            result.columns.get("quote").unwrap().values()[1],
20526            Scalar::Float64(40.0)
20527        );
20528
20529        // Forward: exact match should work (right_val >= left_val includes ==).
20530        let result = super::merge_asof(&left, &right, "time", AsofDirection::Forward).unwrap();
20531        assert_eq!(
20532            result.columns.get("quote").unwrap().values()[0],
20533            Scalar::Float64(20.0)
20534        );
20535    }
20536
20537    #[test]
20538    fn merge_asof_datetime64_wide_ns_range_uses_i64_path() {
20539        use super::AsofDirection;
20540
20541        let day_ns = 86_400_000_000_000i64;
20542        let base = 1_600_000_000_000_000_000i64;
20543        let dt = |days: i64| Scalar::Datetime64(base + days * day_ns);
20544
20545        let left = fp_frame::DataFrame::from_dict(
20546            &["time", "val"],
20547            vec![
20548                ("time", vec![dt(0), dt(200), dt(400)]),
20549                (
20550                    "val",
20551                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
20552                ),
20553            ],
20554        )
20555        .unwrap();
20556
20557        let right = fp_frame::DataFrame::from_dict(
20558            &["time", "quote"],
20559            vec![
20560                ("time", vec![dt(-1), dt(199), dt(401)]),
20561                (
20562                    "quote",
20563                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
20564                ),
20565            ],
20566        )
20567        .unwrap();
20568
20569        let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
20570        let quote_col = result.columns.get("quote").unwrap();
20571        assert_eq!(quote_col.values()[0], Scalar::Int64(10));
20572        assert_eq!(quote_col.values()[1], Scalar::Int64(20));
20573        assert_eq!(quote_col.values()[2], Scalar::Int64(20));
20574    }
20575
20576    #[test]
20577    fn merge_asof_no_matches_backward() {
20578        use super::AsofDirection;
20579
20580        let left = fp_frame::DataFrame::from_dict(
20581            &["time", "val"],
20582            vec![
20583                ("time", vec![Scalar::Int64(1)]),
20584                ("val", vec![Scalar::Float64(10.0)]),
20585            ],
20586        )
20587        .unwrap();
20588
20589        // Right starts at time=5, so backward from time=1 finds nothing.
20590        let right = fp_frame::DataFrame::from_dict(
20591            &["time", "quote"],
20592            vec![
20593                ("time", vec![Scalar::Int64(5)]),
20594                ("quote", vec![Scalar::Float64(50.0)]),
20595            ],
20596        )
20597        .unwrap();
20598
20599        let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
20600        assert!(result.columns.get("quote").unwrap().values()[0].is_missing());
20601    }
20602
20603    #[test]
20604    fn merge_asof_no_matches_forward() {
20605        use super::AsofDirection;
20606
20607        let left = fp_frame::DataFrame::from_dict(
20608            &["time", "val"],
20609            vec![
20610                ("time", vec![Scalar::Int64(10)]),
20611                ("val", vec![Scalar::Float64(10.0)]),
20612            ],
20613        )
20614        .unwrap();
20615
20616        // Right ends at time=5, so forward from time=10 finds nothing.
20617        let right = fp_frame::DataFrame::from_dict(
20618            &["time", "quote"],
20619            vec![
20620                ("time", vec![Scalar::Int64(5)]),
20621                ("quote", vec![Scalar::Float64(50.0)]),
20622            ],
20623        )
20624        .unwrap();
20625
20626        let result = super::merge_asof(&left, &right, "time", AsofDirection::Forward).unwrap();
20627        assert!(result.columns.get("quote").unwrap().values()[0].is_missing());
20628    }
20629
20630    #[test]
20631    fn merge_asof_nan_in_key() {
20632        use super::AsofDirection;
20633
20634        let left = fp_frame::DataFrame::from_dict(
20635            &["time", "val"],
20636            vec![
20637                (
20638                    "time",
20639                    vec![
20640                        Scalar::Int64(1),
20641                        Scalar::Null(NullKind::NaN),
20642                        Scalar::Int64(5),
20643                    ],
20644                ),
20645                (
20646                    "val",
20647                    vec![
20648                        Scalar::Float64(10.0),
20649                        Scalar::Float64(20.0),
20650                        Scalar::Float64(30.0),
20651                    ],
20652                ),
20653            ],
20654        )
20655        .unwrap();
20656
20657        let right = fp_frame::DataFrame::from_dict(
20658            &["time", "quote"],
20659            vec![
20660                ("time", vec![Scalar::Int64(2), Scalar::Int64(4)]),
20661                (
20662                    "quote",
20663                    vec![Scalar::Float64(200.0), Scalar::Float64(400.0)],
20664                ),
20665            ],
20666        )
20667        .unwrap();
20668
20669        // With matching key dtypes, pandas merge_asof accepts NaN keys: the
20670        // NaN row gets no match (null in joined columns).
20671        let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
20672        assert!(result.columns.get("quote").unwrap().values()[1].is_missing());
20673        // time=5 → backward match to time=4 → quote=400
20674        assert_eq!(
20675            result.columns.get("quote").unwrap().values()[2],
20676            Scalar::Float64(400.0)
20677        );
20678    }
20679
20680    #[test]
20681    fn merge_asof_rejects_incompatible_key_dtypes_sopel() {
20682        use super::{AsofDirection, MergeAsofOptions};
20683
20684        // pandas 2.2.3: a NaN makes the left `time` column float64, and
20685        // `merge_asof` refuses it against an int64 right key rather than
20686        // coercing both to a common numeric lane.
20687        let left = fp_frame::DataFrame::from_dict(
20688            &["time", "left_val", "group"],
20689            vec![
20690                (
20691                    "time",
20692                    vec![
20693                        Scalar::Float64(1.0),
20694                        Scalar::Null(NullKind::NaN),
20695                        Scalar::Float64(4.0),
20696                    ],
20697                ),
20698                (
20699                    "left_val",
20700                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
20701                ),
20702                (
20703                    "group",
20704                    vec![
20705                        Scalar::Utf8("a".into()),
20706                        Scalar::Utf8("a".into()),
20707                        Scalar::Utf8("a".into()),
20708                    ],
20709                ),
20710            ],
20711        )
20712        .unwrap();
20713        let right = fp_frame::DataFrame::from_dict(
20714            &["time", "right_val", "group"],
20715            vec![
20716                ("time", vec![Scalar::Int64(1), Scalar::Int64(3)]),
20717                ("right_val", vec![Scalar::Int64(100), Scalar::Int64(300)]),
20718                (
20719                    "group",
20720                    vec![Scalar::Utf8("a".into()), Scalar::Utf8("a".into())],
20721                ),
20722            ],
20723        )
20724        .unwrap();
20725
20726        for options in [
20727            MergeAsofOptions::new(),
20728            MergeAsofOptions::new().by(vec!["group".to_owned()]),
20729        ] {
20730            let error = super::merge_asof_with_options(
20731                &left,
20732                &right,
20733                "time",
20734                AsofDirection::Backward,
20735                options,
20736            )
20737            .expect_err("mixed float64/int64 asof keys must be rejected");
20738            assert!(matches!(
20739                error,
20740                super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(message))
20741                    if message.contains("incompatible merge keys")
20742                        && message.contains("float64")
20743                        && message.contains("int64")
20744            ));
20745        }
20746
20747        // This is the fixture-shaped representation: the null marker makes
20748        // the left lane nullable Int64, while the all-valid right lane stays
20749        // numpy int64. pandas rejects that pair as incompatible too.
20750        let mut nullable_columns = ColumnStore::new();
20751        nullable_columns.insert(
20752            "time".to_owned(),
20753            Column::new(
20754                DType::Int64Nullable,
20755                vec![
20756                    Scalar::Int64(1),
20757                    Scalar::Null(NullKind::NaN),
20758                    Scalar::Int64(4),
20759                ],
20760            )
20761            .unwrap(),
20762        );
20763        nullable_columns.insert(
20764            "left_val".to_owned(),
20765            Column::from_i64_values(vec![10, 20, 30]),
20766        );
20767        let nullable_left = fp_frame::DataFrame::new_with_column_order(
20768            Index::new_known_unique_int64_unit_range(0, 3),
20769            nullable_columns,
20770            vec!["time".to_owned(), "left_val".to_owned()],
20771        )
20772        .unwrap();
20773        let error = super::merge_asof(&nullable_left, &right, "time", AsofDirection::Backward)
20774            .expect_err("nullable Int64 and int64 asof keys must be rejected");
20775        assert!(matches!(
20776            error,
20777            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(message))
20778                if message.contains("incompatible merge keys")
20779                    && message.contains("left dtype('Int64')")
20780                    && message.contains("right dtype('int64')")
20781        ));
20782    }
20783
20784    #[test]
20785    fn merge_asof_nan_in_right_key() {
20786        use super::AsofDirection;
20787
20788        // Symmetric to merge_asof_nan_in_key: NaN keys on the right side
20789        // also get treated as no-candidate (pandas does NOT raise). Other
20790        // left rows still match to non-NaN right rows.
20791        let left = fp_frame::DataFrame::from_dict(
20792            &["time", "val"],
20793            vec![
20794                (
20795                    "time",
20796                    vec![Scalar::Int64(1), Scalar::Int64(3), Scalar::Int64(5)],
20797                ),
20798                (
20799                    "val",
20800                    vec![
20801                        Scalar::Float64(10.0),
20802                        Scalar::Float64(20.0),
20803                        Scalar::Float64(30.0),
20804                    ],
20805                ),
20806            ],
20807        )
20808        .unwrap();
20809
20810        let right = fp_frame::DataFrame::from_dict(
20811            &["time", "quote"],
20812            vec![
20813                (
20814                    "time",
20815                    vec![
20816                        Scalar::Int64(2),
20817                        Scalar::Null(NullKind::NaN),
20818                        Scalar::Int64(4),
20819                    ],
20820                ),
20821                (
20822                    "quote",
20823                    vec![
20824                        Scalar::Float64(200.0),
20825                        Scalar::Float64(999.0),
20826                        Scalar::Float64(400.0),
20827                    ],
20828                ),
20829            ],
20830        )
20831        .unwrap();
20832
20833        let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
20834        // left time=1 → no right ≤ 1 → null
20835        assert!(result.columns.get("quote").unwrap().values()[0].is_missing());
20836        // left time=3 → right time=2 → 200.0 (NaN right row never matches)
20837        assert_eq!(
20838            result.columns.get("quote").unwrap().values()[1],
20839            Scalar::Float64(200.0)
20840        );
20841        // left time=5 → right time=4 → 400.0
20842        assert_eq!(
20843            result.columns.get("quote").unwrap().values()[2],
20844            Scalar::Float64(400.0)
20845        );
20846    }
20847
20848    #[test]
20849    fn merge_asof_overlapping_columns_apply_suffixes() {
20850        use super::AsofDirection;
20851
20852        let left = fp_frame::DataFrame::from_dict(
20853            &["time", "shared", "left_only"],
20854            vec![
20855                ("time", vec![Scalar::Int64(1), Scalar::Int64(2)]),
20856                ("shared", vec![Scalar::Int64(10), Scalar::Int64(20)]),
20857                ("left_only", vec![Scalar::Int64(1), Scalar::Int64(2)]),
20858            ],
20859        )
20860        .unwrap();
20861
20862        let right = fp_frame::DataFrame::from_dict(
20863            &["time", "shared", "right_only"],
20864            vec![
20865                ("time", vec![Scalar::Int64(1), Scalar::Int64(2)]),
20866                ("shared", vec![Scalar::Int64(100), Scalar::Int64(200)]),
20867                ("right_only", vec![Scalar::Int64(9), Scalar::Int64(8)]),
20868            ],
20869        )
20870        .unwrap();
20871
20872        let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
20873        let shared_left = result.columns.get("shared_x").unwrap().values();
20874        let shared_right = result.columns.get("shared_y").unwrap().values();
20875
20876        assert_eq!(shared_left[0], Scalar::Int64(10));
20877        assert_eq!(shared_left[1], Scalar::Int64(20));
20878        assert_eq!(shared_right[0], Scalar::Int64(100));
20879        assert_eq!(shared_right[1], Scalar::Int64(200));
20880    }
20881
20882    #[test]
20883    fn merge_asof_duplicate_column_gets_suffix() {
20884        use super::AsofDirection;
20885
20886        // Both left and right have a "val" column besides the key.
20887        let left = fp_frame::DataFrame::from_dict(
20888            &["time", "val"],
20889            vec![
20890                ("time", vec![Scalar::Int64(1)]),
20891                ("val", vec![Scalar::Float64(10.0)]),
20892            ],
20893        )
20894        .unwrap();
20895
20896        let right = fp_frame::DataFrame::from_dict(
20897            &["time", "val"],
20898            vec![
20899                ("time", vec![Scalar::Int64(1)]),
20900                ("val", vec![Scalar::Float64(99.0)]),
20901            ],
20902        )
20903        .unwrap();
20904
20905        let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
20906        // Overlapping columns should receive default merge suffixes.
20907        assert!(result.columns.contains_key("val_x"));
20908        assert!(result.columns.contains_key("val_y"));
20909        assert_eq!(
20910            result.columns.get("val_x").unwrap().values()[0],
20911            Scalar::Float64(10.0)
20912        );
20913        assert_eq!(
20914            result.columns.get("val_y").unwrap().values()[0],
20915            Scalar::Float64(99.0)
20916        );
20917    }
20918
20919    #[test]
20920    fn merge_asof_missing_column_errors() {
20921        use super::AsofDirection;
20922
20923        let left =
20924            fp_frame::DataFrame::from_dict(&["a"], vec![("a", vec![Scalar::Int64(1)])]).unwrap();
20925
20926        let right =
20927            fp_frame::DataFrame::from_dict(&["b"], vec![("b", vec![Scalar::Int64(1)])]).unwrap();
20928
20929        let err = super::merge_asof(&left, &right, "time", AsofDirection::Backward);
20930        assert!(err.is_err());
20931    }
20932
20933    #[test]
20934    fn merge_asof_invalid_direction_errors() {
20935        let left =
20936            fp_frame::DataFrame::from_dict(&["time"], vec![("time", vec![Scalar::Int64(1)])])
20937                .unwrap();
20938        let right =
20939            fp_frame::DataFrame::from_dict(&["time"], vec![("time", vec![Scalar::Int64(1)])])
20940                .unwrap();
20941
20942        let err = left.merge_asof(&right, "time", "sideways");
20943        assert!(matches!(
20944            err,
20945            Err(super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(msg)))
20946                if msg.contains("invalid direction")
20947        ));
20948    }
20949
20950    #[test]
20951    fn merge_asof_unsorted_left_errors() {
20952        use super::AsofDirection;
20953
20954        let left = fp_frame::DataFrame::from_dict(
20955            &["time", "val"],
20956            vec![
20957                ("time", vec![Scalar::Int64(2), Scalar::Int64(1)]),
20958                ("val", vec![Scalar::Float64(10.0), Scalar::Float64(20.0)]),
20959            ],
20960        )
20961        .unwrap();
20962
20963        let right = fp_frame::DataFrame::from_dict(
20964            &["time", "quote"],
20965            vec![
20966                ("time", vec![Scalar::Int64(1), Scalar::Int64(2)]),
20967                (
20968                    "quote",
20969                    vec![Scalar::Float64(100.0), Scalar::Float64(200.0)],
20970                ),
20971            ],
20972        )
20973        .unwrap();
20974
20975        let err = super::merge_asof(&left, &right, "time", AsofDirection::Backward)
20976            .expect_err("unsorted left should error");
20977        assert!(matches!(
20978            err,
20979            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(msg))
20980                if msg.contains("sorted")
20981        ));
20982    }
20983
20984    #[test]
20985    fn merge_asof_unsorted_right_errors() {
20986        use super::AsofDirection;
20987
20988        let left = fp_frame::DataFrame::from_dict(
20989            &["time", "val"],
20990            vec![
20991                ("time", vec![Scalar::Int64(1), Scalar::Int64(2)]),
20992                ("val", vec![Scalar::Float64(10.0), Scalar::Float64(20.0)]),
20993            ],
20994        )
20995        .unwrap();
20996
20997        let right = fp_frame::DataFrame::from_dict(
20998            &["time", "quote"],
20999            vec![
21000                ("time", vec![Scalar::Int64(2), Scalar::Int64(1)]),
21001                (
21002                    "quote",
21003                    vec![Scalar::Float64(200.0), Scalar::Float64(100.0)],
21004                ),
21005            ],
21006        )
21007        .unwrap();
21008
21009        let err = super::merge_asof(&left, &right, "time", AsofDirection::Backward)
21010            .expect_err("unsorted right should error");
21011        assert!(matches!(
21012            err,
21013            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(msg))
21014                if msg.contains("sorted")
21015        ));
21016    }
21017
21018    #[test]
21019    fn merge_asof_non_numeric_key_errors() {
21020        use super::AsofDirection;
21021
21022        let left = fp_frame::DataFrame::from_dict(
21023            &["time", "val"],
21024            vec![
21025                ("time", vec![Scalar::Utf8("a".into())]),
21026                ("val", vec![Scalar::Float64(10.0)]),
21027            ],
21028        )
21029        .unwrap();
21030
21031        let right = fp_frame::DataFrame::from_dict(
21032            &["time", "quote"],
21033            vec![
21034                ("time", vec![Scalar::Utf8("b".into())]),
21035                ("quote", vec![Scalar::Float64(20.0)]),
21036            ],
21037        )
21038        .unwrap();
21039
21040        let err = super::merge_asof(&left, &right, "time", AsofDirection::Backward)
21041            .expect_err("non-numeric key should error");
21042        assert!(matches!(
21043            err,
21044            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(msg))
21045                if msg.contains("numeric")
21046        ));
21047    }
21048
21049    #[test]
21050    fn merge_asof_preserves_all_left_rows() {
21051        use super::AsofDirection;
21052
21053        let left = fp_frame::DataFrame::from_dict(
21054            &["time", "val"],
21055            vec![
21056                (
21057                    "time",
21058                    vec![
21059                        Scalar::Int64(1),
21060                        Scalar::Int64(2),
21061                        Scalar::Int64(3),
21062                        Scalar::Int64(4),
21063                        Scalar::Int64(5),
21064                    ],
21065                ),
21066                (
21067                    "val",
21068                    vec![
21069                        Scalar::Float64(10.0),
21070                        Scalar::Float64(20.0),
21071                        Scalar::Float64(30.0),
21072                        Scalar::Float64(40.0),
21073                        Scalar::Float64(50.0),
21074                    ],
21075                ),
21076            ],
21077        )
21078        .unwrap();
21079
21080        let right = fp_frame::DataFrame::from_dict(
21081            &["time", "quote"],
21082            vec![
21083                ("time", vec![Scalar::Int64(3)]),
21084                ("quote", vec![Scalar::Float64(300.0)]),
21085            ],
21086        )
21087        .unwrap();
21088
21089        let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
21090        // All 5 left rows should be present.
21091        assert_eq!(result.index.len(), 5);
21092    }
21093
21094    // ── merge_asof options tests ──
21095
21096    #[test]
21097    fn merge_asof_allow_exact_matches_false_backward() {
21098        use super::{AsofDirection, MergeAsofOptions, merge_asof_with_options};
21099
21100        // Left: keys 1, 2, 3
21101        let left = fp_frame::DataFrame::from_dict(
21102            &["time", "val"],
21103            vec![
21104                (
21105                    "time",
21106                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
21107                ),
21108                (
21109                    "val",
21110                    vec![
21111                        Scalar::Float64(10.0),
21112                        Scalar::Float64(20.0),
21113                        Scalar::Float64(30.0),
21114                    ],
21115                ),
21116            ],
21117        )
21118        .unwrap();
21119
21120        // Right: keys 1, 2, 3 (exact matches exist)
21121        let right = fp_frame::DataFrame::from_dict(
21122            &["time", "quote"],
21123            vec![
21124                (
21125                    "time",
21126                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
21127                ),
21128                (
21129                    "quote",
21130                    vec![
21131                        Scalar::Float64(100.0),
21132                        Scalar::Float64(200.0),
21133                        Scalar::Float64(300.0),
21134                    ],
21135                ),
21136            ],
21137        )
21138        .unwrap();
21139
21140        // With allow_exact_matches=true (default), all should match
21141        let result_with_exact = merge_asof_with_options(
21142            &left,
21143            &right,
21144            "time",
21145            AsofDirection::Backward,
21146            MergeAsofOptions::new(),
21147        )
21148        .unwrap();
21149
21150        let quote_col = result_with_exact.columns.get("quote").unwrap();
21151        assert_eq!(quote_col.values()[0], Scalar::Float64(100.0)); // 1 matches 1
21152        assert_eq!(quote_col.values()[1], Scalar::Float64(200.0)); // 2 matches 2
21153        assert_eq!(quote_col.values()[2], Scalar::Float64(300.0)); // 3 matches 3
21154
21155        // With allow_exact_matches=false, exact matches should be excluded
21156        let result_no_exact = merge_asof_with_options(
21157            &left,
21158            &right,
21159            "time",
21160            AsofDirection::Backward,
21161            MergeAsofOptions::new().allow_exact_matches(false),
21162        )
21163        .unwrap();
21164
21165        let quote_col_no_exact = result_no_exact.columns.get("quote").unwrap();
21166        // 1 has no previous right key, should be null
21167        assert!(matches!(quote_col_no_exact.values()[0], Scalar::Null(_)));
21168        // 2 should match previous (1)
21169        assert_eq!(quote_col_no_exact.values()[1], Scalar::Float64(100.0));
21170        // 3 should match previous (2)
21171        assert_eq!(quote_col_no_exact.values()[2], Scalar::Float64(200.0));
21172    }
21173
21174    #[test]
21175    fn merge_asof_tolerance() {
21176        use super::{AsofDirection, MergeAsofOptions, merge_asof_with_options};
21177
21178        // Left: keys 1, 5, 10
21179        let left = fp_frame::DataFrame::from_dict(
21180            &["time", "val"],
21181            vec![
21182                (
21183                    "time",
21184                    vec![Scalar::Int64(1), Scalar::Int64(5), Scalar::Int64(10)],
21185                ),
21186                (
21187                    "val",
21188                    vec![
21189                        Scalar::Float64(10.0),
21190                        Scalar::Float64(50.0),
21191                        Scalar::Float64(100.0),
21192                    ],
21193                ),
21194            ],
21195        )
21196        .unwrap();
21197
21198        // Right: keys 2, 6
21199        let right = fp_frame::DataFrame::from_dict(
21200            &["time", "quote"],
21201            vec![
21202                ("time", vec![Scalar::Int64(2), Scalar::Int64(6)]),
21203                (
21204                    "quote",
21205                    vec![Scalar::Float64(200.0), Scalar::Float64(600.0)],
21206                ),
21207            ],
21208        )
21209        .unwrap();
21210
21211        // With tolerance=2, matches within 2 units are valid
21212        let result = merge_asof_with_options(
21213            &left,
21214            &right,
21215            "time",
21216            AsofDirection::Backward,
21217            MergeAsofOptions::new().tolerance(2.0),
21218        )
21219        .unwrap();
21220
21221        let quote_col = result.columns.get("quote").unwrap();
21222        // 1 < 2, no previous match, null
21223        assert!(matches!(quote_col.values()[0], Scalar::Null(_)));
21224        // 5 finds 2 (diff = 3), but tolerance is 2, so null
21225        assert!(matches!(quote_col.values()[1], Scalar::Null(_)));
21226        // 10 finds 6 (diff = 4), but tolerance is 2, so null
21227        assert!(matches!(quote_col.values()[2], Scalar::Null(_)));
21228
21229        // With tolerance=5, all should match
21230        let result_wider = merge_asof_with_options(
21231            &left,
21232            &right,
21233            "time",
21234            AsofDirection::Backward,
21235            MergeAsofOptions::new().tolerance(5.0),
21236        )
21237        .unwrap();
21238
21239        let quote_col_wider = result_wider.columns.get("quote").unwrap();
21240        // 1 < 2, still no previous
21241        assert!(matches!(quote_col_wider.values()[0], Scalar::Null(_)));
21242        // 5 finds 2 (diff = 3 <= 5)
21243        assert_eq!(quote_col_wider.values()[1], Scalar::Float64(200.0));
21244        // 10 finds 6 (diff = 4 <= 5)
21245        assert_eq!(quote_col_wider.values()[2], Scalar::Float64(600.0));
21246    }
21247
21248    #[test]
21249    fn merge_asof_by_column() {
21250        use super::{AsofDirection, MergeAsofOptions, merge_asof_with_options};
21251
21252        // Left: two groups (A and B), each with times
21253        let left = fp_frame::DataFrame::from_dict(
21254            &["group", "time", "val"],
21255            vec![
21256                (
21257                    "group",
21258                    vec![
21259                        Scalar::Utf8("A".into()),
21260                        Scalar::Utf8("A".into()),
21261                        Scalar::Utf8("B".into()),
21262                        Scalar::Utf8("B".into()),
21263                    ],
21264                ),
21265                (
21266                    "time",
21267                    vec![
21268                        Scalar::Int64(1),
21269                        Scalar::Int64(2),
21270                        Scalar::Int64(3),
21271                        Scalar::Int64(4),
21272                    ],
21273                ),
21274                (
21275                    "val",
21276                    vec![
21277                        Scalar::Float64(10.0),
21278                        Scalar::Float64(30.0),
21279                        Scalar::Float64(20.0),
21280                        Scalar::Float64(40.0),
21281                    ],
21282                ),
21283            ],
21284        )
21285        .unwrap();
21286
21287        // Right: same groups with quotes
21288        let right = fp_frame::DataFrame::from_dict(
21289            &["group", "time", "quote"],
21290            vec![
21291                (
21292                    "group",
21293                    vec![
21294                        Scalar::Utf8("A".into()),
21295                        Scalar::Utf8("B".into()),
21296                        Scalar::Utf8("A".into()),
21297                    ],
21298                ),
21299                (
21300                    "time",
21301                    vec![Scalar::Int64(2), Scalar::Int64(3), Scalar::Int64(4)],
21302                ),
21303                (
21304                    "quote",
21305                    vec![
21306                        Scalar::Float64(200.0),
21307                        Scalar::Float64(400.0),
21308                        Scalar::Float64(300.0),
21309                    ],
21310                ),
21311            ],
21312        )
21313        .unwrap();
21314
21315        // Merge with 'by' column
21316        let result = merge_asof_with_options(
21317            &left,
21318            &right,
21319            "time",
21320            AsofDirection::Backward,
21321            MergeAsofOptions::new().by(vec!["group".to_string()]),
21322        )
21323        .unwrap();
21324
21325        let quote_col = result.columns.get("quote").unwrap();
21326        // Left after 2d3338b1's reorder is (A,1), (A,2), (B,3), (B,4) — globally
21327        // sorted by time. Right is (A,2), (B,3), (A,4). Backward grouped asof:
21328        // Row 0: (A,1) → no right A with time <= 1 → null
21329        assert!(matches!(quote_col.values()[0], Scalar::Null(_)));
21330        // Row 1: (A,2) → right A time=2 → 200.0
21331        assert_eq!(quote_col.values()[1], Scalar::Float64(200.0));
21332        // Row 2: (B,3) → right B time=3 → 400.0
21333        assert_eq!(quote_col.values()[2], Scalar::Float64(400.0));
21334        // Row 3: (B,4) → right B time=3 (latest <= 4) → 400.0
21335        assert_eq!(quote_col.values()[3], Scalar::Float64(400.0));
21336    }
21337
21338    #[test]
21339    fn merge_asof_by_column_requires_globally_sorted_left_keys() {
21340        use super::{AsofDirection, MergeAsofOptions, merge_asof_with_options};
21341
21342        let left = fp_frame::DataFrame::from_dict(
21343            &["group", "time"],
21344            vec![
21345                (
21346                    "group",
21347                    vec![
21348                        Scalar::Utf8("A".into()),
21349                        Scalar::Utf8("A".into()),
21350                        Scalar::Utf8("B".into()),
21351                        Scalar::Utf8("B".into()),
21352                    ],
21353                ),
21354                (
21355                    "time",
21356                    vec![
21357                        Scalar::Int64(1),
21358                        Scalar::Int64(3),
21359                        Scalar::Int64(1),
21360                        Scalar::Int64(2),
21361                    ],
21362                ),
21363            ],
21364        )
21365        .unwrap();
21366        let right = fp_frame::DataFrame::from_dict(
21367            &["group", "time", "quote"],
21368            vec![
21369                (
21370                    "group",
21371                    vec![
21372                        Scalar::Utf8("A".into()),
21373                        Scalar::Utf8("B".into()),
21374                        Scalar::Utf8("A".into()),
21375                    ],
21376                ),
21377                (
21378                    "time",
21379                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
21380                ),
21381                (
21382                    "quote",
21383                    vec![
21384                        Scalar::Float64(10.0),
21385                        Scalar::Float64(20.0),
21386                        Scalar::Float64(30.0),
21387                    ],
21388                ),
21389            ],
21390        )
21391        .unwrap();
21392
21393        let err = merge_asof_with_options(
21394            &left,
21395            &right,
21396            "time",
21397            AsofDirection::Backward,
21398            MergeAsofOptions::new().by(vec!["group".to_string()]),
21399        )
21400        .expect_err("pandas requires globally sorted left keys even with by=");
21401        assert!(matches!(
21402            err,
21403            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(message))
21404                if message.contains("left") && message.contains("sorted")
21405        ));
21406    }
21407
21408    #[test]
21409    fn merge_asof_by_column_requires_globally_sorted_right_keys() {
21410        use super::{AsofDirection, MergeAsofOptions, merge_asof_with_options};
21411
21412        let left = fp_frame::DataFrame::from_dict(
21413            &["group", "time"],
21414            vec![
21415                (
21416                    "group",
21417                    vec![
21418                        Scalar::Utf8("A".into()),
21419                        Scalar::Utf8("B".into()),
21420                        Scalar::Utf8("A".into()),
21421                    ],
21422                ),
21423                (
21424                    "time",
21425                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
21426                ),
21427            ],
21428        )
21429        .unwrap();
21430        let right = fp_frame::DataFrame::from_dict(
21431            &["group", "time", "quote"],
21432            vec![
21433                (
21434                    "group",
21435                    vec![
21436                        Scalar::Utf8("A".into()),
21437                        Scalar::Utf8("A".into()),
21438                        Scalar::Utf8("B".into()),
21439                    ],
21440                ),
21441                (
21442                    "time",
21443                    vec![Scalar::Int64(1), Scalar::Int64(3), Scalar::Int64(2)],
21444                ),
21445                (
21446                    "quote",
21447                    vec![
21448                        Scalar::Float64(10.0),
21449                        Scalar::Float64(30.0),
21450                        Scalar::Float64(20.0),
21451                    ],
21452                ),
21453            ],
21454        )
21455        .unwrap();
21456
21457        let err = merge_asof_with_options(
21458            &left,
21459            &right,
21460            "time",
21461            AsofDirection::Backward,
21462            MergeAsofOptions::new().by(vec!["group".to_string()]),
21463        )
21464        .expect_err("pandas requires globally sorted right keys even with by=");
21465        assert!(matches!(
21466            err,
21467            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(message))
21468                if message.contains("right") && message.contains("sorted")
21469        ));
21470    }
21471
21472    #[test]
21473    fn merge_ordered_sorts_and_ffills_values() {
21474        let left = fp_frame::DataFrame::from_dict(
21475            &["date", "left_val"],
21476            vec![
21477                ("date", vec![Scalar::Int64(1), Scalar::Int64(3)]),
21478                ("left_val", vec![Scalar::Int64(10), Scalar::Int64(30)]),
21479            ],
21480        )
21481        .unwrap();
21482
21483        let right = fp_frame::DataFrame::from_dict(
21484            &["date", "right_val"],
21485            vec![
21486                ("date", vec![Scalar::Int64(2), Scalar::Int64(3)]),
21487                ("right_val", vec![Scalar::Int64(200), Scalar::Int64(300)]),
21488            ],
21489        )
21490        .unwrap();
21491
21492        let result = super::merge_ordered(&left, &right, &["date"], Some("ffill")).unwrap();
21493        let frame = fp_frame::DataFrame::new(result.index, result.columns).unwrap();
21494
21495        assert_eq!(
21496            frame.column("date").unwrap().values(),
21497            &[Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)]
21498        );
21499        // TEST-CHANGE (hayfo): left_val is int64, as live pandas 2.2.3's
21500        // (it asserted the float64 the value fill left behind).
21501        assert_eq!(
21502            frame.column("left_val").unwrap().values(),
21503            &[Scalar::Int64(10), Scalar::Int64(10), Scalar::Int64(30)]
21504        );
21505        // NEGATIVE: a leading gap stays NaN, so the column stays float64.
21506        assert_eq!(
21507            frame.column("right_val").unwrap().values(),
21508            &[
21509                Scalar::Null(NullKind::NaN),
21510                Scalar::Float64(200.0),
21511                Scalar::Float64(300.0),
21512            ]
21513        );
21514    }
21515
21516    /// A filled bool column stays bool, a suffixed overlap its side's int64
21517    /// (live pandas 2.2.3: v bool, s_x int64, s_y float64).
21518    #[test]
21519    fn merge_ordered_ffill_keeps_each_sides_dtype() {
21520        let left = fp_frame::DataFrame::from_dict(
21521            &["k", "v", "s"],
21522            vec![
21523                ("k", vec![Scalar::Int64(1), Scalar::Int64(3)]),
21524                ("v", vec![Scalar::Bool(true), Scalar::Bool(false)]),
21525                ("s", vec![Scalar::Int64(1), Scalar::Int64(2)]),
21526            ],
21527        )
21528        .unwrap();
21529        let right = fp_frame::DataFrame::from_dict(
21530            &["k", "s"],
21531            vec![
21532                ("k", vec![Scalar::Int64(2), Scalar::Int64(3)]),
21533                ("s", vec![Scalar::Int64(5), Scalar::Int64(6)]),
21534            ],
21535        )
21536        .unwrap();
21537        let result = super::merge_ordered(&left, &right, &["k"], Some("ffill")).unwrap();
21538        let frame = fp_frame::DataFrame::new(result.index, result.columns).unwrap();
21539        assert_eq!(
21540            frame.column("v").unwrap().values(),
21541            &[Scalar::Bool(true), Scalar::Bool(true), Scalar::Bool(false)]
21542        );
21543        assert_eq!(
21544            frame.column("s_x").unwrap().values(),
21545            &[Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(2)]
21546        );
21547        assert_eq!(frame.column("s_y").unwrap().dtype(), DType::Float64);
21548    }
21549
21550    #[test]
21551    fn merge_ordered_invalid_fill_method_errors() {
21552        let left = fp_frame::DataFrame::from_dict(
21553            &["date", "left_val"],
21554            vec![
21555                ("date", vec![Scalar::Int64(1)]),
21556                ("left_val", vec![Scalar::Int64(10)]),
21557            ],
21558        )
21559        .unwrap();
21560
21561        let right = fp_frame::DataFrame::from_dict(
21562            &["date", "right_val"],
21563            vec![
21564                ("date", vec![Scalar::Int64(2)]),
21565                ("right_val", vec![Scalar::Int64(200)]),
21566            ],
21567        )
21568        .unwrap();
21569
21570        let err = super::merge_ordered(&left, &right, &["date"], Some("sideways"))
21571            .expect_err("invalid fill method should error");
21572        assert!(matches!(
21573            err,
21574            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(message))
21575                if message.contains("fill_method must be 'ffill' or None")
21576        ));
21577    }
21578
21579    #[test]
21580    fn merge_ordered_rejects_bfill_like_pandas() {
21581        let left = fp_frame::DataFrame::from_dict(
21582            &["date", "left_val"],
21583            vec![
21584                ("date", vec![Scalar::Int64(1), Scalar::Int64(3)]),
21585                ("left_val", vec![Scalar::Int64(10), Scalar::Int64(30)]),
21586            ],
21587        )
21588        .unwrap();
21589
21590        let right = fp_frame::DataFrame::from_dict(
21591            &["date", "right_val"],
21592            vec![
21593                ("date", vec![Scalar::Int64(2), Scalar::Int64(3)]),
21594                ("right_val", vec![Scalar::Int64(200), Scalar::Int64(300)]),
21595            ],
21596        )
21597        .unwrap();
21598
21599        let err = super::merge_ordered(&left, &right, &["date"], Some("bfill"))
21600            .expect_err("pandas only accepts fill_method='ffill' or None");
21601        assert!(matches!(
21602            err,
21603            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(message))
21604                if message.contains("fill_method must be 'ffill' or None")
21605        ));
21606    }
21607
21608    // ── join() pandas-named alias (br-frankenpandas-nk54a) ──────────────
21609
21610    #[test]
21611    fn dataframe_join_aliases_join_on_index() {
21612        use std::collections::BTreeMap;
21613
21614        use fp_columnar::Column;
21615        use fp_frame::DataFrame;
21616        use fp_index::Index;
21617        use fp_types::{DType, Scalar};
21618
21619        use super::DataFrameMergeExt;
21620
21621        fn build(name1: &str, name2: &str, vals1: &[i64], vals2: &[i64]) -> DataFrame {
21622            let mut cols = BTreeMap::new();
21623            cols.insert(
21624                name1.to_owned(),
21625                Column::new(
21626                    DType::Int64,
21627                    vals1.iter().map(|v| Scalar::Int64(*v)).collect(),
21628                )
21629                .unwrap(),
21630            );
21631            cols.insert(
21632                name2.to_owned(),
21633                Column::new(
21634                    DType::Int64,
21635                    vals2.iter().map(|v| Scalar::Int64(*v)).collect(),
21636                )
21637                .unwrap(),
21638            );
21639            DataFrame::new_with_column_order(
21640                Index::new(
21641                    (0..vals1.len() as i64)
21642                        .map(fp_index::IndexLabel::Int64)
21643                        .collect(),
21644                ),
21645                cols,
21646                vec![name1.to_owned(), name2.to_owned()],
21647            )
21648            .unwrap()
21649        }
21650
21651        let left = build("a", "b", &[10, 20, 30], &[1, 2, 3]);
21652        let right = build("c", "d", &[100, 200, 300], &[7, 8, 9]);
21653
21654        let via_join = left.join(&right, super::JoinType::Inner).unwrap();
21655        let via_join_on_index = left.join_on_index(&right, super::JoinType::Inner).unwrap();
21656
21657        // Both produce the same MergedDataFrame shape & values.
21658        let join_keys: Vec<&String> = via_join.columns.keys().collect();
21659        let idx_keys: Vec<&String> = via_join_on_index.columns.keys().collect();
21660        assert_eq!(join_keys, idx_keys);
21661        assert_eq!(via_join.index, via_join_on_index.index);
21662        for k in via_join.columns.keys() {
21663            assert_eq!(
21664                via_join.columns.get(k).unwrap().values(),
21665                via_join_on_index.columns.get(k).unwrap().values(),
21666                "column {k} differs"
21667            );
21668        }
21669    }
21670}
21671
21672#[cfg(test)]
21673mod typed_validate_cardinality_uza04 {
21674    //! `validate=` must stop costing the whole fast-path family.
21675    //!
21676    //! br-frankenpandas-uza04. `validate_merge_cardinality` lives in exactly
21677    //! one place — the generic `collect_composite_keys` branch — so
21678    //! `validate_mode_allows_fast_positions` returned false for every enforcing
21679    //! mode purely to route execution there. Asking for a cardinality guarantee
21680    //! therefore disabled `dense_packed_int64_inner_positions`, the typed
21681    //! two-key and multi-key position paths, and the single-key inner/left
21682    //! shortcuts, and additionally built a `Vec<CompositeJoinKey>` off
21683    //! `column.values()[row]` on both sides.
21684    //!
21685    //! `typed_validate_merge_cardinality` settles the common shape (one
21686    //! all-valid Int64 key) off the raw buffer, so a PASSING validation lets
21687    //! the merge take the same path it would have taken with no `validate=`.
21688    //! These tests pin the two things that has to preserve: the rejections, and
21689    //! the output.
21690
21691    use fp_columnar::Column;
21692    use fp_frame::DataFrame;
21693    use fp_index::Index;
21694    use fp_types::{NullKind, Scalar};
21695
21696    use super::{
21697        JoinType, MergeExecutionOptions, MergeValidateMode, merge_dataframes_on_with_options,
21698        typed_single_int64_key_has_duplicates,
21699    };
21700
21701    fn int_frame(name: &str, keys: Vec<i64>, payload: Vec<i64>) -> DataFrame {
21702        let index = Index::new_known_unique_int64_unit_range(0, keys.len());
21703        DataFrame::new_with_column_order(
21704            index,
21705            std::collections::BTreeMap::from([
21706                ("id".to_owned(), Column::from_i64_values(keys)),
21707                (name.to_owned(), Column::from_i64_values(payload)),
21708            ]),
21709            vec!["id".to_owned(), name.to_owned()],
21710        )
21711        .expect("typed int frame")
21712    }
21713
21714    fn merge(
21715        left: &DataFrame,
21716        right: &DataFrame,
21717        validate: Option<MergeValidateMode>,
21718    ) -> Result<super::MergedDataFrame, super::JoinError> {
21719        merge_dataframes_on_with_options(
21720            left,
21721            right,
21722            &["id"],
21723            &["id"],
21724            JoinType::Inner,
21725            MergeExecutionOptions {
21726                validate_mode: validate,
21727                ..MergeExecutionOptions::default()
21728            },
21729        )
21730    }
21731
21732    /// THE DUPLICATE-KEY NEGATIVE CASE. The typed checker is now what rejects a
21733    /// non-unique left key under `one_to_many`, so it has to reject with the
21734    /// same message the generic checker produced — a caller cannot tell which
21735    /// one ran.
21736    #[test]
21737    fn duplicate_left_keys_still_reject_under_one_to_many_uza04() {
21738        let left = int_frame("left_v", vec![1, 2, 2, 3], vec![10, 20, 21, 30]);
21739        let right = int_frame("right_v", vec![1, 2, 3], vec![100, 200, 300]);
21740        let error = merge(&left, &right, Some(MergeValidateMode::OneToMany))
21741            .expect_err("duplicate left keys must be rejected");
21742        assert!(
21743            format!("{error}")
21744                .contains("merge validate='one_to_many' failed: left keys are not unique"),
21745            "message must match the generic checker exactly, got: {error}"
21746        );
21747    }
21748
21749    #[test]
21750    fn duplicate_right_keys_still_reject_under_many_to_one_uza04() {
21751        let left = int_frame("left_v", vec![1, 2, 3], vec![10, 20, 30]);
21752        let right = int_frame("right_v", vec![1, 2, 2], vec![100, 200, 201]);
21753        let error = merge(&left, &right, Some(MergeValidateMode::ManyToOne))
21754            .expect_err("duplicate right keys must be rejected");
21755        assert!(
21756            format!("{error}")
21757                .contains("merge validate='many_to_one' failed: right keys are not unique"),
21758            "message must match the generic checker exactly, got: {error}"
21759        );
21760    }
21761
21762    /// PRECEDENCE. With BOTH sides duplicated under `one_to_one`, pandas —
21763    /// and the generic checker — name BOTH sides ('not unique in either left
21764    /// or right dataset'; this pinned a left-first report pandas 2.2.3 does
21765    /// not make, z6jxh). The typed checker must not answer from whichever
21766    /// side it happened to inspect first.
21767    #[test]
21768    fn one_to_one_names_both_sides_when_both_repeat_uza04() {
21769        let left = int_frame("left_v", vec![1, 1, 2], vec![10, 11, 20]);
21770        let right = int_frame("right_v", vec![1, 1, 2], vec![100, 101, 200]);
21771        let error = merge(&left, &right, Some(MergeValidateMode::OneToOne))
21772            .expect_err("both sides duplicated must be rejected");
21773        let message = format!("{error}");
21774        assert!(
21775            message.contains("left and right keys are not unique"),
21776            "both sides must be named, got: {message}"
21777        );
21778    }
21779
21780    #[test]
21781    fn one_to_one_still_catches_a_right_only_duplicate_uza04() {
21782        let left = int_frame("left_v", vec![1, 2, 3], vec![10, 20, 30]);
21783        let right = int_frame("right_v", vec![1, 2, 2], vec![100, 200, 201]);
21784        let error = merge(&left, &right, Some(MergeValidateMode::OneToOne))
21785            .expect_err("right duplicate must be rejected");
21786        assert!(
21787            format!("{error}")
21788                .contains("merge validate='one_to_one' failed: right keys are not unique"),
21789            "got: {error}"
21790        );
21791    }
21792
21793    /// THE SAFETY PROPERTY OF THE WHOLE LEVER: a validation that PASSES must
21794    /// leave the merge output byte-identical to the unvalidated merge, because
21795    /// it now takes the same fast path. If enabling those paths changed row
21796    /// order, pairing, or column content, this is what catches it.
21797    #[test]
21798    fn a_passing_validation_produces_the_unvalidated_output_uza04() {
21799        let left = int_frame("left_v", vec![5, 1, 4, 2, 3], vec![50, 10, 40, 20, 30]);
21800        let right = int_frame("right_v", vec![3, 1, 2, 9], vec![300, 100, 200, 900]);
21801
21802        let unvalidated = merge(&left, &right, None).expect("plain merge");
21803        for mode in [
21804            MergeValidateMode::OneToOne,
21805            MergeValidateMode::OneToMany,
21806            MergeValidateMode::ManyToOne,
21807            MergeValidateMode::ManyToMany,
21808        ] {
21809            let validated = merge(&left, &right, Some(mode)).expect("validation should pass");
21810            assert_eq!(
21811                validated.index.len(),
21812                unvalidated.index.len(),
21813                "{mode:?}: row count changed"
21814            );
21815            assert_eq!(
21816                validated.column_order, unvalidated.column_order,
21817                "{mode:?}: column order changed"
21818            );
21819            for name in ["id", "left_v", "right_v"] {
21820                assert_eq!(
21821                    validated.columns.get(name).expect("column").values(),
21822                    unvalidated.columns.get(name).expect("column").values(),
21823                    "{mode:?}: column {name} differs from the unvalidated merge"
21824                );
21825            }
21826        }
21827    }
21828
21829    /// NON-VACUITY, both directions. Every assertion above would still pass if
21830    /// the typed checker declined everything and the generic path did all the
21831    /// work — the lever would simply not exist.
21832    #[test]
21833    fn the_typed_checker_fires_on_typed_keys_and_declines_otherwise_uza04() {
21834        let unique = Column::from_i64_values(vec![1, 2, 3]);
21835        assert_eq!(
21836            typed_single_int64_key_has_duplicates(&[&unique]),
21837            Some(false),
21838            "an all-valid Int64 key must be answered typed"
21839        );
21840        let duplicated = Column::from_i64_values(vec![1, 2, 2]);
21841        assert_eq!(
21842            typed_single_int64_key_has_duplicates(&[&duplicated]),
21843            Some(true),
21844            "and duplicates must be seen"
21845        );
21846
21847        // A key with a missing value has no contiguous all-valid buffer, so the
21848        // typed checker declines and null-key duplicate semantics stay owned by
21849        // the generic path.
21850        let nullable = Column::from_values(vec![
21851            Scalar::Int64(1),
21852            Scalar::Null(NullKind::Null),
21853            Scalar::Int64(3),
21854        ])
21855        .expect("nullable int column");
21856        assert_eq!(
21857            typed_single_int64_key_has_duplicates(&[&nullable]),
21858            None,
21859            "a nullable key must decline"
21860        );
21861
21862        // Utf8 keys decline too (this lever is Int64-only for now).
21863        let text = Column::from_values(vec![
21864            Scalar::Utf8("a".to_owned()),
21865            Scalar::Utf8("b".to_owned()),
21866        ])
21867        .expect("utf8 column");
21868        assert_eq!(
21869            typed_single_int64_key_has_duplicates(&[&text]),
21870            None,
21871            "a Utf8 key must decline"
21872        );
21873
21874        // Multi-key merges decline: the composite question is not this one.
21875        assert_eq!(
21876            typed_single_int64_key_has_duplicates(&[&unique, &duplicated]),
21877            None,
21878            "more than one key column must decline"
21879        );
21880    }
21881
21882    /// A shape the typed checker DECLINES must still be validated — the generic
21883    /// path has to keep running for it. A nullable left key with a repeated
21884    /// value under `one_to_many` is the case that would silently start passing
21885    /// if the skip flag were set too broadly.
21886    #[test]
21887    fn a_declined_shape_is_still_validated_by_the_generic_path_uza04() {
21888        let index = Index::new_known_unique_int64_unit_range(0, 3);
21889        let left = DataFrame::new_with_column_order(
21890            index,
21891            std::collections::BTreeMap::from([
21892                (
21893                    "id".to_owned(),
21894                    Column::from_values(vec![
21895                        Scalar::Int64(1),
21896                        Scalar::Int64(1),
21897                        Scalar::Null(NullKind::Null),
21898                    ])
21899                    .expect("nullable id column"),
21900                ),
21901                (
21902                    "left_v".to_owned(),
21903                    Column::from_i64_values(vec![10, 11, 30]),
21904                ),
21905            ]),
21906            vec!["id".to_owned(), "left_v".to_owned()],
21907        )
21908        .expect("nullable left frame");
21909        let right = int_frame("right_v", vec![1, 2, 3], vec![100, 200, 300]);
21910
21911        let error = merge(&left, &right, Some(MergeValidateMode::OneToMany))
21912            .expect_err("a duplicated nullable left key must still be rejected");
21913        assert!(
21914            format!("{error}").contains("left keys are not unique"),
21915            "the generic checker must still own declined shapes, got: {error}"
21916        );
21917    }
21918
21919    #[test]
21920    fn merge_suffix_collision_preserves_duplicate_columns() {
21921        let left = fp_frame::DataFrame::from_dict_with_index(
21922            vec![
21923                ("key", vec![Scalar::Int64(1)]),
21924                ("a", vec![Scalar::Int64(10)]),
21925                ("a_y", vec![Scalar::Int64(20)]),
21926            ],
21927            vec![0_i64.into()],
21928        )
21929        .unwrap();
21930
21931        let right = fp_frame::DataFrame::from_dict_with_index(
21932            vec![
21933                ("key", vec![Scalar::Int64(1)]),
21934                ("a", vec![Scalar::Int64(30)]),
21935            ],
21936            vec![0_i64.into()],
21937        )
21938        .unwrap();
21939
21940        let options = MergeExecutionOptions {
21941            suffixes: Some([Some("_x".to_string()), Some("_y".to_string())]),
21942            ..MergeExecutionOptions::default()
21943        };
21944
21945        let merged = merge_dataframes_on_with_options(
21946            &left,
21947            &right,
21948            &["key"],
21949            &["key"],
21950            JoinType::Inner,
21951            options,
21952        )
21953        .expect("merge with suffix collision should succeed and produce duplicate columns");
21954
21955        assert_eq!(
21956            merged.column_order,
21957            vec![
21958                "key".to_string(),
21959                "a_x".to_string(),
21960                "a_y".to_string(),
21961                "a_y".to_string()
21962            ]
21963        );
21964        assert_eq!(merged.columns.occurrences("a_y"), 2);
21965        assert_eq!(
21966            merged.columns.column_at(2).unwrap().values(),
21967            &[Scalar::Int64(20)]
21968        );
21969        assert_eq!(
21970            merged.columns.column_at(3).unwrap().values(),
21971            &[Scalar::Int64(30)]
21972        );
21973    }
21974
21975    #[test]
21976    fn merge_suffixes_intra_frame_duplicate_rejected() {
21977        // Left side collision: left has val and val_L, suffix _L produces duplicate val_L
21978        let left = fp_frame::DataFrame::from_dict_with_index(
21979            vec![
21980                ("id", vec![Scalar::Int64(1)]),
21981                ("val", vec![Scalar::Int64(10)]),
21982                ("val_L", vec![Scalar::Int64(77)]),
21983            ],
21984            vec![0_i64.into()],
21985        )
21986        .unwrap();
21987
21988        let right = fp_frame::DataFrame::from_dict_with_index(
21989            vec![
21990                ("id", vec![Scalar::Int64(1)]),
21991                ("val", vec![Scalar::Int64(100)]),
21992            ],
21993            vec![0_i64.into()],
21994        )
21995        .unwrap();
21996
21997        let options = MergeExecutionOptions {
21998            suffixes: Some([Some("_L".to_string()), Some("_R".to_string())]),
21999            ..MergeExecutionOptions::default()
22000        };
22001
22002        let err = merge_dataframes_on_with_options(
22003            &left,
22004            &right,
22005            &["id"],
22006            &["id"],
22007            JoinType::Inner,
22008            options.clone(),
22009        )
22010        .expect_err("merge causing duplicate column within left must be rejected");
22011
22012        assert!(
22013            format!("{err}").contains("duplicate columns {'val_L'}"),
22014            "expected duplicate columns error, got: {err}"
22015        );
22016
22017        // Right side collision: right has val and val_R, suffix _R produces duplicate val_R
22018        let right_with_dup = fp_frame::DataFrame::from_dict_with_index(
22019            vec![
22020                ("id", vec![Scalar::Int64(1)]),
22021                ("val", vec![Scalar::Int64(100)]),
22022                ("val_R", vec![Scalar::Int64(88)]),
22023            ],
22024            vec![0_i64.into()],
22025        )
22026        .unwrap();
22027
22028        let left_simple = fp_frame::DataFrame::from_dict_with_index(
22029            vec![
22030                ("id", vec![Scalar::Int64(1)]),
22031                ("val", vec![Scalar::Int64(10)]),
22032            ],
22033            vec![0_i64.into()],
22034        )
22035        .unwrap();
22036
22037        let err_r = merge_dataframes_on_with_options(
22038            &left_simple,
22039            &right_with_dup,
22040            &["id"],
22041            &["id"],
22042            JoinType::Inner,
22043            options,
22044        )
22045        .expect_err("merge causing duplicate column within right must be rejected");
22046
22047        assert!(
22048            format!("{err_r}").contains("duplicate columns {'val_R'}"),
22049            "expected duplicate columns error, got: {err_r}"
22050        );
22051    }
22052}