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    Ok(column.reindex_by_positions(positions)?)
642}
643
644fn reindex_outer_with_shared_utf8_plan(
645    column: &Column,
646    positions: &[Option<usize>],
647    plan: Option<&SharedOptionalUtf8GatherPlan>,
648) -> Result<Column, JoinError> {
649    if let Some(column) = plan.and_then(|plan| reindex_eager_utf8_with_plan(column, plan)) {
650        return Ok(column);
651    }
652    reindex_join_column_with_invented_gap(column, positions)
653}
654
655fn reindex_eager_utf8_with_plan(
656    column: &Column,
657    plan: &SharedOptionalUtf8GatherPlan,
658) -> Option<Column> {
659    match plan {
660        SharedOptionalUtf8GatherPlan::NullableRange {
661            null_prefix,
662            source_start,
663            source_len,
664            null_suffix,
665        } => column.reindex_eager_utf8_with_nullable_range(
666            *null_prefix,
667            *source_start,
668            *source_len,
669            *null_suffix,
670        ),
671        SharedOptionalUtf8GatherPlan::Positions {
672            positions,
673            validity,
674        } => column.reindex_eager_utf8_with_shared_plan(Arc::clone(positions), validity.clone()),
675    }
676}
677
678fn sort_outer_join_rows(
679    out_labels: &mut Vec<IndexLabel>,
680    left_positions: &mut [Option<usize>],
681    right_positions: &mut [Option<usize>],
682) {
683    if out_labels.len() <= 1 {
684        return;
685    }
686
687    let mut rows = out_labels
688        .drain(..)
689        .zip(left_positions.iter().copied())
690        .zip(right_positions.iter().copied())
691        .map(|((label, left_pos), right_pos)| (label, left_pos, right_pos))
692        .collect::<Vec<_>>();
693    rows.sort_by(|left, right| left.0.cmp(&right.0));
694
695    for (idx, (label, left_pos, right_pos)) in rows.into_iter().enumerate() {
696        out_labels.push(label);
697        left_positions[idx] = left_pos;
698        right_positions[idx] = right_pos;
699    }
700}
701
702fn join_series_with_global_allocator(
703    left: &Series,
704    right: &Series,
705    join_type: JoinType,
706    right_map: &FxHashMap<&IndexLabel, Vec<usize>>,
707    left_map: Option<&FxHashMap<&IndexLabel, Vec<usize>>>,
708    output_rows: usize,
709) -> Result<JoinedSeries, JoinError> {
710    let mut out_labels = Vec::with_capacity(output_rows);
711    let mut left_positions = Vec::<Option<usize>>::with_capacity(output_rows);
712    let mut right_positions = Vec::<Option<usize>>::with_capacity(output_rows);
713
714    match join_type {
715        JoinType::Inner | JoinType::Left | JoinType::Outer => {
716            // Iterate left labels: emit matches and (for Left/Outer) unmatched left rows.
717            for (left_pos, label) in left.index().labels().iter().enumerate() {
718                if let Some(matches) = right_map.get(label) {
719                    for right_pos in matches {
720                        out_labels.push(label.clone());
721                        left_positions.push(Some(left_pos));
722                        right_positions.push(Some(*right_pos));
723                    }
724                    continue;
725                }
726
727                if matches!(join_type, JoinType::Left | JoinType::Outer) {
728                    out_labels.push(label.clone());
729                    left_positions.push(Some(left_pos));
730                    right_positions.push(None);
731                }
732            }
733
734            // For Outer: append right labels that have no match in left.
735            if matches!(join_type, JoinType::Outer) {
736                let left_map = left_map.as_ref().expect("left_map required for Outer join");
737                for (right_pos, label) in right.index().labels().iter().enumerate() {
738                    if !left_map.contains_key(label) {
739                        out_labels.push(label.clone());
740                        left_positions.push(None);
741                        right_positions.push(Some(right_pos));
742                    }
743                }
744            }
745        }
746        JoinType::Right => {
747            // Iterate right labels: emit matches and unmatched right rows.
748            let left_map = left_map.expect("left_map required for Right join");
749            for (right_pos, label) in right.index().labels().iter().enumerate() {
750                if let Some(matches) = left_map.get(label) {
751                    for left_pos in matches {
752                        out_labels.push(label.clone());
753                        left_positions.push(Some(*left_pos));
754                        right_positions.push(Some(right_pos));
755                    }
756                    continue;
757                }
758
759                out_labels.push(label.clone());
760                left_positions.push(None);
761                right_positions.push(Some(right_pos));
762            }
763        }
764        JoinType::Cross => {
765            for (left_pos, left_label) in left.index().labels().iter().enumerate() {
766                for (right_pos, _) in right.index().labels().iter().enumerate() {
767                    out_labels.push(left_label.clone());
768                    left_positions.push(Some(left_pos));
769                    right_positions.push(Some(right_pos));
770                }
771            }
772        }
773    }
774
775    if matches!(join_type, JoinType::Outer) {
776        sort_outer_join_rows(&mut out_labels, &mut left_positions, &mut right_positions);
777    }
778
779    // Every join type, not just Outer: the widening is caused by a gap landing
780    // in THIS column, and a left join invents gaps on the right side just as an
781    // outer join does. The helper is a no-op when no gap is invented, so
782    // right/inner are unaffected. (br-frankenpandas-nywa8)
783    let left_values = reindex_join_column_with_invented_gap(left.column(), &left_positions)?;
784    let right_values = reindex_join_column_with_invented_gap(right.column(), &right_positions)?;
785
786    // Per br-frankenpandas-wp0n6: pandas Series.join preserves shared
787    // index name (preserved when both operands agree, None when they differ).
788    let shared_name = if left.index().name().eq(&right.index().name()) {
789        left.index().name().map(str::to_owned)
790    } else {
791        None
792    };
793    Ok(JoinedSeries {
794        index: Index::new(out_labels).rename_index(shared_name.as_deref()),
795        left_values,
796        right_values,
797    })
798}
799
800fn join_series_with_arena(
801    left: &Series,
802    right: &Series,
803    join_type: JoinType,
804    right_map: &FxHashMap<&IndexLabel, Vec<usize>>,
805    left_map: Option<&FxHashMap<&IndexLabel, Vec<usize>>>,
806    output_rows: usize,
807) -> Result<JoinedSeries, JoinError> {
808    let arena = Bump::new();
809    let mut out_labels = Vec::with_capacity(output_rows);
810    let mut left_positions = BumpVec::<Option<usize>>::with_capacity_in(output_rows, &arena);
811    let mut right_positions = BumpVec::<Option<usize>>::with_capacity_in(output_rows, &arena);
812
813    match join_type {
814        JoinType::Inner | JoinType::Left | JoinType::Outer => {
815            for (left_pos, label) in left.index().labels().iter().enumerate() {
816                if let Some(matches) = right_map.get(label) {
817                    for right_pos in matches {
818                        out_labels.push(label.clone());
819                        left_positions.push(Some(left_pos));
820                        right_positions.push(Some(*right_pos));
821                    }
822                    continue;
823                }
824
825                if matches!(join_type, JoinType::Left | JoinType::Outer) {
826                    out_labels.push(label.clone());
827                    left_positions.push(Some(left_pos));
828                    right_positions.push(None);
829                }
830            }
831
832            if matches!(join_type, JoinType::Outer) {
833                let left_map = left_map.as_ref().expect("left_map required for Outer join");
834                for (right_pos, label) in right.index().labels().iter().enumerate() {
835                    if !left_map.contains_key(label) {
836                        out_labels.push(label.clone());
837                        left_positions.push(None);
838                        right_positions.push(Some(right_pos));
839                    }
840                }
841            }
842        }
843        JoinType::Right => {
844            let left_map = left_map.expect("left_map required for Right join");
845            for (right_pos, label) in right.index().labels().iter().enumerate() {
846                if let Some(matches) = left_map.get(label) {
847                    for left_pos in matches {
848                        out_labels.push(label.clone());
849                        left_positions.push(Some(*left_pos));
850                        right_positions.push(Some(right_pos));
851                    }
852                    continue;
853                }
854
855                out_labels.push(label.clone());
856                left_positions.push(None);
857                right_positions.push(Some(right_pos));
858            }
859        }
860        JoinType::Cross => {
861            for (left_pos, left_label) in left.index().labels().iter().enumerate() {
862                for (right_pos, _) in right.index().labels().iter().enumerate() {
863                    out_labels.push(left_label.clone());
864                    left_positions.push(Some(left_pos));
865                    right_positions.push(Some(right_pos));
866                }
867            }
868        }
869    }
870
871    if matches!(join_type, JoinType::Outer) {
872        sort_outer_join_rows(
873            &mut out_labels,
874            left_positions.as_mut_slice(),
875            right_positions.as_mut_slice(),
876        );
877    }
878
879    // Every join type — see the sibling site above (br-frankenpandas-nywa8).
880    let left_values =
881        reindex_join_column_with_invented_gap(left.column(), left_positions.as_slice())?;
882    let right_values =
883        reindex_join_column_with_invented_gap(right.column(), right_positions.as_slice())?;
884
885    // Per br-frankenpandas-ceces: pandas Series.join preserves shared
886    // index name. Sister to join_series fix (wp0n6).
887    let shared_name = if left.index().name().eq(&right.index().name()) {
888        left.index().name().map(str::to_owned)
889    } else {
890        None
891    };
892    Ok(JoinedSeries {
893        index: Index::new(out_labels).rename_index(shared_name.as_deref()),
894        left_values,
895        right_values,
896    })
897}
898
899/// Result of a DataFrame merge operation.
900#[derive(Debug, Clone, PartialEq)]
901pub struct MergedDataFrame {
902    pub index: Index,
903    /// br-frankenpandas-u387a: a `ColumnStore`, not a `BTreeMap`. Merge suffix
904    /// collisions are one of the pandas cases the duplicate-label work
905    /// (br-frankenpandas-ih4t0) has to support, so a map here would just be
906    /// the same leak one crate over — it cannot represent the repeated labels
907    /// a collision produces.
908    pub columns: ColumnStore,
909    /// Output column order in pandas' convention (key/left columns in their
910    /// source order, then right non-key columns). The `columns` map is sorted,
911    /// so this Vec carries the real order for materialization — br-691lh.
912    pub column_order: Vec<String>,
913}
914
915#[derive(Debug, Clone, PartialEq, Eq, Hash)]
916enum JoinKeyComponent {
917    Present(IndexLabel),
918    FloatBits(u64),
919    Missing,
920}
921
922impl Ord for JoinKeyComponent {
923    fn cmp(&self, other: &Self) -> Ordering {
924        use JoinKeyComponent::{FloatBits, Missing, Present};
925        match (self, other) {
926            (Missing, Missing) => Ordering::Equal,
927            (Missing, _) => Ordering::Greater,
928            (_, Missing) => Ordering::Less,
929            (Present(IndexLabel::Int64(a)), Present(IndexLabel::Int64(b))) => a.cmp(b),
930            (Present(IndexLabel::Utf8(a)), Present(IndexLabel::Utf8(b))) => a.cmp(b),
931            (Present(IndexLabel::Timedelta64(a)), Present(IndexLabel::Timedelta64(b))) => a.cmp(b),
932            (Present(IndexLabel::Datetime64(a)), Present(IndexLabel::Datetime64(b))) => a.cmp(b),
933            // Typed-null labels sort after every concrete label (nulls-last,
934            // consistent with the derived IndexLabel Ord) but before Missing.
935            // Unreachable today: join key extraction maps missing to Missing,
936            // never Present(Null).
937            (Present(IndexLabel::Null(a)), Present(IndexLabel::Null(b))) => a.cmp(b),
938            (Present(IndexLabel::Null(_)), Present(_)) => Ordering::Greater,
939            (Present(_), Present(IndexLabel::Null(_))) => Ordering::Less,
940            (Present(IndexLabel::Null(_)), FloatBits(_)) => Ordering::Greater,
941            (FloatBits(_), Present(IndexLabel::Null(_))) => Ordering::Less,
942            (Present(IndexLabel::Int64(_)), Present(IndexLabel::Utf8(_))) => Ordering::Less,
943            (Present(IndexLabel::Utf8(_)), Present(IndexLabel::Int64(_))) => Ordering::Greater,
944            (Present(IndexLabel::Timedelta64(_)), Present(IndexLabel::Int64(_))) => {
945                Ordering::Greater
946            }
947            (Present(IndexLabel::Timedelta64(_)), Present(IndexLabel::Utf8(_))) => {
948                Ordering::Greater
949            }
950            (Present(IndexLabel::Int64(_)), Present(IndexLabel::Timedelta64(_))) => Ordering::Less,
951            (Present(IndexLabel::Utf8(_)), Present(IndexLabel::Timedelta64(_))) => Ordering::Less,
952            (Present(IndexLabel::Datetime64(_)), Present(IndexLabel::Int64(_))) => {
953                Ordering::Greater
954            }
955            (Present(IndexLabel::Datetime64(_)), Present(IndexLabel::Utf8(_))) => Ordering::Greater,
956            (Present(IndexLabel::Datetime64(_)), Present(IndexLabel::Timedelta64(_))) => {
957                Ordering::Greater
958            }
959            (Present(IndexLabel::Int64(_)), Present(IndexLabel::Datetime64(_))) => Ordering::Less,
960            (Present(IndexLabel::Utf8(_)), Present(IndexLabel::Datetime64(_))) => Ordering::Less,
961            (Present(IndexLabel::Timedelta64(_)), Present(IndexLabel::Datetime64(_))) => {
962                Ordering::Less
963            }
964            (Present(IndexLabel::Int64(a)), FloatBits(bits)) => {
965                let ord = (*a as f64).total_cmp(&f64::from_bits(*bits));
966                if ord == Ordering::Equal {
967                    Ordering::Less
968                } else {
969                    ord
970                }
971            }
972            (FloatBits(bits), Present(IndexLabel::Int64(a))) => {
973                let ord = f64::from_bits(*bits).total_cmp(&(*a as f64));
974                if ord == Ordering::Equal {
975                    Ordering::Greater
976                } else {
977                    ord
978                }
979            }
980            (Present(IndexLabel::Timedelta64(a)), FloatBits(bits)) => {
981                let ord = (*a as f64).total_cmp(&f64::from_bits(*bits));
982                if ord == Ordering::Equal {
983                    Ordering::Less
984                } else {
985                    ord
986                }
987            }
988            (FloatBits(bits), Present(IndexLabel::Timedelta64(a))) => {
989                let ord = f64::from_bits(*bits).total_cmp(&(*a as f64));
990                if ord == Ordering::Equal {
991                    Ordering::Greater
992                } else {
993                    ord
994                }
995            }
996            (Present(IndexLabel::Datetime64(a)), FloatBits(bits)) => {
997                let ord = (*a as f64).total_cmp(&f64::from_bits(*bits));
998                if ord == Ordering::Equal {
999                    Ordering::Less
1000                } else {
1001                    ord
1002                }
1003            }
1004            (FloatBits(bits), Present(IndexLabel::Datetime64(a))) => {
1005                let ord = f64::from_bits(*bits).total_cmp(&(*a as f64));
1006                if ord == Ordering::Equal {
1007                    Ordering::Greater
1008                } else {
1009                    ord
1010                }
1011            }
1012            (FloatBits(a_bits), FloatBits(b_bits)) => {
1013                f64::from_bits(*a_bits).total_cmp(&f64::from_bits(*b_bits))
1014            }
1015            (FloatBits(_), Present(IndexLabel::Utf8(_))) => Ordering::Less,
1016            (Present(IndexLabel::Utf8(_)), FloatBits(_)) => Ordering::Greater,
1017            // Float64/Bool index labels (br-frankenpandas-i10en). Join key
1018            // extraction maps float keys to FloatBits and bool keys to Int64, so
1019            // a Present(Float64)/Present(Bool) join key is unreachable today;
1020            // these arms only keep the manual `Ord` total (same-variant compares
1021            // by value, cross-variant by a stable variant rank).
1022            (Present(IndexLabel::Float64(a)), Present(IndexLabel::Float64(b))) => a.cmp(b),
1023            (Present(IndexLabel::Bool(a)), Present(IndexLabel::Bool(b))) => a.cmp(b),
1024            (a, b) => join_component_rank(a).cmp(&join_component_rank(b)),
1025        }
1026    }
1027}
1028
1029/// Stable per-variant rank used only as the cross-variant fallback for the
1030/// (unreachable) Float64/Bool join-key cases above, keeping `Ord` total.
1031fn join_component_rank(c: &JoinKeyComponent) -> u8 {
1032    use JoinKeyComponent::{FloatBits, Missing, Present};
1033    match c {
1034        Present(IndexLabel::Int64(_)) => 0,
1035        Present(IndexLabel::Float64(_)) => 1,
1036        Present(IndexLabel::Bool(_)) => 2,
1037        Present(IndexLabel::Utf8(_)) => 3,
1038        Present(IndexLabel::Timedelta64(_)) => 4,
1039        Present(IndexLabel::Datetime64(_)) => 5,
1040        Present(IndexLabel::Null(_)) => 6,
1041        FloatBits(_) => 7,
1042        Missing => 8,
1043    }
1044}
1045
1046impl PartialOrd for JoinKeyComponent {
1047    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1048        Some(self.cmp(other))
1049    }
1050}
1051
1052fn scalar_to_key_component(s: &fp_types::Scalar) -> JoinKeyComponent {
1053    match s {
1054        fp_types::Scalar::Int64(v) => JoinKeyComponent::Present(IndexLabel::Int64(*v)),
1055        fp_types::Scalar::Float64(v) if !v.is_nan() => {
1056            if *v == v.trunc() && *v >= i64::MIN as f64 && *v < 9223372036854775808.0 {
1057                JoinKeyComponent::Present(IndexLabel::Int64(*v as i64))
1058            } else {
1059                JoinKeyComponent::FloatBits(v.to_bits())
1060            }
1061        }
1062        fp_types::Scalar::Utf8(v) => JoinKeyComponent::Present(IndexLabel::Utf8(v.clone())),
1063        fp_types::Scalar::Bool(b) => JoinKeyComponent::Present(IndexLabel::Int64(i64::from(*b))),
1064        fp_types::Scalar::Timedelta64(v) if *v != fp_types::Timedelta::NAT => {
1065            JoinKeyComponent::Present(IndexLabel::Timedelta64(*v))
1066        }
1067        fp_types::Scalar::Datetime64(v) if *v != fp_types::Timestamp::NAT => {
1068            JoinKeyComponent::Present(IndexLabel::Datetime64(*v))
1069        }
1070        _ => JoinKeyComponent::Missing, // Null, NaN, NaT
1071    }
1072}
1073
1074/// A row's composite join key. Inline storage for the single-key case (the
1075/// overwhelmingly common join shape) avoids a heap allocation per row during
1076/// key extraction; multi-column keys spill to the heap as before. `SmallVec`
1077/// shares `Vec`'s `Hash`/`Eq`/`Ord`/`Deref<[T]>` semantics, so the join result
1078/// (key equality, grouping, output order) is bit-identical.
1079type CompositeJoinKey = smallvec::SmallVec<[JoinKeyComponent; 1]>;
1080
1081/// `(left_positions, right_positions, out_row_keys)` produced by the merge
1082/// position-computation phase. `out_row_keys` is `Some` only when the rows must
1083/// be reordered by join key (sort or outer join).
1084type MergeRowPositions = (
1085    Vec<Option<usize>>,
1086    Vec<Option<usize>>,
1087    Option<Vec<CompositeJoinKey>>,
1088);
1089type JoinPositionBucket = smallvec::SmallVec<[usize; 1]>;
1090
1091fn collect_join_key_columns<'a>(
1092    frame: &'a fp_frame::DataFrame,
1093    on: &[&str],
1094    side: &str,
1095) -> Result<Vec<&'a Column>, JoinError> {
1096    let mut key_columns = Vec::with_capacity(on.len());
1097    for key_name in on {
1098        let key_column = frame.column(key_name).ok_or_else(|| {
1099            JoinError::Frame(FrameError::CompatibilityRejected(format!(
1100                "{side} DataFrame missing key column '{key_name}'"
1101            )))
1102        })?;
1103        key_columns.push(key_column);
1104    }
1105    Ok(key_columns)
1106}
1107
1108fn collect_composite_keys(key_columns: &[&Column]) -> Vec<CompositeJoinKey> {
1109    let row_count = key_columns.first().map_or(0, |column| column.len());
1110    let mut out = Vec::with_capacity(row_count);
1111
1112    for row in 0..row_count {
1113        let mut parts: CompositeJoinKey = smallvec::SmallVec::with_capacity(key_columns.len());
1114        for column in key_columns {
1115            parts.push(scalar_to_key_component(&column.values()[row]));
1116        }
1117        out.push(parts);
1118    }
1119
1120    out
1121}
1122
1123fn collect_single_join_keys(column: &Column) -> Vec<JoinKeyComponent> {
1124    column
1125        .values()
1126        .iter()
1127        .map(scalar_to_key_component)
1128        .collect()
1129}
1130
1131fn has_duplicate_composite_keys(keys: &[CompositeJoinKey]) -> bool {
1132    let mut seen = FxHashSet::with_capacity_and_hasher(keys.len(), Default::default());
1133    for key in keys {
1134        if !seen.insert(key) {
1135            return true;
1136        }
1137    }
1138    false
1139}
1140
1141fn validate_merge_cardinality(
1142    validate_mode: MergeValidateMode,
1143    left_keys: &[CompositeJoinKey],
1144    right_keys: &[CompositeJoinKey],
1145) -> Result<(), JoinError> {
1146    let fail = |message: &str| {
1147        Err(JoinError::Frame(FrameError::CompatibilityRejected(
1148            message.to_owned(),
1149        )))
1150    };
1151
1152    match validate_mode {
1153        MergeValidateMode::OneToOne => {
1154            // Preserve pandas's left-first failure precedence when both sides
1155            // duplicate while avoiding an unnecessary right-side scan on a
1156            // left-side failure.
1157            if has_duplicate_composite_keys(left_keys) {
1158                return fail("merge validate='one_to_one' failed: left keys are not unique");
1159            }
1160            if has_duplicate_composite_keys(right_keys) {
1161                return fail("merge validate='one_to_one' failed: right keys are not unique");
1162            }
1163        }
1164        MergeValidateMode::OneToMany => {
1165            if has_duplicate_composite_keys(left_keys) {
1166                return fail("merge validate='one_to_many' failed: left keys are not unique");
1167            }
1168        }
1169        MergeValidateMode::ManyToOne => {
1170            if has_duplicate_composite_keys(right_keys) {
1171                return fail("merge validate='many_to_one' failed: right keys are not unique");
1172            }
1173        }
1174        MergeValidateMode::ManyToMany => {}
1175    }
1176
1177    Ok(())
1178}
1179
1180fn validate_mode_allows_fast_positions(validate_mode: Option<MergeValidateMode>) -> bool {
1181    matches!(validate_mode, None | Some(MergeValidateMode::ManyToMany))
1182}
1183
1184/// Duplicate detection straight off a single all-valid `Int64` key buffer.
1185///
1186/// br-frankenpandas-uza04. `has_duplicate_composite_keys` needs a
1187/// `Vec<CompositeJoinKey>`, which `collect_composite_keys` builds by reading
1188/// `column.values()[row]` — the 32 B/elem `Scalar` spine plus a `SmallVec` per
1189/// row. For one all-valid Int64 column the same question is an `FxHashSet<i64>`
1190/// over the contiguous buffer, pre-sized so the build side never rehashes.
1191///
1192/// Returns `None` when this shape does not apply (more than one key column, a
1193/// non-`Int64` dtype, or any missing value — `as_i64_slice` answers only for
1194/// all-valid `DType::Int64`), and the caller keeps the generic path, which is
1195/// also where null-key duplicate semantics stay owned.
1196fn typed_single_int64_key_has_duplicates(key_columns: &[&Column]) -> Option<bool> {
1197    let [column] = key_columns else {
1198        return None;
1199    };
1200    let data = column.as_i64_slice()?;
1201    let mut seen = FxHashSet::with_capacity_and_hasher(data.len(), Default::default());
1202    Some(!data.iter().all(|&key| seen.insert(key)))
1203}
1204
1205/// Typed sibling of [`validate_merge_cardinality`]: enforce the mode off raw
1206/// key buffers, and report whether it was able to.
1207///
1208/// `Ok(true)` means the mode was fully enforced here and PASSED, so the caller
1209/// may use the fast positions paths. `Ok(false)` means this shape is not
1210/// covered and the generic path must still run `validate_merge_cardinality`.
1211/// `Err` is a real validation failure and carries the SAME message the generic
1212/// checker produces, because the two must be indistinguishable to a caller.
1213///
1214/// Precedence matters and is preserved: `OneToOne` reports a left-side failure
1215/// before looking at the right, exactly as the generic checker does. It also
1216/// declines outright unless BOTH sides are typed, so it can never report a
1217/// right-side failure that the generic checker would have pre-empted with a
1218/// left-side one it could not see.
1219fn typed_validate_merge_cardinality(
1220    validate_mode: MergeValidateMode,
1221    left_key_columns: &[&Column],
1222    right_key_columns: &[&Column],
1223) -> Result<bool, JoinError> {
1224    let fail = |message: &str| {
1225        Err(JoinError::Frame(FrameError::CompatibilityRejected(
1226            message.to_owned(),
1227        )))
1228    };
1229
1230    match validate_mode {
1231        MergeValidateMode::ManyToMany => Ok(true),
1232        MergeValidateMode::OneToMany => {
1233            match typed_single_int64_key_has_duplicates(left_key_columns) {
1234                Some(true) => fail("merge validate='one_to_many' failed: left keys are not unique"),
1235                Some(false) => Ok(true),
1236                None => Ok(false),
1237            }
1238        }
1239        MergeValidateMode::ManyToOne => {
1240            match typed_single_int64_key_has_duplicates(right_key_columns) {
1241                Some(true) => {
1242                    fail("merge validate='many_to_one' failed: right keys are not unique")
1243                }
1244                Some(false) => Ok(true),
1245                None => Ok(false),
1246            }
1247        }
1248        MergeValidateMode::OneToOne => {
1249            // Both sides must be typed before deciding anything: a left-side
1250            // failure outranks a right-side one, so answering from the right
1251            // alone could surface the wrong message.
1252            let Some(left_duplicated) = typed_single_int64_key_has_duplicates(left_key_columns)
1253            else {
1254                return Ok(false);
1255            };
1256            let Some(right_duplicated) = typed_single_int64_key_has_duplicates(right_key_columns)
1257            else {
1258                return Ok(false);
1259            };
1260            if left_duplicated {
1261                return fail("merge validate='one_to_one' failed: left keys are not unique");
1262            }
1263            if right_duplicated {
1264                return fail("merge validate='one_to_one' failed: right keys are not unique");
1265            }
1266            Ok(true)
1267        }
1268    }
1269}
1270
1271fn reorder_vec_by_index<T: Clone>(values: &mut Vec<T>, order: &[usize]) {
1272    let existing = values.clone();
1273    values.clear();
1274    values.reserve(order.len());
1275    for &idx in order {
1276        values.push(existing[idx].clone());
1277    }
1278}
1279
1280fn sort_merge_rows_by_join_keys(
1281    left_keys: &[CompositeJoinKey],
1282    right_keys: &[CompositeJoinKey],
1283    left_positions: &mut Vec<Option<usize>>,
1284    right_positions: &mut Vec<Option<usize>>,
1285) {
1286    let n = left_positions.len();
1287    if n <= 1 {
1288        return;
1289    }
1290    // pandas sorts merge output by the join key. The naive O(n·log n) COMPARISON
1291    // sort re-compares full keys (string compares for Utf8) on every step. Instead
1292    // FACTORIZE the keys to dense ranks (sort only the DISTINCT keys once, d≪n)
1293    // then STABLE counting-sort the rows by rank — O(n + d·log d). Crucially, each
1294    // output row's key is read BY REFERENCE from the already-built left_keys /
1295    // right_keys via its position (matched / unmatched-left rows take the left key,
1296    // unmatched-right rows take the right key — exactly what the removed per-row
1297    // `out_row_keys` clone stored), so the ~n String-owning CompositeJoinKey clones
1298    // that dominated outer merge are gone. Bit-identical to the prior path: same
1299    // per-row key, same `cmp`-ordered ranks (over a superset of distinct keys —
1300    // unused ranks are just empty counting-sort buckets), same stable
1301    // ascending-index emission within each rank.
1302    let mut distinct: Vec<&CompositeJoinKey> = {
1303        let mut set = FxHashSet::default();
1304        left_keys
1305            .iter()
1306            .chain(right_keys.iter())
1307            .filter(|k| set.insert(*k))
1308            .collect()
1309    };
1310    distinct.sort_unstable();
1311    let d = distinct.len();
1312    let mut rank_of: FxHashMap<&CompositeJoinKey, u32> = FxHashMap::default();
1313    rank_of.reserve(d);
1314    for (r, k) in distinct.iter().enumerate() {
1315        rank_of.insert(*k, r as u32);
1316    }
1317    let left_rank: Vec<u32> = left_keys.iter().map(|k| rank_of[k]).collect();
1318    let right_rank: Vec<u32> = right_keys.iter().map(|k| rank_of[k]).collect();
1319    let ranks: Vec<u32> = left_positions
1320        .iter()
1321        .zip(right_positions.iter())
1322        .map(|(lp, rp)| match lp {
1323            Some(p) => left_rank[*p],
1324            None => right_rank[rp.expect("an unmatched merge row has a right position")],
1325        })
1326        .collect();
1327    let mut counts = vec![0usize; d + 1];
1328    for &r in &ranks {
1329        counts[r as usize + 1] += 1;
1330    }
1331    for i in 0..d {
1332        counts[i + 1] += counts[i];
1333    }
1334    // `order[new_slot] = old_idx`, matching the comparison sort's permutation —
1335    // stable because rows are scattered in ascending original-index order.
1336    let mut cursor = counts;
1337    let mut order = vec![0usize; n];
1338    for (i, &r) in ranks.iter().enumerate() {
1339        let slot = cursor[r as usize];
1340        order[slot] = i;
1341        cursor[r as usize] = slot + 1;
1342    }
1343    reorder_vec_by_index(left_positions, &order);
1344    reorder_vec_by_index(right_positions, &order);
1345}
1346
1347fn push_merge_row_key(out_row_keys: &mut Option<Vec<CompositeJoinKey>>, key: &CompositeJoinKey) {
1348    if let Some(out_row_keys) = out_row_keys {
1349        out_row_keys.push(key.clone());
1350    }
1351}
1352
1353#[derive(Debug, Clone, PartialEq, Eq)]
1354struct ResolvedMergeSuffixes {
1355    left: Option<String>,
1356    right: Option<String>,
1357}
1358
1359impl Default for ResolvedMergeSuffixes {
1360    fn default() -> Self {
1361        Self {
1362            left: Some("_x".to_owned()),
1363            right: Some("_y".to_owned()),
1364        }
1365    }
1366}
1367
1368fn resolve_merge_suffixes(suffixes: Option<[Option<String>; 2]>) -> ResolvedMergeSuffixes {
1369    match suffixes {
1370        Some([left, right]) => ResolvedMergeSuffixes { left, right },
1371        None => ResolvedMergeSuffixes::default(),
1372    }
1373}
1374
1375fn suffix_is_present(suffix: Option<&str>) -> bool {
1376    suffix.is_some_and(|value| !value.is_empty())
1377}
1378
1379fn apply_merge_suffix(name: &str, suffix: Option<&str>) -> String {
1380    match suffix {
1381        Some(value) if !value.is_empty() => format!("{name}{value}"),
1382        _ => name.to_owned(),
1383    }
1384}
1385
1386fn collect_overlapping_column_names(
1387    left_col_names: &HashSet<&String>,
1388    right_col_names: &HashSet<&String>,
1389    excluded_names: &HashSet<&str>,
1390) -> Vec<String> {
1391    let mut overlaps = left_col_names
1392        .iter()
1393        .filter(|name| right_col_names.contains(*name) && !excluded_names.contains(name.as_str()))
1394        .map(|name| (*name).clone())
1395        .collect::<Vec<_>>();
1396    overlaps.sort();
1397    overlaps
1398}
1399
1400const SMALL_SCHEMA_LINEAR_COLUMN_LOOKUP_LIMIT: usize = 8;
1401
1402fn column_name_lookup_contains(
1403    names: &[&String],
1404    hashed_names: Option<&HashSet<&str>>,
1405    target: &str,
1406) -> bool {
1407    if let Some(hashed_names) = hashed_names {
1408        hashed_names.contains(target)
1409    } else {
1410        names.iter().any(|name| name.as_str() == target)
1411    }
1412}
1413
1414fn ensure_merge_suffixes_for_overlaps(
1415    overlap_names: &[String],
1416    suffixes: &ResolvedMergeSuffixes,
1417) -> Result<(), JoinError> {
1418    if overlap_names.is_empty() {
1419        return Ok(());
1420    }
1421    if !suffix_is_present(suffixes.left.as_deref()) && !suffix_is_present(suffixes.right.as_deref())
1422    {
1423        return Err(JoinError::Frame(FrameError::CompatibilityRejected(
1424            format!(
1425                "columns overlap but no suffix specified: {}",
1426                overlap_names.join(", ")
1427            ),
1428        )));
1429    }
1430    Ok(())
1431}
1432
1433fn insert_merged_output_column(
1434    output_columns: &mut ColumnStore,
1435    order: &mut Vec<String>,
1436    name: String,
1437    column: Column,
1438) -> Result<(), JoinError> {
1439    if output_columns.contains_key(&name) {
1440        return Err(JoinError::Frame(FrameError::CompatibilityRejected(
1441            format!("merge suffixes cause duplicate output column '{name}'"),
1442        )));
1443    }
1444    order.push(name.clone());
1445    output_columns.insert(name, column);
1446    Ok(())
1447}
1448
1449fn ordered_identity_int64_keys_match(left_key: &Column, right_key: &Column) -> bool {
1450    if left_key.len() != right_key.len()
1451        || !matches!(left_key.dtype(), DType::Int64)
1452        || !matches!(right_key.dtype(), DType::Int64)
1453        || !left_key.validity().all()
1454        || !right_key.validity().all()
1455    {
1456        return false;
1457    }
1458
1459    if let (Some(left), Some(right)) = (left_key.as_i64_slice(), right_key.as_i64_slice()) {
1460        let mut previous = None;
1461        let mut strictly_increasing = true;
1462        for (&left_value, &right_value) in left.iter().zip(right) {
1463            if left_value != right_value {
1464                return false;
1465            }
1466            if previous.is_some_and(|previous| left_value <= previous) {
1467                strictly_increasing = false;
1468                break;
1469            }
1470            previous = Some(left_value);
1471        }
1472        if strictly_increasing {
1473            return true;
1474        }
1475    }
1476
1477    // The identity fast path emits a 1:1 positional merge, which is only correct
1478    // when keys are UNIQUE. With duplicate keys pandas multiplies cardinality
1479    // (each duplicate on the left cross-joins every duplicate on the right), so
1480    // identical-but-duplicated keys must fall through to the general cartesian
1481    // path. (br-frankenpandas-jdupk)
1482    let mut seen = FxHashSet::<i64>::with_capacity_and_hasher(left_key.len(), Default::default());
1483    for (left, right) in left_key.values().iter().zip(right_key.values()) {
1484        match (left, right) {
1485            (Scalar::Int64(left), Scalar::Int64(right))
1486                if matches!(left.cmp(right), Ordering::Equal) =>
1487            {
1488                if !seen.insert(*left) {
1489                    return false;
1490                }
1491            }
1492            _ => return false,
1493        }
1494    }
1495    true
1496}
1497
1498fn strictly_increasing_int64_key_values(column: &Column) -> Option<&[Scalar]> {
1499    if column.dtype() != DType::Int64 || !column.validity().all() {
1500        return None;
1501    }
1502
1503    let values = column.values();
1504    let mut previous = None;
1505    for value in values {
1506        let current = match value {
1507            Scalar::Int64(value) => *value,
1508            _ => return None,
1509        };
1510        if previous.is_some_and(|previous| current <= previous) {
1511            return None;
1512        }
1513        previous = Some(current);
1514    }
1515    Some(values)
1516}
1517
1518fn all_valid_int64_key_values(column: &Column) -> Option<&[Scalar]> {
1519    if column.dtype() != DType::Int64 || !column.validity().all() {
1520        return None;
1521    }
1522
1523    let values = column.values();
1524    if values.iter().all(|value| matches!(value, Scalar::Int64(_))) {
1525        Some(values)
1526    } else {
1527        None
1528    }
1529}
1530
1531#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1532struct PositiveAffineI64Witness {
1533    start: i128,
1534    step: i128,
1535    len: usize,
1536}
1537
1538#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1539struct AffineInnerPositionPlan {
1540    left_start: usize,
1541    left_step: usize,
1542    right_start: usize,
1543    right_step: usize,
1544    len: usize,
1545}
1546
1547const AFFINE_I64_INNER_MAX_MORSELS: usize = 64;
1548
1549fn affine_inner_worker_count() -> usize {
1550    fp_columnar::cached_available_parallelism().min(AFFINE_I64_INNER_MAX_MORSELS)
1551}
1552
1553fn balanced_partition(total: usize, index: usize, parts: usize) -> (usize, usize) {
1554    debug_assert!(parts > 0);
1555    debug_assert!(index < parts);
1556    let base = total / parts;
1557    let remainder = total % parts;
1558    let start = index * base + index.min(remainder);
1559    let end = start + base + usize::from(index < remainder);
1560    (start, end)
1561}
1562
1563fn positive_affine_i64_shape(values: &[i64]) -> Option<PositiveAffineI64Witness> {
1564    if values.len() < 2 {
1565        return None;
1566    }
1567    let start = i128::from(values[0]);
1568    let step = i128::from(values[1]) - start;
1569    // Keeping the step within positive i64 makes every CRT intermediate below
1570    // fit i128. Rarer two-point sequences spanning more than i64::MAX retain
1571    // the existing ordered/hash route.
1572    if step <= 0 || step > i128::from(i64::MAX) {
1573        return None;
1574    }
1575    Some(PositiveAffineI64Witness {
1576        start,
1577        step,
1578        len: values.len(),
1579    })
1580}
1581
1582/// Prove two positive affine i64 key sequences with independent row morsels.
1583///
1584/// Every adjacent edge is checked exactly once, including boundaries between
1585/// morsels. A failed proof simply declines the affine route; no result is
1586/// emitted from speculative work. Large ordered joins therefore replace two
1587/// serial O(n) order scans with up to 64 shared-nothing scans while preserving
1588/// the exact strict-unique certificate required by pandas inner-join semantics.
1589fn certify_positive_affine_i64_pair(
1590    left: &[i64],
1591    right: &[i64],
1592) -> Option<(PositiveAffineI64Witness, PositiveAffineI64Witness)> {
1593    let left_shape = positive_affine_i64_shape(left)?;
1594    let right_shape = positive_affine_i64_shape(right)?;
1595    let left_edges = left.len() - 1;
1596    let right_edges = right.len() - 1;
1597    let max_edges = left_edges.max(right_edges);
1598    let worker_count = affine_inner_worker_count().min(max_edges.max(1));
1599
1600    let matches_shape = |values: &[i64], shape: PositiveAffineI64Witness| {
1601        values
1602            .windows(2)
1603            .all(|pair| i128::from(pair[1]) - i128::from(pair[0]) == shape.step)
1604    };
1605    if max_edges < DENSE_I64_INNER_PARALLEL_MIN_VALUES || worker_count < 2 {
1606        return (matches_shape(left, left_shape) && matches_shape(right, right_shape))
1607            .then_some((left_shape, right_shape));
1608    }
1609
1610    let proved = std::thread::scope(|scope| {
1611        let mut handles = Vec::with_capacity(worker_count);
1612        for worker in 0..worker_count {
1613            handles.push(scope.spawn(move || {
1614                let (left_start, left_end) = balanced_partition(left_edges, worker, worker_count);
1615                let (right_start, right_end) =
1616                    balanced_partition(right_edges, worker, worker_count);
1617                let left_ok = (left_start..left_end).all(|idx| {
1618                    i128::from(left[idx + 1]) - i128::from(left[idx]) == left_shape.step
1619                });
1620                let right_ok = (right_start..right_end).all(|idx| {
1621                    i128::from(right[idx + 1]) - i128::from(right[idx]) == right_shape.step
1622                });
1623                left_ok && right_ok
1624            }));
1625        }
1626        handles
1627            .into_iter()
1628            .all(|handle| handle.join().expect("affine join proof worker panicked"))
1629    });
1630    proved.then_some((left_shape, right_shape))
1631}
1632
1633fn positive_i128_gcd(mut left: i128, mut right: i128) -> i128 {
1634    debug_assert!(left > 0 && right > 0);
1635    while right != 0 {
1636        let remainder = left % right;
1637        left = right;
1638        right = remainder;
1639    }
1640    left
1641}
1642
1643fn coprime_mod_inverse(value: i128, modulus: i128) -> Option<i128> {
1644    debug_assert!(value > 0 && modulus > 1);
1645    let (mut old_remainder, mut remainder) = (value, modulus);
1646    let (mut old_coefficient, mut coefficient) = (1i128, 0i128);
1647    while remainder != 0 {
1648        let quotient = old_remainder / remainder;
1649        (old_remainder, remainder) = (
1650            remainder,
1651            old_remainder.checked_sub(quotient.checked_mul(remainder)?)?,
1652        );
1653        (old_coefficient, coefficient) = (
1654            coefficient,
1655            old_coefficient.checked_sub(quotient.checked_mul(coefficient)?)?,
1656        );
1657    }
1658    (old_remainder == 1).then(|| old_coefficient.rem_euclid(modulus))
1659}
1660
1661fn empty_affine_inner_position_plan() -> AffineInnerPositionPlan {
1662    AffineInnerPositionPlan {
1663        left_start: 0,
1664        left_step: 1,
1665        right_start: 0,
1666        right_step: 1,
1667        len: 0,
1668    }
1669}
1670
1671/// Intersect two certified positive affine sequences analytically.
1672///
1673/// The generalized CRT yields the first shared key and the common step. Those
1674/// map back to affine row selections on each input, so the join needs neither
1675/// the serial two-pointer merge nor its two O(matches) position vectors.
1676fn affine_i64_inner_position_plan(
1677    left: PositiveAffineI64Witness,
1678    right: PositiveAffineI64Witness,
1679) -> Option<AffineInnerPositionPlan> {
1680    let left_last = left
1681        .start
1682        .checked_add(left.step.checked_mul(i128::try_from(left.len - 1).ok()?)?)?;
1683    let right_last = right.start.checked_add(
1684        right
1685            .step
1686            .checked_mul(i128::try_from(right.len - 1).ok()?)?,
1687    )?;
1688    let low = left.start.max(right.start);
1689    let high = left_last.min(right_last);
1690    if low > high {
1691        return Some(empty_affine_inner_position_plan());
1692    }
1693
1694    let gcd = positive_i128_gcd(left.step, right.step);
1695    let difference = right.start.checked_sub(left.start)?;
1696    if difference % gcd != 0 {
1697        return Some(empty_affine_inner_position_plan());
1698    }
1699    let left_reduced = left.step / gcd;
1700    let right_reduced = right.step / gcd;
1701    let left_solution = if right_reduced == 1 {
1702        0
1703    } else {
1704        let inverse = coprime_mod_inverse(left_reduced.rem_euclid(right_reduced), right_reduced)?;
1705        difference
1706            .checked_div(gcd)?
1707            .checked_mul(inverse)?
1708            .rem_euclid(right_reduced)
1709    };
1710    let common_step = left.step.checked_mul(right_reduced)?;
1711    let mut first = left
1712        .start
1713        .checked_add(left.step.checked_mul(left_solution)?)?;
1714    if first < low {
1715        let delta = low.checked_sub(first)?;
1716        let jumps = delta
1717            .checked_add(common_step - 1)?
1718            .checked_div(common_step)?;
1719        first = first.checked_add(jumps.checked_mul(common_step)?)?;
1720    }
1721    if first > high {
1722        return Some(empty_affine_inner_position_plan());
1723    }
1724
1725    let len = usize::try_from((high - first) / common_step + 1).ok()?;
1726    let left_start = usize::try_from((first - left.start) / left.step).ok()?;
1727    let right_start = usize::try_from((first - right.start) / right.step).ok()?;
1728    let left_step = usize::try_from(common_step / left.step).ok()?;
1729    let right_step = usize::try_from(common_step / right.step).ok()?;
1730    debug_assert!(
1731        left_start
1732            .checked_add(left_step.saturating_mul(len.saturating_sub(1)))
1733            .is_some_and(|last| last < left.len)
1734    );
1735    debug_assert!(
1736        right_start
1737            .checked_add(right_step.saturating_mul(len.saturating_sub(1)))
1738            .is_some_and(|last| last < right.len)
1739    );
1740    Some(AffineInnerPositionPlan {
1741        left_start,
1742        left_step,
1743        right_start,
1744        right_step,
1745        len,
1746    })
1747}
1748
1749enum AffineInnerOutputLane<'a> {
1750    Int64 {
1751        source: &'a [i64],
1752        start: usize,
1753        step: usize,
1754    },
1755    Built(Column),
1756}
1757
1758struct AffineInnerOutputSpec<'a> {
1759    name: String,
1760    lane: AffineInnerOutputLane<'a>,
1761}
1762
1763fn affine_selection_positions(start: usize, step: usize, len: usize) -> Vec<usize> {
1764    (0..len).map(|idx| start + idx * step).collect()
1765}
1766
1767fn affine_inner_output_lane<'a>(
1768    column: &'a Column,
1769    start: usize,
1770    step: usize,
1771    len: usize,
1772) -> Option<AffineInnerOutputLane<'a>> {
1773    if let Some(source) = column.as_i64_slice() {
1774        return Some(AffineInnerOutputLane::Int64 {
1775            source,
1776            start,
1777            step,
1778        });
1779    }
1780    column.as_f64_slice()?;
1781    let built = if len == 0 {
1782        Column::from_f64_values(Vec::new())
1783    } else if let Some(view) =
1784        column.take_affine_positions_without_materialized_positions(start, step, len)
1785    {
1786        view
1787    } else {
1788        let positions = affine_selection_positions(start, step, len);
1789        column.take_positions(&positions)
1790    };
1791    Some(AffineInnerOutputLane::Built(built))
1792}
1793
1794/// Zero-copy Int64 output for a unit-stride side of an affine match.
1795///
1796/// Shared inner-join keys are byte-identical on both sides. If either side's
1797/// matched rows form one contiguous range, reuse that immutable Arc-backed
1798/// range as a one-chunk output instead of filling an O(matches) key buffer.
1799fn affine_unit_stride_i64_view(
1800    column: &Column,
1801    start: usize,
1802    step: usize,
1803    len: usize,
1804) -> Option<Column> {
1805    if len == 0 {
1806        return Some(Column::from_i64_values_owned(Vec::new()));
1807    }
1808    if step != 1 {
1809        return None;
1810    }
1811    let (data, base) = column.as_i64_arc_view_source()?;
1812    let view_start = base.checked_add(start)?;
1813    view_start
1814        .checked_add(len)
1815        .filter(|&end| end <= data.len())?;
1816    Some(Column::from_i64_all_valid_chunks(
1817        vec![(data, view_start, len)],
1818        len,
1819    ))
1820}
1821
1822/// Fill all Int64 affine output lanes by row morsel into disjoint buffers.
1823/// Float64 lanes are descriptor-only strided views and never enter this fill.
1824fn build_affine_inner_i64_lanes(sources: &[(&[i64], usize, usize)], len: usize) -> Vec<Vec<i64>> {
1825    let mut output: Vec<Vec<i64>> = sources.iter().map(|_| vec![0i64; len]).collect();
1826    if sources.is_empty() || len == 0 {
1827        return output;
1828    }
1829    let worker_count = affine_inner_worker_count().min(len);
1830    if len < DENSE_I64_INNER_PARALLEL_MIN_VALUES || worker_count < 2 {
1831        for (lane, &(source, start, step)) in output.iter_mut().zip(sources) {
1832            for (row, value) in lane.iter_mut().enumerate() {
1833                *value = source[start + row * step];
1834            }
1835        }
1836        return output;
1837    }
1838
1839    let mut bundles: Vec<Vec<&mut [i64]>> = (0..worker_count)
1840        .map(|_| Vec::with_capacity(output.len()))
1841        .collect();
1842    for lane in &mut output {
1843        let mut remainder = lane.as_mut_slice();
1844        for (worker, bundle) in bundles.iter_mut().enumerate() {
1845            let (row_start, row_end) = balanced_partition(len, worker, worker_count);
1846            let (chunk, tail) = remainder.split_at_mut(row_end - row_start);
1847            bundle.push(chunk);
1848            remainder = tail;
1849        }
1850    }
1851
1852    std::thread::scope(|scope| {
1853        for (worker, mut bundle) in bundles.into_iter().enumerate() {
1854            let (row_start, _) = balanced_partition(len, worker, worker_count);
1855            scope.spawn(move || {
1856                for (lane, &(source, start, step)) in bundle.iter_mut().zip(sources) {
1857                    for (local_row, value) in lane.iter_mut().enumerate() {
1858                        *value = source[start + (row_start + local_row) * step];
1859                    }
1860                }
1861            });
1862        }
1863    });
1864    output
1865}
1866
1867/// Shared-nothing affine Int64 inner merge.
1868///
1869/// This is deliberately narrow but structural: all-valid typed Int64 keys are
1870/// certified as positive affine sequences; every carried lane must be an
1871/// all-valid Int64 or Float64. The match relation is then a pair of affine row
1872/// selections. Float64 payloads become zero-copy strided views, while all
1873/// Int64 lanes are filled together across row morsels. Any unsupported shape
1874/// falls through to the general ordered/dense/hash implementations.
1875fn build_single_key_affine_i64_inner_merge_output(
1876    left: &fp_frame::DataFrame,
1877    right: &fp_frame::DataFrame,
1878    left_on: &[&str],
1879    right_on: &[&str],
1880    left_key: &Column,
1881    right_key: &Column,
1882    suffixes: &ResolvedMergeSuffixes,
1883) -> Result<Option<MergedDataFrame>, JoinError> {
1884    debug_assert_eq!(left_on.len(), 1);
1885    debug_assert_eq!(right_on.len(), 1);
1886    let (Some(left_keys), Some(right_keys)) = (left_key.as_i64_slice(), right_key.as_i64_slice())
1887    else {
1888        return Ok(None);
1889    };
1890    let Some((left_shape, right_shape)) = certify_positive_affine_i64_pair(left_keys, right_keys)
1891    else {
1892        return Ok(None);
1893    };
1894    let Some(plan) = affine_i64_inner_position_plan(left_shape, right_shape) else {
1895        return Ok(None);
1896    };
1897
1898    let left_col_names: HashSet<&String> = left.columns().keys().collect();
1899    let right_col_names: HashSet<&String> = right.columns().keys().collect();
1900    let shared_key_names = if left_on[0] == right_on[0] {
1901        [left_on[0]].into_iter().collect::<HashSet<&str>>()
1902    } else {
1903        HashSet::new()
1904    };
1905    let overlapping_names =
1906        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
1907    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
1908
1909    let mut specs = Vec::<AffineInnerOutputSpec<'_>>::new();
1910    for name in left.column_names() {
1911        let column = left
1912            .columns()
1913            .get(name)
1914            .expect("left column listed in column_names must exist");
1915        let out_name = if name.as_str() == left_on[0] {
1916            name.clone()
1917        } else if right_col_names.contains(name) {
1918            apply_merge_suffix(name, suffixes.left.as_deref())
1919        } else {
1920            name.clone()
1921        };
1922        let shared_key_view = (name.as_str() == left_on[0] && left_on[0] == right_on[0])
1923            .then(|| {
1924                affine_unit_stride_i64_view(left_key, plan.left_start, plan.left_step, plan.len)
1925                    .or_else(|| {
1926                        affine_unit_stride_i64_view(
1927                            right_key,
1928                            plan.right_start,
1929                            plan.right_step,
1930                            plan.len,
1931                        )
1932                    })
1933                    .map(AffineInnerOutputLane::Built)
1934            })
1935            .flatten();
1936        let Some(lane) = shared_key_view.or_else(|| {
1937            affine_inner_output_lane(column, plan.left_start, plan.left_step, plan.len)
1938        }) else {
1939            return Ok(None);
1940        };
1941        specs.push(AffineInnerOutputSpec {
1942            name: out_name,
1943            lane,
1944        });
1945    }
1946    for name in right.column_names() {
1947        if name.as_str() == right_on[0] && shared_key_names.contains(name.as_str()) {
1948            continue;
1949        }
1950        let column = right
1951            .columns()
1952            .get(name)
1953            .expect("right column listed in column_names must exist");
1954        let out_name = if left_col_names.contains(name) {
1955            apply_merge_suffix(name, suffixes.right.as_deref())
1956        } else {
1957            name.clone()
1958        };
1959        let Some(lane) =
1960            affine_inner_output_lane(column, plan.right_start, plan.right_step, plan.len)
1961        else {
1962            return Ok(None);
1963        };
1964        specs.push(AffineInnerOutputSpec {
1965            name: out_name,
1966            lane,
1967        });
1968    }
1969
1970    let i64_sources: Vec<(&[i64], usize, usize)> = specs
1971        .iter()
1972        .filter_map(|spec| match &spec.lane {
1973            AffineInnerOutputLane::Int64 {
1974                source,
1975                start,
1976                step,
1977            } => Some((*source, *start, *step)),
1978            AffineInnerOutputLane::Built(_) => None,
1979        })
1980        .collect();
1981    let mut i64_lanes = build_affine_inner_i64_lanes(&i64_sources, plan.len).into_iter();
1982    let index = Index::new_known_unique_int64_unit_range(0, plan.len);
1983    let mut columns = ColumnStore::new();
1984    let mut column_order = Vec::with_capacity(specs.len());
1985    for spec in specs {
1986        let column = match spec.lane {
1987            AffineInnerOutputLane::Int64 { .. } => Column::from_i64_values_owned(
1988                i64_lanes
1989                    .next()
1990                    .expect("one filled lane for every affine Int64 output"),
1991            ),
1992            AffineInnerOutputLane::Built(column) => column,
1993        };
1994        debug_assert_eq!(column.len(), plan.len);
1995        insert_merged_output_column(&mut columns, &mut column_order, spec.name, column)?;
1996    }
1997    Ok(Some(MergedDataFrame {
1998        index,
1999        columns,
2000        column_order,
2001    }))
2002}
2003
2004fn ordered_unique_int64_inner_positions(
2005    left_key: &Column,
2006    right_key: &Column,
2007) -> Option<(Vec<usize>, Vec<usize>)> {
2008    // Typed fast path (see ordered_unique_int64_left_match_positions): walk the
2009    // ordered intersection over raw &[i64] when both keys carry a contiguous
2010    // Int64 backing, skipping the Vec<Scalar> materialization (32 B/elem, ~64 MB
2011    // per merge at 1M rows). Bit-identical: same strictly-increasing gate and
2012    // the same monotone merge emitting the same (left_idx, right_idx) pairs.
2013    if let (Some(left_values), Some(right_values)) = (
2014        strictly_increasing_i64_slice(left_key),
2015        strictly_increasing_i64_slice(right_key),
2016    ) {
2017        let mut left_positions =
2018            Vec::<usize>::with_capacity(left_values.len().min(right_values.len()));
2019        let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
2020        let (mut left_idx, mut right_idx) = (0usize, 0usize);
2021        while left_idx < left_values.len() && right_idx < right_values.len() {
2022            match left_values[left_idx].cmp(&right_values[right_idx]) {
2023                Ordering::Equal => {
2024                    left_positions.push(left_idx);
2025                    right_positions.push(right_idx);
2026                    left_idx += 1;
2027                    right_idx += 1;
2028                }
2029                Ordering::Less => left_idx += 1,
2030                Ordering::Greater => right_idx += 1,
2031            }
2032        }
2033        return Some((left_positions, right_positions));
2034    }
2035
2036    let left_values = strictly_increasing_int64_key_values(left_key)?;
2037    let right_values = strictly_increasing_int64_key_values(right_key)?;
2038
2039    let mut left_positions = Vec::<usize>::with_capacity(left_values.len().min(right_values.len()));
2040    let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
2041    let mut left_idx = 0usize;
2042    let mut right_idx = 0usize;
2043
2044    while left_idx < left_values.len() && right_idx < right_values.len() {
2045        let left_value = match &left_values[left_idx] {
2046            Scalar::Int64(value) => *value,
2047            _ => return None,
2048        };
2049        let right_value = match &right_values[right_idx] {
2050            Scalar::Int64(value) => *value,
2051            _ => return None,
2052        };
2053
2054        match left_value.cmp(&right_value) {
2055            Ordering::Equal => {
2056                left_positions.push(left_idx);
2057                right_positions.push(right_idx);
2058                left_idx += 1;
2059                right_idx += 1;
2060            }
2061            Ordering::Less => left_idx += 1,
2062            Ordering::Greater => right_idx += 1,
2063        }
2064    }
2065
2066    Some((left_positions, right_positions))
2067}
2068
2069fn strictly_increasing_utf8_key_spans(column: &Column) -> Option<(&[u8], &[usize])> {
2070    column.as_strictly_increasing_utf8_contiguous()
2071}
2072
2073fn utf8_span<'a>(bytes: &'a [u8], offsets: &[usize], pos: usize) -> &'a [u8] {
2074    &bytes[offsets[pos]..offsets[pos + 1]]
2075}
2076
2077fn utf8_offsets_are_sorted(bytes: &[u8], offsets: &[usize]) -> bool {
2078    offsets
2079        .windows(3)
2080        .all(|window| bytes[window[0]..window[1]] <= bytes[window[1]..window[2]])
2081}
2082
2083fn sorted_contiguous_utf8_inner_positions(
2084    left_bytes: &[u8],
2085    left_offsets: &[usize],
2086    right_bytes: &[u8],
2087    right_offsets: &[usize],
2088) -> Option<(Vec<usize>, Vec<usize>)> {
2089    if !utf8_offsets_are_sorted(left_bytes, left_offsets)
2090        || !utf8_offsets_are_sorted(right_bytes, right_offsets)
2091    {
2092        return None;
2093    }
2094
2095    let left_n = left_offsets.len() - 1;
2096    let right_n = right_offsets.len() - 1;
2097    let mut left_positions = Vec::<usize>::with_capacity(left_n.min(right_n));
2098    let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
2099    let mut left_pos = 0usize;
2100    let mut right_pos = 0usize;
2101
2102    while left_pos < left_n && right_pos < right_n {
2103        let left_span = utf8_span(left_bytes, left_offsets, left_pos);
2104        let right_span = utf8_span(right_bytes, right_offsets, right_pos);
2105        match left_span.cmp(right_span) {
2106            Ordering::Less => left_pos += 1,
2107            Ordering::Greater => right_pos += 1,
2108            Ordering::Equal => {
2109                let left_start = left_pos;
2110                let right_start = right_pos;
2111                while left_pos < left_n
2112                    && utf8_span(left_bytes, left_offsets, left_pos) == left_span
2113                {
2114                    left_pos += 1;
2115                }
2116                while right_pos < right_n
2117                    && utf8_span(right_bytes, right_offsets, right_pos) == right_span
2118                {
2119                    right_pos += 1;
2120                }
2121                for matched_left in left_start..left_pos {
2122                    for matched_right in right_start..right_pos {
2123                        left_positions.push(matched_left);
2124                        right_positions.push(matched_right);
2125                    }
2126                }
2127            }
2128        }
2129    }
2130
2131    Some((left_positions, right_positions))
2132}
2133
2134fn utf8_span_lower_bound(bytes: &[u8], offsets: &[usize], needle: &[u8]) -> usize {
2135    let mut lo = 0usize;
2136    let mut hi = offsets.len() - 1;
2137    while lo < hi {
2138        let mid = lo + (hi - lo) / 2;
2139        if utf8_span(bytes, offsets, mid) < needle {
2140            lo = mid + 1;
2141        } else {
2142            hi = mid;
2143        }
2144    }
2145    lo
2146}
2147
2148fn ordered_unique_utf8_fixed_width(left_key: &Column, right_key: &Column) -> Option<usize> {
2149    let (_, _, left_width) = left_key.as_fixed_width_strictly_increasing_utf8_contiguous()?;
2150    let (_, _, right_width) = right_key.as_fixed_width_strictly_increasing_utf8_contiguous()?;
2151    (left_width == right_width && left_width > 0).then_some(left_width)
2152}
2153
2154fn ordered_utf8_lower_hex_overlap_len(
2155    left_cert: Utf8LowerHexSequence,
2156    right_cert: Utf8LowerHexSequence,
2157    left_idx: usize,
2158    left_n: usize,
2159    right_idx: usize,
2160    right_n: usize,
2161) -> Option<usize> {
2162    if !left_cert.same_shape(right_cert) {
2163        return None;
2164    }
2165    let left_value = left_cert.value_at(left_idx)?;
2166    let right_value = right_cert.value_at(right_idx)?;
2167    if left_value != right_value {
2168        return None;
2169    }
2170    Some(left_n.saturating_sub(left_idx).min(right_n - right_idx))
2171}
2172
2173fn lower_hex_overlap_plan_from_certificates(
2174    left_key: &Column,
2175    right_key: &Column,
2176) -> Option<InnerPositionPlan> {
2177    let (left_prefix, left_cert, left_n) = left_key.as_lower_hex_sequence_utf8()?;
2178    let (right_prefix, right_cert, right_n) = right_key.as_lower_hex_sequence_utf8()?;
2179    if !left_cert.same_shape(right_cert) {
2180        return None;
2181    }
2182    if left_prefix != right_prefix {
2183        return None;
2184    }
2185
2186    let left_n = u64::try_from(left_n).ok()?;
2187    let right_n = u64::try_from(right_n).ok()?;
2188    if left_n == 0 || right_n == 0 {
2189        return Some(InnerPositionPlan::Gather {
2190            left_positions: Vec::new(),
2191            right_positions: Vec::new(),
2192        });
2193    }
2194
2195    let left_start_value = left_cert.start();
2196    let right_start_value = right_cert.start();
2197    let left_end_value = left_start_value.checked_add(left_n)?;
2198    let right_end_value = right_start_value.checked_add(right_n)?;
2199    let overlap_start = left_start_value.max(right_start_value);
2200    let overlap_end = left_end_value.min(right_end_value);
2201    if overlap_start >= overlap_end {
2202        return Some(InnerPositionPlan::Gather {
2203            left_positions: Vec::new(),
2204            right_positions: Vec::new(),
2205        });
2206    }
2207
2208    let len = usize::try_from(overlap_end.checked_sub(overlap_start)?).ok()?;
2209    let left_start = usize::try_from(overlap_start.checked_sub(left_start_value)?).ok()?;
2210    let right_start = usize::try_from(overlap_start.checked_sub(right_start_value)?).ok()?;
2211    let left_len = usize::try_from(left_n).ok()?;
2212    let right_len = usize::try_from(right_n).ok()?;
2213    let left_end = left_start.checked_add(len)?;
2214    let right_end = right_start.checked_add(len)?;
2215    if left_end > left_len || right_end > right_len {
2216        return None;
2217    }
2218
2219    Some(InnerPositionPlan::ContiguousRanges {
2220        left_start,
2221        right_start,
2222        len,
2223    })
2224}
2225
2226#[derive(Debug, Clone, PartialEq, Eq)]
2227enum InnerPositionPlan {
2228    Gather {
2229        left_positions: Vec<usize>,
2230        right_positions: Vec<usize>,
2231    },
2232    ContiguousRanges {
2233        left_start: usize,
2234        right_start: usize,
2235        len: usize,
2236    },
2237}
2238
2239impl InnerPositionPlan {
2240    #[cfg(test)]
2241    fn into_positions(self) -> (Vec<usize>, Vec<usize>) {
2242        match self {
2243            Self::Gather {
2244                left_positions,
2245                right_positions,
2246            } => (left_positions, right_positions),
2247            Self::ContiguousRanges {
2248                left_start,
2249                right_start,
2250                len,
2251            } => (
2252                (left_start..left_start + len).collect(),
2253                (right_start..right_start + len).collect(),
2254            ),
2255        }
2256    }
2257}
2258
2259/// Hash-free ordered merge for all-valid, strictly increasing contiguous-Utf8
2260/// keys. This is the string-key analogue of
2261/// [`ordered_unique_int64_inner_positions`]: each side is unique and already in
2262/// key order, so a two-cursor byte-span merge emits the exact same 1:1
2263/// `(left_pos, right_pos)` pairs as the hash path while skipping hash table
2264/// build/probe entirely. Duplicate or unsorted inputs fall back to the
2265/// left-major byte-span hash path, preserving pandas row order.
2266fn ordered_unique_utf8_inner_position_plan(
2267    left_key: &Column,
2268    right_key: &Column,
2269) -> Option<InnerPositionPlan> {
2270    if let Some(plan) = lower_hex_overlap_plan_from_certificates(left_key, right_key) {
2271        return Some(plan);
2272    }
2273
2274    let (left_bytes, left_offsets) = strictly_increasing_utf8_key_spans(left_key)?;
2275    let (right_bytes, right_offsets) = strictly_increasing_utf8_key_spans(right_key)?;
2276    let left_n = left_offsets.len() - 1;
2277    let right_n = right_offsets.len() - 1;
2278    let fixed_width = ordered_unique_utf8_fixed_width(left_key, right_key);
2279
2280    if left_n == 0 || right_n == 0 {
2281        return Some(InnerPositionPlan::Gather {
2282            left_positions: Vec::new(),
2283            right_positions: Vec::new(),
2284        });
2285    }
2286
2287    let mut left_positions = Vec::<usize>::with_capacity(left_n.min(right_n));
2288    let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
2289
2290    let first_left = utf8_span(left_bytes, left_offsets, 0);
2291    let last_left = utf8_span(left_bytes, left_offsets, left_n - 1);
2292    let first_right = utf8_span(right_bytes, right_offsets, 0);
2293    let last_right = utf8_span(right_bytes, right_offsets, right_n - 1);
2294    if last_left < first_right || last_right < first_left {
2295        return Some(InnerPositionPlan::Gather {
2296            left_positions,
2297            right_positions,
2298        });
2299    }
2300
2301    let mut left_idx = utf8_span_lower_bound(left_bytes, left_offsets, first_right);
2302    let mut right_idx = if left_idx < left_n {
2303        utf8_span_lower_bound(
2304            right_bytes,
2305            right_offsets,
2306            utf8_span(left_bytes, left_offsets, left_idx),
2307        )
2308    } else {
2309        right_n
2310    };
2311    let mut fixed_width_bulk_attempted = false;
2312
2313    while left_idx < left_n && right_idx < right_n {
2314        let left_span = utf8_span(left_bytes, left_offsets, left_idx);
2315        let right_span = utf8_span(right_bytes, right_offsets, right_idx);
2316
2317        match left_span.cmp(right_span) {
2318            Ordering::Equal => {
2319                if let Some(width) = fixed_width
2320                    && !fixed_width_bulk_attempted
2321                {
2322                    fixed_width_bulk_attempted = true;
2323                    // This branch is reached only after the current left/right
2324                    // key spans compare equal. Matching lower-hex shapes then
2325                    // prove the remaining shifted windows without a full
2326                    // byte-window memcmp.
2327                    let lower_hex_sequences = match (
2328                        left_key.as_lower_hex_sequence_utf8_contiguous(),
2329                        right_key.as_lower_hex_sequence_utf8_contiguous(),
2330                    ) {
2331                        (Some((_, _, left_cert)), Some((_, _, right_cert))) => {
2332                            Some((left_cert, right_cert))
2333                        }
2334                        _ => None,
2335                    };
2336                    if let Some((left_cert, right_cert)) = lower_hex_sequences
2337                        && let Some(run_len) = ordered_utf8_lower_hex_overlap_len(
2338                            left_cert, right_cert, left_idx, left_n, right_idx, right_n,
2339                        )
2340                        && run_len > 1
2341                    {
2342                        if left_positions.is_empty() {
2343                            return Some(InnerPositionPlan::ContiguousRanges {
2344                                left_start: left_idx,
2345                                right_start: right_idx,
2346                                len: run_len,
2347                            });
2348                        }
2349                        left_positions.extend(left_idx..left_idx + run_len);
2350                        right_positions.extend(right_idx..right_idx + run_len);
2351                        left_idx += run_len;
2352                        right_idx += run_len;
2353                        continue;
2354                    }
2355                    let run_len = left_n.saturating_sub(left_idx).min(right_n - right_idx);
2356                    if run_len > 1
2357                        && let Some(byte_len) = run_len.checked_mul(width)
2358                    {
2359                        let left_start = left_offsets[left_idx];
2360                        let right_start = right_offsets[right_idx];
2361                        let left_end = left_start + byte_len;
2362                        let right_end = right_start + byte_len;
2363                        if left_end <= left_bytes.len()
2364                            && right_end <= right_bytes.len()
2365                            && left_bytes[left_start..left_end]
2366                                == right_bytes[right_start..right_end]
2367                        {
2368                            if left_positions.is_empty() {
2369                                return Some(InnerPositionPlan::ContiguousRanges {
2370                                    left_start: left_idx,
2371                                    right_start: right_idx,
2372                                    len: run_len,
2373                                });
2374                            }
2375                            left_positions.extend(left_idx..left_idx + run_len);
2376                            right_positions.extend(right_idx..right_idx + run_len);
2377                            left_idx += run_len;
2378                            right_idx += run_len;
2379                            continue;
2380                        }
2381                    }
2382                }
2383                left_positions.push(left_idx);
2384                right_positions.push(right_idx);
2385                left_idx += 1;
2386                right_idx += 1;
2387            }
2388            Ordering::Less => left_idx += 1,
2389            Ordering::Greater => right_idx += 1,
2390        }
2391    }
2392
2393    Some(InnerPositionPlan::Gather {
2394        left_positions,
2395        right_positions,
2396    })
2397}
2398
2399#[cfg(test)]
2400fn ordered_unique_utf8_inner_positions(
2401    left_key: &Column,
2402    right_key: &Column,
2403) -> Option<(Vec<usize>, Vec<usize>)> {
2404    ordered_unique_utf8_inner_position_plan(left_key, right_key)
2405        .map(InnerPositionPlan::into_positions)
2406}
2407
2408/// Strictly-increasing check over a column's contiguous `&[i64]` backing,
2409/// returning the raw slice. The typed analogue of
2410/// `strictly_increasing_int64_key_values` that skips the `Vec<Scalar>`
2411/// materialization (32 B/elem) — `as_i64_slice` is `Some` only for an
2412/// all-valid contiguous Int64 column, the same gate as the Scalar version
2413/// (dtype Int64 + `validity().all()` + every value `Scalar::Int64`).
2414fn strictly_increasing_i64_slice(column: &Column) -> Option<&[i64]> {
2415    let data = column.as_i64_slice()?;
2416    if data.windows(2).any(|pair| pair[1] <= pair[0]) {
2417        return None;
2418    }
2419    Some(data)
2420}
2421
2422fn ordered_unique_int64_left_match_positions(
2423    left_key: &Column,
2424    right_key: &Column,
2425) -> Option<Vec<Option<usize>>> {
2426    // Typed fast path: both keys carry a contiguous Int64 backing, so run the
2427    // ordered two-pointer match over raw `&[i64]` (8 B/elem, cache-friendly)
2428    // instead of materializing two `Vec<Scalar>` (32 B/elem — ~32 MB per side
2429    // at 1M rows, the tax that left-join paid but the typed inner path did
2430    // not). Bit-identical: same strictly-increasing gate and the same
2431    // monotone walk producing the same `right_idx` per left row.
2432    if let (Some(left_values), Some(right_values)) = (
2433        strictly_increasing_i64_slice(left_key),
2434        strictly_increasing_i64_slice(right_key),
2435    ) {
2436        let mut right_positions = Vec::<Option<usize>>::with_capacity(left_values.len());
2437        let mut right_idx = 0usize;
2438        for &left_value in left_values {
2439            while right_idx < right_values.len() && right_values[right_idx] < left_value {
2440                right_idx += 1;
2441            }
2442            let matched = match right_values.get(right_idx) {
2443                Some(&right_value) if right_value == left_value => Some(right_idx),
2444                _ => None,
2445            };
2446            right_positions.push(matched);
2447        }
2448        return Some(right_positions);
2449    }
2450
2451    let left_values = strictly_increasing_int64_key_values(left_key)?;
2452    let right_values = strictly_increasing_int64_key_values(right_key)?;
2453
2454    let mut right_positions = Vec::<Option<usize>>::with_capacity(left_values.len());
2455    let mut right_idx = 0usize;
2456
2457    for left_value in left_values {
2458        let Scalar::Int64(left_value) = left_value else {
2459            return None;
2460        };
2461        while let Some(Scalar::Int64(right_value)) = right_values.get(right_idx)
2462            && right_value < left_value
2463        {
2464            right_idx += 1;
2465        }
2466
2467        let matched = match right_values.get(right_idx) {
2468            Some(Scalar::Int64(right_value)) if right_value == left_value => Some(right_idx),
2469            Some(Scalar::Int64(_)) | None => None,
2470            Some(_) => return None,
2471        };
2472        right_positions.push(matched);
2473    }
2474
2475    Some(right_positions)
2476}
2477
2478fn ordered_unique_int64_right_match_positions(
2479    left_key: &Column,
2480    right_key: &Column,
2481) -> Option<Vec<Option<usize>>> {
2482    // Typed fast path (mirror of ordered_unique_int64_left_match_positions):
2483    // walk over raw &[i64] when both keys carry a contiguous Int64 backing,
2484    // skipping the Vec<Scalar> materialization (32 B/elem, ~64 MB per merge at
2485    // 1M rows). Bit-identical: same strictly-increasing gate and the same
2486    // monotone walk producing the same left_idx per right row.
2487    if let (Some(left_values), Some(right_values)) = (
2488        strictly_increasing_i64_slice(left_key),
2489        strictly_increasing_i64_slice(right_key),
2490    ) {
2491        let mut left_positions = Vec::<Option<usize>>::with_capacity(right_values.len());
2492        let mut left_idx = 0usize;
2493        for &right_value in right_values {
2494            while left_idx < left_values.len() && left_values[left_idx] < right_value {
2495                left_idx += 1;
2496            }
2497            let matched = match left_values.get(left_idx) {
2498                Some(&left_value) if left_value == right_value => Some(left_idx),
2499                _ => None,
2500            };
2501            left_positions.push(matched);
2502        }
2503        return Some(left_positions);
2504    }
2505
2506    let left_values = strictly_increasing_int64_key_values(left_key)?;
2507    let right_values = strictly_increasing_int64_key_values(right_key)?;
2508
2509    let mut left_positions = Vec::<Option<usize>>::with_capacity(right_values.len());
2510    let mut left_idx = 0usize;
2511
2512    for right_value in right_values {
2513        let Scalar::Int64(right_value) = right_value else {
2514            return None;
2515        };
2516        while let Some(Scalar::Int64(left_value)) = left_values.get(left_idx)
2517            && left_value < right_value
2518        {
2519            left_idx += 1;
2520        }
2521
2522        let matched = match left_values.get(left_idx) {
2523            Some(Scalar::Int64(left_value)) if left_value == right_value => Some(left_idx),
2524            Some(Scalar::Int64(_)) | None => None,
2525            Some(_) => return None,
2526        };
2527        left_positions.push(matched);
2528    }
2529
2530    Some(left_positions)
2531}
2532
2533type OptionalJoinPositions = (Vec<Option<usize>>, Vec<Option<usize>>);
2534
2535/// Direct-address unique-key fast path for a bounded-span Int64 left/inner
2536/// join. When the right keys are *unique* within their value span, the
2537/// counting-sort CSR (count + prefix-sum + scatter + per-bucket emit, over
2538/// several span-sized `usize` arrays) collapses to a single fill pass over one
2539/// compact `u32` table (`pos+1`, `0` == empty) plus a single probe pass — ~14x
2540/// faster at 1M (and faster than open-addressing hashing, no hash/probe).
2541///
2542/// Returns `None` (caller falls back to the CSR path) when: a key column is not
2543/// a contiguous `&[i64]`, the right side is empty, the span exceeds the dense
2544/// gate, the row count would overflow `u32`, or a *duplicate* right key is seen
2545/// (then the CSR path's per-bucket emission is required). For unique right keys
2546/// the emitted `(Some(left_pos), match)` pairs are byte-identical to the CSR
2547/// path: one row per left key in left order, matching the single right position
2548/// in its bucket (or `None` when absent / out of span).
2549fn dense_int64_unique_right_left_positions(
2550    left_key: &Column,
2551    right_key: &Column,
2552) -> Option<OptionalJoinPositions> {
2553    let left_values = left_key.as_i64_slice()?;
2554    let right_values = right_key.as_i64_slice()?;
2555    if right_values.is_empty() || left_values.len() > u32::MAX as usize {
2556        return None;
2557    }
2558
2559    let mut min_key = i64::MAX;
2560    let mut max_key = i64::MIN;
2561    for &key in right_values {
2562        min_key = min_key.min(key);
2563        max_key = max_key.max(key);
2564    }
2565
2566    let span = i128::from(max_key)
2567        .checked_sub(i128::from(min_key))?
2568        .checked_add(1)?;
2569    let row_count = left_values.len().saturating_add(right_values.len());
2570    let max_dense_span = row_count.saturating_mul(4).max(1024);
2571    if span > max_dense_span as i128 {
2572        return None;
2573    }
2574    let span = usize::try_from(span).ok()?;
2575    let span_i128 = i128::try_from(span).ok()?;
2576
2577    // Fill the direct-address table; a non-empty slot means a duplicate right
2578    // key, so bail to the CSR path (which handles many-to-many emission).
2579    let mut table = vec![0u32; span];
2580    for (pos, &key) in right_values.iter().enumerate() {
2581        let bucket = usize::try_from(i128::from(key) - i128::from(min_key)).ok()?;
2582        if table[bucket] != 0 {
2583            return None;
2584        }
2585        table[bucket] = (pos as u32).checked_add(1)?;
2586    }
2587
2588    let mut left_positions = Vec::<Option<usize>>::with_capacity(left_values.len());
2589    let mut right_positions = Vec::<Option<usize>>::with_capacity(left_values.len());
2590    for (left_pos, &key) in left_values.iter().enumerate() {
2591        let offset = i128::from(key) - i128::from(min_key);
2592        let matched = if (0..span_i128).contains(&offset) {
2593            match table[offset as usize] {
2594                0 => None,
2595                slot => Some(slot as usize - 1),
2596            }
2597        } else {
2598            None
2599        };
2600        left_positions.push(Some(left_pos));
2601        right_positions.push(matched);
2602    }
2603
2604    Some((left_positions, right_positions))
2605}
2606
2607fn dense_int64_left_positions(
2608    left_key: &Column,
2609    right_key: &Column,
2610) -> Option<OptionalJoinPositions> {
2611    if let Some(direct) = dense_int64_unique_right_left_positions(left_key, right_key) {
2612        return Some(direct);
2613    }
2614    let left_values = all_valid_int64_key_values(left_key)?;
2615    let right_values = all_valid_int64_key_values(right_key)?;
2616
2617    if right_values.is_empty() {
2618        let left_positions = (0..left_values.len()).map(Some).collect::<Vec<_>>();
2619        let right_positions = vec![None; left_values.len()];
2620        return Some((left_positions, right_positions));
2621    }
2622
2623    let mut min_key = i64::MAX;
2624    let mut max_key = i64::MIN;
2625    for value in right_values {
2626        let Scalar::Int64(key) = value else {
2627            return None;
2628        };
2629        min_key = min_key.min(*key);
2630        max_key = max_key.max(*key);
2631    }
2632
2633    let span = i128::from(max_key)
2634        .checked_sub(i128::from(min_key))?
2635        .checked_add(1)?;
2636    let row_count = left_values.len().saturating_add(right_values.len());
2637    let max_dense_span = row_count.saturating_mul(4).max(1024);
2638    if span > max_dense_span as i128 {
2639        return None;
2640    }
2641    let span = usize::try_from(span).ok()?;
2642    let span_i128 = i128::try_from(span).ok()?;
2643
2644    let mut right_counts = vec![0usize; span];
2645    for value in right_values {
2646        let Scalar::Int64(key) = value else {
2647            return None;
2648        };
2649        let bucket = usize::try_from(i128::from(*key) - i128::from(min_key)).ok()?;
2650        right_counts[bucket] = right_counts[bucket].checked_add(1)?;
2651    }
2652
2653    let mut right_offsets = Vec::<usize>::with_capacity(span + 1);
2654    right_offsets.push(0);
2655    let mut running = 0usize;
2656    for count in &right_counts {
2657        running = running.checked_add(*count)?;
2658        right_offsets.push(running);
2659    }
2660
2661    let mut write_offsets = right_offsets[..span].to_vec();
2662    let mut right_positions_by_bucket = vec![0usize; right_values.len()];
2663    for (pos, value) in right_values.iter().enumerate() {
2664        let Scalar::Int64(key) = value else {
2665            return None;
2666        };
2667        let bucket = usize::try_from(i128::from(*key) - i128::from(min_key)).ok()?;
2668        let write_idx = write_offsets[bucket];
2669        right_positions_by_bucket[write_idx] = pos;
2670        write_offsets[bucket] = write_offsets[bucket].checked_add(1)?;
2671    }
2672
2673    let mut output_len = 0usize;
2674    for value in left_values {
2675        let Scalar::Int64(key) = value else {
2676            return None;
2677        };
2678        let offset = i128::from(*key) - i128::from(min_key);
2679        let bucket_rows = if (0..span_i128).contains(&offset) {
2680            let bucket = usize::try_from(offset).ok()?;
2681            right_counts[bucket].max(1)
2682        } else {
2683            1
2684        };
2685        output_len = output_len.checked_add(bucket_rows)?;
2686    }
2687
2688    let mut left_positions = Vec::<Option<usize>>::with_capacity(output_len);
2689    let mut right_positions = Vec::<Option<usize>>::with_capacity(output_len);
2690    for (left_pos, value) in left_values.iter().enumerate() {
2691        let Scalar::Int64(key) = value else {
2692            return None;
2693        };
2694        let offset = i128::from(*key) - i128::from(min_key);
2695        if (0..span_i128).contains(&offset) {
2696            let bucket = usize::try_from(offset).ok()?;
2697            let start = right_offsets[bucket];
2698            let end = right_offsets[bucket + 1];
2699            if start != end {
2700                for &right_pos in &right_positions_by_bucket[start..end] {
2701                    left_positions.push(Some(left_pos));
2702                    right_positions.push(Some(right_pos));
2703                }
2704                continue;
2705            }
2706        }
2707        left_positions.push(Some(left_pos));
2708        right_positions.push(None);
2709    }
2710
2711    Some((left_positions, right_positions))
2712}
2713
2714/// Direct-address unique-key fast path for a bounded-span Int64 right join —
2715/// the mirror of [`dense_int64_unique_right_left_positions`]. When the *left*
2716/// (build-side) keys are unique within their span, a single fill + single probe
2717/// over one compact `u32` table replaces the CSR. Keeps every right row; bails
2718/// (caller falls back to the CSR path) on a duplicate left key, non-contiguous
2719/// backing, empty left, oversized span, or `u32` row overflow.
2720fn dense_int64_unique_left_right_positions(
2721    left_key: &Column,
2722    right_key: &Column,
2723) -> Option<OptionalJoinPositions> {
2724    let left_values = left_key.as_i64_slice()?;
2725    let right_values = right_key.as_i64_slice()?;
2726    if left_values.is_empty() || left_values.len() > u32::MAX as usize {
2727        return None;
2728    }
2729
2730    let mut min_key = i64::MAX;
2731    let mut max_key = i64::MIN;
2732    for &key in left_values {
2733        min_key = min_key.min(key);
2734        max_key = max_key.max(key);
2735    }
2736
2737    let span = i128::from(max_key)
2738        .checked_sub(i128::from(min_key))?
2739        .checked_add(1)?;
2740    let row_count = left_values.len().saturating_add(right_values.len());
2741    let max_dense_span = row_count.saturating_mul(4).max(1024);
2742    if span > max_dense_span as i128 {
2743        return None;
2744    }
2745    let span = usize::try_from(span).ok()?;
2746    let span_i128 = i128::try_from(span).ok()?;
2747
2748    let mut table = vec![0u32; span];
2749    for (pos, &key) in left_values.iter().enumerate() {
2750        let bucket = usize::try_from(i128::from(key) - i128::from(min_key)).ok()?;
2751        if table[bucket] != 0 {
2752            return None;
2753        }
2754        table[bucket] = (pos as u32).checked_add(1)?;
2755    }
2756
2757    let mut left_positions = Vec::<Option<usize>>::with_capacity(right_values.len());
2758    let mut right_positions = Vec::<Option<usize>>::with_capacity(right_values.len());
2759    for (right_pos, &key) in right_values.iter().enumerate() {
2760        let offset = i128::from(key) - i128::from(min_key);
2761        let matched = if (0..span_i128).contains(&offset) {
2762            match table[offset as usize] {
2763                0 => None,
2764                slot => Some(slot as usize - 1),
2765            }
2766        } else {
2767            None
2768        };
2769        left_positions.push(matched);
2770        right_positions.push(Some(right_pos));
2771    }
2772
2773    Some((left_positions, right_positions))
2774}
2775
2776fn dense_int64_right_positions(
2777    left_key: &Column,
2778    right_key: &Column,
2779) -> Option<OptionalJoinPositions> {
2780    if let Some(direct) = dense_int64_unique_left_right_positions(left_key, right_key) {
2781        return Some(direct);
2782    }
2783    let left_values = all_valid_int64_key_values(left_key)?;
2784    let right_values = all_valid_int64_key_values(right_key)?;
2785
2786    if left_values.is_empty() {
2787        let left_positions = vec![None; right_values.len()];
2788        let right_positions = (0..right_values.len()).map(Some).collect::<Vec<_>>();
2789        return Some((left_positions, right_positions));
2790    }
2791
2792    let mut min_key = i64::MAX;
2793    let mut max_key = i64::MIN;
2794    for value in left_values {
2795        let Scalar::Int64(key) = value else {
2796            return None;
2797        };
2798        min_key = min_key.min(*key);
2799        max_key = max_key.max(*key);
2800    }
2801
2802    let span = i128::from(max_key)
2803        .checked_sub(i128::from(min_key))?
2804        .checked_add(1)?;
2805    let row_count = left_values.len().saturating_add(right_values.len());
2806    let max_dense_span = row_count.saturating_mul(4).max(1024);
2807    if span > max_dense_span as i128 {
2808        return None;
2809    }
2810    let span = usize::try_from(span).ok()?;
2811    let span_i128 = i128::try_from(span).ok()?;
2812
2813    let mut left_counts = vec![0usize; span];
2814    for value in left_values {
2815        let Scalar::Int64(key) = value else {
2816            return None;
2817        };
2818        let bucket = usize::try_from(i128::from(*key) - i128::from(min_key)).ok()?;
2819        left_counts[bucket] = left_counts[bucket].checked_add(1)?;
2820    }
2821
2822    let mut left_offsets = Vec::<usize>::with_capacity(span + 1);
2823    left_offsets.push(0);
2824    let mut running = 0usize;
2825    for count in &left_counts {
2826        running = running.checked_add(*count)?;
2827        left_offsets.push(running);
2828    }
2829
2830    let mut write_offsets = left_offsets[..span].to_vec();
2831    let mut left_positions_by_bucket = vec![0usize; left_values.len()];
2832    for (pos, value) in left_values.iter().enumerate() {
2833        let Scalar::Int64(key) = value else {
2834            return None;
2835        };
2836        let bucket = usize::try_from(i128::from(*key) - i128::from(min_key)).ok()?;
2837        let write_idx = write_offsets[bucket];
2838        left_positions_by_bucket[write_idx] = pos;
2839        write_offsets[bucket] = write_offsets[bucket].checked_add(1)?;
2840    }
2841
2842    let mut output_len = 0usize;
2843    for value in right_values {
2844        let Scalar::Int64(key) = value else {
2845            return None;
2846        };
2847        let offset = i128::from(*key) - i128::from(min_key);
2848        let bucket_rows = if (0..span_i128).contains(&offset) {
2849            let bucket = usize::try_from(offset).ok()?;
2850            left_counts[bucket].max(1)
2851        } else {
2852            1
2853        };
2854        output_len = output_len.checked_add(bucket_rows)?;
2855    }
2856
2857    let mut left_positions = Vec::<Option<usize>>::with_capacity(output_len);
2858    let mut right_positions = Vec::<Option<usize>>::with_capacity(output_len);
2859    for (right_pos, value) in right_values.iter().enumerate() {
2860        let Scalar::Int64(key) = value else {
2861            return None;
2862        };
2863        let offset = i128::from(*key) - i128::from(min_key);
2864        if (0..span_i128).contains(&offset) {
2865            let bucket = usize::try_from(offset).ok()?;
2866            let start = left_offsets[bucket];
2867            let end = left_offsets[bucket + 1];
2868            if start != end {
2869                for &left_pos in &left_positions_by_bucket[start..end] {
2870                    left_positions.push(Some(left_pos));
2871                    right_positions.push(Some(right_pos));
2872                }
2873                continue;
2874            }
2875        }
2876        left_positions.push(None);
2877        right_positions.push(Some(right_pos));
2878    }
2879
2880    Some((left_positions, right_positions))
2881}
2882
2883/// Direct-address unique-key fast path for a bounded-span Int64 full-outer join.
2884/// When BOTH key sides are unique within the joint span, two compact `u32`
2885/// tables (`pos+1`, `0` == empty) plus a single ascending scan over `0..span`
2886/// replace the CSR's `Vec<Vec<usize>>` (one heap `Vec` per bucket — `span`
2887/// allocations) and the `Vec<Scalar>` materialization. Bails (caller falls back
2888/// to the bucket-list CSR) on a duplicate key on either side, non-contiguous
2889/// backing, oversized span, or `u32` row overflow.
2890///
2891/// Bit-identical for unique keys: the CSR emits one row per bucket in ascending
2892/// key (bucket) order — matched `(Some,Some)`, left-only `(Some,None)`,
2893/// right-only `(None,Some)` — which is exactly the per-bucket scan here.
2894fn dense_int64_unique_outer_positions(
2895    left_key: &Column,
2896    right_key: &Column,
2897) -> Option<OptionalJoinPositions> {
2898    let left_values = left_key.as_i64_slice()?;
2899    let right_values = right_key.as_i64_slice()?;
2900    if left_values.len() > u32::MAX as usize || right_values.len() > u32::MAX as usize {
2901        return None;
2902    }
2903
2904    let mut min_key = i64::MAX;
2905    let mut max_key = i64::MIN;
2906    let mut any = false;
2907    for &key in left_values.iter().chain(right_values.iter()) {
2908        min_key = min_key.min(key);
2909        max_key = max_key.max(key);
2910        any = true;
2911    }
2912    if !any {
2913        return Some((Vec::new(), Vec::new()));
2914    }
2915
2916    let span = i128::from(max_key)
2917        .checked_sub(i128::from(min_key))?
2918        .checked_add(1)?;
2919    let row_count = left_values.len().saturating_add(right_values.len());
2920    let max_dense_span = row_count.saturating_mul(4).max(1024);
2921    if span > max_dense_span as i128 {
2922        return None;
2923    }
2924    let span = usize::try_from(span).ok()?;
2925
2926    let mut left_table = vec![0u32; span];
2927    let mut right_table = vec![0u32; span];
2928    for (pos, &key) in left_values.iter().enumerate() {
2929        let bucket = usize::try_from(i128::from(key) - i128::from(min_key)).ok()?;
2930        if left_table[bucket] != 0 {
2931            return None;
2932        }
2933        left_table[bucket] = (pos as u32).checked_add(1)?;
2934    }
2935    for (pos, &key) in right_values.iter().enumerate() {
2936        let bucket = usize::try_from(i128::from(key) - i128::from(min_key)).ok()?;
2937        if right_table[bucket] != 0 {
2938            return None;
2939        }
2940        right_table[bucket] = (pos as u32).checked_add(1)?;
2941    }
2942
2943    let mut left_positions = Vec::<Option<usize>>::new();
2944    let mut right_positions = Vec::<Option<usize>>::new();
2945    for bucket in 0..span {
2946        match (left_table[bucket], right_table[bucket]) {
2947            (0, 0) => {}
2948            (l, 0) => {
2949                left_positions.push(Some(l as usize - 1));
2950                right_positions.push(None);
2951            }
2952            (0, r) => {
2953                left_positions.push(None);
2954                right_positions.push(Some(r as usize - 1));
2955            }
2956            (l, r) => {
2957                left_positions.push(Some(l as usize - 1));
2958                right_positions.push(Some(r as usize - 1));
2959            }
2960        }
2961    }
2962
2963    Some((left_positions, right_positions))
2964}
2965
2966fn dense_int64_outer_positions(
2967    left_key: &Column,
2968    right_key: &Column,
2969) -> Option<OptionalJoinPositions> {
2970    if let Some(direct) = dense_int64_unique_outer_positions(left_key, right_key) {
2971        return Some(direct);
2972    }
2973    let left_values = all_valid_int64_key_values(left_key)?;
2974    let right_values = all_valid_int64_key_values(right_key)?;
2975
2976    let mut min_key = None::<i64>;
2977    let mut max_key = None::<i64>;
2978    for value in left_values.iter().chain(right_values.iter()) {
2979        let Scalar::Int64(key) = value else {
2980            return None;
2981        };
2982        min_key = Some(min_key.map_or(*key, |current| current.min(*key)));
2983        max_key = Some(max_key.map_or(*key, |current| current.max(*key)));
2984    }
2985
2986    let Some(min_key) = min_key else {
2987        return Some((Vec::new(), Vec::new()));
2988    };
2989    let max_key = max_key.expect("max key exists when min key exists");
2990    let span = i128::from(max_key)
2991        .checked_sub(i128::from(min_key))?
2992        .checked_add(1)?;
2993    let row_count = left_values.len().saturating_add(right_values.len());
2994    let max_dense_span = row_count.saturating_mul(4).max(1024);
2995    if span > max_dense_span as i128 {
2996        return None;
2997    }
2998    let span = usize::try_from(span).ok()?;
2999
3000    let mut left_buckets = (0..span).map(|_| Vec::<usize>::new()).collect::<Vec<_>>();
3001    let mut right_buckets = (0..span).map(|_| Vec::<usize>::new()).collect::<Vec<_>>();
3002
3003    for (pos, value) in left_values.iter().enumerate() {
3004        let Scalar::Int64(key) = value else {
3005            return None;
3006        };
3007        let bucket = usize::try_from(i128::from(*key) - i128::from(min_key)).ok()?;
3008        left_buckets[bucket].push(pos);
3009    }
3010    for (pos, value) in right_values.iter().enumerate() {
3011        let Scalar::Int64(key) = value else {
3012            return None;
3013        };
3014        let bucket = usize::try_from(i128::from(*key) - i128::from(min_key)).ok()?;
3015        right_buckets[bucket].push(pos);
3016    }
3017
3018    let mut output_len = 0usize;
3019    for (left_bucket, right_bucket) in left_buckets.iter().zip(right_buckets.iter()) {
3020        let bucket_rows = match (left_bucket.is_empty(), right_bucket.is_empty()) {
3021            (false, false) => left_bucket.len().checked_mul(right_bucket.len())?,
3022            (false, true) => left_bucket.len(),
3023            (true, false) => right_bucket.len(),
3024            (true, true) => 0,
3025        };
3026        output_len = output_len.checked_add(bucket_rows)?;
3027    }
3028
3029    let mut left_positions = Vec::<Option<usize>>::with_capacity(output_len);
3030    let mut right_positions = Vec::<Option<usize>>::with_capacity(output_len);
3031    for (left_bucket, right_bucket) in left_buckets.into_iter().zip(right_buckets) {
3032        match (left_bucket.is_empty(), right_bucket.is_empty()) {
3033            (false, false) => {
3034                for left_pos in left_bucket {
3035                    for &right_pos in &right_bucket {
3036                        left_positions.push(Some(left_pos));
3037                        right_positions.push(Some(right_pos));
3038                    }
3039                }
3040            }
3041            (false, true) => {
3042                for left_pos in left_bucket {
3043                    left_positions.push(Some(left_pos));
3044                    right_positions.push(None);
3045                }
3046            }
3047            (true, false) => {
3048                for right_pos in right_bucket {
3049                    left_positions.push(None);
3050                    right_positions.push(Some(right_pos));
3051                }
3052            }
3053            (true, true) => {}
3054        }
3055    }
3056
3057    Some((left_positions, right_positions))
3058}
3059
3060fn ordered_unique_int64_outer_positions(
3061    left_key: &Column,
3062    right_key: &Column,
3063) -> Option<OptionalJoinPositions> {
3064    // Typed fast path (see ordered_unique_int64_left_match_positions): merge the
3065    // ordered union over raw &[i64] when both keys carry a contiguous Int64
3066    // backing, skipping the Vec<Scalar> materialization (32 B/elem, ~64 MB per
3067    // merge at 1M rows). Bit-identical: same strictly-increasing gate and the
3068    // same three-way merge emitting the same (Option,Option) position pairs and
3069    // the same drain order.
3070    if let (Some(left_values), Some(right_values)) = (
3071        strictly_increasing_i64_slice(left_key),
3072        strictly_increasing_i64_slice(right_key),
3073    ) {
3074        let cap = left_values.len().saturating_add(right_values.len());
3075        let mut left_positions = Vec::<Option<usize>>::with_capacity(cap);
3076        let mut right_positions = Vec::<Option<usize>>::with_capacity(cap);
3077        let (mut left_idx, mut right_idx) = (0usize, 0usize);
3078        while left_idx < left_values.len() && right_idx < right_values.len() {
3079            match left_values[left_idx].cmp(&right_values[right_idx]) {
3080                Ordering::Equal => {
3081                    left_positions.push(Some(left_idx));
3082                    right_positions.push(Some(right_idx));
3083                    left_idx += 1;
3084                    right_idx += 1;
3085                }
3086                Ordering::Less => {
3087                    left_positions.push(Some(left_idx));
3088                    right_positions.push(None);
3089                    left_idx += 1;
3090                }
3091                Ordering::Greater => {
3092                    left_positions.push(None);
3093                    right_positions.push(Some(right_idx));
3094                    right_idx += 1;
3095                }
3096            }
3097        }
3098        while left_idx < left_values.len() {
3099            left_positions.push(Some(left_idx));
3100            right_positions.push(None);
3101            left_idx += 1;
3102        }
3103        while right_idx < right_values.len() {
3104            left_positions.push(None);
3105            right_positions.push(Some(right_idx));
3106            right_idx += 1;
3107        }
3108        return Some((left_positions, right_positions));
3109    }
3110
3111    let left_values = strictly_increasing_int64_key_values(left_key)?;
3112    let right_values = strictly_increasing_int64_key_values(right_key)?;
3113
3114    let mut left_positions =
3115        Vec::<Option<usize>>::with_capacity(left_values.len().saturating_add(right_values.len()));
3116    let mut right_positions = Vec::<Option<usize>>::with_capacity(left_positions.capacity());
3117    let mut left_idx = 0usize;
3118    let mut right_idx = 0usize;
3119
3120    while left_idx < left_values.len() && right_idx < right_values.len() {
3121        let left_value = match &left_values[left_idx] {
3122            Scalar::Int64(value) => *value,
3123            _ => return None,
3124        };
3125        let right_value = match &right_values[right_idx] {
3126            Scalar::Int64(value) => *value,
3127            _ => return None,
3128        };
3129
3130        match left_value.cmp(&right_value) {
3131            Ordering::Equal => {
3132                left_positions.push(Some(left_idx));
3133                right_positions.push(Some(right_idx));
3134                left_idx += 1;
3135                right_idx += 1;
3136            }
3137            Ordering::Less => {
3138                left_positions.push(Some(left_idx));
3139                right_positions.push(None);
3140                left_idx += 1;
3141            }
3142            Ordering::Greater => {
3143                left_positions.push(None);
3144                right_positions.push(Some(right_idx));
3145                right_idx += 1;
3146            }
3147        }
3148    }
3149
3150    while left_idx < left_values.len() {
3151        left_positions.push(Some(left_idx));
3152        right_positions.push(None);
3153        left_idx += 1;
3154    }
3155    while right_idx < right_values.len() {
3156        left_positions.push(None);
3157        right_positions.push(Some(right_idx));
3158        right_idx += 1;
3159    }
3160
3161    Some((left_positions, right_positions))
3162}
3163
3164fn identity_merge_column(
3165    column: &Column,
3166    row_count: usize,
3167    identity_positions: &mut Option<Vec<usize>>,
3168) -> Column {
3169    if column.validity().all() {
3170        return column.clone();
3171    }
3172
3173    let positions = identity_positions.get_or_insert_with(|| (0..row_count).collect());
3174    column.take_positions(positions)
3175}
3176
3177fn resolve_merge_indicator_name(indicator_name: Option<&str>) -> Result<Option<String>, JoinError> {
3178    let Some(name) = indicator_name else {
3179        return Ok(None);
3180    };
3181    if name.trim().is_empty() {
3182        return Err(JoinError::Frame(FrameError::CompatibilityRejected(
3183            "merge indicator column name must be non-empty".to_owned(),
3184        )));
3185    }
3186    Ok(Some(name.to_owned()))
3187}
3188
3189fn build_merge_indicator_column(
3190    left_positions: &[Option<usize>],
3191    right_positions: &[Option<usize>],
3192) -> Result<Column, JoinError> {
3193    let values = left_positions
3194        .iter()
3195        .zip(right_positions.iter())
3196        .map(|(left_pos, right_pos)| match (left_pos, right_pos) {
3197            (Some(_), Some(_)) => fp_types::Scalar::Utf8("both".to_owned()),
3198            (Some(_), None) => fp_types::Scalar::Utf8("left_only".to_owned()),
3199            (None, Some(_)) => fp_types::Scalar::Utf8("right_only".to_owned()),
3200            (None, None) => fp_types::Scalar::Null(fp_types::NullKind::Null),
3201        })
3202        .collect::<Vec<_>>();
3203    Column::from_values(values).map_err(JoinError::from)
3204}
3205
3206fn ensure_indicator_name_available(
3207    indicator_name: &str,
3208    left_col_names: &HashSet<&String>,
3209    right_col_names: &HashSet<&String>,
3210    output_columns: &ColumnStore,
3211) -> Result<(), JoinError> {
3212    if left_col_names
3213        .iter()
3214        .any(|name| name.as_str() == indicator_name)
3215        || right_col_names
3216            .iter()
3217            .any(|name| name.as_str() == indicator_name)
3218        || output_columns.contains_key(indicator_name)
3219    {
3220        return Err(JoinError::Frame(FrameError::CompatibilityRejected(
3221            format!("merge indicator column '{indicator_name}' conflicts with an existing column"),
3222        )));
3223    }
3224    Ok(())
3225}
3226
3227/// Positional gather that keeps an all-valid Int64 output column TYPED.
3228///
3229/// `Column::take_positions` already typed-fast-paths all-valid Float64 (it
3230/// gathers into a contiguous `Vec<f64>` behind `lazy_all_valid_float64`), but
3231/// for all-valid Int64 it materializes a `Vec<Scalar::Int64>` (32 B/elem). On
3232/// the inner-merge output build — one gather per carried column — that Scalar
3233/// rebuild dominates for integer payloads. Here we gather the contiguous `i64`
3234/// buffer directly and hand it to `from_i64_values`, which yields the same
3235/// lazy-typed all-valid Int64 column.
3236///
3237/// Bit-identical to `take_positions`: for an all-valid Int64 column the latter
3238/// produces `Scalar::Int64(slice[pos])` at every output slot with an all-valid
3239/// mask; `from_i64_values(gathered)` materializes exactly those scalars with the
3240/// same all-valid mask (no NaN coercion path for i64), and `Column` equality
3241/// ignores the internal data cache. `as_i64_slice` returns `Some` only for an
3242/// all-valid, typed-backed Int64 column, so every other dtype / any-missing
3243/// column falls through to the unchanged `take_positions`.
3244fn take_positions_typed(column: &Column, positions: &[usize]) -> Column {
3245    if let Some(slice) = column.as_i64_slice() {
3246        let mut data = Vec::with_capacity(positions.len());
3247        for &pos in positions {
3248            data.push(slice[pos]);
3249        }
3250        return Column::from_i64_values(data);
3251    }
3252    column.take_positions(positions)
3253}
3254
3255#[derive(Clone, Copy)]
3256enum PositionSelection<'a> {
3257    Positions(&'a [usize]),
3258    ContiguousRange { start: usize, len: usize },
3259}
3260
3261impl PositionSelection<'_> {
3262    fn len(self) -> usize {
3263        match self {
3264            Self::Positions(positions) => positions.len(),
3265            Self::ContiguousRange { len, .. } => len,
3266        }
3267    }
3268}
3269
3270fn take_position_selection_typed(column: &Column, selection: PositionSelection<'_>) -> Column {
3271    match selection {
3272        PositionSelection::Positions(positions) => take_positions_typed(column, positions),
3273        PositionSelection::ContiguousRange { start, len } => {
3274            column.take_contiguous_range(start, len)
3275        }
3276    }
3277}
3278
3279fn take_lower_hex_sequence_range(column: &Column, start: usize, len: usize) -> Option<Column> {
3280    let (prefix, certificate, source_len) = column.as_lower_hex_sequence_utf8()?;
3281    let end = start.checked_add(len)?;
3282    if end > source_len {
3283        return None;
3284    }
3285    let start_value = certificate.value_at(start)?;
3286    Column::from_lower_hex_sequence_utf8(prefix, start_value, len, certificate.hex_width())
3287}
3288
3289#[derive(Clone, Copy)]
3290enum FusedInt64Side {
3291    Left,
3292    Right,
3293}
3294
3295struct FusedInt64OutputColumn<'a> {
3296    name: String,
3297    side: FusedInt64Side,
3298    values: &'a [i64],
3299}
3300
3301struct FusedInt64MergeOptions<'a> {
3302    suffixes: &'a ResolvedMergeSuffixes,
3303    require_all_left_keys_matched: bool,
3304}
3305
3306#[cfg(not(test))]
3307const DENSE_I64_INNER_PARALLEL_MIN_VALUES: usize = 1 << 18;
3308#[cfg(test)]
3309const DENSE_I64_INNER_PARALLEL_MIN_VALUES: usize = 1;
3310const DENSE_I64_INNER_PARALLEL_MAX_CHUNKS: usize = 16;
3311
3312fn join_parallel_thread_count() -> usize {
3313    static THREAD_COUNT: OnceLock<usize> = OnceLock::new();
3314    *THREAD_COUNT.get_or_init(|| {
3315        fp_columnar::cached_available_parallelism().min(DENSE_I64_INNER_PARALLEL_MAX_CHUNKS)
3316    })
3317}
3318
3319struct DenseI64InnerOutputPlan<'a> {
3320    left_keys: &'a [i64],
3321    min: i64,
3322    max: i64,
3323    offsets: &'a [usize],
3324    positions: &'a [usize],
3325    output_len: usize,
3326}
3327
3328/// One output lane of the dense i64 inner merge.
3329enum DenseI64LaneData {
3330    /// Left lane carried as per-run values plus a shared run-length descriptor
3331    /// — O(matched) memory, expanded lazily by column consumers
3332    /// (br-frankenpandas-3ad4n, br-frankenpandas-l4adm).
3333    RepeatRunLengths {
3334        values: Vec<i64>,
3335        run_lens: Arc<[usize]>,
3336    },
3337    /// Right lane carried as repeated slices of one bucket-order value tape —
3338    /// O(right + matched) memory until a consumer forces a contiguous view.
3339    RepeatedSlices {
3340        data: Vec<i64>,
3341        segments: Arc<[(usize, usize)]>,
3342    },
3343    /// Fully materialized contiguous values.
3344    Full(Vec<i64>),
3345}
3346
3347/// Row-chunked disjoint-write fill (br-frankenpandas-6bsw3) with lazy
3348/// repeat-run left lanes (br-frankenpandas-3ad4n).
3349///
3350/// One probe walk records every matched left row as `(left_pos,
3351/// bucket_start, run_len)`. Left lanes are pure repeat runs (each left value
3352/// repeated `run_len` times), so when the average fanout is >= 2 they are
3353/// emitted as `(value, run_len)` pairs — O(matched) memory instead of
3354/// O(output) — and expanded only if a downstream consumer reads the values.
3355/// Remaining lanes (right lanes always; left lanes too on low-fanout joins
3356/// where a 16 B run would exceed the expanded bytes) are materialized by the
3357/// 6bsw3 scheme: up to [`DENSE_I64_INNER_PARALLEL_MAX_CHUNKS`] output-size-
3358/// balanced chunks of the matched list, each worker filling its disjoint
3359/// `split_at_mut` slice of every full lane (left repeat-runs via
3360/// `slice::fill`, right bucket ranges via `copy_from_slice` from the shared
3361/// muis1 value tapes).
3362///
3363/// Bit-identical: the matched list IS the left probe order; expanding a
3364/// `RepeatRunLengths` lane reproduces exactly the values the `Full` fill
3365/// writes, and chunks partition the matched list so concatenated output equals
3366/// the single-threaded walk byte for byte.
3367fn build_dense_i64_inner_output_data(
3368    specs: &[FusedInt64OutputColumn<'_>],
3369    plan: &DenseI64InnerOutputPlan<'_>,
3370) -> Vec<DenseI64LaneData> {
3371    // Single probe walk shared by every lane: matched left rows in probe
3372    // order as (left_pos, bucket_start, run_len).
3373    let mut matched: Vec<(usize, usize, usize)> = Vec::new();
3374    for (left_pos, &v) in plan.left_keys.iter().enumerate() {
3375        if v < plan.min || v > plan.max {
3376            continue;
3377        }
3378        let bucket = (v - plan.min) as usize;
3379        if bucket + 1 >= plan.offsets.len() {
3380            continue;
3381        }
3382        let start = plan.offsets[bucket];
3383        let run_len = plan.offsets[bucket + 1] - start;
3384        if run_len == 0 {
3385            continue;
3386        }
3387        matched.push((left_pos, start, run_len));
3388    }
3389    debug_assert_eq!(
3390        matched
3391            .iter()
3392            .map(|&(_, _, run_len)| run_len)
3393            .sum::<usize>(),
3394        plan.output_len
3395    );
3396
3397    // A (value, run_len) pair is 16 B vs 8 B x run_len expanded: repeat runs
3398    // only pay when the average fanout is >= 2 (1:1 joins stay materialized).
3399    let use_repeat_runs = plan.output_len >= matched.len().saturating_mul(2);
3400
3401    let use_repeated_slices = use_repeat_runs;
3402    let repeat_run_lens: Option<Arc<[usize]>> = if use_repeat_runs {
3403        Some(
3404            matched
3405                .iter()
3406                .map(|&(_, _, run_len)| run_len)
3407                .collect::<Vec<_>>()
3408                .into(),
3409        )
3410    } else {
3411        None
3412    };
3413    let repeated_segments: Option<Arc<[(usize, usize)]>> = if use_repeated_slices {
3414        Some(
3415            matched
3416                .iter()
3417                .map(|&(_, start, run_len)| (start, run_len))
3418                .collect::<Vec<_>>()
3419                .into(),
3420        )
3421    } else {
3422        None
3423    };
3424
3425    let full_specs: Vec<usize> = specs
3426        .iter()
3427        .enumerate()
3428        .filter(|(_, spec)| {
3429            !(use_repeat_runs && matches!(spec.side, FusedInt64Side::Left))
3430                && !(use_repeated_slices && matches!(spec.side, FusedInt64Side::Right))
3431        })
3432        .map(|(idx, _)| idx)
3433        .collect();
3434
3435    // Fill the full lanes first (right lanes always; left lanes on
3436    // low-fanout joins).
3437    let mut full_data: Vec<Vec<i64>> = Vec::new();
3438    let thread_count = join_parallel_thread_count();
3439    if !full_specs.is_empty()
3440        && plan.output_len >= DENSE_I64_INNER_PARALLEL_MIN_VALUES
3441        && thread_count > 1
3442    {
3443        // Replay buckets from a value tape per right-side column (one gather
3444        // of right values into bucket order, per br-frankenpandas-muis1),
3445        // shared read-only across all chunk workers.
3446        let tapes: Vec<Option<Vec<i64>>> = full_specs
3447            .iter()
3448            .map(|&spec_idx| match specs[spec_idx].side {
3449                FusedInt64Side::Left => None,
3450                FusedInt64Side::Right => Some(
3451                    plan.positions
3452                        .iter()
3453                        .map(|&right_pos| specs[spec_idx].values[right_pos])
3454                        .collect(),
3455                ),
3456            })
3457            .collect();
3458
3459        // Chunk boundaries (matched_idx, out_pos), balanced by OUTPUT size
3460        // so a few hot buckets cannot starve the other workers.
3461        let target = plan.output_len.div_ceil(thread_count).max(1);
3462        let mut boundaries = vec![(0usize, 0usize)];
3463        let mut cumulative = 0usize;
3464        let mut next_target = target;
3465        for (matched_idx, &(_, _, run_len)) in matched.iter().enumerate() {
3466            cumulative += run_len;
3467            if cumulative >= next_target && matched_idx + 1 < matched.len() {
3468                boundaries.push((matched_idx + 1, cumulative));
3469                next_target = cumulative.saturating_add(target);
3470            }
3471        }
3472        boundaries.push((matched.len(), plan.output_len));
3473        let chunk_count = boundaries.len() - 1;
3474
3475        // Pre-size every full lane, then hand each chunk worker its disjoint
3476        // slice of every lane via progressive split_at_mut.
3477        let mut column_bufs: Vec<Vec<i64>> = full_specs
3478            .iter()
3479            .map(|_| vec![0i64; plan.output_len])
3480            .collect();
3481        let mut bundles: Vec<Vec<&mut [i64]>> = (0..chunk_count)
3482            .map(|_| Vec::with_capacity(full_specs.len()))
3483            .collect();
3484        for buf in &mut column_bufs {
3485            let mut rest: &mut [i64] = buf.as_mut_slice();
3486            let mut prev = 0usize;
3487            for (chunk_idx, window) in boundaries.windows(2).enumerate() {
3488                let (chunk_slice, tail) = rest.split_at_mut(window[1].1 - prev);
3489                prev = window[1].1;
3490                rest = tail;
3491                bundles[chunk_idx].push(chunk_slice);
3492            }
3493        }
3494
3495        let matched = &matched;
3496        let full_specs = &full_specs;
3497        std::thread::scope(|scope| {
3498            let mut handles = Vec::with_capacity(chunk_count);
3499            for (chunk_idx, mut bundle) in bundles.into_iter().enumerate() {
3500                let (matched_start, out_start) = boundaries[chunk_idx];
3501                let (matched_end, out_end) = boundaries[chunk_idx + 1];
3502                let tapes = &tapes;
3503                handles.push(scope.spawn(move || {
3504                    let mut cursor = 0usize;
3505                    for &(left_pos, start, run_len) in &matched[matched_start..matched_end] {
3506                        for (slice, (&spec_idx, tape)) in
3507                            bundle.iter_mut().zip(full_specs.iter().zip(tapes.iter()))
3508                        {
3509                            match specs[spec_idx].side {
3510                                FusedInt64Side::Left => {
3511                                    slice[cursor..cursor + run_len]
3512                                        .fill(specs[spec_idx].values[left_pos]);
3513                                }
3514                                FusedInt64Side::Right => {
3515                                    slice[cursor..cursor + run_len].copy_from_slice(
3516                                        &tape.as_ref().expect("right spec must have a bucket tape")
3517                                            [start..start + run_len],
3518                                    );
3519                                }
3520                            }
3521                        }
3522                        cursor += run_len;
3523                    }
3524                    debug_assert_eq!(cursor, out_end - out_start);
3525                }));
3526            }
3527            for handle in handles {
3528                handle
3529                    .join()
3530                    .expect("dense i64 output worker must not panic");
3531            }
3532        });
3533        full_data = column_bufs;
3534    } else if !full_specs.is_empty() {
3535        full_data = full_specs
3536            .iter()
3537            .map(|_| Vec::<i64>::with_capacity(plan.output_len))
3538            .collect();
3539        for &(left_pos, start, run_len) in &matched {
3540            for (out, &spec_idx) in full_data.iter_mut().zip(full_specs.iter()) {
3541                match specs[spec_idx].side {
3542                    FusedInt64Side::Left => {
3543                        out.resize(out.len() + run_len, specs[spec_idx].values[left_pos]);
3544                    }
3545                    FusedInt64Side::Right => {
3546                        for &right_pos in &plan.positions[start..start + run_len] {
3547                            out.push(specs[spec_idx].values[right_pos]);
3548                        }
3549                    }
3550                }
3551            }
3552        }
3553        debug_assert!(full_data.iter().all(|data| data.len() == plan.output_len));
3554    }
3555
3556    // Assemble lanes in spec order: repeat runs for the lazy left lanes,
3557    // filled buffers for everything else.
3558    let mut full_iter = full_data.into_iter();
3559    specs
3560        .iter()
3561        .map(|spec| {
3562            if use_repeat_runs && matches!(spec.side, FusedInt64Side::Left) {
3563                DenseI64LaneData::RepeatRunLengths {
3564                    values: matched
3565                        .iter()
3566                        .map(|&(left_pos, _, _)| spec.values[left_pos])
3567                        .collect(),
3568                    run_lens: Arc::clone(
3569                        repeat_run_lens
3570                            .as_ref()
3571                            .expect("repeat run lengths must exist"),
3572                    ),
3573                }
3574            } else if use_repeated_slices && matches!(spec.side, FusedInt64Side::Right) {
3575                DenseI64LaneData::RepeatedSlices {
3576                    data: plan
3577                        .positions
3578                        .iter()
3579                        .map(|&right_pos| spec.values[right_pos])
3580                        .collect(),
3581                    segments: Arc::clone(
3582                        repeated_segments
3583                            .as_ref()
3584                            .expect("repeated slice segments must exist"),
3585                    ),
3586                }
3587            } else {
3588                DenseI64LaneData::Full(
3589                    full_iter
3590                        .next()
3591                        .expect("full lane buffer must exist for every non-run spec"),
3592                )
3593            }
3594        })
3595        .collect()
3596}
3597
3598/// Which typed lane an output column of the dense inner merge uses, recorded in
3599/// column-encounter order so the i64 (lazy) and f64 (materialized) builds can be
3600/// re-interleaved into the original column order (br-frankenpandas-jzrem).
3601enum DenseInnerSpecKind {
3602    I64,
3603    F64,
3604}
3605
3606/// One Float64 output lane of the dense inner merge (br-frankenpandas-jzrem).
3607struct FusedF64OutputColumn<'a> {
3608    name: String,
3609    side: FusedInt64Side,
3610    values: &'a [f64],
3611}
3612
3613/// The matched-left-row list `(left_pos, bucket_start, run_len)` in probe order
3614/// — identical to the walk inside [`build_dense_i64_inner_output_data`], so the
3615/// Float64 lanes materialize in the exact same row order as the i64 lanes and
3616/// the flat `take_positions` path.
3617fn dense_inner_matched_runs(plan: &DenseI64InnerOutputPlan<'_>) -> Vec<(usize, usize, usize)> {
3618    let mut matched = Vec::new();
3619    for (left_pos, &v) in plan.left_keys.iter().enumerate() {
3620        if v < plan.min || v > plan.max {
3621            continue;
3622        }
3623        let bucket = (v - plan.min) as usize;
3624        if bucket + 1 >= plan.offsets.len() {
3625            continue;
3626        }
3627        let start = plan.offsets[bucket];
3628        let run_len = plan.offsets[bucket + 1] - start;
3629        if run_len == 0 {
3630            continue;
3631        }
3632        matched.push((left_pos, start, run_len));
3633    }
3634    matched
3635}
3636
3637/// Build one Float64 inner-merge output column as a LAZY representation
3638/// (br-frankenpandas-jzrem) — O(matched + right_len), never the O(output_len)
3639/// materialization:
3640///   * a Left column becomes a repeat-values lane: one value per matched run
3641///     (`values[left_pos]`) over the shared `run_lens` descriptor;
3642///   * a Right column becomes a repeated-slices lane over the bucket-ordered
3643///     value tape (`values` gathered by `positions`, one scattered pass) with
3644///     the shared `segments` descriptor.
3645///
3646/// Both materialize, only when a consumer reads them, to exactly the values
3647/// `take_position_selection_typed` would produce on the flat `(left_positions,
3648/// right_positions)` vectors — same values, same row order (matched-run probe
3649/// order == flat position order). Mirrors the i64 lazy lanes the all-Int64 path
3650/// already emits, so a join whose output is only sized (not consumed) stays
3651/// near-free instead of writing the whole fanned-out column.
3652fn build_dense_inner_f64_column(
3653    side: FusedInt64Side,
3654    values: &[f64],
3655    matched: &[(usize, usize, usize)],
3656    positions: &[usize],
3657    run_lens: &Arc<[usize]>,
3658    segments: &Arc<[(usize, usize)]>,
3659    output_len: usize,
3660) -> Column {
3661    match side {
3662        FusedInt64Side::Left => {
3663            let run_values: Vec<f64> = matched
3664                .iter()
3665                .map(|&(left_pos, _, _)| values[left_pos])
3666                .collect();
3667            Column::from_f64_repeat_values_run_lengths(run_values, Arc::clone(run_lens))
3668        }
3669        FusedInt64Side::Right => {
3670            let tape: Vec<f64> = positions.iter().map(|&p| values[p]).collect();
3671            Column::from_f64_repeated_slices_shared(tape, Arc::clone(segments), output_len)
3672        }
3673    }
3674}
3675
3676/// Build every Float64 inner-merge output column, one worker per column when the
3677/// pool is worth it (the fu8f5 column-parallel pattern). Returns `(name, column)`
3678/// pairs in `specs` order. `run_lens`/`segments` are the shared lazy-lane
3679/// descriptors derived from the matched-run list (one per matched run).
3680fn build_dense_inner_f64_columns(
3681    specs: Vec<FusedF64OutputColumn<'_>>,
3682    matched: &[(usize, usize, usize)],
3683    positions: &[usize],
3684    output_len: usize,
3685) -> Vec<(String, Column)> {
3686    if specs.is_empty() {
3687        return Vec::new();
3688    }
3689    let run_lens: Arc<[usize]> = matched.iter().map(|&(_, _, run_len)| run_len).collect();
3690    let segments: Arc<[(usize, usize)]> = matched
3691        .iter()
3692        .map(|&(_, bucket_start, run_len)| (bucket_start, run_len))
3693        .collect();
3694
3695    let worker_count = join_parallel_thread_count().min(specs.len());
3696    if worker_count < 2 {
3697        return specs
3698            .into_iter()
3699            .map(|s| {
3700                (
3701                    s.name,
3702                    build_dense_inner_f64_column(
3703                        s.side, s.values, matched, positions, &run_lens, &segments, output_len,
3704                    ),
3705                )
3706            })
3707            .collect();
3708    }
3709
3710    let next = std::sync::atomic::AtomicUsize::new(0);
3711    let specs_ref = &specs;
3712    let run_lens_ref = &run_lens;
3713    let segments_ref = &segments;
3714    let built_by_worker = std::thread::scope(|scope| {
3715        let mut handles = Vec::with_capacity(worker_count);
3716        for _ in 0..worker_count {
3717            let next = &next;
3718            handles.push(scope.spawn(move || {
3719                let mut local: Vec<(usize, Column)> = Vec::new();
3720                loop {
3721                    let idx = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3722                    if idx >= specs_ref.len() {
3723                        break;
3724                    }
3725                    let s = &specs_ref[idx];
3726                    local.push((
3727                        idx,
3728                        build_dense_inner_f64_column(
3729                            s.side,
3730                            s.values,
3731                            matched,
3732                            positions,
3733                            run_lens_ref,
3734                            segments_ref,
3735                            output_len,
3736                        ),
3737                    ));
3738                }
3739                local
3740            }));
3741        }
3742        let mut all: Vec<(usize, Column)> = Vec::new();
3743        for handle in handles {
3744            all.extend(
3745                handle
3746                    .join()
3747                    .expect("f64 inner-merge column worker panicked"),
3748            );
3749        }
3750        all
3751    });
3752
3753    let mut built: Vec<Option<Column>> = (0..specs.len()).map(|_| None).collect();
3754    for (idx, column) in built_by_worker {
3755        built[idx] = Some(column);
3756    }
3757    specs
3758        .into_iter()
3759        .zip(built)
3760        .map(|(s, column)| {
3761            (
3762                s.name,
3763                column.expect("every f64 column index is built once"),
3764            )
3765        })
3766        .collect()
3767}
3768
3769fn build_single_key_dense_i64_inner_merge_output(
3770    left: &fp_frame::DataFrame,
3771    right: &fp_frame::DataFrame,
3772    left_on: &[&str],
3773    right_on: &[&str],
3774    left_key: &Column,
3775    right_key: &Column,
3776    options: FusedInt64MergeOptions<'_>,
3777) -> Result<Option<MergedDataFrame>, JoinError> {
3778    debug_assert_eq!(left_on.len(), 1);
3779    debug_assert_eq!(right_on.len(), 1);
3780
3781    let Some(left_keys) = left_key.as_i64_slice() else {
3782        return Ok(None);
3783    };
3784    let Some(right_keys) = right_key.as_i64_slice() else {
3785        return Ok(None);
3786    };
3787
3788    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
3789    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
3790    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
3791    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
3792    let shared_key_names = if left_on[0] == right_on[0] {
3793        [left_on[0]].into_iter().collect::<HashSet<&str>>()
3794    } else {
3795        HashSet::new()
3796    };
3797    let overlapping_names =
3798        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
3799
3800    // Collect output specs in column-encounter order, accepting BOTH typed
3801    // all-valid Int64 and typed all-valid Float64 columns (br-frankenpandas-jzrem).
3802    // Int64 columns keep the lazy repeat-run / repeated-slice representation;
3803    // Float64 columns are materialized cache-efficiently below. Any other dtype,
3804    // a nullable column, or a NaN-bearing Float64 (as_f64_slice gates on
3805    // validity.all()) declines the whole fast path (Ok(None)) and falls back to
3806    // the flat gather, exactly as before.
3807    let mut i64_specs = Vec::<FusedInt64OutputColumn<'_>>::new();
3808    let mut f64_specs = Vec::<FusedF64OutputColumn<'_>>::new();
3809    let mut order_kinds = Vec::<DenseInnerSpecKind>::new();
3810
3811    for name in left.column_names() {
3812        let col = left
3813            .columns()
3814            .get(name)
3815            .expect("left column listed in column_names must exist");
3816        let out_name = if left_key_name_set.contains(name.as_str()) {
3817            name.clone()
3818        } else if right_col_names.contains(name) {
3819            apply_merge_suffix(name, options.suffixes.left.as_deref())
3820        } else {
3821            name.clone()
3822        };
3823        if let Some(values) = col.as_i64_slice() {
3824            i64_specs.push(FusedInt64OutputColumn {
3825                name: out_name,
3826                side: FusedInt64Side::Left,
3827                values,
3828            });
3829            order_kinds.push(DenseInnerSpecKind::I64);
3830        } else if let Some(values) = col.as_f64_slice() {
3831            f64_specs.push(FusedF64OutputColumn {
3832                name: out_name,
3833                side: FusedInt64Side::Left,
3834                values,
3835            });
3836            order_kinds.push(DenseInnerSpecKind::F64);
3837        } else {
3838            return Ok(None);
3839        }
3840    }
3841
3842    for name in right.column_names() {
3843        let col = right
3844            .columns()
3845            .get(name)
3846            .expect("right column listed in column_names must exist");
3847        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
3848            continue;
3849        }
3850        let out_name = if left_col_names.contains(name) {
3851            apply_merge_suffix(name, options.suffixes.right.as_deref())
3852        } else {
3853            name.clone()
3854        };
3855        if let Some(values) = col.as_i64_slice() {
3856            i64_specs.push(FusedInt64OutputColumn {
3857                name: out_name,
3858                side: FusedInt64Side::Right,
3859                values,
3860            });
3861            order_kinds.push(DenseInnerSpecKind::I64);
3862        } else if let Some(values) = col.as_f64_slice() {
3863            f64_specs.push(FusedF64OutputColumn {
3864                name: out_name,
3865                side: FusedInt64Side::Right,
3866                values,
3867            });
3868            order_kinds.push(DenseInnerSpecKind::F64);
3869        } else {
3870            return Ok(None);
3871        }
3872    }
3873
3874    ensure_merge_suffixes_for_overlaps(&overlapping_names, options.suffixes)?;
3875
3876    if left_keys.is_empty() || right_keys.is_empty() {
3877        if options.require_all_left_keys_matched && !left_keys.is_empty() {
3878            return Ok(None);
3879        }
3880        let mut columns = ColumnStore::new();
3881        let mut column_order = Vec::with_capacity(order_kinds.len());
3882        let mut i64_it = i64_specs.into_iter();
3883        let mut f64_it = f64_specs.into_iter();
3884        for kind in &order_kinds {
3885            match kind {
3886                DenseInnerSpecKind::I64 => {
3887                    let spec = i64_it.next().expect("i64 spec for each I64 kind");
3888                    insert_merged_output_column(
3889                        &mut columns,
3890                        &mut column_order,
3891                        spec.name,
3892                        Column::from_i64_values(Vec::new()),
3893                    )?;
3894                }
3895                DenseInnerSpecKind::F64 => {
3896                    let spec = f64_it.next().expect("f64 spec for each F64 kind");
3897                    insert_merged_output_column(
3898                        &mut columns,
3899                        &mut column_order,
3900                        spec.name,
3901                        Column::from_f64_values(Vec::new()),
3902                    )?;
3903                }
3904            }
3905        }
3906        return Ok(Some(MergedDataFrame {
3907            index: Index::new(Vec::new()),
3908            columns,
3909            column_order,
3910        }));
3911    }
3912
3913    let mut min = right_keys[0];
3914    let mut max = right_keys[0];
3915    for &v in right_keys {
3916        if v < min {
3917            min = v;
3918        }
3919        if v > max {
3920            max = v;
3921        }
3922    }
3923    let span = (max as i128) - (min as i128) + 1;
3924    if span > (1i128 << 24) || span > 16 * (right_keys.len() as i128) {
3925        return Ok(None);
3926    }
3927    let range = span as usize;
3928
3929    let mut offsets = vec![0usize; range + 1];
3930    for &v in right_keys {
3931        offsets[(v - min) as usize + 1] += 1;
3932    }
3933    for i in 0..range {
3934        offsets[i + 1] += offsets[i];
3935    }
3936    let mut positions = vec![0usize; right_keys.len()];
3937    let mut cursor = offsets.clone();
3938    for (pos, &v) in right_keys.iter().enumerate() {
3939        let bucket = (v - min) as usize;
3940        positions[cursor[bucket]] = pos;
3941        cursor[bucket] += 1;
3942    }
3943
3944    let mut output_len = 0usize;
3945    for &v in left_keys {
3946        if v < min || v > max {
3947            if options.require_all_left_keys_matched {
3948                return Ok(None);
3949            }
3950            continue;
3951        }
3952        let bucket = (v - min) as usize;
3953        let bucket_len = offsets[bucket + 1] - offsets[bucket];
3954        if bucket_len == 0 {
3955            if options.require_all_left_keys_matched {
3956                return Ok(None);
3957            }
3958            continue;
3959        }
3960        let Some(new_output_len) = output_len.checked_add(bucket_len) else {
3961            return Ok(None);
3962        };
3963        output_len = new_output_len;
3964    }
3965
3966    let output_plan = DenseI64InnerOutputPlan {
3967        left_keys,
3968        min,
3969        max,
3970        offsets: &offsets,
3971        positions: &positions,
3972        output_len,
3973    };
3974    let i64_lanes = build_dense_i64_inner_output_data(&i64_specs, &output_plan);
3975    // Float64 lanes materialized cache-efficiently in the same probe row order
3976    // (br-frankenpandas-jzrem); the matched-run walk is only needed when there
3977    // are Float64 columns to build.
3978    let matched = if f64_specs.is_empty() {
3979        Vec::new()
3980    } else {
3981        dense_inner_matched_runs(&output_plan)
3982    };
3983    let f64_columns = build_dense_inner_f64_columns(f64_specs, &matched, &positions, output_len);
3984
3985    // Lazy unit-range output index: identical labels (0..output_len as
3986    // IndexLabel::Int64, materialized on demand), pre-proven unique and
3987    // ascending — skips the eager Vec<IndexLabel> build for huge join outputs.
3988    let index = Index::new_known_unique_int64_unit_range(0, output_len);
3989    let mut columns = ColumnStore::new();
3990    let mut column_order = Vec::with_capacity(order_kinds.len());
3991    let mut i64_it = i64_specs.into_iter().zip(i64_lanes);
3992    let mut f64_it = f64_columns.into_iter();
3993    for kind in &order_kinds {
3994        match kind {
3995            DenseInnerSpecKind::I64 => {
3996                let (spec, lane) = i64_it.next().expect("i64 lane for each I64 kind");
3997                let column = match lane {
3998                    DenseI64LaneData::RepeatRunLengths { values, run_lens } => {
3999                        Column::from_i64_repeat_values_run_lengths(values, run_lens)
4000                    }
4001                    DenseI64LaneData::RepeatedSlices { data, segments } => {
4002                        Column::from_i64_repeated_slices_shared(data, segments, output_len)
4003                    }
4004                    DenseI64LaneData::Full(data) => Column::from_i64_values(data),
4005                };
4006                debug_assert_eq!(column.len(), output_len);
4007                insert_merged_output_column(&mut columns, &mut column_order, spec.name, column)?;
4008            }
4009            DenseInnerSpecKind::F64 => {
4010                let (name, column) = f64_it.next().expect("f64 column for each F64 kind");
4011                debug_assert_eq!(column.len(), output_len);
4012                insert_merged_output_column(&mut columns, &mut column_order, name, column)?;
4013            }
4014        }
4015    }
4016
4017    Ok(Some(MergedDataFrame {
4018        index,
4019        columns,
4020        column_order,
4021    }))
4022}
4023
4024fn push_join_invalid_range(ranges: &mut Vec<(usize, usize)>, start: usize, len: usize) {
4025    if len == 0 {
4026        return;
4027    }
4028    if let Some((last_start, last_len)) = ranges.last_mut()
4029        && last_start.checked_add(*last_len) == Some(start)
4030    {
4031        *last_len += len;
4032        return;
4033    }
4034    ranges.push((start, len));
4035}
4036
4037fn dense_cycle_key_at(witness: Int64DenseCycleWitness, row: usize) -> Option<i64> {
4038    let offset = i64::try_from(row % witness.period).ok()?;
4039    witness.start.checked_add(offset)
4040}
4041
4042fn dense_cycle_left_join_shape(
4043    left_witness: Int64DenseCycleWitness,
4044    right_witness: Int64DenseCycleWitness,
4045) -> Option<(usize, ValidityMask)> {
4046    let mut output_len = 0usize;
4047    let mut invalid_ranges = Vec::<(usize, usize)>::new();
4048    for left_pos in 0..left_witness.len {
4049        let key = dense_cycle_key_at(left_witness, left_pos)?;
4050        if let Some((_, right_count)) = right_witness.offset_count_for_key(key) {
4051            output_len = output_len.checked_add(right_count)?;
4052        } else {
4053            push_join_invalid_range(&mut invalid_ranges, output_len, 1);
4054            output_len = output_len.checked_add(1)?;
4055        }
4056    }
4057    let right_validity = ValidityMask::from_invalid_ranges(Arc::from(invalid_ranges), output_len);
4058    Some((output_len, right_validity))
4059}
4060
4061/// Dense-cycle LEFT merge builder (br-frankenpandas-yq96z).
4062///
4063/// For certified `key[row] = start + (row % period)` Int64 keys, the previous
4064/// high-fanout left path still built an O(left_rows) plan, right segment tape,
4065/// and one repeat-run descriptor per left lane. This path keeps the same
4066/// left-major pandas order but stores only the two key witnesses:
4067///
4068/// - output length/right validity are derived by scanning the left witness once;
4069/// - left lanes read `source[left_pos]` and repeat by the matching right count;
4070/// - right lanes replay positions `right_offset + k * right_period`;
4071/// - unmatched left rows emit one right null at the same output slot.
4072///
4073/// The route accepts only all-valid Int64 columns. Any other dtype/null shape
4074/// falls back to the existing materialized-plan builder.
4075fn build_single_key_dense_cycle_i64_left_merge_output(
4076    left: &fp_frame::DataFrame,
4077    right: &fp_frame::DataFrame,
4078    left_on: &[&str],
4079    right_on: &[&str],
4080    left_key: &Column,
4081    right_key: &Column,
4082    suffixes: &ResolvedMergeSuffixes,
4083) -> Result<Option<MergedDataFrame>, JoinError> {
4084    debug_assert_eq!(left_on.len(), 1);
4085    debug_assert_eq!(right_on.len(), 1);
4086
4087    let Some(left_witness) = left_key
4088        .int64_dense_cycle_witness()
4089        .filter(|witness| witness.len == left_key.len())
4090    else {
4091        return Ok(None);
4092    };
4093    let Some(right_witness) = right_key
4094        .int64_dense_cycle_witness()
4095        .filter(|witness| witness.len == right_key.len())
4096    else {
4097        return Ok(None);
4098    };
4099    let Some((output_len, right_validity)) =
4100        dense_cycle_left_join_shape(left_witness, right_witness)
4101    else {
4102        return Ok(None);
4103    };
4104    if !right_validity.all() {
4105        // The generic gather promotes all-valid Int64 lanes when this join
4106        // invents a gap. This lazy i64-only representation cannot do so.
4107        return Ok(None);
4108    }
4109
4110    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
4111    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
4112    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
4113    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
4114    let shared_key_names = if left_on[0] == right_on[0] {
4115        [left_on[0]].into_iter().collect::<HashSet<&str>>()
4116    } else {
4117        HashSet::new()
4118    };
4119    let overlapping_names =
4120        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
4121
4122    enum DenseCycleLeftLane {
4123        Left,
4124        Right,
4125    }
4126    let mut spec_names = Vec::<String>::new();
4127    let mut spec_kinds = Vec::<DenseCycleLeftLane>::new();
4128    let mut spec_sources = Vec::<Arc<[i64]>>::new();
4129
4130    for name in left.column_names() {
4131        let col = left
4132            .columns()
4133            .get(name)
4134            .expect("left column listed in column_names must exist");
4135        let Some(source) = col.as_i64_arc() else {
4136            return Ok(None);
4137        };
4138        let out_name = if left_key_name_set.contains(name.as_str()) {
4139            name.clone()
4140        } else if right_col_names.contains(name) {
4141            apply_merge_suffix(name, suffixes.left.as_deref())
4142        } else {
4143            name.clone()
4144        };
4145        spec_names.push(out_name);
4146        spec_kinds.push(DenseCycleLeftLane::Left);
4147        spec_sources.push(source);
4148    }
4149
4150    for name in right.column_names() {
4151        let col = right
4152            .columns()
4153            .get(name)
4154            .expect("right column listed in column_names must exist");
4155        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
4156            continue;
4157        }
4158        let Some(source) = col.as_i64_arc() else {
4159            return Ok(None);
4160        };
4161        let out_name = if left_col_names.contains(name) {
4162            apply_merge_suffix(name, suffixes.right.as_deref())
4163        } else {
4164            name.clone()
4165        };
4166        spec_names.push(out_name);
4167        spec_kinds.push(DenseCycleLeftLane::Right);
4168        spec_sources.push(source);
4169    }
4170    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
4171
4172    let index = Index::new_known_unique_int64_unit_range(0, output_len);
4173    let mut columns = ColumnStore::new();
4174    let mut column_order = Vec::with_capacity(spec_names.len());
4175    for ((name, kind), source) in spec_names.into_iter().zip(spec_kinds).zip(spec_sources) {
4176        let column = match kind {
4177            DenseCycleLeftLane::Left => Column::from_i64_left_join_dense_cycle_left(
4178                source,
4179                left_witness,
4180                right_witness,
4181                output_len,
4182            ),
4183            DenseCycleLeftLane::Right => Column::from_i64_left_join_dense_cycle_right_nullable(
4184                source,
4185                left_witness,
4186                right_witness,
4187                right_validity.clone(),
4188                output_len,
4189            ),
4190        };
4191        debug_assert_eq!(column.len(), output_len);
4192        insert_merged_output_column(&mut columns, &mut column_order, name, column)?;
4193    }
4194
4195    Ok(Some(MergedDataFrame {
4196        index,
4197        columns,
4198        column_order,
4199    }))
4200}
4201
4202/// Fused dense-i64 LEFT merge builder (br-frankenpandas-7wxoc).
4203///
4204/// The partial-match left join previously materialized TWO
4205/// `Vec<Option<usize>>` of output length (16 B/slot each — ~627 MB of
4206/// intermediate on a 19.6M-row join) in `dense_int64_left_positions`, then
4207/// re-walked them per column through `reindex_by_positions`. Here the probe
4208/// emits a compact matched plan (`(left_pos, bucket_start, run_len)`, with
4209/// `usize::MAX` as the bucket sentinel for unmatched left rows that emit one
4210/// null-right row), and the output lanes are built with the proven inner-
4211/// builder machinery: muis1 right value tapes, 6bsw3 row-chunked disjoint
4212/// `split_at_mut` fills, 3ad4n lazy repeat-run left lanes, plus ONE shared
4213/// validity mask for every right lane (the null pattern is identical across
4214/// them — word-wise run fills, cloned per lane).
4215///
4216/// Bit-identical to the position-vector path: the plan is the same left
4217/// probe order; matched runs replay the same CSR bucket ranges; right lanes
4218/// keep dtype Int64 with `Null(NullKind::Null)` at unmatched rows (exactly
4219/// `reindex_by_positions`' missing semantics); left lanes repeat the left
4220/// value `run_len` times as `take_positions` would.
4221fn build_single_key_dense_i64_left_merge_output(
4222    left: &fp_frame::DataFrame,
4223    right: &fp_frame::DataFrame,
4224    left_on: &[&str],
4225    right_on: &[&str],
4226    left_key: &Column,
4227    right_key: &Column,
4228    suffixes: &ResolvedMergeSuffixes,
4229) -> Result<Option<MergedDataFrame>, JoinError> {
4230    debug_assert_eq!(left_on.len(), 1);
4231    debug_assert_eq!(right_on.len(), 1);
4232
4233    let Some(left_keys) = left_key.as_i64_slice() else {
4234        return Ok(None);
4235    };
4236    let Some(right_keys) = right_key.as_i64_slice() else {
4237        return Ok(None);
4238    };
4239    // Empty sides are rare and the position-vector path handles their edge
4240    // semantics; the dense-span gate below also needs a non-empty right.
4241    if left_keys.is_empty() || right_keys.is_empty() {
4242        return Ok(None);
4243    }
4244
4245    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
4246    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
4247    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
4248    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
4249    let shared_key_names = if left_on[0] == right_on[0] {
4250        [left_on[0]].into_iter().collect::<HashSet<&str>>()
4251    } else {
4252        HashSet::new()
4253    };
4254    let overlapping_names =
4255        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
4256
4257    let mut specs = Vec::<FusedInt64OutputColumn<'_>>::new();
4258    let mut sources = Vec::<Arc<[i64]>>::new();
4259    for name in left.column_names() {
4260        let col = left
4261            .columns()
4262            .get(name)
4263            .expect("left column listed in column_names must exist");
4264        let Some(values) = col.as_i64_slice() else {
4265            return Ok(None);
4266        };
4267        let source = col.as_i64_arc().unwrap_or_else(|| Arc::from(values));
4268        let out_name = if left_key_name_set.contains(name.as_str()) {
4269            name.clone()
4270        } else if right_col_names.contains(name) {
4271            apply_merge_suffix(name, suffixes.left.as_deref())
4272        } else {
4273            name.clone()
4274        };
4275        specs.push(FusedInt64OutputColumn {
4276            name: out_name,
4277            side: FusedInt64Side::Left,
4278            values,
4279        });
4280        sources.push(source);
4281    }
4282    for name in right.column_names() {
4283        let col = right
4284            .columns()
4285            .get(name)
4286            .expect("right column listed in column_names must exist");
4287        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
4288            continue;
4289        }
4290        let Some(values) = col.as_i64_slice() else {
4291            return Ok(None);
4292        };
4293        let source = col.as_i64_arc().unwrap_or_else(|| Arc::from(values));
4294        let out_name = if left_col_names.contains(name) {
4295            apply_merge_suffix(name, suffixes.right.as_deref())
4296        } else {
4297            name.clone()
4298        };
4299        specs.push(FusedInt64OutputColumn {
4300            name: out_name,
4301            side: FusedInt64Side::Right,
4302            values,
4303        });
4304        sources.push(source);
4305    }
4306    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
4307
4308    let row_count = left_keys.len().saturating_add(right_keys.len());
4309    let max_dense_span = row_count.saturating_mul(4).max(1024);
4310    let left_witness = left_key
4311        .int64_dense_cycle_witness()
4312        .filter(|witness| witness.len == left_keys.len());
4313    let right_witness = right_key
4314        .int64_dense_cycle_witness()
4315        .filter(|witness| witness.len == right_keys.len());
4316    if let (Some(left_witness), Some(right_witness), Some((right_min, right_max))) = (
4317        left_witness,
4318        right_witness,
4319        right_witness.and_then(dense_cycle_domain),
4320    ) {
4321        let right_span = i128::from(right_max) - i128::from(right_min) + 1;
4322        if right_span <= max_dense_span as i128
4323            && let Some((output_len, right_validity)) =
4324                dense_cycle_probe_output_len_and_validity(left_witness, right_witness)
4325        {
4326            if !right_validity.all() {
4327                // Fall through to the typed gather below, which widens the
4328                // gap-bearing Int64 lanes to Float64 like pandas.
4329            } else {
4330                let index = Index::new_known_unique_int64_unit_range(0, output_len);
4331                let mut columns = ColumnStore::new();
4332                let mut column_order = Vec::with_capacity(specs.len());
4333                for (spec, source) in specs.into_iter().zip(sources) {
4334                    let column = match spec.side {
4335                        FusedInt64Side::Left => Column::from_i64_dense_cycle_probe_repeat(
4336                            source,
4337                            left_witness,
4338                            right_witness,
4339                            output_len,
4340                        ),
4341                        FusedInt64Side::Right => {
4342                            Column::from_i64_nullable_dense_cycle_probe_build_with_sparse_validity(
4343                                source,
4344                                left_witness,
4345                                right_witness,
4346                                right_validity.clone(),
4347                                output_len,
4348                            )
4349                        }
4350                    };
4351                    debug_assert_eq!(column.len(), output_len);
4352                    insert_merged_output_column(
4353                        &mut columns,
4354                        &mut column_order,
4355                        spec.name,
4356                        column,
4357                    )?;
4358                }
4359                return Ok(Some(MergedDataFrame {
4360                    index,
4361                    columns,
4362                    column_order,
4363                }));
4364            }
4365        }
4366    }
4367
4368    // Dense CSR over the RIGHT key range — same gate as the position path
4369    // (span <= 4*(rows)+1024) so routing between fused/fallback matches
4370    // dense_int64_left_positions' accept set.
4371    let mut min_key = right_keys[0];
4372    let mut max_key = right_keys[0];
4373    for &key in right_keys {
4374        min_key = min_key.min(key);
4375        max_key = max_key.max(key);
4376    }
4377    let span = (i128::from(max_key)) - (i128::from(min_key)) + 1;
4378    if span > max_dense_span as i128 {
4379        return Ok(None);
4380    }
4381    let span = usize::try_from(span).expect("span bounded by max_dense_span");
4382
4383    let mut offsets = vec![0usize; span + 1];
4384    for &key in right_keys {
4385        offsets[(key - min_key) as usize + 1] += 1;
4386    }
4387    for i in 0..span {
4388        offsets[i + 1] += offsets[i];
4389    }
4390    let mut positions = vec![0usize; right_keys.len()];
4391    let mut cursor = offsets[..span].to_vec();
4392    for (pos, &key) in right_keys.iter().enumerate() {
4393        let bucket = (key - min_key) as usize;
4394        positions[cursor[bucket]] = pos;
4395        cursor[bucket] += 1;
4396    }
4397
4398    // Matched plan: (left_pos, bucket_start, run_len); bucket_start ==
4399    // usize::MAX marks an unmatched left row (one output row, null right).
4400    const UNMATCHED: usize = usize::MAX;
4401    let mut plan = Vec::<(usize, usize, usize)>::with_capacity(left_keys.len());
4402    let mut output_len = 0usize;
4403    for (left_pos, &key) in left_keys.iter().enumerate() {
4404        let offset = i128::from(key) - i128::from(min_key);
4405        let run = if offset >= 0 && offset < span as i128 {
4406            let bucket = offset as usize;
4407            let start = offsets[bucket];
4408            let len = offsets[bucket + 1] - start;
4409            if len == 0 {
4410                (left_pos, UNMATCHED, 1)
4411            } else {
4412                (left_pos, start, len)
4413            }
4414        } else {
4415            (left_pos, UNMATCHED, 1)
4416        };
4417        let Some(new_len) = output_len.checked_add(run.2) else {
4418            return Ok(None);
4419        };
4420        output_len = new_len;
4421        plan.push(run);
4422    }
4423    if plan.iter().any(|&(_, start, _)| start == UNMATCHED) {
4424        return Ok(None);
4425    }
4426
4427    // Shared right-lane segment descriptor (br-frankenpandas-yiqv5): the plan's
4428    // `(bucket_start, run_len)` pairs are exactly the nullable repeated-slices
4429    // segment format (`bucket_start == usize::MAX` == UNMATCHED ⇒ a null run), so
4430    // every right lane is emitted as a LAZY `LazyNullableRepeatedSlicesInt64`
4431    // over its bucket-order value tape instead of a materialized O(output_len)
4432    // buffer. The validity mask is rebuilt from these segments inside the column
4433    // ctor (matched runs valid, unmatched rows null) — identical to the prior
4434    // word-wise fill.
4435    let right_segments: Arc<[(usize, usize)]> = plan
4436        .iter()
4437        .map(|&(_, start, run_len)| (start, run_len))
4438        .collect();
4439
4440    // Left lanes as lazy repeat runs when the average fanout pays (3ad4n
4441    // gate); unmatched rows are singleton runs so the representation is
4442    // uniform.
4443    let use_repeat_runs = output_len >= plan.len().saturating_mul(2);
4444
4445    // Only LOW-FANOUT LEFT lanes still materialize into O(output_len) buffers;
4446    // right lanes are always lazy (nullable repeated-slices) and high-fanout
4447    // left lanes are lazy repeat runs.
4448    let full_specs: Vec<usize> = specs
4449        .iter()
4450        .enumerate()
4451        .filter(|(_, spec)| matches!(spec.side, FusedInt64Side::Left) && !use_repeat_runs)
4452        .map(|(idx, _)| idx)
4453        .collect();
4454
4455    let mut full_data: Vec<Vec<i64>> = Vec::new();
4456    let thread_count = join_parallel_thread_count();
4457    if !full_specs.is_empty() {
4458        // Right value tapes in bucket order (muis1), shared read-only.
4459        let tapes: Vec<Option<Vec<i64>>> = full_specs
4460            .iter()
4461            .map(|&spec_idx| match specs[spec_idx].side {
4462                FusedInt64Side::Left => None,
4463                FusedInt64Side::Right => Some(
4464                    positions
4465                        .iter()
4466                        .map(|&right_pos| specs[spec_idx].values[right_pos])
4467                        .collect(),
4468                ),
4469            })
4470            .collect();
4471
4472        if output_len >= DENSE_I64_INNER_PARALLEL_MIN_VALUES && thread_count > 1 {
4473            // Output-balanced chunk boundaries over the plan (6bsw3).
4474            let target = output_len.div_ceil(thread_count).max(1);
4475            let mut boundaries = vec![(0usize, 0usize)];
4476            let mut cumulative = 0usize;
4477            let mut next_target = target;
4478            for (plan_idx, &(_, _, run_len)) in plan.iter().enumerate() {
4479                cumulative += run_len;
4480                if cumulative >= next_target && plan_idx + 1 < plan.len() {
4481                    boundaries.push((plan_idx + 1, cumulative));
4482                    next_target = cumulative.saturating_add(target);
4483                }
4484            }
4485            boundaries.push((plan.len(), output_len));
4486            let chunk_count = boundaries.len() - 1;
4487
4488            let mut column_bufs: Vec<Vec<i64>> =
4489                full_specs.iter().map(|_| vec![0i64; output_len]).collect();
4490            let mut bundles: Vec<Vec<&mut [i64]>> = (0..chunk_count)
4491                .map(|_| Vec::with_capacity(full_specs.len()))
4492                .collect();
4493            for buf in &mut column_bufs {
4494                let mut rest: &mut [i64] = buf.as_mut_slice();
4495                let mut prev = 0usize;
4496                for (chunk_idx, window) in boundaries.windows(2).enumerate() {
4497                    let (chunk_slice, tail) = rest.split_at_mut(window[1].1 - prev);
4498                    prev = window[1].1;
4499                    rest = tail;
4500                    bundles[chunk_idx].push(chunk_slice);
4501                }
4502            }
4503
4504            let plan = &plan;
4505            let specs_ref = &specs;
4506            let full_specs_ref = &full_specs;
4507            std::thread::scope(|scope| {
4508                let mut handles = Vec::with_capacity(chunk_count);
4509                for (chunk_idx, mut bundle) in bundles.into_iter().enumerate() {
4510                    let (plan_start, out_start) = boundaries[chunk_idx];
4511                    let (plan_end, out_end) = boundaries[chunk_idx + 1];
4512                    let tapes = &tapes;
4513                    handles.push(scope.spawn(move || {
4514                        let mut cursor = 0usize;
4515                        for &(left_pos, start, run_len) in &plan[plan_start..plan_end] {
4516                            for (slice, (&spec_idx, tape)) in bundle
4517                                .iter_mut()
4518                                .zip(full_specs_ref.iter().zip(tapes.iter()))
4519                            {
4520                                match specs_ref[spec_idx].side {
4521                                    FusedInt64Side::Left => {
4522                                        slice[cursor..cursor + run_len]
4523                                            .fill(specs_ref[spec_idx].values[left_pos]);
4524                                    }
4525                                    FusedInt64Side::Right => {
4526                                        if start != UNMATCHED {
4527                                            slice[cursor..cursor + run_len].copy_from_slice(
4528                                                &tape
4529                                                    .as_ref()
4530                                                    .expect("right spec must have a bucket tape")
4531                                                    [start..start + run_len],
4532                                            );
4533                                        }
4534                                        // Unmatched rows keep the zeroed
4535                                        // datum; the shared validity mask
4536                                        // marks them null.
4537                                    }
4538                                }
4539                            }
4540                            cursor += run_len;
4541                        }
4542                        debug_assert_eq!(cursor, out_end - out_start);
4543                    }));
4544                }
4545                for handle in handles {
4546                    handle
4547                        .join()
4548                        .expect("dense i64 left output worker must not panic");
4549                }
4550            });
4551            full_data = column_bufs;
4552        } else {
4553            full_data = full_specs.iter().map(|_| vec![0i64; output_len]).collect();
4554            let mut cursor = 0usize;
4555            for &(left_pos, start, run_len) in &plan {
4556                for (buf, (&spec_idx, tape)) in full_data
4557                    .iter_mut()
4558                    .zip(full_specs.iter().zip(tapes.iter()))
4559                {
4560                    match specs[spec_idx].side {
4561                        FusedInt64Side::Left => {
4562                            buf[cursor..cursor + run_len].fill(specs[spec_idx].values[left_pos]);
4563                        }
4564                        FusedInt64Side::Right => {
4565                            if start != UNMATCHED {
4566                                buf[cursor..cursor + run_len].copy_from_slice(
4567                                    &tape.as_ref().expect("right spec must have a bucket tape")
4568                                        [start..start + run_len],
4569                                );
4570                            }
4571                        }
4572                    }
4573                }
4574                cursor += run_len;
4575            }
4576            debug_assert_eq!(cursor, output_len);
4577        }
4578    }
4579
4580    // Lazy unit-range output index (see build_single_key_dense_i64 site).
4581    let index = Index::new_known_unique_int64_unit_range(0, output_len);
4582    let mut columns = ColumnStore::new();
4583    let mut column_order = Vec::with_capacity(specs.len());
4584    let mut full_iter = full_data.into_iter();
4585    for spec in specs {
4586        let column = match spec.side {
4587            FusedInt64Side::Right => {
4588                // Lazy nullable repeated-slices over the bucket-order tape
4589                // (br-frankenpandas-yiqv5): O(matched) descriptor, no O(output)
4590                // materialization.
4591                let tape: Vec<i64> = positions
4592                    .iter()
4593                    .map(|&right_pos| spec.values[right_pos])
4594                    .collect();
4595                Column::from_i64_nullable_repeated_slices_shared(
4596                    tape,
4597                    Arc::clone(&right_segments),
4598                    output_len,
4599                )
4600            }
4601            FusedInt64Side::Left if use_repeat_runs => Column::from_i64_repeat_runs(
4602                plan.iter()
4603                    .map(|&(left_pos, _, run_len)| (spec.values[left_pos], run_len))
4604                    .collect(),
4605            ),
4606            FusedInt64Side::Left => {
4607                let data = full_iter
4608                    .next()
4609                    .expect("full lane buffer must exist for every non-run left spec");
4610                Column::from_i64_values(data)
4611            }
4612        };
4613        debug_assert_eq!(column.len(), output_len);
4614        insert_merged_output_column(&mut columns, &mut column_order, spec.name, column)?;
4615    }
4616
4617    Ok(Some(MergedDataFrame {
4618        index,
4619        columns,
4620        column_order,
4621    }))
4622}
4623
4624/// Fused dense-i64 RIGHT merge builder (br-frankenpandas-4p3ie) — the
4625/// side-swapped mirror of [`build_single_key_dense_i64_left_merge_output`]:
4626/// the probe walks RIGHT keys in probe order against a dense CSR over the
4627/// LEFT key range, emitting `(right_pos, left_bucket_start, run_len)` plan
4628/// rows (`usize::MAX` sentinel = unmatched right row, one null-left output
4629/// row). Right lanes (including the shared key column, which pandas fills
4630/// from the RIGHT side under the LEFT name) are all-valid repeat runs; left
4631/// lanes fill from muis1-style left value tapes with ONE shared validity
4632/// mask and keep dtype Int64 with `Null(NullKind::Null)` at unmatched rows
4633/// (`reindex_by_positions` missing semantics — NOT Float64-promoted).
4634fn build_single_key_dense_i64_right_merge_output(
4635    left: &fp_frame::DataFrame,
4636    right: &fp_frame::DataFrame,
4637    left_on: &[&str],
4638    right_on: &[&str],
4639    left_key: &Column,
4640    right_key: &Column,
4641    suffixes: &ResolvedMergeSuffixes,
4642) -> Result<Option<MergedDataFrame>, JoinError> {
4643    debug_assert_eq!(left_on.len(), 1);
4644    debug_assert_eq!(right_on.len(), 1);
4645
4646    let Some(left_keys) = left_key.as_i64_slice() else {
4647        return Ok(None);
4648    };
4649    let Some(right_keys) = right_key.as_i64_slice() else {
4650        return Ok(None);
4651    };
4652    if left_keys.is_empty() || right_keys.is_empty() {
4653        return Ok(None);
4654    }
4655
4656    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
4657    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
4658    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
4659    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
4660    let shared_key_names = if left_on[0] == right_on[0] {
4661        [left_on[0]].into_iter().collect::<HashSet<&str>>()
4662    } else {
4663        HashSet::new()
4664    };
4665    let overlapping_names =
4666        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
4667
4668    // Lane specs in output order. The shared key slot keeps the LEFT name
4669    // but carries RIGHT key values (all output rows have a right row), so it
4670    // is a Right-side lane on right_keys.
4671    let mut specs = Vec::<FusedInt64OutputColumn<'_>>::new();
4672    let mut sources = Vec::<Arc<[i64]>>::new();
4673    for name in left.column_names() {
4674        let col = left
4675            .columns()
4676            .get(name)
4677            .expect("left column listed in column_names must exist");
4678        let Some(values) = col.as_i64_slice() else {
4679            return Ok(None);
4680        };
4681        if left_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
4682            let right_key_col = right
4683                .columns()
4684                .get(right_on[0])
4685                .expect("right key column must exist");
4686            let source = right_key_col
4687                .as_i64_arc()
4688                .unwrap_or_else(|| Arc::from(right_keys));
4689            specs.push(FusedInt64OutputColumn {
4690                name: name.clone(),
4691                side: FusedInt64Side::Right,
4692                values: right_keys,
4693            });
4694            sources.push(source);
4695            continue;
4696        }
4697        let source = col.as_i64_arc().unwrap_or_else(|| Arc::from(values));
4698        let out_name = if left_key_name_set.contains(name.as_str()) {
4699            name.clone()
4700        } else if right_col_names.contains(name) {
4701            apply_merge_suffix(name, suffixes.left.as_deref())
4702        } else {
4703            name.clone()
4704        };
4705        specs.push(FusedInt64OutputColumn {
4706            name: out_name,
4707            side: FusedInt64Side::Left,
4708            values,
4709        });
4710        sources.push(source);
4711    }
4712    for name in right.column_names() {
4713        let col = right
4714            .columns()
4715            .get(name)
4716            .expect("right column listed in column_names must exist");
4717        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
4718            continue;
4719        }
4720        let Some(values) = col.as_i64_slice() else {
4721            return Ok(None);
4722        };
4723        let source = col.as_i64_arc().unwrap_or_else(|| Arc::from(values));
4724        let out_name = if left_col_names.contains(name) {
4725            apply_merge_suffix(name, suffixes.right.as_deref())
4726        } else {
4727            name.clone()
4728        };
4729        specs.push(FusedInt64OutputColumn {
4730            name: out_name,
4731            side: FusedInt64Side::Right,
4732            values,
4733        });
4734        sources.push(source);
4735    }
4736    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
4737
4738    let row_count = left_keys.len().saturating_add(right_keys.len());
4739    let max_dense_span = row_count.saturating_mul(4).max(1024);
4740    let left_witness = left_key
4741        .int64_dense_cycle_witness()
4742        .filter(|witness| witness.len == left_keys.len());
4743    let right_witness = right_key
4744        .int64_dense_cycle_witness()
4745        .filter(|witness| witness.len == right_keys.len());
4746    if let (Some(left_witness), Some(right_witness), Some((left_min, left_max))) = (
4747        left_witness,
4748        right_witness,
4749        left_witness.and_then(dense_cycle_domain),
4750    ) {
4751        let left_span = i128::from(left_max) - i128::from(left_min) + 1;
4752        if left_span <= max_dense_span as i128
4753            && let Some((output_len, left_validity)) =
4754                dense_cycle_probe_output_len_and_validity(right_witness, left_witness)
4755        {
4756            if !left_validity.all() {
4757                // See the LEFT merge mirror: only the typed gather can
4758                // preserve pandas' Int64-to-Float64 widening for a new gap.
4759            } else {
4760                let index = Index::new_known_unique_int64_unit_range(0, output_len);
4761                let mut columns = ColumnStore::new();
4762                let mut column_order = Vec::with_capacity(specs.len());
4763                for (spec, source) in specs.into_iter().zip(sources) {
4764                    let column = match spec.side {
4765                        FusedInt64Side::Left => {
4766                            Column::from_i64_nullable_dense_cycle_probe_build_with_sparse_validity(
4767                                source,
4768                                right_witness,
4769                                left_witness,
4770                                left_validity.clone(),
4771                                output_len,
4772                            )
4773                        }
4774                        FusedInt64Side::Right => Column::from_i64_dense_cycle_probe_repeat(
4775                            source,
4776                            right_witness,
4777                            left_witness,
4778                            output_len,
4779                        ),
4780                    };
4781                    debug_assert_eq!(column.len(), output_len);
4782                    insert_merged_output_column(
4783                        &mut columns,
4784                        &mut column_order,
4785                        spec.name,
4786                        column,
4787                    )?;
4788                }
4789                return Ok(Some(MergedDataFrame {
4790                    index,
4791                    columns,
4792                    column_order,
4793                }));
4794            }
4795        }
4796    }
4797
4798    // Dense CSR over the LEFT key range — same gate as
4799    // dense_int64_right_positions (span <= 4*rows+1024).
4800    let mut min_key = left_keys[0];
4801    let mut max_key = left_keys[0];
4802    for &key in left_keys {
4803        min_key = min_key.min(key);
4804        max_key = max_key.max(key);
4805    }
4806    let span = (i128::from(max_key)) - (i128::from(min_key)) + 1;
4807    if span > max_dense_span as i128 {
4808        return Ok(None);
4809    }
4810    let span = usize::try_from(span).expect("span bounded by max_dense_span");
4811
4812    let mut offsets = vec![0usize; span + 1];
4813    for &key in left_keys {
4814        offsets[(key - min_key) as usize + 1] += 1;
4815    }
4816    for i in 0..span {
4817        offsets[i + 1] += offsets[i];
4818    }
4819    let mut positions = vec![0usize; left_keys.len()];
4820    let mut cursor = offsets[..span].to_vec();
4821    for (pos, &key) in left_keys.iter().enumerate() {
4822        let bucket = (key - min_key) as usize;
4823        positions[cursor[bucket]] = pos;
4824        cursor[bucket] += 1;
4825    }
4826
4827    // Plan over RIGHT probe order: (right_pos, left_bucket_start, run_len);
4828    // usize::MAX = unmatched right row (one null-left output row).
4829    const UNMATCHED: usize = usize::MAX;
4830    let mut plan = Vec::<(usize, usize, usize)>::with_capacity(right_keys.len());
4831    let mut output_len = 0usize;
4832    for (right_pos, &key) in right_keys.iter().enumerate() {
4833        let offset = i128::from(key) - i128::from(min_key);
4834        let run = if offset >= 0 && offset < span as i128 {
4835            let bucket = offset as usize;
4836            let start = offsets[bucket];
4837            let len = offsets[bucket + 1] - start;
4838            if len == 0 {
4839                (right_pos, UNMATCHED, 1)
4840            } else {
4841                (right_pos, start, len)
4842            }
4843        } else {
4844            (right_pos, UNMATCHED, 1)
4845        };
4846        let Some(new_len) = output_len.checked_add(run.2) else {
4847            return Ok(None);
4848        };
4849        output_len = new_len;
4850        plan.push(run);
4851    }
4852    if plan.iter().any(|&(_, start, _)| start == UNMATCHED) {
4853        return Ok(None);
4854    }
4855
4856    // One shared validity mask for every left lane.
4857    // Shared left-lane segment descriptor (br-frankenpandas-yiqv5): mirror of
4858    // the left builder — every null-introduced LEFT lane is a LAZY
4859    // `LazyNullableRepeatedSlicesInt64` over its bucket-order tape (plan's
4860    // `(bucket_start, run_len)`, `usize::MAX` ⇒ null run) instead of a
4861    // materialized O(output_len) buffer; validity rebuilt in the ctor.
4862    let left_segments: Arc<[(usize, usize)]> = plan
4863        .iter()
4864        .map(|&(_, start, run_len)| (start, run_len))
4865        .collect();
4866
4867    // Right lanes (all-valid) as lazy repeat runs when the fanout pays.
4868    let use_repeat_runs = output_len >= plan.len().saturating_mul(2);
4869
4870    // Only LOW-FANOUT RIGHT lanes still materialize; left lanes are always lazy
4871    // (nullable repeated-slices) and high-fanout right lanes are lazy repeat runs.
4872    let full_specs: Vec<usize> = specs
4873        .iter()
4874        .enumerate()
4875        .filter(|(_, spec)| matches!(spec.side, FusedInt64Side::Right) && !use_repeat_runs)
4876        .map(|(idx, _)| idx)
4877        .collect();
4878
4879    let mut full_data: Vec<Vec<i64>> = Vec::new();
4880    let thread_count = join_parallel_thread_count();
4881    if !full_specs.is_empty() {
4882        // LEFT value tapes in bucket order, shared read-only.
4883        let tapes: Vec<Option<Vec<i64>>> = full_specs
4884            .iter()
4885            .map(|&spec_idx| match specs[spec_idx].side {
4886                FusedInt64Side::Right => None,
4887                FusedInt64Side::Left => Some(
4888                    positions
4889                        .iter()
4890                        .map(|&left_pos| specs[spec_idx].values[left_pos])
4891                        .collect(),
4892                ),
4893            })
4894            .collect();
4895
4896        if output_len >= DENSE_I64_INNER_PARALLEL_MIN_VALUES && thread_count > 1 {
4897            let target = output_len.div_ceil(thread_count).max(1);
4898            let mut boundaries = vec![(0usize, 0usize)];
4899            let mut cumulative = 0usize;
4900            let mut next_target = target;
4901            for (plan_idx, &(_, _, run_len)) in plan.iter().enumerate() {
4902                cumulative += run_len;
4903                if cumulative >= next_target && plan_idx + 1 < plan.len() {
4904                    boundaries.push((plan_idx + 1, cumulative));
4905                    next_target = cumulative.saturating_add(target);
4906                }
4907            }
4908            boundaries.push((plan.len(), output_len));
4909            let chunk_count = boundaries.len() - 1;
4910
4911            let mut column_bufs: Vec<Vec<i64>> =
4912                full_specs.iter().map(|_| vec![0i64; output_len]).collect();
4913            let mut bundles: Vec<Vec<&mut [i64]>> = (0..chunk_count)
4914                .map(|_| Vec::with_capacity(full_specs.len()))
4915                .collect();
4916            for buf in &mut column_bufs {
4917                let mut rest: &mut [i64] = buf.as_mut_slice();
4918                let mut prev = 0usize;
4919                for (chunk_idx, window) in boundaries.windows(2).enumerate() {
4920                    let (chunk_slice, tail) = rest.split_at_mut(window[1].1 - prev);
4921                    prev = window[1].1;
4922                    rest = tail;
4923                    bundles[chunk_idx].push(chunk_slice);
4924                }
4925            }
4926
4927            let plan = &plan;
4928            let specs_ref = &specs;
4929            let full_specs_ref = &full_specs;
4930            std::thread::scope(|scope| {
4931                let mut handles = Vec::with_capacity(chunk_count);
4932                for (chunk_idx, mut bundle) in bundles.into_iter().enumerate() {
4933                    let (plan_start, out_start) = boundaries[chunk_idx];
4934                    let (plan_end, out_end) = boundaries[chunk_idx + 1];
4935                    let tapes = &tapes;
4936                    handles.push(scope.spawn(move || {
4937                        let mut cursor = 0usize;
4938                        for &(right_pos, start, run_len) in &plan[plan_start..plan_end] {
4939                            for (slice, (&spec_idx, tape)) in bundle
4940                                .iter_mut()
4941                                .zip(full_specs_ref.iter().zip(tapes.iter()))
4942                            {
4943                                match specs_ref[spec_idx].side {
4944                                    FusedInt64Side::Right => {
4945                                        slice[cursor..cursor + run_len]
4946                                            .fill(specs_ref[spec_idx].values[right_pos]);
4947                                    }
4948                                    FusedInt64Side::Left => {
4949                                        if start != UNMATCHED {
4950                                            slice[cursor..cursor + run_len].copy_from_slice(
4951                                                &tape
4952                                                    .as_ref()
4953                                                    .expect("left spec must have a bucket tape")
4954                                                    [start..start + run_len],
4955                                            );
4956                                        }
4957                                    }
4958                                }
4959                            }
4960                            cursor += run_len;
4961                        }
4962                        debug_assert_eq!(cursor, out_end - out_start);
4963                    }));
4964                }
4965                for handle in handles {
4966                    handle
4967                        .join()
4968                        .expect("dense i64 right output worker must not panic");
4969                }
4970            });
4971            full_data = column_bufs;
4972        } else {
4973            full_data = full_specs.iter().map(|_| vec![0i64; output_len]).collect();
4974            let mut cursor = 0usize;
4975            for &(right_pos, start, run_len) in &plan {
4976                for (buf, (&spec_idx, tape)) in full_data
4977                    .iter_mut()
4978                    .zip(full_specs.iter().zip(tapes.iter()))
4979                {
4980                    match specs[spec_idx].side {
4981                        FusedInt64Side::Right => {
4982                            buf[cursor..cursor + run_len].fill(specs[spec_idx].values[right_pos]);
4983                        }
4984                        FusedInt64Side::Left => {
4985                            if start != UNMATCHED {
4986                                buf[cursor..cursor + run_len].copy_from_slice(
4987                                    &tape.as_ref().expect("left spec must have a bucket tape")
4988                                        [start..start + run_len],
4989                                );
4990                            }
4991                        }
4992                    }
4993                }
4994                cursor += run_len;
4995            }
4996            debug_assert_eq!(cursor, output_len);
4997        }
4998    }
4999
5000    // Lazy unit-range output index (see build_single_key_dense_i64 site).
5001    let index = Index::new_known_unique_int64_unit_range(0, output_len);
5002    let mut columns = ColumnStore::new();
5003    let mut column_order = Vec::with_capacity(specs.len());
5004    let mut full_iter = full_data.into_iter();
5005    for spec in specs {
5006        let column = match spec.side {
5007            FusedInt64Side::Left => {
5008                // Lazy nullable repeated-slices over the left bucket-order tape
5009                // (br-frankenpandas-yiqv5). When no left row is missing the
5010                // segments carry no `usize::MAX` sentinel, so the ctor yields an
5011                // all-valid mask — identical to the prior `from_i64_values`.
5012                let tape: Vec<i64> = positions
5013                    .iter()
5014                    .map(|&left_pos| spec.values[left_pos])
5015                    .collect();
5016                Column::from_i64_nullable_repeated_slices_shared(
5017                    tape,
5018                    Arc::clone(&left_segments),
5019                    output_len,
5020                )
5021            }
5022            FusedInt64Side::Right if use_repeat_runs => Column::from_i64_repeat_runs(
5023                plan.iter()
5024                    .map(|&(right_pos, _, run_len)| (spec.values[right_pos], run_len))
5025                    .collect(),
5026            ),
5027            FusedInt64Side::Right => {
5028                let data = full_iter
5029                    .next()
5030                    .expect("full lane buffer must exist for every non-run right spec");
5031                Column::from_i64_values(data)
5032            }
5033        };
5034        debug_assert_eq!(column.len(), output_len);
5035        insert_merged_output_column(&mut columns, &mut column_order, spec.name, column)?;
5036    }
5037
5038    Ok(Some(MergedDataFrame {
5039        index,
5040        columns,
5041        column_order,
5042    }))
5043}
5044
5045fn dense_cycle_domain(witness: Int64DenseCycleWitness) -> Option<(i64, i64)> {
5046    let last_offset = i64::try_from(witness.period.checked_sub(1)?).ok()?;
5047    Some((witness.start, witness.start.checked_add(last_offset)?))
5048}
5049
5050fn dense_cycle_probe_output_len_and_validity(
5051    probe_witness: Int64DenseCycleWitness,
5052    build_witness: Int64DenseCycleWitness,
5053) -> Option<(usize, ValidityMask)> {
5054    let mut output_len = 0usize;
5055    let mut invalid_ranges = Vec::<(usize, usize)>::new();
5056    for probe_pos in 0..probe_witness.len {
5057        let offset = i64::try_from(probe_pos % probe_witness.period).ok()?;
5058        let key = probe_witness.start.checked_add(offset)?;
5059        let run_len = build_witness
5060            .offset_count_for_key(key)
5061            .map_or(1, |(_, count)| count);
5062        if build_witness.offset_count_for_key(key).is_none() {
5063            push_dense_outer_invalid_range(&mut invalid_ranges, output_len, 1);
5064        }
5065        output_len = output_len.checked_add(run_len)?;
5066    }
5067    Some((
5068        output_len,
5069        ValidityMask::from_invalid_ranges(Arc::from(invalid_ranges), output_len),
5070    ))
5071}
5072
5073struct DenseOuterRunTape {
5074    run_lens: Option<Arc<[usize]>>,
5075    left_run_valid: Option<Arc<[bool]>>,
5076    left_run_positions: Option<Arc<[usize]>>,
5077    right_positions_csr: Option<Arc<[usize]>>,
5078    right_segments: Option<Arc<[(usize, usize)]>>,
5079    key_runs: Vec<(i64, usize)>,
5080    left_sparse_validity: ValidityMask,
5081    right_sparse_validity: ValidityMask,
5082    output_len: usize,
5083    has_left_missing: bool,
5084    has_right_missing: bool,
5085}
5086
5087fn push_dense_outer_invalid_range(ranges: &mut Vec<(usize, usize)>, start: usize, len: usize) {
5088    if len == 0 {
5089        return;
5090    }
5091    if let Some((last_start, last_len)) = ranges.last_mut()
5092        && last_start.checked_add(*last_len) == Some(start)
5093    {
5094        *last_len += len;
5095        return;
5096    }
5097    ranges.push((start, len));
5098}
5099
5100fn append_dense_cycle_positions(
5101    positions: &mut Vec<usize>,
5102    witness: Int64DenseCycleWitness,
5103    key: i64,
5104) -> Option<usize> {
5105    let (mut pos, count) = witness.offset_count_for_key(key)?;
5106    for _ in 0..count {
5107        positions.push(pos);
5108        pos = pos.checked_add(witness.period)?;
5109    }
5110    Some(count)
5111}
5112
5113fn build_dense_cycle_outer_run_tape(
5114    left_witness: Int64DenseCycleWitness,
5115    right_witness: Int64DenseCycleWitness,
5116    min_key: i64,
5117    span: usize,
5118) -> Option<DenseOuterRunTape> {
5119    let mut run_count = 0usize;
5120    let mut active_key_count = 0usize;
5121    let mut output_len = 0usize;
5122    let mut has_left_missing = false;
5123    let mut has_right_missing = false;
5124    for bucket in 0..span {
5125        let key = min_key.checked_add(i64::try_from(bucket).ok()?)?;
5126        let ll = left_witness
5127            .offset_count_for_key(key)
5128            .map_or(0, |(_, count)| count);
5129        let rl = right_witness
5130            .offset_count_for_key(key)
5131            .map_or(0, |(_, count)| count);
5132        let rows = match (ll > 0, rl > 0) {
5133            (true, true) => {
5134                run_count = run_count.checked_add(ll)?;
5135                ll.checked_mul(rl)?
5136            }
5137            (true, false) => {
5138                has_right_missing = true;
5139                run_count = run_count.checked_add(ll)?;
5140                ll
5141            }
5142            (false, true) => {
5143                has_left_missing = true;
5144                run_count = run_count.checked_add(1)?;
5145                rl
5146            }
5147            (false, false) => continue,
5148        };
5149        active_key_count = active_key_count.checked_add(1)?;
5150        output_len = output_len.checked_add(rows)?;
5151    }
5152
5153    let build_left_tape = !has_left_missing;
5154    let mut run_lens = Vec::with_capacity(if build_left_tape { run_count } else { 0 });
5155    let mut left_run_valid = Vec::with_capacity(if build_left_tape { run_count } else { 0 });
5156    let mut left_run_positions = Vec::with_capacity(if build_left_tape { run_count } else { 0 });
5157    let mut right_positions_csr = Vec::with_capacity(right_witness.len);
5158    let mut right_segments = Vec::with_capacity(run_count);
5159    let mut key_runs = Vec::with_capacity(active_key_count);
5160    let mut left_invalid_ranges = Vec::<(usize, usize)>::new();
5161    let mut right_invalid_ranges = Vec::<(usize, usize)>::new();
5162    let mut out_pos = 0usize;
5163    let build_right_tape = !has_right_missing;
5164    for bucket in 0..span {
5165        let key = min_key.checked_add(i64::try_from(bucket).ok()?)?;
5166        let left_span = left_witness.offset_count_for_key(key);
5167        let right_span = right_witness.offset_count_for_key(key);
5168        let ll = left_span.map_or(0, |(_, count)| count);
5169        let rl = right_span.map_or(0, |(_, count)| count);
5170        if ll == 0 && rl == 0 {
5171            continue;
5172        }
5173
5174        let right_start = if rl > 0 {
5175            if build_right_tape {
5176                let start = right_positions_csr.len();
5177                let appended =
5178                    append_dense_cycle_positions(&mut right_positions_csr, right_witness, key)?;
5179                debug_assert_eq!(appended, rl);
5180                start
5181            } else {
5182                0
5183            }
5184        } else {
5185            usize::MAX
5186        };
5187
5188        let rows = match (left_span, right_span) {
5189            (Some((mut left_pos, left_count)), Some((_, right_count))) => {
5190                let rows = left_count.checked_mul(right_count)?;
5191                if build_left_tape {
5192                    run_lens.extend(std::iter::repeat_n(right_count, left_count));
5193                    left_run_valid.extend(std::iter::repeat_n(true, left_count));
5194                }
5195                if build_right_tape {
5196                    right_segments
5197                        .extend(std::iter::repeat_n((right_start, right_count), left_count));
5198                }
5199                if build_left_tape {
5200                    for _ in 0..left_count {
5201                        left_run_positions.push(left_pos);
5202                        left_pos = left_pos.checked_add(left_witness.period)?;
5203                    }
5204                }
5205                rows
5206            }
5207            (Some((mut left_pos, left_count)), None) => {
5208                push_dense_outer_invalid_range(&mut right_invalid_ranges, out_pos, left_count);
5209                if build_left_tape {
5210                    run_lens.extend(std::iter::repeat_n(1, left_count));
5211                    left_run_valid.extend(std::iter::repeat_n(true, left_count));
5212                }
5213                if build_right_tape {
5214                    right_segments.extend(std::iter::repeat_n((usize::MAX, 1), left_count));
5215                }
5216                if build_left_tape {
5217                    for _ in 0..left_count {
5218                        left_run_positions.push(left_pos);
5219                        left_pos = left_pos.checked_add(left_witness.period)?;
5220                    }
5221                }
5222                left_count
5223            }
5224            (None, Some((_, right_count))) => {
5225                push_dense_outer_invalid_range(&mut left_invalid_ranges, out_pos, right_count);
5226                if build_left_tape {
5227                    run_lens.push(right_count);
5228                    left_run_valid.push(false);
5229                    left_run_positions.push(0);
5230                }
5231                if build_right_tape {
5232                    right_segments.push((right_start, right_count));
5233                }
5234                right_count
5235            }
5236            (None, None) => unreachable!("empty buckets are skipped above"),
5237        };
5238        key_runs.push((key, rows));
5239        out_pos = out_pos.checked_add(rows)?;
5240    }
5241    if out_pos != output_len
5242        || (build_left_tape
5243            && (run_lens.len() != run_count
5244                || left_run_valid.len() != run_count
5245                || left_run_positions.len() != run_count))
5246        || (!build_left_tape
5247            && (!run_lens.is_empty()
5248                || !left_run_valid.is_empty()
5249                || !left_run_positions.is_empty()))
5250        || (build_right_tape
5251            && (right_segments.len() != run_count
5252                || right_positions_csr.len() != right_witness.len))
5253        || (!build_right_tape && (!right_segments.is_empty() || !right_positions_csr.is_empty()))
5254    {
5255        return None;
5256    }
5257
5258    Some(DenseOuterRunTape {
5259        run_lens: build_left_tape.then(|| Arc::from(run_lens)),
5260        left_run_valid: build_left_tape.then(|| Arc::from(left_run_valid)),
5261        left_run_positions: build_left_tape.then(|| Arc::from(left_run_positions)),
5262        right_positions_csr: build_right_tape.then(|| Arc::from(right_positions_csr)),
5263        right_segments: build_right_tape.then(|| Arc::from(right_segments)),
5264        key_runs,
5265        left_sparse_validity: ValidityMask::from_invalid_ranges(
5266            Arc::from(left_invalid_ranges),
5267            output_len,
5268        ),
5269        right_sparse_validity: ValidityMask::from_invalid_ranges(
5270            Arc::from(right_invalid_ranges),
5271            output_len,
5272        ),
5273        output_len,
5274        has_left_missing,
5275        has_right_missing,
5276    })
5277}
5278
5279/// Fused dense-i64 OUTER merge builder (br-frankenpandas-343ho).
5280///
5281/// `dense_int64_outer_positions` + the position-vector outer builder cost:
5282/// per-bucket `Vec<Vec<usize>>` heap allocs, two `Vec<Option<usize>>` of
5283/// output length, a per-row Scalar coalesce for the shared key column, and
5284/// per-column reindex walks. Here the bucket walk (ascending key order —
5285/// the dense outer output IS bucket order) emits a compact plan
5286/// (`(left_pos | MAX, right_bucket_start | MAX, run_len)`), and:
5287///
5288/// - the SHARED KEY lane is synthesized as `(min_key + bucket, bucket_rows)`
5289///   repeat runs — every row in a bucket has the bucket's key, whichever
5290///   side it came from, so the coalesce is a closed form (all-valid Int64);
5291/// - left lanes promote to nullable Float64 ONLY when right-only buckets
5292///   exist, right lanes ONLY when left-only rows exist — matching
5293///   `reindex_join_column_with_invented_gap`'s per-positions `has_missing` check (a
5294///   side with no missing rows keeps dtype Int64 via the all-present
5295///   take_positions path);
5296/// - per-side shared validity masks are word-filled once from the plan and
5297///   cloned per lane;
5298/// - lanes fill via the 6bsw3 row-chunked disjoint `split_at_mut` scheme
5299///   (an i64 group and an f64 group, sharing plan/boundaries), with muis1
5300///   right value tapes (i64, plus a once-cast f64 tape for promoted lanes).
5301///
5302/// Bit-identical: bucket walk order == `dense_int64_outer_positions`
5303/// (cross products left-major, then left-only rows, then right-only rows,
5304/// per ascending bucket); promoted slots use `v as f64` + the 0.0-datum
5305/// gap (`Null(NaN)`), preserved slots `Null(NullKind::Null)` — the exact
5306/// eager semantics per br-frankenpandas-1bvcl/lt5qx.
5307fn build_single_key_dense_i64_outer_merge_output(
5308    left: &fp_frame::DataFrame,
5309    right: &fp_frame::DataFrame,
5310    left_on: &[&str],
5311    right_on: &[&str],
5312    left_key: &Column,
5313    right_key: &Column,
5314    suffixes: &ResolvedMergeSuffixes,
5315) -> Result<Option<MergedDataFrame>, JoinError> {
5316    debug_assert_eq!(left_on.len(), 1);
5317    debug_assert_eq!(right_on.len(), 1);
5318
5319    // The closed-form key lane needs the coalesced shared-key shape; the
5320    // non-shared-name variant keeps the position-vector path.
5321    if left_on[0] != right_on[0] {
5322        return Ok(None);
5323    }
5324    let Some(left_keys) = left_key.as_i64_slice() else {
5325        return Ok(None);
5326    };
5327    let Some(right_keys) = right_key.as_i64_slice() else {
5328        return Ok(None);
5329    };
5330    if left_keys.is_empty() || right_keys.is_empty() {
5331        return Ok(None);
5332    }
5333
5334    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
5335    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
5336    let key_name = left_on[0];
5337    let shared_key_names = [key_name].into_iter().collect::<HashSet<&str>>();
5338    let overlapping_names =
5339        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
5340
5341    // Lane specs in output order: left columns (the key slot handled as the
5342    // synthetic coalesced lane), then right non-key columns.
5343    enum OuterLaneKind {
5344        SharedKey,
5345        Lane(FusedInt64Side),
5346    }
5347    let mut spec_names = Vec::<String>::new();
5348    let mut spec_kinds = Vec::<OuterLaneKind>::new();
5349    let mut spec_values = Vec::<&[i64]>::new();
5350    let mut spec_sources = Vec::<Arc<[i64]>>::new();
5351    for name in left.column_names() {
5352        let col = left
5353            .columns()
5354            .get(name)
5355            .expect("left column listed in column_names must exist");
5356        let Some(values) = col.as_i64_slice() else {
5357            return Ok(None);
5358        };
5359        let source = col.as_i64_arc().unwrap_or_else(|| Arc::from(values));
5360        if name.as_str() == key_name {
5361            spec_names.push(name.clone());
5362            spec_kinds.push(OuterLaneKind::SharedKey);
5363            spec_values.push(values);
5364            spec_sources.push(Arc::clone(&source));
5365            continue;
5366        }
5367        let out_name = if right_col_names.contains(name) {
5368            apply_merge_suffix(name, suffixes.left.as_deref())
5369        } else {
5370            name.clone()
5371        };
5372        spec_names.push(out_name);
5373        spec_kinds.push(OuterLaneKind::Lane(FusedInt64Side::Left));
5374        spec_values.push(values);
5375        spec_sources.push(source);
5376    }
5377    for name in right.column_names() {
5378        let col = right
5379            .columns()
5380            .get(name)
5381            .expect("right column listed in column_names must exist");
5382        let Some(values) = col.as_i64_slice() else {
5383            return Ok(None);
5384        };
5385        let source = col.as_i64_arc().unwrap_or_else(|| Arc::from(values));
5386        if name.as_str() == key_name {
5387            continue;
5388        }
5389        let out_name = if left_col_names.contains(name) {
5390            apply_merge_suffix(name, suffixes.right.as_deref())
5391        } else {
5392            name.clone()
5393        };
5394        spec_names.push(out_name);
5395        spec_kinds.push(OuterLaneKind::Lane(FusedInt64Side::Right));
5396        spec_values.push(values);
5397        spec_sources.push(source);
5398    }
5399    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
5400
5401    // Dense span over BOTH key sets (same gate as dense_int64_outer_positions
5402    // so fused/fallback routing matches).
5403    let left_witness = left_key
5404        .int64_dense_cycle_witness()
5405        .filter(|witness| witness.len == left_keys.len());
5406    let right_witness = right_key
5407        .int64_dense_cycle_witness()
5408        .filter(|witness| witness.len == right_keys.len());
5409    let (min_key, max_key) = match (
5410        left_witness.and_then(dense_cycle_domain),
5411        right_witness.and_then(dense_cycle_domain),
5412    ) {
5413        (Some((left_min, left_max)), Some((right_min, right_max))) => {
5414            (left_min.min(right_min), left_max.max(right_max))
5415        }
5416        _ => {
5417            let mut min_key = left_keys[0];
5418            let mut max_key = left_keys[0];
5419            for &key in left_keys.iter().chain(right_keys.iter()) {
5420                min_key = min_key.min(key);
5421                max_key = max_key.max(key);
5422            }
5423            (min_key, max_key)
5424        }
5425    };
5426    let span = (i128::from(max_key)) - (i128::from(min_key)) + 1;
5427    let row_count = left_keys.len().saturating_add(right_keys.len());
5428    let max_dense_span = row_count.saturating_mul(4).max(1024);
5429    if span > max_dense_span as i128 {
5430        return Ok(None);
5431    }
5432    let span = usize::try_from(span).expect("span bounded by max_dense_span");
5433
5434    const NONE_POS: usize = usize::MAX;
5435    let Some(DenseOuterRunTape {
5436        run_lens,
5437        left_run_valid,
5438        left_run_positions,
5439        right_positions_csr,
5440        right_segments,
5441        key_runs,
5442        left_sparse_validity,
5443        right_sparse_validity,
5444        output_len,
5445        has_left_missing,
5446        has_right_missing,
5447    }) = (match (left_witness, right_witness) {
5448        (Some(left_witness), Some(right_witness)) => {
5449            build_dense_cycle_outer_run_tape(left_witness, right_witness, min_key, span)
5450        }
5451        _ => None,
5452    })
5453    .or_else(|| {
5454        // CSR layouts for both sides (replaces the per-bucket Vec<Vec<usize>>).
5455        let build_dense_cycle_csr =
5456            |witness: Int64DenseCycleWitness| -> Option<(Vec<usize>, Vec<usize>)> {
5457                let mut offsets = Vec::with_capacity(span + 1);
5458                offsets.push(0);
5459                let mut total = 0usize;
5460                for bucket in 0..span {
5461                    let key = min_key.checked_add(i64::try_from(bucket).ok()?)?;
5462                    let count = witness
5463                        .offset_count_for_key(key)
5464                        .map_or(0, |(_, count)| count);
5465                    total = total.checked_add(count)?;
5466                    offsets.push(total);
5467                }
5468                if total != witness.len {
5469                    return None;
5470                }
5471                let mut positions = Vec::with_capacity(witness.len);
5472                for bucket in 0..span {
5473                    let key = min_key.checked_add(i64::try_from(bucket).ok()?)?;
5474                    let appended =
5475                        append_dense_cycle_positions(&mut positions, witness, key).unwrap_or(0);
5476                    debug_assert_eq!(
5477                        appended,
5478                        witness
5479                            .offset_count_for_key(key)
5480                            .map_or(0, |(_, count)| count)
5481                    );
5482                }
5483                (positions.len() == witness.len).then_some((offsets, positions))
5484            };
5485        let build_csr = |keys: &[i64], witness: Option<Int64DenseCycleWitness>| {
5486            if let Some(csr) = witness
5487                .filter(|witness| witness.len == keys.len())
5488                .and_then(&build_dense_cycle_csr)
5489            {
5490                return csr;
5491            }
5492            let mut offsets = vec![0usize; span + 1];
5493            for &key in keys {
5494                offsets[(key - min_key) as usize + 1] += 1;
5495            }
5496            for i in 0..span {
5497                offsets[i + 1] += offsets[i];
5498            }
5499            let mut positions = vec![0usize; keys.len()];
5500            let mut cursor = offsets[..span].to_vec();
5501            for (pos, &key) in keys.iter().enumerate() {
5502                let bucket = (key - min_key) as usize;
5503                positions[cursor[bucket]] = pos;
5504                cursor[bucket] += 1;
5505            }
5506            (offsets, positions)
5507        };
5508        let (left_offsets, left_positions_csr) = build_csr(left_keys, left_witness);
5509        let (right_offsets, right_positions_csr) = build_csr(right_keys, right_witness);
5510
5511        // Bucket walk -> compact plan + closed-form key runs + output length.
5512        let mut plan = Vec::<(usize, usize, usize)>::new();
5513        let mut key_runs = Vec::<(i64, usize)>::new();
5514        let mut left_invalid_ranges = Vec::<(usize, usize)>::new();
5515        let mut right_invalid_ranges = Vec::<(usize, usize)>::new();
5516        let mut output_len = 0usize;
5517        let mut has_left_missing = false; // right-only buckets exist
5518        let mut has_right_missing = false; // left-only rows exist
5519        for bucket in 0..span {
5520            let ll = left_offsets[bucket + 1] - left_offsets[bucket];
5521            let rl = right_offsets[bucket + 1] - right_offsets[bucket];
5522            let bucket_rows = match (ll > 0, rl > 0) {
5523                (true, true) => {
5524                    let rows = ll.checked_mul(rl)?;
5525                    let rs = right_offsets[bucket];
5526                    for &lp in &left_positions_csr[left_offsets[bucket]..left_offsets[bucket + 1]] {
5527                        plan.push((lp, rs, rl));
5528                    }
5529                    rows
5530                }
5531                (true, false) => {
5532                    has_right_missing = true;
5533                    push_dense_outer_invalid_range(&mut right_invalid_ranges, output_len, ll);
5534                    for &lp in &left_positions_csr[left_offsets[bucket]..left_offsets[bucket + 1]] {
5535                        plan.push((lp, NONE_POS, 1));
5536                    }
5537                    ll
5538                }
5539                (false, true) => {
5540                    has_left_missing = true;
5541                    push_dense_outer_invalid_range(&mut left_invalid_ranges, output_len, rl);
5542                    plan.push((NONE_POS, right_offsets[bucket], rl));
5543                    rl
5544                }
5545                (false, false) => continue,
5546            };
5547            output_len = output_len.checked_add(bucket_rows)?;
5548            key_runs.push((min_key + bucket as i64, bucket_rows));
5549        }
5550
5551        // Shared lazy-lane descriptors (br-frankenpandas-yiqv5): the plan drives
5552        // every value lane as a LAZY column rather than an O(output_len)
5553        // materialized buffer. The kept side stays all-valid; the promoted
5554        // side becomes the matching nullable lazy lane.
5555        let run_lens: Arc<[usize]> = plan.iter().map(|&(_, _, run_len)| run_len).collect();
5556        let left_run_valid: Arc<[bool]> = plan.iter().map(|&(lp, _, _)| lp < NONE_POS).collect();
5557        let left_run_positions: Arc<[usize]> = plan
5558            .iter()
5559            .map(|&(lp, _, _)| if lp == NONE_POS { 0 } else { lp })
5560            .collect();
5561        let right_segments: Arc<[(usize, usize)]> =
5562            plan.iter().map(|&(_, rs, run_len)| (rs, run_len)).collect();
5563        Some(DenseOuterRunTape {
5564            run_lens: Some(run_lens),
5565            left_run_valid: Some(left_run_valid),
5566            left_run_positions: Some(left_run_positions),
5567            right_positions_csr: Some(Arc::from(right_positions_csr)),
5568            right_segments: Some(right_segments),
5569            key_runs,
5570            left_sparse_validity: ValidityMask::from_invalid_ranges(
5571                Arc::from(left_invalid_ranges),
5572                output_len,
5573            ),
5574            right_sparse_validity: ValidityMask::from_invalid_ranges(
5575                Arc::from(right_invalid_ranges),
5576                output_len,
5577            ),
5578            output_len,
5579            has_left_missing,
5580            has_right_missing,
5581        })
5582    })
5583    else {
5584        return Ok(None);
5585    };
5586
5587    // Promoted (nullable Float64) when that side has missing rows, preserved
5588    // (all-valid Int64) otherwise.
5589    let promoted = |side: FusedInt64Side| match side {
5590        FusedInt64Side::Left => has_left_missing,
5591        FusedInt64Side::Right => has_right_missing,
5592    };
5593
5594    // Left broadcast run values (one per run): i64 (preserved) or f64 (promoted).
5595    let left_run_values_i64 = |idx: usize| -> Option<Vec<i64>> {
5596        Some(
5597            left_run_positions
5598                .as_ref()?
5599                .iter()
5600                .zip(left_run_valid.as_ref()?.iter())
5601                .map(|(&lp, &valid)| if valid { spec_values[idx][lp] } else { 0 })
5602                .collect(),
5603        )
5604    };
5605    // Assemble columns in spec order, each a lazy lane.
5606    let index = Index::new_known_unique_int64_unit_range(0, output_len);
5607    let mut columns = ColumnStore::new();
5608    let mut column_order = Vec::with_capacity(spec_names.len());
5609    for (idx, (name, kind)) in spec_names.into_iter().zip(spec_kinds.iter()).enumerate() {
5610        let column = match kind {
5611            OuterLaneKind::SharedKey => {
5612                // Closed-form coalesced key: all-valid, bucket key repeated in
5613                // ascending bucket order. Lazy repeat-runs when the fanout pays.
5614                if output_len >= key_runs.len().saturating_mul(2) {
5615                    Column::from_i64_repeat_runs(key_runs.clone())
5616                } else {
5617                    let mut data = Vec::with_capacity(output_len);
5618                    for &(key, run_len) in &key_runs {
5619                        data.resize(data.len() + run_len, key);
5620                    }
5621                    Column::from_i64_values(data)
5622                }
5623            }
5624            OuterLaneKind::Lane(side) => match (side, promoted(*side)) {
5625                (FusedInt64Side::Left, false) => {
5626                    let Some(run_lens) = run_lens.as_ref() else {
5627                        return Ok(None);
5628                    };
5629                    let Some(run_values) = left_run_values_i64(idx) else {
5630                        return Ok(None);
5631                    };
5632                    Column::from_i64_repeat_values_run_lengths(run_values, Arc::clone(run_lens))
5633                }
5634                (FusedInt64Side::Left, true) => {
5635                    if left_run_positions.is_none()
5636                        && let (Some(left_witness), Some(right_witness)) =
5637                            (left_witness, right_witness)
5638                    {
5639                        Column::from_i64_nullable_dense_cycle_left_as_f64_with_sparse_validity(
5640                            Arc::clone(&spec_sources[idx]),
5641                            left_witness,
5642                            right_witness,
5643                            min_key,
5644                            span,
5645                            left_sparse_validity.clone(),
5646                            output_len,
5647                        )
5648                    } else {
5649                        let Some(run_lens) = run_lens.as_ref() else {
5650                            return Ok(None);
5651                        };
5652                        let Some(left_run_positions) = left_run_positions.as_ref() else {
5653                            return Ok(None);
5654                        };
5655                        let Some(left_run_valid) = left_run_valid.as_ref() else {
5656                            return Ok(None);
5657                        };
5658                        Column::from_i64_nullable_repeat_positions_as_f64_with_sparse_validity(
5659                            Arc::clone(&spec_sources[idx]),
5660                            Arc::clone(left_run_positions),
5661                            Arc::clone(left_run_valid),
5662                            Arc::clone(run_lens),
5663                            left_sparse_validity.clone(),
5664                            output_len,
5665                        )
5666                    }
5667                }
5668                (FusedInt64Side::Right, false) => {
5669                    let Some(right_positions_csr) = right_positions_csr.as_ref() else {
5670                        return Ok(None);
5671                    };
5672                    let Some(right_segments) = right_segments.as_ref() else {
5673                        return Ok(None);
5674                    };
5675                    let tape_i64 = right_positions_csr
5676                        .iter()
5677                        .map(|&pos| spec_values[idx][pos])
5678                        .collect();
5679                    Column::from_i64_repeated_slices_shared(
5680                        tape_i64,
5681                        Arc::clone(right_segments),
5682                        output_len,
5683                    )
5684                }
5685                (FusedInt64Side::Right, true) => {
5686                    if right_positions_csr.is_none()
5687                        && let (Some(left_witness), Some(right_witness)) =
5688                            (left_witness, right_witness)
5689                    {
5690                        Column::from_i64_nullable_dense_cycle_right_as_f64_with_sparse_validity(
5691                            Arc::clone(&spec_sources[idx]),
5692                            left_witness,
5693                            right_witness,
5694                            min_key,
5695                            span,
5696                            right_sparse_validity.clone(),
5697                            output_len,
5698                        )
5699                    } else {
5700                        let Some(right_positions_csr) = right_positions_csr.as_ref() else {
5701                            return Ok(None);
5702                        };
5703                        let Some(right_segments) = right_segments.as_ref() else {
5704                            return Ok(None);
5705                        };
5706                        Column::from_i64_nullable_repeated_positions_as_f64_with_sparse_validity(
5707                            Arc::clone(&spec_sources[idx]),
5708                            Arc::clone(right_positions_csr),
5709                            Arc::clone(right_segments),
5710                            right_sparse_validity.clone(),
5711                            output_len,
5712                        )
5713                    }
5714                }
5715            },
5716        };
5717        debug_assert_eq!(column.len(), output_len);
5718        insert_merged_output_column(&mut columns, &mut column_order, name, column)?;
5719    }
5720
5721    Ok(Some(MergedDataFrame {
5722        index,
5723        columns,
5724        column_order,
5725    }))
5726}
5727
5728fn build_single_key_dense_i64_right_all_matched_merge_output(
5729    left: &fp_frame::DataFrame,
5730    right: &fp_frame::DataFrame,
5731    left_on: &[&str],
5732    right_on: &[&str],
5733    left_key: &Column,
5734    right_key: &Column,
5735    suffixes: &ResolvedMergeSuffixes,
5736) -> Result<Option<MergedDataFrame>, JoinError> {
5737    debug_assert_eq!(left_on.len(), 1);
5738    debug_assert_eq!(right_on.len(), 1);
5739
5740    let Some(left_keys) = left_key.as_i64_slice() else {
5741        return Ok(None);
5742    };
5743    let Some(right_keys) = right_key.as_i64_slice() else {
5744        return Ok(None);
5745    };
5746
5747    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
5748    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
5749    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
5750    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
5751    let shared_key_names = if left_on[0] == right_on[0] {
5752        [left_on[0]].into_iter().collect::<HashSet<&str>>()
5753    } else {
5754        HashSet::new()
5755    };
5756    let overlapping_names =
5757        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
5758
5759    let mut specs = Vec::<FusedInt64OutputColumn<'_>>::new();
5760    for name in left.column_names() {
5761        let col = left
5762            .columns()
5763            .get(name)
5764            .expect("left column listed in column_names must exist");
5765        let (values, side) = if left_key_name_set.contains(name.as_str())
5766            && shared_key_names.contains(name.as_str())
5767        {
5768            let right_key_col = right
5769                .columns()
5770                .get(right_on[0])
5771                .expect("right key column must exist");
5772            let Some(values) = right_key_col.as_i64_slice() else {
5773                return Ok(None);
5774            };
5775            (values, FusedInt64Side::Right)
5776        } else {
5777            let Some(values) = col.as_i64_slice() else {
5778                return Ok(None);
5779            };
5780            (values, FusedInt64Side::Left)
5781        };
5782        let out_name = if left_key_name_set.contains(name.as_str()) {
5783            name.clone()
5784        } else if right_col_names.contains(name) {
5785            apply_merge_suffix(name, suffixes.left.as_deref())
5786        } else {
5787            name.clone()
5788        };
5789        specs.push(FusedInt64OutputColumn {
5790            name: out_name,
5791            side,
5792            values,
5793        });
5794    }
5795
5796    for name in right.column_names() {
5797        let col = right
5798            .columns()
5799            .get(name)
5800            .expect("right column listed in column_names must exist");
5801        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
5802            continue;
5803        }
5804        let Some(values) = col.as_i64_slice() else {
5805            return Ok(None);
5806        };
5807        let out_name = if left_col_names.contains(name) {
5808            apply_merge_suffix(name, suffixes.right.as_deref())
5809        } else {
5810            name.clone()
5811        };
5812        specs.push(FusedInt64OutputColumn {
5813            name: out_name,
5814            side: FusedInt64Side::Right,
5815            values,
5816        });
5817    }
5818
5819    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
5820
5821    if right_keys.is_empty() {
5822        let mut columns = ColumnStore::new();
5823        let mut column_order = Vec::with_capacity(specs.len());
5824        for spec in specs {
5825            insert_merged_output_column(
5826                &mut columns,
5827                &mut column_order,
5828                spec.name,
5829                Column::from_i64_values(Vec::new()),
5830            )?;
5831        }
5832        return Ok(Some(MergedDataFrame {
5833            index: Index::new(Vec::new()),
5834            columns,
5835            column_order,
5836        }));
5837    }
5838    if left_keys.is_empty() {
5839        return Ok(None);
5840    }
5841
5842    let mut min = left_keys[0];
5843    let mut max = left_keys[0];
5844    for &v in left_keys {
5845        if v < min {
5846            min = v;
5847        }
5848        if v > max {
5849            max = v;
5850        }
5851    }
5852    let span = (max as i128) - (min as i128) + 1;
5853    if span > (1i128 << 24) || span > 16 * (left_keys.len() as i128) {
5854        return Ok(None);
5855    }
5856    let range = span as usize;
5857
5858    let mut offsets = vec![0usize; range + 1];
5859    for &v in left_keys {
5860        offsets[(v - min) as usize + 1] += 1;
5861    }
5862    for i in 0..range {
5863        offsets[i + 1] += offsets[i];
5864    }
5865    let mut positions = vec![0usize; left_keys.len()];
5866    let mut cursor = offsets.clone();
5867    for (pos, &v) in left_keys.iter().enumerate() {
5868        let bucket = (v - min) as usize;
5869        positions[cursor[bucket]] = pos;
5870        cursor[bucket] += 1;
5871    }
5872
5873    let mut output_len = 0usize;
5874    for &v in right_keys {
5875        if v < min || v > max {
5876            return Ok(None);
5877        }
5878        let bucket = (v - min) as usize;
5879        let bucket_len = offsets[bucket + 1] - offsets[bucket];
5880        if bucket_len == 0 {
5881            return Ok(None);
5882        }
5883        let Some(new_output_len) = output_len.checked_add(bucket_len) else {
5884            return Ok(None);
5885        };
5886        output_len = new_output_len;
5887    }
5888
5889    let mut output_data = specs
5890        .iter()
5891        .map(|_| Vec::<i64>::with_capacity(output_len))
5892        .collect::<Vec<_>>();
5893    for (right_pos, &v) in right_keys.iter().enumerate() {
5894        let bucket = (v - min) as usize;
5895        for &left_pos in &positions[offsets[bucket]..offsets[bucket + 1]] {
5896            for (out, spec) in output_data.iter_mut().zip(specs.iter()) {
5897                match spec.side {
5898                    FusedInt64Side::Left => out.push(spec.values[left_pos]),
5899                    FusedInt64Side::Right => out.push(spec.values[right_pos]),
5900                }
5901            }
5902        }
5903    }
5904
5905    // Lazy unit-range output index: identical labels (0..output_len as
5906    // IndexLabel::Int64, materialized on demand), pre-proven unique and
5907    // ascending — skips the eager Vec<IndexLabel> build for huge join outputs.
5908    let index = Index::new_known_unique_int64_unit_range(0, output_len);
5909    let mut columns = ColumnStore::new();
5910    let mut column_order = Vec::with_capacity(specs.len());
5911    for (spec, data) in specs.into_iter().zip(output_data) {
5912        debug_assert_eq!(data.len(), output_len);
5913        insert_merged_output_column(
5914            &mut columns,
5915            &mut column_order,
5916            spec.name,
5917            Column::from_i64_values(data),
5918        )?;
5919    }
5920
5921    Ok(Some(MergedDataFrame {
5922        index,
5923        columns,
5924        column_order,
5925    }))
5926}
5927
5928fn build_single_key_dense_i64_outer_all_matched_merge_output(
5929    left: &fp_frame::DataFrame,
5930    right: &fp_frame::DataFrame,
5931    left_on: &[&str],
5932    right_on: &[&str],
5933    left_key: &Column,
5934    right_key: &Column,
5935    suffixes: &ResolvedMergeSuffixes,
5936) -> Result<Option<MergedDataFrame>, JoinError> {
5937    debug_assert_eq!(left_on.len(), 1);
5938    debug_assert_eq!(right_on.len(), 1);
5939
5940    let Some(left_keys) = left_key.as_i64_slice() else {
5941        return Ok(None);
5942    };
5943    let Some(right_keys) = right_key.as_i64_slice() else {
5944        return Ok(None);
5945    };
5946
5947    if left_keys.is_empty() != right_keys.is_empty() {
5948        return Ok(None);
5949    }
5950    let dense_domain = if left_keys.is_empty() {
5951        None
5952    } else {
5953        let left_witness = left_key
5954            .int64_dense_cycle_witness()
5955            .filter(|witness| witness.len == left_keys.len());
5956        let right_witness = right_key
5957            .int64_dense_cycle_witness()
5958            .filter(|witness| witness.len == right_keys.len());
5959        match (
5960            left_witness.and_then(dense_cycle_domain),
5961            right_witness.and_then(dense_cycle_domain),
5962        ) {
5963            (Some(left_domain), Some(right_domain)) => {
5964                if left_domain != right_domain {
5965                    return Ok(None);
5966                }
5967                Some(left_domain)
5968            }
5969            _ => {
5970                let min_max = |keys: &[i64]| {
5971                    let mut min_key = keys[0];
5972                    let mut max_key = keys[0];
5973                    for &key in &keys[1..] {
5974                        min_key = min_key.min(key);
5975                        max_key = max_key.max(key);
5976                    }
5977                    (min_key, max_key)
5978                };
5979                let (left_min_key, left_max_key) = min_max(left_keys);
5980                let (right_min_key, right_max_key) = min_max(right_keys);
5981                if left_min_key != right_min_key || left_max_key != right_max_key {
5982                    return Ok(None);
5983                }
5984                Some((left_min_key, left_max_key))
5985            }
5986        }
5987    };
5988
5989    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
5990    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
5991    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
5992    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
5993    let shared_key_names = if left_on[0] == right_on[0] {
5994        [left_on[0]].into_iter().collect::<HashSet<&str>>()
5995    } else {
5996        HashSet::new()
5997    };
5998    let overlapping_names =
5999        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
6000
6001    let mut specs = Vec::<FusedInt64OutputColumn<'_>>::new();
6002    for name in left.column_names() {
6003        let col = left
6004            .columns()
6005            .get(name)
6006            .expect("left column listed in column_names must exist");
6007        let Some(values) = col.as_i64_slice() else {
6008            return Ok(None);
6009        };
6010        let out_name = if left_key_name_set.contains(name.as_str()) {
6011            name.clone()
6012        } else if right_col_names.contains(name) {
6013            apply_merge_suffix(name, suffixes.left.as_deref())
6014        } else {
6015            name.clone()
6016        };
6017        specs.push(FusedInt64OutputColumn {
6018            name: out_name,
6019            side: FusedInt64Side::Left,
6020            values,
6021        });
6022    }
6023
6024    for name in right.column_names() {
6025        let col = right
6026            .columns()
6027            .get(name)
6028            .expect("right column listed in column_names must exist");
6029        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
6030            continue;
6031        }
6032        let Some(values) = col.as_i64_slice() else {
6033            return Ok(None);
6034        };
6035        let out_name = if left_col_names.contains(name) {
6036            apply_merge_suffix(name, suffixes.right.as_deref())
6037        } else {
6038            name.clone()
6039        };
6040        specs.push(FusedInt64OutputColumn {
6041            name: out_name,
6042            side: FusedInt64Side::Right,
6043            values,
6044        });
6045    }
6046
6047    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
6048
6049    if left_keys.is_empty() || right_keys.is_empty() {
6050        if !left_keys.is_empty() || !right_keys.is_empty() {
6051            return Ok(None);
6052        }
6053        let mut columns = ColumnStore::new();
6054        let mut column_order = Vec::with_capacity(specs.len());
6055        for spec in specs {
6056            insert_merged_output_column(
6057                &mut columns,
6058                &mut column_order,
6059                spec.name,
6060                Column::from_i64_values(Vec::new()),
6061            )?;
6062        }
6063        return Ok(Some(MergedDataFrame {
6064            index: Index::new(Vec::new()),
6065            columns,
6066            column_order,
6067        }));
6068    }
6069
6070    let (min_key, max_key) = dense_domain.expect("empty dense outer case returned above");
6071
6072    let span = i128::from(max_key)
6073        .checked_sub(i128::from(min_key))
6074        .and_then(|span| span.checked_add(1));
6075    let Some(span) = span else {
6076        return Ok(None);
6077    };
6078    let row_count = left_keys.len().saturating_add(right_keys.len());
6079    let max_dense_span = row_count.saturating_mul(4).max(1024);
6080    if span > max_dense_span as i128 {
6081        return Ok(None);
6082    }
6083    let Ok(span) = usize::try_from(span) else {
6084        return Ok(None);
6085    };
6086
6087    let mut left_buckets = (0..span).map(|_| Vec::<usize>::new()).collect::<Vec<_>>();
6088    let mut right_buckets = (0..span).map(|_| Vec::<usize>::new()).collect::<Vec<_>>();
6089    for (pos, &key) in left_keys.iter().enumerate() {
6090        let Ok(bucket) = usize::try_from(i128::from(key) - i128::from(min_key)) else {
6091            return Ok(None);
6092        };
6093        left_buckets[bucket].push(pos);
6094    }
6095    for (pos, &key) in right_keys.iter().enumerate() {
6096        let Ok(bucket) = usize::try_from(i128::from(key) - i128::from(min_key)) else {
6097            return Ok(None);
6098        };
6099        right_buckets[bucket].push(pos);
6100    }
6101
6102    let mut output_len = 0usize;
6103    for (left_bucket, right_bucket) in left_buckets.iter().zip(right_buckets.iter()) {
6104        match (left_bucket.is_empty(), right_bucket.is_empty()) {
6105            (false, false) => {
6106                let Some(bucket_rows) = left_bucket.len().checked_mul(right_bucket.len()) else {
6107                    return Ok(None);
6108                };
6109                let Some(new_output_len) = output_len.checked_add(bucket_rows) else {
6110                    return Ok(None);
6111                };
6112                output_len = new_output_len;
6113            }
6114            (false, true) | (true, false) => return Ok(None),
6115            (true, true) => {}
6116        }
6117    }
6118
6119    // Lazy unit-range output index: identical labels (0..output_len as
6120    // IndexLabel::Int64, materialized on demand), pre-proven unique and
6121    // ascending — skips the eager Vec<IndexLabel> build for huge join outputs.
6122    let index = Index::new_known_unique_int64_unit_range(0, output_len);
6123    let mut columns = ColumnStore::new();
6124    let mut column_order = Vec::with_capacity(specs.len());
6125    for spec in specs {
6126        let FusedInt64OutputColumn { name, side, values } = spec;
6127        let mut data = Vec::<i64>::with_capacity(output_len);
6128        match side {
6129            FusedInt64Side::Left => {
6130                for (left_bucket, right_bucket) in left_buckets.iter().zip(right_buckets.iter()) {
6131                    if left_bucket.is_empty() {
6132                        continue;
6133                    }
6134                    let repeat_count = right_bucket.len();
6135                    for &left_pos in left_bucket {
6136                        let value = values[left_pos];
6137                        for _ in 0..repeat_count {
6138                            data.push(value);
6139                        }
6140                    }
6141                }
6142            }
6143            FusedInt64Side::Right => {
6144                for (left_bucket, right_bucket) in left_buckets.iter().zip(right_buckets.iter()) {
6145                    if left_bucket.is_empty() {
6146                        continue;
6147                    }
6148                    for _ in left_bucket {
6149                        for &right_pos in right_bucket {
6150                            data.push(values[right_pos]);
6151                        }
6152                    }
6153                }
6154            }
6155        }
6156        debug_assert_eq!(data.len(), output_len);
6157        insert_merged_output_column(
6158            &mut columns,
6159            &mut column_order,
6160            name,
6161            Column::from_i64_values(data),
6162        )?;
6163    }
6164
6165    Ok(Some(MergedDataFrame {
6166        index,
6167        columns,
6168        column_order,
6169    }))
6170}
6171
6172struct FixedDecimalUtf8Domain {
6173    prefix: Vec<u8>,
6174    decimal_width: usize,
6175    start: u64,
6176    len: usize,
6177}
6178
6179impl FixedDecimalUtf8Domain {
6180    fn row_width(&self) -> usize {
6181        self.prefix.len() + self.decimal_width
6182    }
6183}
6184
6185fn trailing_decimal_width(bytes: &[u8]) -> Option<usize> {
6186    let width = bytes
6187        .iter()
6188        .rev()
6189        .take_while(|byte| byte.is_ascii_digit())
6190        .count();
6191    (width > 0).then_some(width)
6192}
6193
6194fn parse_decimal_u64(bytes: &[u8]) -> Option<u64> {
6195    let mut out = 0u64;
6196    for &byte in bytes {
6197        if !byte.is_ascii_digit() {
6198            return None;
6199        }
6200        out = out.checked_mul(10)?.checked_add(u64::from(byte - b'0'))?;
6201    }
6202    Some(out)
6203}
6204
6205fn fixed_decimal_utf8_domain(bytes: &[u8], offsets: &[usize]) -> Option<FixedDecimalUtf8Domain> {
6206    let len = offsets.len().checked_sub(1)?;
6207    if len == 0 {
6208        return None;
6209    }
6210
6211    let first = utf8_span(bytes, offsets, 0);
6212    let decimal_width = trailing_decimal_width(first)?;
6213    let prefix_len = first.len().checked_sub(decimal_width)?;
6214    let prefix = first[..prefix_len].to_vec();
6215    let start = parse_decimal_u64(&first[prefix_len..])?;
6216    let row_width = first.len();
6217
6218    for row in 0..len {
6219        let span = utf8_span(bytes, offsets, row);
6220        if span.len() != row_width || !span.starts_with(&prefix) {
6221            return None;
6222        }
6223        let value = parse_decimal_u64(&span[prefix_len..])?;
6224        if value != start.checked_add(row as u64)? {
6225            return None;
6226        }
6227    }
6228
6229    Some(FixedDecimalUtf8Domain {
6230        prefix,
6231        decimal_width,
6232        start,
6233        len,
6234    })
6235}
6236
6237fn fixed_decimal_utf8_bucket(span: &[u8], domain: &FixedDecimalUtf8Domain) -> Option<usize> {
6238    if span.len() != domain.row_width() || !span.starts_with(&domain.prefix) {
6239        return None;
6240    }
6241    let value = parse_decimal_u64(&span[domain.prefix.len()..])?;
6242    let relative = value.checked_sub(domain.start)?;
6243    let bucket = usize::try_from(relative).ok()?;
6244    (bucket < domain.len).then_some(bucket)
6245}
6246
6247enum FixedDecimalUtf8OuterLane<'a> {
6248    SharedKey,
6249    LeftF64(&'a [f64]),
6250    RightF64(&'a [f64]),
6251    LeftI64(&'a [i64]),
6252    RightI64(&'a [i64]),
6253}
6254
6255fn build_single_key_fixed_decimal_utf8_outer_all_matched_merge_output(
6256    left: &fp_frame::DataFrame,
6257    right: &fp_frame::DataFrame,
6258    left_on: &[&str],
6259    right_on: &[&str],
6260    left_key: &Column,
6261    right_key: &Column,
6262    suffixes: &ResolvedMergeSuffixes,
6263) -> Result<Option<MergedDataFrame>, JoinError> {
6264    debug_assert_eq!(left_on.len(), 1);
6265    debug_assert_eq!(right_on.len(), 1);
6266
6267    if left_on[0] != right_on[0] {
6268        return Ok(None);
6269    }
6270
6271    let Some((left_bytes, left_offsets)) = left_key.as_utf8_contiguous() else {
6272        return Ok(None);
6273    };
6274    let Some((right_bytes, right_offsets)) = right_key.as_utf8_contiguous() else {
6275        return Ok(None);
6276    };
6277    let left_len = left_offsets.len().saturating_sub(1);
6278    let right_len = right_offsets.len().saturating_sub(1);
6279    if left_len == 0 || right_len == 0 {
6280        return Ok(None);
6281    }
6282
6283    let Some(domain) = fixed_decimal_utf8_domain(right_bytes, right_offsets) else {
6284        return Ok(None);
6285    };
6286
6287    let mut counts = vec![0usize; right_len];
6288    let mut left_buckets = Vec::<usize>::with_capacity(left_len);
6289    for left_pos in 0..left_len {
6290        let span = utf8_span(left_bytes, left_offsets, left_pos);
6291        let Some(bucket) = fixed_decimal_utf8_bucket(span, &domain) else {
6292            return Ok(None);
6293        };
6294        counts[bucket] = counts[bucket].checked_add(1).ok_or_else(|| {
6295            JoinError::Frame(FrameError::CompatibilityRejected(
6296                "merge output row count overflowed".to_owned(),
6297            ))
6298        })?;
6299        left_buckets.push(bucket);
6300    }
6301    if counts.contains(&0) {
6302        return Ok(None);
6303    }
6304
6305    let mut offsets = Vec::with_capacity(right_len + 1);
6306    offsets.push(0usize);
6307    for &count in &counts {
6308        offsets.push(offsets.last().copied().unwrap_or(0) + count);
6309    }
6310    let output_len = offsets[right_len];
6311    let mut left_positions = vec![0usize; output_len];
6312    let mut cursor = offsets[..right_len].to_vec();
6313    for (left_pos, &bucket) in left_buckets.iter().enumerate() {
6314        let out = cursor[bucket];
6315        left_positions[out] = left_pos;
6316        cursor[bucket] += 1;
6317    }
6318
6319    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
6320    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
6321    let shared_key_names = [left_on[0]].into_iter().collect::<HashSet<&str>>();
6322    let overlapping_names =
6323        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
6324    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
6325
6326    let mut specs = Vec::<(String, FixedDecimalUtf8OuterLane<'_>)>::new();
6327    for name in left.column_names() {
6328        let col = left
6329            .columns()
6330            .get(name)
6331            .expect("left column listed in column_names must exist");
6332        let lane = if name.as_str() == left_on[0] {
6333            FixedDecimalUtf8OuterLane::SharedKey
6334        } else if let Some(values) = col.as_f64_slice() {
6335            FixedDecimalUtf8OuterLane::LeftF64(values)
6336        } else if let Some(values) = col.as_i64_slice() {
6337            FixedDecimalUtf8OuterLane::LeftI64(values)
6338        } else {
6339            return Ok(None);
6340        };
6341        let out_name = if name.as_str() == left_on[0] {
6342            name.clone()
6343        } else if right_col_names.contains(name) {
6344            apply_merge_suffix(name, suffixes.left.as_deref())
6345        } else {
6346            name.clone()
6347        };
6348        specs.push((out_name, lane));
6349    }
6350    for name in right.column_names() {
6351        if name.as_str() == right_on[0] {
6352            continue;
6353        }
6354        let col = right
6355            .columns()
6356            .get(name)
6357            .expect("right column listed in column_names must exist");
6358        let lane = if let Some(values) = col.as_f64_slice() {
6359            FixedDecimalUtf8OuterLane::RightF64(values)
6360        } else if let Some(values) = col.as_i64_slice() {
6361            FixedDecimalUtf8OuterLane::RightI64(values)
6362        } else {
6363            return Ok(None);
6364        };
6365        let out_name = if left_col_names.contains(name) {
6366            apply_merge_suffix(name, suffixes.right.as_deref())
6367        } else {
6368            name.clone()
6369        };
6370        specs.push((out_name, lane));
6371    }
6372
6373    let run_lens: Arc<[usize]> = Arc::from(counts.clone());
6374    let index = Index::new_known_unique_int64_unit_range(0, output_len);
6375    let mut columns = ColumnStore::new();
6376    let mut column_order = Vec::with_capacity(specs.len());
6377    for (name, lane) in specs {
6378        let column = match lane {
6379            FixedDecimalUtf8OuterLane::SharedKey => {
6380                let row_width = domain.row_width();
6381                let mut bytes = Vec::with_capacity(output_len.saturating_mul(row_width));
6382                let mut out_offsets = Vec::with_capacity(output_len + 1);
6383                out_offsets.push(0);
6384                for (bucket, &count) in counts.iter().enumerate() {
6385                    let span = utf8_span(right_bytes, right_offsets, bucket);
6386                    for _ in 0..count {
6387                        bytes.extend_from_slice(span);
6388                        out_offsets.push(bytes.len());
6389                    }
6390                }
6391                Column::from_utf8_contiguous(bytes, out_offsets)
6392            }
6393            FixedDecimalUtf8OuterLane::LeftF64(values) => {
6394                let data = left_positions.iter().map(|&pos| values[pos]).collect();
6395                Column::from_f64_values_all_valid_unchecked(data)
6396            }
6397            FixedDecimalUtf8OuterLane::RightF64(values) => {
6398                let run_values = (0..right_len).map(|bucket| values[bucket]).collect();
6399                Column::from_f64_repeat_values_run_lengths(run_values, Arc::clone(&run_lens))
6400            }
6401            FixedDecimalUtf8OuterLane::LeftI64(values) => {
6402                let data = left_positions.iter().map(|&pos| values[pos]).collect();
6403                Column::from_i64_values(data)
6404            }
6405            FixedDecimalUtf8OuterLane::RightI64(values) => {
6406                let run_values = (0..right_len).map(|bucket| values[bucket]).collect();
6407                Column::from_i64_repeat_values_run_lengths(run_values, Arc::clone(&run_lens))
6408            }
6409        };
6410        debug_assert_eq!(column.len(), output_len);
6411        insert_merged_output_column(&mut columns, &mut column_order, name, column)?;
6412    }
6413
6414    Ok(Some(MergedDataFrame {
6415        index,
6416        columns,
6417        column_order,
6418    }))
6419}
6420
6421fn build_single_key_inner_merge_output(
6422    left: &fp_frame::DataFrame,
6423    right: &fp_frame::DataFrame,
6424    left_on: &[&str],
6425    right_on: &[&str],
6426    left_positions: &[usize],
6427    right_positions: &[usize],
6428    suffixes: &ResolvedMergeSuffixes,
6429) -> Result<MergedDataFrame, JoinError> {
6430    build_single_key_inner_merge_output_with_selections(
6431        left,
6432        right,
6433        left_on,
6434        right_on,
6435        PositionSelection::Positions(left_positions),
6436        PositionSelection::Positions(right_positions),
6437        suffixes,
6438    )
6439}
6440
6441fn build_single_key_inner_contiguous_no_overlap_output(
6442    left: &fp_frame::DataFrame,
6443    right: &fp_frame::DataFrame,
6444    left_on: &[&str],
6445    right_on: &[&str],
6446    left_positions: PositionSelection<'_>,
6447    right_positions: PositionSelection<'_>,
6448) -> Option<MergedDataFrame> {
6449    let (
6450        PositionSelection::ContiguousRange {
6451            start: left_start,
6452            len,
6453        },
6454        PositionSelection::ContiguousRange {
6455            start: right_start,
6456            len: right_len,
6457        },
6458    ) = (left_positions, right_positions)
6459    else {
6460        return None;
6461    };
6462    if left_on[0] != right_on[0] || len != right_len {
6463        return None;
6464    }
6465
6466    let left_col_names = left.column_names();
6467    let right_col_names = right.column_names();
6468    if left_col_names.iter().any(|left_name| {
6469        left_name.as_str() != left_on[0]
6470            && right_col_names
6471                .iter()
6472                .any(|right_name| right_name.as_str() == left_name.as_str())
6473    }) {
6474        return None;
6475    }
6476
6477    let mut columns = ColumnStore::new();
6478    let mut column_order =
6479        Vec::with_capacity(left_col_names.len() + right_col_names.len().saturating_sub(1));
6480    let left_selection = PositionSelection::ContiguousRange {
6481        start: left_start,
6482        len,
6483    };
6484    let right_selection = PositionSelection::ContiguousRange {
6485        start: right_start,
6486        len,
6487    };
6488
6489    for name in left_col_names.iter().copied() {
6490        let column = left
6491            .columns()
6492            .get(name)
6493            .expect("left column listed in column_names must exist");
6494        let output_column = if name.as_str() == left_on[0] {
6495            take_lower_hex_sequence_range(column, left_start, len)
6496                .unwrap_or_else(|| take_position_selection_typed(column, left_selection))
6497        } else {
6498            take_position_selection_typed(column, left_selection)
6499        };
6500        column_order.push(name.clone());
6501        let previous = columns.insert(name.clone(), output_column);
6502        debug_assert!(previous.is_none());
6503    }
6504    for name in right_col_names.iter().copied() {
6505        if name.as_str() == right_on[0] {
6506            continue;
6507        }
6508        let column = right
6509            .columns()
6510            .get(name)
6511            .expect("right column listed in column_names must exist");
6512        column_order.push(name.clone());
6513        let previous = columns.insert(
6514            name.clone(),
6515            take_position_selection_typed(column, right_selection),
6516        );
6517        debug_assert!(previous.is_none());
6518    }
6519
6520    Some(MergedDataFrame {
6521        index: Index::new_known_unique_int64_unit_range(0, len),
6522        columns,
6523        column_order,
6524    })
6525}
6526
6527fn build_single_key_inner_merge_output_with_selections(
6528    left: &fp_frame::DataFrame,
6529    right: &fp_frame::DataFrame,
6530    left_on: &[&str],
6531    right_on: &[&str],
6532    left_positions: PositionSelection<'_>,
6533    right_positions: PositionSelection<'_>,
6534    suffixes: &ResolvedMergeSuffixes,
6535) -> Result<MergedDataFrame, JoinError> {
6536    debug_assert_eq!(left_on.len(), 1);
6537    debug_assert_eq!(right_on.len(), 1);
6538    debug_assert_eq!(left_positions.len(), right_positions.len());
6539
6540    if let Some(merged) = build_single_key_inner_contiguous_no_overlap_output(
6541        left,
6542        right,
6543        left_on,
6544        right_on,
6545        left_positions,
6546        right_positions,
6547    ) {
6548        return Ok(merged);
6549    }
6550
6551    let n = left_positions.len();
6552    // Lazy unit-range output index (see build_single_key_dense_i64 site).
6553    let index = Index::new_known_unique_int64_unit_range(0, n);
6554
6555    let left_col_names = left.column_names();
6556    let right_col_names = right.column_names();
6557    let use_linear_name_lookup =
6558        left_col_names.len() + right_col_names.len() <= SMALL_SCHEMA_LINEAR_COLUMN_LOOKUP_LIMIT;
6559    let left_hashed_col_names = (!use_linear_name_lookup).then(|| {
6560        left_col_names
6561            .iter()
6562            .map(|name| name.as_str())
6563            .collect::<HashSet<_>>()
6564    });
6565    let right_hashed_col_names = (!use_linear_name_lookup).then(|| {
6566        right_col_names
6567            .iter()
6568            .map(|name| name.as_str())
6569            .collect::<HashSet<_>>()
6570    });
6571    let shared_key_name = (left_on[0] == right_on[0]).then_some(left_on[0]);
6572    let mut overlapping_names = left_col_names
6573        .iter()
6574        .filter_map(|name| {
6575            let name = name.as_str();
6576            (Some(name) != shared_key_name
6577                && column_name_lookup_contains(
6578                    &right_col_names,
6579                    right_hashed_col_names.as_ref(),
6580                    name,
6581                ))
6582            .then(|| name.to_owned())
6583        })
6584        .collect::<Vec<_>>();
6585    overlapping_names.sort();
6586    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
6587
6588    // Resolve output column specs in order (name/suffix resolution is cheap),
6589    // then gather them. Each output column is an independent typed gather over
6590    // the position vector, so wide/large outputs build every column in parallel
6591    // (one column per worker) — the same disjoint-fill pattern as the dense-i64
6592    // fused builder (br-frankenpandas-j3jnd). Bit-identical to the serial loop:
6593    // identical per-column take_positions_typed result, inserted in spec order.
6594    let mut specs: Vec<(String, &Column, PositionSelection<'_>)> = Vec::new();
6595    for name in left_col_names.iter().copied() {
6596        let col = left
6597            .columns()
6598            .get(name)
6599            .expect("left column listed in column_names must exist");
6600        let out_name = if name.as_str() == left_on[0] {
6601            name.clone()
6602        } else if column_name_lookup_contains(
6603            &right_col_names,
6604            right_hashed_col_names.as_ref(),
6605            name.as_str(),
6606        ) {
6607            apply_merge_suffix(name, suffixes.left.as_deref())
6608        } else {
6609            name.clone()
6610        };
6611        specs.push((out_name, col, left_positions));
6612    }
6613    for name in right_col_names.iter().copied() {
6614        if name.as_str() == right_on[0] && shared_key_name == Some(name.as_str()) {
6615            continue;
6616        }
6617        let col = right
6618            .columns()
6619            .get(name)
6620            .expect("right column listed in column_names must exist");
6621        let out_name = if column_name_lookup_contains(
6622            &left_col_names,
6623            left_hashed_col_names.as_ref(),
6624            name.as_str(),
6625        ) {
6626            apply_merge_suffix(name, suffixes.right.as_deref())
6627        } else {
6628            name.clone()
6629        };
6630        specs.push((out_name, col, right_positions));
6631    }
6632
6633    let built: Vec<Column> = {
6634        let thread_count = join_parallel_thread_count();
6635        if specs.len() > 1 && n >= DENSE_I64_INNER_PARALLEL_MIN_VALUES && thread_count > 1 {
6636            let mut slots: Vec<Option<Column>> = (0..specs.len()).map(|_| None).collect();
6637            let chunk = specs.len().div_ceil(thread_count).max(1);
6638            std::thread::scope(|scope| {
6639                for (spec_chunk, slot_chunk) in specs.chunks(chunk).zip(slots.chunks_mut(chunk)) {
6640                    scope.spawn(move || {
6641                        for ((_, col, positions), slot) in spec_chunk.iter().zip(slot_chunk) {
6642                            *slot = Some(take_position_selection_typed(col, *positions));
6643                        }
6644                    });
6645                }
6646            });
6647            slots
6648                .into_iter()
6649                .map(|c| c.expect("every spec column must be built"))
6650                .collect()
6651        } else {
6652            specs
6653                .iter()
6654                .map(|(_, col, positions)| take_position_selection_typed(col, *positions))
6655                .collect()
6656        }
6657    };
6658
6659    let mut columns = ColumnStore::new();
6660    let mut column_order: Vec<String> = Vec::with_capacity(specs.len());
6661    for ((out_name, _, _), column) in specs.into_iter().zip(built) {
6662        insert_merged_output_column(&mut columns, &mut column_order, out_name, column)?;
6663    }
6664
6665    Ok(MergedDataFrame {
6666        index,
6667        columns,
6668        column_order,
6669    })
6670}
6671
6672fn build_single_key_dense_left_merge_output(
6673    left: &fp_frame::DataFrame,
6674    right: &fp_frame::DataFrame,
6675    left_on: &[&str],
6676    right_on: &[&str],
6677    left_positions: &[Option<usize>],
6678    right_positions: &[Option<usize>],
6679    suffixes: &ResolvedMergeSuffixes,
6680) -> Result<MergedDataFrame, JoinError> {
6681    debug_assert_eq!(left_on.len(), 1);
6682    debug_assert_eq!(right_on.len(), 1);
6683    debug_assert_eq!(left_positions.len(), right_positions.len());
6684
6685    let n = left_positions.len();
6686    // Lazy unit-range output index (see build_single_key_dense_i64 site).
6687    let index = Index::new_known_unique_int64_unit_range(0, n);
6688    let mut columns = ColumnStore::new();
6689    let mut column_order: Vec<String> = Vec::new();
6690
6691    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
6692    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
6693    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
6694    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
6695    let shared_key_names = if left_on[0] == right_on[0] {
6696        [left_on[0]].into_iter().collect::<HashSet<&str>>()
6697    } else {
6698        HashSet::new()
6699    };
6700    let overlapping_names =
6701        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
6702    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
6703    for name in left.column_names() {
6704        let col = left
6705            .columns()
6706            .get(name)
6707            .expect("left column listed in column_names must exist");
6708        let out_name = if left_key_name_set.contains(name.as_str()) {
6709            name.clone()
6710        } else if right_col_names.contains(name) {
6711            apply_merge_suffix(name, suffixes.left.as_deref())
6712        } else {
6713            name.clone()
6714        };
6715        let output = col.reindex_by_positions(left_positions)?;
6716        insert_merged_output_column(&mut columns, &mut column_order, out_name, output)?;
6717    }
6718
6719    for name in right.column_names() {
6720        let col = right
6721            .columns()
6722            .get(name)
6723            .expect("right column listed in column_names must exist");
6724        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
6725            continue;
6726        }
6727
6728        let reindexed = reindex_join_column_with_invented_gap(col, right_positions)?;
6729        let out_name = if left_col_names.contains(name) {
6730            apply_merge_suffix(name, suffixes.right.as_deref())
6731        } else {
6732            name.clone()
6733        };
6734        insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
6735    }
6736
6737    Ok(MergedDataFrame {
6738        index,
6739        columns,
6740        column_order,
6741    })
6742}
6743
6744fn build_single_key_ordered_unique_left_merge_output(
6745    left: &fp_frame::DataFrame,
6746    right: &fp_frame::DataFrame,
6747    left_on: &[&str],
6748    right_on: &[&str],
6749    right_positions: &[Option<usize>],
6750    suffixes: &ResolvedMergeSuffixes,
6751) -> Result<MergedDataFrame, JoinError> {
6752    debug_assert_eq!(left_on.len(), 1);
6753    debug_assert_eq!(right_on.len(), 1);
6754    debug_assert_eq!(left.len(), right_positions.len());
6755
6756    let n = left.len();
6757    // Lazy unit-range output index (see build_single_key_dense_i64 site).
6758    let index = Index::new_known_unique_int64_unit_range(0, n);
6759    let mut columns = ColumnStore::new();
6760    let mut column_order: Vec<String> = Vec::new();
6761    let mut identity_positions = None;
6762
6763    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
6764    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
6765    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
6766    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
6767    let shared_key_names = if left_on[0] == right_on[0] {
6768        [left_on[0]].into_iter().collect::<HashSet<&str>>()
6769    } else {
6770        HashSet::new()
6771    };
6772    let overlapping_names =
6773        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
6774    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
6775    // Building the shared Utf8 gather plan is O(output_rows): it scans every
6776    // optional position and, for a non-contiguous match pattern, allocates an
6777    // additional position tape plus validity bitmap. Most ordered Int64 joins
6778    // have only numeric payloads, where every column ignores that plan and uses
6779    // its typed reindexer. Defer the work until the first Utf8 payload actually
6780    // asks for it; subsequent Utf8 columns still share the single immutable
6781    // plan exactly as before.
6782    let right_utf8_plan: OnceLock<Option<SharedOptionalUtf8GatherPlan>> = OnceLock::new();
6783
6784    for name in left.column_names() {
6785        let col = left
6786            .columns()
6787            .get(name)
6788            .expect("left column listed in column_names must exist");
6789        let out_name = if left_key_name_set.contains(name.as_str()) {
6790            name.clone()
6791        } else if right_col_names.contains(name) {
6792            apply_merge_suffix(name, suffixes.left.as_deref())
6793        } else {
6794            name.clone()
6795        };
6796        let output = identity_merge_column(col, n, &mut identity_positions);
6797        insert_merged_output_column(&mut columns, &mut column_order, out_name, output)?;
6798    }
6799
6800    for name in right.column_names() {
6801        let col = right
6802            .columns()
6803            .get(name)
6804            .expect("right column listed in column_names must exist");
6805        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
6806            continue;
6807        }
6808
6809        let reindexed = if col.dtype() == DType::Utf8 {
6810            let utf8_plan = right_utf8_plan
6811                .get_or_init(|| shared_optional_utf8_gather_plan(right_positions, right.len()))
6812                .as_ref();
6813            reindex_with_shared_utf8_plan(col, right_positions, utf8_plan)?
6814        } else {
6815            reindex_join_column_with_invented_gap(col, right_positions)?
6816        };
6817        let out_name = if left_col_names.contains(name) {
6818            apply_merge_suffix(name, suffixes.right.as_deref())
6819        } else {
6820            name.clone()
6821        };
6822        insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
6823    }
6824
6825    Ok(MergedDataFrame {
6826        index,
6827        columns,
6828        column_order,
6829    })
6830}
6831
6832fn build_single_key_ordered_unique_right_merge_output(
6833    left: &fp_frame::DataFrame,
6834    right: &fp_frame::DataFrame,
6835    left_on: &[&str],
6836    right_on: &[&str],
6837    left_positions: &[Option<usize>],
6838    suffixes: &ResolvedMergeSuffixes,
6839) -> Result<MergedDataFrame, JoinError> {
6840    debug_assert_eq!(left_on.len(), 1);
6841    debug_assert_eq!(right_on.len(), 1);
6842    debug_assert_eq!(right.len(), left_positions.len());
6843
6844    let n = right.len();
6845    // Lazy unit-range output index (see build_single_key_dense_i64 site).
6846    let index = Index::new_known_unique_int64_unit_range(0, n);
6847    let mut columns = ColumnStore::new();
6848    let mut column_order: Vec<String> = Vec::new();
6849    let mut identity_positions = None;
6850
6851    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
6852    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
6853    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
6854    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
6855    let shared_key_names = if left_on[0] == right_on[0] {
6856        [left_on[0]].into_iter().collect::<HashSet<&str>>()
6857    } else {
6858        HashSet::new()
6859    };
6860    let overlapping_names =
6861        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
6862    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
6863
6864    for name in left.column_names() {
6865        let col = left
6866            .columns()
6867            .get(name)
6868            .expect("left column listed in column_names must exist");
6869        let out_name = if left_key_name_set.contains(name.as_str()) {
6870            name.clone()
6871        } else if right_col_names.contains(name) {
6872            apply_merge_suffix(name, suffixes.left.as_deref())
6873        } else {
6874            name.clone()
6875        };
6876        let output = if left_key_name_set.contains(name.as_str())
6877            && shared_key_names.contains(name.as_str())
6878        {
6879            let right_key_col = right
6880                .columns()
6881                .get(right_on[0])
6882                .expect("right key column must exist");
6883            identity_merge_column(right_key_col, n, &mut identity_positions)
6884        } else {
6885            reindex_join_column_with_invented_gap(col, left_positions)?
6886        };
6887        insert_merged_output_column(&mut columns, &mut column_order, out_name, output)?;
6888    }
6889
6890    for name in right.column_names() {
6891        let col = right
6892            .columns()
6893            .get(name)
6894            .expect("right column listed in column_names must exist");
6895        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
6896            continue;
6897        }
6898
6899        let reindexed = identity_merge_column(col, n, &mut identity_positions);
6900        let out_name = if left_col_names.contains(name) {
6901            apply_merge_suffix(name, suffixes.right.as_deref())
6902        } else {
6903            name.clone()
6904        };
6905        insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
6906    }
6907
6908    Ok(MergedDataFrame {
6909        index,
6910        columns,
6911        column_order,
6912    })
6913}
6914
6915fn build_single_key_dense_right_merge_output(
6916    left: &fp_frame::DataFrame,
6917    right: &fp_frame::DataFrame,
6918    left_on: &[&str],
6919    right_on: &[&str],
6920    left_positions: &[Option<usize>],
6921    right_positions: &[Option<usize>],
6922    suffixes: &ResolvedMergeSuffixes,
6923) -> Result<MergedDataFrame, JoinError> {
6924    debug_assert_eq!(left_on.len(), 1);
6925    debug_assert_eq!(right_on.len(), 1);
6926    debug_assert_eq!(left_positions.len(), right_positions.len());
6927
6928    let n = left_positions.len();
6929    // Lazy unit-range output index (see build_single_key_dense_i64 site).
6930    let index = Index::new_known_unique_int64_unit_range(0, n);
6931    let mut columns = ColumnStore::new();
6932    let mut column_order: Vec<String> = Vec::new();
6933
6934    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
6935    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
6936    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
6937    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
6938    let shared_key_names = if left_on[0] == right_on[0] {
6939        [left_on[0]].into_iter().collect::<HashSet<&str>>()
6940    } else {
6941        HashSet::new()
6942    };
6943    let overlapping_names =
6944        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
6945    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
6946
6947    for name in left.column_names() {
6948        let col = left
6949            .columns()
6950            .get(name)
6951            .expect("left column listed in column_names must exist");
6952        let out_name = if left_key_name_set.contains(name.as_str()) {
6953            name.clone()
6954        } else if right_col_names.contains(name) {
6955            apply_merge_suffix(name, suffixes.left.as_deref())
6956        } else {
6957            name.clone()
6958        };
6959        let output = if left_key_name_set.contains(name.as_str())
6960            && shared_key_names.contains(name.as_str())
6961        {
6962            let right_key_col = right
6963                .columns()
6964                .get(right_on[0])
6965                .expect("right key column must exist");
6966            right_key_col.reindex_by_positions(right_positions)?
6967        } else {
6968            reindex_join_column_with_invented_gap(col, left_positions)?
6969        };
6970        insert_merged_output_column(&mut columns, &mut column_order, out_name, output)?;
6971    }
6972
6973    for name in right.column_names() {
6974        let col = right
6975            .columns()
6976            .get(name)
6977            .expect("right column listed in column_names must exist");
6978        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
6979            continue;
6980        }
6981
6982        let reindexed = col.reindex_by_positions(right_positions)?;
6983        let out_name = if left_col_names.contains(name) {
6984            apply_merge_suffix(name, suffixes.right.as_deref())
6985        } else {
6986            name.clone()
6987        };
6988        insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
6989    }
6990
6991    Ok(MergedDataFrame {
6992        index,
6993        columns,
6994        column_order,
6995    })
6996}
6997
6998fn build_single_key_ordered_unique_outer_merge_output(
6999    left: &fp_frame::DataFrame,
7000    right: &fp_frame::DataFrame,
7001    left_on: &[&str],
7002    right_on: &[&str],
7003    left_positions: &[Option<usize>],
7004    right_positions: &[Option<usize>],
7005    suffixes: &ResolvedMergeSuffixes,
7006) -> Result<MergedDataFrame, JoinError> {
7007    debug_assert_eq!(left_on.len(), 1);
7008    debug_assert_eq!(right_on.len(), 1);
7009    debug_assert_eq!(left_positions.len(), right_positions.len());
7010
7011    let n = left_positions.len();
7012    // Lazy unit-range output index (see build_single_key_dense_i64 site).
7013    let index = Index::new_known_unique_int64_unit_range(0, n);
7014    let mut columns = ColumnStore::new();
7015    let mut column_order: Vec<String> = Vec::new();
7016
7017    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
7018    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
7019    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
7020    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
7021
7022    let mut shared_name_positions = HashMap::<&str, (usize, usize)>::new();
7023    if left_on[0] == right_on[0] {
7024        shared_name_positions.insert(left_on[0], (0, 0));
7025    }
7026    let shared_key_names = shared_name_positions
7027        .keys()
7028        .copied()
7029        .collect::<HashSet<&str>>();
7030    let overlapping_names =
7031        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
7032    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
7033
7034    let mut left_take_positions = Vec::with_capacity(n);
7035    let mut right_take_positions = Vec::with_capacity(n);
7036    let mut all_positions_present = true;
7037    for (left_pos, right_pos) in left_positions.iter().zip(right_positions.iter()) {
7038        let (Some(left_pos), Some(right_pos)) = (*left_pos, *right_pos) else {
7039            all_positions_present = false;
7040            break;
7041        };
7042        left_take_positions.push(left_pos);
7043        right_take_positions.push(right_pos);
7044    }
7045    let all_present_take_positions =
7046        all_positions_present.then_some((left_take_positions, right_take_positions));
7047    let all_present_left_positions = all_present_take_positions
7048        .as_ref()
7049        .map(|(positions, _)| positions.as_slice());
7050    let all_present_right_positions = all_present_take_positions
7051        .as_ref()
7052        .map(|(_, positions)| positions.as_slice());
7053    let left_has_utf8 = left
7054        .columns()
7055        .values()
7056        .any(|column| column.dtype() == DType::Utf8);
7057    let right_has_utf8 = right
7058        .columns()
7059        .values()
7060        .any(|column| column.dtype() == DType::Utf8);
7061    let left_utf8_plan = (left_has_utf8 && all_present_left_positions.is_none())
7062        .then(|| shared_optional_utf8_gather_plan(left_positions, left.len()))
7063        .flatten();
7064    let right_utf8_plan = (right_has_utf8 && all_present_right_positions.is_none())
7065        .then(|| shared_optional_utf8_gather_plan(right_positions, right.len()))
7066        .flatten();
7067
7068    // Per-column output build is INDEPENDENT across columns and was the serial
7069    // hot phase of the join (~10.5ms of str_outer_join's reindex assembly at
7070    // n=150000, 12 Utf8 value columns). Build an ordered list of column specs
7071    // (cheap), compute each column — the O(output) `reindex_join_column_with_invented_gap`
7072    // gather / take / key-coalesce — across workers, then insert in the SAME
7073    // first-seen order (br-frankenpandas-uza04.102). Byte-identical: each output
7074    // column is the same values in the same row order, inserted in the same
7075    // left-then-right column order, so `columns`/`column_order` are unchanged.
7076    enum ColBuild<'a> {
7077        KeyCoalesce {
7078            left_key_col: &'a Column,
7079            right_key_col: &'a Column,
7080        },
7081        Reindex {
7082            col: &'a Column,
7083            positions: &'a [Option<usize>],
7084            utf8_plan: Option<&'a SharedOptionalUtf8GatherPlan>,
7085        },
7086        Take {
7087            col: &'a Column,
7088            present: &'a [usize],
7089        },
7090    }
7091    let mut jobs: Vec<(String, ColBuild<'_>)> = Vec::new();
7092    for name in left.column_names() {
7093        let col = left
7094            .columns()
7095            .get(name)
7096            .expect("left column listed in column_names must exist");
7097        if left_key_name_set.contains(name.as_str()) {
7098            if let Some((left_key_idx, right_key_idx)) = shared_name_positions.get(name.as_str()) {
7099                let left_key_col = left
7100                    .columns()
7101                    .get(left_on[*left_key_idx])
7102                    .expect("left key column must exist");
7103                let spec = if let Some(positions) = all_present_left_positions {
7104                    ColBuild::Take {
7105                        col: left_key_col,
7106                        present: positions,
7107                    }
7108                } else {
7109                    let right_key_col = right
7110                        .columns()
7111                        .get(right_on[*right_key_idx])
7112                        .expect("right key column must exist");
7113                    ColBuild::KeyCoalesce {
7114                        left_key_col,
7115                        right_key_col,
7116                    }
7117                };
7118                jobs.push((name.clone(), spec));
7119            } else {
7120                let spec = if let Some(positions) = all_present_left_positions {
7121                    ColBuild::Take {
7122                        col,
7123                        present: positions,
7124                    }
7125                } else {
7126                    ColBuild::Reindex {
7127                        col,
7128                        positions: left_positions,
7129                        utf8_plan: left_utf8_plan.as_ref(),
7130                    }
7131                };
7132                jobs.push((name.clone(), spec));
7133            }
7134            continue;
7135        }
7136        let spec = if let Some(positions) = all_present_left_positions {
7137            ColBuild::Take {
7138                col,
7139                present: positions,
7140            }
7141        } else {
7142            ColBuild::Reindex {
7143                col,
7144                positions: left_positions,
7145                utf8_plan: left_utf8_plan.as_ref(),
7146            }
7147        };
7148        let out_name = if right_col_names.contains(name) {
7149            apply_merge_suffix(name, suffixes.left.as_deref())
7150        } else {
7151            name.clone()
7152        };
7153        jobs.push((out_name, spec));
7154    }
7155    for name in right.column_names() {
7156        let col = right
7157            .columns()
7158            .get(name)
7159            .expect("right column listed in column_names must exist");
7160        if right_key_name_set.contains(name.as_str())
7161            && shared_name_positions.contains_key(name.as_str())
7162        {
7163            continue;
7164        }
7165        let spec = if let Some(positions) = all_present_right_positions {
7166            ColBuild::Take {
7167                col,
7168                present: positions,
7169            }
7170        } else {
7171            ColBuild::Reindex {
7172                col,
7173                positions: right_positions,
7174                utf8_plan: right_utf8_plan.as_ref(),
7175            }
7176        };
7177        let out_name = if left_col_names.contains(name) {
7178            apply_merge_suffix(name, suffixes.right.as_deref())
7179        } else {
7180            name.clone()
7181        };
7182        jobs.push((out_name, spec));
7183    }
7184
7185    let compute = |spec: &ColBuild<'_>| -> Result<Column, JoinError> {
7186        match spec {
7187            ColBuild::KeyCoalesce {
7188                left_key_col,
7189                right_key_col,
7190            } => {
7191                if let Some(column) = coalesce_temporal_i64_key_column(
7192                    left_key_col,
7193                    right_key_col,
7194                    left_positions,
7195                    right_positions,
7196                ) {
7197                    return Ok(column);
7198                }
7199                if let (Some(left_keys), Some(right_keys)) =
7200                    (left_key_col.as_i64_slice(), right_key_col.as_i64_slice())
7201                {
7202                    let mut data = Vec::with_capacity(left_positions.len());
7203                    let mut all_positions_valid = true;
7204                    for (left_pos, right_pos) in left_positions.iter().zip(right_positions.iter()) {
7205                        match (*left_pos, *right_pos) {
7206                            (Some(pos), _) if pos < left_keys.len() => data.push(left_keys[pos]),
7207                            (None, Some(pos)) if pos < right_keys.len() => {
7208                                data.push(right_keys[pos])
7209                            }
7210                            _ => {
7211                                all_positions_valid = false;
7212                                break;
7213                            }
7214                        }
7215                    }
7216                    if all_positions_valid {
7217                        return Ok(Column::from_i64_values(data));
7218                    }
7219                }
7220
7221                let values = left_positions
7222                    .iter()
7223                    .zip(right_positions.iter())
7224                    .map(|(left_pos, right_pos)| match (left_pos, right_pos) {
7225                        (Some(pos), _) => left_key_col.values()[*pos].clone(),
7226                        (None, Some(pos)) => right_key_col.values()[*pos].clone(),
7227                        (None, None) => fp_types::Scalar::Null(fp_types::NullKind::Null),
7228                    })
7229                    .collect::<Vec<_>>();
7230                Ok(Column::from_values(values)?)
7231            }
7232            ColBuild::Reindex {
7233                col,
7234                positions,
7235                utf8_plan,
7236            } => reindex_outer_with_shared_utf8_plan(col, positions, *utf8_plan),
7237            ColBuild::Take { col, present } => Ok(take_positions_typed(col, present)),
7238        }
7239    };
7240
7241    let worker_count = fp_columnar::cached_available_parallelism()
7242        .min(64)
7243        .min(jobs.len().max(1));
7244    let computed: Vec<Result<Column, JoinError>> = if worker_count >= 2 && jobs.len() >= 2 {
7245        let next = std::sync::atomic::AtomicUsize::new(0);
7246        let jobs_ref = &jobs;
7247        let compute_ref = &compute;
7248        let mut slots: Vec<Option<Result<Column, JoinError>>> =
7249            (0..jobs.len()).map(|_| None).collect();
7250        let parts = std::thread::scope(|scope| {
7251            let mut handles = Vec::with_capacity(worker_count);
7252            for _ in 0..worker_count {
7253                let next = &next;
7254                handles.push(scope.spawn(move || {
7255                    let mut out: Vec<(usize, Result<Column, JoinError>)> = Vec::new();
7256                    loop {
7257                        let i = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7258                        if i >= jobs_ref.len() {
7259                            break;
7260                        }
7261                        out.push((i, compute_ref(&jobs_ref[i].1)));
7262                    }
7263                    out
7264                }));
7265            }
7266            handles
7267                .into_iter()
7268                .map(|h| h.join().expect("join assembly worker panicked"))
7269                .collect::<Vec<_>>()
7270        });
7271        for part in parts {
7272            for (i, r) in part {
7273                slots[i] = Some(r);
7274            }
7275        }
7276        slots
7277            .into_iter()
7278            .map(|s| s.expect("every output column computed"))
7279            .collect()
7280    } else {
7281        jobs.iter().map(|(_, spec)| compute(spec)).collect()
7282    };
7283
7284    for ((out_name, _), col_res) in jobs.into_iter().zip(computed) {
7285        insert_merged_output_column(&mut columns, &mut column_order, out_name, col_res?)?;
7286    }
7287
7288    Ok(MergedDataFrame {
7289        index,
7290        columns,
7291        column_order,
7292    })
7293}
7294
7295fn build_single_key_ordered_identity_inner_merge_output(
7296    left: &fp_frame::DataFrame,
7297    right: &fp_frame::DataFrame,
7298    left_on: &[&str],
7299    right_on: &[&str],
7300    suffixes: &ResolvedMergeSuffixes,
7301) -> Result<MergedDataFrame, JoinError> {
7302    debug_assert_eq!(left_on.len(), 1);
7303    debug_assert_eq!(right_on.len(), 1);
7304    debug_assert_eq!(left_on[0], right_on[0]);
7305
7306    let n = left.len();
7307    debug_assert_eq!(n, right.len());
7308    // Lazy unit-range output index (see build_single_key_dense_i64 site).
7309    let index = Index::new_known_unique_int64_unit_range(0, n);
7310    let mut columns = ColumnStore::new();
7311    let mut column_order: Vec<String> = Vec::new();
7312    let mut identity_positions = None;
7313
7314    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
7315    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
7316    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
7317    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
7318    let shared_key_names = left_on.iter().copied().collect::<HashSet<&str>>();
7319    let overlapping_names =
7320        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
7321    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
7322
7323    for name in left.column_names() {
7324        let col = left
7325            .columns()
7326            .get(name)
7327            .expect("left column listed in column_names must exist");
7328        let out_name = if left_key_name_set.contains(name.as_str()) {
7329            name.clone()
7330        } else if right_col_names.contains(name) {
7331            apply_merge_suffix(name, suffixes.left.as_deref())
7332        } else {
7333            name.clone()
7334        };
7335        let output = identity_merge_column(col, n, &mut identity_positions);
7336        insert_merged_output_column(&mut columns, &mut column_order, out_name, output)?;
7337    }
7338
7339    for name in right.column_names() {
7340        if right_key_name_set.contains(name.as_str()) {
7341            continue;
7342        }
7343
7344        let col = right
7345            .columns()
7346            .get(name)
7347            .expect("right column listed in column_names must exist");
7348        let out_name = if left_col_names.contains(name) {
7349            apply_merge_suffix(name, suffixes.right.as_deref())
7350        } else {
7351            name.clone()
7352        };
7353        let output = identity_merge_column(col, n, &mut identity_positions);
7354        insert_merged_output_column(&mut columns, &mut column_order, out_name, output)?;
7355    }
7356
7357    Ok(MergedDataFrame {
7358        index,
7359        columns,
7360        column_order,
7361    })
7362}
7363
7364/// Hash-free inner-join position build for two all-valid, bounded-range Int64
7365/// key columns. Replaces the `FxHashMap<&JoinKeyComponent, _>` build+probe with
7366/// a counting-sort / CSR direct-address table indexed by `key - min`.
7367///
7368/// Bit-identical to the hash path's emitted `(left_pos, right_pos)` pairs: the
7369/// hash path buckets right positions in *insertion* order (ascending position),
7370/// and this CSR fill also writes right positions in ascending-position order,
7371/// so for every left row the matched right rows are emitted in the same order;
7372/// left rows are still probed in ascending order. All-valid Int64 keys map to
7373/// `Present(IndexLabel::Int64(v))` in the hash path, whose equality is plain
7374/// `i64 ==`, so membership/equality semantics are identical. A left key outside
7375/// the right key span matches nothing in either path. Returns `None` (caller
7376/// falls back to the hash path) for non-Int64, any-missing, or wide-span keys.
7377fn dense_int64_inner_positions(
7378    left_key: &Column,
7379    right_key: &Column,
7380) -> Option<(Vec<usize>, Vec<usize>)> {
7381    let left = left_key.as_i64_slice()?;
7382    let right = right_key.as_i64_slice()?;
7383    dense_i64_inner_positions_slices(left, right)
7384}
7385
7386/// Typed single-key INNER positions for all-valid temporal columns. Datetime64
7387/// and Timedelta64 both store exact nanoseconds in `i64`; matching those raw
7388/// values is identical to matching their same-variant `IndexLabel` wrappers.
7389///
7390/// The fast path requires equal temporal dtypes and rejects NaT explicitly.
7391/// Ordered inputs validate each newly reached value while intersecting, instead
7392/// of pre-scanning both slices for NaT and strict ordering. Nullable keys
7393/// therefore fall through to the Scalar oracle, preserving its Missing-to-
7394/// Missing join behavior. Output construction still gathers the original
7395/// temporal key column, so dtype and value representation are kept.
7396fn temporal_i64_inner_positions(
7397    left_key: &Column,
7398    right_key: &Column,
7399) -> Option<(Vec<usize>, Vec<usize>)> {
7400    if !left_key.validity().all() || !right_key.validity().all() {
7401        return None;
7402    }
7403
7404    let (left, right, nat) = match (left_key.dtype(), right_key.dtype()) {
7405        (DType::Datetime64 { tz: left_tz }, DType::Datetime64 { tz: right_tz })
7406            if left_tz == right_tz =>
7407        {
7408            (
7409                left_key.as_datetime64_slice()?,
7410                right_key.as_datetime64_slice()?,
7411                fp_types::Timestamp::NAT,
7412            )
7413        }
7414        (DType::Timedelta64, DType::Timedelta64) => (
7415            left_key.as_timedelta64_slice()?,
7416            right_key.as_timedelta64_slice()?,
7417            fp_types::Timedelta::NAT,
7418        ),
7419        _ => return None,
7420    };
7421    let mut left_positions = Vec::with_capacity(left.len().min(right.len()));
7422    let mut right_positions = Vec::with_capacity(left_positions.capacity());
7423    let (mut left_idx, mut right_idx) = (0usize, 0usize);
7424    let mut ordered = newly_reached_temporal_i64_value_is_strict(left, 0, nat)
7425        && newly_reached_temporal_i64_value_is_strict(right, 0, nat);
7426    while ordered && left_idx < left.len() && right_idx < right.len() {
7427        match left[left_idx].cmp(&right[right_idx]) {
7428            Ordering::Equal => {
7429                left_positions.push(left_idx);
7430                right_positions.push(right_idx);
7431                left_idx += 1;
7432                right_idx += 1;
7433                ordered = newly_reached_temporal_i64_value_is_strict(left, left_idx, nat)
7434                    && newly_reached_temporal_i64_value_is_strict(right, right_idx, nat);
7435            }
7436            Ordering::Less => {
7437                left_idx += 1;
7438                ordered = newly_reached_temporal_i64_value_is_strict(left, left_idx, nat);
7439            }
7440            Ordering::Greater => {
7441                right_idx += 1;
7442                ordered = newly_reached_temporal_i64_value_is_strict(right, right_idx, nat);
7443            }
7444        }
7445    }
7446    while ordered && left_idx < left.len() {
7447        left_idx += 1;
7448        ordered = newly_reached_temporal_i64_value_is_strict(left, left_idx, nat);
7449    }
7450    while ordered && right_idx < right.len() {
7451        right_idx += 1;
7452        ordered = newly_reached_temporal_i64_value_is_strict(right, right_idx, nat);
7453    }
7454    if ordered {
7455        return Some((left_positions, right_positions));
7456    }
7457
7458    if left.contains(&nat) || right.contains(&nat) {
7459        return None;
7460    }
7461
7462    dense_i64_inner_positions_slices(left, right)
7463        .or_else(|| Some(hash_i64_inner_positions_slices(left, right)))
7464}
7465
7466/// Typed single-key LEFT positions for all-valid temporal columns. The ordered
7467/// unique case uses a two-pointer match scan; remaining shapes hash the raw
7468/// nanoseconds. Both emit left-major rows and ascending right positions per
7469/// key, exactly matching the generic Scalar planner. Nullable keys and NaT
7470/// retain that planner's Missing-key behavior by declining this path.
7471fn temporal_i64_left_positions(
7472    left_key: &Column,
7473    right_key: &Column,
7474) -> Option<OptionalJoinPositions> {
7475    if !left_key.validity().all() || !right_key.validity().all() {
7476        return None;
7477    }
7478
7479    let (left, right, nat) = match (left_key.dtype(), right_key.dtype()) {
7480        (DType::Datetime64 { tz: left_tz }, DType::Datetime64 { tz: right_tz })
7481            if left_tz == right_tz =>
7482        {
7483            (
7484                left_key.as_datetime64_slice()?,
7485                right_key.as_datetime64_slice()?,
7486                fp_types::Timestamp::NAT,
7487            )
7488        }
7489        (DType::Timedelta64, DType::Timedelta64) => (
7490            left_key.as_timedelta64_slice()?,
7491            right_key.as_timedelta64_slice()?,
7492            fp_types::Timedelta::NAT,
7493        ),
7494        _ => return None,
7495    };
7496    if left.contains(&nat) || right.contains(&nat) {
7497        return None;
7498    }
7499
7500    if left.windows(2).all(|pair| pair[0] < pair[1])
7501        && right.windows(2).all(|pair| pair[0] < pair[1])
7502    {
7503        let left_positions = (0..left.len()).map(Some).collect::<Vec<_>>();
7504        let mut right_positions = Vec::with_capacity(left.len());
7505        let mut right_idx = 0usize;
7506        for &left_value in left {
7507            while right_idx < right.len() && right[right_idx] < left_value {
7508                right_idx += 1;
7509            }
7510            right_positions.push(
7511                (right_idx < right.len()
7512                    && matches!(right[right_idx].cmp(&left_value), Ordering::Equal))
7513                .then_some(right_idx),
7514            );
7515        }
7516        return Some((left_positions, right_positions));
7517    }
7518
7519    if right.is_empty() {
7520        return Some(((0..left.len()).map(Some).collect(), vec![None; left.len()]));
7521    }
7522    let mut right_map = FxHashMap::<i64, JoinPositionBucket>::with_capacity_and_hasher(
7523        right.len(),
7524        Default::default(),
7525    );
7526    for (pos, &key) in right.iter().enumerate() {
7527        right_map.entry(key).or_default().push(pos);
7528    }
7529    let mut left_positions = Vec::<Option<usize>>::with_capacity(left.len());
7530    let mut right_positions = Vec::<Option<usize>>::with_capacity(left.len());
7531    for (left_pos, &key) in left.iter().enumerate() {
7532        if let Some(matches) = right_map.get(&key) {
7533            for &right_pos in matches {
7534                left_positions.push(Some(left_pos));
7535                right_positions.push(Some(right_pos));
7536            }
7537        } else {
7538            left_positions.push(Some(left_pos));
7539            right_positions.push(None);
7540        }
7541    }
7542    Some((left_positions, right_positions))
7543}
7544
7545#[inline]
7546fn newly_reached_temporal_i64_value_is_strict(values: &[i64], idx: usize, nat: i64) -> bool {
7547    let Some(&value) = values.get(idx) else {
7548        return true;
7549    };
7550    value != nat && (idx == 0 || values[idx - 1] < value)
7551}
7552
7553/// Ordered-unique single-key RIGHT matches for all-valid temporal columns.
7554/// Datetime64 and Timedelta64 both store exact nanoseconds in `i64`, so a
7555/// monotone two-pointer scan produces the same optional left position per
7556/// right row as the generic Scalar planner without materializing either key.
7557/// Each newly reached value is validated for NaT and strict ordering during
7558/// that scan, avoiding separate input pre-scans. Nullable, NaT-bearing,
7559/// duplicate, unsorted, or mixed-dtype keys decline.
7560fn ordered_unique_temporal_i64_right_match_positions(
7561    left_key: &Column,
7562    right_key: &Column,
7563) -> Option<Vec<Option<usize>>> {
7564    if !left_key.validity().all() || !right_key.validity().all() {
7565        return None;
7566    }
7567
7568    let (left, right, nat) = match (left_key.dtype(), right_key.dtype()) {
7569        (DType::Datetime64 { tz: left_tz }, DType::Datetime64 { tz: right_tz })
7570            if left_tz == right_tz =>
7571        {
7572            (
7573                left_key.as_datetime64_slice()?,
7574                right_key.as_datetime64_slice()?,
7575                fp_types::Timestamp::NAT,
7576            )
7577        }
7578        (DType::Timedelta64, DType::Timedelta64) => (
7579            left_key.as_timedelta64_slice()?,
7580            right_key.as_timedelta64_slice()?,
7581            fp_types::Timedelta::NAT,
7582        ),
7583        _ => return None,
7584    };
7585    if !newly_reached_temporal_i64_value_is_strict(left, 0, nat) {
7586        return None;
7587    }
7588
7589    let mut left_positions = Vec::with_capacity(right.len());
7590    let mut left_idx = 0usize;
7591    for (right_idx, &right_value) in right.iter().enumerate() {
7592        if !newly_reached_temporal_i64_value_is_strict(right, right_idx, nat) {
7593            return None;
7594        }
7595        while left_idx < left.len() && left[left_idx] < right_value {
7596            left_idx += 1;
7597            if !newly_reached_temporal_i64_value_is_strict(left, left_idx, nat) {
7598                return None;
7599            }
7600        }
7601        left_positions.push(
7602            (left_idx < left.len() && matches!(left[left_idx].cmp(&right_value), Ordering::Equal))
7603                .then_some(left_idx),
7604        );
7605    }
7606    while left_idx < left.len() {
7607        left_idx += 1;
7608        if !newly_reached_temporal_i64_value_is_strict(left, left_idx, nat) {
7609            return None;
7610        }
7611    }
7612    Some(left_positions)
7613}
7614
7615/// Ordered-unique single-key OUTER union for all-valid temporal columns.
7616/// Datetime64 and Timedelta64 ordering is their raw nanosecond ordering, so a
7617/// three-way merge produces the same key-sorted optional position tapes as the
7618/// generic Scalar planner without materializing either input key for position
7619/// planning. Each newly reached value is validated for NaT and strict ordering
7620/// inside that merge, avoiding separate input pre-scans. Nullable, NaT-bearing,
7621/// duplicate, unsorted, or mixed-dtype keys decline.
7622fn ordered_unique_temporal_i64_outer_positions(
7623    left_key: &Column,
7624    right_key: &Column,
7625) -> Option<OptionalJoinPositions> {
7626    if !left_key.validity().all() || !right_key.validity().all() {
7627        return None;
7628    }
7629
7630    let (left, right, nat) = match (left_key.dtype(), right_key.dtype()) {
7631        (DType::Datetime64 { tz: left_tz }, DType::Datetime64 { tz: right_tz })
7632            if left_tz == right_tz =>
7633        {
7634            (
7635                left_key.as_datetime64_slice()?,
7636                right_key.as_datetime64_slice()?,
7637                fp_types::Timestamp::NAT,
7638            )
7639        }
7640        (DType::Timedelta64, DType::Timedelta64) => (
7641            left_key.as_timedelta64_slice()?,
7642            right_key.as_timedelta64_slice()?,
7643            fp_types::Timedelta::NAT,
7644        ),
7645        _ => return None,
7646    };
7647    if !newly_reached_temporal_i64_value_is_strict(left, 0, nat)
7648        || !newly_reached_temporal_i64_value_is_strict(right, 0, nat)
7649    {
7650        return None;
7651    }
7652
7653    let capacity = left.len().saturating_add(right.len());
7654    let mut left_positions = Vec::<Option<usize>>::with_capacity(capacity);
7655    let mut right_positions = Vec::<Option<usize>>::with_capacity(capacity);
7656    let (mut left_idx, mut right_idx) = (0usize, 0usize);
7657    while left_idx < left.len() && right_idx < right.len() {
7658        match left[left_idx].cmp(&right[right_idx]) {
7659            Ordering::Equal => {
7660                left_positions.push(Some(left_idx));
7661                right_positions.push(Some(right_idx));
7662                left_idx += 1;
7663                right_idx += 1;
7664                if !newly_reached_temporal_i64_value_is_strict(left, left_idx, nat)
7665                    || !newly_reached_temporal_i64_value_is_strict(right, right_idx, nat)
7666                {
7667                    return None;
7668                }
7669            }
7670            Ordering::Less => {
7671                left_positions.push(Some(left_idx));
7672                right_positions.push(None);
7673                left_idx += 1;
7674                if !newly_reached_temporal_i64_value_is_strict(left, left_idx, nat) {
7675                    return None;
7676                }
7677            }
7678            Ordering::Greater => {
7679                left_positions.push(None);
7680                right_positions.push(Some(right_idx));
7681                right_idx += 1;
7682                if !newly_reached_temporal_i64_value_is_strict(right, right_idx, nat) {
7683                    return None;
7684                }
7685            }
7686        }
7687    }
7688    while left_idx < left.len() {
7689        left_positions.push(Some(left_idx));
7690        right_positions.push(None);
7691        left_idx += 1;
7692        if !newly_reached_temporal_i64_value_is_strict(left, left_idx, nat) {
7693            return None;
7694        }
7695    }
7696    while right_idx < right.len() {
7697        left_positions.push(None);
7698        right_positions.push(Some(right_idx));
7699        right_idx += 1;
7700        if !newly_reached_temporal_i64_value_is_strict(right, right_idx, nat) {
7701            return None;
7702        }
7703    }
7704    Some((left_positions, right_positions))
7705}
7706
7707/// Core counting-sort/CSR inner-join over two `i64` key slices (see
7708/// [`dense_int64_inner_positions`]). Emits `(left_pos, right_pos)` pairs with
7709/// right positions ascending per left key, left probed ascending — matching the
7710/// hash path's bucket-insertion order. Returns `None` for a span wider than the
7711/// bounded direct-address gate so the caller falls back to hashing.
7712fn dense_i64_inner_positions_slices(
7713    left: &[i64],
7714    right: &[i64],
7715) -> Option<(Vec<usize>, Vec<usize>)> {
7716    if right.is_empty() || left.is_empty() {
7717        return Some((Vec::new(), Vec::new()));
7718    }
7719
7720    let mut min = right[0];
7721    let mut max = right[0];
7722    for &v in right {
7723        if v < min {
7724            min = v;
7725        }
7726        if v > max {
7727            max = v;
7728        }
7729    }
7730    // Bounded-span gate (mirrors the fp-columnar direct-address tally gates):
7731    // the dense table costs O(span) memory, so only take it when the span is
7732    // small in absolute terms AND relative to the build (right) side.
7733    let span = (max as i128) - (min as i128) + 1;
7734    if span > (1i128 << 24) || span > 16 * (right.len() as i128) {
7735        return None;
7736    }
7737    let range = span as usize;
7738
7739    // CSR build over the right side: counts -> exclusive-prefix offsets ->
7740    // positions filled in ascending right-position order.
7741    let mut offsets = vec![0usize; range + 1];
7742    for &v in right {
7743        offsets[(v - min) as usize + 1] += 1;
7744    }
7745    for i in 0..range {
7746        offsets[i + 1] += offsets[i];
7747    }
7748    let mut positions = vec![0usize; right.len()];
7749    let mut cursor = offsets.clone();
7750    for (pos, &v) in right.iter().enumerate() {
7751        let bucket = (v - min) as usize;
7752        positions[cursor[bucket]] = pos;
7753        cursor[bucket] += 1;
7754    }
7755
7756    let mut left_positions = Vec::<usize>::with_capacity(left.len().min(right.len()));
7757    let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
7758    for (left_pos, &v) in left.iter().enumerate() {
7759        if v < min || v > max {
7760            continue;
7761        }
7762        let bucket = (v - min) as usize;
7763        for &right_pos in &positions[offsets[bucket]..offsets[bucket + 1]] {
7764            left_positions.push(left_pos);
7765            right_positions.push(right_pos);
7766        }
7767    }
7768    Some((left_positions, right_positions))
7769}
7770
7771/// Hash inner-join position build for the remaining all-valid Int64 single-key
7772/// shape after ordered/dense witnesses reject. This keeps the generic hash
7773/// path's left-major probe order and right-bucket insertion order, but hashes
7774/// raw `i64` keys instead of materializing `JoinKeyComponent::Present` wrappers.
7775fn hash_int64_inner_positions(
7776    left_key: &Column,
7777    right_key: &Column,
7778) -> Option<(Vec<usize>, Vec<usize>)> {
7779    let left = left_key.as_i64_slice()?;
7780    let right = right_key.as_i64_slice()?;
7781    Some(hash_i64_inner_positions_slices(left, right))
7782}
7783
7784/// LEFT-join positions via a typed `FxHashMap<i64>` build+probe for all-valid
7785/// Int64 keys — the wide/sparse sibling of `dense_int64_left_positions` (whose
7786/// direct-address table bails on a wide key span, dropping the join to the
7787/// generic `JoinKeyComponent` Scalar-materialization path: left merge on a
7788/// wide-i64 key was 0.65x pandas). Build the right key -> ascending-position
7789/// buckets, then emit one output row per (left row, matching right row) in left
7790/// order, or a single (left, None) for an unmatched left row (null-fill).
7791/// Bit-identical to the dense/generic left path: same left iteration order, same
7792/// ascending right positions per key bucket. `None` (falls back) unless BOTH keys
7793/// are all-valid Int64 (a null-bearing key keeps the generic null-matching path).
7794fn hash_int64_left_positions(
7795    left_key: &Column,
7796    right_key: &Column,
7797) -> Option<OptionalJoinPositions> {
7798    let left = left_key.as_i64_slice()?;
7799    let right = right_key.as_i64_slice()?;
7800    if right.is_empty() {
7801        let left_positions = (0..left.len()).map(Some).collect::<Vec<_>>();
7802        let right_positions = vec![None; left.len()];
7803        return Some((left_positions, right_positions));
7804    }
7805    let mut right_map = FxHashMap::<i64, JoinPositionBucket>::with_capacity_and_hasher(
7806        right.len(),
7807        Default::default(),
7808    );
7809    for (pos, &key) in right.iter().enumerate() {
7810        right_map.entry(key).or_default().push(pos);
7811    }
7812    let mut left_positions = Vec::<Option<usize>>::with_capacity(left.len());
7813    let mut right_positions = Vec::<Option<usize>>::with_capacity(left.len());
7814    for (left_pos, &key) in left.iter().enumerate() {
7815        if let Some(matches) = right_map.get(&key) {
7816            for &right_pos in matches {
7817                left_positions.push(Some(left_pos));
7818                right_positions.push(Some(right_pos));
7819            }
7820        } else {
7821            left_positions.push(Some(left_pos));
7822            right_positions.push(None);
7823        }
7824    }
7825    Some((left_positions, right_positions))
7826}
7827
7828/// OUTER positions for wide/sparse Int64 keys. Uses a LIGHT `FxHashMap<i64,u32>`
7829/// key -> gid (first-seen) plus CSR position lists per gid — far cheaper than a
7830/// `FxHashMap<i64,(SmallVec,SmallVec)>` (whose 40-byte value dominated the build
7831/// at ~270ms). Emits per key ASCENDING (gids argsorted by key), left×right cross
7832/// product per key, else unmatched-left/right — bit-identical to
7833/// `dense_int64_outer_positions` (its key-min buckets walk keys ascending with
7834/// the same per-bucket order; the CSR scatter preserves ascending row order per
7835/// key, matching the dense per-bucket push order).
7836fn hash_int64_outer_positions(
7837    left_key: &Column,
7838    right_key: &Column,
7839) -> Option<OptionalJoinPositions> {
7840    let left = left_key.as_i64_slice()?;
7841    let right = right_key.as_i64_slice()?;
7842    let mut gid_of: FxHashMap<i64, u32> = FxHashMap::with_capacity_and_hasher(
7843        left.len().saturating_add(right.len()),
7844        Default::default(),
7845    );
7846    let mut gid_keys: Vec<i64> = Vec::new();
7847    let mut left_gid: Vec<u32> = Vec::with_capacity(left.len());
7848    for &key in left {
7849        let g = *gid_of.entry(key).or_insert_with(|| {
7850            let x = gid_keys.len() as u32;
7851            gid_keys.push(key);
7852            x
7853        });
7854        left_gid.push(g);
7855    }
7856    let mut right_gid: Vec<u32> = Vec::with_capacity(right.len());
7857    for &key in right {
7858        let g = *gid_of.entry(key).or_insert_with(|| {
7859            let x = gid_keys.len() as u32;
7860            gid_keys.push(key);
7861            x
7862        });
7863        right_gid.push(g);
7864    }
7865    let ng = gid_keys.len();
7866    // CSR offsets from per-gid counts.
7867    let mut loff = vec![0u32; ng + 1];
7868    for &g in &left_gid {
7869        loff[g as usize + 1] += 1;
7870    }
7871    let mut roff = vec![0u32; ng + 1];
7872    for &g in &right_gid {
7873        roff[g as usize + 1] += 1;
7874    }
7875    for g in 0..ng {
7876        loff[g + 1] += loff[g];
7877        roff[g + 1] += roff[g];
7878    }
7879    let mut lpos = vec![0u32; left.len()];
7880    let mut lw = loff[..ng].to_vec();
7881    for (i, &g) in left_gid.iter().enumerate() {
7882        let g = g as usize;
7883        lpos[lw[g] as usize] = i as u32;
7884        lw[g] += 1;
7885    }
7886    let mut rpos = vec![0u32; right.len()];
7887    let mut rw = roff[..ng].to_vec();
7888    for (i, &g) in right_gid.iter().enumerate() {
7889        let g = g as usize;
7890        rpos[rw[g] as usize] = i as u32;
7891        rw[g] += 1;
7892    }
7893    let mut order: Vec<u32> = (0..ng as u32).collect();
7894    order.sort_unstable_by_key(|&g| gid_keys[g as usize]);
7895    let mut left_positions = Vec::<Option<usize>>::new();
7896    let mut right_positions = Vec::<Option<usize>>::new();
7897    for &g in &order {
7898        let g = g as usize;
7899        let ls = &lpos[loff[g] as usize..loff[g + 1] as usize];
7900        let rs = &rpos[roff[g] as usize..roff[g + 1] as usize];
7901        match (ls.is_empty(), rs.is_empty()) {
7902            (false, false) => {
7903                for &l in ls {
7904                    for &r in rs {
7905                        left_positions.push(Some(l as usize));
7906                        right_positions.push(Some(r as usize));
7907                    }
7908                }
7909            }
7910            (false, true) => {
7911                for &l in ls {
7912                    left_positions.push(Some(l as usize));
7913                    right_positions.push(None);
7914                }
7915            }
7916            (true, false) => {
7917                for &r in rs {
7918                    left_positions.push(None);
7919                    right_positions.push(Some(r as usize));
7920                }
7921            }
7922            (true, true) => {}
7923        }
7924    }
7925    Some((left_positions, right_positions))
7926}
7927
7928/// Hash build+probe over raw UTF-8 byte spans for all-valid contiguous-Utf8
7929/// keys (br-frankenpandas-i388q). Mirrors the generic `JoinKeyComponent` inner
7930/// path exactly — right positions pushed ascending per key bucket, left probed
7931/// in order — but hashes `&[u8]` spans directly instead of materializing each
7932/// key column to `Vec<Scalar>` and cloning every string into a
7933/// `JoinKeyComponent::Present(IndexLabel::Utf8)` wrapper. Returns `None` unless
7934/// BOTH keys are all-valid contiguous Utf8; null-bearing keys keep the generic
7935/// path (which matches null-to-null — a case `as_utf8_contiguous` excludes).
7936fn contiguous_utf8_inner_positions(
7937    left_key: &Column,
7938    right_key: &Column,
7939) -> Option<(Vec<usize>, Vec<usize>)> {
7940    let (left_bytes, left_offsets) = left_key.as_utf8_contiguous()?;
7941    let (right_bytes, right_offsets) = right_key.as_utf8_contiguous()?;
7942    let left_n = left_offsets.len() - 1;
7943    let right_n = right_offsets.len() - 1;
7944    if left_n == 0 || right_n == 0 {
7945        return Some((Vec::new(), Vec::new()));
7946    }
7947
7948    if let Some(positions) =
7949        sorted_contiguous_utf8_inner_positions(left_bytes, left_offsets, right_bytes, right_offsets)
7950    {
7951        return Some(positions);
7952    }
7953
7954    let mut right_map = FxHashMap::<&[u8], JoinPositionBucket>::with_capacity_and_hasher(
7955        right_n,
7956        Default::default(),
7957    );
7958    for pos in 0..right_n {
7959        let span = &right_bytes[right_offsets[pos]..right_offsets[pos + 1]];
7960        right_map.entry(span).or_default().push(pos);
7961    }
7962
7963    let mut left_positions = Vec::<usize>::with_capacity(left_n.min(right_n));
7964    let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
7965    for left_pos in 0..left_n {
7966        let span = &left_bytes[left_offsets[left_pos]..left_offsets[left_pos + 1]];
7967        if let Some(matches) = right_map.get(span) {
7968            for &right_pos in matches {
7969                left_positions.push(left_pos);
7970                right_positions.push(right_pos);
7971            }
7972        }
7973    }
7974    Some((left_positions, right_positions))
7975}
7976
7977fn collect_contiguous_utf8_position_map<'a>(
7978    bytes: &'a [u8],
7979    offsets: &[usize],
7980) -> FxHashMap<&'a [u8], JoinPositionBucket> {
7981    let n = offsets.len() - 1;
7982    let mut map =
7983        FxHashMap::<&[u8], JoinPositionBucket>::with_capacity_and_hasher(n, Default::default());
7984    for pos in 0..n {
7985        let span = &bytes[offsets[pos]..offsets[pos + 1]];
7986        map.entry(span).or_default().push(pos);
7987    }
7988    map
7989}
7990
7991fn contiguous_utf8_left_positions(
7992    left_key: &Column,
7993    right_key: &Column,
7994) -> Option<OptionalJoinPositions> {
7995    let (left_bytes, left_offsets) = left_key.as_utf8_contiguous()?;
7996    let (right_bytes, right_offsets) = right_key.as_utf8_contiguous()?;
7997    let left_n = left_offsets.len() - 1;
7998    let right_map = collect_contiguous_utf8_position_map(right_bytes, right_offsets);
7999
8000    let mut out_len = 0usize;
8001    for left_pos in 0..left_n {
8002        let span = &left_bytes[left_offsets[left_pos]..left_offsets[left_pos + 1]];
8003        out_len += right_map.get(span).map_or(1, JoinPositionBucket::len);
8004    }
8005
8006    let mut left_positions = Vec::<Option<usize>>::with_capacity(out_len);
8007    let mut right_positions = Vec::<Option<usize>>::with_capacity(out_len);
8008    for left_pos in 0..left_n {
8009        let span = &left_bytes[left_offsets[left_pos]..left_offsets[left_pos + 1]];
8010        if let Some(matches) = right_map.get(span) {
8011            for &right_pos in matches {
8012                left_positions.push(Some(left_pos));
8013                right_positions.push(Some(right_pos));
8014            }
8015        } else {
8016            left_positions.push(Some(left_pos));
8017            right_positions.push(None);
8018        }
8019    }
8020    Some((left_positions, right_positions))
8021}
8022
8023fn contiguous_utf8_outer_positions(
8024    left_key: &Column,
8025    right_key: &Column,
8026) -> Option<OptionalJoinPositions> {
8027    let (left_bytes, left_offsets) = left_key.as_utf8_contiguous()?;
8028    let (right_bytes, right_offsets) = right_key.as_utf8_contiguous()?;
8029    let left_n = left_offsets.len() - 1;
8030    let right_n = right_offsets.len() - 1;
8031
8032    let left_map = collect_contiguous_utf8_position_map(left_bytes, left_offsets);
8033    let right_map = collect_contiguous_utf8_position_map(right_bytes, right_offsets);
8034    let mut seen = FxHashSet::<&[u8]>::with_capacity_and_hasher(
8035        left_map.len() + right_map.len(),
8036        Default::default(),
8037    );
8038    let mut keys = Vec::<&[u8]>::with_capacity(left_map.len() + right_map.len());
8039    for pos in 0..left_n {
8040        let span = &left_bytes[left_offsets[pos]..left_offsets[pos + 1]];
8041        if seen.insert(span) {
8042            keys.push(span);
8043        }
8044    }
8045    for pos in 0..right_n {
8046        let span = &right_bytes[right_offsets[pos]..right_offsets[pos + 1]];
8047        if seen.insert(span) {
8048            keys.push(span);
8049        }
8050    }
8051    keys.sort_unstable();
8052
8053    let mut out_len = 0usize;
8054    for &key in &keys {
8055        out_len += match (left_map.get(key), right_map.get(key)) {
8056            (Some(lefts), Some(rights)) => lefts.len() * rights.len(),
8057            (Some(lefts), None) => lefts.len(),
8058            (None, Some(rights)) => rights.len(),
8059            (None, None) => 0,
8060        };
8061    }
8062
8063    let mut left_positions = Vec::<Option<usize>>::with_capacity(out_len);
8064    let mut right_positions = Vec::<Option<usize>>::with_capacity(out_len);
8065    for key in keys {
8066        match (left_map.get(key), right_map.get(key)) {
8067            (Some(lefts), Some(rights)) => {
8068                for &left_pos in lefts {
8069                    for &right_pos in rights {
8070                        left_positions.push(Some(left_pos));
8071                        right_positions.push(Some(right_pos));
8072                    }
8073                }
8074            }
8075            (Some(lefts), None) => {
8076                for &left_pos in lefts {
8077                    left_positions.push(Some(left_pos));
8078                    right_positions.push(None);
8079                }
8080            }
8081            (None, Some(rights)) => {
8082                for &right_pos in rights {
8083                    left_positions.push(None);
8084                    right_positions.push(Some(right_pos));
8085                }
8086            }
8087            (None, None) => {}
8088        }
8089    }
8090    Some((left_positions, right_positions))
8091}
8092
8093fn scalar_utf8_values(column: &Column) -> Option<&[Scalar]> {
8094    if column.dtype() != DType::Utf8 || !column.validity().all() {
8095        return None;
8096    }
8097    let values = column.values();
8098    values
8099        .iter()
8100        .all(|value| matches!(value, Scalar::Utf8(_)))
8101        .then_some(values)
8102}
8103
8104fn scalar_utf8_span(value: &Scalar) -> Option<&[u8]> {
8105    match value {
8106        Scalar::Utf8(value) => Some(value.as_bytes()),
8107        _ => None,
8108    }
8109}
8110
8111fn collect_scalar_utf8_position_map(
8112    values: &[Scalar],
8113) -> Option<FxHashMap<&[u8], JoinPositionBucket>> {
8114    let mut map = FxHashMap::<&[u8], JoinPositionBucket>::with_capacity_and_hasher(
8115        values.len(),
8116        Default::default(),
8117    );
8118    for (pos, value) in values.iter().enumerate() {
8119        map.entry(scalar_utf8_span(value)?).or_default().push(pos);
8120    }
8121    Some(map)
8122}
8123
8124fn scalar_utf8_inner_positions(
8125    left_key: &Column,
8126    right_key: &Column,
8127) -> Option<(Vec<usize>, Vec<usize>)> {
8128    let left = scalar_utf8_values(left_key)?;
8129    let right = scalar_utf8_values(right_key)?;
8130    if left.is_empty() || right.is_empty() {
8131        return Some((Vec::new(), Vec::new()));
8132    }
8133
8134    let right_map = collect_scalar_utf8_position_map(right)?;
8135    let mut left_positions = Vec::<usize>::with_capacity(left.len().min(right.len()));
8136    let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
8137    for (left_pos, value) in left.iter().enumerate() {
8138        if let Some(matches) = right_map.get(scalar_utf8_span(value)?) {
8139            for &right_pos in matches {
8140                left_positions.push(left_pos);
8141                right_positions.push(right_pos);
8142            }
8143        }
8144    }
8145    Some((left_positions, right_positions))
8146}
8147
8148fn scalar_utf8_left_positions(
8149    left_key: &Column,
8150    right_key: &Column,
8151) -> Option<OptionalJoinPositions> {
8152    let left = scalar_utf8_values(left_key)?;
8153    let right = scalar_utf8_values(right_key)?;
8154    let right_map = collect_scalar_utf8_position_map(right)?;
8155
8156    let mut out_len = 0usize;
8157    for value in left {
8158        out_len += right_map
8159            .get(scalar_utf8_span(value)?)
8160            .map_or(1, JoinPositionBucket::len);
8161    }
8162
8163    let mut left_positions = Vec::<Option<usize>>::with_capacity(out_len);
8164    let mut right_positions = Vec::<Option<usize>>::with_capacity(out_len);
8165    for (left_pos, value) in left.iter().enumerate() {
8166        if let Some(matches) = right_map.get(scalar_utf8_span(value)?) {
8167            for &right_pos in matches {
8168                left_positions.push(Some(left_pos));
8169                right_positions.push(Some(right_pos));
8170            }
8171        } else {
8172            left_positions.push(Some(left_pos));
8173            right_positions.push(None);
8174        }
8175    }
8176    Some((left_positions, right_positions))
8177}
8178
8179fn scalar_utf8_outer_positions(
8180    left_key: &Column,
8181    right_key: &Column,
8182) -> Option<OptionalJoinPositions> {
8183    let left = scalar_utf8_values(left_key)?;
8184    let right = scalar_utf8_values(right_key)?;
8185    let left_map = collect_scalar_utf8_position_map(left)?;
8186    let right_map = collect_scalar_utf8_position_map(right)?;
8187
8188    let mut seen = FxHashSet::<&[u8]>::with_capacity_and_hasher(
8189        left_map.len() + right_map.len(),
8190        Default::default(),
8191    );
8192    let mut keys = Vec::<&[u8]>::with_capacity(left_map.len() + right_map.len());
8193    for value in left {
8194        let span = scalar_utf8_span(value)?;
8195        if seen.insert(span) {
8196            keys.push(span);
8197        }
8198    }
8199    for value in right {
8200        let span = scalar_utf8_span(value)?;
8201        if seen.insert(span) {
8202            keys.push(span);
8203        }
8204    }
8205    keys.sort_unstable();
8206
8207    let mut out_len = 0usize;
8208    for &key in &keys {
8209        out_len += match (left_map.get(key), right_map.get(key)) {
8210            (Some(lefts), Some(rights)) => lefts.len() * rights.len(),
8211            (Some(lefts), None) => lefts.len(),
8212            (None, Some(rights)) => rights.len(),
8213            (None, None) => 0,
8214        };
8215    }
8216
8217    let mut left_positions = Vec::<Option<usize>>::with_capacity(out_len);
8218    let mut right_positions = Vec::<Option<usize>>::with_capacity(out_len);
8219    for key in keys {
8220        match (left_map.get(key), right_map.get(key)) {
8221            (Some(lefts), Some(rights)) => {
8222                for &left_pos in lefts {
8223                    for &right_pos in rights {
8224                        left_positions.push(Some(left_pos));
8225                        right_positions.push(Some(right_pos));
8226                    }
8227                }
8228            }
8229            (Some(lefts), None) => {
8230                for &left_pos in lefts {
8231                    left_positions.push(Some(left_pos));
8232                    right_positions.push(None);
8233                }
8234            }
8235            (None, Some(rights)) => {
8236                for &right_pos in rights {
8237                    left_positions.push(None);
8238                    right_positions.push(Some(right_pos));
8239                }
8240            }
8241            (None, None) => {}
8242        }
8243    }
8244    Some((left_positions, right_positions))
8245}
8246
8247fn hash_i64_inner_positions_slices(left: &[i64], right: &[i64]) -> (Vec<usize>, Vec<usize>) {
8248    if right.is_empty() || left.is_empty() {
8249        return (Vec::new(), Vec::new());
8250    }
8251
8252    let mut right_map = FxHashMap::<i64, JoinPositionBucket>::with_capacity_and_hasher(
8253        right.len(),
8254        Default::default(),
8255    );
8256    for (pos, &key) in right.iter().enumerate() {
8257        right_map.entry(key).or_default().push(pos);
8258    }
8259
8260    let mut left_positions = Vec::<usize>::with_capacity(left.len().min(right.len()));
8261    let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
8262    for (left_pos, &key) in left.iter().enumerate() {
8263        if let Some(matches) = right_map.get(&key) {
8264            for &right_pos in matches {
8265                left_positions.push(left_pos);
8266                right_positions.push(right_pos);
8267            }
8268        }
8269    }
8270    (left_positions, right_positions)
8271}
8272
8273/// Hash-free inner-join positions for a MULTI-column key whose every component
8274/// is an all-valid, bounded-range Int64 column. Packs each row's composite key
8275/// into a single `i64` via a mixed-radix code over the per-column spans
8276/// (`packed = Σ_c (val_c - min_c) · stride_c`, `stride_0 = 1`, `stride_c =
8277/// stride_{c-1}·range_{c-1}`), then runs the dense CSR core on the packed keys.
8278///
8279/// The packing is a bijection on the joint key box (mins/ranges computed over
8280/// BOTH sides so left- and right-side codes are comparable), so two composite
8281/// keys collide under packing IFF every component is equal — identical to the
8282/// `CompositeJoinKey` equality the FxHashMap path uses. Pair order is therefore
8283/// byte-for-byte the same as the hash path. Returns `None` (caller falls back to
8284/// the composite-hash path) for any non-Int64 / any-missing component or when
8285/// the packed span exceeds the bounded direct-address gate.
8286/// Typed INNER/LEFT positions for a 2-column all-valid Int64 composite key that's
8287/// too WIDE for `dense_packed_int64_inner_positions` (its packed mixed-radix span
8288/// exceeds the bounded gate on a high-cardinality component), which otherwise
8289/// dropped multi-key merge to the generic `collect_composite_keys` Scalar path
8290/// (2-i64-key merge was 0.65x inner / 0.69x left pandas). Packs each row's
8291/// `(k0, k1)` into a `u128` — a bijection, so key equality is exact — builds the
8292/// right key -> ascending-position map, and probes left in order: one row per
8293/// (left, matching right), or (for Left) a single `(Some, None)` null-fill for an
8294/// unmatched left row. Bit-identical to the generic `CompositeJoinKey` path (same
8295/// left iteration + ascending-right-per-key emit). Returns `None` for non-Inner/
8296/// Left, non-2-key, or any non-all-valid-Int64 component.
8297fn typed_wide_two_i64_key_positions(
8298    join_type: JoinType,
8299    left_cols: &[&Column],
8300    right_cols: &[&Column],
8301) -> Option<MergeRowPositions> {
8302    if !matches!(
8303        join_type,
8304        JoinType::Inner | JoinType::Left | JoinType::Outer
8305    ) {
8306        return None;
8307    }
8308    if left_cols.len() != 2 || right_cols.len() != 2 {
8309        return None;
8310    }
8311    let l0 = left_cols[0].as_i64_slice()?;
8312    let l1 = left_cols[1].as_i64_slice()?;
8313    let r0 = right_cols[0].as_i64_slice()?;
8314    let r1 = right_cols[1].as_i64_slice()?;
8315    let pack = |a: i64, b: i64| -> u128 { (u128::from(a as u64) << 64) | u128::from(b as u64) };
8316
8317    if matches!(join_type, JoinType::Outer) {
8318        // OUTER: gid-factorize the u128 composite, CSR the per-gid positions, then
8319        // emit key-ASCENDING by the SEMANTIC (i64, i64) tuple (decoded from the
8320        // packed key — u128 order would mis-sort negatives). The typed branch
8321        // returns positions directly (the generic in-block sort is bypassed), so
8322        // they must arrive pre-sorted, matching sort_merge_rows_by_join_keys.
8323        let mut gid_of: FxHashMap<u128, u32> = FxHashMap::with_capacity_and_hasher(
8324            l0.len().saturating_add(r0.len()),
8325            Default::default(),
8326        );
8327        let mut gid_keys: Vec<u128> = Vec::new();
8328        let mut left_gid: Vec<u32> = Vec::with_capacity(l0.len());
8329        for pos in 0..l0.len() {
8330            let key = pack(l0[pos], l1[pos]);
8331            let g = *gid_of.entry(key).or_insert_with(|| {
8332                let x = gid_keys.len() as u32;
8333                gid_keys.push(key);
8334                x
8335            });
8336            left_gid.push(g);
8337        }
8338        let mut right_gid: Vec<u32> = Vec::with_capacity(r0.len());
8339        for pos in 0..r0.len() {
8340            let key = pack(r0[pos], r1[pos]);
8341            let g = *gid_of.entry(key).or_insert_with(|| {
8342                let x = gid_keys.len() as u32;
8343                gid_keys.push(key);
8344                x
8345            });
8346            right_gid.push(g);
8347        }
8348        let ng = gid_keys.len();
8349        let mut loff = vec![0u32; ng + 1];
8350        for &g in &left_gid {
8351            loff[g as usize + 1] += 1;
8352        }
8353        let mut roff = vec![0u32; ng + 1];
8354        for &g in &right_gid {
8355            roff[g as usize + 1] += 1;
8356        }
8357        for g in 0..ng {
8358            loff[g + 1] += loff[g];
8359            roff[g + 1] += roff[g];
8360        }
8361        let mut lpos = vec![0u32; l0.len()];
8362        let mut lw = loff[..ng].to_vec();
8363        for (i, &g) in left_gid.iter().enumerate() {
8364            let g = g as usize;
8365            lpos[lw[g] as usize] = i as u32;
8366            lw[g] += 1;
8367        }
8368        let mut rpos = vec![0u32; r0.len()];
8369        let mut rw = roff[..ng].to_vec();
8370        for (i, &g) in right_gid.iter().enumerate() {
8371            let g = g as usize;
8372            rpos[rw[g] as usize] = i as u32;
8373            rw[g] += 1;
8374        }
8375        // Argsort gids by the SEMANTIC (i64, i64) key (hi = k0, lo = k1).
8376        let decode = |packed: u128| -> (i64, i64) {
8377            (((packed >> 64) as u64) as i64, (packed as u64) as i64)
8378        };
8379        let mut order: Vec<u32> = (0..ng as u32).collect();
8380        order.sort_unstable_by_key(|&g| decode(gid_keys[g as usize]));
8381        let mut left_positions = Vec::<Option<usize>>::new();
8382        let mut right_positions = Vec::<Option<usize>>::new();
8383        for &g in &order {
8384            let g = g as usize;
8385            let ls = &lpos[loff[g] as usize..loff[g + 1] as usize];
8386            let rs = &rpos[roff[g] as usize..roff[g + 1] as usize];
8387            match (ls.is_empty(), rs.is_empty()) {
8388                (false, false) => {
8389                    for &l in ls {
8390                        for &r in rs {
8391                            left_positions.push(Some(l as usize));
8392                            right_positions.push(Some(r as usize));
8393                        }
8394                    }
8395                }
8396                (false, true) => {
8397                    for &l in ls {
8398                        left_positions.push(Some(l as usize));
8399                        right_positions.push(None);
8400                    }
8401                }
8402                (true, false) => {
8403                    for &r in rs {
8404                        left_positions.push(None);
8405                        right_positions.push(Some(r as usize));
8406                    }
8407                }
8408                (true, true) => {}
8409            }
8410        }
8411        return Some((left_positions, right_positions, None));
8412    }
8413
8414    // Inner / Left: right key -> ascending-position map, probe left in order.
8415    let mut right_map = FxHashMap::<u128, JoinPositionBucket>::with_capacity_and_hasher(
8416        r0.len(),
8417        Default::default(),
8418    );
8419    for pos in 0..r0.len() {
8420        right_map
8421            .entry(pack(r0[pos], r1[pos]))
8422            .or_default()
8423            .push(pos);
8424    }
8425    let is_left = matches!(join_type, JoinType::Left);
8426    let mut left_positions = Vec::<Option<usize>>::new();
8427    let mut right_positions = Vec::<Option<usize>>::new();
8428    for left_pos in 0..l0.len() {
8429        let key = pack(l0[left_pos], l1[left_pos]);
8430        if let Some(matches) = right_map.get(&key) {
8431            for &right_pos in matches {
8432                left_positions.push(Some(left_pos));
8433                right_positions.push(Some(right_pos));
8434            }
8435        } else if is_left {
8436            left_positions.push(Some(left_pos));
8437            right_positions.push(None);
8438        }
8439    }
8440    Some((left_positions, right_positions, None))
8441}
8442
8443/// General K-key (K >= 3) sibling of `typed_wide_two_i64_key_positions` for wide
8444/// Int64 key columns that overflow `dense_packed_int64_inner_positions` and exceed
8445/// the 2-key u128 packer. Factorizes each key column over left ∪ right into dense
8446/// gids (first-seen), then packs each row's per-column gids into a single u128
8447/// (column 0 most-significant) — a bijection whenever the summed gid bit-widths
8448/// fit 127 bits (else `None` → generic Scalar composite path). With the composite
8449/// as one integer, this reuses the exact same inner/left/outer emit as the 2-key
8450/// path. OUTER argsorts groups by the SEMANTIC original (i64,..,i64) tuple captured
8451/// at gid creation (packed-gid order is first-seen, not sorted). Bit-identical to
8452/// the `CompositeJoinKey` path (same left-order probe + ascending-right-per-key emit
8453/// for inner/left; same key-ascending group emit for outer). Returns `None` for
8454/// non-Inner/Left/Outer, K < 3, unequal K, any non-all-valid-Int64 component, or a
8455/// composite too wide for u128.
8456fn typed_wide_multi_i64_key_positions(
8457    join_type: JoinType,
8458    left_cols: &[&Column],
8459    right_cols: &[&Column],
8460) -> Option<MergeRowPositions> {
8461    if !matches!(
8462        join_type,
8463        JoinType::Inner | JoinType::Left | JoinType::Outer
8464    ) {
8465        return None;
8466    }
8467    let k = left_cols.len();
8468    if k < 3 || right_cols.len() != k {
8469        return None;
8470    }
8471    let mut ls: Vec<&[i64]> = Vec::with_capacity(k);
8472    let mut rs: Vec<&[i64]> = Vec::with_capacity(k);
8473    for c in 0..k {
8474        ls.push(left_cols[c].as_i64_slice()?);
8475        rs.push(right_cols[c].as_i64_slice()?);
8476    }
8477    let nl = ls[0].len();
8478    let nr = rs[0].len();
8479    if ls.iter().any(|s| s.len() != nl) || rs.iter().any(|s| s.len() != nr) {
8480        return None;
8481    }
8482
8483    // Factorize each key column over left ∪ right into dense first-seen gids.
8484    let mut lgid: Vec<Vec<u32>> = Vec::with_capacity(k);
8485    let mut rgid: Vec<Vec<u32>> = Vec::with_capacity(k);
8486    let mut cards: Vec<u64> = Vec::with_capacity(k);
8487    for c in 0..k {
8488        let mut m: FxHashMap<i64, u32> =
8489            FxHashMap::with_capacity_and_hasher(nl + nr, Default::default());
8490        let mut next: u32 = 0;
8491        let mut lg = Vec::with_capacity(nl);
8492        for &v in ls[c] {
8493            let g = *m.entry(v).or_insert_with(|| {
8494                let x = next;
8495                next += 1;
8496                x
8497            });
8498            lg.push(g);
8499        }
8500        let mut rg = Vec::with_capacity(nr);
8501        for &v in rs[c] {
8502            let g = *m.entry(v).or_insert_with(|| {
8503                let x = next;
8504                next += 1;
8505                x
8506            });
8507            rg.push(g);
8508        }
8509        cards.push(next as u64);
8510        lgid.push(lg);
8511        rgid.push(rg);
8512    }
8513
8514    // Per-column bit widths; bail if the packed composite exceeds u128.
8515    let mut bits: Vec<u32> = Vec::with_capacity(k);
8516    let mut total: u32 = 0;
8517    for &card in &cards {
8518        let b = if card <= 1 {
8519            0
8520        } else {
8521            64 - (card - 1).leading_zeros()
8522        };
8523        bits.push(b);
8524        total += b;
8525    }
8526    if total > 127 {
8527        return None;
8528    }
8529
8530    let pack = |gids: &[Vec<u32>], row: usize| -> u128 {
8531        let mut p: u128 = 0;
8532        for c in 0..k {
8533            p = (p << bits[c]) | u128::from(gids[c][row]);
8534        }
8535        p
8536    };
8537
8538    if matches!(join_type, JoinType::Outer) {
8539        let mut gid_of: FxHashMap<u128, u32> =
8540            FxHashMap::with_capacity_and_hasher(nl.saturating_add(nr), Default::default());
8541        // Semantic original tuple per composite gid (for the key-ascending sort).
8542        let mut gid_tuple: Vec<Vec<i64>> = Vec::new();
8543        let mut left_g: Vec<u32> = Vec::with_capacity(nl);
8544        for (row, _) in ls[0].iter().enumerate().take(nl) {
8545            let key = pack(&lgid, row);
8546            let g = *gid_of.entry(key).or_insert_with(|| {
8547                let x = gid_tuple.len() as u32;
8548                gid_tuple.push((0..k).map(|c| ls[c][row]).collect());
8549                x
8550            });
8551            left_g.push(g);
8552        }
8553        let mut right_g: Vec<u32> = Vec::with_capacity(nr);
8554        for (row, _) in rs[0].iter().enumerate().take(nr) {
8555            let key = pack(&rgid, row);
8556            let g = *gid_of.entry(key).or_insert_with(|| {
8557                let x = gid_tuple.len() as u32;
8558                gid_tuple.push((0..k).map(|c| rs[c][row]).collect());
8559                x
8560            });
8561            right_g.push(g);
8562        }
8563        let ng = gid_tuple.len();
8564        let mut loff = vec![0u32; ng + 1];
8565        for &g in &left_g {
8566            loff[g as usize + 1] += 1;
8567        }
8568        let mut roff = vec![0u32; ng + 1];
8569        for &g in &right_g {
8570            roff[g as usize + 1] += 1;
8571        }
8572        for g in 0..ng {
8573            loff[g + 1] += loff[g];
8574            roff[g + 1] += roff[g];
8575        }
8576        let mut lpos = vec![0u32; nl];
8577        let mut lw = loff[..ng].to_vec();
8578        for (i, &g) in left_g.iter().enumerate() {
8579            let g = g as usize;
8580            lpos[lw[g] as usize] = i as u32;
8581            lw[g] += 1;
8582        }
8583        let mut rpos = vec![0u32; nr];
8584        let mut rw = roff[..ng].to_vec();
8585        for (i, &g) in right_g.iter().enumerate() {
8586            let g = g as usize;
8587            rpos[rw[g] as usize] = i as u32;
8588            rw[g] += 1;
8589        }
8590        let mut order: Vec<u32> = (0..ng as u32).collect();
8591        order.sort_unstable_by(|&a, &b| gid_tuple[a as usize].cmp(&gid_tuple[b as usize]));
8592        let mut left_positions = Vec::<Option<usize>>::new();
8593        let mut right_positions = Vec::<Option<usize>>::new();
8594        for &g in &order {
8595            let g = g as usize;
8596            let lsl = &lpos[loff[g] as usize..loff[g + 1] as usize];
8597            let rsl = &rpos[roff[g] as usize..roff[g + 1] as usize];
8598            match (lsl.is_empty(), rsl.is_empty()) {
8599                (false, false) => {
8600                    for &l in lsl {
8601                        for &r in rsl {
8602                            left_positions.push(Some(l as usize));
8603                            right_positions.push(Some(r as usize));
8604                        }
8605                    }
8606                }
8607                (false, true) => {
8608                    for &l in lsl {
8609                        left_positions.push(Some(l as usize));
8610                        right_positions.push(None);
8611                    }
8612                }
8613                (true, false) => {
8614                    for &r in rsl {
8615                        left_positions.push(None);
8616                        right_positions.push(Some(r as usize));
8617                    }
8618                }
8619                (true, true) => {}
8620            }
8621        }
8622        return Some((left_positions, right_positions, None));
8623    }
8624
8625    // Inner / Left: right composite -> ascending-position map, probe left in order.
8626    let mut right_map =
8627        FxHashMap::<u128, JoinPositionBucket>::with_capacity_and_hasher(nr, Default::default());
8628    for pos in 0..nr {
8629        right_map.entry(pack(&rgid, pos)).or_default().push(pos);
8630    }
8631    let is_left = matches!(join_type, JoinType::Left);
8632    let mut left_positions = Vec::<Option<usize>>::new();
8633    let mut right_positions = Vec::<Option<usize>>::new();
8634    for left_pos in 0..nl {
8635        let key = pack(&lgid, left_pos);
8636        if let Some(matches) = right_map.get(&key) {
8637            for &right_pos in matches {
8638                left_positions.push(Some(left_pos));
8639                right_positions.push(Some(right_pos));
8640            }
8641        } else if is_left {
8642            left_positions.push(Some(left_pos));
8643            right_positions.push(None);
8644        }
8645    }
8646    Some((left_positions, right_positions, None))
8647}
8648
8649/// K-key (K >= 3) INNER/LEFT positions for all-valid BOUNDED-range Int64 keys
8650/// whose joint mixed-radix span fits an `i64` — even when that span exceeds the
8651/// direct-address gate of `dense_packed_int64_inner_positions` (2^24). Packs each
8652/// row's composite into one `i64` (`Σ_c (val_c - min_c)·stride_c`, `stride_0 = 1`,
8653/// `stride_c = stride_{c-1}·range_{c-1}`; a bijection on the joint key box, so
8654/// composite equality IFF every component equal) and runs the SINGLE-key i64 hash
8655/// merge on it — skipping the K per-column factorization `FxHashMap`s that
8656/// `typed_wide_multi_i64_key_positions` builds (the khash-floor cost that left
8657/// 3-key merge at 0.43-0.57x pandas). Bit-identical to that path / the generic
8658/// Scalar composite path: same left iteration order, same ascending right position
8659/// per composite bucket, same unmatched-left null-fill. Returns `None` (caller
8660/// falls back to the factorize path) unless every key is an all-valid Int64 slice
8661/// and the joint span fits `i64` — Outer bails (its key-ascending emit is handled
8662/// by the factorize path's semantic gid sort).
8663fn bounded_composite_multi_i64_key_positions(
8664    join_type: JoinType,
8665    left_cols: &[&Column],
8666    right_cols: &[&Column],
8667) -> Option<MergeRowPositions> {
8668    if !matches!(join_type, JoinType::Inner | JoinType::Left) {
8669        return None;
8670    }
8671    let k = left_cols.len();
8672    if k < 3 || right_cols.len() != k {
8673        return None;
8674    }
8675    let mut ls: Vec<&[i64]> = Vec::with_capacity(k);
8676    let mut rs: Vec<&[i64]> = Vec::with_capacity(k);
8677    for c in 0..k {
8678        ls.push(left_cols[c].as_i64_slice()?);
8679        rs.push(right_cols[c].as_i64_slice()?);
8680    }
8681    let nl = ls[0].len();
8682    let nr = rs[0].len();
8683    if ls.iter().any(|s| s.len() != nl) || rs.iter().any(|s| s.len() != nr) {
8684        return None;
8685    }
8686    if nl == 0 || nr == 0 {
8687        // Let the generic/factorize path handle degenerate empties (its
8688        // left-null-fill / empty-output shape is already validated there).
8689        return None;
8690    }
8691
8692    // Per-column min + span over left ∪ right; bail if the joint mixed-radix
8693    // product overflows i64 (a truly wide key keeps the factorize path).
8694    let mut mins = vec![0i64; k];
8695    let mut ranges = vec![0u128; k];
8696    for c in 0..k {
8697        let mut mn = i64::MAX;
8698        let mut mx = i64::MIN;
8699        for &v in ls[c] {
8700            if v < mn {
8701                mn = v;
8702            }
8703            if v > mx {
8704                mx = v;
8705            }
8706        }
8707        for &v in rs[c] {
8708            if v < mn {
8709                mn = v;
8710            }
8711            if v > mx {
8712                mx = v;
8713            }
8714        }
8715        mins[c] = mn;
8716        ranges[c] = (mx as i128 - mn as i128 + 1) as u128;
8717    }
8718    // strides[0] = 1, strides[c] = strides[c-1] * ranges[c-1]; bail on overflow.
8719    let mut strides = vec![1i64; k];
8720    let mut acc: u128 = 1;
8721    for c in 0..k {
8722        strides[c] = acc as i64;
8723        acc = acc.checked_mul(ranges[c])?;
8724        if acc > i64::MAX as u128 {
8725            return None;
8726        }
8727    }
8728    let comp = |s: &[&[i64]], row: usize| -> i64 {
8729        let mut p: i64 = 0;
8730        for c in 0..k {
8731            // (val - min) < range_c and range product fits i64 ⇒ no overflow.
8732            p += (s[c][row] - mins[c]) * strides[c];
8733        }
8734        p
8735    };
8736    let lcomp: Vec<i64> = (0..nl).map(|r| comp(&ls, r)).collect();
8737    let rcomp: Vec<i64> = (0..nr).map(|r| comp(&rs, r)).collect();
8738
8739    if matches!(join_type, JoinType::Inner) {
8740        let (lp, rp) = hash_i64_inner_positions_slices(&lcomp, &rcomp);
8741        return Some((
8742            lp.into_iter().map(Some).collect(),
8743            rp.into_iter().map(Some).collect(),
8744            None,
8745        ));
8746    }
8747
8748    // LEFT: right composite -> ascending-position buckets, probe left in order
8749    // (mirror of hash_int64_left_positions on the composite slices).
8750    let mut right_map =
8751        FxHashMap::<i64, JoinPositionBucket>::with_capacity_and_hasher(nr, Default::default());
8752    for (pos, &key) in rcomp.iter().enumerate() {
8753        right_map.entry(key).or_default().push(pos);
8754    }
8755    let mut left_positions = Vec::<Option<usize>>::with_capacity(nl);
8756    let mut right_positions = Vec::<Option<usize>>::with_capacity(nl);
8757    for (left_pos, &key) in lcomp.iter().enumerate() {
8758        if let Some(matches) = right_map.get(&key) {
8759            for &right_pos in matches {
8760                left_positions.push(Some(left_pos));
8761                right_positions.push(Some(right_pos));
8762            }
8763        } else {
8764            left_positions.push(Some(left_pos));
8765            right_positions.push(None);
8766        }
8767    }
8768    Some((left_positions, right_positions, None))
8769}
8770
8771fn dense_packed_int64_inner_positions(
8772    left_cols: &[&Column],
8773    right_cols: &[&Column],
8774) -> Option<(Vec<usize>, Vec<usize>)> {
8775    let k = left_cols.len();
8776    if k == 0 || k != right_cols.len() {
8777        return None;
8778    }
8779
8780    let left_slices: Vec<&[i64]> = left_cols
8781        .iter()
8782        .map(|c| c.as_i64_slice())
8783        .collect::<Option<Vec<_>>>()?;
8784    let right_slices: Vec<&[i64]> = right_cols
8785        .iter()
8786        .map(|c| c.as_i64_slice())
8787        .collect::<Option<Vec<_>>>()?;
8788
8789    let n_left = left_slices[0].len();
8790    let n_right = right_slices[0].len();
8791    if n_left == 0 || n_right == 0 {
8792        return Some((Vec::new(), Vec::new()));
8793    }
8794
8795    // Per-column min and span over BOTH sides; product = joint packed span.
8796    let mut mins = vec![0i64; k];
8797    let mut strides = vec![1i128; k];
8798    let mut total: i128 = 1;
8799    for c in 0..k {
8800        let mut mn = right_slices[c][0];
8801        let mut mx = right_slices[c][0];
8802        for &v in left_slices[c].iter().chain(right_slices[c].iter()) {
8803            if v < mn {
8804                mn = v;
8805            }
8806            if v > mx {
8807                mx = v;
8808            }
8809        }
8810        mins[c] = mn;
8811        let range = (mx as i128) - (mn as i128) + 1;
8812        strides[c] = total;
8813        total = total.checked_mul(range)?;
8814        // Gate the packed span the same way the single-key core does, up front
8815        // (the product can overflow the bounded table for wide multi-keys).
8816        if total > (1i128 << 24) {
8817            return None;
8818        }
8819    }
8820    if total > 16 * ((n_left + n_right) as i128) {
8821        return None;
8822    }
8823
8824    let pack = |slices: &[&[i64]], n: usize| -> Vec<i64> {
8825        (0..n)
8826            .map(|row| {
8827                let mut acc: i128 = 0;
8828                for c in 0..k {
8829                    acc += ((slices[c][row] as i128) - (mins[c] as i128)) * strides[c];
8830                }
8831                acc as i64
8832            })
8833            .collect()
8834    };
8835    let packed_left = pack(&left_slices, n_left);
8836    let packed_right = pack(&right_slices, n_right);
8837
8838    dense_i64_inner_positions_slices(&packed_left, &packed_right)
8839}
8840
8841fn merge_single_key_inner_unsorted(
8842    left: &fp_frame::DataFrame,
8843    right: &fp_frame::DataFrame,
8844    left_on: &[&str],
8845    right_on: &[&str],
8846    left_key_columns: &[&Column],
8847    right_key_columns: &[&Column],
8848    suffixes: &ResolvedMergeSuffixes,
8849) -> Result<MergedDataFrame, JoinError> {
8850    debug_assert_eq!(left_key_columns.len(), 1);
8851    debug_assert_eq!(right_key_columns.len(), 1);
8852
8853    if left_on[0] == right_on[0]
8854        && ordered_identity_int64_keys_match(left_key_columns[0], right_key_columns[0])
8855    {
8856        return build_single_key_ordered_identity_inner_merge_output(
8857            left, right, left_on, right_on, suffixes,
8858        );
8859    }
8860    if let Some(merged) = build_single_key_affine_i64_inner_merge_output(
8861        left,
8862        right,
8863        left_on,
8864        right_on,
8865        left_key_columns[0],
8866        right_key_columns[0],
8867        suffixes,
8868    )? {
8869        return Ok(merged);
8870    }
8871    if let Some((left_positions, right_positions)) =
8872        ordered_unique_int64_inner_positions(left_key_columns[0], right_key_columns[0])
8873    {
8874        return build_single_key_inner_merge_output(
8875            left,
8876            right,
8877            left_on,
8878            right_on,
8879            &left_positions,
8880            &right_positions,
8881            suffixes,
8882        );
8883    }
8884
8885    if let Some(merged) = build_single_key_dense_i64_inner_merge_output(
8886        left,
8887        right,
8888        left_on,
8889        right_on,
8890        left_key_columns[0],
8891        right_key_columns[0],
8892        FusedInt64MergeOptions {
8893            suffixes,
8894            require_all_left_keys_matched: false,
8895        },
8896    )? {
8897        return Ok(merged);
8898    }
8899
8900    // Datetime64/Timedelta64 keys are physically i64 nanoseconds. For the
8901    // all-valid, same-dtype case, plan positions directly over that backing
8902    // instead of materializing one Scalar + JoinKeyComponent per row. Nullable
8903    // temporal keys deliberately keep the generic path below, where NaT joins
8904    // use the existing Missing-key semantics.
8905    if let Some((left_positions, right_positions)) =
8906        temporal_i64_inner_positions(left_key_columns[0], right_key_columns[0])
8907    {
8908        return build_single_key_inner_merge_output(
8909            left,
8910            right,
8911            left_on,
8912            right_on,
8913            &left_positions,
8914            &right_positions,
8915            suffixes,
8916        );
8917    }
8918
8919    // Hash-free dense direct-address build+probe for bounded all-valid Int64
8920    // keys (the common low-cardinality join-key shape). Bit-identical pairs.
8921    if let Some((left_positions, right_positions)) =
8922        dense_int64_inner_positions(left_key_columns[0], right_key_columns[0])
8923    {
8924        return build_single_key_inner_merge_output(
8925            left,
8926            right,
8927            left_on,
8928            right_on,
8929            &left_positions,
8930            &right_positions,
8931            suffixes,
8932        );
8933    }
8934    if let Some((left_positions, right_positions)) =
8935        hash_int64_inner_positions(left_key_columns[0], right_key_columns[0])
8936    {
8937        return build_single_key_inner_merge_output(
8938            left,
8939            right,
8940            left_on,
8941            right_on,
8942            &left_positions,
8943            &right_positions,
8944            suffixes,
8945        );
8946    }
8947
8948    if let Some(position_plan) =
8949        ordered_unique_utf8_inner_position_plan(left_key_columns[0], right_key_columns[0])
8950    {
8951        return match position_plan {
8952            InnerPositionPlan::Gather {
8953                left_positions,
8954                right_positions,
8955            } => build_single_key_inner_merge_output(
8956                left,
8957                right,
8958                left_on,
8959                right_on,
8960                &left_positions,
8961                &right_positions,
8962                suffixes,
8963            ),
8964            InnerPositionPlan::ContiguousRanges {
8965                left_start,
8966                right_start,
8967                len,
8968            } => build_single_key_inner_merge_output_with_selections(
8969                left,
8970                right,
8971                left_on,
8972                right_on,
8973                PositionSelection::ContiguousRange {
8974                    start: left_start,
8975                    len,
8976                },
8977                PositionSelection::ContiguousRange {
8978                    start: right_start,
8979                    len,
8980                },
8981                suffixes,
8982            ),
8983        };
8984    }
8985
8986    // Byte-span build+probe for all-valid contiguous-Utf8 string keys
8987    // (br-frankenpandas-i388q): skips the per-row String clone + Scalar
8988    // materialization of the JoinKeyComponent path. Same pairing -> same output.
8989    if let Some((left_positions, right_positions)) =
8990        contiguous_utf8_inner_positions(left_key_columns[0], right_key_columns[0])
8991    {
8992        return build_single_key_inner_merge_output(
8993            left,
8994            right,
8995            left_on,
8996            right_on,
8997            &left_positions,
8998            &right_positions,
8999            suffixes,
9000        );
9001    }
9002    if let Some((left_positions, right_positions)) =
9003        scalar_utf8_inner_positions(left_key_columns[0], right_key_columns[0])
9004    {
9005        return build_single_key_inner_merge_output(
9006            left,
9007            right,
9008            left_on,
9009            right_on,
9010            &left_positions,
9011            &right_positions,
9012            suffixes,
9013        );
9014    }
9015
9016    let left_keys = collect_single_join_keys(left_key_columns[0]);
9017    let right_keys = collect_single_join_keys(right_key_columns[0]);
9018    let mut right_map =
9019        FxHashMap::<&JoinKeyComponent, JoinPositionBucket>::with_capacity_and_hasher(
9020            right_keys.len(),
9021            Default::default(),
9022        );
9023    for (pos, key) in right_keys.iter().enumerate() {
9024        right_map.entry(key).or_default().push(pos);
9025    }
9026
9027    let mut left_positions = Vec::<usize>::with_capacity(left_keys.len().min(right_keys.len()));
9028    let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
9029    for (left_pos, key) in left_keys.iter().enumerate() {
9030        if let Some(matches) = right_map.get(key) {
9031            for &right_pos in matches {
9032                left_positions.push(left_pos);
9033                right_positions.push(right_pos);
9034            }
9035        }
9036    }
9037
9038    build_single_key_inner_merge_output(
9039        left,
9040        right,
9041        left_on,
9042        right_on,
9043        &left_positions,
9044        &right_positions,
9045        suffixes,
9046    )
9047}
9048
9049/// Merge two DataFrames on one or more key columns.
9050///
9051/// Matches `pd.merge(left, right, left_on=left_keys, right_on=right_keys, how=join_type)`.
9052/// - Key columns are used for matching rows (hash join).
9053/// - Non-key columns are carried through and reindexed.
9054/// - Column name conflicts use configurable suffixes (default `_x`/`_y`).
9055/// - The output index is auto-generated (0..n RangeIndex-style).
9056pub fn merge_dataframes_on_with(
9057    left: &fp_frame::DataFrame,
9058    right: &fp_frame::DataFrame,
9059    left_on: &[&str],
9060    right_on: &[&str],
9061    join_type: JoinType,
9062) -> Result<MergedDataFrame, JoinError> {
9063    merge_dataframes_on_with_options(
9064        left,
9065        right,
9066        left_on,
9067        right_on,
9068        join_type,
9069        MergeExecutionOptions::default(),
9070    )
9071}
9072
9073/// Merge two DataFrames on one or more key columns with execution options.
9074pub fn merge_dataframes_on_with_options(
9075    left: &fp_frame::DataFrame,
9076    right: &fp_frame::DataFrame,
9077    left_on: &[&str],
9078    right_on: &[&str],
9079    join_type: JoinType,
9080    options: MergeExecutionOptions,
9081) -> Result<MergedDataFrame, JoinError> {
9082    let MergeExecutionOptions {
9083        indicator_name,
9084        validate_mode,
9085        suffixes,
9086        sort,
9087    } = options;
9088    let indicator_name = resolve_merge_indicator_name(indicator_name.as_deref())?;
9089    let suffixes = resolve_merge_suffixes(suffixes);
9090
9091    if matches!(join_type, JoinType::Cross) {
9092        if let Some(validate_mode) = validate_mode
9093            && !matches!(validate_mode, MergeValidateMode::ManyToMany)
9094        {
9095            return Err(JoinError::Frame(FrameError::CompatibilityRejected(
9096                format!(
9097                    "merge validate='{}' is not supported for cross join",
9098                    validate_mode.as_str()
9099                ),
9100            )));
9101        }
9102        return merge_dataframes_cross(left, right, indicator_name.as_deref(), &suffixes);
9103    }
9104
9105    if left_on.is_empty() || right_on.is_empty() {
9106        return Err(JoinError::Frame(FrameError::CompatibilityRejected(
9107            "merge requires at least one key column".to_owned(),
9108        )));
9109    }
9110    if left_on.len() != right_on.len() {
9111        return Err(JoinError::Frame(FrameError::CompatibilityRejected(
9112            "merge requires left_on and right_on key lists with equal length".to_owned(),
9113        )));
9114    }
9115
9116    let mut seen_left_keys = HashSet::new();
9117    for key_name in left_on {
9118        if !seen_left_keys.insert(*key_name) {
9119            return Err(JoinError::Frame(FrameError::CompatibilityRejected(
9120                format!("merge left key column '{key_name}' is duplicated"),
9121            )));
9122        }
9123    }
9124    let mut seen_right_keys = HashSet::new();
9125    for key_name in right_on {
9126        if !seen_right_keys.insert(*key_name) {
9127            return Err(JoinError::Frame(FrameError::CompatibilityRejected(
9128                format!("merge right key column '{key_name}' is duplicated"),
9129            )));
9130        }
9131    }
9132
9133    let left_key_columns = collect_join_key_columns(left, left_on, "left")?;
9134    let right_key_columns = collect_join_key_columns(right, right_on, "right")?;
9135
9136    // br-frankenpandas-uza04: settle `validate=` HERE, off the raw typed key
9137    // buffer, instead of letting it drag the whole merge onto the generic
9138    // Scalar path.
9139    //
9140    // `validate_merge_cardinality` is called in exactly ONE place — the generic
9141    // `collect_composite_keys` branch at the bottom of this function — so
9142    // `validate_mode_allows_fast_positions` had to return false for every
9143    // enforcing mode purely to *route execution there*. The cost of asking for
9144    // a cardinality guarantee was therefore the entire fast-path family:
9145    // `dense_packed_int64_inner_positions`, `typed_wide_two_i64_key_positions`,
9146    // `bounded_composite_multi_i64_key_positions`,
9147    // `typed_wide_multi_i64_key_positions` and the single-key inner/left
9148    // shortcuts, all disabled, plus a `Vec<CompositeJoinKey>` built by reading
9149    // `column.values()[row]` — 32 B/elem of `Scalar` spine and a `SmallVec` per
9150    // row — on both sides.
9151    //
9152    // A single all-valid Int64 key needs none of that: duplicate detection is
9153    // an `FxHashSet<i64>` over `as_i64_slice`. When that check applies AND
9154    // passes, the merge is free to take exactly the path it would have taken
9155    // with no `validate=` at all, because a passing validation adds nothing to
9156    // the output — it only decides whether the merge is allowed to happen.
9157    //
9158    // Semantics preserved exactly: same messages, same left-before-right
9159    // precedence, same modes checked on the same sides. Moving the check
9160    // earlier is unobservable because nothing between this point and the old
9161    // call site can fail — every fast-path helper in between returns `Option`,
9162    // never `Err`.
9163    let typed_validation_settled = match validate_mode {
9164        Some(mode) => {
9165            typed_validate_merge_cardinality(mode, &left_key_columns, &right_key_columns)?
9166        }
9167        None => false,
9168    };
9169    let validate_allows_fast_positions =
9170        validate_mode_allows_fast_positions(validate_mode) || typed_validation_settled;
9171
9172    if matches!(join_type, JoinType::Inner)
9173        && left_on.len() == 1
9174        && right_on.len() == 1
9175        && !sort
9176        && indicator_name.is_none()
9177        && validate_allows_fast_positions
9178    {
9179        return merge_single_key_inner_unsorted(
9180            left,
9181            right,
9182            left_on,
9183            right_on,
9184            &left_key_columns,
9185            &right_key_columns,
9186            &suffixes,
9187        );
9188    }
9189    if matches!(join_type, JoinType::Left)
9190        && left_on.len() == 1
9191        && right_on.len() == 1
9192        && !sort
9193        && indicator_name.is_none()
9194        && validate_allows_fast_positions
9195        && let Some(right_positions) =
9196            ordered_unique_int64_left_match_positions(left_key_columns[0], right_key_columns[0])
9197    {
9198        return build_single_key_ordered_unique_left_merge_output(
9199            left,
9200            right,
9201            left_on,
9202            right_on,
9203            &right_positions,
9204            &suffixes,
9205        );
9206    }
9207    if matches!(join_type, JoinType::Left)
9208        && left_on.len() == 1
9209        && right_on.len() == 1
9210        && !sort
9211        && indicator_name.is_none()
9212        && validate_allows_fast_positions
9213        && let Some((left_positions, right_positions)) =
9214            temporal_i64_left_positions(left_key_columns[0], right_key_columns[0])
9215    {
9216        return build_single_key_dense_left_merge_output(
9217            left,
9218            right,
9219            left_on,
9220            right_on,
9221            &left_positions,
9222            &right_positions,
9223            &suffixes,
9224        );
9225    }
9226    if matches!(join_type, JoinType::Left)
9227        && left_on.len() == 1
9228        && right_on.len() == 1
9229        && !sort
9230        && indicator_name.is_none()
9231        && validate_allows_fast_positions
9232        && let Some(merged) = build_single_key_dense_cycle_i64_left_merge_output(
9233            left,
9234            right,
9235            left_on,
9236            right_on,
9237            left_key_columns[0],
9238            right_key_columns[0],
9239            &suffixes,
9240        )?
9241    {
9242        return Ok(merged);
9243    }
9244    if matches!(join_type, JoinType::Left)
9245        && left_on.len() == 1
9246        && right_on.len() == 1
9247        && !sort
9248        && indicator_name.is_none()
9249        && validate_allows_fast_positions
9250        && let Some(merged) = build_single_key_dense_i64_inner_merge_output(
9251            left,
9252            right,
9253            left_on,
9254            right_on,
9255            left_key_columns[0],
9256            right_key_columns[0],
9257            FusedInt64MergeOptions {
9258                suffixes: &suffixes,
9259                require_all_left_keys_matched: true,
9260            },
9261        )?
9262    {
9263        return Ok(merged);
9264    }
9265    if matches!(join_type, JoinType::Left)
9266        && left_on.len() == 1
9267        && right_on.len() == 1
9268        && !sort
9269        && indicator_name.is_none()
9270        && validate_allows_fast_positions
9271        && let Some(merged) = build_single_key_dense_i64_left_merge_output(
9272            left,
9273            right,
9274            left_on,
9275            right_on,
9276            left_key_columns[0],
9277            right_key_columns[0],
9278            &suffixes,
9279        )?
9280    {
9281        return Ok(merged);
9282    }
9283    if matches!(join_type, JoinType::Left)
9284        && left_on.len() == 1
9285        && right_on.len() == 1
9286        && !sort
9287        && indicator_name.is_none()
9288        && validate_allows_fast_positions
9289        && let Some((left_positions, right_positions)) =
9290            dense_int64_left_positions(left_key_columns[0], right_key_columns[0])
9291    {
9292        return build_single_key_dense_left_merge_output(
9293            left,
9294            right,
9295            left_on,
9296            right_on,
9297            &left_positions,
9298            &right_positions,
9299            &suffixes,
9300        );
9301    }
9302    if matches!(join_type, JoinType::Left)
9303        && left_on.len() == 1
9304        && right_on.len() == 1
9305        && !sort
9306        && indicator_name.is_none()
9307        && validate_allows_fast_positions
9308        && let Some((left_positions, right_positions)) =
9309            hash_int64_left_positions(left_key_columns[0], right_key_columns[0])
9310    {
9311        return build_single_key_dense_left_merge_output(
9312            left,
9313            right,
9314            left_on,
9315            right_on,
9316            &left_positions,
9317            &right_positions,
9318            &suffixes,
9319        );
9320    }
9321    if matches!(join_type, JoinType::Left)
9322        && left_on.len() == 1
9323        && right_on.len() == 1
9324        && !sort
9325        && indicator_name.is_none()
9326        && validate_allows_fast_positions
9327        && let Some((left_positions, right_positions)) =
9328            contiguous_utf8_left_positions(left_key_columns[0], right_key_columns[0])
9329    {
9330        return build_single_key_dense_left_merge_output(
9331            left,
9332            right,
9333            left_on,
9334            right_on,
9335            &left_positions,
9336            &right_positions,
9337            &suffixes,
9338        );
9339    }
9340    if matches!(join_type, JoinType::Left)
9341        && left_on.len() == 1
9342        && right_on.len() == 1
9343        && !sort
9344        && indicator_name.is_none()
9345        && validate_allows_fast_positions
9346        && let Some((left_positions, right_positions)) =
9347            scalar_utf8_left_positions(left_key_columns[0], right_key_columns[0])
9348    {
9349        return build_single_key_dense_left_merge_output(
9350            left,
9351            right,
9352            left_on,
9353            right_on,
9354            &left_positions,
9355            &right_positions,
9356            &suffixes,
9357        );
9358    }
9359    if matches!(join_type, JoinType::Right)
9360        && left_on.len() == 1
9361        && right_on.len() == 1
9362        && !sort
9363        && indicator_name.is_none()
9364        && validate_allows_fast_positions
9365        && let Some(left_positions) =
9366            ordered_unique_int64_right_match_positions(left_key_columns[0], right_key_columns[0])
9367    {
9368        return build_single_key_ordered_unique_right_merge_output(
9369            left,
9370            right,
9371            left_on,
9372            right_on,
9373            &left_positions,
9374            &suffixes,
9375        );
9376    }
9377    if matches!(join_type, JoinType::Right)
9378        && left_on.len() == 1
9379        && right_on.len() == 1
9380        && !sort
9381        && indicator_name.is_none()
9382        && validate_allows_fast_positions
9383        && let Some(left_positions) = ordered_unique_temporal_i64_right_match_positions(
9384            left_key_columns[0],
9385            right_key_columns[0],
9386        )
9387    {
9388        return build_single_key_ordered_unique_right_merge_output(
9389            left,
9390            right,
9391            left_on,
9392            right_on,
9393            &left_positions,
9394            &suffixes,
9395        );
9396    }
9397    if matches!(join_type, JoinType::Right)
9398        && left_on.len() == 1
9399        && right_on.len() == 1
9400        && !sort
9401        && indicator_name.is_none()
9402        && validate_allows_fast_positions
9403        && let Some(merged) = build_single_key_dense_i64_right_all_matched_merge_output(
9404            left,
9405            right,
9406            left_on,
9407            right_on,
9408            left_key_columns[0],
9409            right_key_columns[0],
9410            &suffixes,
9411        )?
9412    {
9413        return Ok(merged);
9414    }
9415    if matches!(join_type, JoinType::Right)
9416        && left_on.len() == 1
9417        && right_on.len() == 1
9418        && !sort
9419        && indicator_name.is_none()
9420        && validate_allows_fast_positions
9421        && let Some(merged) = build_single_key_dense_i64_right_merge_output(
9422            left,
9423            right,
9424            left_on,
9425            right_on,
9426            left_key_columns[0],
9427            right_key_columns[0],
9428            &suffixes,
9429        )?
9430    {
9431        return Ok(merged);
9432    }
9433    if matches!(join_type, JoinType::Right)
9434        && left_on.len() == 1
9435        && right_on.len() == 1
9436        && !sort
9437        && indicator_name.is_none()
9438        && validate_allows_fast_positions
9439        && let Some((left_positions, right_positions)) =
9440            dense_int64_right_positions(left_key_columns[0], right_key_columns[0])
9441    {
9442        return build_single_key_dense_right_merge_output(
9443            left,
9444            right,
9445            left_on,
9446            right_on,
9447            &left_positions,
9448            &right_positions,
9449            &suffixes,
9450        );
9451    }
9452    if matches!(join_type, JoinType::Outer)
9453        && left_on.len() == 1
9454        && right_on.len() == 1
9455        && !sort
9456        && indicator_name.is_none()
9457        && validate_allows_fast_positions
9458        && let Some((left_positions, right_positions)) =
9459            ordered_unique_temporal_i64_outer_positions(left_key_columns[0], right_key_columns[0])
9460    {
9461        return build_single_key_ordered_unique_outer_merge_output(
9462            left,
9463            right,
9464            left_on,
9465            right_on,
9466            &left_positions,
9467            &right_positions,
9468            &suffixes,
9469        );
9470    }
9471    if matches!(join_type, JoinType::Outer)
9472        && left_on.len() == 1
9473        && right_on.len() == 1
9474        && !sort
9475        && indicator_name.is_none()
9476        && validate_allows_fast_positions
9477        && let Some((left_positions, right_positions)) =
9478            ordered_unique_int64_outer_positions(left_key_columns[0], right_key_columns[0])
9479    {
9480        return build_single_key_ordered_unique_outer_merge_output(
9481            left,
9482            right,
9483            left_on,
9484            right_on,
9485            &left_positions,
9486            &right_positions,
9487            &suffixes,
9488        );
9489    }
9490    if matches!(join_type, JoinType::Outer)
9491        && left_on.len() == 1
9492        && right_on.len() == 1
9493        && !sort
9494        && indicator_name.is_none()
9495        && validate_allows_fast_positions
9496        && let Some(merged) = build_single_key_dense_i64_outer_all_matched_merge_output(
9497            left,
9498            right,
9499            left_on,
9500            right_on,
9501            left_key_columns[0],
9502            right_key_columns[0],
9503            &suffixes,
9504        )?
9505    {
9506        return Ok(merged);
9507    }
9508    if matches!(join_type, JoinType::Outer)
9509        && left_on.len() == 1
9510        && right_on.len() == 1
9511        && !sort
9512        && indicator_name.is_none()
9513        && validate_allows_fast_positions
9514        && let Some(merged) = build_single_key_dense_i64_outer_merge_output(
9515            left,
9516            right,
9517            left_on,
9518            right_on,
9519            left_key_columns[0],
9520            right_key_columns[0],
9521            &suffixes,
9522        )?
9523    {
9524        return Ok(merged);
9525    }
9526    if matches!(join_type, JoinType::Outer)
9527        && left_on.len() == 1
9528        && right_on.len() == 1
9529        && !sort
9530        && indicator_name.is_none()
9531        && validate_allows_fast_positions
9532        && let Some((left_positions, right_positions)) =
9533            dense_int64_outer_positions(left_key_columns[0], right_key_columns[0])
9534    {
9535        return build_single_key_ordered_unique_outer_merge_output(
9536            left,
9537            right,
9538            left_on,
9539            right_on,
9540            &left_positions,
9541            &right_positions,
9542            &suffixes,
9543        );
9544    }
9545    if matches!(join_type, JoinType::Outer)
9546        && left_on.len() == 1
9547        && right_on.len() == 1
9548        && !sort
9549        && indicator_name.is_none()
9550        && validate_allows_fast_positions
9551        && let Some((left_positions, right_positions)) =
9552            hash_int64_outer_positions(left_key_columns[0], right_key_columns[0])
9553    {
9554        return build_single_key_ordered_unique_outer_merge_output(
9555            left,
9556            right,
9557            left_on,
9558            right_on,
9559            &left_positions,
9560            &right_positions,
9561            &suffixes,
9562        );
9563    }
9564    if matches!(join_type, JoinType::Outer)
9565        && left_on.len() == 1
9566        && right_on.len() == 1
9567        && !sort
9568        && indicator_name.is_none()
9569        && validate_allows_fast_positions
9570        && let Some(merged) = build_single_key_fixed_decimal_utf8_outer_all_matched_merge_output(
9571            left,
9572            right,
9573            left_on,
9574            right_on,
9575            left_key_columns[0],
9576            right_key_columns[0],
9577            &suffixes,
9578        )?
9579    {
9580        return Ok(merged);
9581    }
9582    if matches!(join_type, JoinType::Outer)
9583        && left_on.len() == 1
9584        && right_on.len() == 1
9585        && !sort
9586        && indicator_name.is_none()
9587        && validate_allows_fast_positions
9588        && let Some((left_positions, right_positions)) =
9589            contiguous_utf8_outer_positions(left_key_columns[0], right_key_columns[0])
9590    {
9591        return build_single_key_ordered_unique_outer_merge_output(
9592            left,
9593            right,
9594            left_on,
9595            right_on,
9596            &left_positions,
9597            &right_positions,
9598            &suffixes,
9599        );
9600    }
9601    if matches!(join_type, JoinType::Outer)
9602        && left_on.len() == 1
9603        && right_on.len() == 1
9604        && !sort
9605        && indicator_name.is_none()
9606        && validate_allows_fast_positions
9607        && let Some((left_positions, right_positions)) =
9608            scalar_utf8_outer_positions(left_key_columns[0], right_key_columns[0])
9609    {
9610        return build_single_key_ordered_unique_outer_merge_output(
9611            left,
9612            right,
9613            left_on,
9614            right_on,
9615            &left_positions,
9616            &right_positions,
9617            &suffixes,
9618        );
9619    }
9620
9621    let needs_key_order = sort || matches!(join_type, JoinType::Outer);
9622
9623    // Hash-free fast path: a plain inner join on all-valid bounded-Int64 key
9624    // column(s) packs the composite key into one i64 and runs the dense CSR
9625    // core, skipping CompositeJoinKey materialization + FxHashMap build/probe.
9626    // Gated to inner joins with no sort/indicator/enforcing validate, where the
9627    // emitted (left,right) pairs are byte-for-byte identical to the hash path.
9628    let packed_inner = if matches!(join_type, JoinType::Inner)
9629        && !sort
9630        && validate_allows_fast_positions
9631        && indicator_name.is_none()
9632    {
9633        dense_packed_int64_inner_positions(&left_key_columns, &right_key_columns)
9634    } else {
9635        None
9636    };
9637
9638    // Typed wide 2-i64-key INNER/LEFT positions (bypasses the Scalar composite
9639    // path when a component is too wide for the packed dense gate). Same fast-path
9640    // gates as packed_inner (no sort/indicator, validate allows fast positions).
9641    let typed_two_key = if !sort
9642        && indicator_name.is_none()
9643        && validate_allows_fast_positions
9644        && packed_inner.is_none()
9645    {
9646        typed_wide_two_i64_key_positions(join_type, &left_key_columns, &right_key_columns)
9647    } else {
9648        None
9649    };
9650
9651    // Typed K-key (K >= 3) BOUNDED-Int64 INNER/LEFT positions: pack the composite
9652    // into one i64 + single-key i64 hash merge, skipping the K per-column
9653    // factorization maps the factorize path below builds (3-key merge was
9654    // 0.43-0.57x pandas — the khash floor of those maps). Same fast-path gates.
9655    let composite_multi_key = if !sort
9656        && indicator_name.is_none()
9657        && validate_allows_fast_positions
9658        && packed_inner.is_none()
9659        && typed_two_key.is_none()
9660    {
9661        bounded_composite_multi_i64_key_positions(join_type, &left_key_columns, &right_key_columns)
9662    } else {
9663        None
9664    };
9665
9666    // Typed general K-key (K >= 3) wide-Int64 positions: factorize-to-gid + u128
9667    // pack, bypassing the Scalar collect_composite_keys path. Same fast-path gates.
9668    let typed_multi_key = if !sort
9669        && indicator_name.is_none()
9670        && validate_allows_fast_positions
9671        && packed_inner.is_none()
9672        && typed_two_key.is_none()
9673        && composite_multi_key.is_none()
9674    {
9675        typed_wide_multi_i64_key_positions(join_type, &left_key_columns, &right_key_columns)
9676    } else {
9677        None
9678    };
9679
9680    let (left_positions, right_positions, _out_row_keys): MergeRowPositions =
9681        if let Some((lp, rp)) = packed_inner {
9682            (
9683                lp.into_iter().map(Some).collect(),
9684                rp.into_iter().map(Some).collect(),
9685                None,
9686            )
9687        } else if let Some(typed) = typed_two_key {
9688            typed
9689        } else if let Some(typed) = composite_multi_key {
9690            typed
9691        } else if let Some(typed) = typed_multi_key {
9692            typed
9693        } else {
9694            // Convert key columns to hashable composite keys.
9695            let left_keys = collect_composite_keys(&left_key_columns);
9696            let right_keys = collect_composite_keys(&right_key_columns);
9697            // Skip when the typed checker above already enforced this mode
9698            // (br-frankenpandas-uza04) — re-running it here would be a second
9699            // full pass over both key sides for an answer already known. A
9700            // shape the typed checker declined still lands here and is checked
9701            // exactly as before.
9702            if let Some(validate_mode) = validate_mode
9703                && !typed_validation_settled
9704            {
9705                validate_merge_cardinality(validate_mode, &left_keys, &right_keys)?;
9706            }
9707
9708            // Build only the probe maps required by the selected join direction.
9709            let right_map = if matches!(
9710                join_type,
9711                JoinType::Inner | JoinType::Left | JoinType::Outer | JoinType::Right
9712            ) {
9713                let mut m =
9714                    FxHashMap::<&CompositeJoinKey, JoinPositionBucket>::with_capacity_and_hasher(
9715                        right_keys.len(),
9716                        Default::default(),
9717                    );
9718                for (pos, key) in right_keys.iter().enumerate() {
9719                    m.entry(key).or_default().push(pos);
9720                }
9721                Some(m)
9722            } else {
9723                None
9724            };
9725
9726            // Right no longer needs a left_map: its branch below probes the small
9727            // right_map with a single left pass (O(right) build, not O(left)).
9728            let left_map = if matches!(join_type, JoinType::Outer) {
9729                let mut m =
9730                    FxHashMap::<&CompositeJoinKey, JoinPositionBucket>::with_capacity_and_hasher(
9731                        left_keys.len(),
9732                        Default::default(),
9733                    );
9734                for (pos, key) in left_keys.iter().enumerate() {
9735                    m.entry(key).or_default().push(pos);
9736                }
9737                Some(m)
9738            } else {
9739                None
9740            };
9741
9742            // Compute row position mappings.
9743            let row_capacity = match join_type {
9744                JoinType::Inner => left_keys.len().min(right_keys.len()),
9745                JoinType::Left => left_keys.len(),
9746                JoinType::Right => right_keys.len(),
9747                JoinType::Outer => left_keys.len().saturating_add(right_keys.len()),
9748                JoinType::Cross => left_keys.len().saturating_mul(right_keys.len()),
9749            };
9750            let mut left_positions = Vec::<Option<usize>>::with_capacity(row_capacity);
9751            let mut right_positions = Vec::<Option<usize>>::with_capacity(row_capacity);
9752            // No longer materialized: the post-position sort reads each row's key by
9753            // reference from left_keys/right_keys via its position, so the per-row
9754            // push_merge_row_key calls below no-op (no String-owning key clones).
9755            let mut out_row_keys: Option<Vec<CompositeJoinKey>> = None;
9756
9757            match join_type {
9758                JoinType::Inner | JoinType::Left | JoinType::Outer => {
9759                    let right_map = right_map
9760                        .as_ref()
9761                        .expect("right_map required for Inner, Left, and Outer joins");
9762                    for (left_pos, key) in left_keys.iter().enumerate() {
9763                        if let Some(matches) = right_map.get(key) {
9764                            for &right_pos in matches {
9765                                push_merge_row_key(&mut out_row_keys, key);
9766                                left_positions.push(Some(left_pos));
9767                                right_positions.push(Some(right_pos));
9768                            }
9769                            continue;
9770                        }
9771
9772                        if matches!(join_type, JoinType::Left | JoinType::Outer) {
9773                            push_merge_row_key(&mut out_row_keys, key);
9774                            left_positions.push(Some(left_pos));
9775                            right_positions.push(None);
9776                        }
9777                    }
9778
9779                    if matches!(join_type, JoinType::Outer) {
9780                        let left_map = left_map.as_ref().expect("left_map required for Outer join");
9781                        for (right_pos, key) in right_keys.iter().enumerate() {
9782                            if !left_map.contains_key(key) {
9783                                push_merge_row_key(&mut out_row_keys, key);
9784                                left_positions.push(None);
9785                                right_positions.push(Some(right_pos));
9786                            }
9787                        }
9788                    }
9789                }
9790                JoinType::Right => {
9791                    // Probe the SMALL right_map with a single left pass instead of
9792                    // building a left_map over every left row (the prior path —
9793                    // O(left) hash build; for a 1M⋈10k merge that was ~2.4x slower
9794                    // than the symmetric Left join). Bucket each matching left
9795                    // position under its right row; `left_by_right[r]` collects in
9796                    // left-iteration order, and we then emit right rows in order —
9797                    // byte-for-byte identical (left,right) pairs to the left_map
9798                    // path (right-row order outer, left-position order inner),
9799                    // including duplicate right keys and unmatched right rows.
9800                    let right_map = right_map
9801                        .as_ref()
9802                        .expect("right_map required for Right join");
9803                    let mut left_by_right: Vec<Vec<usize>> = vec![Vec::new(); right_keys.len()];
9804                    for (left_pos, key) in left_keys.iter().enumerate() {
9805                        if let Some(right_rows) = right_map.get(key) {
9806                            for &right_pos in right_rows {
9807                                left_by_right[right_pos].push(left_pos);
9808                            }
9809                        }
9810                    }
9811                    for (right_pos, key) in right_keys.iter().enumerate() {
9812                        let lefts = &left_by_right[right_pos];
9813                        if lefts.is_empty() {
9814                            push_merge_row_key(&mut out_row_keys, key);
9815                            left_positions.push(None);
9816                            right_positions.push(Some(right_pos));
9817                        } else {
9818                            for &left_pos in lefts {
9819                                push_merge_row_key(&mut out_row_keys, key);
9820                                left_positions.push(Some(left_pos));
9821                                right_positions.push(Some(right_pos));
9822                            }
9823                        }
9824                    }
9825                }
9826                JoinType::Cross => {
9827                    return Err(JoinError::Frame(FrameError::CompatibilityRejected(
9828                        "cross join must be handled by merge_dataframes_cross".to_owned(),
9829                    )));
9830                }
9831            }
9832
9833            // Sort the output rows by join key in-place while left_keys/right_keys
9834            // are in scope (read by reference per row — no out_row_keys clone).
9835            if needs_key_order {
9836                sort_merge_rows_by_join_keys(
9837                    &left_keys,
9838                    &right_keys,
9839                    &mut left_positions,
9840                    &mut right_positions,
9841                );
9842            }
9843            (left_positions, right_positions, out_row_keys)
9844        };
9845
9846    let all_positions_present = matches!(join_type, JoinType::Inner)
9847        || (matches!(
9848            join_type,
9849            JoinType::Left | JoinType::Right | JoinType::Outer
9850        ) && left_positions.iter().all(Option::is_some)
9851            && right_positions.iter().all(Option::is_some));
9852    let all_present_take_positions = all_positions_present.then(|| {
9853        let left = left_positions
9854            .iter()
9855            .map(|position| position.expect("all-present join emits left positions for every row"))
9856            .collect::<Vec<_>>();
9857        let right = right_positions
9858            .iter()
9859            .map(|position| position.expect("all-present join emits right positions for every row"))
9860            .collect::<Vec<_>>();
9861        (left, right)
9862    });
9863    let all_present_left_positions = all_present_take_positions
9864        .as_ref()
9865        .map(|(positions, _)| positions.as_slice());
9866    let all_present_right_positions = all_present_take_positions
9867        .as_ref()
9868        .map(|(_, positions)| positions.as_slice());
9869
9870    // Build output columns by reindexing.
9871    let n = left_positions.len();
9872    // Lazy unit-range output index (see build_single_key_dense_i64 site).
9873    let index = Index::new_known_unique_int64_unit_range(0, n);
9874    let mut columns = ColumnStore::new();
9875    let mut column_order: Vec<String> = Vec::new();
9876
9877    // Collect column names to handle conflicts.
9878    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
9879    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
9880    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
9881    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
9882
9883    // Track positional pairs where left_on[i] and right_on[i] share the same key name.
9884    let mut shared_name_positions = HashMap::<&str, (usize, usize)>::new();
9885    for (idx, (left_key_name, right_key_name)) in left_on.iter().zip(right_on.iter()).enumerate() {
9886        if left_key_name == right_key_name {
9887            shared_name_positions.insert(*left_key_name, (idx, idx));
9888        }
9889    }
9890    let shared_key_names = shared_name_positions
9891        .keys()
9892        .copied()
9893        .collect::<HashSet<&str>>();
9894    let overlapping_names =
9895        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
9896    ensure_merge_suffixes_for_overlaps(&overlapping_names, &suffixes)?;
9897
9898    // Add left columns (including left key columns) in the left frame's own
9899    // column order (pandas preserves it; the BTreeMap would re-sort) — br-691lh.
9900    for name in left.column_names() {
9901        let col = left
9902            .columns()
9903            .get(name)
9904            .expect("left column listed in column_names must exist");
9905        if left_key_name_set.contains(name.as_str()) {
9906            if let Some((left_key_idx, right_key_idx)) = shared_name_positions.get(name.as_str()) {
9907                // Shared key name: for rows emitted from right-only keys, source key values from
9908                // the right frame instead of leaving them null.
9909                let left_key_col = left_key_columns[*left_key_idx];
9910                let key_column = if let Some(positions) = all_present_left_positions {
9911                    take_positions_typed(left_key_col, positions)
9912                } else {
9913                    let right_key_col = right_key_columns[*right_key_idx];
9914                    coalesce_utf8_contiguous_key_column(
9915                        left_key_col,
9916                        right_key_col,
9917                        &left_positions,
9918                        &right_positions,
9919                    )
9920                    .map(Ok)
9921                    .unwrap_or_else(|| {
9922                        let values = left_positions
9923                            .iter()
9924                            .zip(right_positions.iter())
9925                            .map(|(left_pos, right_pos)| match (left_pos, right_pos) {
9926                                (Some(pos), _) => left_key_col.values()[*pos].clone(),
9927                                (None, Some(pos)) => right_key_col.values()[*pos].clone(),
9928                                (None, None) => fp_types::Scalar::Null(fp_types::NullKind::Null),
9929                            })
9930                            .collect::<Vec<_>>();
9931                        Column::from_values(values)
9932                    })?
9933                };
9934                insert_merged_output_column(
9935                    &mut columns,
9936                    &mut column_order,
9937                    name.clone(),
9938                    key_column,
9939                )?;
9940            } else {
9941                let key_column = if let Some(positions) = all_present_left_positions {
9942                    take_positions_typed(col, positions)
9943                } else {
9944                    reindex_join_column_with_invented_gap(col, &left_positions)?
9945                };
9946                insert_merged_output_column(
9947                    &mut columns,
9948                    &mut column_order,
9949                    name.clone(),
9950                    key_column,
9951                )?;
9952            }
9953            continue;
9954        }
9955        let reindexed = if let Some(positions) = all_present_left_positions {
9956            take_positions_typed(col, positions)
9957        } else {
9958            reindex_join_column_with_invented_gap(col, &left_positions)?
9959        };
9960        let out_name = if right_col_names.contains(name) {
9961            apply_merge_suffix(name, suffixes.left.as_deref())
9962        } else {
9963            name.clone()
9964        };
9965        insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
9966    }
9967
9968    // Add right non-key columns in the right frame's own column order — br-691lh.
9969    for name in right.column_names() {
9970        let col = right
9971            .columns()
9972            .get(name)
9973            .expect("right column listed in column_names must exist");
9974        if right_key_name_set.contains(name.as_str())
9975            && shared_name_positions.contains_key(name.as_str())
9976        {
9977            // Shared same-name key already emitted from the left side.
9978            continue;
9979        }
9980        let reindexed = if let Some(positions) = all_present_right_positions {
9981            take_positions_typed(col, positions)
9982        } else {
9983            reindex_join_column_with_invented_gap(col, &right_positions)?
9984        };
9985        let out_name = if left_col_names.contains(name) {
9986            apply_merge_suffix(name, suffixes.right.as_deref())
9987        } else {
9988            name.clone()
9989        };
9990        insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
9991    }
9992
9993    if let Some(indicator_name) = indicator_name.as_deref() {
9994        ensure_indicator_name_available(
9995            indicator_name,
9996            &left_col_names,
9997            &right_col_names,
9998            &columns,
9999        )?;
10000        let indicator_col = build_merge_indicator_column(&left_positions, &right_positions)?;
10001        insert_merged_output_column(
10002            &mut columns,
10003            &mut column_order,
10004            indicator_name.to_owned(),
10005            indicator_col,
10006        )?;
10007    }
10008
10009    Ok(MergedDataFrame {
10010        index,
10011        columns,
10012        column_order,
10013    })
10014}
10015
10016/// Merge two DataFrames on one or more key columns with identical key names.
10017///
10018/// Matches `pd.merge(left, right, on=keys, how=join_type)`.
10019pub fn merge_dataframes_on(
10020    left: &fp_frame::DataFrame,
10021    right: &fp_frame::DataFrame,
10022    on: &[&str],
10023    join_type: JoinType,
10024) -> Result<MergedDataFrame, JoinError> {
10025    merge_dataframes_on_with(left, right, on, on, join_type)
10026}
10027
10028/// Merge two DataFrames on a single key column.
10029pub fn merge_dataframes(
10030    left: &fp_frame::DataFrame,
10031    right: &fp_frame::DataFrame,
10032    on: &str,
10033    join_type: JoinType,
10034) -> Result<MergedDataFrame, JoinError> {
10035    if matches!(join_type, JoinType::Inner) {
10036        let left_key = left.column(on).ok_or_else(|| {
10037            JoinError::Frame(FrameError::CompatibilityRejected(format!(
10038                "left DataFrame missing key column '{on}'"
10039            )))
10040        })?;
10041        let right_key = right.column(on).ok_or_else(|| {
10042            JoinError::Frame(FrameError::CompatibilityRejected(format!(
10043                "right DataFrame missing key column '{on}'"
10044            )))
10045        })?;
10046        let suffixes = ResolvedMergeSuffixes::default();
10047        return merge_single_key_inner_unsorted(
10048            left,
10049            right,
10050            &[on],
10051            &[on],
10052            &[left_key],
10053            &[right_key],
10054            &suffixes,
10055        );
10056    }
10057    merge_dataframes_on(left, right, &[on], join_type)
10058}
10059
10060fn merge_dataframes_cross(
10061    left: &fp_frame::DataFrame,
10062    right: &fp_frame::DataFrame,
10063    indicator_name: Option<&str>,
10064    suffixes: &ResolvedMergeSuffixes,
10065) -> Result<MergedDataFrame, JoinError> {
10066    let left_rows = left.index().len();
10067    let right_rows = right.index().len();
10068    let out_rows = left_rows.saturating_mul(right_rows);
10069
10070    let mut left_positions = Vec::<Option<usize>>::with_capacity(out_rows);
10071    let mut right_positions = Vec::<Option<usize>>::with_capacity(out_rows);
10072    for left_pos in 0..left_rows {
10073        for right_pos in 0..right_rows {
10074            left_positions.push(Some(left_pos));
10075            right_positions.push(Some(right_pos));
10076        }
10077    }
10078
10079    let index = Index::new((0..out_rows as i64).map(IndexLabel::from).collect());
10080    let mut columns = ColumnStore::new();
10081    let mut column_order: Vec<String> = Vec::new();
10082
10083    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
10084    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
10085    let overlapping_names =
10086        collect_overlapping_column_names(&left_col_names, &right_col_names, &HashSet::new());
10087    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
10088
10089    for (name, col) in left.columns() {
10090        let reindexed = col.reindex_by_positions(&left_positions)?;
10091        let out_name = if right_col_names.contains(name) {
10092            apply_merge_suffix(name, suffixes.left.as_deref())
10093        } else {
10094            name.clone()
10095        };
10096        insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
10097    }
10098
10099    for (name, col) in right.columns() {
10100        let reindexed = col.reindex_by_positions(&right_positions)?;
10101        let out_name = if left_col_names.contains(name) {
10102            apply_merge_suffix(name, suffixes.right.as_deref())
10103        } else {
10104            name.clone()
10105        };
10106        insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
10107    }
10108
10109    if let Some(indicator_name) = indicator_name {
10110        ensure_indicator_name_available(
10111            indicator_name,
10112            &left_col_names,
10113            &right_col_names,
10114            &columns,
10115        )?;
10116        let indicator_col = build_merge_indicator_column(&left_positions, &right_positions)?;
10117        insert_merged_output_column(
10118            &mut columns,
10119            &mut column_order,
10120            indicator_name.to_owned(),
10121            indicator_col,
10122        )?;
10123    }
10124
10125    Ok(MergedDataFrame {
10126        index,
10127        columns,
10128        column_order,
10129    })
10130}
10131
10132/// Extension trait adding `.merge()` and `.join()` instance methods to `DataFrame`.
10133///
10134/// Import this trait to get pandas-style `df.merge(other, ...)` and `df.join(other, ...)`
10135/// as instance methods.
10136pub trait DataFrameMergeExt {
10137    /// Merge this DataFrame with another on shared key columns.
10138    ///
10139    /// Matches `pd.DataFrame.merge(other, on=keys, how=join_type)`.
10140    fn merge(
10141        &self,
10142        other: &fp_frame::DataFrame,
10143        on: &[&str],
10144        how: JoinType,
10145    ) -> Result<MergedDataFrame, JoinError>;
10146
10147    /// Merge with separate left/right key columns and execution options.
10148    ///
10149    /// Matches `pd.DataFrame.merge(other, left_on=..., right_on=..., how=...)`.
10150    fn merge_with_options(
10151        &self,
10152        other: &fp_frame::DataFrame,
10153        left_on: &[&str],
10154        right_on: &[&str],
10155        how: JoinType,
10156        options: MergeExecutionOptions,
10157    ) -> Result<MergedDataFrame, JoinError>;
10158
10159    /// Join another DataFrame on the index.
10160    ///
10161    /// Matches `pd.DataFrame.join(other, how=join_type)` (index-based join).
10162    fn join_on_index(
10163        &self,
10164        other: &fp_frame::DataFrame,
10165        how: JoinType,
10166    ) -> Result<MergedDataFrame, JoinError>;
10167
10168    /// pandas-named alias for [`Self::join_on_index`]. Matches
10169    /// `pd.DataFrame.join(other, how=...)` directly. Per br-frankenpandas-nk54a.
10170    ///
10171    /// Default impl delegates to `join_on_index`. Implementors that already
10172    /// have an optimized index-based join can leave this default.
10173    fn join(
10174        &self,
10175        other: &fp_frame::DataFrame,
10176        how: JoinType,
10177    ) -> Result<MergedDataFrame, JoinError> {
10178        self.join_on_index(other, how)
10179    }
10180
10181    /// Perform an asof merge (nearest-match join) on a sorted key column.
10182    ///
10183    /// Matches `pd.merge_asof(left, right, on=key)`. Both DataFrames must
10184    /// be sorted by the key column. For each row in `left`, finds the last
10185    /// row in `right` where `right[on] <= left[on]` (backward direction)
10186    /// or the nearest row in the specified direction.
10187    ///
10188    /// `direction`: "backward" (default), "forward", "nearest".
10189    fn merge_asof(
10190        &self,
10191        other: &fp_frame::DataFrame,
10192        on: &str,
10193        direction: &str,
10194    ) -> Result<MergedDataFrame, JoinError>;
10195
10196    /// Perform an asof merge with additional options.
10197    ///
10198    /// Matches `pd.merge_asof(left, right, on=key, direction=...,
10199    /// allow_exact_matches=..., tolerance=..., by=...)`.
10200    ///
10201    /// # Parameters
10202    /// - `other`: Right DataFrame to merge with
10203    /// - `on`: Column name to merge on (must be numeric and sorted)
10204    /// - `direction`: "backward", "forward", or "nearest"
10205    /// - `options`: Additional options (allow_exact_matches, tolerance, by)
10206    fn merge_asof_with_options(
10207        &self,
10208        other: &fp_frame::DataFrame,
10209        on: &str,
10210        direction: &str,
10211        options: MergeAsofOptions,
10212    ) -> Result<MergedDataFrame, JoinError>;
10213
10214    /// Perform an ordered merge (outer join + sort by keys).
10215    ///
10216    /// Matches `pd.merge_ordered(left, right, on=keys, fill_method=...)`.
10217    fn merge_ordered(
10218        &self,
10219        other: &fp_frame::DataFrame,
10220        on: &[&str],
10221        fill_method: Option<&str>,
10222    ) -> Result<MergedDataFrame, JoinError>;
10223}
10224
10225/// Perform an ordered merge of two DataFrames.
10226///
10227/// Matches `pd.merge_ordered(left, right, on=keys, fill_method=...)`.
10228/// Performs an outer join and ensures the result is sorted by the join keys.
10229pub fn merge_ordered(
10230    left: &fp_frame::DataFrame,
10231    right: &fp_frame::DataFrame,
10232    on: &[&str],
10233    fill_method: Option<&str>,
10234) -> Result<MergedDataFrame, JoinError> {
10235    let options = MergeExecutionOptions {
10236        sort: true,
10237        ..MergeExecutionOptions::default()
10238    };
10239    let merged = merge_dataframes_on_with_options(left, right, on, on, JoinType::Outer, options)?;
10240
10241    if let Some(method) = fill_method {
10242        // Convert to DataFrame to apply fill
10243        let mut df = fp_frame::DataFrame::new_with_column_order(
10244            merged.index.clone(),
10245            merged.columns.clone(),
10246            merged.column_order.clone(),
10247        )
10248        .map_err(JoinError::Frame)?;
10249
10250        df = match method {
10251            "ffill" => df.ffill(None).map_err(JoinError::Frame)?,
10252            _ => {
10253                return Err(JoinError::Frame(FrameError::CompatibilityRejected(
10254                    format!("merge_ordered: fill_method must be 'ffill' or None, got '{method}'"),
10255                )));
10256            }
10257        };
10258
10259        let column_order = df.column_names().into_iter().cloned().collect();
10260        Ok(MergedDataFrame {
10261            index: df.index().clone(),
10262            columns: df.columns().clone(),
10263            column_order,
10264        })
10265    } else {
10266        Ok(merged)
10267    }
10268}
10269
10270/// Direction for asof merge matching.
10271#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10272pub enum AsofDirection {
10273    Backward,
10274    Forward,
10275    Nearest,
10276}
10277
10278/// Options for asof merge operations.
10279///
10280/// Matches pandas `merge_asof` parameters:
10281/// - `allow_exact_matches`: If true (default), allow matching with same key value
10282/// - `tolerance`: Maximum distance between keys for a match
10283/// - `by`: Columns to match exactly before asof matching
10284#[derive(Debug, Clone, Default)]
10285pub struct MergeAsofOptions {
10286    /// If true (default), allow matching with the same 'on' value.
10287    /// If false, don't match rows where left key == right key exactly.
10288    pub allow_exact_matches: bool,
10289    /// Maximum distance between left and right keys for a valid match.
10290    /// None means no tolerance limit.
10291    pub tolerance: Option<f64>,
10292    /// Columns to match exactly before performing asof merge.
10293    /// Acts like an equi-join on these columns first.
10294    pub by: Option<Vec<String>>,
10295}
10296
10297impl MergeAsofOptions {
10298    /// Create options with defaults matching pandas behavior.
10299    pub fn new() -> Self {
10300        Self {
10301            allow_exact_matches: true,
10302            tolerance: None,
10303            by: None,
10304        }
10305    }
10306
10307    /// Set whether exact matches are allowed.
10308    pub fn allow_exact_matches(mut self, allow: bool) -> Self {
10309        self.allow_exact_matches = allow;
10310        self
10311    }
10312
10313    /// Set the tolerance for matching.
10314    pub fn tolerance(mut self, tol: f64) -> Self {
10315        self.tolerance = Some(tol);
10316        self
10317    }
10318
10319    /// Set the columns to match exactly before asof merge.
10320    pub fn by(mut self, cols: Vec<String>) -> Self {
10321        self.by = Some(cols);
10322        self
10323    }
10324}
10325
10326/// When BOTH `on` keys are Datetime64, extract them as f64 SHIFTED by the global
10327/// minimum ns so the values fit f64's 2^53 integer precision exactly. A raw
10328/// Datetime64->ns->f64 cast collapses ns (~1.6e18) to garbage (>2^53), so
10329/// merge_asof previously REJECTED datetime keys ("must be numeric") — the primary
10330/// time-series asof case. Shifting is order- and difference-preserving (both sides
10331/// by the same min), so the f64 asof match + tolerance stay exact whenever the ns
10332/// RANGE fits 2^53 (~104 days). Returns:
10333/// - `None`: not both Datetime64 → caller uses the f64 numeric path unchanged.
10334/// - `Some(Err)`: range too wide for exact f64 → clean rejection (better than the
10335///   silently-wrong result a lossy cast would give).
10336/// - `Some(Ok((left,right)))`: shifted f64 keys, NaT/null → NaN.
10337type ShiftedDatetimeAsofKeys = (Vec<f64>, Vec<f64>);
10338
10339fn try_asof_datetime_shift(
10340    left_key: &Column,
10341    right_key: &Column,
10342    on: &str,
10343) -> Option<Result<ShiftedDatetimeAsofKeys, JoinError>> {
10344    if !matches!(
10345        (left_key.dtype(), right_key.dtype()),
10346        (DType::Datetime64 { tz: left_tz }, DType::Datetime64 { tz: right_tz }) if left_tz == right_tz
10347    ) {
10348        return None;
10349    }
10350    let ld = left_key.as_datetime64_slice()?;
10351    let rd = right_key.as_datetime64_slice()?;
10352    let lv = left_key.validity();
10353    let rv = right_key.validity();
10354    // All-valid fast path: when a side has no null bits, the per-element
10355    // ValidityMask::get bit-test is skipped in both the min-scan and the shift
10356    // (only the cheap NaT sentinel compare remains, which vectorizes). NaT/null
10357    // are rare in an asof `on` key, so this is the hot path.
10358    let l_all = lv.all();
10359    let r_all = rv.all();
10360    let is_valid = |data: &[i64], v: &fp_columnar::ValidityMask, all: bool, i: usize| -> bool {
10361        (all || v.get(i)) && data[i] != fp_types::Timestamp::NAT
10362    };
10363    // Global min/max over the valid (non-NaT) ns of both sides.
10364    let mut lo = i64::MAX;
10365    let mut hi = i64::MIN;
10366    let mut any = false;
10367    for i in 0..ld.len() {
10368        if is_valid(ld, lv, l_all, i) {
10369            lo = lo.min(ld[i]);
10370            hi = hi.max(ld[i]);
10371            any = true;
10372        }
10373    }
10374    for i in 0..rd.len() {
10375        if is_valid(rd, rv, r_all, i) {
10376            lo = lo.min(rd[i]);
10377            hi = hi.max(rd[i]);
10378            any = true;
10379        }
10380    }
10381    if !any {
10382        // All-NaT/empty: every shifted value is NaN; produce that directly.
10383        return Some(Ok((vec![f64::NAN; ld.len()], vec![f64::NAN; rd.len()])));
10384    }
10385    if (hi as i128 - lo as i128) >= (1i128 << 53) {
10386        return Some(Err(JoinError::Frame(FrameError::CompatibilityRejected(
10387            format!(
10388                "merge_asof: Datetime64 key '{on}' spans more than ~104 days of nanoseconds, \
10389             which exceeds f64 asof precision; not yet supported"
10390            ),
10391        ))));
10392    }
10393    let shift = |data: &[i64], v: &fp_columnar::ValidityMask, all: bool| -> Vec<f64> {
10394        (0..data.len())
10395            .map(|i| {
10396                if is_valid(data, v, all, i) {
10397                    (data[i] - lo) as f64
10398                } else {
10399                    f64::NAN
10400                }
10401            })
10402            .collect()
10403    };
10404    Some(Ok((shift(ld, lv, l_all), shift(rd, rv, r_all))))
10405}
10406
10407#[derive(Clone, Copy)]
10408struct Datetime64AsofKey<'a> {
10409    data: &'a [i64],
10410    validity: &'a ValidityMask,
10411    all_valid: bool,
10412}
10413
10414impl Datetime64AsofKey<'_> {
10415    #[inline]
10416    fn is_valid(self, i: usize) -> bool {
10417        (self.all_valid || self.validity.get(i)) && self.data[i] != fp_types::Timestamp::NAT
10418    }
10419}
10420
10421fn datetime64_key_parts(column: &Column) -> Option<Datetime64AsofKey<'_>> {
10422    let data = column.as_datetime64_slice()?;
10423    let validity = column.validity();
10424    Some(Datetime64AsofKey {
10425        data,
10426        validity,
10427        all_valid: validity.all(),
10428    })
10429}
10430
10431fn ensure_sorted_non_decreasing_datetime64(
10432    key: Datetime64AsofKey<'_>,
10433    side: &str,
10434    on: &str,
10435) -> Result<(), JoinError> {
10436    let mut prev: Option<i64> = None;
10437    for i in 0..key.data.len() {
10438        if !key.is_valid(i) {
10439            continue;
10440        }
10441        let value = key.data[i];
10442        if let Some(prev_value) = prev
10443            && value < prev_value
10444        {
10445            return Err(JoinError::Frame(FrameError::CompatibilityRejected(
10446                format!("merge_asof: {side} column '{on}' must be sorted"),
10447            )));
10448        }
10449        prev = Some(value);
10450    }
10451    Ok(())
10452}
10453
10454fn within_datetime64_tolerance(left: i64, right: i64, tolerance: Option<f64>) -> bool {
10455    match tolerance {
10456        Some(tol) => ((left as i128 - right as i128).abs() as f64) <= tol,
10457        None => true,
10458    }
10459}
10460
10461fn compute_asof_matches_datetime64(
10462    left: Datetime64AsofKey<'_>,
10463    right: Datetime64AsofKey<'_>,
10464    direction: AsofDirection,
10465    allow_exact_matches: bool,
10466    tolerance: Option<f64>,
10467) -> Vec<Option<usize>> {
10468    let mut filtered_values = Vec::new();
10469    let mut filtered_positions = Vec::new();
10470    let (right_valid_values, right_valid_positions) =
10471        if right.all_valid && !right.data.contains(&fp_types::Timestamp::NAT) {
10472            (right.data, None)
10473        } else {
10474            for i in 0..right.data.len() {
10475                if right.is_valid(i) {
10476                    filtered_values.push(right.data[i]);
10477                    filtered_positions.push(i);
10478                }
10479            }
10480            (
10481                filtered_values.as_slice(),
10482                Some(filtered_positions.as_slice()),
10483            )
10484        };
10485
10486    compute_asof_matches_datetime64_prepared(
10487        left,
10488        right_valid_values,
10489        right_valid_positions,
10490        direction,
10491        allow_exact_matches,
10492        tolerance,
10493    )
10494}
10495
10496fn compute_asof_matches_datetime64_prepared(
10497    left: Datetime64AsofKey<'_>,
10498    right_valid_values: &[i64],
10499    right_valid_positions: Option<&[usize]>,
10500    direction: AsofDirection,
10501    allow_exact_matches: bool,
10502    tolerance: Option<f64>,
10503) -> Vec<Option<usize>> {
10504    let right_source_position =
10505        |position: usize| right_valid_positions.map_or(position, |positions| positions[position]);
10506
10507    let mut right_matches = Vec::with_capacity(left.data.len());
10508
10509    match direction {
10510        AsofDirection::Backward => {
10511            let mut best: Option<usize> = None;
10512            let mut best_val: Option<i64> = None;
10513            let mut j = 0usize;
10514            for i in 0..left.data.len() {
10515                if !left.is_valid(i) {
10516                    right_matches.push(None);
10517                    continue;
10518                }
10519                let lv = left.data[i];
10520                while j < right_valid_values.len() {
10521                    let rv = right_valid_values[j];
10522                    let should_include = if allow_exact_matches {
10523                        rv <= lv
10524                    } else {
10525                        rv < lv
10526                    };
10527                    if !should_include {
10528                        break;
10529                    }
10530                    best = Some(right_source_position(j));
10531                    best_val = Some(rv);
10532                    j += 1;
10533                }
10534
10535                let matched = match (best, best_val) {
10536                    (Some(idx), Some(rv)) if within_datetime64_tolerance(lv, rv, tolerance) => {
10537                        Some(idx)
10538                    }
10539                    _ => None,
10540                };
10541                right_matches.push(matched);
10542            }
10543        }
10544        AsofDirection::Forward => {
10545            let mut j = 0usize;
10546            for i in 0..left.data.len() {
10547                if !left.is_valid(i) {
10548                    right_matches.push(None);
10549                    continue;
10550                }
10551                let lv = left.data[i];
10552                while j < right_valid_values.len() {
10553                    let rv = right_valid_values[j];
10554                    let should_skip = if allow_exact_matches {
10555                        rv < lv
10556                    } else {
10557                        rv <= lv
10558                    };
10559                    if !should_skip {
10560                        break;
10561                    }
10562                    j += 1;
10563                }
10564
10565                if j < right_valid_values.len() {
10566                    let rv = right_valid_values[j];
10567                    if within_datetime64_tolerance(lv, rv, tolerance) {
10568                        right_matches.push(Some(right_source_position(j)));
10569                    } else {
10570                        right_matches.push(None);
10571                    }
10572                } else {
10573                    right_matches.push(None);
10574                }
10575            }
10576        }
10577        AsofDirection::Nearest => {
10578            for i in 0..left.data.len() {
10579                if !left.is_valid(i) {
10580                    right_matches.push(None);
10581                    continue;
10582                }
10583                if right_valid_values.is_empty() {
10584                    right_matches.push(None);
10585                    continue;
10586                }
10587
10588                let lv = left.data[i];
10589                let (lower, upper) = if allow_exact_matches {
10590                    let lo = right_valid_values.partition_point(|rv| *rv <= lv);
10591                    let up = right_valid_values.partition_point(|rv| *rv < lv);
10592                    (
10593                        if lo > 0 { Some(lo - 1) } else { None },
10594                        if up < right_valid_values.len() {
10595                            Some(up)
10596                        } else {
10597                            None
10598                        },
10599                    )
10600                } else {
10601                    let lo = right_valid_values.partition_point(|rv| *rv < lv);
10602                    let up = right_valid_values.partition_point(|rv| *rv <= lv);
10603                    (
10604                        if lo > 0 { Some(lo - 1) } else { None },
10605                        if up < right_valid_values.len() {
10606                            Some(up)
10607                        } else {
10608                            None
10609                        },
10610                    )
10611                };
10612
10613                let chosen = match (lower, upper) {
10614                    (Some(l), Some(u)) => {
10615                        let lower_dist = (right_valid_values[l] as i128 - lv as i128).abs();
10616                        let upper_dist = (right_valid_values[u] as i128 - lv as i128).abs();
10617                        if upper_dist < lower_dist {
10618                            Some(u)
10619                        } else {
10620                            Some(l)
10621                        }
10622                    }
10623                    (Some(l), None) => Some(l),
10624                    (None, Some(u)) => Some(u),
10625                    (None, None) => None,
10626                };
10627
10628                let matched = match chosen {
10629                    Some(idx)
10630                        if within_datetime64_tolerance(lv, right_valid_values[idx], tolerance) =>
10631                    {
10632                        Some(right_source_position(idx))
10633                    }
10634                    _ => None,
10635                };
10636                right_matches.push(matched);
10637            }
10638        }
10639    }
10640
10641    right_matches
10642}
10643
10644fn try_asof_datetime_matches(
10645    left_key: &Column,
10646    right_key: &Column,
10647    on: &str,
10648    direction: AsofDirection,
10649    allow_exact_matches: bool,
10650    tolerance: Option<f64>,
10651) -> Option<Result<Vec<Option<usize>>, JoinError>> {
10652    if !matches!(
10653        (left_key.dtype(), right_key.dtype()),
10654        (DType::Datetime64 { tz: left_tz }, DType::Datetime64 { tz: right_tz }) if left_tz == right_tz
10655    ) {
10656        return None;
10657    }
10658    let left = datetime64_key_parts(left_key)?;
10659    let right = datetime64_key_parts(right_key)?;
10660
10661    Some((|| {
10662        ensure_sorted_non_decreasing_datetime64(left, "left", on)?;
10663        ensure_sorted_non_decreasing_datetime64(right, "right", on)?;
10664
10665        Ok(compute_asof_matches_datetime64(
10666            left,
10667            right,
10668            direction,
10669            allow_exact_matches,
10670            tolerance,
10671        ))
10672    })())
10673}
10674
10675fn asof_numeric_values(column: &Column, side: &str, on: &str) -> Result<Vec<f64>, JoinError> {
10676    // Typed fast path: an all-valid Int64/Float64 key column reads the raw slice
10677    // directly, skipping the per-cell values() Scalar materialization + to_f64
10678    // dispatch (merge_asof key extraction was ~0.83x pandas). Bit-identical:
10679    // as_i64_slice/as_f64_slice are all-valid (no missing → no NaN-fill branch),
10680    // and Scalar::Int64(v).to_f64() == v as f64, Scalar::Float64(v).to_f64() == v.
10681    // Nullable / Timedelta64 / Datetime64 keys fall through to the Scalar loop.
10682    if let Some(data) = column.as_i64_slice() {
10683        return Ok(data.iter().map(|&v| v as f64).collect());
10684    }
10685    if let Some(data) = column.as_f64_slice() {
10686        return Ok(data.to_vec());
10687    }
10688    let mut out = Vec::with_capacity(column.len());
10689    for value in column.values() {
10690        // pandas merge_asof accepts Timedelta64 (and datetime) `on` columns
10691        // and orders them by ns count. Scalar::Timedelta64.to_f64() returns
10692        // NonNumericValue, so the default branch would reject the join.
10693        // Extract ns directly for non-NaT Timedelta values; treat NaT as NaN
10694        // (matches the ValueIsMissing arm below).
10695        if let Scalar::Timedelta64(ns) = value {
10696            if *ns == fp_types::Timedelta::NAT {
10697                out.push(f64::NAN);
10698            } else {
10699                out.push(*ns as f64);
10700            }
10701            continue;
10702        }
10703        match value.to_f64() {
10704            Ok(v) => out.push(v),
10705            Err(TypeError::ValueIsMissing { .. }) => out.push(f64::NAN),
10706            Err(_) => {
10707                return Err(JoinError::Frame(FrameError::CompatibilityRejected(
10708                    format!("merge_asof: {side} column '{on}' must be numeric"),
10709                )));
10710            }
10711        }
10712    }
10713    Ok(out)
10714}
10715
10716/// `merge_asof` compares ordering keys rather than coercing them to a common
10717/// numeric representation.  Converting both sides to `f64` before validating
10718/// their dtypes makes an `int64` key appear compatible with a `float64` key,
10719/// which pandas rejects even when every finite value is exactly representable.
10720fn ensure_matching_asof_key_dtypes(
10721    left_key: &Column,
10722    right_key: &Column,
10723    on: &str,
10724) -> Result<(), JoinError> {
10725    if left_key.dtype() != right_key.dtype() {
10726        return Err(JoinError::Frame(FrameError::CompatibilityRejected(
10727            format!(
10728                "merge_asof: incompatible merge keys [0] for '{on}': left dtype('{}'), right dtype('{}'), must be the same type",
10729                left_key.dtype().name(),
10730                right_key.dtype().name(),
10731            ),
10732        )));
10733    }
10734    Ok(())
10735}
10736
10737fn ensure_sorted_non_decreasing(values: &[f64], side: &str, on: &str) -> Result<(), JoinError> {
10738    let mut prev: Option<f64> = None;
10739    for &value in values {
10740        if value.is_nan() {
10741            continue;
10742        }
10743        if let Some(prev_value) = prev
10744            && value < prev_value
10745        {
10746            return Err(JoinError::Frame(FrameError::CompatibilityRejected(
10747                format!("merge_asof: {side} column '{on}' must be sorted"),
10748            )));
10749        }
10750        prev = Some(value);
10751    }
10752    Ok(())
10753}
10754
10755/// Perform an asof merge between two DataFrames.
10756pub fn merge_asof(
10757    left: &fp_frame::DataFrame,
10758    right: &fp_frame::DataFrame,
10759    on: &str,
10760    direction: AsofDirection,
10761) -> Result<MergedDataFrame, JoinError> {
10762    merge_asof_with_options(left, right, on, direction, MergeAsofOptions::new())
10763}
10764
10765/// Perform an asof merge between two DataFrames with additional options.
10766///
10767/// # Parameters
10768/// - `left`: Left DataFrame
10769/// - `right`: Right DataFrame
10770/// - `on`: Column name to merge on (must be numeric and sorted)
10771/// - `direction`: Match direction (Backward, Forward, Nearest)
10772/// - `options`: Additional merge options (allow_exact_matches, tolerance, by)
10773pub fn merge_asof_with_options(
10774    left: &fp_frame::DataFrame,
10775    right: &fp_frame::DataFrame,
10776    on: &str,
10777    direction: AsofDirection,
10778    options: MergeAsofOptions,
10779) -> Result<MergedDataFrame, JoinError> {
10780    // If `by` columns are specified, we need to do grouped asof merge
10781    if let Some(ref by_cols) = options.by {
10782        return merge_asof_grouped(left, right, on, direction, &options, by_cols);
10783    }
10784
10785    merge_asof_simple(left, right, on, direction, &options)
10786}
10787
10788/// Simple asof merge without grouping.
10789fn merge_asof_simple(
10790    left: &fp_frame::DataFrame,
10791    right: &fp_frame::DataFrame,
10792    on: &str,
10793    direction: AsofDirection,
10794    options: &MergeAsofOptions,
10795) -> Result<MergedDataFrame, JoinError> {
10796    let left_key = left.columns().get(on).ok_or_else(|| {
10797        JoinError::Frame(FrameError::CompatibilityRejected(format!(
10798            "merge_asof: column '{on}' not found in left"
10799        )))
10800    })?;
10801    let right_key = right.columns().get(on).ok_or_else(|| {
10802        JoinError::Frame(FrameError::CompatibilityRejected(format!(
10803            "merge_asof: column '{on}' not found in right"
10804        )))
10805    })?;
10806
10807    ensure_matching_asof_key_dtypes(left_key, right_key, on)?;
10808
10809    if let Some(datetime_matches) = try_asof_datetime_matches(
10810        left_key,
10811        right_key,
10812        on,
10813        direction,
10814        options.allow_exact_matches,
10815        options.tolerance,
10816    ) {
10817        let right_matches = datetime_matches?;
10818        return build_asof_output(left, right, on, &right_matches, None);
10819    }
10820
10821    // Non-Datetime64 keys: use the f64 numeric path. The grouped Datetime64
10822    // route below still uses the old shift-to-f64 bridge until it gets its own
10823    // i64 grouped path.
10824    let (left_vals, right_vals) = match try_asof_datetime_shift(left_key, right_key, on) {
10825        Some(shifted) => shifted?,
10826        None => (
10827            asof_numeric_values(left_key, "left", on)?,
10828            asof_numeric_values(right_key, "right", on)?,
10829        ),
10830    };
10831
10832    // With matching key dtypes, pandas accepts NaN keys: the NaN row gets a
10833    // null in the joined columns (no match). Dtype incompatibility is rejected
10834    // above before this value-level rule is reached.
10835    ensure_sorted_non_decreasing(&left_vals, "left", on)?;
10836    ensure_sorted_non_decreasing(&right_vals, "right", on)?;
10837
10838    let right_matches = compute_asof_matches(
10839        &left_vals,
10840        &right_vals,
10841        direction,
10842        options.allow_exact_matches,
10843        options.tolerance,
10844    );
10845
10846    build_asof_output(left, right, on, &right_matches, None)
10847}
10848
10849/// Grouped asof merge: match on `by` columns first, then asof within groups.
10850fn merge_asof_grouped(
10851    left: &fp_frame::DataFrame,
10852    right: &fp_frame::DataFrame,
10853    on: &str,
10854    direction: AsofDirection,
10855    options: &MergeAsofOptions,
10856    by_cols: &[String],
10857) -> Result<MergedDataFrame, JoinError> {
10858    // Validate by columns exist
10859    for col in by_cols {
10860        if left.columns().get(col).is_none() {
10861            return Err(JoinError::Frame(FrameError::CompatibilityRejected(
10862                format!("merge_asof: 'by' column '{col}' not found in left"),
10863            )));
10864        }
10865        if right.columns().get(col).is_none() {
10866            return Err(JoinError::Frame(FrameError::CompatibilityRejected(
10867                format!("merge_asof: 'by' column '{col}' not found in right"),
10868            )));
10869        }
10870    }
10871
10872    let left_key = left.columns().get(on).ok_or_else(|| {
10873        JoinError::Frame(FrameError::CompatibilityRejected(format!(
10874            "merge_asof: column '{on}' not found in left"
10875        )))
10876    })?;
10877    let right_key = right.columns().get(on).ok_or_else(|| {
10878        JoinError::Frame(FrameError::CompatibilityRejected(format!(
10879            "merge_asof: column '{on}' not found in right"
10880        )))
10881    })?;
10882
10883    ensure_matching_asof_key_dtypes(left_key, right_key, on)?;
10884
10885    // Datetime64 keys: shift-to-f64 (exact for <~104-day ns ranges) instead of the
10886    // rejected/precision-lossy direct cast. Falls back to the f64 numeric path.
10887    let (left_vals, right_vals) = match try_asof_datetime_shift(left_key, right_key, on) {
10888        Some(shifted) => shifted?,
10889        None => (
10890            asof_numeric_values(left_key, "left", on)?,
10891            asof_numeric_values(right_key, "right", on)?,
10892        ),
10893    };
10894
10895    // With matching key dtypes, pandas accepts NaN keys: the NaN row gets a
10896    // null in the joined columns (no match). Dtype incompatibility is rejected
10897    // above before this value-level rule is reached.
10898    ensure_sorted_non_decreasing(&left_vals, "left", on)?;
10899    ensure_sorted_non_decreasing(&right_vals, "right", on)?;
10900
10901    // Dense u32 group ids over the `by` columns (shared id space for left and
10902    // right). The single non-float `by` column case factorizes the column's
10903    // scalars with a borrowed typed key — no per-row `format!`/`Vec<String>`
10904    // allocation — and is bit-identical to the Debug-string grouping (see
10905    // `build_group_ids`). Everything else falls back to the string path.
10906    let (left_ids, right_ids) = build_group_ids(left, right, by_cols)?;
10907
10908    // Group right rows by their `by` group id for asof matching (looked up by
10909    // `.get()` per left group below). No per-group sort validation is needed:
10910    // the global `ensure_sorted_non_decreasing` checks above already require the
10911    // `on` column to be non-decreasing over the whole frame, and every
10912    // per-group subsequence of a sorted column is itself sorted — so the old
10913    // per-group checks were unreachable (the global check fires first on any
10914    // unsorted input). FxHashMap (vs std SipHash) speeds the build.
10915    let mut right_groups: FxHashMap<u32, Vec<usize>> = FxHashMap::default();
10916    for (idx, &id) in right_ids.iter().enumerate() {
10917        right_groups.entry(id).or_default().push(idx);
10918    }
10919
10920    // Group LEFT rows by their `by` group id (preserving the globally-sorted
10921    // order within each group), then run the monotonic two-pointer asof sweep
10922    // ONCE per group over all of the group's left values — instead of rebuilding
10923    // the group's right-value vector and re-scanning it from scratch for every
10924    // individual left row (the old O(L·R) per group). compute_asof_matches
10925    // already drives a single left array with a monotonic cursor and handles
10926    // NaN left keys (→ None, cursor unchanged); because every per-group left
10927    // subsequence is sorted (the global `on` column is non-decreasing), the
10928    // grouped sweep yields the identical match for each left row as the old
10929    // fresh-per-row scan. Results are scattered by absolute left index, so the
10930    // output order is independent of group-iteration order.
10931    let mut left_groups: FxHashMap<u32, Vec<usize>> = FxHashMap::default();
10932    for (left_idx, &id) in left_ids.iter().enumerate() {
10933        left_groups.entry(id).or_default().push(left_idx);
10934    }
10935
10936    let mut right_matches: Vec<Option<usize>> = vec![None; left_vals.len()];
10937    for (group_id, left_positions) in &left_groups {
10938        let Some(group_indices) = right_groups.get(group_id) else {
10939            continue; // no right rows for this group -> all matches stay None
10940        };
10941        let group_right_vals: Vec<f64> = group_indices.iter().map(|&i| right_vals[i]).collect();
10942        let group_left_vals: Vec<f64> = left_positions.iter().map(|&i| left_vals[i]).collect();
10943
10944        let group_matches = compute_asof_matches(
10945            &group_left_vals,
10946            &group_right_vals,
10947            direction,
10948            options.allow_exact_matches,
10949            options.tolerance,
10950        );
10951
10952        for (k, &left_idx) in left_positions.iter().enumerate() {
10953            if let Some(Some(group_idx)) = group_matches.get(k) {
10954                right_matches[left_idx] = Some(group_indices[*group_idx]);
10955            }
10956        }
10957    }
10958
10959    build_asof_output(left, right, on, &right_matches, Some(by_cols))
10960}
10961
10962/// Borrowed, allocation-free `by`-key for the single-column factorize fast
10963/// path. Each variant is the typed payload of a `Scalar` whose *derived*
10964/// `Debug` is injective and equality-consistent — so two scalars share a
10965/// `ByKey` iff their `format!("{val:?}")` strings (the legacy group key) are
10966/// equal. `Float64` (`-0.0` vs `0.0`, `NaN`) and `Interval` Debug strings
10967/// disagree with value equality, so `from_scalar` returns `None` for them and
10968/// the caller falls back to the string path.
10969#[derive(PartialEq, Eq, Hash)]
10970enum ByKey<'a> {
10971    Null(u8),
10972    Bool(bool),
10973    Int(i64),
10974    Str(&'a str),
10975    Timedelta(i64),
10976    Datetime(i64),
10977    Period(i64),
10978}
10979
10980impl<'a> ByKey<'a> {
10981    fn from_scalar(s: &'a Scalar) -> Option<Self> {
10982        Some(match s {
10983            Scalar::Null(NullKind::Null) => ByKey::Null(0),
10984            Scalar::Null(NullKind::NaN) => ByKey::Null(1),
10985            Scalar::Null(NullKind::NaT) => ByKey::Null(2),
10986            Scalar::Bool(b) => ByKey::Bool(*b),
10987            Scalar::Int64(v) => ByKey::Int(*v),
10988            Scalar::Utf8(s) => ByKey::Str(s.as_str()),
10989            Scalar::Timedelta64(v) => ByKey::Timedelta(*v),
10990            Scalar::Datetime64(v) => ByKey::Datetime(*v),
10991            Scalar::Period(v) => ByKey::Period(v.ordinal),
10992            Scalar::Float64(_) | Scalar::Interval(_) => return None,
10993        })
10994    }
10995}
10996
10997/// Factorize a single `by` column over both frames into a shared u32 id space.
10998/// Returns `None` (caller falls back to the string path) if any value is a
10999/// `Float64`/`Interval` whose Debug string would not agree with typed equality.
11000fn try_factorize_typed<'a>(
11001    left: &'a [Scalar],
11002    right: &'a [Scalar],
11003) -> Option<(Vec<u32>, Vec<u32>)> {
11004    let mut codes: FxHashMap<ByKey<'a>, u32> = FxHashMap::default();
11005    let mut next = 0u32;
11006    let mut left_ids = Vec::with_capacity(left.len());
11007    for v in left {
11008        let id = *codes.entry(ByKey::from_scalar(v)?).or_insert_with(|| {
11009            let i = next;
11010            next += 1;
11011            i
11012        });
11013        left_ids.push(id);
11014    }
11015    let mut right_ids = Vec::with_capacity(right.len());
11016    for v in right {
11017        let id = *codes.entry(ByKey::from_scalar(v)?).or_insert_with(|| {
11018            let i = next;
11019            next += 1;
11020            i
11021        });
11022        right_ids.push(id);
11023    }
11024    Some((left_ids, right_ids))
11025}
11026
11027/// Build dense u32 group ids for the left and right frames over the `by`
11028/// columns, sharing one id space. Returns `(left_ids, right_ids)`.
11029///
11030/// Fast path (a single non-float `by` column): factorize the column's scalars
11031/// directly with the borrowed typed [`ByKey`] — zero per-row string formatting
11032/// or allocation. Bit-identical to the `format!("{val:?}")` grouping because
11033/// the typed key induces the exact same equality classes. Multi-column or
11034/// float/interval `by` keys route to the original Debug-string builder, whose
11035/// per-row composite keys are then interned to u32 (one clone per *distinct*
11036/// group, not per row).
11037fn build_group_ids(
11038    left: &fp_frame::DataFrame,
11039    right: &fp_frame::DataFrame,
11040    by_cols: &[String],
11041) -> Result<(Vec<u32>, Vec<u32>), JoinError> {
11042    if by_cols.len() == 1
11043        && let (Some(lcol), Some(rcol)) = (
11044            left.columns().get(&by_cols[0]),
11045            right.columns().get(&by_cols[0]),
11046        )
11047        && let Some(ids) = try_factorize_typed(lcol.values(), rcol.values())
11048    {
11049        return Ok(ids);
11050    }
11051
11052    let left_keys = build_group_keys(left, by_cols)?;
11053    let right_keys = build_group_keys(right, by_cols)?;
11054    let mut codes: FxHashMap<Vec<String>, u32> = FxHashMap::default();
11055    let mut next = 0u32;
11056    let mut intern = |k: &Vec<String>, codes: &mut FxHashMap<Vec<String>, u32>| -> u32 {
11057        if let Some(&id) = codes.get(k) {
11058            id
11059        } else {
11060            let id = next;
11061            next += 1;
11062            codes.insert(k.clone(), id);
11063            id
11064        }
11065    };
11066    let left_ids = left_keys.iter().map(|k| intern(k, &mut codes)).collect();
11067    let right_ids = right_keys.iter().map(|k| intern(k, &mut codes)).collect();
11068    Ok((left_ids, right_ids))
11069}
11070
11071/// Build group keys from the `by` columns.
11072fn build_group_keys(
11073    df: &fp_frame::DataFrame,
11074    by_cols: &[String],
11075) -> Result<Vec<Vec<String>>, JoinError> {
11076    let n = df.len();
11077    let mut keys = vec![Vec::with_capacity(by_cols.len()); n];
11078
11079    for col_name in by_cols {
11080        let col = df.columns().get(col_name).ok_or_else(|| {
11081            JoinError::Frame(FrameError::CompatibilityRejected(format!(
11082                "merge_asof: column '{col_name}' not found"
11083            )))
11084        })?;
11085        for (i, val) in col.values().iter().enumerate() {
11086            keys[i].push(format!("{val:?}"));
11087        }
11088    }
11089
11090    Ok(keys)
11091}
11092
11093/// Compute asof matches for a single group or the whole dataset.
11094fn compute_asof_matches(
11095    left_vals: &[f64],
11096    right_vals: &[f64],
11097    direction: AsofDirection,
11098    allow_exact_matches: bool,
11099    tolerance: Option<f64>,
11100) -> Vec<Option<usize>> {
11101    let mut right_non_nan_values = Vec::new();
11102    let mut right_non_nan_positions = Vec::new();
11103    for (pos, &rv) in right_vals.iter().enumerate() {
11104        if !rv.is_nan() {
11105            right_non_nan_values.push(rv);
11106            right_non_nan_positions.push(pos);
11107        }
11108    }
11109
11110    let mut right_matches: Vec<Option<usize>> = Vec::with_capacity(left_vals.len());
11111
11112    match direction {
11113        AsofDirection::Backward => {
11114            let mut best: Option<usize> = None;
11115            let mut best_val: Option<f64> = None;
11116            let mut j = 0usize;
11117            for &lv in left_vals {
11118                if lv.is_nan() {
11119                    right_matches.push(None);
11120                    continue;
11121                }
11122                // Advance while right <= left (or right < left if !allow_exact_matches)
11123                while j < right_non_nan_values.len() {
11124                    let rv = right_non_nan_values[j];
11125                    let should_include = if allow_exact_matches {
11126                        rv <= lv
11127                    } else {
11128                        rv < lv
11129                    };
11130                    if !should_include {
11131                        break;
11132                    }
11133                    best = Some(right_non_nan_positions[j]);
11134                    best_val = Some(rv);
11135                    j += 1;
11136                }
11137
11138                // Check tolerance
11139                let matched = match (best, best_val, tolerance) {
11140                    (Some(idx), Some(rv), Some(tol)) if (lv - rv).abs() <= tol => Some(idx),
11141                    (Some(idx), _, None) => Some(idx),
11142                    _ => None,
11143                };
11144                right_matches.push(matched);
11145            }
11146        }
11147        AsofDirection::Forward => {
11148            let mut j = 0usize;
11149            for &lv in left_vals {
11150                if lv.is_nan() {
11151                    right_matches.push(None);
11152                    continue;
11153                }
11154                // Advance while right < left (or right <= left if !allow_exact_matches)
11155                while j < right_non_nan_values.len() {
11156                    let rv = right_non_nan_values[j];
11157                    let should_skip = if allow_exact_matches {
11158                        rv < lv
11159                    } else {
11160                        rv <= lv
11161                    };
11162                    if !should_skip {
11163                        break;
11164                    }
11165                    j += 1;
11166                }
11167
11168                if j < right_non_nan_values.len() {
11169                    let rv = right_non_nan_values[j];
11170                    // Check tolerance
11171                    let matched = match tolerance {
11172                        Some(tol) if (rv - lv).abs() <= tol => Some(right_non_nan_positions[j]),
11173                        None => Some(right_non_nan_positions[j]),
11174                        _ => None,
11175                    };
11176                    right_matches.push(matched);
11177                } else {
11178                    right_matches.push(None);
11179                }
11180            }
11181        }
11182        AsofDirection::Nearest => {
11183            for &lv in left_vals {
11184                if lv.is_nan() {
11185                    right_matches.push(None);
11186                    continue;
11187                }
11188                if right_non_nan_values.is_empty() {
11189                    right_matches.push(None);
11190                    continue;
11191                }
11192
11193                // For nearest, pick the closest neighbor on each side. The
11194                // candidate window depends on whether exact (equal) keys may
11195                // match:
11196                //   allow_exact:  lower = last value <= lv, upper = first value >= lv
11197                //   !allow_exact: lower = last value <  lv, upper = first value >  lv
11198                // Selecting the window up front (rather than excluding exact
11199                // matches after the fact) skips over runs of exact-equal keys
11200                // when they are disallowed, so a nearer non-equal key beyond
11201                // the run is still found — matching pandas merge_asof.
11202                let (lower, upper) = if allow_exact_matches {
11203                    let lo = right_non_nan_values.partition_point(|rv| *rv <= lv);
11204                    let up = right_non_nan_values.partition_point(|rv| *rv < lv);
11205                    (
11206                        if lo > 0 { Some(lo - 1) } else { None },
11207                        if up < right_non_nan_values.len() {
11208                            Some(up)
11209                        } else {
11210                            None
11211                        },
11212                    )
11213                } else {
11214                    let lo = right_non_nan_values.partition_point(|rv| *rv < lv);
11215                    let up = right_non_nan_values.partition_point(|rv| *rv <= lv);
11216                    (
11217                        if lo > 0 { Some(lo - 1) } else { None },
11218                        if up < right_non_nan_values.len() {
11219                            Some(up)
11220                        } else {
11221                            None
11222                        },
11223                    )
11224                };
11225
11226                let chosen = match (lower, upper) {
11227                    (Some(l), Some(u)) => {
11228                        let lower_dist = (right_non_nan_values[l] - lv).abs();
11229                        let upper_dist = (right_non_nan_values[u] - lv).abs();
11230                        // Ties go to the lower (backward) neighbor, like pandas.
11231                        if upper_dist < lower_dist {
11232                            Some(u)
11233                        } else {
11234                            Some(l)
11235                        }
11236                    }
11237                    (Some(l), None) => Some(l),
11238                    (None, Some(u)) => Some(u),
11239                    (None, None) => None,
11240                };
11241
11242                // Apply tolerance check
11243                let matched = match chosen {
11244                    Some(idx) => {
11245                        let rv = right_non_nan_values[idx];
11246                        match tolerance {
11247                            Some(tol) if (lv - rv).abs() <= tol => {
11248                                Some(right_non_nan_positions[idx])
11249                            }
11250                            None => Some(right_non_nan_positions[idx]),
11251                            _ => None,
11252                        }
11253                    }
11254                    None => None,
11255                };
11256                right_matches.push(matched);
11257            }
11258        }
11259    }
11260
11261    right_matches
11262}
11263
11264/// Build the output DataFrame from computed matches.
11265/// One output column of `build_asof_output`: left columns are present for every
11266/// row (clone), right columns are gathered by the asof match positions.
11267enum AsofOutputTask<'a> {
11268    LeftClone(&'a Column),
11269    RightGather(&'a Column),
11270}
11271
11272fn build_asof_output(
11273    left: &fp_frame::DataFrame,
11274    right: &fp_frame::DataFrame,
11275    on: &str,
11276    right_matches: &[Option<usize>],
11277    by_cols: Option<&[String]>,
11278) -> Result<MergedDataFrame, JoinError> {
11279    let right_n = right.len();
11280
11281    let left_col_names: Vec<String> = left.column_names().iter().map(|s| s.to_string()).collect();
11282    let right_col_names_all: Vec<String> =
11283        right.column_names().iter().map(|s| s.to_string()).collect();
11284
11285    // Exclude the `on` column and `by` columns from right output
11286    let excluded_cols: HashSet<&str> = {
11287        let mut s = HashSet::new();
11288        s.insert(on);
11289        if let Some(by) = by_cols {
11290            for c in by {
11291                s.insert(c.as_str());
11292            }
11293        }
11294        s
11295    };
11296
11297    let right_col_names: Vec<String> = right_col_names_all
11298        .iter()
11299        .filter(|c| !excluded_cols.contains(c.as_str()))
11300        .cloned()
11301        .collect();
11302
11303    let left_name_set: HashSet<&String> = left_col_names.iter().collect();
11304    let right_name_set: HashSet<&String> = right_col_names_all.iter().collect();
11305    let mut excluded_names = HashSet::new();
11306    excluded_names.insert(on);
11307    // `by` columns are equi-join keys: pandas emits them once, unsuffixed,
11308    // exactly like `on`. They were left out of this set, so a `by` column
11309    // present on both sides counted as an overlap and the LEFT copy came out
11310    // as `group_x` (the right copy is excluded above), where pandas 2.2.3
11311    // returns `group` (br-frankenpandas-fkiu9, live-oracle
11312    // merge_asof_by_group_and_no_exact_matches).
11313    if let Some(by) = by_cols {
11314        for column in by {
11315            excluded_names.insert(column.as_str());
11316        }
11317    }
11318    let overlap_names =
11319        collect_overlapping_column_names(&left_name_set, &right_name_set, &excluded_names);
11320    let overlap_set: HashSet<String> = overlap_names.iter().cloned().collect();
11321    let suffixes = ResolvedMergeSuffixes::default();
11322    ensure_merge_suffixes_for_overlaps(&overlap_names, &suffixes)?;
11323
11324    let n_out = left.len();
11325    let mut out_columns = ColumnStore::new();
11326    let mut column_order: Vec<String> = Vec::new();
11327
11328    // Resolve every output column (name + build task) in order, then build the
11329    // columns — left columns clone all rows, right columns gather matched-or-null
11330    // values. Each output column is independent, so wide/large outputs build all
11331    // columns across a worker pool (br-frankenpandas-fu8f5; same disjoint-fill
11332    // pattern as the dense-i64/inner-merge builders). Bit-identical to the serial
11333    // loops: identical per-column result (left clone; right Scalar gather with
11334    // Null(NullKind::NaN) on unmatched, then Column::new with the source dtype),
11335    // inserted in the same order.
11336    let mut specs: Vec<(String, AsofOutputTask<'_>)> = Vec::new();
11337    for col_name in &left_col_names {
11338        let col = left.columns().get(col_name).ok_or_else(|| {
11339            JoinError::Frame(FrameError::CompatibilityRejected(format!(
11340                "merge_asof: left column '{col_name}' not found"
11341            )))
11342        })?;
11343        let output_name = if overlap_set.contains(col_name) {
11344            apply_merge_suffix(col_name, suffixes.left.as_deref())
11345        } else {
11346            col_name.clone()
11347        };
11348        specs.push((output_name, AsofOutputTask::LeftClone(col)));
11349    }
11350    for col_name in &right_col_names {
11351        let right_col = right.columns().get(col_name).ok_or_else(|| {
11352            JoinError::Frame(FrameError::CompatibilityRejected(format!(
11353                "merge_asof: right column '{col_name}' not found"
11354            )))
11355        })?;
11356        let output_name = if overlap_set.contains(col_name) {
11357            apply_merge_suffix(col_name, suffixes.right.as_deref())
11358        } else {
11359            col_name.clone()
11360        };
11361        specs.push((output_name, AsofOutputTask::RightGather(right_col)));
11362    }
11363
11364    let build_one = |task: &AsofOutputTask<'_>| -> Result<Column, JoinError> {
11365        match task {
11366            AsofOutputTask::LeftClone(col) => Ok((*col).clone()),
11367            AsofOutputTask::RightGather(right_col) => {
11368                // Typed all-valid-Float64 gather (br-frankenpandas asof typed
11369                // output): an `as_f64_slice` source is all-valid, so it carries
11370                // NO NaN values (Float64 validity marks NaN invalid, and the
11371                // slice is gated on `validity.all()`). Gather matched data into a
11372                // contiguous f64 buffer + validity bitset instead of cloning a
11373                // 32 B Scalar per row and re-validating in Column::new. Bit-
11374                // identical to the Scalar path: a matched slot is a finite
11375                // `Float64(src[j])` (valid bit), an unmatched slot is
11376                // `Null(NullKind::NaN)` (cleared bit) — exactly what the Scalar
11377                // gather + Column::new produce, with no matched-NaN ambiguity
11378                // because the source has none.
11379                if let Some(src) = right_col.as_f64_slice() {
11380                    let mut data = Vec::with_capacity(n_out);
11381                    let mut validity = fp_columnar::ValidityMask::all_valid(n_out);
11382                    for (i, m) in right_matches.iter().enumerate() {
11383                        match m {
11384                            Some(j) if *j < right_n => data.push(src[*j]),
11385                            _ => {
11386                                // 0.0 datum + cleared bit is the gap convention:
11387                                // LazyNullableFloat64 materializes Null(NaN) only
11388                                // when the datum is NOT NaN, so an unmatched slot
11389                                // must use 0.0 (a NaN datum would materialize a
11390                                // present Float64(NaN) instead).
11391                                data.push(0.0);
11392                                validity.set(i, false);
11393                            }
11394                        }
11395                    }
11396                    return Ok(Column::from_f64_values_with_validity(data, validity));
11397                }
11398                // A right column that gains an UNMATCHED row gains a gap, and an
11399                // all-valid numpy int64 cannot hold one — pandas widens it to
11400                // float64, exactly as it does for the join family. This used to
11401                // be a hand-rolled gather ending in
11402                // `Column::new(right_col.dtype(), vals)`, which kept Int64 and
11403                // left the present values pinned as ints beside a NaN.
11404                //
11405                // MEASURED, live pandas 2.2.3:
11406                //   L = DataFrame({'time':[1,5,10], 'left_val':[10,50,100]})
11407                //   R = DataFrame({'time':[2,6],    'right_val':[20,60]})
11408                //   pd.merge_asof(L, R, on='time', direction='forward')
11409                //     right_val -> [20.0, 60.0, NaN]   dtype float64
11410                //     time and left_val stay int64 — they gain no gap
11411                //   with every left row matched, right_val stays int64
11412                //
11413                // Note the rule here is PER COLUMN, unlike Series.unstack where
11414                // a gap widens the whole frame: merge builds each output column
11415                // independently, so only the column that gains the gap moves.
11416                //
11417                // reindex_join_column_with_invented_gap is the helper the nywa8
11418                // join sweep already built for this, including the guard that a
11419                // source ALREADY carrying a missing value is nullable and keeps
11420                // its dtype. merge_asof was the sibling that sweep did not
11421                // reach; calling it rather than re-deriving the rule here.
11422                Ok(reindex_join_column_with_invented_gap(
11423                    right_col,
11424                    right_matches,
11425                )?)
11426            }
11427        }
11428    };
11429
11430    let built: Vec<Result<Column, JoinError>> = {
11431        let thread_count = join_parallel_thread_count();
11432        if specs.len() > 1 && n_out >= DENSE_I64_INNER_PARALLEL_MIN_VALUES && thread_count > 1 {
11433            let mut slots: Vec<Option<Result<Column, JoinError>>> =
11434                (0..specs.len()).map(|_| None).collect();
11435            let chunk = specs.len().div_ceil(thread_count).max(1);
11436            let build_one = &build_one;
11437            std::thread::scope(|scope| {
11438                for (spec_chunk, slot_chunk) in specs.chunks(chunk).zip(slots.chunks_mut(chunk)) {
11439                    scope.spawn(move || {
11440                        for ((_, task), slot) in spec_chunk.iter().zip(slot_chunk) {
11441                            *slot = Some(build_one(task));
11442                        }
11443                    });
11444                }
11445            });
11446            slots
11447                .into_iter()
11448                .map(|c| c.expect("every asof output column must be built"))
11449                .collect()
11450        } else {
11451            specs.iter().map(|(_, task)| build_one(task)).collect()
11452        }
11453    };
11454
11455    for ((output_name, _), column) in specs.into_iter().zip(built) {
11456        insert_merged_output_column(&mut out_columns, &mut column_order, output_name, column?)?;
11457    }
11458
11459    Ok(MergedDataFrame {
11460        index: left.index().clone(),
11461        columns: out_columns,
11462        column_order,
11463    })
11464}
11465
11466impl DataFrameMergeExt for fp_frame::DataFrame {
11467    fn merge(
11468        &self,
11469        other: &fp_frame::DataFrame,
11470        on: &[&str],
11471        how: JoinType,
11472    ) -> Result<MergedDataFrame, JoinError> {
11473        merge_dataframes_on(self, other, on, how)
11474    }
11475
11476    fn merge_with_options(
11477        &self,
11478        other: &fp_frame::DataFrame,
11479        left_on: &[&str],
11480        right_on: &[&str],
11481        how: JoinType,
11482        options: MergeExecutionOptions,
11483    ) -> Result<MergedDataFrame, JoinError> {
11484        merge_dataframes_on_with_options(self, other, left_on, right_on, how, options)
11485    }
11486
11487    fn join_on_index(
11488        &self,
11489        other: &fp_frame::DataFrame,
11490        how: JoinType,
11491    ) -> Result<MergedDataFrame, JoinError> {
11492        let left = self.reset_index(false)?;
11493        let right = other.reset_index(false)?;
11494        merge_dataframes_on(&left, &right, &["index"], how)
11495    }
11496
11497    fn merge_asof(
11498        &self,
11499        other: &fp_frame::DataFrame,
11500        on: &str,
11501        direction: &str,
11502    ) -> Result<MergedDataFrame, JoinError> {
11503        self.merge_asof_with_options(other, on, direction, MergeAsofOptions::new())
11504    }
11505
11506    fn merge_asof_with_options(
11507        &self,
11508        other: &fp_frame::DataFrame,
11509        on: &str,
11510        direction: &str,
11511        options: MergeAsofOptions,
11512    ) -> Result<MergedDataFrame, JoinError> {
11513        let dir = match direction {
11514            "backward" => AsofDirection::Backward,
11515            "forward" => AsofDirection::Forward,
11516            "nearest" => AsofDirection::Nearest,
11517            _ => {
11518                return Err(JoinError::Frame(FrameError::CompatibilityRejected(
11519                    format!("merge_asof: invalid direction '{direction}'"),
11520                )));
11521            }
11522        };
11523        crate::merge_asof_with_options(self, other, on, dir, options)
11524    }
11525
11526    fn merge_ordered(
11527        &self,
11528        other: &fp_frame::DataFrame,
11529        on: &[&str],
11530        fill_method: Option<&str>,
11531    ) -> Result<MergedDataFrame, JoinError> {
11532        crate::merge_ordered(self, other, on, fill_method)
11533    }
11534}
11535
11536#[cfg(test)]
11537mod tests {
11538    use fp_columnar::{Column, ValidityMask};
11539    use fp_frame::{ColumnStore, Series};
11540    use fp_index::{Index, IndexLabel};
11541    use fp_types::{DType, NullKind, Scalar};
11542
11543    use super::{
11544        DataFrameMergeExt, DenseI64InnerOutputPlan, DenseI64LaneData, FusedInt64OutputColumn,
11545        FusedInt64Side, InnerPositionPlan, JoinExecutionOptions, JoinType, PositionSelection,
11546        ResolvedMergeSuffixes, build_dense_i64_inner_output_data,
11547        build_single_key_dense_cycle_i64_left_merge_output,
11548        build_single_key_dense_i64_left_merge_output,
11549        build_single_key_dense_i64_right_merge_output,
11550        build_single_key_inner_contiguous_no_overlap_output, join_series, join_series_with_options,
11551        join_series_with_trace, lower_hex_overlap_plan_from_certificates,
11552        ordered_unique_utf8_inner_position_plan, ordered_unique_utf8_inner_positions,
11553        ordered_utf8_lower_hex_overlap_len, scalar_utf8_left_positions,
11554        scalar_utf8_outer_positions, sorted_contiguous_utf8_inner_positions,
11555        strictly_increasing_utf8_key_spans, utf8_span_lower_bound,
11556    };
11557
11558    fn contiguous_utf8_column(values: &[&str]) -> Column {
11559        let mut bytes = Vec::new();
11560        let mut offsets = Vec::with_capacity(values.len() + 1);
11561        offsets.push(0);
11562        for value in values {
11563            bytes.extend_from_slice(value.as_bytes());
11564            offsets.push(bytes.len());
11565        }
11566        Column::from_utf8_contiguous(bytes, offsets)
11567    }
11568
11569    fn utf8_key_merge_frame(keys: &[&str], value_name: &str, base: i64) -> DataFrame {
11570        let index = Index::new(
11571            (0..keys.len())
11572                .map(|row| IndexLabel::Int64(row as i64))
11573                .collect(),
11574        );
11575        let mut columns = ColumnStore::new();
11576        columns.insert("id".to_owned(), contiguous_utf8_column(keys));
11577        columns.insert(
11578            value_name.to_owned(),
11579            Column::from_i64_values((0..keys.len()).map(|row| base + row as i64).collect()),
11580        );
11581        DataFrame::new_with_column_order(
11582            index,
11583            columns,
11584            vec!["id".to_owned(), value_name.to_owned()],
11585        )
11586        .expect("utf8 key frame")
11587    }
11588
11589    fn scalar_utf8_column(values: &[&str]) -> Column {
11590        Column::from_values(
11591            values
11592                .iter()
11593                .map(|value| Scalar::Utf8((*value).to_owned()))
11594                .collect(),
11595        )
11596        .expect("scalar utf8 column")
11597    }
11598
11599    #[test]
11600    fn scalar_utf8_left_positions_preserve_duplicate_order_blackthrush() {
11601        let left = scalar_utf8_column(&["b", "a", "b", "x"]);
11602        let right = scalar_utf8_column(&["a", "b", "b"]);
11603
11604        let (left_positions, right_positions) =
11605            scalar_utf8_left_positions(&left, &right).expect("scalar utf8 left positions");
11606
11607        assert_eq!(
11608            left_positions,
11609            vec![Some(0), Some(0), Some(1), Some(2), Some(2), Some(3)]
11610        );
11611        assert_eq!(
11612            right_positions,
11613            vec![Some(1), Some(2), Some(0), Some(1), Some(2), None]
11614        );
11615    }
11616
11617    #[test]
11618    fn scalar_utf8_outer_positions_sort_keys_and_keep_unmatched_blackthrush() {
11619        let left = scalar_utf8_column(&["b", "a", "b", "x"]);
11620        let right = scalar_utf8_column(&["a", "b", "b", "z"]);
11621
11622        let (left_positions, right_positions) =
11623            scalar_utf8_outer_positions(&left, &right).expect("scalar utf8 outer positions");
11624
11625        assert_eq!(
11626            left_positions,
11627            vec![Some(1), Some(0), Some(0), Some(2), Some(2), Some(3), None,]
11628        );
11629        assert_eq!(
11630            right_positions,
11631            vec![Some(0), Some(1), Some(2), Some(1), Some(2), None, Some(3),]
11632        );
11633    }
11634
11635    #[test]
11636    fn inner_join_multiplies_cardinality_for_duplicates() {
11637        let left = Series::from_values(
11638            "left",
11639            vec!["k".into(), "k".into(), "x".into()],
11640            vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
11641        )
11642        .expect("left");
11643
11644        let right = Series::from_values(
11645            "right",
11646            vec!["k".into(), "k".into()],
11647            vec![Scalar::Int64(10), Scalar::Int64(20)],
11648        )
11649        .expect("right");
11650
11651        let out = join_series(&left, &right, JoinType::Inner).expect("join");
11652        assert_eq!(out.index.labels().len(), 4);
11653        assert_eq!(
11654            out.left_values.values(),
11655            &[
11656                Scalar::Int64(1),
11657                Scalar::Int64(1),
11658                Scalar::Int64(2),
11659                Scalar::Int64(2)
11660            ]
11661        );
11662    }
11663
11664    #[test]
11665    fn left_join_injects_missing_for_unmatched_right_rows() {
11666        let left = Series::from_values(
11667            "left",
11668            vec!["a".into(), "b".into()],
11669            vec![Scalar::Int64(1), Scalar::Int64(2)],
11670        )
11671        .expect("left");
11672        let right =
11673            Series::from_values("right", vec!["a".into()], vec![Scalar::Int64(10)]).expect("right");
11674
11675        let out = join_series(&left, &right, JoinType::Left).expect("join");
11676        // The right side gains a gap, so pandas widens it to float64 and the
11677        // gap is a NaN — on a LEFT join exactly as on an outer one. MEASURED,
11678        // live pandas 2.2.3, l=[10,20,30]@[1,2,3] joined with r=[200]@[2]:
11679        //   how='left'  -> l int64 [10,20,30]   r float64 [nan, 200.0, nan]
11680        //   how='outer' -> same
11681        // This assertion previously pinned Int64 + Null(Null), which was
11682        // FrankenPandas' own pre-fix answer. (br-frankenpandas-nywa8)
11683        assert_eq!(
11684            out.right_values.values(),
11685            &[Scalar::Float64(10.0), Scalar::Null(NullKind::NaN)]
11686        );
11687    }
11688
11689    #[test]
11690    fn arena_join_matches_global_allocator_behavior() {
11691        let left = Series::from_values(
11692            "left",
11693            vec!["k".into(), "k".into(), "x".into()],
11694            vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
11695        )
11696        .expect("left");
11697
11698        let right = Series::from_values(
11699            "right",
11700            vec!["k".into(), "k".into()],
11701            vec![Scalar::Int64(10), Scalar::Int64(20)],
11702        )
11703        .expect("right");
11704
11705        let global = join_series_with_options(
11706            &left,
11707            &right,
11708            JoinType::Inner,
11709            JoinExecutionOptions {
11710                use_arena: false,
11711                arena_budget_bytes: 0,
11712            },
11713        )
11714        .expect("global join");
11715
11716        let arena = join_series_with_options(
11717            &left,
11718            &right,
11719            JoinType::Inner,
11720            JoinExecutionOptions::default(),
11721        )
11722        .expect("arena join");
11723
11724        assert_eq!(arena, global);
11725    }
11726
11727    #[test]
11728    fn arena_join_falls_back_when_budget_is_too_small() {
11729        let left = Series::from_values(
11730            "left",
11731            vec!["a".into(), "a".into(), "a".into()],
11732            vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
11733        )
11734        .expect("left");
11735        let right = Series::from_values(
11736            "right",
11737            vec!["a".into(), "a".into()],
11738            vec![Scalar::Int64(10), Scalar::Int64(20)],
11739        )
11740        .expect("right");
11741
11742        let options = JoinExecutionOptions {
11743            use_arena: true,
11744            arena_budget_bytes: 1,
11745        };
11746        let (fallback_out, trace) =
11747            join_series_with_trace(&left, &right, JoinType::Inner, options).expect("fallback join");
11748        let global_out = join_series_with_options(
11749            &left,
11750            &right,
11751            JoinType::Inner,
11752            JoinExecutionOptions {
11753                use_arena: false,
11754                arena_budget_bytes: 0,
11755            },
11756        )
11757        .expect("global join");
11758
11759        assert_eq!(fallback_out, global_out);
11760        assert!(!trace.used_arena);
11761        assert!(trace.estimated_bytes > options.arena_budget_bytes);
11762    }
11763
11764    #[test]
11765    fn arena_join_is_stable_across_many_small_operations() {
11766        let left = Series::from_values(
11767            "left",
11768            vec!["a".into(), "b".into()],
11769            vec![Scalar::Int64(1), Scalar::Int64(2)],
11770        )
11771        .expect("left");
11772        let right = Series::from_values(
11773            "right",
11774            vec!["a".into(), "b".into()],
11775            vec![Scalar::Int64(10), Scalar::Int64(20)],
11776        )
11777        .expect("right");
11778
11779        let options = JoinExecutionOptions::default();
11780        for _ in 0..1_000 {
11781            let out = join_series_with_options(&left, &right, JoinType::Inner, options)
11782                .expect("arena join");
11783            assert_eq!(out.index.labels().len(), 2);
11784            assert_eq!(
11785                out.right_values.values(),
11786                &[Scalar::Int64(10), Scalar::Int64(20)]
11787            );
11788        }
11789    }
11790
11791    /// AG-06-T test #8: 100K-row inner join with arena -> correct output, no OOM.
11792    #[test]
11793    fn arena_large_join_100k_rows() {
11794        let n = 100_000;
11795        let labels: Vec<IndexLabel> = (0..n).map(|i| IndexLabel::Int64(i as i64 % 1000)).collect();
11796        let values: Vec<Scalar> = (0..n).map(|i| Scalar::Int64(i as i64)).collect();
11797
11798        let left = Series::from_values("left", labels.clone(), values.clone()).expect("left");
11799        let right = Series::from_values("right", labels, values).expect("right");
11800
11801        let out = join_series_with_options(
11802            &left,
11803            &right,
11804            JoinType::Inner,
11805            JoinExecutionOptions::default(),
11806        )
11807        .expect("100K arena join");
11808
11809        // With 1000 distinct keys, each appearing 100 times on each side,
11810        // inner join produces 100 * 100 * 1000 = 10M rows.
11811        // But that's too large; use a budget that forces fallback.
11812        let out_fallback = join_series_with_options(
11813            &left,
11814            &right,
11815            JoinType::Inner,
11816            JoinExecutionOptions {
11817                use_arena: true,
11818                arena_budget_bytes: 1,
11819            },
11820        )
11821        .expect("100K fallback join");
11822
11823        assert_eq!(out.index.labels().len(), out_fallback.index.labels().len());
11824    }
11825
11826    #[test]
11827    fn right_join_contains_all_right_labels() {
11828        let left = Series::from_values(
11829            "left",
11830            vec!["a".into(), "b".into()],
11831            vec![Scalar::Int64(1), Scalar::Int64(2)],
11832        )
11833        .expect("left");
11834        let right = Series::from_values(
11835            "right",
11836            vec!["b".into(), "c".into()],
11837            vec![Scalar::Int64(20), Scalar::Int64(30)],
11838        )
11839        .expect("right");
11840
11841        let out = join_series(&left, &right, JoinType::Right).expect("join");
11842        // Right join: all right labels preserved. "b" matches, "c" unmatched.
11843        assert_eq!(out.index.labels().len(), 2);
11844        assert_eq!(
11845            out.index.labels(),
11846            &[IndexLabel::Utf8("b".into()), IndexLabel::Utf8("c".into())]
11847        );
11848        // "b" matched -> left=2, right=20. "c" unmatched -> left is a gap, so
11849        // the LEFT lane widens to float64 with a NaN (br-frankenpandas-nywa8;
11850        // the widening follows the invented gap, not the join type).
11851        assert_eq!(
11852            out.left_values.values(),
11853            &[Scalar::Float64(2.0), Scalar::Null(NullKind::NaN)]
11854        );
11855        assert_eq!(
11856            out.right_values.values(),
11857            &[Scalar::Int64(20), Scalar::Int64(30)]
11858        );
11859    }
11860
11861    #[test]
11862    fn right_join_multiplies_cardinality_for_duplicates() {
11863        let left = Series::from_values(
11864            "left",
11865            vec!["k".into(), "k".into()],
11866            vec![Scalar::Int64(1), Scalar::Int64(2)],
11867        )
11868        .expect("left");
11869        let right = Series::from_values(
11870            "right",
11871            vec!["k".into(), "x".into()],
11872            vec![Scalar::Int64(10), Scalar::Int64(30)],
11873        )
11874        .expect("right");
11875
11876        let out = join_series(&left, &right, JoinType::Right).expect("join");
11877        // "k" in right matches 2 left rows -> 2 output rows for "k", plus 1 for "x" unmatched.
11878        assert_eq!(out.index.labels().len(), 3);
11879        assert_eq!(
11880            out.right_values.values(),
11881            &[Scalar::Int64(10), Scalar::Int64(10), Scalar::Int64(30)]
11882        );
11883    }
11884
11885    #[test]
11886    fn outer_join_contains_all_labels_from_both_sides() {
11887        let left = Series::from_values(
11888            "left",
11889            vec!["a".into(), "b".into()],
11890            vec![Scalar::Int64(1), Scalar::Int64(2)],
11891        )
11892        .expect("left");
11893        let right = Series::from_values(
11894            "right",
11895            vec!["b".into(), "c".into()],
11896            vec![Scalar::Int64(20), Scalar::Int64(30)],
11897        )
11898        .expect("right");
11899
11900        let out = join_series(&left, &right, JoinType::Outer).expect("join");
11901        // Outer: "a" (left only), "b" (both), "c" (right only) -> 3 rows
11902        assert_eq!(out.index.labels().len(), 3);
11903        assert_eq!(
11904            out.left_values.values(),
11905            &[
11906                Scalar::Float64(1.0),
11907                Scalar::Float64(2.0),
11908                Scalar::Null(NullKind::NaN)
11909            ]
11910        );
11911        assert_eq!(
11912            out.right_values.values(),
11913            &[
11914                Scalar::Null(NullKind::NaN),
11915                Scalar::Float64(20.0),
11916                Scalar::Float64(30.0)
11917            ]
11918        );
11919    }
11920
11921    #[test]
11922    fn outer_join_sorts_union_labels_like_pandas() {
11923        let left = Series::from_values(
11924            "left",
11925            vec!["a".into(), "c".into()],
11926            vec![Scalar::Int64(1), Scalar::Int64(3)],
11927        )
11928        .expect("left");
11929        let right = Series::from_values(
11930            "right",
11931            vec!["b".into(), "c".into()],
11932            vec![Scalar::Int64(20), Scalar::Int64(30)],
11933        )
11934        .expect("right");
11935
11936        let out = join_series(&left, &right, JoinType::Outer).expect("join");
11937        assert_eq!(
11938            out.index.labels(),
11939            &[
11940                IndexLabel::Utf8("a".into()),
11941                IndexLabel::Utf8("b".into()),
11942                IndexLabel::Utf8("c".into())
11943            ]
11944        );
11945        assert_eq!(
11946            out.left_values.values(),
11947            &[
11948                Scalar::Float64(1.0),
11949                Scalar::Null(NullKind::NaN),
11950                Scalar::Float64(3.0)
11951            ]
11952        );
11953        assert_eq!(
11954            out.right_values.values(),
11955            &[
11956                Scalar::Null(NullKind::NaN),
11957                Scalar::Float64(20.0),
11958                Scalar::Float64(30.0)
11959            ]
11960        );
11961    }
11962
11963    #[test]
11964    fn outer_join_with_duplicates() {
11965        let left = Series::from_values(
11966            "left",
11967            vec!["k".into(), "k".into(), "a".into()],
11968            vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
11969        )
11970        .expect("left");
11971        let right = Series::from_values(
11972            "right",
11973            vec!["k".into(), "z".into()],
11974            vec![Scalar::Int64(10), Scalar::Int64(99)],
11975        )
11976        .expect("right");
11977
11978        let out = join_series(&left, &right, JoinType::Outer).expect("join");
11979        // "k" x "k": 2 matched rows. "a": left-only (1 row). "z": right-only (1 row).
11980        assert_eq!(out.index.labels().len(), 4);
11981    }
11982
11983    #[test]
11984    fn arena_right_join_matches_global() {
11985        let left = Series::from_values(
11986            "left",
11987            vec!["a".into(), "b".into()],
11988            vec![Scalar::Int64(1), Scalar::Int64(2)],
11989        )
11990        .expect("left");
11991        let right = Series::from_values(
11992            "right",
11993            vec!["b".into(), "c".into()],
11994            vec![Scalar::Int64(20), Scalar::Int64(30)],
11995        )
11996        .expect("right");
11997
11998        let global = join_series_with_options(
11999            &left,
12000            &right,
12001            JoinType::Right,
12002            JoinExecutionOptions {
12003                use_arena: false,
12004                arena_budget_bytes: 0,
12005            },
12006        )
12007        .expect("global");
12008        let arena = join_series_with_options(
12009            &left,
12010            &right,
12011            JoinType::Right,
12012            JoinExecutionOptions::default(),
12013        )
12014        .expect("arena");
12015        assert_eq!(arena, global);
12016    }
12017
12018    #[test]
12019    fn arena_outer_join_matches_global() {
12020        let left = Series::from_values(
12021            "left",
12022            vec!["a".into(), "b".into()],
12023            vec![Scalar::Int64(1), Scalar::Int64(2)],
12024        )
12025        .expect("left");
12026        let right = Series::from_values(
12027            "right",
12028            vec!["b".into(), "c".into()],
12029            vec![Scalar::Int64(20), Scalar::Int64(30)],
12030        )
12031        .expect("right");
12032
12033        let global = join_series_with_options(
12034            &left,
12035            &right,
12036            JoinType::Outer,
12037            JoinExecutionOptions {
12038                use_arena: false,
12039                arena_budget_bytes: 0,
12040            },
12041        )
12042        .expect("global");
12043        let arena = join_series_with_options(
12044            &left,
12045            &right,
12046            JoinType::Outer,
12047            JoinExecutionOptions::default(),
12048        )
12049        .expect("arena");
12050        assert_eq!(arena, global);
12051    }
12052
12053    /// AG-06-T test #6: arena is scoped per-operation. Two sequential
12054    /// operations each get their own arena (verified by both succeeding).
12055    #[test]
12056    fn arena_reset_between_operations() {
12057        let left = Series::from_values(
12058            "left",
12059            vec!["a".into(), "b".into()],
12060            vec![Scalar::Int64(1), Scalar::Int64(2)],
12061        )
12062        .expect("left");
12063        let right = Series::from_values(
12064            "right",
12065            vec!["a".into(), "c".into()],
12066            vec![Scalar::Int64(10), Scalar::Int64(30)],
12067        )
12068        .expect("right");
12069
12070        // Operation 1: inner join
12071        let out1 = join_series_with_options(
12072            &left,
12073            &right,
12074            JoinType::Inner,
12075            JoinExecutionOptions::default(),
12076        )
12077        .expect("op1");
12078        assert_eq!(out1.index.labels().len(), 1);
12079
12080        // Operation 2: left join (arena from op1 was freed)
12081        let out2 = join_series_with_options(
12082            &left,
12083            &right,
12084            JoinType::Left,
12085            JoinExecutionOptions::default(),
12086        )
12087        .expect("op2");
12088        assert_eq!(out2.index.labels().len(), 2);
12089    }
12090
12091    // ---- DataFrame merge tests (bd-2gi.17) ----
12092
12093    use fp_frame::{DataFrame, FrameError};
12094
12095    use super::{
12096        JoinError, MergeExecutionOptions, MergeValidateMode, MergedDataFrame,
12097        build_single_key_dense_right_merge_output, dense_int64_right_positions, merge_dataframes,
12098        merge_dataframes_on, merge_dataframes_on_with, merge_dataframes_on_with_options,
12099        ordered_identity_int64_keys_match, resolve_merge_suffixes,
12100    };
12101
12102    fn make_left_df() -> DataFrame {
12103        DataFrame::from_dict(
12104            &["id", "val_a"],
12105            vec![
12106                (
12107                    "id",
12108                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
12109                ),
12110                (
12111                    "val_a",
12112                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
12113                ),
12114            ],
12115        )
12116        .unwrap()
12117    }
12118
12119    fn make_right_df() -> DataFrame {
12120        DataFrame::from_dict(
12121            &["id", "val_b"],
12122            vec![
12123                (
12124                    "id",
12125                    vec![Scalar::Int64(2), Scalar::Int64(3), Scalar::Int64(4)],
12126                ),
12127                (
12128                    "val_b",
12129                    vec![Scalar::Int64(200), Scalar::Int64(300), Scalar::Int64(400)],
12130                ),
12131            ],
12132        )
12133        .unwrap()
12134    }
12135
12136    #[test]
12137    fn merge_preserves_pandas_column_order_for_nonalphabetical_names() {
12138        // br-frankenpandas-691lh: output columns follow pandas order — key/left
12139        // columns in the LEFT frame's source order, then right non-key columns —
12140        // not alphabetical (the columns map is a BTreeMap). Verified vs pandas
12141        // 2.2.3: merge(left[k,zebra,apple], right[k,mango], on=k)
12142        //   -> [k, zebra, apple, mango].
12143        let left = DataFrame::from_dict(
12144            &["k", "zebra", "apple"],
12145            vec![
12146                ("k", vec![Scalar::Int64(1), Scalar::Int64(2)]),
12147                ("zebra", vec![Scalar::Int64(10), Scalar::Int64(20)]),
12148                ("apple", vec![Scalar::Int64(30), Scalar::Int64(40)]),
12149            ],
12150        )
12151        .unwrap();
12152        let right = DataFrame::from_dict(
12153            &["k", "mango"],
12154            vec![
12155                ("k", vec![Scalar::Int64(1), Scalar::Int64(2)]),
12156                ("mango", vec![Scalar::Int64(50), Scalar::Int64(60)]),
12157            ],
12158        )
12159        .unwrap();
12160        let merged = merge_dataframes(&left, &right, "k", JoinType::Inner).unwrap();
12161        let order: Vec<&str> = merged.column_order.iter().map(String::as_str).collect();
12162        assert_eq!(order, ["k", "zebra", "apple", "mango"]);
12163    }
12164
12165    #[test]
12166    fn join_row_count_lattice_n8npw() {
12167        // Invariant (br-frankenpandas-n8npw): inner<=left<=outer and inner<=right<=outer
12168        // by row count. Seeded LCG, no mocks.
12169        let mut s: u64 = 0x4e57_0b1c_2d3e_4f55;
12170        let mut next = || {
12171            s = s
12172                .wrapping_mul(6_364_136_223_846_793_005)
12173                .wrapping_add(1_442_695_040_888_963_407);
12174            (s >> 33) as u32
12175        };
12176        for iter in 0..300u32 {
12177            let ln = (next() % 6) as usize + 1;
12178            let rn = (next() % 6) as usize + 1;
12179            let lk: Vec<Scalar> = (0..ln)
12180                .map(|_| Scalar::Int64((next() % 4) as i64))
12181                .collect();
12182            let rk: Vec<Scalar> = (0..rn)
12183                .map(|_| Scalar::Int64((next() % 4) as i64))
12184                .collect();
12185            let left = DataFrame::from_dict(
12186                &["k", "lv"],
12187                vec![
12188                    ("k", lk),
12189                    ("lv", (0..ln).map(|i| Scalar::Int64(i as i64)).collect()),
12190                ],
12191            )
12192            .unwrap();
12193            let right = DataFrame::from_dict(
12194                &["k", "rv"],
12195                vec![
12196                    ("k", rk),
12197                    ("rv", (0..rn).map(|i| Scalar::Int64(i as i64)).collect()),
12198                ],
12199            )
12200            .unwrap();
12201            let rows = |jt| {
12202                let m = merge_dataframes(&left, &right, "k", jt).unwrap();
12203                merged_values(&m, "k").unwrap().len()
12204            };
12205            let inner = rows(JoinType::Inner);
12206            let lj = rows(JoinType::Left);
12207            let rj = rows(JoinType::Right);
12208            let outer = rows(JoinType::Outer);
12209            assert!(
12210                inner <= lj && lj <= outer,
12211                "inner<=left<=outer iter={iter}: {inner} {lj} {outer}"
12212            );
12213            assert!(
12214                inner <= rj && rj <= outer,
12215                "inner<=right<=outer iter={iter}: {inner} {rj} {outer}"
12216            );
12217        }
12218    }
12219
12220    #[test]
12221    fn right_join_null_fill_multiset_7je8m() {
12222        use std::collections::HashMap;
12223        // Differential (br-frankenpandas-7je8m): RIGHT join preserves every right row;
12224        // matched left payload cross-product else null. (key, lv-or-None, rv) multiset
12225        // vs oracle. Seeded LCG, no mocks.
12226        let mut s: u64 = 0x4e57_0b1c_2d3e_4f54;
12227        let mut next = || {
12228            s = s
12229                .wrapping_mul(6_364_136_223_846_793_005)
12230                .wrapping_add(1_442_695_040_888_963_407);
12231            (s >> 33) as u32
12232        };
12233        for iter in 0..300u32 {
12234            let ln = (next() % 6) as usize + 1;
12235            let rn = (next() % 6) as usize + 1;
12236            let lk: Vec<i64> = (0..ln).map(|_| (next() % 4) as i64).collect();
12237            let lv: Vec<i64> = (0..ln).map(|i| i as i64).collect();
12238            let rk: Vec<i64> = (0..rn).map(|_| (next() % 4) as i64).collect();
12239            let rv: Vec<i64> = (0..rn).map(|i| 100 + i as i64).collect();
12240            let left = DataFrame::from_dict(
12241                &["k", "lv"],
12242                vec![
12243                    ("k", lk.iter().map(|&x| Scalar::Int64(x)).collect()),
12244                    ("lv", lv.iter().map(|&x| Scalar::Int64(x)).collect()),
12245                ],
12246            )
12247            .unwrap();
12248            let right = DataFrame::from_dict(
12249                &["k", "rv"],
12250                vec![
12251                    ("k", rk.iter().map(|&x| Scalar::Int64(x)).collect()),
12252                    ("rv", rv.iter().map(|&x| Scalar::Int64(x)).collect()),
12253                ],
12254            )
12255            .unwrap();
12256            let merged = merge_dataframes(&left, &right, "k", JoinType::Right).unwrap();
12257
12258            let ks = merged_values(&merged, "k").unwrap();
12259            let lvs = merged_values(&merged, "lv").unwrap();
12260            let rvs = merged_values(&merged, "rv").unwrap();
12261            let ki = |v: &Scalar| -> i64 {
12262                match v {
12263                    Scalar::Int64(x) => *x,
12264                    Scalar::Float64(x) => *x as i64,
12265                    _ => i64::MIN,
12266                }
12267            };
12268            let kopt =
12269                |v: &Scalar| -> Option<i64> { if v.is_missing() { None } else { Some(ki(v)) } };
12270            let mut got: Vec<(i64, Option<i64>, i64)> = (0..ks.len())
12271                .map(|i| (ki(&ks[i]), kopt(&lvs[i]), ki(&rvs[i])))
12272                .collect();
12273            // Oracle.
12274            let mut lby: HashMap<i64, Vec<i64>> = HashMap::new();
12275            for i in 0..ln {
12276                lby.entry(lk[i]).or_default().push(lv[i]);
12277            }
12278            let mut exp: Vec<(i64, Option<i64>, i64)> = Vec::new();
12279            for i in 0..rn {
12280                match lby.get(&rk[i]) {
12281                    Some(lvals) => {
12282                        for &a in lvals {
12283                            exp.push((rk[i], Some(a), rv[i]));
12284                        }
12285                    }
12286                    None => exp.push((rk[i], None, rv[i])),
12287                }
12288            }
12289            got.sort();
12290            exp.sort();
12291            assert_eq!(got, exp, "right join multiset iter={iter}");
12292        }
12293    }
12294
12295    #[test]
12296    fn inner_join_utf8_value_multiset_fr4ns() {
12297        use std::collections::HashMap;
12298        // Differential (br-frankenpandas-fr4ns): inner join on Utf8 keys; the (key,
12299        // lv, rv) multiset == per-key cross-product (5foyp was int/dense; jlf8d a
12300        // single case). Seeded LCG, no mocks.
12301        let mut s: u64 = 0x4e57_0b1c_2d3e_4f51;
12302        let mut next = || {
12303            s = s
12304                .wrapping_mul(6_364_136_223_846_793_005)
12305                .wrapping_add(1_442_695_040_888_963_407);
12306            (s >> 33) as u32
12307        };
12308        let key = |n: u32| Scalar::Utf8(format!("{}", (b'a' + (n % 4) as u8) as char));
12309        for iter in 0..300u32 {
12310            let ln = (next() % 6) as usize + 1;
12311            let rn = (next() % 6) as usize + 1;
12312            let lk: Vec<Scalar> = (0..ln).map(|_| key(next())).collect();
12313            let lv: Vec<i64> = (0..ln).map(|i| i as i64).collect();
12314            let rk: Vec<Scalar> = (0..rn).map(|_| key(next())).collect();
12315            let rv: Vec<i64> = (0..rn).map(|i| 100 + i as i64).collect();
12316            let left = DataFrame::from_dict(
12317                &["k", "lv"],
12318                vec![
12319                    ("k", lk.clone()),
12320                    ("lv", lv.iter().map(|&x| Scalar::Int64(x)).collect()),
12321                ],
12322            )
12323            .unwrap();
12324            let right = DataFrame::from_dict(
12325                &["k", "rv"],
12326                vec![
12327                    ("k", rk.clone()),
12328                    ("rv", rv.iter().map(|&x| Scalar::Int64(x)).collect()),
12329                ],
12330            )
12331            .unwrap();
12332            let merged = merge_dataframes(&left, &right, "k", JoinType::Inner).unwrap();
12333
12334            let ks = merged_values(&merged, "k").unwrap();
12335            let lvs = merged_values(&merged, "lv").unwrap();
12336            let rvs = merged_values(&merged, "rv").unwrap();
12337            let kstr = |v: &Scalar| -> String {
12338                match v {
12339                    Scalar::Utf8(x) => x.clone(),
12340                    _ => String::new(),
12341                }
12342            };
12343            let ki = |v: &Scalar| -> i64 {
12344                match v {
12345                    Scalar::Int64(x) => *x,
12346                    _ => i64::MIN,
12347                }
12348            };
12349            let mut got: Vec<(String, i64, i64)> = (0..ks.len())
12350                .map(|i| (kstr(&ks[i]), ki(&lvs[i]), ki(&rvs[i])))
12351                .collect();
12352            // Oracle: per-key cross product.
12353            let mut lby: HashMap<String, Vec<i64>> = HashMap::new();
12354            for i in 0..ln {
12355                lby.entry(kstr(&lk[i])).or_default().push(lv[i]);
12356            }
12357            let mut rby: HashMap<String, Vec<i64>> = HashMap::new();
12358            for i in 0..rn {
12359                rby.entry(kstr(&rk[i])).or_default().push(rv[i]);
12360            }
12361            let mut exp: Vec<(String, i64, i64)> = Vec::new();
12362            for (k, lvals) in &lby {
12363                if let Some(rvals) = rby.get(k) {
12364                    for &a in lvals {
12365                        for &b in rvals {
12366                            exp.push((k.clone(), a, b));
12367                        }
12368                    }
12369                }
12370            }
12371            got.sort();
12372            exp.sort();
12373            assert_eq!(got, exp, "inner Utf8 multiset iter={iter}");
12374        }
12375    }
12376
12377    #[test]
12378    fn inner_join_utf8_keys_jlf8d() {
12379        use std::collections::HashMap;
12380        // br-frankenpandas-jlf8d: inner join on Utf8 keys (general/hash path).
12381        let s = |v: &str| Scalar::Utf8(v.to_owned());
12382        let left = DataFrame::from_dict(
12383            &["k", "lv"],
12384            vec![
12385                ("k", vec![s("a"), s("b"), s("c")]),
12386                (
12387                    "lv",
12388                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
12389                ),
12390            ],
12391        )
12392        .expect("left");
12393        let right = DataFrame::from_dict(
12394            &["k", "rv"],
12395            vec![
12396                ("k", vec![s("b"), s("c"), s("d")]),
12397                (
12398                    "rv",
12399                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
12400                ),
12401            ],
12402        )
12403        .expect("right");
12404        let merged = merge_dataframes(&left, &right, "k", JoinType::Inner).expect("merge");
12405
12406        let keys = merged_values(&merged, "k").expect("k");
12407        let lv = merged_values(&merged, "lv").expect("lv");
12408        let rv = merged_values(&merged, "rv").expect("rv");
12409        let exp_lv: HashMap<&str, i64> = [("b", 2), ("c", 3)].into_iter().collect();
12410        let exp_rv: HashMap<&str, i64> = [("b", 10), ("c", 20)].into_iter().collect();
12411        assert_eq!(keys.len(), 2, "inner keys = {{b,c}}");
12412        for i in 0..keys.len() {
12413            let k = match &keys[i] {
12414                Scalar::Utf8(x) => x.as_str(),
12415                _ => "?",
12416            };
12417            let geti = |s: &Scalar| match s {
12418                Scalar::Int64(v) => *v,
12419                _ => i64::MIN,
12420            };
12421            assert_eq!(geti(&lv[i]), exp_lv[k], "lv at {k}");
12422            assert_eq!(geti(&rv[i]), exp_rv[k], "rv at {k}");
12423        }
12424    }
12425
12426    #[test]
12427    fn merge_indicator_column_d3ec6() {
12428        use std::collections::BTreeSet;
12429        // br-frankenpandas-d3ec6: outer-join indicator marks left_only/both/right_only.
12430        let left = DataFrame::from_dict(
12431            &["k"],
12432            vec![(
12433                "k",
12434                vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
12435            )],
12436        )
12437        .expect("left");
12438        let right = DataFrame::from_dict(
12439            &["k"],
12440            vec![(
12441                "k",
12442                vec![Scalar::Int64(2), Scalar::Int64(3), Scalar::Int64(4)],
12443            )],
12444        )
12445        .expect("right");
12446        let opts = super::MergeExecutionOptions {
12447            indicator_name: Some("_merge".to_owned()),
12448            ..Default::default()
12449        };
12450        let m = super::merge_dataframes_on_with_options(
12451            &left,
12452            &right,
12453            &["k"],
12454            &["k"],
12455            JoinType::Outer,
12456            opts,
12457        )
12458        .expect("merge");
12459
12460        let keys = merged_values(&m, "k").expect("k");
12461        let ind = merged_values(&m, "_merge").expect("_merge present");
12462        let lset: BTreeSet<i64> = [1, 2, 3].into_iter().collect();
12463        let rset: BTreeSet<i64> = [2, 3, 4].into_iter().collect();
12464        assert_eq!(keys.len(), 4, "outer keys = union");
12465        for i in 0..keys.len() {
12466            let k = match &keys[i] {
12467                Scalar::Int64(v) => *v,
12468                _ => i64::MIN,
12469            };
12470            let exp = match (lset.contains(&k), rset.contains(&k)) {
12471                (true, true) => "both",
12472                (true, false) => "left_only",
12473                (false, true) => "right_only",
12474                (false, false) => "??",
12475            };
12476            assert_eq!(ind[i], Scalar::Utf8(exp.to_owned()), "indicator at key {k}");
12477        }
12478    }
12479
12480    #[test]
12481    fn merge_overlapping_columns_suffixed_vb10q() {
12482        // br-frankenpandas-vb10q: a non-key column present in both frames is
12483        // suffixed _x (left) / _y (right) on merge.
12484        let mk = |vfactor: i64| {
12485            DataFrame::from_dict(
12486                &["k", "v"],
12487                vec![
12488                    (
12489                        "k",
12490                        vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
12491                    ),
12492                    (
12493                        "v",
12494                        vec![
12495                            Scalar::Int64(vfactor),
12496                            Scalar::Int64(2 * vfactor),
12497                            Scalar::Int64(3 * vfactor),
12498                        ],
12499                    ),
12500                ],
12501            )
12502            .expect("frame")
12503        };
12504        let left = mk(10); // v = k*10
12505        let right = mk(100); // v = k*100
12506        let merged = merge_dataframes(&left, &right, "k", JoinType::Inner).expect("merge");
12507
12508        let keys = merged_values(&merged, "k").expect("k");
12509        let vx = merged_values(&merged, "v_x").expect("v_x present");
12510        let vy = merged_values(&merged, "v_y").expect("v_y present");
12511        assert_eq!(keys.len(), 3);
12512        for i in 0..keys.len() {
12513            let k = match &keys[i] {
12514                Scalar::Int64(x) => *x,
12515                _ => i64::MIN,
12516            };
12517            assert_eq!(vx[i], Scalar::Int64(k * 10), "v_x at key {k}");
12518            assert_eq!(vy[i], Scalar::Int64(k * 100), "v_y at key {k}");
12519        }
12520    }
12521
12522    #[test]
12523    fn int64_join_row_count_matches_cardinality_invariant_ya1po() {
12524        use std::collections::BTreeMap;
12525
12526        // Metamorphic harness (br-frankenpandas-ya1po): merge_dataframes row count
12527        // must equal the pandas-standard cardinality per join type — an
12528        // ordering-independent invariant guarding the dense/direct-address Int64
12529        // join fast paths. Deterministic seeded LCG — no rand crate, no mocks.
12530        let mut state: u64 = 0xa5a5_5a5a_dead_beef;
12531        let mut next = || {
12532            state = state
12533                .wrapping_mul(6_364_136_223_846_793_005)
12534                .wrapping_add(1_442_695_040_888_963_407);
12535            (state >> 33) as u32
12536        };
12537
12538        let build = |keys: &[i64], payload_name: &str| {
12539            let n = keys.len();
12540            DataFrame::from_dict(
12541                &["k", payload_name],
12542                vec![
12543                    (
12544                        "k",
12545                        keys.iter().copied().map(Scalar::Int64).collect::<Vec<_>>(),
12546                    ),
12547                    (
12548                        payload_name,
12549                        (0..n as i64).map(Scalar::Int64).collect::<Vec<_>>(),
12550                    ),
12551                ],
12552            )
12553            .expect("frame")
12554        };
12555
12556        for iter in 0..1500u32 {
12557            let nl = (next() % 9) as usize + 1;
12558            let nr = (next() % 9) as usize + 1;
12559            // Small key range so many-to-many (duplicate-key) joins are common.
12560            let lk: Vec<i64> = (0..nl).map(|_| (next() % 4) as i64).collect();
12561            let rk: Vec<i64> = (0..nr).map(|_| (next() % 4) as i64).collect();
12562            let left = build(&lk, "lv");
12563            let right = build(&rk, "rv");
12564
12565            let mut lc: BTreeMap<i64, i64> = BTreeMap::new();
12566            let mut rc: BTreeMap<i64, i64> = BTreeMap::new();
12567            for &k in &lk {
12568                *lc.entry(k).or_default() += 1;
12569            }
12570            for &k in &rk {
12571                *rc.entry(k).or_default() += 1;
12572            }
12573            let mut all_keys: Vec<i64> = lc.keys().chain(rc.keys()).copied().collect();
12574            all_keys.sort_unstable();
12575            all_keys.dedup();
12576
12577            let g = |k: i64, m: &BTreeMap<i64, i64>| m.get(&k).copied().unwrap_or(0);
12578            let inner: i64 = all_keys.iter().map(|&k| g(k, &lc) * g(k, &rc)).sum();
12579            let left_exp: i64 = lc.iter().map(|(&k, &l)| l * g(k, &rc).max(1)).sum();
12580            let right_exp: i64 = rc.iter().map(|(&k, &r)| r * g(k, &lc).max(1)).sum();
12581            let outer: i64 = all_keys
12582                .iter()
12583                .map(|&k| {
12584                    let (l, r) = (g(k, &lc), g(k, &rc));
12585                    if l > 0 && r > 0 { l * r } else { l + r }
12586                })
12587                .sum();
12588
12589            let ctx = format!("iter={iter} lk={lk:?} rk={rk:?}");
12590            for (jt, exp) in [
12591                (JoinType::Inner, inner),
12592                (JoinType::Left, left_exp),
12593                (JoinType::Right, right_exp),
12594                (JoinType::Outer, outer),
12595            ] {
12596                let merged = merge_dataframes(&left, &right, "k", jt).expect("merge");
12597                let rows = merged_values(&merged, "k").expect("key col").len() as i64;
12598                assert_eq!(rows, exp, "{jt:?} row count {ctx}");
12599            }
12600        }
12601    }
12602
12603    #[test]
12604    fn inner_join_value_multiset_matches_crossproduct_oracle_5foyp() {
12605        use std::collections::BTreeMap;
12606
12607        // Value-level oracle (br-frankenpandas-5foyp): an inner join must pair the
12608        // CORRECT rows, not merely produce the right count. Assert the multiset of
12609        // output (key, left_payload, right_payload) triples equals the
12610        // independently-computed per-key cross product. Ordering-independent
12611        // (sorted-vector compare). Deterministic seeded LCG — no rand, no mocks.
12612        let mut state: u64 = 0x0ddc_0ffe_e0dd_f00d;
12613        let mut next = || {
12614            state = state
12615                .wrapping_mul(6_364_136_223_846_793_005)
12616                .wrapping_add(1_442_695_040_888_963_407);
12617            (state >> 33) as u32
12618        };
12619
12620        let build = |keys: &[i64], pname: &str| {
12621            let n = keys.len();
12622            DataFrame::from_dict(
12623                &["k", pname],
12624                vec![
12625                    (
12626                        "k",
12627                        keys.iter().copied().map(Scalar::Int64).collect::<Vec<_>>(),
12628                    ),
12629                    // Distinct per-row payload (= row index) so mis-pairings are visible.
12630                    (pname, (0..n as i64).map(Scalar::Int64).collect::<Vec<_>>()),
12631                ],
12632            )
12633            .expect("frame")
12634        };
12635        // Extract i64; a non-Int64 maps to a sentinel that will never equal a
12636        // real row index/key, so any dtype regression still fails the multiset
12637        // assert below (no panic — keeps the helper side-effect-free).
12638        let geti = |s: &Scalar| match s {
12639            Scalar::Int64(v) => *v,
12640            _ => i64::MIN,
12641        };
12642
12643        for iter in 0..1500u32 {
12644            let nl = (next() % 9) as usize + 1;
12645            let nr = (next() % 9) as usize + 1;
12646            let lk: Vec<i64> = (0..nl).map(|_| (next() % 4) as i64).collect();
12647            let rk: Vec<i64> = (0..nr).map(|_| (next() % 4) as i64).collect();
12648            let left = build(&lk, "lv");
12649            let right = build(&rk, "rv");
12650
12651            let merged = merge_dataframes(&left, &right, "k", JoinType::Inner).expect("merge");
12652            let ks = merged_values(&merged, "k").expect("k");
12653            let lvs = merged_values(&merged, "lv").expect("lv");
12654            let rvs = merged_values(&merged, "rv").expect("rv");
12655            let mut got: Vec<(i64, i64, i64)> = (0..ks.len())
12656                .map(|i| (geti(&ks[i]), geti(&lvs[i]), geti(&rvs[i])))
12657                .collect();
12658            got.sort_unstable();
12659
12660            // Independent oracle: per-key cross product of left/right row payloads.
12661            let mut lg: BTreeMap<i64, Vec<i64>> = BTreeMap::new();
12662            let mut rg: BTreeMap<i64, Vec<i64>> = BTreeMap::new();
12663            for (i, &k) in lk.iter().enumerate() {
12664                lg.entry(k).or_default().push(i as i64);
12665            }
12666            for (i, &k) in rk.iter().enumerate() {
12667                rg.entry(k).or_default().push(i as i64);
12668            }
12669            let mut exp: Vec<(i64, i64, i64)> = Vec::new();
12670            for (&k, lps) in &lg {
12671                if let Some(rps) = rg.get(&k) {
12672                    for &a in lps {
12673                        for &b in rps {
12674                            exp.push((k, a, b));
12675                        }
12676                    }
12677                }
12678            }
12679            exp.sort_unstable();
12680
12681            assert_eq!(
12682                got, exp,
12683                "inner join value multiset iter={iter} lk={lk:?} rk={rk:?}"
12684            );
12685        }
12686    }
12687
12688    #[test]
12689    fn left_outer_join_nullfill_value_oracle_kaj3t() {
12690        use std::collections::BTreeMap;
12691
12692        // Value oracle for LEFT/OUTER null-fill (br-frankenpandas-kaj3t): unmatched
12693        // rows get NULL-filled on the absent side — the subtlest join behavior.
12694        // NULL is represented by the i64::MIN sentinel (payloads are 0..n and keys
12695        // 0..3, so a sentinel never collides with a real value). Deterministic
12696        // seeded LCG — no rand crate, no mocks.
12697        const NUL: i64 = i64::MIN;
12698        let mut state: u64 = 0xfeed_face_cafe_b0ba;
12699        let mut next = || {
12700            state = state
12701                .wrapping_mul(6_364_136_223_846_793_005)
12702                .wrapping_add(1_442_695_040_888_963_407);
12703            (state >> 33) as u32
12704        };
12705
12706        let build = |keys: &[i64], pname: &str| {
12707            let n = keys.len();
12708            DataFrame::from_dict(
12709                &["k", pname],
12710                vec![
12711                    (
12712                        "k",
12713                        keys.iter().copied().map(Scalar::Int64).collect::<Vec<_>>(),
12714                    ),
12715                    (pname, (0..n as i64).map(Scalar::Int64).collect::<Vec<_>>()),
12716                ],
12717            )
12718            .expect("frame")
12719        };
12720        // Int64 -> value. Left/outer joins upcast Int64 payload columns to
12721        // Float64 when null-fill introduces missing values (pandas parity: Int64
12722        // can't hold NaN), so accept finite Float64 too. NULL / NaN -> NUL
12723        // sentinel. Payloads are small whole numbers, so f64 -> i64 is exact.
12724        let geti = |s: &Scalar| match s {
12725            Scalar::Int64(v) => *v,
12726            Scalar::Float64(v) if v.is_finite() => *v as i64,
12727            _ => NUL,
12728        };
12729
12730        for iter in 0..1500u32 {
12731            let nl = (next() % 9) as usize + 1;
12732            let nr = (next() % 9) as usize + 1;
12733            let lk: Vec<i64> = (0..nl).map(|_| (next() % 4) as i64).collect();
12734            let rk: Vec<i64> = (0..nr).map(|_| (next() % 4) as i64).collect();
12735            let left = build(&lk, "lv");
12736            let right = build(&rk, "rv");
12737
12738            // Right rows grouped by key (payload = row index).
12739            let mut rg: BTreeMap<i64, Vec<i64>> = BTreeMap::new();
12740            for (j, &k) in rk.iter().enumerate() {
12741                rg.entry(k).or_default().push(j as i64);
12742            }
12743            let lkeys: std::collections::BTreeSet<i64> = lk.iter().copied().collect();
12744
12745            let read = |jt: JoinType| -> Vec<(i64, i64, i64)> {
12746                let merged = merge_dataframes(&left, &right, "k", jt).expect("merge");
12747                let ks = merged_values(&merged, "k").expect("k");
12748                let lvs = merged_values(&merged, "lv").expect("lv");
12749                let rvs = merged_values(&merged, "rv").expect("rv");
12750                let mut got: Vec<(i64, i64, i64)> = (0..ks.len())
12751                    .map(|i| (geti(&ks[i]), geti(&lvs[i]), geti(&rvs[i])))
12752                    .collect();
12753                got.sort_unstable();
12754                got
12755            };
12756
12757            // LEFT oracle: every left row appears; matched -> one row per right
12758            // match, unmatched -> NULL right payload (key still the left key).
12759            let mut exp_left: Vec<(i64, i64, i64)> = Vec::new();
12760            for (i, &k) in lk.iter().enumerate() {
12761                match rg.get(&k) {
12762                    Some(rps) => {
12763                        for &j in rps {
12764                            exp_left.push((k, i as i64, j));
12765                        }
12766                    }
12767                    None => exp_left.push((k, i as i64, NUL)),
12768                }
12769            }
12770            exp_left.sort_unstable();
12771            assert_eq!(
12772                read(JoinType::Left),
12773                exp_left,
12774                "left join value oracle iter={iter} lk={lk:?} rk={rk:?}"
12775            );
12776
12777            // OUTER oracle: LEFT plus right-only rows (no left match) with NULL
12778            // left payload and the coalesced key.
12779            let mut exp_outer = exp_left.clone();
12780            for (j, &k) in rk.iter().enumerate() {
12781                if !lkeys.contains(&k) {
12782                    exp_outer.push((k, NUL, j as i64));
12783                }
12784            }
12785            exp_outer.sort_unstable();
12786            assert_eq!(
12787                read(JoinType::Outer),
12788                exp_outer,
12789                "outer join value oracle iter={iter} lk={lk:?} rk={rk:?}"
12790            );
12791        }
12792    }
12793
12794    #[test]
12795    fn left_join_value_multiset_matches_unmatched_oracle_gp0ik() {
12796        use std::collections::BTreeMap;
12797
12798        // Value-level LEFT join oracle (br-frankenpandas-gp0ik): matched keys
12799        // emit the left/right cross product; unmatched left rows emit exactly one
12800        // row with a missing right payload. Ordering-independent sorted multiset.
12801        let mut state: u64 = 0x51de_cafe_2026_0618;
12802        let mut next = || {
12803            state = state
12804                .wrapping_mul(6_364_136_223_846_793_005)
12805                .wrapping_add(1_442_695_040_888_963_407);
12806            (state >> 33) as u32
12807        };
12808
12809        let build = |keys: &[i64], pname: &str| {
12810            let n = keys.len();
12811            DataFrame::from_dict(
12812                &["k", pname],
12813                vec![
12814                    (
12815                        "k",
12816                        keys.iter().copied().map(Scalar::Int64).collect::<Vec<_>>(),
12817                    ),
12818                    (pname, (0..n as i64).map(Scalar::Int64).collect::<Vec<_>>()),
12819                ],
12820            )
12821            .expect("frame")
12822        };
12823        let geti = |s: &Scalar| match s {
12824            Scalar::Int64(v) => *v,
12825            _ => i64::MIN,
12826        };
12827        let get_optional_i64 = |s: &Scalar| match s {
12828            Scalar::Int64(v) => Some(*v),
12829            Scalar::Float64(v) if v.is_finite() && v.fract() == 0.0 => Some(*v as i64),
12830            value if value.is_missing() => None,
12831            _ => Some(i64::MIN),
12832        };
12833
12834        for iter in 0..1500u32 {
12835            let nl = (next() % 9) as usize + 1;
12836            let nr = (next() % 9) as usize + 1;
12837            let lk: Vec<i64> = (0..nl).map(|_| (next() % 5) as i64).collect();
12838            let rk: Vec<i64> = (0..nr).map(|_| (next() % 3) as i64).collect();
12839            let left = build(&lk, "lv");
12840            let right = build(&rk, "rv");
12841
12842            let merged = merge_dataframes(&left, &right, "k", JoinType::Left).expect("merge");
12843            let ks = merged_values(&merged, "k").expect("k");
12844            let lvs = merged_values(&merged, "lv").expect("lv");
12845            let rvs = merged_values(&merged, "rv").expect("rv");
12846            let mut got: Vec<(i64, i64, Option<i64>)> = (0..ks.len())
12847                .map(|i| (geti(&ks[i]), geti(&lvs[i]), get_optional_i64(&rvs[i])))
12848                .collect();
12849            got.sort_unstable();
12850
12851            let mut rg: BTreeMap<i64, Vec<i64>> = BTreeMap::new();
12852            for (i, &k) in rk.iter().enumerate() {
12853                rg.entry(k).or_default().push(i as i64);
12854            }
12855            let mut exp: Vec<(i64, i64, Option<i64>)> = Vec::new();
12856            for (left_pos, &k) in lk.iter().enumerate() {
12857                if let Some(right_positions) = rg.get(&k) {
12858                    for &right_pos in right_positions {
12859                        exp.push((k, left_pos as i64, Some(right_pos)));
12860                    }
12861                } else {
12862                    exp.push((k, left_pos as i64, None));
12863                }
12864            }
12865            exp.sort_unstable();
12866
12867            assert_eq!(
12868                got, exp,
12869                "left join value multiset iter={iter} lk={lk:?} rk={rk:?}"
12870            );
12871        }
12872    }
12873
12874    #[test]
12875    fn right_join_value_multiset_matches_unmatched_oracle_pd1h5() {
12876        use std::collections::BTreeMap;
12877
12878        // Value-level RIGHT join oracle (br-frankenpandas-pd1h5): matched keys
12879        // emit the left/right cross product; unmatched right rows emit exactly one
12880        // row with a missing left payload. Ordering-independent sorted multiset.
12881        let mut state: u64 = 0x7191_2026_0618_a015;
12882        let mut next = || {
12883            state = state
12884                .wrapping_mul(6_364_136_223_846_793_005)
12885                .wrapping_add(1_442_695_040_888_963_407);
12886            (state >> 33) as u32
12887        };
12888
12889        let build = |keys: &[i64], pname: &str| {
12890            let n = keys.len();
12891            DataFrame::from_dict(
12892                &["k", pname],
12893                vec![
12894                    (
12895                        "k",
12896                        keys.iter().copied().map(Scalar::Int64).collect::<Vec<_>>(),
12897                    ),
12898                    (pname, (0..n as i64).map(Scalar::Int64).collect::<Vec<_>>()),
12899                ],
12900            )
12901            .expect("frame")
12902        };
12903        let geti = |s: &Scalar| match s {
12904            Scalar::Int64(v) => *v,
12905            Scalar::Float64(v) if v.is_finite() => *v as i64,
12906            _ => i64::MIN,
12907        };
12908        let get_optional_i64 = |s: &Scalar| match s {
12909            Scalar::Int64(v) => Some(*v),
12910            Scalar::Float64(v) if v.is_finite() => Some(*v as i64),
12911            value if value.is_missing() => None,
12912            _ => Some(i64::MIN),
12913        };
12914
12915        for iter in 0..1500u32 {
12916            let nl = (next() % 9) as usize + 1;
12917            let nr = (next() % 9) as usize + 1;
12918            let lk: Vec<i64> = (0..nl).map(|_| (next() % 4) as i64).collect();
12919            let rk: Vec<i64> = (0..nr).map(|_| (next() % 5) as i64).collect();
12920            let left = build(&lk, "lv");
12921            let right = build(&rk, "rv");
12922
12923            let merged = merge_dataframes(&left, &right, "k", JoinType::Right).expect("merge");
12924            let ks = merged_values(&merged, "k").expect("k");
12925            let lvs = merged_values(&merged, "lv").expect("lv");
12926            let rvs = merged_values(&merged, "rv").expect("rv");
12927            let mut got: Vec<(i64, Option<i64>, i64)> = (0..ks.len())
12928                .map(|i| (geti(&ks[i]), get_optional_i64(&lvs[i]), geti(&rvs[i])))
12929                .collect();
12930            got.sort_unstable();
12931
12932            let mut lg: BTreeMap<i64, Vec<i64>> = BTreeMap::new();
12933            for (i, &k) in lk.iter().enumerate() {
12934                lg.entry(k).or_default().push(i as i64);
12935            }
12936            let mut exp: Vec<(i64, Option<i64>, i64)> = Vec::new();
12937            for (right_pos, &k) in rk.iter().enumerate() {
12938                if let Some(left_positions) = lg.get(&k) {
12939                    for &left_pos in left_positions {
12940                        exp.push((k, Some(left_pos), right_pos as i64));
12941                    }
12942                } else {
12943                    exp.push((k, None, right_pos as i64));
12944                }
12945            }
12946            exp.sort_unstable();
12947
12948            assert_eq!(
12949                got, exp,
12950                "right join value multiset iter={iter} lk={lk:?} rk={rk:?}"
12951            );
12952        }
12953    }
12954
12955    fn merged_values<'a>(
12956        merged: &'a MergedDataFrame,
12957        name: &str,
12958    ) -> Result<&'a [Scalar], JoinError> {
12959        Ok(merged
12960            .columns
12961            .get(name)
12962            .ok_or_else(|| {
12963                JoinError::Frame(FrameError::CompatibilityRejected(format!(
12964                    "missing merged column '{name}'"
12965                )))
12966            })?
12967            .values())
12968    }
12969
12970    #[test]
12971    fn temporal_i64_inner_positions_match_scalar_oracle_with_duplicates_b2hwb() {
12972        let build_positions_from_scalar_oracle = |left: &Column, right: &Column| {
12973            let left_keys = super::collect_single_join_keys(left);
12974            let right_keys = super::collect_single_join_keys(right);
12975            let mut left_positions = Vec::new();
12976            let mut right_positions = Vec::new();
12977            for (left_pos, left_key) in left_keys.iter().enumerate() {
12978                for (right_pos, right_key) in right_keys.iter().enumerate() {
12979                    if left_key == right_key {
12980                        left_positions.push(left_pos);
12981                        right_positions.push(right_pos);
12982                    }
12983                }
12984            }
12985            (left_positions, right_positions)
12986        };
12987
12988        let left_ns = [30, 10, 20, 10];
12989        let right_ns = [10, 30, 10, 40];
12990        for temporal in [DType::datetime64_naive(), DType::Timedelta64] {
12991            let scalar = |ns| match &temporal {
12992                DType::Datetime64 { .. } => Scalar::Datetime64(ns),
12993                DType::Timedelta64 => Scalar::Timedelta64(ns),
12994                _ => unreachable!("test iterates only temporal dtypes"),
12995            };
12996            let left = Column::from_values(left_ns.into_iter().map(scalar).collect())
12997                .expect("left temporal key");
12998            let right = Column::from_values(right_ns.into_iter().map(scalar).collect())
12999                .expect("right temporal key");
13000
13001            assert_eq!(
13002                super::temporal_i64_inner_positions(&left, &right),
13003                Some(build_positions_from_scalar_oracle(&left, &right)),
13004                "raw-nanosecond planner must preserve scalar-oracle pair order for {temporal:?}"
13005            );
13006        }
13007
13008        let nat = fp_types::Timestamp::NAT;
13009        let ordered = Column::from_datetime64_values(vec![1, 2, 3, 4]);
13010        let nat_middle = Column::from_datetime64_values(vec![1, 2, nat, 4]);
13011        let nat_tail = Column::from_datetime64_values(vec![1, 2, 3, nat]);
13012        let single_nat = Column::from_datetime64_values(vec![nat]);
13013        for (left, right) in [
13014            (&nat_middle, &ordered),
13015            (&ordered, &nat_tail),
13016            (&single_nat, &ordered),
13017        ] {
13018            assert!(
13019                super::temporal_i64_inner_positions(left, right).is_none(),
13020                "NaT anywhere must retain the scalar INNER fallback",
13021            );
13022        }
13023    }
13024
13025    #[test]
13026    #[ignore = "foreground performance probe"]
13027    fn bench_temporal_i64_inner_validation_fusion_71kgc() {
13028        let n = 400_000_i64;
13029        let input_len = usize::try_from(n).expect("positive benchmark length");
13030        let left = Column::from_datetime64_values_with_validity(
13031            (0..n).collect(),
13032            ValidityMask::all_valid(input_len),
13033        );
13034        let right = Column::from_datetime64_values_with_validity(
13035            (0..n).map(|value| value * 2).collect(),
13036            ValidityMask::all_valid(input_len),
13037        );
13038
13039        // Exact pre-71kgc ordered body: separate NaT and strict-order scans
13040        // followed by the same two-pointer intersection.
13041        let former = || {
13042            if !left.validity().all() || !right.validity().all() {
13043                return None;
13044            }
13045            let left_raw = left.as_datetime64_slice()?;
13046            let right_raw = right.as_datetime64_slice()?;
13047            let nat = fp_types::Timestamp::NAT;
13048            if left_raw.contains(&nat) || right_raw.contains(&nat) {
13049                return None;
13050            }
13051            if left_raw.windows(2).any(|pair| pair[0] >= pair[1])
13052                || right_raw.windows(2).any(|pair| pair[0] >= pair[1])
13053            {
13054                return None;
13055            }
13056
13057            let mut left_positions = Vec::with_capacity(left_raw.len().min(right_raw.len()));
13058            let mut right_positions = Vec::with_capacity(left_positions.capacity());
13059            let (mut left_idx, mut right_idx) = (0usize, 0usize);
13060            while left_idx < left_raw.len() && right_idx < right_raw.len() {
13061                match left_raw[left_idx].cmp(&right_raw[right_idx]) {
13062                    std::cmp::Ordering::Equal => {
13063                        left_positions.push(left_idx);
13064                        right_positions.push(right_idx);
13065                        left_idx += 1;
13066                        right_idx += 1;
13067                    }
13068                    std::cmp::Ordering::Less => left_idx += 1,
13069                    std::cmp::Ordering::Greater => right_idx += 1,
13070                }
13071            }
13072            Some((left_positions, right_positions))
13073        };
13074        let candidate = || super::temporal_i64_inner_positions(&left, &right);
13075
13076        let former_output = former().expect("former temporal INNER positions");
13077        let candidate_output = candidate().expect("temporal INNER positions");
13078        assert_eq!(candidate_output, former_output);
13079        assert_eq!(candidate_output.0.len(), input_len.div_ceil(2));
13080        drop((former_output, candidate_output));
13081        for _ in 0..2 {
13082            std::hint::black_box(former());
13083            std::hint::black_box(candidate());
13084        }
13085
13086        type InnerPositions = Option<(Vec<usize>, Vec<usize>)>;
13087        let sample = |plan: &dyn Fn() -> InnerPositions| {
13088            let start = std::time::Instant::now();
13089            let output = std::hint::black_box(plan()).expect("supported temporal INNER plan");
13090            assert_eq!(std::hint::black_box(output.0.len()), input_len.div_ceil(2));
13091            drop(output);
13092            start.elapsed().as_secs_f64() * 1_000.0
13093        };
13094        let mut former_a = Vec::with_capacity(15);
13095        let mut former_b = Vec::with_capacity(15);
13096        let mut candidate_a = Vec::with_capacity(15);
13097        let mut candidate_b = Vec::with_capacity(15);
13098        for round in 0..15 {
13099            if round % 2 == 0 {
13100                former_a.push(sample(&former));
13101                candidate_a.push(sample(&candidate));
13102                candidate_b.push(sample(&candidate));
13103                former_b.push(sample(&former));
13104            } else {
13105                former_b.push(sample(&former));
13106                candidate_b.push(sample(&candidate));
13107                candidate_a.push(sample(&candidate));
13108                former_a.push(sample(&former));
13109            }
13110        }
13111
13112        let report = |label: &str, mut samples: Vec<f64>| {
13113            samples.sort_by(f64::total_cmp);
13114            let p50 = samples[samples.len() / 2];
13115            let p95_idx = samples
13116                .len()
13117                .saturating_mul(95)
13118                .div_ceil(100)
13119                .saturating_sub(1);
13120            println!(
13121                "{label}: p50={p50:.3} ms p95={:.3} ms max={:.3} ms",
13122                samples[p95_idx],
13123                samples[samples.len() - 1],
13124            );
13125        };
13126        report("inner_plan_three_pass_former_a", former_a);
13127        report("inner_plan_three_pass_former_b", former_b);
13128        report("inner_plan_fused_candidate_a", candidate_a);
13129        report("inner_plan_fused_candidate_b", candidate_b);
13130    }
13131
13132    #[test]
13133    fn merge_datetime_inner_preserves_dtype_order_and_nat_fallback_b2hwb() -> Result<(), JoinError>
13134    {
13135        let left = DataFrame::from_dict(
13136            &["key", "lv"],
13137            vec![
13138                (
13139                    "key",
13140                    vec![
13141                        Scalar::Datetime64(30),
13142                        Scalar::Datetime64(10),
13143                        Scalar::Datetime64(20),
13144                        Scalar::Datetime64(10),
13145                    ],
13146                ),
13147                (
13148                    "lv",
13149                    vec![
13150                        Scalar::Int64(0),
13151                        Scalar::Int64(1),
13152                        Scalar::Int64(2),
13153                        Scalar::Int64(3),
13154                    ],
13155                ),
13156            ],
13157        )?;
13158        let right = DataFrame::from_dict(
13159            &["key", "rv"],
13160            vec![
13161                (
13162                    "key",
13163                    vec![
13164                        Scalar::Datetime64(10),
13165                        Scalar::Datetime64(30),
13166                        Scalar::Datetime64(10),
13167                        Scalar::Datetime64(40),
13168                    ],
13169                ),
13170                (
13171                    "rv",
13172                    vec![
13173                        Scalar::Int64(100),
13174                        Scalar::Int64(101),
13175                        Scalar::Int64(102),
13176                        Scalar::Int64(103),
13177                    ],
13178                ),
13179            ],
13180        )?;
13181        let merged = merge_dataframes_on(&left, &right, &["key"], JoinType::Inner)?;
13182        assert_eq!(merged.columns["key"].dtype(), DType::datetime64_naive());
13183        assert_eq!(
13184            merged_values(&merged, "key")?,
13185            &[
13186                Scalar::Datetime64(30),
13187                Scalar::Datetime64(10),
13188                Scalar::Datetime64(10),
13189                Scalar::Datetime64(10),
13190                Scalar::Datetime64(10),
13191            ]
13192        );
13193        assert_eq!(
13194            merged_values(&merged, "lv")?,
13195            &[
13196                Scalar::Int64(0),
13197                Scalar::Int64(1),
13198                Scalar::Int64(1),
13199                Scalar::Int64(3),
13200                Scalar::Int64(3),
13201            ]
13202        );
13203        assert_eq!(
13204            merged_values(&merged, "rv")?,
13205            &[
13206                Scalar::Int64(101),
13207                Scalar::Int64(100),
13208                Scalar::Int64(102),
13209                Scalar::Int64(100),
13210                Scalar::Int64(102),
13211            ]
13212        );
13213
13214        let nat = fp_types::Timestamp::NAT;
13215        let nat_left = DataFrame::from_dict(
13216            &["key", "lv"],
13217            vec![
13218                ("key", vec![Scalar::Datetime64(nat), Scalar::Datetime64(5)]),
13219                ("lv", vec![Scalar::Int64(0), Scalar::Int64(1)]),
13220            ],
13221        )?;
13222        let nat_right = DataFrame::from_dict(
13223            &["key", "rv"],
13224            vec![
13225                ("key", vec![Scalar::Datetime64(nat), Scalar::Datetime64(5)]),
13226                ("rv", vec![Scalar::Int64(10), Scalar::Int64(11)]),
13227            ],
13228        )?;
13229        assert!(
13230            super::temporal_i64_inner_positions(
13231                nat_left.column("key").expect("left NaT key"),
13232                nat_right.column("key").expect("right NaT key")
13233            )
13234            .is_none(),
13235            "NaT must retain the scalar Missing-key fallback"
13236        );
13237        let nat_merged = merge_dataframes_on(&nat_left, &nat_right, &["key"], JoinType::Inner)?;
13238        assert_eq!(nat_merged.columns["key"].dtype(), DType::datetime64_naive());
13239        assert_eq!(nat_merged.index.len(), 2);
13240        assert!(merged_values(&nat_merged, "key")?[0].is_missing());
13241        assert_eq!(
13242            &merged_values(&nat_merged, "key")?[1..],
13243            &[Scalar::Datetime64(5)]
13244        );
13245
13246        Ok(())
13247    }
13248
13249    #[test]
13250    fn temporal_i64_left_positions_match_scalar_oracle_with_duplicates_lw0qg() {
13251        let build_positions_from_scalar_oracle = |left: &Column, right: &Column| {
13252            let left_keys = super::collect_single_join_keys(left);
13253            let right_keys = super::collect_single_join_keys(right);
13254            let mut left_positions = Vec::new();
13255            let mut right_positions = Vec::new();
13256            for (left_pos, left_key) in left_keys.iter().enumerate() {
13257                let mut matched = false;
13258                for (right_pos, right_key) in right_keys.iter().enumerate() {
13259                    if left_key == right_key {
13260                        left_positions.push(Some(left_pos));
13261                        right_positions.push(Some(right_pos));
13262                        matched = true;
13263                    }
13264                }
13265                if !matched {
13266                    left_positions.push(Some(left_pos));
13267                    right_positions.push(None);
13268                }
13269            }
13270            (left_positions, right_positions)
13271        };
13272
13273        let left_ns = [30, 10, 20, 10, 50];
13274        let right_ns = [10, 30, 10, 40];
13275        for temporal in [DType::datetime64_naive(), DType::Timedelta64] {
13276            let scalar = |ns| match &temporal {
13277                DType::Datetime64 { .. } => Scalar::Datetime64(ns),
13278                DType::Timedelta64 => Scalar::Timedelta64(ns),
13279                _ => unreachable!("test iterates only temporal dtypes"),
13280            };
13281            let left = Column::from_values(left_ns.into_iter().map(scalar).collect())
13282                .expect("left temporal key");
13283            let right = Column::from_values(right_ns.into_iter().map(scalar).collect())
13284                .expect("right temporal key");
13285
13286            assert_eq!(
13287                super::temporal_i64_left_positions(&left, &right),
13288                Some(build_positions_from_scalar_oracle(&left, &right)),
13289                "raw-nanosecond LEFT planner must preserve scalar-oracle row order for {temporal:?}"
13290            );
13291        }
13292    }
13293
13294    #[test]
13295    fn merge_datetime_left_preserves_dtype_order_and_nat_fallback_lw0qg() -> Result<(), JoinError> {
13296        let left = DataFrame::from_dict(
13297            &["key", "lv"],
13298            vec![
13299                (
13300                    "key",
13301                    vec![
13302                        Scalar::Datetime64(30),
13303                        Scalar::Datetime64(10),
13304                        Scalar::Datetime64(20),
13305                        Scalar::Datetime64(10),
13306                        Scalar::Datetime64(50),
13307                    ],
13308                ),
13309                (
13310                    "lv",
13311                    vec![
13312                        Scalar::Int64(0),
13313                        Scalar::Int64(1),
13314                        Scalar::Int64(2),
13315                        Scalar::Int64(3),
13316                        Scalar::Int64(4),
13317                    ],
13318                ),
13319            ],
13320        )?;
13321        let right = DataFrame::from_dict(
13322            &["key", "rv"],
13323            vec![
13324                (
13325                    "key",
13326                    vec![
13327                        Scalar::Datetime64(10),
13328                        Scalar::Datetime64(30),
13329                        Scalar::Datetime64(10),
13330                        Scalar::Datetime64(40),
13331                    ],
13332                ),
13333                (
13334                    "rv",
13335                    vec![
13336                        Scalar::Int64(100),
13337                        Scalar::Int64(101),
13338                        Scalar::Int64(102),
13339                        Scalar::Int64(103),
13340                    ],
13341                ),
13342            ],
13343        )?;
13344        let merged = merge_dataframes_on(&left, &right, &["key"], JoinType::Left)?;
13345        assert_eq!(merged.columns["key"].dtype(), DType::datetime64_naive());
13346        assert_eq!(
13347            merged_values(&merged, "key")?,
13348            &[
13349                Scalar::Datetime64(30),
13350                Scalar::Datetime64(10),
13351                Scalar::Datetime64(10),
13352                Scalar::Datetime64(20),
13353                Scalar::Datetime64(10),
13354                Scalar::Datetime64(10),
13355                Scalar::Datetime64(50),
13356            ]
13357        );
13358        assert_eq!(
13359            merged_values(&merged, "lv")?,
13360            &[
13361                Scalar::Int64(0),
13362                Scalar::Int64(1),
13363                Scalar::Int64(1),
13364                Scalar::Int64(2),
13365                Scalar::Int64(3),
13366                Scalar::Int64(3),
13367                Scalar::Int64(4),
13368            ]
13369        );
13370        let right_values = merged_values(&merged, "rv")?;
13371        assert_eq!(right_values.len(), 7);
13372        assert_eq!(right_values[0], Scalar::Float64(101.0));
13373        assert_eq!(
13374            &right_values[1..3],
13375            &[Scalar::Float64(100.0), Scalar::Float64(102.0)]
13376        );
13377        assert!(right_values[3].is_missing());
13378        assert_eq!(
13379            &right_values[4..6],
13380            &[Scalar::Float64(100.0), Scalar::Float64(102.0)]
13381        );
13382        assert!(right_values[6].is_missing());
13383
13384        let nat = fp_types::Timestamp::NAT;
13385        let nat_left = DataFrame::from_dict(
13386            &["key", "lv"],
13387            vec![
13388                (
13389                    "key",
13390                    vec![
13391                        Scalar::Datetime64(nat),
13392                        Scalar::Datetime64(5),
13393                        Scalar::Datetime64(7),
13394                    ],
13395                ),
13396                (
13397                    "lv",
13398                    vec![Scalar::Int64(0), Scalar::Int64(1), Scalar::Int64(2)],
13399                ),
13400            ],
13401        )?;
13402        let nat_right = DataFrame::from_dict(
13403            &["key", "rv"],
13404            vec![
13405                ("key", vec![Scalar::Datetime64(nat), Scalar::Datetime64(5)]),
13406                ("rv", vec![Scalar::Int64(10), Scalar::Int64(11)]),
13407            ],
13408        )?;
13409        assert!(
13410            super::temporal_i64_left_positions(
13411                nat_left.column("key").expect("left NaT key"),
13412                nat_right.column("key").expect("right NaT key")
13413            )
13414            .is_none(),
13415            "NaT must retain the scalar Missing-key fallback"
13416        );
13417        let nat_merged = merge_dataframes_on(&nat_left, &nat_right, &["key"], JoinType::Left)?;
13418        assert_eq!(nat_merged.columns["key"].dtype(), DType::datetime64_naive());
13419        assert_eq!(nat_merged.index.len(), 3);
13420        assert!(merged_values(&nat_merged, "key")?[0].is_missing());
13421        assert_eq!(
13422            &merged_values(&nat_merged, "key")?[1..],
13423            &[Scalar::Datetime64(5), Scalar::Datetime64(7)]
13424        );
13425        let nat_right_values = merged_values(&nat_merged, "rv")?;
13426        assert_eq!(
13427            &nat_right_values[..2],
13428            &[Scalar::Float64(10.0), Scalar::Float64(11.0)]
13429        );
13430        assert!(nat_right_values[2].is_missing());
13431
13432        Ok(())
13433    }
13434
13435    #[test]
13436    fn temporal_i64_right_positions_match_scalar_oracle_and_reject_unsupported_8tf5c() {
13437        let scalar_oracle = |left: &Column, right: &Column| {
13438            let left_keys = super::collect_single_join_keys(left);
13439            let right_keys = super::collect_single_join_keys(right);
13440            right_keys
13441                .iter()
13442                .map(|right_key| left_keys.iter().position(|left_key| left_key == right_key))
13443                .collect::<Vec<_>>()
13444        };
13445
13446        let left_ns = [-20, 10, 30, 50];
13447        let right_ns = [-30, -20, 20, 30, 60];
13448        for temporal in [DType::datetime64_naive(), DType::Timedelta64] {
13449            let scalar = |ns| match &temporal {
13450                DType::Datetime64 { .. } => Scalar::Datetime64(ns),
13451                DType::Timedelta64 => Scalar::Timedelta64(ns),
13452                _ => unreachable!("test iterates only temporal dtypes"),
13453            };
13454            let left = Column::from_values(left_ns.into_iter().map(scalar).collect())
13455                .expect("left temporal key");
13456            let right = Column::from_values(right_ns.into_iter().map(scalar).collect())
13457                .expect("right temporal key");
13458            assert_eq!(
13459                super::ordered_unique_temporal_i64_right_match_positions(&left, &right),
13460                Some(scalar_oracle(&left, &right)),
13461                "raw-nanosecond RIGHT planner must preserve right-major scalar matches for {temporal:?}",
13462            );
13463        }
13464
13465        let empty_left = Column::from_datetime64_values(Vec::new());
13466        let ordered_right = Column::from_datetime64_values(vec![1, 2, 3]);
13467        assert_eq!(
13468            super::ordered_unique_temporal_i64_right_match_positions(&empty_left, &ordered_right,),
13469            Some(vec![None; 3]),
13470        );
13471
13472        let nat = fp_types::Timestamp::NAT;
13473        let nat_left = Column::from_datetime64_values(vec![nat, 1, 2]);
13474        let nat_middle_left = Column::from_datetime64_values(vec![1, nat, 3]);
13475        let nat_tail_right = Column::from_datetime64_values(vec![1, 2, nat]);
13476        let single_nat = Column::from_datetime64_values(vec![nat]);
13477        let duplicate_left = Column::from_datetime64_values(vec![1, 1, 2]);
13478        let late_duplicate_left = Column::from_datetime64_values(vec![1, 2, 3, 3]);
13479        let unsorted_right = Column::from_datetime64_values(vec![2, 1, 3]);
13480        let late_unsorted_right = Column::from_datetime64_values(vec![1, 2, 4, 3]);
13481        let mixed_right =
13482            Column::from_values([1, 2, 3].into_iter().map(Scalar::Timedelta64).collect())
13483                .expect("mixed timedelta key");
13484        let mut validity = ValidityMask::all_valid(3);
13485        validity.set(1, false);
13486        let nullable_left = Column::from_datetime64_values_with_validity(vec![1, 2, 3], validity);
13487        for (left, right) in [
13488            (&nat_left, &ordered_right),
13489            (&nat_middle_left, &ordered_right),
13490            (&ordered_right, &nat_tail_right),
13491            (&single_nat, &ordered_right),
13492            (&duplicate_left, &ordered_right),
13493            (&late_duplicate_left, &ordered_right),
13494            (&ordered_right, &unsorted_right),
13495            (&ordered_right, &late_unsorted_right),
13496            (&ordered_right, &mixed_right),
13497            (&nullable_left, &ordered_right),
13498        ] {
13499            assert!(
13500                super::ordered_unique_temporal_i64_right_match_positions(left, right).is_none(),
13501                "unsupported temporal RIGHT shape must retain the scalar fallback",
13502            );
13503        }
13504    }
13505
13506    #[test]
13507    #[ignore = "foreground performance probe"]
13508    fn bench_temporal_i64_right_validation_fusion_69e0m() {
13509        let n = 400_000_i64;
13510        let input_len = usize::try_from(n).expect("positive benchmark length");
13511        let left = Column::from_datetime64_values_with_validity(
13512            (0..n).collect(),
13513            ValidityMask::all_valid(input_len),
13514        );
13515        let right = Column::from_datetime64_values_with_validity(
13516            (0..n).map(|value| value * 2).collect(),
13517            ValidityMask::all_valid(input_len),
13518        );
13519
13520        // Exact pre-69e0m body: separate NaT and strict-order scans followed
13521        // by the same right-major two-pointer match.
13522        let former = || {
13523            if !left.validity().all() || !right.validity().all() {
13524                return None;
13525            }
13526            let left_raw = left.as_datetime64_slice()?;
13527            let right_raw = right.as_datetime64_slice()?;
13528            let nat = fp_types::Timestamp::NAT;
13529            if left_raw.contains(&nat) || right_raw.contains(&nat) {
13530                return None;
13531            }
13532            if left_raw.windows(2).any(|pair| pair[0] >= pair[1])
13533                || right_raw.windows(2).any(|pair| pair[0] >= pair[1])
13534            {
13535                return None;
13536            }
13537
13538            let mut left_positions = Vec::with_capacity(right_raw.len());
13539            let mut left_idx = 0usize;
13540            for &right_value in right_raw {
13541                while left_idx < left_raw.len() && left_raw[left_idx] < right_value {
13542                    left_idx += 1;
13543                }
13544                left_positions.push(
13545                    (left_idx < left_raw.len()
13546                        && matches!(
13547                            left_raw[left_idx].cmp(&right_value),
13548                            std::cmp::Ordering::Equal
13549                        ))
13550                    .then_some(left_idx),
13551                );
13552            }
13553            Some(left_positions)
13554        };
13555        let candidate = || super::ordered_unique_temporal_i64_right_match_positions(&left, &right);
13556
13557        let former_output = former().expect("former temporal RIGHT positions");
13558        let candidate_output = candidate().expect("fused temporal RIGHT positions");
13559        assert_eq!(candidate_output, former_output);
13560        assert_eq!(candidate_output.len(), input_len);
13561        drop((former_output, candidate_output));
13562        for _ in 0..2 {
13563            std::hint::black_box(former());
13564            std::hint::black_box(candidate());
13565        }
13566
13567        let sample = |plan: &dyn Fn() -> Option<Vec<Option<usize>>>| {
13568            let start = std::time::Instant::now();
13569            let output = std::hint::black_box(plan()).expect("supported temporal RIGHT plan");
13570            assert_eq!(std::hint::black_box(output.len()), input_len);
13571            drop(output);
13572            start.elapsed().as_secs_f64() * 1_000.0
13573        };
13574        let mut former_a = Vec::with_capacity(15);
13575        let mut former_b = Vec::with_capacity(15);
13576        let mut candidate_a = Vec::with_capacity(15);
13577        let mut candidate_b = Vec::with_capacity(15);
13578        for round in 0..15 {
13579            if round % 2 == 0 {
13580                former_a.push(sample(&former));
13581                candidate_a.push(sample(&candidate));
13582                candidate_b.push(sample(&candidate));
13583                former_b.push(sample(&former));
13584            } else {
13585                former_b.push(sample(&former));
13586                candidate_b.push(sample(&candidate));
13587                candidate_a.push(sample(&candidate));
13588                former_a.push(sample(&former));
13589            }
13590        }
13591
13592        let report = |label: &str, mut samples: Vec<f64>| {
13593            samples.sort_by(f64::total_cmp);
13594            let p50 = samples[samples.len() / 2];
13595            let p95_idx = samples
13596                .len()
13597                .saturating_mul(95)
13598                .div_ceil(100)
13599                .saturating_sub(1);
13600            println!(
13601                "{label}: p50={p50:.3} ms p95={:.3} ms max={:.3} ms",
13602                samples[p95_idx],
13603                samples[samples.len() - 1],
13604            );
13605        };
13606        report("right_plan_three_pass_former_a", former_a);
13607        report("right_plan_three_pass_former_b", former_b);
13608        report("right_plan_fused_candidate_a", candidate_a);
13609        report("right_plan_fused_candidate_b", candidate_b);
13610    }
13611
13612    #[test]
13613    fn merge_datetime_right_preserves_dtype_order_and_nat_fallback_8tf5c() -> Result<(), JoinError>
13614    {
13615        let left = DataFrame::from_dict(
13616            &["key", "lv"],
13617            vec![
13618                (
13619                    "key",
13620                    vec![
13621                        Scalar::Datetime64(10),
13622                        Scalar::Datetime64(30),
13623                        Scalar::Datetime64(50),
13624                    ],
13625                ),
13626                (
13627                    "lv",
13628                    vec![Scalar::Int64(0), Scalar::Int64(1), Scalar::Int64(2)],
13629                ),
13630            ],
13631        )?;
13632        let right = DataFrame::from_dict(
13633            &["key", "rv"],
13634            vec![
13635                (
13636                    "key",
13637                    vec![
13638                        Scalar::Datetime64(0),
13639                        Scalar::Datetime64(10),
13640                        Scalar::Datetime64(40),
13641                        Scalar::Datetime64(50),
13642                        Scalar::Datetime64(60),
13643                    ],
13644                ),
13645                (
13646                    "rv",
13647                    vec![
13648                        Scalar::Int64(100),
13649                        Scalar::Int64(101),
13650                        Scalar::Int64(102),
13651                        Scalar::Int64(103),
13652                        Scalar::Int64(104),
13653                    ],
13654                ),
13655            ],
13656        )?;
13657        let merged = merge_dataframes_on(&left, &right, &["key"], JoinType::Right)?;
13658        assert_eq!(merged.columns["key"].dtype(), DType::datetime64_naive());
13659        assert_eq!(
13660            merged_values(&merged, "key")?,
13661            &[
13662                Scalar::Datetime64(0),
13663                Scalar::Datetime64(10),
13664                Scalar::Datetime64(40),
13665                Scalar::Datetime64(50),
13666                Scalar::Datetime64(60),
13667            ],
13668        );
13669        assert_eq!(
13670            merged_values(&merged, "rv")?,
13671            &[
13672                Scalar::Int64(100),
13673                Scalar::Int64(101),
13674                Scalar::Int64(102),
13675                Scalar::Int64(103),
13676                Scalar::Int64(104),
13677            ],
13678        );
13679        let left_values = merged_values(&merged, "lv")?;
13680        assert_eq!(left_values.len(), 5);
13681        assert!(left_values[0].is_missing());
13682        assert_eq!(left_values[1], Scalar::Float64(0.0));
13683        assert!(left_values[2].is_missing());
13684        assert_eq!(left_values[3], Scalar::Float64(2.0));
13685        assert!(left_values[4].is_missing());
13686
13687        let nat = fp_types::Timestamp::NAT;
13688        let nat_left = DataFrame::from_dict(
13689            &["key", "lv"],
13690            vec![
13691                ("key", vec![Scalar::Datetime64(nat), Scalar::Datetime64(5)]),
13692                ("lv", vec![Scalar::Int64(0), Scalar::Int64(1)]),
13693            ],
13694        )?;
13695        let nat_right = DataFrame::from_dict(
13696            &["key", "rv"],
13697            vec![
13698                (
13699                    "key",
13700                    vec![
13701                        Scalar::Datetime64(nat),
13702                        Scalar::Datetime64(5),
13703                        Scalar::Datetime64(7),
13704                    ],
13705                ),
13706                (
13707                    "rv",
13708                    vec![Scalar::Int64(10), Scalar::Int64(11), Scalar::Int64(12)],
13709                ),
13710            ],
13711        )?;
13712        assert!(
13713            super::ordered_unique_temporal_i64_right_match_positions(
13714                nat_left.column("key").expect("left NaT key"),
13715                nat_right.column("key").expect("right NaT key"),
13716            )
13717            .is_none(),
13718            "NaT must retain the scalar Missing-key fallback",
13719        );
13720        let nat_merged = merge_dataframes_on(&nat_left, &nat_right, &["key"], JoinType::Right)?;
13721        assert_eq!(nat_merged.columns["key"].dtype(), DType::datetime64_naive());
13722        assert_eq!(nat_merged.index.len(), 3);
13723        assert!(merged_values(&nat_merged, "key")?[0].is_missing());
13724        assert_eq!(
13725            &merged_values(&nat_merged, "key")?[1..],
13726            &[Scalar::Datetime64(5), Scalar::Datetime64(7)],
13727        );
13728        let nat_left_values = merged_values(&nat_merged, "lv")?;
13729        assert_eq!(
13730            &nat_left_values[..2],
13731            &[Scalar::Float64(0.0), Scalar::Float64(1.0)]
13732        );
13733        assert!(nat_left_values[2].is_missing());
13734
13735        Ok(())
13736    }
13737
13738    #[test]
13739    fn temporal_i64_outer_key_coalesce_matches_scalar_and_declines_unsupported_i4gzc() {
13740        let left_positions = [None, Some(0), Some(1), None, Some(2), Some(3), None];
13741        let right_positions = [Some(0), Some(1), None, Some(2), Some(3), None, Some(4)];
13742        let left_ns = vec![-20, 10, 30, 50];
13743        let right_ns = vec![-30, -20, 20, 30, 60];
13744        let union_ns = [-30, -20, 10, 20, 30, 50, 60];
13745        let temporal_column = |dtype: &DType, values: Vec<i64>| {
13746            let len = values.len();
13747            match dtype {
13748                DType::Datetime64 { .. } => Column::from_datetime64_values_with_validity(
13749                    values,
13750                    ValidityMask::all_valid(len),
13751                ),
13752                DType::Timedelta64 => Column::from_timedelta64_values_with_validity(
13753                    values,
13754                    ValidityMask::all_valid(len),
13755                ),
13756                _ => unreachable!("test iterates only temporal dtypes"),
13757            }
13758        };
13759
13760        for temporal in [DType::datetime64_naive(), DType::Timedelta64] {
13761            let left = temporal_column(&temporal, left_ns.clone());
13762            let right = temporal_column(&temporal, right_ns.clone());
13763            let candidate = super::coalesce_temporal_i64_key_column(
13764                &left,
13765                &right,
13766                &left_positions,
13767                &right_positions,
13768            )
13769            .expect("supported temporal key coalesce");
13770            assert_eq!(candidate.dtype(), temporal);
13771            assert!(candidate.validity().all());
13772            let candidate_ns = match &temporal {
13773                DType::Datetime64 { .. } => candidate.as_datetime64_slice(),
13774                DType::Timedelta64 => candidate.as_timedelta64_slice(),
13775                _ => unreachable!("test iterates only temporal dtypes"),
13776            };
13777            assert_eq!(candidate_ns, Some(union_ns.as_slice()));
13778
13779            let reference_values = left_positions
13780                .iter()
13781                .zip(right_positions.iter())
13782                .map(|(left_pos, right_pos)| match (left_pos, right_pos) {
13783                    (Some(pos), _) => left.values()[*pos].clone(),
13784                    (None, Some(pos)) => right.values()[*pos].clone(),
13785                    (None, None) => Scalar::Null(NullKind::Null),
13786                })
13787                .collect::<Vec<_>>();
13788            let reference = Column::from_values(reference_values).expect("scalar reference");
13789            assert_eq!(candidate, reference);
13790        }
13791
13792        let naive_datetime = DType::datetime64_naive();
13793        let datetime_left = temporal_column(&naive_datetime, left_ns);
13794        let datetime_right = temporal_column(&naive_datetime, right_ns);
13795        let timedelta_right = temporal_column(&DType::Timedelta64, vec![-30, -20, 20, 30, 60]);
13796        let mut nullable_validity = ValidityMask::all_valid(datetime_left.len());
13797        nullable_validity.set(1, false);
13798        let nullable_left =
13799            Column::from_datetime64_values_with_validity(vec![-20, 10, 30, 50], nullable_validity);
13800        let nat_left = Column::from_datetime64_values_with_validity(
13801            vec![fp_types::Timestamp::NAT, 10, 30, 50],
13802            ValidityMask::all_valid(4),
13803        );
13804        for (left, right, left_tape, right_tape) in [
13805            (
13806                &nullable_left,
13807                &datetime_right,
13808                left_positions.as_slice(),
13809                right_positions.as_slice(),
13810            ),
13811            (
13812                &datetime_left,
13813                &timedelta_right,
13814                left_positions.as_slice(),
13815                right_positions.as_slice(),
13816            ),
13817            (&nat_left, &datetime_right, &[Some(0)], &[Some(0)]),
13818            (&datetime_left, &datetime_right, &[Some(0)], &[]),
13819            (&datetime_left, &datetime_right, &[Some(99)], &[None]),
13820            (&datetime_left, &datetime_right, &[None], &[None]),
13821        ] {
13822            assert!(
13823                super::coalesce_temporal_i64_key_column(left, right, left_tape, right_tape,)
13824                    .is_none(),
13825                "unsupported temporal key coalesce must retain Scalar fallback",
13826            );
13827        }
13828    }
13829
13830    #[test]
13831    #[ignore = "foreground performance probe"]
13832    fn bench_temporal_i64_outer_key_coalesce_i4gzc() {
13833        let n = 200_000_i64;
13834        let input_len = usize::try_from(n).expect("positive benchmark length");
13835        let left = Column::from_datetime64_values_with_validity(
13836            (0..n).collect(),
13837            ValidityMask::all_valid(input_len),
13838        );
13839        let right = Column::from_datetime64_values_with_validity(
13840            (0..n).map(|value| value * 2).collect(),
13841            ValidityMask::all_valid(input_len),
13842        );
13843        let (left_positions, right_positions) =
13844            super::ordered_unique_temporal_i64_outer_positions(&left, &right)
13845                .expect("ordered temporal position tapes");
13846        let expected_rows = 300_000usize;
13847        assert_eq!(left_positions.len(), expected_rows);
13848
13849        let former = || {
13850            let values = left_positions
13851                .iter()
13852                .zip(right_positions.iter())
13853                .map(|(left_pos, right_pos)| match (left_pos, right_pos) {
13854                    (Some(pos), _) => left.values()[*pos].clone(),
13855                    (None, Some(pos)) => right.values()[*pos].clone(),
13856                    (None, None) => Scalar::Null(NullKind::Null),
13857                })
13858                .collect::<Vec<_>>();
13859            Column::from_values(values).expect("former Scalar key coalesce")
13860        };
13861        let candidate = || {
13862            super::coalesce_temporal_i64_key_column(
13863                &left,
13864                &right,
13865                &left_positions,
13866                &right_positions,
13867            )
13868            .expect("typed temporal key coalesce")
13869        };
13870
13871        let former_output = former();
13872        let candidate_output = candidate();
13873        assert_eq!(candidate_output, former_output);
13874        drop((former_output, candidate_output));
13875        for _ in 0..2 {
13876            std::hint::black_box(former());
13877            std::hint::black_box(candidate());
13878        }
13879
13880        let sample = |build: &dyn Fn() -> Column| {
13881            let start = std::time::Instant::now();
13882            let output = std::hint::black_box(build());
13883            assert_eq!(std::hint::black_box(output.len()), expected_rows);
13884            drop(output);
13885            start.elapsed().as_secs_f64() * 1_000.0
13886        };
13887        let mut former_a = Vec::with_capacity(15);
13888        let mut former_b = Vec::with_capacity(15);
13889        let mut candidate_a = Vec::with_capacity(15);
13890        let mut candidate_b = Vec::with_capacity(15);
13891        for round in 0..15 {
13892            if round % 2 == 0 {
13893                former_a.push(sample(&former));
13894                candidate_a.push(sample(&candidate));
13895                candidate_b.push(sample(&candidate));
13896                former_b.push(sample(&former));
13897            } else {
13898                former_b.push(sample(&former));
13899                candidate_b.push(sample(&candidate));
13900                candidate_a.push(sample(&candidate));
13901                former_a.push(sample(&former));
13902            }
13903        }
13904
13905        let report = |label: &str, mut samples: Vec<f64>| {
13906            samples.sort_by(f64::total_cmp);
13907            let p50 = samples[samples.len() / 2];
13908            let p95_idx = samples
13909                .len()
13910                .saturating_mul(95)
13911                .div_ceil(100)
13912                .saturating_sub(1);
13913            println!(
13914                "{label}: p50={p50:.3} ms p95={:.3} ms max={:.3} ms",
13915                samples[p95_idx],
13916                samples[samples.len() - 1],
13917            );
13918        };
13919        report("outer_key_scalar_former_a", former_a);
13920        report("outer_key_scalar_former_b", former_b);
13921        report("outer_key_typed_candidate_a", candidate_a);
13922        report("outer_key_typed_candidate_b", candidate_b);
13923    }
13924
13925    #[test]
13926    fn temporal_i64_outer_positions_match_ordered_union_and_reject_unsupported_rvb6u() {
13927        let left_ns = [-20, 10, 30, 50];
13928        let right_ns = [-30, -20, 20, 30, 60];
13929        let expected = (
13930            vec![None, Some(0), Some(1), None, Some(2), Some(3), None],
13931            vec![Some(0), Some(1), None, Some(2), Some(3), None, Some(4)],
13932        );
13933        for temporal in [DType::datetime64_naive(), DType::Timedelta64] {
13934            let scalar = |ns| match &temporal {
13935                DType::Datetime64 { .. } => Scalar::Datetime64(ns),
13936                DType::Timedelta64 => Scalar::Timedelta64(ns),
13937                _ => unreachable!("test iterates only temporal dtypes"),
13938            };
13939            let left = Column::from_values(left_ns.into_iter().map(scalar).collect())
13940                .expect("left temporal key");
13941            let right = Column::from_values(right_ns.into_iter().map(scalar).collect())
13942                .expect("right temporal key");
13943            assert_eq!(
13944                super::ordered_unique_temporal_i64_outer_positions(&left, &right),
13945                Some(expected.clone()),
13946                "raw-nanosecond OUTER planner must preserve key-sorted optional positions for {temporal:?}",
13947            );
13948        }
13949
13950        let empty_left = Column::from_datetime64_values(Vec::new());
13951        let ordered_right = Column::from_datetime64_values(vec![1, 2, 3]);
13952        assert_eq!(
13953            super::ordered_unique_temporal_i64_outer_positions(&empty_left, &ordered_right),
13954            Some((vec![None; 3], vec![Some(0), Some(1), Some(2)])),
13955        );
13956
13957        let nat = fp_types::Timestamp::NAT;
13958        let nat_left = Column::from_datetime64_values(vec![nat, 1, 2]);
13959        let duplicate_left = Column::from_datetime64_values(vec![1, 1, 2]);
13960        let unsorted_right = Column::from_datetime64_values(vec![2, 1, 3]);
13961        let mixed_right =
13962            Column::from_values([1, 2, 3].into_iter().map(Scalar::Timedelta64).collect())
13963                .expect("mixed timedelta key");
13964        let mut validity = ValidityMask::all_valid(3);
13965        validity.set(1, false);
13966        let nullable_left = Column::from_datetime64_values_with_validity(vec![1, 2, 3], validity);
13967        for (left, right) in [
13968            (&nat_left, &ordered_right),
13969            (&duplicate_left, &ordered_right),
13970            (&ordered_right, &unsorted_right),
13971            (&ordered_right, &mixed_right),
13972            (&nullable_left, &ordered_right),
13973        ] {
13974            assert!(
13975                super::ordered_unique_temporal_i64_outer_positions(left, right).is_none(),
13976                "unsupported temporal OUTER shape must retain the scalar fallback",
13977            );
13978        }
13979    }
13980
13981    #[test]
13982    #[ignore = "foreground performance probe"]
13983    fn bench_temporal_i64_outer_validation_fusion_pizud() {
13984        let n = 400_000_i64;
13985        let input_len = usize::try_from(n).expect("positive benchmark length");
13986        let left = Column::from_datetime64_values_with_validity(
13987            (0..n).collect(),
13988            ValidityMask::all_valid(input_len),
13989        );
13990        let right = Column::from_datetime64_values_with_validity(
13991            (0..n).map(|value| value * 2).collect(),
13992            ValidityMask::all_valid(input_len),
13993        );
13994        let expected_rows = 600_000usize;
13995
13996        // Exact pre-pizud body: separate NaT and strict-order scans followed by
13997        // the same three-way optional-position union.
13998        let former = || {
13999            if !left.validity().all() || !right.validity().all() {
14000                return None;
14001            }
14002            let left_raw = left.as_datetime64_slice()?;
14003            let right_raw = right.as_datetime64_slice()?;
14004            let nat = fp_types::Timestamp::NAT;
14005            if left_raw.contains(&nat) || right_raw.contains(&nat) {
14006                return None;
14007            }
14008            if left_raw.windows(2).any(|pair| pair[0] >= pair[1])
14009                || right_raw.windows(2).any(|pair| pair[0] >= pair[1])
14010            {
14011                return None;
14012            }
14013
14014            let capacity = left_raw.len().saturating_add(right_raw.len());
14015            let mut left_positions = Vec::<Option<usize>>::with_capacity(capacity);
14016            let mut right_positions = Vec::<Option<usize>>::with_capacity(capacity);
14017            let (mut left_idx, mut right_idx) = (0usize, 0usize);
14018            while left_idx < left_raw.len() && right_idx < right_raw.len() {
14019                match left_raw[left_idx].cmp(&right_raw[right_idx]) {
14020                    std::cmp::Ordering::Equal => {
14021                        left_positions.push(Some(left_idx));
14022                        right_positions.push(Some(right_idx));
14023                        left_idx += 1;
14024                        right_idx += 1;
14025                    }
14026                    std::cmp::Ordering::Less => {
14027                        left_positions.push(Some(left_idx));
14028                        right_positions.push(None);
14029                        left_idx += 1;
14030                    }
14031                    std::cmp::Ordering::Greater => {
14032                        left_positions.push(None);
14033                        right_positions.push(Some(right_idx));
14034                        right_idx += 1;
14035                    }
14036                }
14037            }
14038            while left_idx < left_raw.len() {
14039                left_positions.push(Some(left_idx));
14040                right_positions.push(None);
14041                left_idx += 1;
14042            }
14043            while right_idx < right_raw.len() {
14044                left_positions.push(None);
14045                right_positions.push(Some(right_idx));
14046                right_idx += 1;
14047            }
14048            Some((left_positions, right_positions))
14049        };
14050        let candidate = || super::ordered_unique_temporal_i64_outer_positions(&left, &right);
14051
14052        let former_output = former().expect("former temporal union");
14053        let candidate_output = candidate().expect("fused temporal union");
14054        assert_eq!(candidate_output, former_output);
14055        assert_eq!(candidate_output.0.len(), expected_rows);
14056        drop((former_output, candidate_output));
14057        for _ in 0..2 {
14058            std::hint::black_box(former());
14059            std::hint::black_box(candidate());
14060        }
14061
14062        let sample = |plan: &dyn Fn() -> Option<super::OptionalJoinPositions>| {
14063            let start = std::time::Instant::now();
14064            let output = std::hint::black_box(plan()).expect("supported temporal union");
14065            assert_eq!(std::hint::black_box(output.0.len()), expected_rows);
14066            drop(output);
14067            start.elapsed().as_secs_f64() * 1_000.0
14068        };
14069        let mut former_a = Vec::with_capacity(15);
14070        let mut former_b = Vec::with_capacity(15);
14071        let mut candidate_a = Vec::with_capacity(15);
14072        let mut candidate_b = Vec::with_capacity(15);
14073        for round in 0..15 {
14074            if round % 2 == 0 {
14075                former_a.push(sample(&former));
14076                candidate_a.push(sample(&candidate));
14077                candidate_b.push(sample(&candidate));
14078                former_b.push(sample(&former));
14079            } else {
14080                former_b.push(sample(&former));
14081                candidate_b.push(sample(&candidate));
14082                candidate_a.push(sample(&candidate));
14083                former_a.push(sample(&former));
14084            }
14085        }
14086
14087        let report = |label: &str, mut samples: Vec<f64>| {
14088            samples.sort_by(f64::total_cmp);
14089            let p50 = samples[samples.len() / 2];
14090            let p95_idx = samples
14091                .len()
14092                .saturating_mul(95)
14093                .div_ceil(100)
14094                .saturating_sub(1);
14095            println!(
14096                "{label}: p50={p50:.3} ms p95={:.3} ms max={:.3} ms",
14097                samples[p95_idx],
14098                samples[samples.len() - 1],
14099            );
14100        };
14101        report("outer_plan_three_pass_former_a", former_a);
14102        report("outer_plan_three_pass_former_b", former_b);
14103        report("outer_plan_fused_candidate_a", candidate_a);
14104        report("outer_plan_fused_candidate_b", candidate_b);
14105    }
14106
14107    #[test]
14108    fn merge_temporal_outer_matches_generic_dtype_order_and_null_fill_rvb6u()
14109    -> Result<(), JoinError> {
14110        let left_ns = [-20, 10, 30, 50];
14111        let right_ns = [-30, -20, 20, 30, 60];
14112        let union_ns = [-30, -20, 10, 20, 30, 50, 60];
14113        for temporal in [DType::datetime64_naive(), DType::Timedelta64] {
14114            let scalar = |ns| match &temporal {
14115                DType::Datetime64 { .. } => Scalar::Datetime64(ns),
14116                DType::Timedelta64 => Scalar::Timedelta64(ns),
14117                _ => unreachable!("test iterates only temporal dtypes"),
14118            };
14119            let left = DataFrame::from_dict(
14120                &["key", "lv"],
14121                vec![
14122                    ("key", left_ns.into_iter().map(scalar).collect()),
14123                    (
14124                        "lv",
14125                        vec![
14126                            Scalar::Int64(100),
14127                            Scalar::Int64(101),
14128                            Scalar::Int64(102),
14129                            Scalar::Int64(103),
14130                        ],
14131                    ),
14132                ],
14133            )?;
14134            let right = DataFrame::from_dict(
14135                &["key", "rv"],
14136                vec![
14137                    ("key", right_ns.into_iter().map(scalar).collect()),
14138                    (
14139                        "rv",
14140                        vec![
14141                            Scalar::Int64(200),
14142                            Scalar::Int64(201),
14143                            Scalar::Int64(202),
14144                            Scalar::Int64(203),
14145                            Scalar::Int64(204),
14146                        ],
14147                    ),
14148                ],
14149            )?;
14150            let candidate = merge_dataframes_on(&left, &right, &["key"], JoinType::Outer)?;
14151            let generic = merge_dataframes_on_with_options(
14152                &left,
14153                &right,
14154                &["key"],
14155                &["key"],
14156                JoinType::Outer,
14157                MergeExecutionOptions {
14158                    sort: true,
14159                    ..MergeExecutionOptions::default()
14160                },
14161            )?;
14162            assert_eq!(candidate, generic, "{temporal:?} OUTER output parity");
14163            assert_eq!(candidate.columns["key"].dtype(), temporal);
14164            assert_eq!(
14165                merged_values(&candidate, "key")?,
14166                union_ns
14167                    .into_iter()
14168                    .map(scalar)
14169                    .collect::<Vec<_>>()
14170                    .as_slice(),
14171            );
14172
14173            let left_values = merged_values(&candidate, "lv")?;
14174            assert!(left_values[0].is_missing());
14175            assert_eq!(left_values[1], Scalar::Float64(100.0));
14176            assert_eq!(left_values[2], Scalar::Float64(101.0));
14177            assert!(left_values[3].is_missing());
14178            assert_eq!(left_values[4], Scalar::Float64(102.0));
14179            assert_eq!(left_values[5], Scalar::Float64(103.0));
14180            assert!(left_values[6].is_missing());
14181
14182            let right_values = merged_values(&candidate, "rv")?;
14183            assert_eq!(right_values[0], Scalar::Float64(200.0));
14184            assert_eq!(right_values[1], Scalar::Float64(201.0));
14185            assert!(right_values[2].is_missing());
14186            assert_eq!(right_values[3], Scalar::Float64(202.0));
14187            assert_eq!(right_values[4], Scalar::Float64(203.0));
14188            assert!(right_values[5].is_missing());
14189            assert_eq!(right_values[6], Scalar::Float64(204.0));
14190        }
14191
14192        let nat = fp_types::Timestamp::NAT;
14193        let nat_left = DataFrame::from_dict(
14194            &["key", "lv"],
14195            vec![
14196                ("key", vec![Scalar::Datetime64(nat), Scalar::Datetime64(5)]),
14197                ("lv", vec![Scalar::Int64(0), Scalar::Int64(1)]),
14198            ],
14199        )?;
14200        let nat_right = DataFrame::from_dict(
14201            &["key", "rv"],
14202            vec![
14203                (
14204                    "key",
14205                    vec![
14206                        Scalar::Datetime64(nat),
14207                        Scalar::Datetime64(5),
14208                        Scalar::Datetime64(7),
14209                    ],
14210                ),
14211                (
14212                    "rv",
14213                    vec![Scalar::Int64(10), Scalar::Int64(11), Scalar::Int64(12)],
14214                ),
14215            ],
14216        )?;
14217        assert!(
14218            super::ordered_unique_temporal_i64_outer_positions(
14219                nat_left.column("key").expect("left NaT key"),
14220                nat_right.column("key").expect("right NaT key"),
14221            )
14222            .is_none(),
14223            "NaT must retain the scalar Missing-key fallback",
14224        );
14225        let nat_candidate = merge_dataframes_on(&nat_left, &nat_right, &["key"], JoinType::Outer)?;
14226        let nat_generic = merge_dataframes_on_with_options(
14227            &nat_left,
14228            &nat_right,
14229            &["key"],
14230            &["key"],
14231            JoinType::Outer,
14232            MergeExecutionOptions {
14233                sort: true,
14234                ..MergeExecutionOptions::default()
14235            },
14236        )?;
14237        assert_eq!(nat_candidate, nat_generic);
14238        assert_eq!(
14239            nat_candidate.columns["key"].dtype(),
14240            DType::datetime64_naive()
14241        );
14242        assert!(
14243            merged_values(&nat_candidate, "key")?
14244                .iter()
14245                .any(Scalar::is_missing),
14246        );
14247
14248        Ok(())
14249    }
14250
14251    #[test]
14252    fn merge_composite_datetime_component_is_honored_not_missing_j0in7() -> Result<(), JoinError> {
14253        // A COMPOSITE join key [Utf8, Datetime64] declines the single-key temporal
14254        // fast path (`temporal_i64_inner_positions`) and routes through the generic
14255        // Scalar/`scalar_to_key_component` path. The Datetime64 (and Timedelta64)
14256        // component must map to a Present key by value — NOT collapse to `Missing`.
14257        // If it collapsed to Missing, rows sharing the Utf8 component would match
14258        // regardless of timestamp (Missing == Missing), over-matching. Left has two
14259        // "a" rows at ts=10/20; right has "a" at ts=10/99. Honoring the datetime,
14260        // the only equal composite keys are ("a",10) and ("b",10) => exactly 2 rows.
14261        // Under the old Missing-collapse this would be 5 rows.
14262        let left = DataFrame::from_dict(
14263            &["region", "ts", "lv"],
14264            vec![
14265                (
14266                    "region",
14267                    vec![
14268                        Scalar::Utf8("a".to_owned()),
14269                        Scalar::Utf8("a".to_owned()),
14270                        Scalar::Utf8("b".to_owned()),
14271                    ],
14272                ),
14273                (
14274                    "ts",
14275                    vec![
14276                        Scalar::Datetime64(10),
14277                        Scalar::Datetime64(20),
14278                        Scalar::Datetime64(10),
14279                    ],
14280                ),
14281                (
14282                    "lv",
14283                    vec![Scalar::Int64(0), Scalar::Int64(1), Scalar::Int64(2)],
14284                ),
14285            ],
14286        )?;
14287        let right = DataFrame::from_dict(
14288            &["region", "ts", "rv"],
14289            vec![
14290                (
14291                    "region",
14292                    vec![
14293                        Scalar::Utf8("a".to_owned()),
14294                        Scalar::Utf8("a".to_owned()),
14295                        Scalar::Utf8("b".to_owned()),
14296                    ],
14297                ),
14298                (
14299                    "ts",
14300                    vec![
14301                        Scalar::Datetime64(10),
14302                        Scalar::Datetime64(99),
14303                        Scalar::Datetime64(10),
14304                    ],
14305                ),
14306                (
14307                    "rv",
14308                    vec![Scalar::Int64(100), Scalar::Int64(101), Scalar::Int64(102)],
14309                ),
14310            ],
14311        )?;
14312        let merged = merge_dataframes_on(&left, &right, &["region", "ts"], JoinType::Inner)?;
14313        assert_eq!(
14314            merged.index.len(),
14315            2,
14316            "datetime composite component must discriminate, not collapse to Missing"
14317        );
14318        assert_eq!(merged.columns["ts"].dtype(), DType::datetime64_naive());
14319        // Pair (lv, rv) up per output row, order-independently.
14320        let mut pairs: Vec<(i64, i64)> = merged_values(&merged, "lv")?
14321            .iter()
14322            .zip(merged_values(&merged, "rv")?)
14323            .map(|(l, r)| match (l, r) {
14324                (Scalar::Int64(a), Scalar::Int64(b)) => (*a, *b),
14325                _ => panic!("unexpected non-Int64 value column"),
14326            })
14327            .collect();
14328        pairs.sort_unstable();
14329        assert_eq!(pairs, vec![(0, 100), (2, 102)]);
14330
14331        // The Timedelta64 sibling arm must behave identically.
14332        let ltd = DataFrame::from_dict(
14333            &["region", "td", "lv"],
14334            vec![
14335                (
14336                    "region",
14337                    vec![Scalar::Utf8("a".to_owned()), Scalar::Utf8("a".to_owned())],
14338                ),
14339                ("td", vec![Scalar::Timedelta64(10), Scalar::Timedelta64(20)]),
14340                ("lv", vec![Scalar::Int64(0), Scalar::Int64(1)]),
14341            ],
14342        )?;
14343        let rtd = DataFrame::from_dict(
14344            &["region", "td", "rv"],
14345            vec![
14346                (
14347                    "region",
14348                    vec![Scalar::Utf8("a".to_owned()), Scalar::Utf8("a".to_owned())],
14349                ),
14350                ("td", vec![Scalar::Timedelta64(10), Scalar::Timedelta64(99)]),
14351                ("rv", vec![Scalar::Int64(100), Scalar::Int64(101)]),
14352            ],
14353        )?;
14354        let merged_td = merge_dataframes_on(&ltd, &rtd, &["region", "td"], JoinType::Inner)?;
14355        assert_eq!(
14356            merged_td.index.len(),
14357            1,
14358            "timedelta composite component must discriminate, not collapse to Missing"
14359        );
14360        assert_eq!(merged_values(&merged_td, "lv")?, &[Scalar::Int64(0)]);
14361        assert_eq!(merged_values(&merged_td, "rv")?, &[Scalar::Int64(100)]);
14362
14363        Ok(())
14364    }
14365
14366    fn merged_values_where_indicator(
14367        merged: &MergedDataFrame,
14368        column_name: &str,
14369        indicator_name: &str,
14370        indicator_value: &str,
14371    ) -> Result<Vec<Scalar>, JoinError> {
14372        let values = merged_values(merged, column_name)?;
14373        let indicators = merged_values(merged, indicator_name)?;
14374        Ok(values
14375            .iter()
14376            .zip(indicators.iter())
14377            .filter_map(|(value, indicator)| {
14378                if matches!(indicator, Scalar::Utf8(v) if v == indicator_value) {
14379                    Some(value.clone())
14380                } else {
14381                    None
14382                }
14383            })
14384            .collect())
14385    }
14386
14387    #[test]
14388    fn merge_inner_basic() {
14389        let left = make_left_df();
14390        let right = make_right_df();
14391        let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
14392
14393        assert_eq!(merged.columns.get("id").unwrap().len(), 2);
14394        assert_eq!(
14395            merged.columns.get("id").unwrap().values(),
14396            &[Scalar::Int64(2), Scalar::Int64(3)]
14397        );
14398        assert_eq!(
14399            merged.columns.get("val_a").unwrap().values(),
14400            &[Scalar::Int64(20), Scalar::Int64(30)]
14401        );
14402        assert_eq!(
14403            merged.columns.get("val_b").unwrap().values(),
14404            &[Scalar::Int64(200), Scalar::Int64(300)]
14405        );
14406    }
14407
14408    #[test]
14409    fn merge_inner_single_key_preserves_duplicate_probe_order() {
14410        let left = DataFrame::from_dict(
14411            &["id", "left_value"],
14412            vec![
14413                (
14414                    "id",
14415                    vec![Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(2)],
14416                ),
14417                (
14418                    "left_value",
14419                    vec![Scalar::Int64(20), Scalar::Int64(10), Scalar::Int64(21)],
14420                ),
14421            ],
14422        )
14423        .unwrap();
14424        let right = DataFrame::from_dict(
14425            &["id", "right_value"],
14426            vec![
14427                (
14428                    "id",
14429                    vec![Scalar::Int64(2), Scalar::Int64(2), Scalar::Int64(1)],
14430                ),
14431                (
14432                    "right_value",
14433                    vec![Scalar::Int64(200), Scalar::Int64(201), Scalar::Int64(100)],
14434                ),
14435            ],
14436        )
14437        .unwrap();
14438
14439        let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
14440
14441        assert_eq!(
14442            merged.columns.get("id").unwrap().values(),
14443            &[
14444                Scalar::Int64(2),
14445                Scalar::Int64(2),
14446                Scalar::Int64(1),
14447                Scalar::Int64(2),
14448                Scalar::Int64(2),
14449            ]
14450        );
14451        assert_eq!(
14452            merged.columns.get("left_value").unwrap().values(),
14453            &[
14454                Scalar::Int64(20),
14455                Scalar::Int64(20),
14456                Scalar::Int64(10),
14457                Scalar::Int64(21),
14458                Scalar::Int64(21),
14459            ]
14460        );
14461        assert_eq!(
14462            merged.columns.get("right_value").unwrap().values(),
14463            &[
14464                Scalar::Int64(200),
14465                Scalar::Int64(201),
14466                Scalar::Int64(100),
14467                Scalar::Int64(200),
14468                Scalar::Int64(201),
14469            ]
14470        );
14471    }
14472
14473    #[test]
14474    fn merge_inner_wide_sparse_int64_hash_matches_generic_validated_route() {
14475        let stride = 1_i64 << 30;
14476        let left = DataFrame::from_dict(
14477            &["id", "left_value"],
14478            vec![
14479                (
14480                    "id",
14481                    vec![3, 1, 3, 0, 2]
14482                        .into_iter()
14483                        .map(|v| Scalar::Int64(v * stride))
14484                        .collect(),
14485                ),
14486                (
14487                    "left_value",
14488                    vec![
14489                        Scalar::Int64(10),
14490                        Scalar::Int64(11),
14491                        Scalar::Int64(12),
14492                        Scalar::Int64(13),
14493                        Scalar::Int64(14),
14494                    ],
14495                ),
14496            ],
14497        )
14498        .unwrap();
14499        let right = DataFrame::from_dict(
14500            &["id", "right_value"],
14501            vec![
14502                (
14503                    "id",
14504                    vec![3, 2, 3, 1]
14505                        .into_iter()
14506                        .map(|v| Scalar::Int64(v * stride))
14507                        .collect(),
14508                ),
14509                (
14510                    "right_value",
14511                    vec![
14512                        Scalar::Int64(100),
14513                        Scalar::Int64(101),
14514                        Scalar::Int64(102),
14515                        Scalar::Int64(103),
14516                    ],
14517                ),
14518            ],
14519        )
14520        .unwrap();
14521
14522        let fast = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
14523        let generic = merge_dataframes_on_with_options(
14524            &left,
14525            &right,
14526            &["id"],
14527            &["id"],
14528            JoinType::Inner,
14529            MergeExecutionOptions {
14530                validate_mode: Some(MergeValidateMode::ManyToMany),
14531                ..MergeExecutionOptions::default()
14532            },
14533        )
14534        .unwrap();
14535
14536        assert_eq!(fast.index, generic.index);
14537        assert_eq!(fast.column_order, generic.column_order);
14538        assert_eq!(fast.columns, generic.columns);
14539        assert_eq!(
14540            fast.columns.get("id").unwrap().values(),
14541            &[
14542                Scalar::Int64(3 * stride),
14543                Scalar::Int64(3 * stride),
14544                Scalar::Int64(stride),
14545                Scalar::Int64(3 * stride),
14546                Scalar::Int64(3 * stride),
14547                Scalar::Int64(2 * stride),
14548            ]
14549        );
14550        assert_eq!(
14551            fast.columns.get("left_value").unwrap().values(),
14552            &[
14553                Scalar::Int64(10),
14554                Scalar::Int64(10),
14555                Scalar::Int64(11),
14556                Scalar::Int64(12),
14557                Scalar::Int64(12),
14558                Scalar::Int64(14),
14559            ]
14560        );
14561        assert_eq!(
14562            fast.columns.get("right_value").unwrap().values(),
14563            &[
14564                Scalar::Int64(100),
14565                Scalar::Int64(102),
14566                Scalar::Int64(103),
14567                Scalar::Int64(100),
14568                Scalar::Int64(102),
14569                Scalar::Int64(101),
14570            ]
14571        );
14572    }
14573
14574    #[test]
14575    fn dense_i64_inner_parallel_output_data_preserves_row_major_order() {
14576        let left_keys = vec![-1, 2, 1, 2, 3, 9];
14577        let min = 1;
14578        let max = 3;
14579        let offsets = vec![0, 2, 3, 5];
14580        let positions = vec![1usize, 4, 0, 2, 3];
14581        let left_values = vec![10, 20, 30, 40, 50, 60];
14582        let right_values = vec![100, 101, 102, 103, 104];
14583        let specs = vec![
14584            FusedInt64OutputColumn {
14585                name: "left".to_string(),
14586                side: FusedInt64Side::Left,
14587                values: &left_values,
14588            },
14589            FusedInt64OutputColumn {
14590                name: "right".to_string(),
14591                side: FusedInt64Side::Right,
14592                values: &right_values,
14593            },
14594        ];
14595
14596        let plan = DenseI64InnerOutputPlan {
14597            left_keys: &left_keys,
14598            min,
14599            max,
14600            offsets: &offsets,
14601            positions: &positions,
14602            output_len: 6,
14603        };
14604        let actual = build_dense_i64_inner_output_data(&specs, &plan);
14605
14606        // 4 matched left rows -> 6 output rows: avg fanout < 2, so the left
14607        // lane stays fully materialized alongside the right lane.
14608        assert_eq!(lane_expanded(&actual[0]), vec![20, 30, 30, 40, 50, 50]);
14609        assert_eq!(
14610            lane_expanded(&actual[1]),
14611            vec![100, 101, 104, 100, 102, 103]
14612        );
14613        assert!(matches!(actual[0], DenseI64LaneData::Full(_)));
14614        assert!(matches!(actual[1], DenseI64LaneData::Full(_)));
14615    }
14616
14617    fn lane_expanded(lane: &DenseI64LaneData) -> Vec<i64> {
14618        match lane {
14619            DenseI64LaneData::RepeatRunLengths { values, run_lens } => {
14620                let mut out = Vec::new();
14621                for (&value, &run_len) in values.iter().zip(run_lens.iter()) {
14622                    out.resize(out.len() + run_len, value);
14623                }
14624                out
14625            }
14626            DenseI64LaneData::RepeatedSlices { data, segments } => {
14627                let mut out = Vec::new();
14628                for &(start, len) in segments.iter() {
14629                    out.extend_from_slice(&data[start..start + len]);
14630                }
14631                out
14632            }
14633            DenseI64LaneData::Full(data) => data.clone(),
14634        }
14635    }
14636
14637    #[test]
14638    fn dense_i64_inner_high_fanout_emits_repeat_run_left_lanes() {
14639        // 2 matched left rows, each matching 3 right rows -> avg fanout 3:
14640        // left lane must come back as repeat runs and the right lane as
14641        // repeated slices. Their expansion equals the old full fill.
14642        let left_keys = vec![1, 7, 2];
14643        let min = 1;
14644        let max = 2;
14645        let offsets = vec![0, 3, 6];
14646        let positions = vec![0usize, 2, 4, 1, 3, 5];
14647        let left_values = vec![10, 20, 30];
14648        let right_values = vec![100, 101, 102, 103, 104, 105];
14649        let specs = vec![
14650            FusedInt64OutputColumn {
14651                name: "left".to_string(),
14652                side: FusedInt64Side::Left,
14653                values: &left_values,
14654            },
14655            FusedInt64OutputColumn {
14656                name: "right".to_string(),
14657                side: FusedInt64Side::Right,
14658                values: &right_values,
14659            },
14660        ];
14661
14662        let plan = DenseI64InnerOutputPlan {
14663            left_keys: &left_keys,
14664            min,
14665            max,
14666            offsets: &offsets,
14667            positions: &positions,
14668            output_len: 6,
14669        };
14670        let actual = build_dense_i64_inner_output_data(&specs, &plan);
14671
14672        assert!(matches!(
14673            actual[0],
14674            DenseI64LaneData::RepeatRunLengths { .. }
14675        ));
14676        assert!(matches!(actual[1], DenseI64LaneData::RepeatedSlices { .. }));
14677        assert_eq!(lane_expanded(&actual[0]), vec![10, 10, 10, 30, 30, 30]);
14678        assert_eq!(
14679            lane_expanded(&actual[1]),
14680            vec![100, 102, 104, 101, 103, 105]
14681        );
14682
14683        // The lazy Column built from shared run lengths is indistinguishable
14684        // from the eagerly materialized one (values, slice view, length,
14685        // equality).
14686        let lazy = fp_columnar::Column::from_i64_repeat_values_run_lengths(
14687            vec![10, 30],
14688            std::sync::Arc::from([3usize, 3]),
14689        );
14690        let eager = fp_columnar::Column::from_i64_values(vec![10, 10, 10, 30, 30, 30]);
14691        assert_eq!(lazy.len(), eager.len());
14692        assert_eq!(lazy.as_i64_slice(), eager.as_i64_slice());
14693        assert_eq!(lazy.values(), eager.values());
14694        assert_eq!(lazy, eager);
14695    }
14696
14697    #[test]
14698    fn dense_cycle_left_join_declines_invented_gaps_66wab() {
14699        let left = DataFrame::from_dict(
14700            &["id", "v"],
14701            vec![
14702                (
14703                    "id",
14704                    vec![
14705                        Scalar::Int64(0),
14706                        Scalar::Int64(1),
14707                        Scalar::Int64(2),
14708                        Scalar::Int64(0),
14709                        Scalar::Int64(1),
14710                        Scalar::Int64(2),
14711                        Scalar::Int64(0),
14712                    ],
14713                ),
14714                (
14715                    "v",
14716                    vec![
14717                        Scalar::Int64(10),
14718                        Scalar::Int64(11),
14719                        Scalar::Int64(12),
14720                        Scalar::Int64(13),
14721                        Scalar::Int64(14),
14722                        Scalar::Int64(15),
14723                        Scalar::Int64(16),
14724                    ],
14725                ),
14726            ],
14727        )
14728        .unwrap();
14729        let right = DataFrame::from_dict(
14730            &["id", "rv"],
14731            vec![
14732                (
14733                    "id",
14734                    vec![
14735                        Scalar::Int64(1),
14736                        Scalar::Int64(2),
14737                        Scalar::Int64(1),
14738                        Scalar::Int64(2),
14739                    ],
14740                ),
14741                (
14742                    "rv",
14743                    vec![
14744                        Scalar::Int64(100),
14745                        Scalar::Int64(200),
14746                        Scalar::Int64(101),
14747                        Scalar::Int64(201),
14748                    ],
14749                ),
14750            ],
14751        )
14752        .unwrap();
14753        let suffixes = ResolvedMergeSuffixes::default();
14754        let left_key = left.column("id").unwrap();
14755        let right_key = right.column("id").unwrap();
14756
14757        let dense_cycle = build_single_key_dense_cycle_i64_left_merge_output(
14758            &left,
14759            &right,
14760            &["id"],
14761            &["id"],
14762            left_key,
14763            right_key,
14764            &suffixes,
14765        )
14766        .unwrap();
14767        assert!(dense_cycle.is_none());
14768        assert!(
14769            build_single_key_dense_i64_left_merge_output(
14770                &left,
14771                &right,
14772                &["id"],
14773                &["id"],
14774                left_key,
14775                right_key,
14776                &suffixes,
14777            )
14778            .unwrap()
14779            .is_none()
14780        );
14781    }
14782
14783    #[test]
14784    fn merge_inner_ordered_identity_matches_generic_validated_route() {
14785        let left = DataFrame::from_dict(
14786            &["id", "v"],
14787            vec![
14788                (
14789                    "id",
14790                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
14791                ),
14792                (
14793                    "v",
14794                    vec![
14795                        Scalar::Int64(10),
14796                        Scalar::Null(NullKind::Null),
14797                        Scalar::Int64(30),
14798                    ],
14799                ),
14800            ],
14801        )
14802        .unwrap();
14803        let right = DataFrame::from_dict(
14804            &["id", "w"],
14805            vec![
14806                (
14807                    "id",
14808                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
14809                ),
14810                (
14811                    "w",
14812                    vec![Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(300)],
14813                ),
14814            ],
14815        )
14816        .unwrap();
14817
14818        let fast = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
14819        let generic = merge_dataframes_on_with_options(
14820            &left,
14821            &right,
14822            &["id"],
14823            &["id"],
14824            JoinType::Inner,
14825            MergeExecutionOptions {
14826                validate_mode: Some(MergeValidateMode::OneToOne),
14827                ..MergeExecutionOptions::default()
14828            },
14829        )
14830        .unwrap();
14831
14832        assert_eq!(fast.index, generic.index);
14833        assert_eq!(fast.column_order, generic.column_order);
14834        assert_eq!(fast.columns, generic.columns);
14835    }
14836
14837    #[test]
14838    fn merge_inner_dense_int64_fused_materialization_matches_generic_route() {
14839        let left = DataFrame::from_dict(
14840            &["id", "v", "overlap"],
14841            vec![
14842                (
14843                    "id",
14844                    vec![
14845                        Scalar::Int64(2),
14846                        Scalar::Int64(1),
14847                        Scalar::Int64(2),
14848                        Scalar::Int64(3),
14849                    ],
14850                ),
14851                (
14852                    "v",
14853                    vec![
14854                        Scalar::Int64(20),
14855                        Scalar::Int64(10),
14856                        Scalar::Int64(21),
14857                        Scalar::Int64(30),
14858                    ],
14859                ),
14860                (
14861                    "overlap",
14862                    vec![
14863                        Scalar::Int64(200),
14864                        Scalar::Int64(100),
14865                        Scalar::Int64(201),
14866                        Scalar::Int64(300),
14867                    ],
14868                ),
14869            ],
14870        )
14871        .unwrap();
14872        let right = DataFrame::from_dict(
14873            &["id", "w", "overlap"],
14874            vec![
14875                (
14876                    "id",
14877                    vec![
14878                        Scalar::Int64(2),
14879                        Scalar::Int64(2),
14880                        Scalar::Int64(1),
14881                        Scalar::Int64(4),
14882                    ],
14883                ),
14884                (
14885                    "w",
14886                    vec![
14887                        Scalar::Int64(2000),
14888                        Scalar::Int64(2001),
14889                        Scalar::Int64(1000),
14890                        Scalar::Int64(4000),
14891                    ],
14892                ),
14893                (
14894                    "overlap",
14895                    vec![
14896                        Scalar::Int64(20_000),
14897                        Scalar::Int64(20_001),
14898                        Scalar::Int64(10_000),
14899                        Scalar::Int64(40_000),
14900                    ],
14901                ),
14902            ],
14903        )
14904        .unwrap();
14905
14906        let fast = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
14907        let generic = merge_dataframes_on_with_options(
14908            &left,
14909            &right,
14910            &["id"],
14911            &["id"],
14912            JoinType::Inner,
14913            MergeExecutionOptions {
14914                validate_mode: Some(MergeValidateMode::ManyToMany),
14915                ..MergeExecutionOptions::default()
14916            },
14917        )
14918        .unwrap();
14919
14920        assert_eq!(fast.index, generic.index);
14921        assert_eq!(fast.column_order, generic.column_order);
14922        assert_eq!(fast.columns, generic.columns);
14923        assert_eq!(
14924            fast.column_order,
14925            ["id", "v", "overlap_x", "w", "overlap_y"]
14926        );
14927        assert_eq!(
14928            fast.columns.get("id").unwrap().values(),
14929            &[
14930                Scalar::Int64(2),
14931                Scalar::Int64(2),
14932                Scalar::Int64(1),
14933                Scalar::Int64(2),
14934                Scalar::Int64(2),
14935            ]
14936        );
14937        assert_eq!(
14938            fast.columns.get("w").unwrap().values(),
14939            &[
14940                Scalar::Int64(2000),
14941                Scalar::Int64(2001),
14942                Scalar::Int64(1000),
14943                Scalar::Int64(2000),
14944                Scalar::Int64(2001),
14945            ]
14946        );
14947        assert!(
14948            fast.columns
14949                .values()
14950                .all(|column| column.as_i64_slice().is_some())
14951        );
14952    }
14953
14954    #[test]
14955    fn merge_inner_ordered_unique_int64_subset_matches_generic_validated_route() {
14956        let left = DataFrame::from_dict(
14957            &["id", "v"],
14958            vec![
14959                (
14960                    "id",
14961                    vec![
14962                        Scalar::Int64(0),
14963                        Scalar::Int64(1),
14964                        Scalar::Int64(2),
14965                        Scalar::Int64(3),
14966                        Scalar::Int64(4),
14967                    ],
14968                ),
14969                (
14970                    "v",
14971                    vec![
14972                        Scalar::Int64(10),
14973                        Scalar::Int64(11),
14974                        Scalar::Int64(12),
14975                        Scalar::Int64(13),
14976                        Scalar::Int64(14),
14977                    ],
14978                ),
14979            ],
14980        )
14981        .unwrap();
14982        let right = DataFrame::from_dict(
14983            &["id", "w"],
14984            vec![
14985                (
14986                    "id",
14987                    vec![
14988                        Scalar::Int64(0),
14989                        Scalar::Int64(2),
14990                        Scalar::Int64(4),
14991                        Scalar::Int64(6),
14992                    ],
14993                ),
14994                (
14995                    "w",
14996                    vec![
14997                        Scalar::Int64(100),
14998                        Scalar::Int64(200),
14999                        Scalar::Int64(300),
15000                        Scalar::Int64(400),
15001                    ],
15002                ),
15003            ],
15004        )
15005        .unwrap();
15006
15007        let fast = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
15008        let generic = merge_dataframes_on_with_options(
15009            &left,
15010            &right,
15011            &["id"],
15012            &["id"],
15013            JoinType::Inner,
15014            MergeExecutionOptions {
15015                validate_mode: Some(MergeValidateMode::OneToOne),
15016                ..MergeExecutionOptions::default()
15017            },
15018        )
15019        .unwrap();
15020
15021        assert_eq!(fast.index, generic.index);
15022        assert_eq!(fast.column_order, generic.column_order);
15023        assert_eq!(fast.columns, generic.columns);
15024        assert_eq!(
15025            fast.columns.get("id").unwrap().values(),
15026            &[Scalar::Int64(0), Scalar::Int64(2), Scalar::Int64(4)]
15027        );
15028        assert_eq!(
15029            fast.columns.get("v").unwrap().values(),
15030            &[Scalar::Int64(10), Scalar::Int64(12), Scalar::Int64(14)]
15031        );
15032        assert_eq!(
15033            fast.columns.get("w").unwrap().values(),
15034            &[Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(300)]
15035        );
15036    }
15037
15038    #[test]
15039    fn merge_inner_ordered_identity_falls_back_for_non_identity_keys() {
15040        let cases = [
15041            (
15042                vec![Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(4)],
15043                vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
15044            ),
15045            (
15046                vec![
15047                    Scalar::Int64(1),
15048                    Scalar::Null(NullKind::Null),
15049                    Scalar::Int64(3),
15050                ],
15051                vec![
15052                    Scalar::Int64(1),
15053                    Scalar::Null(NullKind::Null),
15054                    Scalar::Int64(3),
15055                ],
15056            ),
15057        ];
15058
15059        for (left_keys, right_keys) in cases {
15060            let left = DataFrame::from_dict(
15061                &["id", "v"],
15062                vec![
15063                    ("id", left_keys),
15064                    (
15065                        "v",
15066                        vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
15067                    ),
15068                ],
15069            )
15070            .unwrap();
15071            let right = DataFrame::from_dict(
15072                &["id", "w"],
15073                vec![
15074                    ("id", right_keys),
15075                    (
15076                        "w",
15077                        vec![Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(300)],
15078                    ),
15079                ],
15080            )
15081            .unwrap();
15082
15083            let maybe_fast = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
15084            let generic = merge_dataframes_on_with_options(
15085                &left,
15086                &right,
15087                &["id"],
15088                &["id"],
15089                JoinType::Inner,
15090                MergeExecutionOptions {
15091                    validate_mode: Some(MergeValidateMode::OneToOne),
15092                    ..MergeExecutionOptions::default()
15093                },
15094            )
15095            .unwrap();
15096
15097            assert_eq!(maybe_fast.index, generic.index);
15098            assert_eq!(maybe_fast.column_order, generic.column_order);
15099            assert_eq!(maybe_fast.columns, generic.columns);
15100        }
15101    }
15102
15103    #[test]
15104    fn merge_default_suffixes_match_pandas() {
15105        // Overlapping non-key column "v" gets pandas default _x/_y suffixes.
15106        // Verified vs pandas 2.2.3: left{k:[1,2,3],v:[10,20,30]} merged inner on
15107        // k with right{k:[2,3,4],v:[200,300,400]} -> cols [k,v_x,v_y],
15108        // k=[2,3], v_x=[20,30], v_y=[200,300].
15109        let idx: Vec<_> = (0..3).map(|i| (i as i64).into()).collect();
15110        let left = fp_frame::DataFrame::from_series(vec![
15111            fp_frame::Series::from_values(
15112                "k",
15113                idx.clone(),
15114                vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
15115            )
15116            .unwrap(),
15117            fp_frame::Series::from_values(
15118                "v",
15119                idx.clone(),
15120                vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
15121            )
15122            .unwrap(),
15123        ])
15124        .unwrap();
15125        let right = fp_frame::DataFrame::from_series(vec![
15126            fp_frame::Series::from_values(
15127                "k",
15128                idx.clone(),
15129                vec![Scalar::Int64(2), Scalar::Int64(3), Scalar::Int64(4)],
15130            )
15131            .unwrap(),
15132            fp_frame::Series::from_values(
15133                "v",
15134                idx,
15135                vec![Scalar::Int64(200), Scalar::Int64(300), Scalar::Int64(400)],
15136            )
15137            .unwrap(),
15138        ])
15139        .unwrap();
15140        let merged = merge_dataframes(&left, &right, "k", JoinType::Inner).unwrap();
15141
15142        assert_eq!(
15143            merged.columns.get("k").unwrap().values(),
15144            &[Scalar::Int64(2), Scalar::Int64(3)],
15145            "k"
15146        );
15147        assert_eq!(
15148            merged.columns.get("v_x").unwrap().values(),
15149            &[Scalar::Int64(20), Scalar::Int64(30)],
15150            "v_x"
15151        );
15152        assert_eq!(
15153            merged.columns.get("v_y").unwrap().values(),
15154            &[Scalar::Int64(200), Scalar::Int64(300)],
15155            "v_y"
15156        );
15157        assert!(
15158            !merged.columns.contains_key("v"),
15159            "bare 'v' should be suffixed away"
15160        );
15161    }
15162
15163    #[test]
15164    fn merge_left_preserves_all_left_rows() {
15165        let left = make_left_df();
15166        let right = make_right_df();
15167        let merged = merge_dataframes(&left, &right, "id", JoinType::Left).unwrap();
15168
15169        assert_eq!(merged.columns.get("id").unwrap().len(), 3);
15170        assert_eq!(
15171            merged.columns.get("val_a").unwrap().values(),
15172            &[Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)]
15173        );
15174        // val_b widens to Float64 because id=1 invents a missing value.
15175        assert_eq!(merged.columns.get("val_b").unwrap().dtype(), DType::Float64);
15176        assert_eq!(
15177            merged.columns.get("val_b").unwrap().values()[0],
15178            Scalar::Null(NullKind::NaN)
15179        );
15180        assert_eq!(
15181            merged.columns.get("val_b").unwrap().values()[1],
15182            Scalar::Float64(200.0)
15183        );
15184        assert_eq!(
15185            merged.columns.get("val_b").unwrap().values()[2],
15186            Scalar::Float64(300.0)
15187        );
15188    }
15189
15190    #[test]
15191    fn merge_left_ordered_unique_int64_subset_matches_generic_validated_route() {
15192        let left = DataFrame::from_dict(
15193            &["id", "v"],
15194            vec![
15195                (
15196                    "id",
15197                    vec![
15198                        Scalar::Int64(0),
15199                        Scalar::Int64(1),
15200                        Scalar::Int64(2),
15201                        Scalar::Int64(3),
15202                        Scalar::Int64(4),
15203                    ],
15204                ),
15205                (
15206                    "v",
15207                    vec![
15208                        Scalar::Int64(10),
15209                        Scalar::Int64(11),
15210                        Scalar::Int64(12),
15211                        Scalar::Int64(13),
15212                        Scalar::Int64(14),
15213                    ],
15214                ),
15215            ],
15216        )
15217        .unwrap();
15218        let right = DataFrame::from_dict(
15219            &["id", "w"],
15220            vec![
15221                (
15222                    "id",
15223                    vec![
15224                        Scalar::Int64(0),
15225                        Scalar::Int64(2),
15226                        Scalar::Int64(4),
15227                        Scalar::Int64(6),
15228                    ],
15229                ),
15230                (
15231                    "w",
15232                    vec![
15233                        Scalar::Int64(100),
15234                        Scalar::Int64(200),
15235                        Scalar::Int64(300),
15236                        Scalar::Int64(400),
15237                    ],
15238                ),
15239            ],
15240        )
15241        .unwrap();
15242
15243        let fast = merge_dataframes(&left, &right, "id", JoinType::Left).unwrap();
15244        let generic = merge_dataframes_on_with_options(
15245            &left,
15246            &right,
15247            &["id"],
15248            &["id"],
15249            JoinType::Left,
15250            MergeExecutionOptions {
15251                validate_mode: Some(MergeValidateMode::OneToOne),
15252                ..MergeExecutionOptions::default()
15253            },
15254        )
15255        .unwrap();
15256
15257        assert_eq!(fast.index, generic.index);
15258        assert_eq!(fast.column_order, generic.column_order);
15259        assert_eq!(fast.columns, generic.columns);
15260        assert_eq!(
15261            fast.columns.get("id").unwrap().values(),
15262            &[
15263                Scalar::Int64(0),
15264                Scalar::Int64(1),
15265                Scalar::Int64(2),
15266                Scalar::Int64(3),
15267                Scalar::Int64(4)
15268            ]
15269        );
15270        let right_values = fast.columns.get("w").unwrap().values();
15271        assert_eq!(right_values[0], Scalar::Float64(100.0));
15272        assert!(right_values[1].is_missing());
15273        assert_eq!(right_values[2], Scalar::Float64(200.0));
15274        assert!(right_values[3].is_missing());
15275        assert_eq!(right_values[4], Scalar::Float64(300.0));
15276    }
15277
15278    #[test]
15279    fn merge_left_ordered_unique_int64_retains_lazy_utf8_payload_plan() {
15280        let left = DataFrame::from_dict(
15281            &["id", "v"],
15282            vec![
15283                ("id", (0..5_i64).map(Scalar::Int64).collect::<Vec<_>>()),
15284                ("v", (10..15_i64).map(Scalar::Int64).collect::<Vec<_>>()),
15285            ],
15286        )
15287        .unwrap();
15288        let right = DataFrame::from_dict(
15289            &["id", "tag"],
15290            vec![
15291                (
15292                    "id",
15293                    [0_i64, 2, 4, 6].into_iter().map(Scalar::Int64).collect(),
15294                ),
15295                (
15296                    "tag",
15297                    ["zero", "two", "four", "six"]
15298                        .into_iter()
15299                        .map(|value| Scalar::Utf8(value.to_owned()))
15300                        .collect(),
15301                ),
15302            ],
15303        )
15304        .unwrap();
15305
15306        let merged = merge_dataframes(&left, &right, "id", JoinType::Left).unwrap();
15307        let tags = merged.columns.get("tag").unwrap().values();
15308        assert_eq!(tags[0], Scalar::Utf8("zero".to_owned()));
15309        assert!(tags[1].is_missing());
15310        assert_eq!(tags[2], Scalar::Utf8("two".to_owned()));
15311        assert!(tags[3].is_missing());
15312        assert_eq!(tags[4], Scalar::Utf8("four".to_owned()));
15313    }
15314
15315    #[test]
15316    fn merge_left_dense_int64_duplicates_matches_generic_validated_route() {
15317        let left = DataFrame::from_dict(
15318            &["id", "v"],
15319            vec![
15320                (
15321                    "id",
15322                    vec![
15323                        Scalar::Int64(2),
15324                        Scalar::Int64(0),
15325                        Scalar::Int64(2),
15326                        Scalar::Int64(1),
15327                        Scalar::Int64(5),
15328                    ],
15329                ),
15330                (
15331                    "v",
15332                    vec![
15333                        Scalar::Int64(10),
15334                        Scalar::Int64(11),
15335                        Scalar::Int64(12),
15336                        Scalar::Int64(13),
15337                        Scalar::Int64(15),
15338                    ],
15339                ),
15340            ],
15341        )
15342        .unwrap();
15343        let right = DataFrame::from_dict(
15344            &["id", "w"],
15345            vec![
15346                (
15347                    "id",
15348                    vec![
15349                        Scalar::Int64(2),
15350                        Scalar::Int64(2),
15351                        Scalar::Int64(3),
15352                        Scalar::Int64(0),
15353                    ],
15354                ),
15355                (
15356                    "w",
15357                    vec![
15358                        Scalar::Int64(200),
15359                        Scalar::Int64(201),
15360                        Scalar::Int64(300),
15361                        Scalar::Int64(400),
15362                    ],
15363                ),
15364            ],
15365        )
15366        .unwrap();
15367
15368        let fast = merge_dataframes(&left, &right, "id", JoinType::Left).unwrap();
15369        let generic = merge_dataframes_on_with_options(
15370            &left,
15371            &right,
15372            &["id"],
15373            &["id"],
15374            JoinType::Left,
15375            MergeExecutionOptions {
15376                validate_mode: Some(MergeValidateMode::ManyToMany),
15377                ..MergeExecutionOptions::default()
15378            },
15379        )
15380        .unwrap();
15381
15382        assert_eq!(fast.index, generic.index);
15383        assert_eq!(fast.column_order, generic.column_order);
15384        assert_eq!(fast.columns, generic.columns);
15385        assert_eq!(
15386            fast.columns.get("id").unwrap().values(),
15387            &[
15388                Scalar::Int64(2),
15389                Scalar::Int64(2),
15390                Scalar::Int64(0),
15391                Scalar::Int64(2),
15392                Scalar::Int64(2),
15393                Scalar::Int64(1),
15394                Scalar::Int64(5),
15395            ]
15396        );
15397        let left_values = fast.columns.get("v").unwrap().values();
15398        assert_eq!(left_values[0], Scalar::Int64(10));
15399        assert_eq!(left_values[1], Scalar::Int64(10));
15400        assert_eq!(left_values[2], Scalar::Int64(11));
15401        assert_eq!(left_values[4], Scalar::Int64(12));
15402        assert_eq!(left_values[6], Scalar::Int64(15));
15403        let right_values = fast.columns.get("w").unwrap().values();
15404        assert_eq!(right_values[0], Scalar::Float64(200.0));
15405        assert_eq!(right_values[1], Scalar::Float64(201.0));
15406        assert_eq!(right_values[2], Scalar::Float64(400.0));
15407        assert!(right_values[5].is_missing());
15408        assert!(right_values[6].is_missing());
15409    }
15410
15411    #[test]
15412    fn merge_left_dense_cycle_probe_declines_invented_gaps_66wab() {
15413        let left = DataFrame::from_dict(
15414            &["id", "v"],
15415            vec![
15416                (
15417                    "id",
15418                    vec![
15419                        Scalar::Int64(0),
15420                        Scalar::Int64(1),
15421                        Scalar::Int64(2),
15422                        Scalar::Int64(0),
15423                        Scalar::Int64(1),
15424                    ],
15425                ),
15426                (
15427                    "v",
15428                    vec![
15429                        Scalar::Int64(10),
15430                        Scalar::Int64(11),
15431                        Scalar::Int64(12),
15432                        Scalar::Int64(13),
15433                        Scalar::Int64(14),
15434                    ],
15435                ),
15436            ],
15437        )
15438        .unwrap();
15439        let right = DataFrame::from_dict(
15440            &["id", "w"],
15441            vec![
15442                (
15443                    "id",
15444                    vec![
15445                        Scalar::Int64(1),
15446                        Scalar::Int64(2),
15447                        Scalar::Int64(1),
15448                        Scalar::Int64(2),
15449                    ],
15450                ),
15451                (
15452                    "w",
15453                    vec![
15454                        Scalar::Int64(100),
15455                        Scalar::Int64(200),
15456                        Scalar::Int64(101),
15457                        Scalar::Int64(201),
15458                    ],
15459                ),
15460            ],
15461        )
15462        .unwrap();
15463        let left_key = left.columns().get("id").unwrap();
15464        let right_key = right.columns().get("id").unwrap();
15465        assert!(left_key.int64_dense_cycle_witness().is_some());
15466        assert!(right_key.int64_dense_cycle_witness().is_some());
15467        let suffixes = resolve_merge_suffixes(None);
15468
15469        let fused = build_single_key_dense_i64_left_merge_output(
15470            &left,
15471            &right,
15472            &["id"],
15473            &["id"],
15474            left_key,
15475            right_key,
15476            &suffixes,
15477        )
15478        .unwrap();
15479        assert!(fused.is_none());
15480    }
15481
15482    #[test]
15483    fn partial_int64_merges_promote_invented_gaps_66wab() {
15484        let left = DataFrame::from_dict(
15485            &["id", "v"],
15486            vec![
15487                (
15488                    "id",
15489                    vec![
15490                        Scalar::Int64(0),
15491                        Scalar::Int64(1),
15492                        Scalar::Int64(2),
15493                        Scalar::Int64(0),
15494                        Scalar::Int64(1),
15495                    ],
15496                ),
15497                (
15498                    "v",
15499                    vec![
15500                        Scalar::Int64(10),
15501                        Scalar::Int64(11),
15502                        Scalar::Int64(12),
15503                        Scalar::Int64(13),
15504                        Scalar::Int64(14),
15505                    ],
15506                ),
15507            ],
15508        )
15509        .unwrap();
15510        let right = DataFrame::from_dict(
15511            &["id", "w"],
15512            vec![
15513                (
15514                    "id",
15515                    vec![
15516                        Scalar::Int64(1),
15517                        Scalar::Int64(2),
15518                        Scalar::Int64(1),
15519                        Scalar::Int64(2),
15520                    ],
15521                ),
15522                (
15523                    "w",
15524                    vec![
15525                        Scalar::Int64(100),
15526                        Scalar::Int64(200),
15527                        Scalar::Int64(101),
15528                        Scalar::Int64(201),
15529                    ],
15530                ),
15531            ],
15532        )
15533        .unwrap();
15534
15535        let left_join = merge_dataframes(&left, &right, "id", JoinType::Left).unwrap();
15536        let left_gap_column = left_join.columns.get("w").unwrap();
15537        assert_eq!(left_gap_column.dtype(), DType::Float64);
15538        assert_eq!(left_gap_column.values()[0], Scalar::Null(NullKind::NaN));
15539        assert_eq!(left_gap_column.values()[1], Scalar::Float64(100.0));
15540
15541        let right_join = merge_dataframes(&right, &left, "id", JoinType::Right).unwrap();
15542        let right_gap_column = right_join.columns.get("w").unwrap();
15543        assert_eq!(right_gap_column.dtype(), DType::Float64);
15544        assert_eq!(right_gap_column.values()[0], Scalar::Null(NullKind::NaN));
15545        assert_eq!(right_gap_column.values()[1], Scalar::Float64(100.0));
15546    }
15547
15548    /// A missing value FrankenPandas spells two ways on a float lane: the
15549    /// `Null(NaN)` marker, and a present `Float64` whose bits are NaN (typed
15550    /// kernels emit the latter directly). pandas has ONE representation — the
15551    /// NaN bit pattern in the float64 array — and the fixture format writes
15552    /// either as `na_n`, so a null-kind assertion on a float lane must accept
15553    /// both or it fails on a legitimate representation change. What it must
15554    /// still reject is a carried-over generic `Null(Null)` or a `NaT`.
15555    ///
15556    /// br-frankenpandas-nywa8; the trap is WindyHare's window/derived slice.
15557    fn assert_nan_flavoured(value: &Scalar, what: &str) {
15558        let ok = match value {
15559            Scalar::Null(NullKind::NaN) => true,
15560            Scalar::Float64(v) => v.is_nan(),
15561            _ => false,
15562        };
15563        assert!(
15564            ok,
15565            "{what}: expected a NaN-flavoured missing, got {value:?}"
15566        );
15567    }
15568
15569    /// The four merge fixtures that were the last structural rows on
15570    /// br-frankenpandas-nywa8, run through the SAME entry point the conformance
15571    /// harness uses (`merge_dataframes_on_with_options`) on their exact
15572    /// payloads.
15573    ///
15574    /// THE RULE, and every line of it MEASURED against live pandas 2.2.3 rather
15575    /// than inferred from the differ: a lane widens iff the merge INVENTS a gap
15576    /// in THAT lane. The join type is irrelevant, and a lane that gains no gap
15577    /// keeps int64.
15578    ///
15579    /// ```text
15580    ///   l={'id':[1,2,3],'left_v':[10,20,30],'shared':[1,2,3]}
15581    ///   r={'id':[2],'right_v':[200],'shared':[9]}
15582    ///   l.merge(r, on='id', how='left')
15583    ///     id int64  left_v int64  shared_x int64      no gap  -> unchanged
15584    ///     right_v float64 [nan,200.0,nan]
15585    ///     shared_y float64 [nan,9.0,nan]              gap     -> widened
15586    ///
15587    ///   l={'id':[1,2],'left_v':[11,22]}  r={'id':[2,3],'right_v':[220,330]}
15588    ///   l.merge(r, on='id', how='right')
15589    ///     left_v float64 [22.0,nan]   right_v int64 [220,330]   id int64
15590    ///
15591    ///   l.merge(r, on='id', how='right', sort=True) over id l=[3,1] r=[2,1,3]
15592    ///     id int64 [1,2,3]  left_v float64 [10.0,nan,30.0]  right_v int64
15593    /// ```
15594    ///
15595    /// THE COMPOSITE OUTER CASE IS THE ONE WORTH THE TEST, because a single
15596    /// object column carries nywa8's two rules side by side. Measured on
15597    /// `lk2 = ['a', None, 'c']` outer-merged against `rk2 = ['a', None, 'd']`:
15598    ///
15599    /// ```text
15600    ///   lk2 dtype object, kinds ['str', 'NoneType', 'str', 'float']
15601    ///                                     ^ RULE 2          ^ RULE 1
15602    /// ```
15603    ///
15604    /// Row 1's `None` was SUPPLIED and object can store it, so pandas keeps it.
15605    /// Row 3's gap was INVENTED by the outer join, and pandas writes a float nan
15606    /// there even though the column is object. That is why the rule cannot be
15607    /// "derive the marker from the column dtype" — the same column answers
15608    /// differently per cell, and only the site that invents the gap knows which.
15609    #[test]
15610    fn merge_widens_only_the_lane_that_gains_an_invented_gap_nywa8() {
15611        // FP-P2D-014 dataframe_merge_column_left_missing_hardened
15612        let left = DataFrame::from_dict(
15613            &["id", "left_v", "shared"],
15614            vec![
15615                (
15616                    "id",
15617                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
15618                ),
15619                (
15620                    "left_v",
15621                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
15622                ),
15623                (
15624                    "shared",
15625                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
15626                ),
15627            ],
15628        )
15629        .unwrap();
15630        let right = DataFrame::from_dict(
15631            &["id", "right_v", "shared"],
15632            vec![
15633                ("id", vec![Scalar::Int64(2)]),
15634                ("right_v", vec![Scalar::Int64(200)]),
15635                ("shared", vec![Scalar::Int64(9)]),
15636            ],
15637        )
15638        .unwrap();
15639        let merged = merge_dataframes_on_with_options(
15640            &left,
15641            &right,
15642            &["id"],
15643            &["id"],
15644            JoinType::Left,
15645            MergeExecutionOptions::default(),
15646        )
15647        .unwrap();
15648        for gapless in ["id", "left_v", "shared_x"] {
15649            assert_eq!(
15650                merged.columns.get(gapless).unwrap().dtype(),
15651                DType::Int64,
15652                "{gapless} gains no gap and must stay int64"
15653            );
15654        }
15655        for gapped in ["right_v", "shared_y"] {
15656            let column = merged.columns.get(gapped).unwrap();
15657            assert_eq!(column.dtype(), DType::Float64, "{gapped} gains a gap");
15658            assert_nan_flavoured(&column.values()[0], gapped);
15659            assert_nan_flavoured(&column.values()[2], gapped);
15660        }
15661        assert_eq!(
15662            merged.columns.get("right_v").unwrap().values()[1],
15663            Scalar::Float64(200.0)
15664        );
15665        assert_eq!(
15666            merged.columns.get("shared_y").unwrap().values()[1],
15667            Scalar::Float64(9.0)
15668        );
15669
15670        // FP-P2D-014 dataframe_merge_column_right_order_strict
15671        let left = DataFrame::from_dict(
15672            &["id", "left_v"],
15673            vec![
15674                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
15675                ("left_v", vec![Scalar::Int64(11), Scalar::Int64(22)]),
15676            ],
15677        )
15678        .unwrap();
15679        let right = DataFrame::from_dict(
15680            &["id", "right_v"],
15681            vec![
15682                ("id", vec![Scalar::Int64(2), Scalar::Int64(3)]),
15683                ("right_v", vec![Scalar::Int64(220), Scalar::Int64(330)]),
15684            ],
15685        )
15686        .unwrap();
15687        let merged = merge_dataframes_on_with_options(
15688            &left,
15689            &right,
15690            &["id"],
15691            &["id"],
15692            JoinType::Right,
15693            MergeExecutionOptions::default(),
15694        )
15695        .unwrap();
15696        assert_eq!(merged.columns.get("id").unwrap().dtype(), DType::Int64);
15697        assert_eq!(merged.columns.get("right_v").unwrap().dtype(), DType::Int64);
15698        let left_v = merged.columns.get("left_v").unwrap();
15699        assert_eq!(left_v.dtype(), DType::Float64);
15700        assert_eq!(left_v.values()[0], Scalar::Float64(22.0));
15701        assert_nan_flavoured(&left_v.values()[1], "left_v");
15702
15703        // FP-P2D-037 dataframe_merge_sort_true_right_hardened
15704        let left = DataFrame::from_dict(
15705            &["id", "left_v"],
15706            vec![
15707                ("id", vec![Scalar::Int64(3), Scalar::Int64(1)]),
15708                ("left_v", vec![Scalar::Int64(30), Scalar::Int64(10)]),
15709            ],
15710        )
15711        .unwrap();
15712        let right = DataFrame::from_dict(
15713            &["id", "right_v"],
15714            vec![
15715                (
15716                    "id",
15717                    vec![Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(3)],
15718                ),
15719                (
15720                    "right_v",
15721                    vec![Scalar::Int64(200), Scalar::Int64(100), Scalar::Int64(300)],
15722                ),
15723            ],
15724        )
15725        .unwrap();
15726        let merged = merge_dataframes_on_with_options(
15727            &left,
15728            &right,
15729            &["id"],
15730            &["id"],
15731            JoinType::Right,
15732            MergeExecutionOptions {
15733                sort: true,
15734                ..MergeExecutionOptions::default()
15735            },
15736        )
15737        .unwrap();
15738        assert_eq!(merged.columns.get("id").unwrap().dtype(), DType::Int64);
15739        assert_eq!(merged.columns.get("right_v").unwrap().dtype(), DType::Int64);
15740        let left_v = merged.columns.get("left_v").unwrap();
15741        assert_eq!(left_v.dtype(), DType::Float64);
15742        assert_eq!(left_v.values()[0], Scalar::Float64(10.0));
15743        assert_nan_flavoured(&left_v.values()[1], "left_v");
15744        assert_eq!(left_v.values()[2], Scalar::Float64(30.0));
15745
15746        // FP-P2D-033 dataframe_merge_composite_left_right_alias_outer_hardened
15747        let left = DataFrame::from_dict(
15748            &["lk1", "lk2", "left_v"],
15749            vec![
15750                (
15751                    "lk1",
15752                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
15753                ),
15754                (
15755                    "lk2",
15756                    vec![
15757                        Scalar::Utf8("a".to_owned()),
15758                        Scalar::Null(NullKind::Null),
15759                        Scalar::Utf8("c".to_owned()),
15760                    ],
15761                ),
15762                (
15763                    "left_v",
15764                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
15765                ),
15766            ],
15767        )
15768        .unwrap();
15769        let right = DataFrame::from_dict(
15770            &["rk1", "rk2", "right_v"],
15771            vec![
15772                (
15773                    "rk1",
15774                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(4)],
15775                ),
15776                (
15777                    "rk2",
15778                    vec![
15779                        Scalar::Utf8("a".to_owned()),
15780                        Scalar::Null(NullKind::Null),
15781                        Scalar::Utf8("d".to_owned()),
15782                    ],
15783                ),
15784                (
15785                    "right_v",
15786                    vec![Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(400)],
15787                ),
15788            ],
15789        )
15790        .unwrap();
15791        let merged = merge_dataframes_on_with_options(
15792            &left,
15793            &right,
15794            &["lk1", "lk2"],
15795            &["rk1", "rk2"],
15796            JoinType::Outer,
15797            MergeExecutionOptions::default(),
15798        )
15799        .unwrap();
15800        // Every numeric lane gains a gap under this outer merge, so all four widen.
15801        for numeric in ["lk1", "rk1", "left_v", "right_v"] {
15802            assert_eq!(
15803                merged.columns.get(numeric).unwrap().dtype(),
15804                DType::Float64,
15805                "{numeric} gains a gap under the outer merge"
15806            );
15807        }
15808        assert_nan_flavoured(&merged.columns.get("lk1").unwrap().values()[3], "lk1");
15809        assert_nan_flavoured(&merged.columns.get("left_v").unwrap().values()[3], "left_v");
15810        assert_nan_flavoured(&merged.columns.get("rk1").unwrap().values()[2], "rk1");
15811        assert_nan_flavoured(
15812            &merged.columns.get("right_v").unwrap().values()[2],
15813            "right_v",
15814        );
15815
15816        // The object lanes are the point: SUPPLIED None survives, INVENTED gap
15817        // is a nan, in the same column.
15818        let lk2 = merged.columns.get("lk2").unwrap();
15819        assert_eq!(lk2.values()[0], Scalar::Utf8("a".to_owned()));
15820        assert_eq!(
15821            lk2.values()[1],
15822            Scalar::Null(NullKind::Null),
15823            "lk2[1]'s None was SUPPLIED and object can hold it (nywa8 Rule 2)"
15824        );
15825        assert_eq!(lk2.values()[2], Scalar::Utf8("c".to_owned()));
15826        assert_nan_flavoured(&lk2.values()[3], "lk2[3] is an INVENTED gap (nywa8 Rule 1)");
15827
15828        let rk2 = merged.columns.get("rk2").unwrap();
15829        assert_eq!(rk2.values()[0], Scalar::Utf8("a".to_owned()));
15830        assert_eq!(
15831            rk2.values()[1],
15832            Scalar::Null(NullKind::Null),
15833            "rk2[1]'s None was SUPPLIED and object can hold it (nywa8 Rule 2)"
15834        );
15835        assert_nan_flavoured(&rk2.values()[2], "rk2[2] is an INVENTED gap (nywa8 Rule 1)");
15836        assert_eq!(rk2.values()[3], Scalar::Utf8("d".to_owned()));
15837    }
15838
15839    #[test]
15840    fn merge_left_all_matched_dense_int64_fused_output_matches_sorted_generic_route() {
15841        let left = DataFrame::from_dict(
15842            &["id", "v"],
15843            vec![
15844                (
15845                    "id",
15846                    vec![
15847                        Scalar::Int64(0),
15848                        Scalar::Int64(0),
15849                        Scalar::Int64(1),
15850                        Scalar::Int64(1),
15851                        Scalar::Int64(2),
15852                    ],
15853                ),
15854                (
15855                    "v",
15856                    vec![
15857                        Scalar::Int64(10),
15858                        Scalar::Int64(11),
15859                        Scalar::Int64(20),
15860                        Scalar::Int64(21),
15861                        Scalar::Int64(30),
15862                    ],
15863                ),
15864            ],
15865        )
15866        .unwrap();
15867        let right = DataFrame::from_dict(
15868            &["id", "w"],
15869            vec![
15870                (
15871                    "id",
15872                    vec![
15873                        Scalar::Int64(0),
15874                        Scalar::Int64(0),
15875                        Scalar::Int64(1),
15876                        Scalar::Int64(2),
15877                        Scalar::Int64(2),
15878                    ],
15879                ),
15880                (
15881                    "w",
15882                    vec![
15883                        Scalar::Int64(100),
15884                        Scalar::Int64(101),
15885                        Scalar::Int64(200),
15886                        Scalar::Int64(300),
15887                        Scalar::Int64(301),
15888                    ],
15889                ),
15890            ],
15891        )
15892        .unwrap();
15893
15894        let fast = merge_dataframes(&left, &right, "id", JoinType::Left).unwrap();
15895        let generic = merge_dataframes_on_with_options(
15896            &left,
15897            &right,
15898            &["id"],
15899            &["id"],
15900            JoinType::Left,
15901            MergeExecutionOptions {
15902                sort: true,
15903                ..MergeExecutionOptions::default()
15904            },
15905        )
15906        .unwrap();
15907
15908        assert_eq!(fast.index, generic.index);
15909        assert_eq!(fast.column_order, generic.column_order);
15910        assert_eq!(fast.columns, generic.columns);
15911        assert_eq!(
15912            fast.columns.get("id").unwrap().values(),
15913            &[
15914                Scalar::Int64(0),
15915                Scalar::Int64(0),
15916                Scalar::Int64(0),
15917                Scalar::Int64(0),
15918                Scalar::Int64(1),
15919                Scalar::Int64(1),
15920                Scalar::Int64(2),
15921                Scalar::Int64(2),
15922            ]
15923        );
15924        assert_eq!(
15925            fast.columns.get("v").unwrap().values(),
15926            &[
15927                Scalar::Int64(10),
15928                Scalar::Int64(10),
15929                Scalar::Int64(11),
15930                Scalar::Int64(11),
15931                Scalar::Int64(20),
15932                Scalar::Int64(21),
15933                Scalar::Int64(30),
15934                Scalar::Int64(30),
15935            ]
15936        );
15937        assert_eq!(
15938            fast.columns.get("w").unwrap().values(),
15939            &[
15940                Scalar::Int64(100),
15941                Scalar::Int64(101),
15942                Scalar::Int64(100),
15943                Scalar::Int64(101),
15944                Scalar::Int64(200),
15945                Scalar::Int64(200),
15946                Scalar::Int64(300),
15947                Scalar::Int64(301),
15948            ]
15949        );
15950    }
15951
15952    #[test]
15953    fn merge_outer_ordered_unique_int64_subset_matches_generic_validated_route() {
15954        let left = DataFrame::from_dict(
15955            &["id", "v"],
15956            vec![
15957                (
15958                    "id",
15959                    vec![Scalar::Int64(0), Scalar::Int64(1), Scalar::Int64(3)],
15960                ),
15961                (
15962                    "v",
15963                    vec![Scalar::Int64(10), Scalar::Int64(11), Scalar::Int64(13)],
15964                ),
15965            ],
15966        )
15967        .unwrap();
15968        let right = DataFrame::from_dict(
15969            &["id", "w"],
15970            vec![
15971                (
15972                    "id",
15973                    vec![
15974                        Scalar::Int64(0),
15975                        Scalar::Int64(2),
15976                        Scalar::Int64(3),
15977                        Scalar::Int64(5),
15978                    ],
15979                ),
15980                (
15981                    "w",
15982                    vec![
15983                        Scalar::Int64(100),
15984                        Scalar::Int64(200),
15985                        Scalar::Int64(300),
15986                        Scalar::Int64(500),
15987                    ],
15988                ),
15989            ],
15990        )
15991        .unwrap();
15992
15993        let fast = merge_dataframes(&left, &right, "id", JoinType::Outer).unwrap();
15994        let generic = merge_dataframes_on_with_options(
15995            &left,
15996            &right,
15997            &["id"],
15998            &["id"],
15999            JoinType::Outer,
16000            MergeExecutionOptions {
16001                validate_mode: Some(MergeValidateMode::OneToOne),
16002                ..MergeExecutionOptions::default()
16003            },
16004        )
16005        .unwrap();
16006
16007        assert_eq!(fast.index, generic.index);
16008        assert_eq!(fast.column_order, generic.column_order);
16009        assert_eq!(fast.columns, generic.columns);
16010        assert_eq!(
16011            fast.columns.get("id").unwrap().values(),
16012            &[
16013                Scalar::Int64(0),
16014                Scalar::Int64(1),
16015                Scalar::Int64(2),
16016                Scalar::Int64(3),
16017                Scalar::Int64(5)
16018            ]
16019        );
16020        let left_values = fast.columns.get("v").unwrap().values();
16021        assert_eq!(left_values[0], Scalar::Float64(10.0));
16022        assert_eq!(left_values[1], Scalar::Float64(11.0));
16023        assert!(left_values[2].is_missing());
16024        assert_eq!(left_values[3], Scalar::Float64(13.0));
16025        assert!(left_values[4].is_missing());
16026        let right_values = fast.columns.get("w").unwrap().values();
16027        assert_eq!(right_values[0], Scalar::Float64(100.0));
16028        assert!(right_values[1].is_missing());
16029        assert_eq!(right_values[2], Scalar::Float64(200.0));
16030        assert_eq!(right_values[3], Scalar::Float64(300.0));
16031        assert_eq!(right_values[4], Scalar::Float64(500.0));
16032    }
16033
16034    #[test]
16035    fn merge_outer_dense_int64_duplicates_matches_generic_validated_route() {
16036        let left = DataFrame::from_dict(
16037            &["id", "v"],
16038            vec![
16039                (
16040                    "id",
16041                    vec![
16042                        Scalar::Int64(2),
16043                        Scalar::Int64(0),
16044                        Scalar::Int64(2),
16045                        Scalar::Int64(1),
16046                        Scalar::Int64(5),
16047                    ],
16048                ),
16049                (
16050                    "v",
16051                    vec![
16052                        Scalar::Int64(10),
16053                        Scalar::Int64(11),
16054                        Scalar::Int64(12),
16055                        Scalar::Int64(13),
16056                        Scalar::Int64(15),
16057                    ],
16058                ),
16059            ],
16060        )
16061        .unwrap();
16062        let right = DataFrame::from_dict(
16063            &["id", "w"],
16064            vec![
16065                (
16066                    "id",
16067                    vec![
16068                        Scalar::Int64(2),
16069                        Scalar::Int64(2),
16070                        Scalar::Int64(3),
16071                        Scalar::Int64(0),
16072                    ],
16073                ),
16074                (
16075                    "w",
16076                    vec![
16077                        Scalar::Int64(200),
16078                        Scalar::Int64(201),
16079                        Scalar::Int64(300),
16080                        Scalar::Int64(400),
16081                    ],
16082                ),
16083            ],
16084        )
16085        .unwrap();
16086
16087        let fast = merge_dataframes(&left, &right, "id", JoinType::Outer).unwrap();
16088        let generic = merge_dataframes_on_with_options(
16089            &left,
16090            &right,
16091            &["id"],
16092            &["id"],
16093            JoinType::Outer,
16094            MergeExecutionOptions {
16095                validate_mode: Some(MergeValidateMode::ManyToMany),
16096                ..MergeExecutionOptions::default()
16097            },
16098        )
16099        .unwrap();
16100
16101        assert_eq!(fast.index, generic.index);
16102        assert_eq!(fast.column_order, generic.column_order);
16103        assert_eq!(fast.columns, generic.columns);
16104        assert_eq!(
16105            fast.columns.get("id").unwrap().values(),
16106            &[
16107                Scalar::Int64(0),
16108                Scalar::Int64(1),
16109                Scalar::Int64(2),
16110                Scalar::Int64(2),
16111                Scalar::Int64(2),
16112                Scalar::Int64(2),
16113                Scalar::Int64(3),
16114                Scalar::Int64(5),
16115            ]
16116        );
16117        let left_values = fast.columns.get("v").unwrap().values();
16118        assert_eq!(left_values[0], Scalar::Float64(11.0));
16119        assert_eq!(left_values[1], Scalar::Float64(13.0));
16120        assert_eq!(left_values[2], Scalar::Float64(10.0));
16121        assert_eq!(left_values[5], Scalar::Float64(12.0));
16122        assert!(left_values[6].is_missing());
16123        assert_eq!(left_values[7], Scalar::Float64(15.0));
16124        let right_values = fast.columns.get("w").unwrap().values();
16125        assert_eq!(right_values[0], Scalar::Float64(400.0));
16126        assert!(right_values[1].is_missing());
16127        assert_eq!(right_values[2], Scalar::Float64(200.0));
16128        assert_eq!(right_values[3], Scalar::Float64(201.0));
16129        assert!(right_values[7].is_missing());
16130    }
16131
16132    #[test]
16133    fn merge_outer_all_matched_dense_int64_duplicates_matches_generic_validated_route() {
16134        let left = DataFrame::from_dict(
16135            &["id", "v"],
16136            vec![
16137                (
16138                    "id",
16139                    vec![
16140                        Scalar::Int64(2),
16141                        Scalar::Int64(1),
16142                        Scalar::Int64(2),
16143                        Scalar::Int64(1),
16144                    ],
16145                ),
16146                (
16147                    "v",
16148                    vec![
16149                        Scalar::Int64(20),
16150                        Scalar::Int64(10),
16151                        Scalar::Int64(21),
16152                        Scalar::Int64(11),
16153                    ],
16154                ),
16155            ],
16156        )
16157        .unwrap();
16158        let right = DataFrame::from_dict(
16159            &["id", "w"],
16160            vec![
16161                (
16162                    "id",
16163                    vec![
16164                        Scalar::Int64(1),
16165                        Scalar::Int64(2),
16166                        Scalar::Int64(1),
16167                        Scalar::Int64(2),
16168                    ],
16169                ),
16170                (
16171                    "w",
16172                    vec![
16173                        Scalar::Int64(100),
16174                        Scalar::Int64(200),
16175                        Scalar::Int64(101),
16176                        Scalar::Int64(201),
16177                    ],
16178                ),
16179            ],
16180        )
16181        .unwrap();
16182
16183        let fast = merge_dataframes(&left, &right, "id", JoinType::Outer).unwrap();
16184        let generic = merge_dataframes_on_with_options(
16185            &left,
16186            &right,
16187            &["id"],
16188            &["id"],
16189            JoinType::Outer,
16190            MergeExecutionOptions {
16191                validate_mode: Some(MergeValidateMode::ManyToMany),
16192                ..MergeExecutionOptions::default()
16193            },
16194        )
16195        .unwrap();
16196
16197        assert_eq!(fast.index, generic.index);
16198        assert_eq!(fast.column_order, generic.column_order);
16199        assert_eq!(fast.columns, generic.columns);
16200        assert_eq!(
16201            generic.columns.get("id").unwrap().values(),
16202            &[
16203                Scalar::Int64(1),
16204                Scalar::Int64(1),
16205                Scalar::Int64(1),
16206                Scalar::Int64(1),
16207                Scalar::Int64(2),
16208                Scalar::Int64(2),
16209                Scalar::Int64(2),
16210                Scalar::Int64(2),
16211            ]
16212        );
16213        assert!(
16214            generic
16215                .columns
16216                .values()
16217                .all(|column| column.as_i64_slice().is_some())
16218        );
16219    }
16220
16221    #[test]
16222    fn merge_outer_all_matched_dense_int64_fused_output_matches_sorted_generic_route() {
16223        let left = DataFrame::from_dict(
16224            &["id", "v"],
16225            vec![
16226                (
16227                    "id",
16228                    vec![
16229                        Scalar::Int64(2),
16230                        Scalar::Int64(1),
16231                        Scalar::Int64(2),
16232                        Scalar::Int64(1),
16233                    ],
16234                ),
16235                (
16236                    "v",
16237                    vec![
16238                        Scalar::Int64(20),
16239                        Scalar::Int64(10),
16240                        Scalar::Int64(21),
16241                        Scalar::Int64(11),
16242                    ],
16243                ),
16244            ],
16245        )
16246        .unwrap();
16247        let right = DataFrame::from_dict(
16248            &["id", "w"],
16249            vec![
16250                (
16251                    "id",
16252                    vec![
16253                        Scalar::Int64(1),
16254                        Scalar::Int64(2),
16255                        Scalar::Int64(1),
16256                        Scalar::Int64(2),
16257                    ],
16258                ),
16259                (
16260                    "w",
16261                    vec![
16262                        Scalar::Int64(100),
16263                        Scalar::Int64(200),
16264                        Scalar::Int64(101),
16265                        Scalar::Int64(201),
16266                    ],
16267                ),
16268            ],
16269        )
16270        .unwrap();
16271
16272        let fused = merge_dataframes(&left, &right, "id", JoinType::Outer).unwrap();
16273        let generic = merge_dataframes_on_with_options(
16274            &left,
16275            &right,
16276            &["id"],
16277            &["id"],
16278            JoinType::Outer,
16279            MergeExecutionOptions {
16280                validate_mode: Some(MergeValidateMode::ManyToMany),
16281                sort: true,
16282                ..MergeExecutionOptions::default()
16283            },
16284        )
16285        .unwrap();
16286
16287        assert_eq!(fused.index, generic.index);
16288        assert_eq!(fused.column_order, generic.column_order);
16289        assert_eq!(fused.columns, generic.columns);
16290    }
16291
16292    #[test]
16293    fn merge_left_contiguous_utf8_duplicates_matches_sorted_generic_route() {
16294        let s = |v: &str| Scalar::Utf8(v.to_owned());
16295        let left = DataFrame::from_dict(
16296            &["id", "v"],
16297            vec![
16298                ("id", vec![s("a"), s("a"), s("b"), s("c")]),
16299                (
16300                    "v",
16301                    vec![
16302                        Scalar::Int64(10),
16303                        Scalar::Int64(11),
16304                        Scalar::Int64(20),
16305                        Scalar::Int64(30),
16306                    ],
16307                ),
16308            ],
16309        )
16310        .unwrap();
16311        let right = DataFrame::from_dict(
16312            &["id", "w"],
16313            vec![
16314                ("id", vec![s("a"), s("a"), s("c")]),
16315                (
16316                    "w",
16317                    vec![Scalar::Int64(100), Scalar::Int64(101), Scalar::Int64(300)],
16318                ),
16319            ],
16320        )
16321        .unwrap();
16322
16323        let fast = merge_dataframes(&left, &right, "id", JoinType::Left).unwrap();
16324        let generic = merge_dataframes_on_with_options(
16325            &left,
16326            &right,
16327            &["id"],
16328            &["id"],
16329            JoinType::Left,
16330            MergeExecutionOptions {
16331                sort: true,
16332                ..MergeExecutionOptions::default()
16333            },
16334        )
16335        .unwrap();
16336
16337        assert_eq!(fast.index, generic.index);
16338        assert_eq!(fast.column_order, generic.column_order);
16339        assert_eq!(fast.columns, generic.columns);
16340        assert_eq!(
16341            fast.columns.get("id").unwrap().values(),
16342            &[s("a"), s("a"), s("a"), s("a"), s("b"), s("c")]
16343        );
16344        assert!(fast.columns.get("w").unwrap().values()[4].is_missing());
16345    }
16346
16347    #[test]
16348    fn merge_outer_contiguous_utf8_duplicates_matches_sorted_generic_route() {
16349        let s = |v: &str| Scalar::Utf8(v.to_owned());
16350        let left = DataFrame::from_dict(
16351            &["id", "v"],
16352            vec![
16353                ("id", vec![s("a"), s("a"), s("b"), s("d")]),
16354                (
16355                    "v",
16356                    vec![
16357                        Scalar::Int64(10),
16358                        Scalar::Int64(11),
16359                        Scalar::Int64(20),
16360                        Scalar::Int64(40),
16361                    ],
16362                ),
16363            ],
16364        )
16365        .unwrap();
16366        let right = DataFrame::from_dict(
16367            &["id", "w"],
16368            vec![
16369                ("id", vec![s("a"), s("c"), s("a")]),
16370                (
16371                    "w",
16372                    vec![Scalar::Int64(100), Scalar::Int64(300), Scalar::Int64(101)],
16373                ),
16374            ],
16375        )
16376        .unwrap();
16377
16378        let fast = merge_dataframes(&left, &right, "id", JoinType::Outer).unwrap();
16379        let generic = merge_dataframes_on_with_options(
16380            &left,
16381            &right,
16382            &["id"],
16383            &["id"],
16384            JoinType::Outer,
16385            MergeExecutionOptions {
16386                sort: true,
16387                ..MergeExecutionOptions::default()
16388            },
16389        )
16390        .unwrap();
16391
16392        assert_eq!(fast.index, generic.index);
16393        assert_eq!(fast.column_order, generic.column_order);
16394        assert_eq!(fast.columns, generic.columns);
16395        assert_eq!(
16396            fast.columns.get("id").unwrap().values(),
16397            &[s("a"), s("a"), s("a"), s("a"), s("b"), s("c"), s("d")]
16398        );
16399        assert!(fast.columns.get("v").unwrap().values()[5].is_missing());
16400        assert!(fast.columns.get("w").unwrap().values()[4].is_missing());
16401        assert!(fast.columns.get("w").unwrap().values()[6].is_missing());
16402    }
16403
16404    #[test]
16405    fn merge_outer_fixed_decimal_utf8_all_matched_fuses_sorted_output_wikcu() {
16406        let s = |v: &str| Scalar::Utf8(v.to_owned());
16407        let left = DataFrame::from_dict(
16408            &["id", "lv"],
16409            vec![
16410                (
16411                    "id",
16412                    vec![
16413                        s("k00000002"),
16414                        s("k00000000"),
16415                        s("k00000002"),
16416                        s("k00000001"),
16417                    ],
16418                ),
16419                (
16420                    "lv",
16421                    vec![
16422                        Scalar::Float64(20.0),
16423                        Scalar::Float64(0.0),
16424                        Scalar::Float64(21.0),
16425                        Scalar::Float64(10.0),
16426                    ],
16427                ),
16428            ],
16429        )
16430        .unwrap();
16431        let right = DataFrame::from_dict(
16432            &["id", "rv"],
16433            vec![
16434                ("id", vec![s("k00000000"), s("k00000001"), s("k00000002")]),
16435                (
16436                    "rv",
16437                    vec![
16438                        Scalar::Float64(100.0),
16439                        Scalar::Float64(110.0),
16440                        Scalar::Float64(120.0),
16441                    ],
16442                ),
16443            ],
16444        )
16445        .unwrap();
16446
16447        let fast = merge_dataframes(&left, &right, "id", JoinType::Outer).unwrap();
16448        let generic = merge_dataframes_on_with_options(
16449            &left,
16450            &right,
16451            &["id"],
16452            &["id"],
16453            JoinType::Outer,
16454            MergeExecutionOptions {
16455                sort: true,
16456                ..MergeExecutionOptions::default()
16457            },
16458        )
16459        .unwrap();
16460
16461        assert_eq!(fast.index, generic.index);
16462        assert_eq!(fast.column_order, generic.column_order);
16463        assert_eq!(fast.columns, generic.columns);
16464        assert_eq!(
16465            fast.columns.get("id").unwrap().values(),
16466            &[
16467                s("k00000000"),
16468                s("k00000001"),
16469                s("k00000002"),
16470                s("k00000002")
16471            ]
16472        );
16473        assert_eq!(
16474            fast.columns.get("lv").unwrap().values(),
16475            &[
16476                Scalar::Float64(0.0),
16477                Scalar::Float64(10.0),
16478                Scalar::Float64(20.0),
16479                Scalar::Float64(21.0),
16480            ]
16481        );
16482    }
16483
16484    #[test]
16485    fn merge_right_dense_int64_duplicates_matches_generic_validated_route() {
16486        let left = DataFrame::from_dict(
16487            &["id", "v"],
16488            vec![
16489                (
16490                    "id",
16491                    vec![
16492                        Scalar::Int64(2),
16493                        Scalar::Int64(0),
16494                        Scalar::Int64(2),
16495                        Scalar::Int64(1),
16496                        Scalar::Int64(5),
16497                    ],
16498                ),
16499                (
16500                    "v",
16501                    vec![
16502                        Scalar::Int64(10),
16503                        Scalar::Int64(11),
16504                        Scalar::Int64(12),
16505                        Scalar::Int64(13),
16506                        Scalar::Int64(15),
16507                    ],
16508                ),
16509            ],
16510        )
16511        .unwrap();
16512        let right = DataFrame::from_dict(
16513            &["id", "w"],
16514            vec![
16515                (
16516                    "id",
16517                    vec![
16518                        Scalar::Int64(2),
16519                        Scalar::Int64(2),
16520                        Scalar::Int64(3),
16521                        Scalar::Int64(0),
16522                    ],
16523                ),
16524                (
16525                    "w",
16526                    vec![
16527                        Scalar::Int64(200),
16528                        Scalar::Int64(201),
16529                        Scalar::Int64(300),
16530                        Scalar::Int64(400),
16531                    ],
16532                ),
16533            ],
16534        )
16535        .unwrap();
16536
16537        let fast = merge_dataframes(&left, &right, "id", JoinType::Right).unwrap();
16538        let generic = merge_dataframes_on_with_options(
16539            &left,
16540            &right,
16541            &["id"],
16542            &["id"],
16543            JoinType::Right,
16544            MergeExecutionOptions {
16545                validate_mode: Some(MergeValidateMode::ManyToMany),
16546                ..MergeExecutionOptions::default()
16547            },
16548        )
16549        .unwrap();
16550
16551        assert_eq!(fast.index, generic.index);
16552        assert_eq!(fast.column_order, generic.column_order);
16553        assert_eq!(fast.columns, generic.columns);
16554        assert_eq!(
16555            fast.columns.get("id").unwrap().values(),
16556            &[
16557                Scalar::Int64(2),
16558                Scalar::Int64(2),
16559                Scalar::Int64(2),
16560                Scalar::Int64(2),
16561                Scalar::Int64(3),
16562                Scalar::Int64(0),
16563            ]
16564        );
16565        let left_values = fast.columns.get("v").unwrap().values();
16566        assert_eq!(left_values[0], Scalar::Float64(10.0));
16567        assert_eq!(left_values[1], Scalar::Float64(12.0));
16568        assert_eq!(left_values[2], Scalar::Float64(10.0));
16569        assert_eq!(left_values[3], Scalar::Float64(12.0));
16570        assert!(left_values[4].is_missing());
16571        assert_eq!(left_values[5], Scalar::Float64(11.0));
16572        let right_values = fast.columns.get("w").unwrap().values();
16573        assert_eq!(right_values[0], Scalar::Int64(200));
16574        assert_eq!(right_values[1], Scalar::Int64(200));
16575        assert_eq!(right_values[2], Scalar::Int64(201));
16576        assert_eq!(right_values[3], Scalar::Int64(201));
16577        assert_eq!(right_values[4], Scalar::Int64(300));
16578        assert_eq!(right_values[5], Scalar::Int64(400));
16579    }
16580
16581    #[test]
16582    fn merge_right_dense_cycle_probe_declines_invented_gaps_66wab() {
16583        let left = DataFrame::from_dict(
16584            &["id", "v"],
16585            vec![
16586                (
16587                    "id",
16588                    vec![
16589                        Scalar::Int64(1),
16590                        Scalar::Int64(2),
16591                        Scalar::Int64(1),
16592                        Scalar::Int64(2),
16593                    ],
16594                ),
16595                (
16596                    "v",
16597                    vec![
16598                        Scalar::Int64(100),
16599                        Scalar::Int64(200),
16600                        Scalar::Int64(101),
16601                        Scalar::Int64(201),
16602                    ],
16603                ),
16604            ],
16605        )
16606        .unwrap();
16607        let right = DataFrame::from_dict(
16608            &["id", "w"],
16609            vec![
16610                (
16611                    "id",
16612                    vec![
16613                        Scalar::Int64(0),
16614                        Scalar::Int64(1),
16615                        Scalar::Int64(2),
16616                        Scalar::Int64(0),
16617                        Scalar::Int64(1),
16618                    ],
16619                ),
16620                (
16621                    "w",
16622                    vec![
16623                        Scalar::Int64(10),
16624                        Scalar::Int64(11),
16625                        Scalar::Int64(12),
16626                        Scalar::Int64(13),
16627                        Scalar::Int64(14),
16628                    ],
16629                ),
16630            ],
16631        )
16632        .unwrap();
16633        let left_key = left.columns().get("id").unwrap();
16634        let right_key = right.columns().get("id").unwrap();
16635        assert!(left_key.int64_dense_cycle_witness().is_some());
16636        assert!(right_key.int64_dense_cycle_witness().is_some());
16637        let suffixes = resolve_merge_suffixes(None);
16638
16639        let fused = build_single_key_dense_i64_right_merge_output(
16640            &left,
16641            &right,
16642            &["id"],
16643            &["id"],
16644            left_key,
16645            right_key,
16646            &suffixes,
16647        )
16648        .unwrap();
16649        assert!(fused.is_none());
16650    }
16651
16652    #[test]
16653    fn merge_left_right_all_matched_dense_int64_duplicates_match_generic_validated_route() {
16654        let left = DataFrame::from_dict(
16655            &["id", "v"],
16656            vec![
16657                (
16658                    "id",
16659                    vec![
16660                        Scalar::Int64(2),
16661                        Scalar::Int64(1),
16662                        Scalar::Int64(2),
16663                        Scalar::Int64(1),
16664                    ],
16665                ),
16666                (
16667                    "v",
16668                    vec![
16669                        Scalar::Int64(20),
16670                        Scalar::Int64(10),
16671                        Scalar::Int64(21),
16672                        Scalar::Int64(11),
16673                    ],
16674                ),
16675            ],
16676        )
16677        .unwrap();
16678        let right = DataFrame::from_dict(
16679            &["id", "w"],
16680            vec![
16681                (
16682                    "id",
16683                    vec![
16684                        Scalar::Int64(1),
16685                        Scalar::Int64(2),
16686                        Scalar::Int64(1),
16687                        Scalar::Int64(2),
16688                    ],
16689                ),
16690                (
16691                    "w",
16692                    vec![
16693                        Scalar::Int64(100),
16694                        Scalar::Int64(200),
16695                        Scalar::Int64(101),
16696                        Scalar::Int64(201),
16697                    ],
16698                ),
16699            ],
16700        )
16701        .unwrap();
16702
16703        for join_type in [JoinType::Left, JoinType::Right] {
16704            let fast = merge_dataframes(&left, &right, "id", join_type).unwrap();
16705            let generic = merge_dataframes_on_with_options(
16706                &left,
16707                &right,
16708                &["id"],
16709                &["id"],
16710                join_type,
16711                MergeExecutionOptions {
16712                    validate_mode: Some(MergeValidateMode::ManyToMany),
16713                    ..MergeExecutionOptions::default()
16714                },
16715            )
16716            .unwrap();
16717
16718            assert_eq!(fast.index, generic.index);
16719            assert_eq!(fast.column_order, generic.column_order);
16720            assert_eq!(fast.columns, generic.columns);
16721            assert!(
16722                generic
16723                    .columns
16724                    .values()
16725                    .all(|column| column.as_i64_slice().is_some())
16726            );
16727        }
16728    }
16729
16730    #[test]
16731    fn merge_right_all_matched_dense_int64_fused_output_matches_dense_materialization() {
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::Right).unwrap();
16782        let left_key = left.columns().get("id").unwrap();
16783        let right_key = right.columns().get("id").unwrap();
16784        let (left_positions, right_positions) =
16785            dense_int64_right_positions(left_key, right_key).unwrap();
16786        let suffixes = resolve_merge_suffixes(None);
16787        let materialized = build_single_key_dense_right_merge_output(
16788            &left,
16789            &right,
16790            &["id"],
16791            &["id"],
16792            &left_positions,
16793            &right_positions,
16794            &suffixes,
16795        )
16796        .unwrap();
16797
16798        assert_eq!(fused.index, materialized.index);
16799        assert_eq!(fused.column_order, materialized.column_order);
16800        assert_eq!(fused.columns, materialized.columns);
16801        assert_eq!(
16802            fused.columns.get("id").unwrap().values(),
16803            &[
16804                Scalar::Int64(1),
16805                Scalar::Int64(1),
16806                Scalar::Int64(2),
16807                Scalar::Int64(2),
16808                Scalar::Int64(1),
16809                Scalar::Int64(1),
16810                Scalar::Int64(2),
16811                Scalar::Int64(2),
16812            ]
16813        );
16814        assert!(
16815            fused
16816                .columns
16817                .values()
16818                .all(|column| column.as_i64_slice().is_some())
16819        );
16820    }
16821
16822    #[test]
16823    fn merge_right_ordered_unique_int64_subset_matches_generic_validated_route() {
16824        let left = DataFrame::from_dict(
16825            &["id", "v"],
16826            vec![
16827                (
16828                    "id",
16829                    vec![Scalar::Int64(0), Scalar::Int64(1), Scalar::Int64(3)],
16830                ),
16831                (
16832                    "v",
16833                    vec![Scalar::Int64(10), Scalar::Int64(11), Scalar::Int64(13)],
16834                ),
16835            ],
16836        )
16837        .unwrap();
16838        let right = DataFrame::from_dict(
16839            &["id", "w"],
16840            vec![
16841                (
16842                    "id",
16843                    vec![
16844                        Scalar::Int64(0),
16845                        Scalar::Int64(2),
16846                        Scalar::Int64(3),
16847                        Scalar::Int64(5),
16848                    ],
16849                ),
16850                (
16851                    "w",
16852                    vec![
16853                        Scalar::Int64(100),
16854                        Scalar::Int64(200),
16855                        Scalar::Int64(300),
16856                        Scalar::Int64(500),
16857                    ],
16858                ),
16859            ],
16860        )
16861        .unwrap();
16862
16863        let fast = merge_dataframes(&left, &right, "id", JoinType::Right).unwrap();
16864        let generic = merge_dataframes_on_with_options(
16865            &left,
16866            &right,
16867            &["id"],
16868            &["id"],
16869            JoinType::Right,
16870            MergeExecutionOptions {
16871                validate_mode: Some(MergeValidateMode::OneToOne),
16872                ..MergeExecutionOptions::default()
16873            },
16874        )
16875        .unwrap();
16876
16877        assert_eq!(fast.index, generic.index);
16878        assert_eq!(fast.column_order, generic.column_order);
16879        assert_eq!(fast.columns, generic.columns);
16880        assert_eq!(
16881            fast.columns.get("id").unwrap().values(),
16882            &[
16883                Scalar::Int64(0),
16884                Scalar::Int64(2),
16885                Scalar::Int64(3),
16886                Scalar::Int64(5)
16887            ]
16888        );
16889        let left_values = fast.columns.get("v").unwrap().values();
16890        assert_eq!(left_values[0], Scalar::Float64(10.0));
16891        assert!(left_values[1].is_missing());
16892        assert_eq!(left_values[2], Scalar::Float64(13.0));
16893        assert!(left_values[3].is_missing());
16894        let right_values = fast.columns.get("w").unwrap().values();
16895        assert_eq!(right_values[0], Scalar::Int64(100));
16896        assert_eq!(right_values[1], Scalar::Int64(200));
16897        assert_eq!(right_values[2], Scalar::Int64(300));
16898        assert_eq!(right_values[3], Scalar::Int64(500));
16899    }
16900
16901    #[test]
16902    fn merge_right_preserves_all_right_rows() {
16903        let left = make_left_df();
16904        let right = make_right_df();
16905        let merged = merge_dataframes(&left, &right, "id", JoinType::Right).unwrap();
16906
16907        assert_eq!(merged.columns.get("id").unwrap().len(), 3);
16908        assert_eq!(
16909            merged.columns.get("val_b").unwrap().values(),
16910            &[Scalar::Int64(200), Scalar::Int64(300), Scalar::Int64(400)]
16911        );
16912        // val_a widens to Float64 because id=4 invents a missing value.
16913        assert_eq!(merged.columns.get("val_a").unwrap().dtype(), DType::Float64);
16914        assert_eq!(
16915            merged.columns.get("val_a").unwrap().values()[0],
16916            Scalar::Float64(20.0)
16917        );
16918        assert_eq!(
16919            merged.columns.get("val_a").unwrap().values()[1],
16920            Scalar::Float64(30.0)
16921        );
16922        assert_eq!(
16923            merged.columns.get("val_a").unwrap().values()[2],
16924            Scalar::Null(NullKind::NaN)
16925        );
16926    }
16927
16928    #[test]
16929    fn merge_outer_contains_all_rows() {
16930        let left = make_left_df();
16931        let right = make_right_df();
16932        let merged = merge_dataframes(&left, &right, "id", JoinType::Outer).unwrap();
16933
16934        // ids: 1, 2, 3 from left + 4 from right = 4 rows
16935        assert_eq!(merged.columns.get("id").unwrap().len(), 4);
16936    }
16937
16938    #[test]
16939    fn merge_inner_sort_false_preserves_left_key_order() {
16940        let left = DataFrame::from_dict(
16941            &["id", "left_v"],
16942            vec![
16943                (
16944                    "id",
16945                    vec![Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(2)],
16946                ),
16947                (
16948                    "left_v",
16949                    vec![Scalar::Int64(20), Scalar::Int64(10), Scalar::Int64(21)],
16950                ),
16951            ],
16952        )
16953        .expect("left");
16954        let right = DataFrame::from_dict(
16955            &["id", "right_v"],
16956            vec![
16957                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
16958                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
16959            ],
16960        )
16961        .expect("right");
16962
16963        let merged = merge_dataframes_on_with_options(
16964            &left,
16965            &right,
16966            &["id"],
16967            &["id"],
16968            JoinType::Inner,
16969            MergeExecutionOptions::default(),
16970        )
16971        .expect("merge");
16972        assert_eq!(
16973            merged.columns.get("id").expect("id").values(),
16974            &[Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(2)]
16975        );
16976        assert_eq!(
16977            merged.columns.get("left_v").expect("left_v").values(),
16978            &[Scalar::Int64(20), Scalar::Int64(10), Scalar::Int64(21)]
16979        );
16980        assert_eq!(
16981            merged.columns.get("right_v").expect("right_v").values(),
16982            &[Scalar::Int64(200), Scalar::Int64(100), Scalar::Int64(200)]
16983        );
16984    }
16985
16986    #[test]
16987    fn merge_inner_sort_true_orders_join_keys_lexicographically() {
16988        let left = DataFrame::from_dict(
16989            &["id", "left_v"],
16990            vec![
16991                (
16992                    "id",
16993                    vec![Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(2)],
16994                ),
16995                (
16996                    "left_v",
16997                    vec![Scalar::Int64(20), Scalar::Int64(10), Scalar::Int64(21)],
16998                ),
16999            ],
17000        )
17001        .expect("left");
17002        let right = DataFrame::from_dict(
17003            &["id", "right_v"],
17004            vec![
17005                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
17006                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
17007            ],
17008        )
17009        .expect("right");
17010
17011        let merged = merge_dataframes_on_with_options(
17012            &left,
17013            &right,
17014            &["id"],
17015            &["id"],
17016            JoinType::Inner,
17017            MergeExecutionOptions {
17018                sort: true,
17019                ..MergeExecutionOptions::default()
17020            },
17021        )
17022        .expect("merge");
17023        assert_eq!(
17024            merged.columns.get("id").expect("id").values(),
17025            &[Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(2)]
17026        );
17027        assert_eq!(
17028            merged.columns.get("left_v").expect("left_v").values(),
17029            &[Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(21)]
17030        );
17031        assert_eq!(
17032            merged.columns.get("right_v").expect("right_v").values(),
17033            &[Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(200)]
17034        );
17035    }
17036
17037    #[test]
17038    fn merge_inner_sort_true_orders_float_keys_numerically() {
17039        let left = DataFrame::from_dict(
17040            &["id", "left_v"],
17041            vec![
17042                (
17043                    "id",
17044                    vec![
17045                        Scalar::Float64(1.5),
17046                        Scalar::Float64(-2.5),
17047                        Scalar::Float64(0.25),
17048                    ],
17049                ),
17050                (
17051                    "left_v",
17052                    vec![Scalar::Int64(15), Scalar::Int64(-25), Scalar::Int64(2)],
17053                ),
17054            ],
17055        )
17056        .expect("left");
17057        let right = DataFrame::from_dict(
17058            &["id", "right_v"],
17059            vec![
17060                (
17061                    "id",
17062                    vec![
17063                        Scalar::Float64(-2.5),
17064                        Scalar::Float64(0.25),
17065                        Scalar::Float64(1.5),
17066                    ],
17067                ),
17068                (
17069                    "right_v",
17070                    vec![Scalar::Int64(250), Scalar::Int64(25), Scalar::Int64(150)],
17071                ),
17072            ],
17073        )
17074        .expect("right");
17075
17076        let merged = merge_dataframes_on_with_options(
17077            &left,
17078            &right,
17079            &["id"],
17080            &["id"],
17081            JoinType::Inner,
17082            MergeExecutionOptions {
17083                sort: true,
17084                ..MergeExecutionOptions::default()
17085            },
17086        )
17087        .expect("merge");
17088
17089        assert_eq!(
17090            merged.columns.get("id").expect("id").values(),
17091            &[
17092                Scalar::Float64(-2.5),
17093                Scalar::Float64(0.25),
17094                Scalar::Float64(1.5)
17095            ]
17096        );
17097        assert_eq!(
17098            merged.columns.get("left_v").expect("left_v").values(),
17099            &[Scalar::Int64(-25), Scalar::Int64(2), Scalar::Int64(15)]
17100        );
17101        assert_eq!(
17102            merged.columns.get("right_v").expect("right_v").values(),
17103            &[Scalar::Int64(250), Scalar::Int64(25), Scalar::Int64(150)]
17104        );
17105    }
17106
17107    #[test]
17108    fn merge_right_sort_true_orders_join_keys_lexicographically() {
17109        let left = DataFrame::from_dict(
17110            &["id", "left_v"],
17111            vec![
17112                ("id", vec![Scalar::Int64(3), Scalar::Int64(1)]),
17113                ("left_v", vec![Scalar::Int64(30), Scalar::Int64(10)]),
17114            ],
17115        )
17116        .expect("left");
17117        let right = DataFrame::from_dict(
17118            &["id", "right_v"],
17119            vec![
17120                (
17121                    "id",
17122                    vec![Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(3)],
17123                ),
17124                (
17125                    "right_v",
17126                    vec![Scalar::Int64(200), Scalar::Int64(100), Scalar::Int64(300)],
17127                ),
17128            ],
17129        )
17130        .expect("right");
17131
17132        let merged = merge_dataframes_on_with_options(
17133            &left,
17134            &right,
17135            &["id"],
17136            &["id"],
17137            JoinType::Right,
17138            MergeExecutionOptions {
17139                sort: true,
17140                ..MergeExecutionOptions::default()
17141            },
17142        )
17143        .expect("merge");
17144        assert_eq!(
17145            merged.columns.get("id").expect("id").values(),
17146            &[Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)]
17147        );
17148        assert_eq!(
17149            merged.columns.get("left_v").expect("left_v").values(),
17150            &[
17151                Scalar::Float64(10.0),
17152                Scalar::Null(NullKind::NaN),
17153                Scalar::Float64(30.0)
17154            ]
17155        );
17156        assert_eq!(
17157            merged.columns.get("right_v").expect("right_v").values(),
17158            &[Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(300)]
17159        );
17160    }
17161
17162    #[test]
17163    fn merge_column_name_conflict_adds_suffixes() {
17164        let left = DataFrame::from_dict(
17165            &["id", "val"],
17166            vec![
17167                ("id", vec![Scalar::Int64(1)]),
17168                ("val", vec![Scalar::Int64(10)]),
17169            ],
17170        )
17171        .unwrap();
17172        let right = DataFrame::from_dict(
17173            &["id", "val"],
17174            vec![
17175                ("id", vec![Scalar::Int64(1)]),
17176                ("val", vec![Scalar::Int64(99)]),
17177            ],
17178        )
17179        .unwrap();
17180
17181        let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
17182        assert!(merged.columns.contains_key("val_x"));
17183        assert!(merged.columns.contains_key("val_y"));
17184        assert_eq!(
17185            merged.columns.get("val_x").unwrap().values(),
17186            &[Scalar::Int64(10)]
17187        );
17188        assert_eq!(
17189            merged.columns.get("val_y").unwrap().values(),
17190            &[Scalar::Int64(99)]
17191        );
17192    }
17193
17194    #[test]
17195    fn merge_column_name_conflict_honors_custom_suffixes() {
17196        let left = DataFrame::from_dict(
17197            &["id", "val"],
17198            vec![
17199                ("id", vec![Scalar::Int64(1)]),
17200                ("val", vec![Scalar::Int64(10)]),
17201            ],
17202        )
17203        .expect("left");
17204        let right = DataFrame::from_dict(
17205            &["id", "val"],
17206            vec![
17207                ("id", vec![Scalar::Int64(1)]),
17208                ("val", vec![Scalar::Int64(99)]),
17209            ],
17210        )
17211        .expect("right");
17212
17213        let merged = merge_dataframes_on_with_options(
17214            &left,
17215            &right,
17216            &["id"],
17217            &["id"],
17218            JoinType::Inner,
17219            MergeExecutionOptions {
17220                suffixes: Some([Some("_L".to_owned()), Some("_R".to_owned())]),
17221                ..MergeExecutionOptions::default()
17222            },
17223        )
17224        .expect("merge");
17225        assert!(merged.columns.contains_key("val_L"));
17226        assert!(merged.columns.contains_key("val_R"));
17227        assert_eq!(
17228            merged.columns.get("val_L").expect("left suffixed").values(),
17229            &[Scalar::Int64(10)]
17230        );
17231        assert_eq!(
17232            merged
17233                .columns
17234                .get("val_R")
17235                .expect("right suffixed")
17236                .values(),
17237            &[Scalar::Int64(99)]
17238        );
17239    }
17240
17241    #[test]
17242    fn merge_column_name_conflict_allows_one_sided_suffix() {
17243        let left = DataFrame::from_dict(
17244            &["id", "val"],
17245            vec![
17246                ("id", vec![Scalar::Int64(1)]),
17247                ("val", vec![Scalar::Int64(10)]),
17248            ],
17249        )
17250        .expect("left");
17251        let right = DataFrame::from_dict(
17252            &["id", "val"],
17253            vec![
17254                ("id", vec![Scalar::Int64(1)]),
17255                ("val", vec![Scalar::Int64(99)]),
17256            ],
17257        )
17258        .expect("right");
17259
17260        let merged = merge_dataframes_on_with_options(
17261            &left,
17262            &right,
17263            &["id"],
17264            &["id"],
17265            JoinType::Inner,
17266            MergeExecutionOptions {
17267                suffixes: Some([None, Some("_r".to_owned())]),
17268                ..MergeExecutionOptions::default()
17269            },
17270        )
17271        .expect("merge");
17272        assert!(merged.columns.contains_key("val"));
17273        assert!(merged.columns.contains_key("val_r"));
17274        assert_eq!(
17275            merged.columns.get("val").expect("left unsuffixed").values(),
17276            &[Scalar::Int64(10)]
17277        );
17278        assert_eq!(
17279            merged
17280                .columns
17281                .get("val_r")
17282                .expect("right suffixed")
17283                .values(),
17284            &[Scalar::Int64(99)]
17285        );
17286    }
17287
17288    #[test]
17289    fn merge_column_name_conflict_rejects_missing_suffixes_for_overlap() {
17290        let left = DataFrame::from_dict(
17291            &["id", "val"],
17292            vec![
17293                ("id", vec![Scalar::Int64(1)]),
17294                ("val", vec![Scalar::Int64(10)]),
17295            ],
17296        )
17297        .expect("left");
17298        let right = DataFrame::from_dict(
17299            &["id", "val"],
17300            vec![
17301                ("id", vec![Scalar::Int64(1)]),
17302                ("val", vec![Scalar::Int64(99)]),
17303            ],
17304        )
17305        .expect("right");
17306
17307        let err = merge_dataframes_on_with_options(
17308            &left,
17309            &right,
17310            &["id"],
17311            &["id"],
17312            JoinType::Inner,
17313            MergeExecutionOptions {
17314                suffixes: Some([Some(String::new()), Some(String::new())]),
17315                ..MergeExecutionOptions::default()
17316            },
17317        )
17318        .expect_err("merge should reject overlapping columns without suffixes");
17319        assert!(format!("{err}").contains("columns overlap but no suffix specified"));
17320    }
17321
17322    #[test]
17323    fn merge_column_name_conflict_rejects_duplicate_output_columns_from_suffixes() {
17324        let left = DataFrame::from_dict(
17325            &["id", "val", "val_L"],
17326            vec![
17327                ("id", vec![Scalar::Int64(1)]),
17328                ("val", vec![Scalar::Int64(10)]),
17329                ("val_L", vec![Scalar::Int64(77)]),
17330            ],
17331        )
17332        .expect("left");
17333        let right = DataFrame::from_dict(
17334            &["id", "val"],
17335            vec![
17336                ("id", vec![Scalar::Int64(1)]),
17337                ("val", vec![Scalar::Int64(99)]),
17338            ],
17339        )
17340        .expect("right");
17341
17342        let err = merge_dataframes_on_with_options(
17343            &left,
17344            &right,
17345            &["id"],
17346            &["id"],
17347            JoinType::Inner,
17348            MergeExecutionOptions {
17349                suffixes: Some([Some("_L".to_owned()), Some("_R".to_owned())]),
17350                ..MergeExecutionOptions::default()
17351            },
17352        )
17353        .expect_err("merge should reject duplicate output names caused by suffixes");
17354        assert!(format!("{err}").contains("duplicate output column"));
17355    }
17356
17357    #[test]
17358    fn merge_missing_key_column_errors() {
17359        let left = make_left_df();
17360        let right = make_right_df();
17361        let err = merge_dataframes(&left, &right, "nonexistent", JoinType::Inner)
17362            .expect_err("should fail");
17363        assert!(format!("{err}").contains("nonexistent"));
17364    }
17365
17366    #[test]
17367    fn merge_duplicate_keys_multiply_cardinality() {
17368        let left = DataFrame::from_dict(
17369            &["id", "a"],
17370            vec![
17371                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
17372                ("a", vec![Scalar::Int64(10), Scalar::Int64(20)]),
17373            ],
17374        )
17375        .unwrap();
17376        let right = DataFrame::from_dict(
17377            &["id", "b"],
17378            vec![
17379                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
17380                ("b", vec![Scalar::Int64(100), Scalar::Int64(200)]),
17381            ],
17382        )
17383        .unwrap();
17384
17385        let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
17386        // 2 left × 2 right = 4 rows
17387        assert_eq!(merged.columns.get("id").unwrap().len(), 4);
17388    }
17389
17390    #[test]
17391    fn ordered_identity_int64_guard_uses_strict_unique_certificate() {
17392        let left = fp_columnar::Column::from_i64_values(vec![1, 2, 3, 4]);
17393        let right = fp_columnar::Column::from_i64_values(vec![1, 2, 3, 4]);
17394        assert!(ordered_identity_int64_keys_match(&left, &right));
17395
17396        let duplicate_left = fp_columnar::Column::from_i64_values(vec![1, 1, 2]);
17397        let duplicate_right = fp_columnar::Column::from_i64_values(vec![1, 1, 2]);
17398        assert!(!ordered_identity_int64_keys_match(
17399            &duplicate_left,
17400            &duplicate_right
17401        ));
17402
17403        let unsorted_left = fp_columnar::Column::from_i64_values(vec![2, 1, 3]);
17404        let unsorted_right = fp_columnar::Column::from_i64_values(vec![2, 1, 3]);
17405        assert!(ordered_identity_int64_keys_match(
17406            &unsorted_left,
17407            &unsorted_right
17408        ));
17409    }
17410
17411    #[test]
17412    fn affine_i64_inner_plan_solves_nontrivial_stride_intersection() {
17413        let left = super::PositiveAffineI64Witness {
17414            start: -3,
17415            step: 4,
17416            len: 8,
17417        };
17418        let right = super::PositiveAffineI64Witness {
17419            start: 1,
17420            step: 6,
17421            len: 6,
17422        };
17423        assert_eq!(
17424            super::affine_i64_inner_position_plan(left, right),
17425            Some(super::AffineInnerPositionPlan {
17426                left_start: 1,
17427                left_step: 3,
17428                right_start: 0,
17429                right_step: 2,
17430                len: 3,
17431            })
17432        );
17433    }
17434
17435    #[test]
17436    fn affine_i64_inner_plan_matches_brute_force_small_domain() {
17437        const LENGTHS: [usize; 4] = [2, 3, 7, 11];
17438        for left_start in -8i128..=8 {
17439            for right_start in -8i128..=8 {
17440                for left_step in 1i128..=7 {
17441                    for right_step in 1i128..=7 {
17442                        for left_len in LENGTHS {
17443                            for right_len in LENGTHS {
17444                                let left = super::PositiveAffineI64Witness {
17445                                    start: left_start,
17446                                    step: left_step,
17447                                    len: left_len,
17448                                };
17449                                let right = super::PositiveAffineI64Witness {
17450                                    start: right_start,
17451                                    step: right_step,
17452                                    len: right_len,
17453                                };
17454                                let plan = super::affine_i64_inner_position_plan(left, right)
17455                                    .expect("small affine sequences cannot overflow");
17456                                let expected = (0..left_len)
17457                                    .flat_map(|left_row| {
17458                                        (0..right_len).filter_map(move |right_row| {
17459                                            let left_key = left_start
17460                                                + left_step * i128::try_from(left_row).unwrap();
17461                                            let right_key = right_start
17462                                                + right_step * i128::try_from(right_row).unwrap();
17463                                            (left_key == right_key).then_some((left_row, right_row))
17464                                        })
17465                                    })
17466                                    .collect::<Vec<_>>();
17467                                let actual = (0..plan.len)
17468                                    .map(|row| {
17469                                        (
17470                                            plan.left_start + row * plan.left_step,
17471                                            plan.right_start + row * plan.right_step,
17472                                        )
17473                                    })
17474                                    .collect::<Vec<_>>();
17475                                assert_eq!(actual, expected);
17476                            }
17477                        }
17478                    }
17479                }
17480            }
17481        }
17482    }
17483
17484    #[test]
17485    fn affine_i64_inner_merge_matches_left_major_values() {
17486        let left_keys = vec![-3, 1, 5, 9, 13, 17, 21, 25];
17487        let right_keys = vec![1, 7, 13, 19, 25, 31];
17488        let mut left_columns = std::collections::BTreeMap::new();
17489        left_columns.insert("id".to_owned(), Column::from_i64_values(left_keys));
17490        left_columns.insert(
17491            "left_value".to_owned(),
17492            Column::from_f64_values((0..8).map(|row| row as f64 + 0.5).collect()),
17493        );
17494        let left = DataFrame::new_with_column_order(
17495            Index::new_known_unique_int64_unit_range(0, 8),
17496            left_columns,
17497            vec!["id".to_owned(), "left_value".to_owned()],
17498        )
17499        .unwrap();
17500        let mut right_columns = std::collections::BTreeMap::new();
17501        right_columns.insert("id".to_owned(), Column::from_i64_values(right_keys));
17502        right_columns.insert(
17503            "right_value".to_owned(),
17504            Column::from_i64_values((100..106).collect()),
17505        );
17506        let right = DataFrame::new_with_column_order(
17507            Index::new_known_unique_int64_unit_range(0, 6),
17508            right_columns,
17509            vec!["id".to_owned(), "right_value".to_owned()],
17510        )
17511        .unwrap();
17512        let suffixes = resolve_merge_suffixes(None);
17513        let merged = super::build_single_key_affine_i64_inner_merge_output(
17514            &left,
17515            &right,
17516            &["id"],
17517            &["id"],
17518            left.columns().get("id").unwrap(),
17519            right.columns().get("id").unwrap(),
17520            &suffixes,
17521        )
17522        .unwrap()
17523        .expect("certified affine typed inputs must use the fast path");
17524
17525        assert_eq!(
17526            merged.columns.get("id").unwrap().values(),
17527            &[Scalar::Int64(1), Scalar::Int64(13), Scalar::Int64(25)]
17528        );
17529        assert_eq!(
17530            merged.columns.get("left_value").unwrap().values(),
17531            &[
17532                Scalar::Float64(1.5),
17533                Scalar::Float64(4.5),
17534                Scalar::Float64(7.5),
17535            ]
17536        );
17537        assert_eq!(
17538            merged.columns.get("right_value").unwrap().values(),
17539            &[Scalar::Int64(100), Scalar::Int64(102), Scalar::Int64(104)]
17540        );
17541    }
17542
17543    #[test]
17544    fn merge_identical_duplicate_keys_cross_join_values_jdupk() {
17545        // Identical left/right key columns that contain duplicates must NOT take
17546        // the identity 1:1 fast path: pandas cross-joins each duplicate, so a=10
17547        // and a=20 each pair with b=100 and b=200. (br-frankenpandas-jdupk)
17548        let left = DataFrame::from_dict(
17549            &["id", "a"],
17550            vec![
17551                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
17552                ("a", vec![Scalar::Int64(10), Scalar::Int64(20)]),
17553            ],
17554        )
17555        .unwrap();
17556        let right = DataFrame::from_dict(
17557            &["id", "b"],
17558            vec![
17559                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
17560                ("b", vec![Scalar::Int64(100), Scalar::Int64(200)]),
17561            ],
17562        )
17563        .unwrap();
17564
17565        let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
17566        assert_eq!(
17567            merged.columns.get("a").unwrap().values(),
17568            &[
17569                Scalar::Int64(10),
17570                Scalar::Int64(10),
17571                Scalar::Int64(20),
17572                Scalar::Int64(20)
17573            ]
17574        );
17575        assert_eq!(
17576            merged.columns.get("b").unwrap().values(),
17577            &[
17578                Scalar::Int64(100),
17579                Scalar::Int64(200),
17580                Scalar::Int64(100),
17581                Scalar::Int64(200)
17582            ]
17583        );
17584    }
17585
17586    #[test]
17587    fn ordered_unique_utf8_inner_positions_match_left_major_hash_order_53lat() {
17588        let left = contiguous_utf8_column(&["a", "b", "d", "f"]);
17589        let right = contiguous_utf8_column(&["b", "c", "f"]);
17590        let (left_positions, right_positions) =
17591            ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
17592
17593        assert_eq!(left_positions, vec![1, 3]);
17594        assert_eq!(right_positions, vec![0, 2]);
17595
17596        let merged = merge_dataframes(
17597            &utf8_key_merge_frame(&["a", "b", "d", "f"], "lv", 10),
17598            &utf8_key_merge_frame(&["b", "c", "f"], "rv", 20),
17599            "id",
17600            JoinType::Inner,
17601        )
17602        .unwrap();
17603        assert_eq!(
17604            merged.columns.get("lv").unwrap().values(),
17605            &[Scalar::Int64(11), Scalar::Int64(13)]
17606        );
17607        assert_eq!(
17608            merged.columns.get("rv").unwrap().values(),
17609            &[Scalar::Int64(20), Scalar::Int64(22)]
17610        );
17611    }
17612
17613    #[test]
17614    fn sorted_contiguous_utf8_inner_positions_preserves_duplicate_order_codb() {
17615        let left = contiguous_utf8_column(&["a", "a", "b", "d"]);
17616        let right = contiguous_utf8_column(&["a", "a", "c", "d"]);
17617        let (left_bytes, left_offsets) = left.as_utf8_contiguous().expect("left contiguous");
17618        let (right_bytes, right_offsets) = right.as_utf8_contiguous().expect("right contiguous");
17619
17620        let (left_positions, right_positions) = sorted_contiguous_utf8_inner_positions(
17621            left_bytes,
17622            left_offsets,
17623            right_bytes,
17624            right_offsets,
17625        )
17626        .expect("sorted spans should use two-pointer merge");
17627
17628        assert_eq!(left_positions, vec![0, 0, 1, 1, 3]);
17629        assert_eq!(right_positions, vec![0, 1, 0, 1, 3]);
17630    }
17631
17632    #[test]
17633    fn sorted_contiguous_utf8_inner_positions_rejects_unsorted_input_codb() {
17634        let left = contiguous_utf8_column(&["b", "a"]);
17635        let right = contiguous_utf8_column(&["a", "b"]);
17636        let (left_bytes, left_offsets) = left.as_utf8_contiguous().expect("left contiguous");
17637        let (right_bytes, right_offsets) = right.as_utf8_contiguous().expect("right contiguous");
17638
17639        assert!(
17640            sorted_contiguous_utf8_inner_positions(
17641                left_bytes,
17642                left_offsets,
17643                right_bytes,
17644                right_offsets,
17645            )
17646            .is_none()
17647        );
17648    }
17649
17650    #[test]
17651    fn ordered_unique_utf8_seek_bound_preserves_late_overlap_lr52z() {
17652        let left = contiguous_utf8_column(&["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]);
17653        let right = contiguous_utf8_column(&["h", "i", "j", "k"]);
17654        let (left_bytes, left_offsets) =
17655            strictly_increasing_utf8_key_spans(&left).expect("sorted left");
17656
17657        assert_eq!(utf8_span_lower_bound(left_bytes, left_offsets, b"h"), 7);
17658
17659        let (left_positions, right_positions) =
17660            ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
17661        assert_eq!(left_positions, vec![7, 8, 9]);
17662        assert_eq!(right_positions, vec![0, 1, 2]);
17663
17664        let disjoint_left = contiguous_utf8_column(&["a", "b"]);
17665        let disjoint_right = contiguous_utf8_column(&["c", "d"]);
17666        let (left_positions, right_positions) =
17667            ordered_unique_utf8_inner_positions(&disjoint_left, &disjoint_right)
17668                .expect("ordered disjoint utf8 positions");
17669        assert!(left_positions.is_empty());
17670        assert!(right_positions.is_empty());
17671    }
17672
17673    #[test]
17674    fn ordered_unique_utf8_bulk_fixed_width_window_jbyuc11() {
17675        let left = contiguous_utf8_column(&["k000", "k001", "k002", "k003", "k004"]);
17676        let right = contiguous_utf8_column(&["k002", "k003", "k004", "k005"]);
17677
17678        let (left_positions, right_positions) =
17679            ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
17680        assert_eq!(left_positions, vec![2, 3, 4]);
17681        assert_eq!(right_positions, vec![0, 1, 2]);
17682    }
17683
17684    #[test]
17685    fn ordered_unique_utf8_bulk_window_returns_range_plan_jbyuc11111() {
17686        let left = contiguous_utf8_column(&["k000", "k001", "k002", "k003", "k004"]);
17687        let right = contiguous_utf8_column(&["k002", "k003", "k004", "k005"]);
17688
17689        let plan =
17690            ordered_unique_utf8_inner_position_plan(&left, &right).expect("ordered utf8 plan");
17691
17692        assert_eq!(
17693            plan,
17694            InnerPositionPlan::ContiguousRanges {
17695                left_start: 2,
17696                right_start: 0,
17697                len: 3
17698            }
17699        );
17700    }
17701
17702    #[test]
17703    fn ordered_unique_utf8_lower_hex_certificate_returns_range_plan_jbyuc111111() {
17704        let left =
17705            contiguous_utf8_column(&["id_0000000a", "id_0000000b", "id_0000000c", "id_0000000d"]);
17706        let right = contiguous_utf8_column(&["id_0000000c", "id_0000000d", "id_0000000e"]);
17707        let (_, _, left_cert) = left
17708            .as_lower_hex_sequence_utf8_contiguous()
17709            .expect("left sequence certificate");
17710        let (_, _, right_cert) = right
17711            .as_lower_hex_sequence_utf8_contiguous()
17712            .expect("right sequence certificate");
17713
17714        assert_eq!(
17715            ordered_utf8_lower_hex_overlap_len(left_cert, right_cert, 2, 4, 0, 3),
17716            Some(2)
17717        );
17718        assert_eq!(
17719            lower_hex_overlap_plan_from_certificates(&left, &right),
17720            Some(InnerPositionPlan::ContiguousRanges {
17721                left_start: 2,
17722                right_start: 0,
17723                len: 2
17724            })
17725        );
17726        let plan =
17727            ordered_unique_utf8_inner_position_plan(&left, &right).expect("ordered utf8 plan");
17728        assert_eq!(
17729            plan,
17730            InnerPositionPlan::ContiguousRanges {
17731                left_start: 2,
17732                right_start: 0,
17733                len: 2
17734            }
17735        );
17736    }
17737
17738    #[test]
17739    fn ordered_unique_utf8_lower_hex_arithmetic_empty_overlap_jbyuc1111111111() {
17740        let left = contiguous_utf8_column(&["id_00000001", "id_00000002", "id_00000003"]);
17741        let right = contiguous_utf8_column(&["id_00000008", "id_00000009"]);
17742
17743        assert_eq!(
17744            lower_hex_overlap_plan_from_certificates(&left, &right),
17745            Some(InnerPositionPlan::Gather {
17746                left_positions: Vec::new(),
17747                right_positions: Vec::new(),
17748            })
17749        );
17750        let (left_positions, right_positions) =
17751            ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
17752        assert!(left_positions.is_empty());
17753        assert!(right_positions.is_empty());
17754    }
17755
17756    #[test]
17757    fn ordered_unique_utf8_lower_hex_prefix_mismatch_falls_back_jbyuc1111111111() {
17758        let left = contiguous_utf8_column(&["aa_00000001", "aa_00000002", "aa_00000003"]);
17759        let right = contiguous_utf8_column(&["bb_00000001", "bb_00000002", "bb_00000003"]);
17760
17761        assert!(
17762            lower_hex_overlap_plan_from_certificates(&left, &right).is_none(),
17763            "matching lower-hex counters with different prefixes must not use arithmetic overlap"
17764        );
17765        let (left_positions, right_positions) =
17766            ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
17767        assert!(left_positions.is_empty());
17768        assert!(right_positions.is_empty());
17769    }
17770
17771    #[test]
17772    fn ordered_utf8_contiguous_no_overlap_output_fast_path_jbyuc111111111() -> Result<(), String> {
17773        let left = utf8_key_merge_frame(
17774            &["id_00000000", "id_00000001", "id_00000002", "id_00000003"],
17775            "lv",
17776            10,
17777        );
17778        let right = utf8_key_merge_frame(&["id_00000002", "id_00000003", "id_00000004"], "rv", 100);
17779        let plan = ordered_unique_utf8_inner_position_plan(
17780            left.columns()
17781                .get("id")
17782                .ok_or_else(|| "left key column missing".to_owned())?,
17783            right
17784                .columns()
17785                .get("id")
17786                .ok_or_else(|| "right key column missing".to_owned())?,
17787        )
17788        .ok_or_else(|| "ordered utf8 plan unavailable".to_owned())?;
17789        let InnerPositionPlan::ContiguousRanges {
17790            left_start,
17791            right_start,
17792            len,
17793        } = plan
17794        else {
17795            return Err("expected contiguous range plan".to_owned());
17796        };
17797
17798        let merged = build_single_key_inner_contiguous_no_overlap_output(
17799            &left,
17800            &right,
17801            &["id"],
17802            &["id"],
17803            PositionSelection::ContiguousRange {
17804                start: left_start,
17805                len,
17806            },
17807            PositionSelection::ContiguousRange {
17808                start: right_start,
17809                len,
17810            },
17811        )
17812        .ok_or_else(|| "no-overlap contiguous output fast path missed".to_owned())?;
17813
17814        assert_eq!(merged.column_order, ["id", "lv", "rv"]);
17815        let id_output = merged
17816            .columns
17817            .get("id")
17818            .ok_or_else(|| "id output missing".to_owned())?;
17819        let (prefix, certificate, certificate_len) = id_output
17820            .as_lower_hex_sequence_utf8()
17821            .ok_or_else(|| "id output lost lower-hex sequence witness".to_owned())?;
17822        assert_eq!(prefix, b"id_");
17823        assert_eq!(certificate.start(), 2);
17824        assert_eq!(certificate.hex_width(), 8);
17825        assert_eq!(certificate_len, 2);
17826        assert_eq!(
17827            id_output.values(),
17828            &[
17829                Scalar::Utf8("id_00000002".to_owned()),
17830                Scalar::Utf8("id_00000003".to_owned())
17831            ]
17832        );
17833        assert_eq!(
17834            merged
17835                .columns
17836                .get("lv")
17837                .ok_or_else(|| "lv output missing".to_owned())?
17838                .values(),
17839            &[Scalar::Int64(12), Scalar::Int64(13)]
17840        );
17841        assert_eq!(
17842            merged
17843                .columns
17844                .get("rv")
17845                .ok_or_else(|| "rv output missing".to_owned())?
17846                .values(),
17847            &[Scalar::Int64(100), Scalar::Int64(101)]
17848        );
17849
17850        let overlapping_right =
17851            utf8_key_merge_frame(&["id_00000002", "id_00000003", "id_00000004"], "lv", 100);
17852        assert!(
17853            build_single_key_inner_contiguous_no_overlap_output(
17854                &left,
17855                &overlapping_right,
17856                &["id"],
17857                &["id"],
17858                PositionSelection::ContiguousRange {
17859                    start: left_start,
17860                    len,
17861                },
17862                PositionSelection::ContiguousRange {
17863                    start: right_start,
17864                    len,
17865                },
17866            )
17867            .is_none(),
17868            "overlapping non-key columns must keep the suffix/error generic path"
17869        );
17870        Ok(())
17871    }
17872
17873    #[test]
17874    fn ordered_unique_utf8_uncertified_fixed_width_still_matches_jbyuc111111() {
17875        let left = contiguous_utf8_column(&["k00A", "k00B", "k00C", "k00D"]);
17876        let right = contiguous_utf8_column(&["k00B", "k00D"]);
17877
17878        assert!(left.as_lower_hex_sequence_utf8_contiguous().is_none());
17879        assert!(right.as_lower_hex_sequence_utf8_contiguous().is_none());
17880        let (left_positions, right_positions) =
17881            ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
17882        assert_eq!(left_positions, vec![1, 3]);
17883        assert_eq!(right_positions, vec![0, 1]);
17884    }
17885
17886    #[test]
17887    fn ordered_unique_utf8_fixed_width_gap_falls_back_jbyuc11() {
17888        let left = contiguous_utf8_column(&["k000", "k001", "k003", "k004"]);
17889        let right = contiguous_utf8_column(&["k001", "k002", "k004"]);
17890
17891        let (left_positions, right_positions) =
17892            ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
17893        assert_eq!(left_positions, vec![1, 3]);
17894        assert_eq!(right_positions, vec![0, 2]);
17895    }
17896
17897    #[test]
17898    fn ordered_unique_utf8_rejects_unsorted_or_duplicate_keys_53lat() {
17899        let unsorted_left = contiguous_utf8_column(&["b", "a", "b"]);
17900        let duplicate_right = contiguous_utf8_column(&["b", "b", "a"]);
17901        assert!(ordered_unique_utf8_inner_positions(&unsorted_left, &duplicate_right).is_none());
17902
17903        let left = utf8_key_merge_frame(&["b", "a", "b"], "lv", 10);
17904        let right = utf8_key_merge_frame(&["b", "b", "a"], "rv", 20);
17905        let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
17906
17907        assert_eq!(
17908            merged.columns.get("lv").unwrap().values(),
17909            &[
17910                Scalar::Int64(10),
17911                Scalar::Int64(10),
17912                Scalar::Int64(11),
17913                Scalar::Int64(12),
17914                Scalar::Int64(12)
17915            ]
17916        );
17917        assert_eq!(
17918            merged.columns.get("rv").unwrap().values(),
17919            &[
17920                Scalar::Int64(20),
17921                Scalar::Int64(21),
17922                Scalar::Int64(22),
17923                Scalar::Int64(20),
17924                Scalar::Int64(21)
17925            ]
17926        );
17927    }
17928
17929    #[test]
17930    fn merge_inner_int64_fast_paths_match_naive_reference_fuzz_jdupk() {
17931        // Differential guard: merge_dataframes dispatches int64 single-key inner
17932        // merges to ordered/identity/dense fast paths. Each MUST equal a naive
17933        // left-major nested-loop join for arbitrary int64 keys (sorted/unsorted,
17934        // unique/duplicate, overlapping/disjoint, negative). This is the
17935        // isomorphism proof those perf paths owe; it caught the identity-path
17936        // row-loss bug. (br-frankenpandas-rw0r5)
17937        let mut state: u64 = 0x9E37_79B9_7F4A_7C15;
17938        let mut next = || {
17939            state = state
17940                .wrapping_mul(6_364_136_223_846_793_005)
17941                .wrapping_add(1_442_695_040_888_963_407);
17942            state >> 33
17943        };
17944        for _ in 0..400 {
17945            let nl = (next() % 6 + 1) as usize;
17946            let nr = (next() % 6 + 1) as usize;
17947            // small key range forces collisions; offset gives negatives too
17948            let lk: Vec<i64> = (0..nl).map(|_| (next() % 5) as i64 - 2).collect();
17949            let rk: Vec<i64> = (0..nr).map(|_| (next() % 5) as i64 - 2).collect();
17950
17951            let left = DataFrame::from_dict(
17952                &["id", "a"],
17953                vec![
17954                    ("id", lk.iter().map(|&k| Scalar::Int64(k)).collect()),
17955                    (
17956                        "a",
17957                        (0..nl).map(|i| Scalar::Int64(i as i64 + 1000)).collect(),
17958                    ),
17959                ],
17960            )
17961            .unwrap();
17962            let right = DataFrame::from_dict(
17963                &["id", "b"],
17964                vec![
17965                    ("id", rk.iter().map(|&k| Scalar::Int64(k)).collect()),
17966                    (
17967                        "b",
17968                        (0..nr).map(|j| Scalar::Int64(j as i64 + 2000)).collect(),
17969                    ),
17970                ],
17971            )
17972            .unwrap();
17973
17974            let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
17975
17976            // Naive reference: pandas inner merge is left-major, right-minor.
17977            let mut exp_a = Vec::new();
17978            let mut exp_b = Vec::new();
17979            for (i, &left_value) in lk.iter().enumerate() {
17980                for (j, &right_value) in rk.iter().enumerate() {
17981                    if left_value == right_value {
17982                        exp_a.push(Scalar::Int64(i as i64 + 1000));
17983                        exp_b.push(Scalar::Int64(j as i64 + 2000));
17984                    }
17985                }
17986            }
17987            assert_eq!(
17988                merged.columns.get("a").unwrap().values(),
17989                exp_a.as_slice(),
17990                "left payload mismatch for lk={lk:?} rk={rk:?}"
17991            );
17992            assert_eq!(
17993                merged.columns.get("b").unwrap().values(),
17994                exp_b.as_slice(),
17995                "right payload mismatch for lk={lk:?} rk={rk:?}"
17996            );
17997
17998            // Cardinality guard for left/right/outer (dtype/order independent —
17999            // catches the row-loss class regardless of int->float promotion).
18000            let inner_pairs = exp_a.len();
18001            let left_only = lk.iter().filter(|&key| !rk.contains(key)).count();
18002            let right_only = rk.iter().filter(|&key| !lk.contains(key)).count();
18003            for (how, expected_rows) in [
18004                (JoinType::Left, inner_pairs + left_only),
18005                (JoinType::Right, inner_pairs + right_only),
18006                (JoinType::Outer, inner_pairs + left_only + right_only),
18007            ] {
18008                let m = merge_dataframes(&left, &right, "id", how).unwrap();
18009                assert_eq!(
18010                    m.columns.get("id").unwrap().len(),
18011                    expected_rows,
18012                    "{how:?} cardinality mismatch for lk={lk:?} rk={rk:?}"
18013                );
18014            }
18015        }
18016    }
18017
18018    #[test]
18019    fn merge_null_nan_keys_metamorphic_unmatched_rows_do_not_disturb_inner_tn6qb8()
18020    -> Result<(), JoinError> {
18021        let left = DataFrame::from_dict(
18022            &["id", "left_v"],
18023            vec![
18024                (
18025                    "id",
18026                    vec![
18027                        Scalar::Float64(1.0),
18028                        Scalar::Null(NullKind::NaN),
18029                        Scalar::Null(NullKind::Null),
18030                        Scalar::Float64(2.0),
18031                    ],
18032                ),
18033                (
18034                    "left_v",
18035                    vec![
18036                        Scalar::Int64(10),
18037                        Scalar::Int64(20),
18038                        Scalar::Int64(21),
18039                        Scalar::Int64(30),
18040                    ],
18041                ),
18042            ],
18043        )?;
18044        let right = DataFrame::from_dict(
18045            &["id", "right_v"],
18046            vec![
18047                (
18048                    "id",
18049                    vec![
18050                        Scalar::Null(NullKind::Null),
18051                        Scalar::Float64(2.0),
18052                        Scalar::Float64(f64::NAN),
18053                    ],
18054                ),
18055                (
18056                    "right_v",
18057                    vec![Scalar::Int64(200), Scalar::Int64(300), Scalar::Int64(201)],
18058                ),
18059            ],
18060        )?;
18061
18062        let baseline = merge_dataframes(&left, &right, "id", JoinType::Inner)?;
18063
18064        let left_with_unmatched = DataFrame::from_dict(
18065            &["id", "left_v"],
18066            vec![
18067                (
18068                    "id",
18069                    vec![
18070                        Scalar::Float64(1.0),
18071                        Scalar::Null(NullKind::NaN),
18072                        Scalar::Null(NullKind::Null),
18073                        Scalar::Float64(2.0),
18074                        Scalar::Float64(99.0),
18075                    ],
18076                ),
18077                (
18078                    "left_v",
18079                    vec![
18080                        Scalar::Int64(10),
18081                        Scalar::Int64(20),
18082                        Scalar::Int64(21),
18083                        Scalar::Int64(30),
18084                        Scalar::Int64(990),
18085                    ],
18086                ),
18087            ],
18088        )?;
18089        let right_with_unmatched = DataFrame::from_dict(
18090            &["id", "right_v"],
18091            vec![
18092                (
18093                    "id",
18094                    vec![
18095                        Scalar::Null(NullKind::Null),
18096                        Scalar::Float64(2.0),
18097                        Scalar::Float64(f64::NAN),
18098                        Scalar::Float64(100.0),
18099                    ],
18100                ),
18101                (
18102                    "right_v",
18103                    vec![
18104                        Scalar::Int64(200),
18105                        Scalar::Int64(300),
18106                        Scalar::Int64(201),
18107                        Scalar::Int64(1000),
18108                    ],
18109                ),
18110            ],
18111        )?;
18112
18113        let transformed = merge_dataframes(
18114            &left_with_unmatched,
18115            &right_with_unmatched,
18116            "id",
18117            JoinType::Inner,
18118        )?;
18119
18120        assert_eq!(
18121            merged_values(&baseline, "left_v")?,
18122            merged_values(&transformed, "left_v")?
18123        );
18124        assert_eq!(
18125            merged_values(&baseline, "right_v")?,
18126            merged_values(&transformed, "right_v")?
18127        );
18128        assert_eq!(
18129            merged_values(&baseline, "left_v")?,
18130            &[
18131                Scalar::Int64(20),
18132                Scalar::Int64(20),
18133                Scalar::Int64(21),
18134                Scalar::Int64(21),
18135                Scalar::Int64(30),
18136            ]
18137        );
18138        assert_eq!(
18139            merged_values(&baseline, "right_v")?,
18140            &[
18141                Scalar::Int64(200),
18142                Scalar::Int64(201),
18143                Scalar::Int64(200),
18144                Scalar::Int64(201),
18145                Scalar::Int64(300),
18146            ]
18147        );
18148
18149        Ok(())
18150    }
18151
18152    #[test]
18153    fn merge_mixed_dtype_missing_keys_metamorphic_outer_both_equals_inner_tn6qb8()
18154    -> Result<(), JoinError> {
18155        let left = DataFrame::from_dict(
18156            &["id", "left_v"],
18157            vec![
18158                (
18159                    "id",
18160                    vec![
18161                        Scalar::Int64(1),
18162                        Scalar::Int64(2),
18163                        Scalar::Null(NullKind::NaN),
18164                        Scalar::Int64(3),
18165                    ],
18166                ),
18167                (
18168                    "left_v",
18169                    vec![
18170                        Scalar::Float64(10.0),
18171                        Scalar::Float64(20.0),
18172                        Scalar::Float64(30.0),
18173                        Scalar::Float64(40.0),
18174                    ],
18175                ),
18176            ],
18177        )?;
18178        let right = DataFrame::from_dict(
18179            &["id", "right_v"],
18180            vec![
18181                (
18182                    "id",
18183                    vec![
18184                        Scalar::Float64(1.0),
18185                        Scalar::Float64(2.5),
18186                        Scalar::Null(NullKind::Null),
18187                        Scalar::Float64(3.0),
18188                    ],
18189                ),
18190                (
18191                    "right_v",
18192                    vec![
18193                        Scalar::Float64(100.0),
18194                        Scalar::Float64(250.0),
18195                        Scalar::Float64(300.0),
18196                        Scalar::Float64(400.0),
18197                    ],
18198                ),
18199            ],
18200        )?;
18201        let options = MergeExecutionOptions {
18202            indicator_name: Some("_merge".to_owned()),
18203            sort: true,
18204            ..MergeExecutionOptions::default()
18205        };
18206
18207        let inner = merge_dataframes_on_with_options(
18208            &left,
18209            &right,
18210            &["id"],
18211            &["id"],
18212            JoinType::Inner,
18213            options.clone(),
18214        )?;
18215        let outer = merge_dataframes_on_with_options(
18216            &left,
18217            &right,
18218            &["id"],
18219            &["id"],
18220            JoinType::Outer,
18221            options,
18222        )?;
18223
18224        assert_eq!(
18225            merged_values(&inner, "left_v")?,
18226            merged_values_where_indicator(&outer, "left_v", "_merge", "both")?
18227        );
18228        assert_eq!(
18229            merged_values(&inner, "right_v")?,
18230            merged_values_where_indicator(&outer, "right_v", "_merge", "both")?
18231        );
18232        assert_eq!(
18233            merged_values(&inner, "left_v")?,
18234            &[
18235                Scalar::Float64(10.0),
18236                Scalar::Float64(40.0),
18237                Scalar::Float64(30.0)
18238            ]
18239        );
18240        assert_eq!(
18241            merged_values(&inner, "right_v")?,
18242            &[
18243                Scalar::Float64(100.0),
18244                Scalar::Float64(400.0),
18245                Scalar::Float64(300.0)
18246            ]
18247        );
18248        assert_eq!(
18249            merged_values(&outer, "_merge")?,
18250            &[
18251                Scalar::Utf8("both".to_owned()),
18252                Scalar::Utf8("left_only".to_owned()),
18253                Scalar::Utf8("right_only".to_owned()),
18254                Scalar::Utf8("both".to_owned()),
18255                Scalar::Utf8("both".to_owned()),
18256            ]
18257        );
18258
18259        Ok(())
18260    }
18261
18262    #[test]
18263    fn merge_cross_cartesian_product() {
18264        let left = make_left_df();
18265        let right = make_right_df();
18266
18267        let merged = merge_dataframes(&left, &right, "unused_key", JoinType::Cross).unwrap();
18268
18269        assert_eq!(merged.columns.get("id_x").unwrap().len(), 9);
18270        assert_eq!(
18271            &merged.columns.get("id_x").unwrap().values()[0..3],
18272            &[Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(1)]
18273        );
18274        assert_eq!(
18275            &merged.columns.get("id_y").unwrap().values()[0..3],
18276            &[Scalar::Int64(2), Scalar::Int64(3), Scalar::Int64(4)]
18277        );
18278        assert_eq!(
18279            &merged.columns.get("val_a").unwrap().values()[0..3],
18280            &[Scalar::Int64(10), Scalar::Int64(10), Scalar::Int64(10)]
18281        );
18282        assert_eq!(
18283            &merged.columns.get("val_b").unwrap().values()[0..3],
18284            &[Scalar::Int64(200), Scalar::Int64(300), Scalar::Int64(400)]
18285        );
18286    }
18287
18288    #[test]
18289    fn merge_cross_does_not_require_on_column() {
18290        let left = make_left_df();
18291        let right = make_right_df();
18292
18293        let merged =
18294            merge_dataframes(&left, &right, "definitely_missing", JoinType::Cross).unwrap();
18295        assert_eq!(merged.columns.get("id_x").unwrap().len(), 9);
18296    }
18297
18298    #[test]
18299    fn merge_cross_with_empty_side_yields_empty_rows() {
18300        let left = DataFrame::from_dict(
18301            &["l"],
18302            vec![("l", vec![Scalar::Int64(1), Scalar::Int64(2)])],
18303        )
18304        .unwrap();
18305        let right = DataFrame::from_dict(&["r"], vec![("r", vec![])]).unwrap();
18306
18307        let merged = merge_dataframes(&left, &right, "ignored", JoinType::Cross).unwrap();
18308        assert_eq!(merged.index.labels().len(), 0);
18309        assert!(merged.columns.get("l").unwrap().values().is_empty());
18310        assert!(merged.columns.get("r").unwrap().values().is_empty());
18311    }
18312
18313    #[test]
18314    fn merge_composite_inner_multiplies_cardinality_for_duplicates() {
18315        let left = DataFrame::from_dict(
18316            &["k1", "k2", "left_v"],
18317            vec![
18318                (
18319                    "k1",
18320                    vec![Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(1)],
18321                ),
18322                (
18323                    "k2",
18324                    vec![
18325                        Scalar::Utf8("a".to_owned()),
18326                        Scalar::Utf8("a".to_owned()),
18327                        Scalar::Utf8("b".to_owned()),
18328                    ],
18329                ),
18330                (
18331                    "left_v",
18332                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
18333                ),
18334            ],
18335        )
18336        .unwrap();
18337        let right = DataFrame::from_dict(
18338            &["k1", "k2", "right_v"],
18339            vec![
18340                (
18341                    "k1",
18342                    vec![Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(1)],
18343                ),
18344                (
18345                    "k2",
18346                    vec![
18347                        Scalar::Utf8("a".to_owned()),
18348                        Scalar::Utf8("a".to_owned()),
18349                        Scalar::Utf8("c".to_owned()),
18350                    ],
18351                ),
18352                (
18353                    "right_v",
18354                    vec![Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(300)],
18355                ),
18356            ],
18357        )
18358        .unwrap();
18359
18360        let merged = merge_dataframes_on(&left, &right, &["k1", "k2"], JoinType::Inner).unwrap();
18361        assert_eq!(merged.columns.get("k1").unwrap().len(), 4);
18362        assert_eq!(
18363            merged.columns.get("k1").unwrap().values(),
18364            &[
18365                Scalar::Int64(1),
18366                Scalar::Int64(1),
18367                Scalar::Int64(1),
18368                Scalar::Int64(1)
18369            ]
18370        );
18371        assert_eq!(
18372            merged.columns.get("k2").unwrap().values(),
18373            &[
18374                Scalar::Utf8("a".to_owned()),
18375                Scalar::Utf8("a".to_owned()),
18376                Scalar::Utf8("a".to_owned()),
18377                Scalar::Utf8("a".to_owned())
18378            ]
18379        );
18380        assert_eq!(
18381            merged.columns.get("left_v").unwrap().values(),
18382            &[
18383                Scalar::Int64(10),
18384                Scalar::Int64(10),
18385                Scalar::Int64(20),
18386                Scalar::Int64(20)
18387            ]
18388        );
18389        assert_eq!(
18390            merged.columns.get("right_v").unwrap().values(),
18391            &[
18392                Scalar::Int64(100),
18393                Scalar::Int64(200),
18394                Scalar::Int64(100),
18395                Scalar::Int64(200)
18396            ]
18397        );
18398    }
18399
18400    #[test]
18401    fn merge_composite_outer_sorts_join_keys_lexicographically() {
18402        let left = DataFrame::from_dict(
18403            &["k1", "k2", "left_v"],
18404            vec![
18405                ("k1", vec![Scalar::Int64(2), Scalar::Int64(1)]),
18406                (
18407                    "k2",
18408                    vec![Scalar::Utf8("y".to_owned()), Scalar::Utf8("x".to_owned())],
18409                ),
18410                ("left_v", vec![Scalar::Int64(20), Scalar::Int64(10)]),
18411            ],
18412        )
18413        .unwrap();
18414        let right = DataFrame::from_dict(
18415            &["k1", "k2", "right_v"],
18416            vec![
18417                ("k1", vec![Scalar::Int64(2), Scalar::Int64(3)]),
18418                (
18419                    "k2",
18420                    vec![Scalar::Utf8("y".to_owned()), Scalar::Utf8("z".to_owned())],
18421                ),
18422                ("right_v", vec![Scalar::Int64(200), Scalar::Int64(300)]),
18423            ],
18424        )
18425        .unwrap();
18426
18427        let merged = merge_dataframes_on(&left, &right, &["k1", "k2"], JoinType::Outer).unwrap();
18428        assert_eq!(
18429            merged.columns.get("k1").unwrap().values(),
18430            &[Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)]
18431        );
18432        assert_eq!(
18433            merged.columns.get("k2").unwrap().values(),
18434            &[
18435                Scalar::Utf8("x".to_owned()),
18436                Scalar::Utf8("y".to_owned()),
18437                Scalar::Utf8("z".to_owned())
18438            ]
18439        );
18440        assert_eq!(
18441            merged.columns.get("left_v").unwrap().values(),
18442            &[
18443                Scalar::Float64(10.0),
18444                Scalar::Float64(20.0),
18445                Scalar::Null(NullKind::NaN)
18446            ]
18447        );
18448        assert_eq!(
18449            merged.columns.get("right_v").unwrap().values(),
18450            &[
18451                Scalar::Null(NullKind::NaN),
18452                Scalar::Float64(200.0),
18453                Scalar::Float64(300.0)
18454            ]
18455        );
18456    }
18457
18458    #[test]
18459    fn merge_composite_outer_contiguous_utf8_key_coalesce_matches_scalar_route_blackthrush() {
18460        let contiguous_frame =
18461            |k1: &[&str], k2: &[&str], value_name: &str, values: &[i64]| -> DataFrame {
18462                let index = Index::new(
18463                    (0..k1.len())
18464                        .map(|row| IndexLabel::Int64(row as i64))
18465                        .collect(),
18466                );
18467                let mut columns = ColumnStore::new();
18468                columns.insert("k1".to_owned(), contiguous_utf8_column(k1));
18469                columns.insert("k2".to_owned(), contiguous_utf8_column(k2));
18470                columns.insert(
18471                    value_name.to_owned(),
18472                    Column::from_i64_values(values.to_vec()),
18473                );
18474                DataFrame::new_with_column_order(
18475                    index,
18476                    columns,
18477                    vec!["k1".to_owned(), "k2".to_owned(), value_name.to_owned()],
18478                )
18479                .expect("contiguous frame")
18480            };
18481        let scalar_frame =
18482            |k1: &[&str], k2: &[&str], value_name: &str, values: &[i64]| -> DataFrame {
18483                DataFrame::from_dict(
18484                    &["k1", "k2", value_name],
18485                    vec![
18486                        (
18487                            "k1",
18488                            k1.iter()
18489                                .map(|value| Scalar::Utf8((*value).to_owned()))
18490                                .collect(),
18491                        ),
18492                        (
18493                            "k2",
18494                            k2.iter()
18495                                .map(|value| Scalar::Utf8((*value).to_owned()))
18496                                .collect(),
18497                        ),
18498                        (
18499                            value_name,
18500                            values.iter().copied().map(Scalar::Int64).collect(),
18501                        ),
18502                    ],
18503                )
18504                .expect("scalar frame")
18505            };
18506
18507        let left_fast =
18508            contiguous_frame(&["b", "a", "c"], &["y", "x", "z"], "left_v", &[20, 10, 30]);
18509        let right_fast = contiguous_frame(&["b", "d"], &["y", "w"], "right_v", &[200, 400]);
18510        let left_scalar = scalar_frame(&["b", "a", "c"], &["y", "x", "z"], "left_v", &[20, 10, 30]);
18511        let right_scalar = scalar_frame(&["b", "d"], &["y", "w"], "right_v", &[200, 400]);
18512
18513        let fast =
18514            merge_dataframes_on(&left_fast, &right_fast, &["k1", "k2"], JoinType::Outer).unwrap();
18515        let scalar =
18516            merge_dataframes_on(&left_scalar, &right_scalar, &["k1", "k2"], JoinType::Outer)
18517                .unwrap();
18518
18519        for name in ["k1", "k2", "left_v", "right_v"] {
18520            assert_eq!(
18521                fast.columns.get(name).unwrap().values(),
18522                scalar.columns.get(name).unwrap().values(),
18523                "column {name}"
18524            );
18525        }
18526        assert!(
18527            fast.columns
18528                .get("k1")
18529                .unwrap()
18530                .as_utf8_contiguous()
18531                .is_some()
18532        );
18533        assert!(
18534            fast.columns
18535                .get("k2")
18536                .unwrap()
18537                .as_utf8_contiguous()
18538                .is_some()
18539        );
18540    }
18541
18542    #[test]
18543    fn merge_composite_inner_matches_missing_key_components() {
18544        let left = DataFrame::from_dict(
18545            &["k1", "k2", "left_v"],
18546            vec![
18547                ("k1", vec![Scalar::Int64(1), Scalar::Int64(1)]),
18548                (
18549                    "k2",
18550                    vec![Scalar::Null(NullKind::Null), Scalar::Utf8("a".to_owned())],
18551                ),
18552                ("left_v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
18553            ],
18554        )
18555        .unwrap();
18556        let right = DataFrame::from_dict(
18557            &["k1", "k2", "right_v"],
18558            vec![
18559                (
18560                    "k1",
18561                    vec![Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(2)],
18562                ),
18563                (
18564                    "k2",
18565                    vec![
18566                        Scalar::Null(NullKind::Null),
18567                        Scalar::Utf8("a".to_owned()),
18568                        Scalar::Null(NullKind::Null),
18569                    ],
18570                ),
18571                (
18572                    "right_v",
18573                    vec![Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(300)],
18574                ),
18575            ],
18576        )
18577        .unwrap();
18578
18579        let merged = merge_dataframes_on(&left, &right, &["k1", "k2"], JoinType::Inner).unwrap();
18580        assert_eq!(
18581            merged.columns.get("k1").unwrap().values(),
18582            &[Scalar::Int64(1), Scalar::Int64(1)]
18583        );
18584        assert_eq!(
18585            merged.columns.get("k2").unwrap().values(),
18586            &[Scalar::Null(NullKind::Null), Scalar::Utf8("a".to_owned())]
18587        );
18588        assert_eq!(
18589            merged.columns.get("left_v").unwrap().values(),
18590            &[Scalar::Int64(10), Scalar::Int64(20)]
18591        );
18592        assert_eq!(
18593            merged.columns.get("right_v").unwrap().values(),
18594            &[Scalar::Int64(100), Scalar::Int64(200)]
18595        );
18596    }
18597
18598    #[test]
18599    fn merge_composite_outer_keeps_right_only_rows_with_missing_keys() {
18600        let left = DataFrame::from_dict(
18601            &["k1", "k2", "left_v"],
18602            vec![
18603                ("k1", vec![Scalar::Int64(1)]),
18604                ("k2", vec![Scalar::Null(NullKind::Null)]),
18605                ("left_v", vec![Scalar::Int64(10)]),
18606            ],
18607        )
18608        .unwrap();
18609        let right = DataFrame::from_dict(
18610            &["k1", "k2", "right_v"],
18611            vec![
18612                ("k1", vec![Scalar::Int64(1), Scalar::Int64(2)]),
18613                (
18614                    "k2",
18615                    vec![Scalar::Null(NullKind::Null), Scalar::Null(NullKind::Null)],
18616                ),
18617                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
18618            ],
18619        )
18620        .unwrap();
18621
18622        let merged = merge_dataframes_on(&left, &right, &["k1", "k2"], JoinType::Outer).unwrap();
18623        assert_eq!(
18624            merged.columns.get("k1").unwrap().values(),
18625            &[Scalar::Int64(1), Scalar::Int64(2)]
18626        );
18627        assert_eq!(
18628            merged.columns.get("k2").unwrap().values(),
18629            &[Scalar::Null(NullKind::Null), Scalar::Null(NullKind::Null)]
18630        );
18631        assert_eq!(
18632            merged.columns.get("left_v").unwrap().values(),
18633            &[Scalar::Float64(10.0), Scalar::Null(NullKind::NaN)]
18634        );
18635        assert_eq!(
18636            merged.columns.get("right_v").unwrap().values(),
18637            &[Scalar::Int64(100), Scalar::Int64(200)]
18638        );
18639    }
18640
18641    #[test]
18642    fn merge_composite_missing_key_column_errors() {
18643        let left = DataFrame::from_dict(
18644            &["k1", "k2", "left_v"],
18645            vec![
18646                ("k1", vec![Scalar::Int64(1)]),
18647                ("k2", vec![Scalar::Utf8("x".to_owned())]),
18648                ("left_v", vec![Scalar::Int64(10)]),
18649            ],
18650        )
18651        .unwrap();
18652        let right = DataFrame::from_dict(
18653            &["k1", "right_v"],
18654            vec![
18655                ("k1", vec![Scalar::Int64(1)]),
18656                ("right_v", vec![Scalar::Int64(100)]),
18657            ],
18658        )
18659        .unwrap();
18660
18661        let err = merge_dataframes_on(&left, &right, &["k1", "k2"], JoinType::Inner)
18662            .expect_err("should fail");
18663        assert!(format!("{err}").contains("right DataFrame missing key column 'k2'"));
18664    }
18665
18666    #[test]
18667    fn merge_composite_key_alias_inner_keeps_both_key_sets() {
18668        let left = DataFrame::from_dict(
18669            &["lk1", "lk2", "left_v"],
18670            vec![
18671                (
18672                    "lk1",
18673                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
18674                ),
18675                (
18676                    "lk2",
18677                    vec![
18678                        Scalar::Utf8("a".to_owned()),
18679                        Scalar::Utf8("b".to_owned()),
18680                        Scalar::Utf8("c".to_owned()),
18681                    ],
18682                ),
18683                (
18684                    "left_v",
18685                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
18686                ),
18687            ],
18688        )
18689        .unwrap();
18690        let right = DataFrame::from_dict(
18691            &["rk1", "rk2", "right_v"],
18692            vec![
18693                (
18694                    "rk1",
18695                    vec![Scalar::Int64(2), Scalar::Int64(3), Scalar::Int64(4)],
18696                ),
18697                (
18698                    "rk2",
18699                    vec![
18700                        Scalar::Utf8("b".to_owned()),
18701                        Scalar::Utf8("c".to_owned()),
18702                        Scalar::Utf8("d".to_owned()),
18703                    ],
18704                ),
18705                (
18706                    "right_v",
18707                    vec![Scalar::Int64(200), Scalar::Int64(300), Scalar::Int64(400)],
18708                ),
18709            ],
18710        )
18711        .unwrap();
18712
18713        let merged = merge_dataframes_on_with(
18714            &left,
18715            &right,
18716            &["lk1", "lk2"],
18717            &["rk1", "rk2"],
18718            JoinType::Inner,
18719        )
18720        .unwrap();
18721        assert_eq!(
18722            merged.columns.get("lk1").unwrap().values(),
18723            &[Scalar::Int64(2), Scalar::Int64(3)]
18724        );
18725        assert_eq!(
18726            merged.columns.get("lk2").unwrap().values(),
18727            &[Scalar::Utf8("b".to_owned()), Scalar::Utf8("c".to_owned())]
18728        );
18729        assert_eq!(
18730            merged.columns.get("left_v").unwrap().values(),
18731            &[Scalar::Int64(20), Scalar::Int64(30)]
18732        );
18733        assert_eq!(
18734            merged.columns.get("rk1").unwrap().values(),
18735            &[Scalar::Int64(2), Scalar::Int64(3)]
18736        );
18737        assert_eq!(
18738            merged.columns.get("rk2").unwrap().values(),
18739            &[Scalar::Utf8("b".to_owned()), Scalar::Utf8("c".to_owned())]
18740        );
18741        assert_eq!(
18742            merged.columns.get("right_v").unwrap().values(),
18743            &[Scalar::Int64(200), Scalar::Int64(300)]
18744        );
18745    }
18746
18747    #[test]
18748    fn merge_composite_key_alias_outer_propagates_missing_per_side() {
18749        let left = DataFrame::from_dict(
18750            &["lk1", "lk2", "left_v"],
18751            vec![
18752                (
18753                    "lk1",
18754                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
18755                ),
18756                (
18757                    "lk2",
18758                    vec![
18759                        Scalar::Utf8("a".to_owned()),
18760                        Scalar::Null(NullKind::Null),
18761                        Scalar::Utf8("c".to_owned()),
18762                    ],
18763                ),
18764                (
18765                    "left_v",
18766                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
18767                ),
18768            ],
18769        )
18770        .unwrap();
18771        let right = DataFrame::from_dict(
18772            &["rk1", "rk2", "right_v"],
18773            vec![
18774                (
18775                    "rk1",
18776                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(4)],
18777                ),
18778                (
18779                    "rk2",
18780                    vec![
18781                        Scalar::Utf8("a".to_owned()),
18782                        Scalar::Null(NullKind::Null),
18783                        Scalar::Utf8("d".to_owned()),
18784                    ],
18785                ),
18786                (
18787                    "right_v",
18788                    vec![Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(400)],
18789                ),
18790            ],
18791        )
18792        .unwrap();
18793
18794        let merged = merge_dataframes_on_with(
18795            &left,
18796            &right,
18797            &["lk1", "lk2"],
18798            &["rk1", "rk2"],
18799            JoinType::Outer,
18800        )
18801        .unwrap();
18802
18803        assert_eq!(
18804            merged.columns.get("lk1").unwrap().values(),
18805            &[
18806                Scalar::Float64(1.0),
18807                Scalar::Float64(2.0),
18808                Scalar::Float64(3.0),
18809                Scalar::Null(NullKind::NaN)
18810            ]
18811        );
18812        assert_eq!(
18813            merged.columns.get("rk1").unwrap().values(),
18814            &[
18815                Scalar::Float64(1.0),
18816                Scalar::Float64(2.0),
18817                Scalar::Null(NullKind::NaN),
18818                Scalar::Float64(4.0)
18819            ]
18820        );
18821        assert_eq!(
18822            merged.columns.get("left_v").unwrap().values(),
18823            &[
18824                Scalar::Float64(10.0),
18825                Scalar::Float64(20.0),
18826                Scalar::Float64(30.0),
18827                Scalar::Null(NullKind::NaN)
18828            ]
18829        );
18830        assert_eq!(
18831            merged.columns.get("right_v").unwrap().values(),
18832            &[
18833                Scalar::Float64(100.0),
18834                Scalar::Float64(200.0),
18835                Scalar::Null(NullKind::NaN),
18836                Scalar::Float64(400.0)
18837            ]
18838        );
18839    }
18840
18841    #[test]
18842    fn merge_key_alias_lists_must_have_equal_lengths() {
18843        let left = make_left_df();
18844        let right = make_right_df();
18845        let err = merge_dataframes_on_with(&left, &right, &["id", "id"], &["id"], JoinType::Inner)
18846            .expect_err("should fail");
18847        assert!(format!("{err}").contains("equal length"));
18848    }
18849
18850    #[test]
18851    fn merge_indicator_default_name_tracks_row_provenance() {
18852        let left = make_left_df();
18853        let right = make_right_df();
18854
18855        let merged = merge_dataframes_on_with_options(
18856            &left,
18857            &right,
18858            &["id"],
18859            &["id"],
18860            JoinType::Outer,
18861            MergeExecutionOptions {
18862                indicator_name: Some("_merge".to_owned()),
18863                ..MergeExecutionOptions::default()
18864            },
18865        )
18866        .expect("merge");
18867
18868        assert_eq!(
18869            merged.columns.get("_merge").expect("indicator").values(),
18870            &[
18871                Scalar::Utf8("left_only".to_owned()),
18872                Scalar::Utf8("both".to_owned()),
18873                Scalar::Utf8("both".to_owned()),
18874                Scalar::Utf8("right_only".to_owned())
18875            ]
18876        );
18877    }
18878
18879    #[test]
18880    fn merge_indicator_custom_name_preserves_suffix_behavior() {
18881        let left = DataFrame::from_dict(
18882            &["id", "val"],
18883            vec![
18884                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
18885                ("val", vec![Scalar::Int64(10), Scalar::Int64(20)]),
18886            ],
18887        )
18888        .unwrap();
18889        let right = DataFrame::from_dict(
18890            &["id", "val"],
18891            vec![
18892                ("id", vec![Scalar::Int64(2), Scalar::Int64(3)]),
18893                ("val", vec![Scalar::Int64(200), Scalar::Int64(300)]),
18894            ],
18895        )
18896        .unwrap();
18897
18898        let merged = merge_dataframes_on_with_options(
18899            &left,
18900            &right,
18901            &["id"],
18902            &["id"],
18903            JoinType::Outer,
18904            MergeExecutionOptions {
18905                indicator_name: Some("origin".to_owned()),
18906                ..MergeExecutionOptions::default()
18907            },
18908        )
18909        .expect("merge");
18910
18911        assert!(merged.columns.contains_key("val_x"));
18912        assert!(merged.columns.contains_key("val_y"));
18913        assert_eq!(
18914            merged.columns.get("origin").expect("indicator").values(),
18915            &[
18916                Scalar::Utf8("left_only".to_owned()),
18917                Scalar::Utf8("both".to_owned()),
18918                Scalar::Utf8("right_only".to_owned())
18919            ]
18920        );
18921    }
18922
18923    #[test]
18924    fn merge_indicator_rejects_conflicting_column_name() {
18925        let left = make_left_df();
18926        let right = make_right_df();
18927
18928        let err = merge_dataframes_on_with_options(
18929            &left,
18930            &right,
18931            &["id"],
18932            &["id"],
18933            JoinType::Inner,
18934            MergeExecutionOptions {
18935                indicator_name: Some("id".to_owned()),
18936                ..MergeExecutionOptions::default()
18937            },
18938        )
18939        .expect_err("expected indicator name conflict");
18940        assert!(format!("{err}").contains("conflicts with an existing column"));
18941    }
18942
18943    #[test]
18944    fn merge_cross_indicator_marks_all_rows_both() {
18945        // Restored after br-frankenpandas-glsam revert: pandas 2.2.3
18946        // supports `how='cross', indicator=...` and emits "both" for every
18947        // cross-product row (verified against FP-P2D-039 fixture provenance
18948        // pandas_version=2.2.3). The Explore-agent claim that pandas raises
18949        // was incorrect; this test locks in the actual pandas behavior.
18950        let left = DataFrame::from_dict(
18951            &["l"],
18952            vec![("l", vec![Scalar::Int64(1), Scalar::Int64(2)])],
18953        )
18954        .unwrap();
18955        let right = DataFrame::from_dict(&["r"], vec![("r", vec![Scalar::Int64(9)])]).unwrap();
18956
18957        let merged = merge_dataframes_on_with_options(
18958            &left,
18959            &right,
18960            &["ignored"],
18961            &["ignored"],
18962            JoinType::Cross,
18963            MergeExecutionOptions {
18964                indicator_name: Some("_merge".to_owned()),
18965                ..MergeExecutionOptions::default()
18966            },
18967        )
18968        .expect("cross merge");
18969        assert_eq!(
18970            merged.columns.get("_merge").expect("indicator").values(),
18971            &[
18972                Scalar::Utf8("both".to_owned()),
18973                Scalar::Utf8("both".to_owned())
18974            ]
18975        );
18976    }
18977
18978    #[test]
18979    fn merge_cross_validate_mode_contract_ohb5f() {
18980        let left = DataFrame::from_dict(
18981            &["l"],
18982            vec![("l", vec![Scalar::Int64(1), Scalar::Int64(2)])],
18983        )
18984        .expect("left");
18985        let right = DataFrame::from_dict(
18986            &["r"],
18987            vec![("r", vec![Scalar::Int64(10), Scalar::Int64(20)])],
18988        )
18989        .expect("right");
18990
18991        let many_to_many = merge_dataframes_on_with_options(
18992            &left,
18993            &right,
18994            &["missing_left_key"],
18995            &["missing_right_key"],
18996            JoinType::Cross,
18997            MergeExecutionOptions {
18998                validate_mode: Some(MergeValidateMode::ManyToMany),
18999                ..MergeExecutionOptions::default()
19000            },
19001        )
19002        .expect("cross merge validate=many_to_many");
19003        assert_eq!(many_to_many.index.len(), 4);
19004
19005        for validate_mode in [
19006            MergeValidateMode::OneToOne,
19007            MergeValidateMode::OneToMany,
19008            MergeValidateMode::ManyToOne,
19009        ] {
19010            let err = merge_dataframes_on_with_options(
19011                &left,
19012                &right,
19013                &["missing_left_key"],
19014                &["missing_right_key"],
19015                JoinType::Cross,
19016                MergeExecutionOptions {
19017                    validate_mode: Some(validate_mode),
19018                    ..MergeExecutionOptions::default()
19019                },
19020            )
19021            .expect_err("enforcing validate modes are not meaningful for cross joins");
19022            let message = format!("{err}");
19023            assert!(message.contains(validate_mode.as_str()));
19024            assert!(message.contains("not supported for cross join"));
19025        }
19026    }
19027
19028    #[test]
19029    fn merge_validate_one_to_one_rejects_duplicate_left_keys() {
19030        let left = DataFrame::from_dict(
19031            &["id", "left_v"],
19032            vec![
19033                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
19034                ("left_v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
19035            ],
19036        )
19037        .expect("left frame");
19038        let right = DataFrame::from_dict(
19039            &["id", "right_v"],
19040            vec![
19041                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
19042                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
19043            ],
19044        )
19045        .expect("right frame");
19046
19047        let err = merge_dataframes_on_with_options(
19048            &left,
19049            &right,
19050            &["id"],
19051            &["id"],
19052            JoinType::Inner,
19053            MergeExecutionOptions {
19054                validate_mode: Some(MergeValidateMode::OneToOne),
19055                ..MergeExecutionOptions::default()
19056            },
19057        )
19058        .expect_err("one_to_one must reject duplicate left keys");
19059        assert!(format!("{err}").contains("left keys are not unique"));
19060    }
19061
19062    #[test]
19063    fn merge_validate_one_to_one_keeps_left_error_precedence_when_both_sides_duplicate() {
19064        let left = DataFrame::from_dict(
19065            &["id", "left_v"],
19066            vec![
19067                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
19068                ("left_v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
19069            ],
19070        )
19071        .expect("left frame");
19072        let right = DataFrame::from_dict(
19073            &["id", "right_v"],
19074            vec![
19075                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
19076                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
19077            ],
19078        )
19079        .expect("right frame");
19080
19081        let err = merge_dataframes_on_with_options(
19082            &left,
19083            &right,
19084            &["id"],
19085            &["id"],
19086            JoinType::Inner,
19087            MergeExecutionOptions {
19088                validate_mode: Some(MergeValidateMode::OneToOne),
19089                ..MergeExecutionOptions::default()
19090            },
19091        )
19092        .expect_err("one_to_one must reject duplicate left keys before right keys");
19093        assert!(format!("{err}").contains("left keys are not unique"));
19094    }
19095
19096    #[test]
19097    fn merge_validate_one_to_many_allows_duplicate_right_keys() {
19098        let left = DataFrame::from_dict(
19099            &["id", "left_v"],
19100            vec![
19101                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
19102                ("left_v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
19103            ],
19104        )
19105        .expect("left frame");
19106        let right = DataFrame::from_dict(
19107            &["id", "right_v"],
19108            vec![
19109                (
19110                    "id",
19111                    vec![Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(2)],
19112                ),
19113                (
19114                    "right_v",
19115                    vec![Scalar::Int64(100), Scalar::Int64(101), Scalar::Int64(200)],
19116                ),
19117            ],
19118        )
19119        .expect("right frame");
19120
19121        let merged = merge_dataframes_on_with_options(
19122            &left,
19123            &right,
19124            &["id"],
19125            &["id"],
19126            JoinType::Inner,
19127            MergeExecutionOptions {
19128                validate_mode: Some(MergeValidateMode::OneToMany),
19129                ..MergeExecutionOptions::default()
19130            },
19131        )
19132        .expect("one_to_many should allow duplicate right keys");
19133        assert_eq!(merged.columns.get("id").expect("id").values().len(), 3);
19134    }
19135
19136    #[test]
19137    fn merge_validate_one_to_many_rejects_duplicate_left_keys_9hsb3() {
19138        let left = DataFrame::from_dict(
19139            &["id", "left_v"],
19140            vec![
19141                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
19142                ("left_v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
19143            ],
19144        )
19145        .expect("left frame");
19146        let right = DataFrame::from_dict(
19147            &["id", "right_v"],
19148            vec![
19149                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
19150                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
19151            ],
19152        )
19153        .expect("right frame");
19154
19155        let err = merge_dataframes_on_with_options(
19156            &left,
19157            &right,
19158            &["id"],
19159            &["id"],
19160            JoinType::Inner,
19161            MergeExecutionOptions {
19162                validate_mode: Some(MergeValidateMode::OneToMany),
19163                ..MergeExecutionOptions::default()
19164            },
19165        )
19166        .expect_err("one_to_many must reject duplicate left keys");
19167        assert!(format!("{err}").contains("left keys are not unique"));
19168    }
19169
19170    #[test]
19171    fn merge_validate_many_to_one_rejects_duplicate_right_keys() {
19172        let left = DataFrame::from_dict(
19173            &["id", "left_v"],
19174            vec![
19175                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
19176                ("left_v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
19177            ],
19178        )
19179        .expect("left frame");
19180        let right = DataFrame::from_dict(
19181            &["id", "right_v"],
19182            vec![
19183                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
19184                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(101)]),
19185            ],
19186        )
19187        .expect("right frame");
19188
19189        let err = merge_dataframes_on_with_options(
19190            &left,
19191            &right,
19192            &["id"],
19193            &["id"],
19194            JoinType::Inner,
19195            MergeExecutionOptions {
19196                validate_mode: Some(MergeValidateMode::ManyToOne),
19197                ..MergeExecutionOptions::default()
19198            },
19199        )
19200        .expect_err("many_to_one must reject duplicate right keys");
19201        assert!(format!("{err}").contains("right keys are not unique"));
19202    }
19203
19204    #[test]
19205    fn merge_validate_many_to_one_allows_duplicate_left_keys_9hsb3() {
19206        let left = DataFrame::from_dict(
19207            &["id", "left_v"],
19208            vec![
19209                (
19210                    "id",
19211                    vec![Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(2)],
19212                ),
19213                (
19214                    "left_v",
19215                    vec![Scalar::Int64(10), Scalar::Int64(11), Scalar::Int64(20)],
19216                ),
19217            ],
19218        )
19219        .expect("left frame");
19220        let right = DataFrame::from_dict(
19221            &["id", "right_v"],
19222            vec![
19223                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
19224                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
19225            ],
19226        )
19227        .expect("right frame");
19228
19229        let merged = merge_dataframes_on_with_options(
19230            &left,
19231            &right,
19232            &["id"],
19233            &["id"],
19234            JoinType::Inner,
19235            MergeExecutionOptions {
19236                validate_mode: Some(MergeValidateMode::ManyToOne),
19237                ..MergeExecutionOptions::default()
19238            },
19239        )
19240        .expect("many_to_one should allow duplicate left keys");
19241        assert_eq!(merged.columns.get("id").expect("id").values().len(), 3);
19242    }
19243
19244    #[test]
19245    fn merge_validate_many_to_many_allows_duplicates_on_both_sides() {
19246        let left = DataFrame::from_dict(
19247            &["id", "left_v"],
19248            vec![
19249                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
19250                ("left_v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
19251            ],
19252        )
19253        .expect("left frame");
19254        let right = DataFrame::from_dict(
19255            &["id", "right_v"],
19256            vec![
19257                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
19258                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
19259            ],
19260        )
19261        .expect("right frame");
19262
19263        let merged = merge_dataframes_on_with_options(
19264            &left,
19265            &right,
19266            &["id"],
19267            &["id"],
19268            JoinType::Inner,
19269            MergeExecutionOptions {
19270                validate_mode: Some(MergeValidateMode::ManyToMany),
19271                ..MergeExecutionOptions::default()
19272            },
19273        )
19274        .expect("many_to_many should allow duplicate keys on both sides");
19275        assert_eq!(merged.columns.get("id").expect("id").values().len(), 4);
19276    }
19277
19278    #[test]
19279    fn join_series_cross_cartesian_product() {
19280        let left = Series::from_values(
19281            "left",
19282            vec!["a".into(), "b".into()],
19283            vec![Scalar::Int64(1), Scalar::Int64(2)],
19284        )
19285        .unwrap();
19286        let right = Series::from_values(
19287            "right",
19288            vec!["x".into(), "y".into()],
19289            vec![Scalar::Int64(10), Scalar::Int64(20)],
19290        )
19291        .unwrap();
19292
19293        let out = join_series(&left, &right, JoinType::Cross).unwrap();
19294        assert_eq!(out.index.labels().len(), 4);
19295        assert_eq!(
19296            out.left_values.values(),
19297            &[
19298                Scalar::Int64(1),
19299                Scalar::Int64(1),
19300                Scalar::Int64(2),
19301                Scalar::Int64(2)
19302            ]
19303        );
19304        assert_eq!(
19305            out.right_values.values(),
19306            &[
19307                Scalar::Int64(10),
19308                Scalar::Int64(20),
19309                Scalar::Int64(10),
19310                Scalar::Int64(20)
19311            ]
19312        );
19313    }
19314
19315    // ── DataFrameMergeExt trait tests ──
19316
19317    #[test]
19318    fn dataframe_merge_via_trait() {
19319        use fp_frame::DataFrame;
19320
19321        use super::{DataFrameMergeExt, merge_dataframes_on};
19322
19323        let left = DataFrame::from_series(vec![
19324            Series::from_values(
19325                "key",
19326                vec![0_i64.into(), 1_i64.into()],
19327                vec![Scalar::Int64(1), Scalar::Int64(2)],
19328            )
19329            .unwrap(),
19330            Series::from_values(
19331                "val_l",
19332                vec![0_i64.into(), 1_i64.into()],
19333                vec![Scalar::Int64(10), Scalar::Int64(20)],
19334            )
19335            .unwrap(),
19336        ])
19337        .unwrap();
19338
19339        let right = DataFrame::from_series(vec![
19340            Series::from_values(
19341                "key",
19342                vec![0_i64.into(), 1_i64.into()],
19343                vec![Scalar::Int64(1), Scalar::Int64(3)],
19344            )
19345            .unwrap(),
19346            Series::from_values(
19347                "val_r",
19348                vec![0_i64.into(), 1_i64.into()],
19349                vec![Scalar::Int64(100), Scalar::Int64(300)],
19350            )
19351            .unwrap(),
19352        ])
19353        .unwrap();
19354
19355        // Instance method
19356        let result = left.merge(&right, &["key"], JoinType::Inner).unwrap();
19357        assert_eq!(result.index.len(), 1); // only key=1 matches
19358
19359        // Standalone function should give same result
19360        let result2 = merge_dataframes_on(&left, &right, &["key"], JoinType::Inner).unwrap();
19361        assert_eq!(result.index.len(), result2.index.len());
19362    }
19363
19364    // ── merge_asof tests ──
19365
19366    fn compute_asof_matches_datetime64_former_nsslz(
19367        left: super::Datetime64AsofKey<'_>,
19368        right: super::Datetime64AsofKey<'_>,
19369        direction: super::AsofDirection,
19370        allow_exact_matches: bool,
19371        tolerance: Option<f64>,
19372    ) -> Vec<Option<usize>> {
19373        let mut right_valid_values = Vec::new();
19374        let mut right_valid_positions = Vec::new();
19375        for i in 0..right.data.len() {
19376            if right.is_valid(i) {
19377                right_valid_values.push(right.data[i]);
19378                right_valid_positions.push(i);
19379            }
19380        }
19381        super::compute_asof_matches_datetime64_prepared(
19382            left,
19383            &right_valid_values,
19384            Some(&right_valid_positions),
19385            direction,
19386            allow_exact_matches,
19387            tolerance,
19388        )
19389    }
19390
19391    #[test]
19392    fn merge_asof_datetime64_borrowed_dense_right_matches_former_nsslz() {
19393        let dense_left = Column::from_datetime64_values_with_validity(
19394            vec![-15, -10, -5, 0, 5, 30, 35],
19395            ValidityMask::all_valid(7),
19396        );
19397        let dense_right = Column::from_datetime64_values_with_validity(
19398            vec![-10, 0, 10, 20, 30],
19399            ValidityMask::all_valid(5),
19400        );
19401
19402        let nat_right = Column::from_datetime64_values_with_validity(
19403            vec![fp_types::Timestamp::NAT, -10, 0, 20, 30],
19404            ValidityMask::all_valid(5),
19405        );
19406        let nat_left = Column::from_datetime64_values_with_validity(
19407            vec![fp_types::Timestamp::NAT, -10, -5, 0, 5, 30, 35],
19408            ValidityMask::all_valid(7),
19409        );
19410
19411        for (left, right) in [
19412            (&dense_left, &dense_right),
19413            (&dense_left, &nat_right),
19414            (&nat_left, &dense_right),
19415        ] {
19416            let left_key = super::datetime64_key_parts(left).expect("Datetime64 left key");
19417            let right_key = super::datetime64_key_parts(right).expect("Datetime64 right key");
19418            for direction in [
19419                super::AsofDirection::Backward,
19420                super::AsofDirection::Forward,
19421                super::AsofDirection::Nearest,
19422            ] {
19423                for allow_exact_matches in [false, true] {
19424                    for tolerance in [None, Some(7.0)] {
19425                        assert_eq!(
19426                            super::compute_asof_matches_datetime64(
19427                                left_key,
19428                                right_key,
19429                                direction,
19430                                allow_exact_matches,
19431                                tolerance,
19432                            ),
19433                            compute_asof_matches_datetime64_former_nsslz(
19434                                left_key,
19435                                right_key,
19436                                direction,
19437                                allow_exact_matches,
19438                                tolerance,
19439                            ),
19440                            "direction={direction:?} exact={allow_exact_matches} tolerance={tolerance:?}",
19441                        );
19442                    }
19443                }
19444            }
19445        }
19446    }
19447
19448    #[test]
19449    #[ignore = "foreground release A/B only"]
19450    fn datetime64_asof_borrowed_dense_right_ab_nsslz() {
19451        use std::{hint::black_box, time::Instant};
19452
19453        const ITEMS: usize = 131_072;
19454        const SAMPLES: usize = 10;
19455
19456        fn elapsed(run: impl FnOnce() -> Vec<Option<usize>>) -> u128 {
19457            let started = Instant::now();
19458            let output = black_box(run());
19459            black_box(output.len());
19460            let elapsed = started.elapsed().as_nanos();
19461            drop(output);
19462            elapsed
19463        }
19464
19465        let left = Column::from_datetime64_values_with_validity(
19466            (0..ITEMS).map(|i| i as i64 * 4 + 1).collect(),
19467            ValidityMask::all_valid(ITEMS),
19468        );
19469        let right = Column::from_datetime64_values_with_validity(
19470            (0..ITEMS).map(|i| i as i64 * 4).collect(),
19471            ValidityMask::all_valid(ITEMS),
19472        );
19473        let left_key = super::datetime64_key_parts(&left).expect("Datetime64 left key");
19474        let right_key = super::datetime64_key_parts(&right).expect("Datetime64 right key");
19475        let former = || {
19476            compute_asof_matches_datetime64_former_nsslz(
19477                left_key,
19478                right_key,
19479                super::AsofDirection::Backward,
19480                true,
19481                None,
19482            )
19483        };
19484        let candidate = || {
19485            super::compute_asof_matches_datetime64(
19486                left_key,
19487                right_key,
19488                super::AsofDirection::Backward,
19489                true,
19490                None,
19491            )
19492        };
19493
19494        assert_eq!(candidate(), former());
19495        black_box(former());
19496        black_box(candidate());
19497
19498        let mut former_ns = Vec::with_capacity(SAMPLES);
19499        let mut candidate_ns = Vec::with_capacity(SAMPLES);
19500        for sample in 0..SAMPLES {
19501            if sample.is_multiple_of(2) {
19502                former_ns.push(elapsed(former));
19503                candidate_ns.push(elapsed(candidate));
19504            } else {
19505                candidate_ns.push(elapsed(candidate));
19506                former_ns.push(elapsed(former));
19507            }
19508        }
19509        former_ns.sort_unstable();
19510        candidate_ns.sort_unstable();
19511        let former_p50 = former_ns[SAMPLES / 2];
19512        let candidate_p50 = candidate_ns[SAMPLES / 2];
19513        println!(
19514            "datetime64_asof_borrowed_dense_right_ab items={ITEMS} samples={SAMPLES} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} speedup={:.6}x",
19515            former_p50 as f64 / candidate_p50 as f64,
19516        );
19517        println!("former_samples_ns={former_ns:?}");
19518        println!("candidate_samples_ns={candidate_ns:?}");
19519    }
19520
19521    #[test]
19522    fn merge_asof_backward() {
19523        use super::DataFrameMergeExt;
19524
19525        // Left: trades at times 1, 3, 5, 7
19526        let left = fp_frame::DataFrame::from_dict(
19527            &["time", "price"],
19528            vec![
19529                (
19530                    "time",
19531                    vec![
19532                        Scalar::Int64(1),
19533                        Scalar::Int64(3),
19534                        Scalar::Int64(5),
19535                        Scalar::Int64(7),
19536                    ],
19537                ),
19538                (
19539                    "price",
19540                    vec![
19541                        Scalar::Float64(100.0),
19542                        Scalar::Float64(101.0),
19543                        Scalar::Float64(102.0),
19544                        Scalar::Float64(103.0),
19545                    ],
19546                ),
19547            ],
19548        )
19549        .unwrap();
19550
19551        // Right: quotes at times 2, 4, 6
19552        let right = fp_frame::DataFrame::from_dict(
19553            &["time", "bid"],
19554            vec![
19555                (
19556                    "time",
19557                    vec![Scalar::Int64(2), Scalar::Int64(4), Scalar::Int64(6)],
19558                ),
19559                (
19560                    "bid",
19561                    vec![
19562                        Scalar::Float64(99.5),
19563                        Scalar::Float64(100.5),
19564                        Scalar::Float64(101.5),
19565                    ],
19566                ),
19567            ],
19568        )
19569        .unwrap();
19570
19571        let result = left.merge_asof(&right, "time", "backward").unwrap();
19572        // For time=1: no right row <= 1, so bid=NaN
19573        // For time=3: last right row <= 3 is time=2 → bid=99.5
19574        // For time=5: last right row <= 5 is time=4 → bid=100.5
19575        // For time=7: last right row <= 7 is time=6 → bid=101.5
19576        let bid_col = result.columns.get("bid").unwrap();
19577        assert!(bid_col.values()[0].is_missing());
19578        assert_eq!(bid_col.values()[1], Scalar::Float64(99.5));
19579        assert_eq!(bid_col.values()[2], Scalar::Float64(100.5));
19580        assert_eq!(bid_col.values()[3], Scalar::Float64(101.5));
19581    }
19582
19583    /// A right column that gains an UNMATCHED row gains a gap, and an all-valid
19584    /// numpy int64 cannot hold one — pandas widens that column to float64,
19585    /// exactly as it does across the join family.
19586    ///
19587    /// Measured, live pandas 2.2.3:
19588    /// ```text
19589    ///   L = DataFrame({'time':[1,5,10], 'left_val':[10,50,100]})
19590    ///   R = DataFrame({'time':[2,6],    'right_val':[20,60]})
19591    ///   pd.merge_asof(L, R, on='time', direction='forward')
19592    ///     right_val -> [20.0, 60.0, NaN]  dtype float64
19593    ///     dtypes: time int64, left_val int64, right_val float64
19594    ///
19595    ///   L2 = DataFrame({'time':[1,5]}, ...); R2 = DataFrame({'time':[2,4]}, ...)
19596    ///   pd.merge_asof(L2, R2, on='time', direction='backward')
19597    ///     right_val -> [NaN, 40.0]        dtype float64
19598    ///
19599    ///   with every left row matched (times 3,7 against 2,4)
19600    ///     right_val -> [20, 40]           dtype int64
19601    /// ```
19602    /// The rule is PER COLUMN here — `time` and `left_val` gain no gap and stay
19603    /// int64 — unlike `Series.unstack`, where a gap widens the whole frame
19604    /// because it reshapes one block. Both fixtures on FP-P2D-056 pinned the
19605    /// present values as int64 beside the NaN, which is FrankenPandas' own
19606    /// pre-fix answer.
19607    #[test]
19608    fn merge_asof_unmatched_row_widens_that_column_to_float64() {
19609        use super::DataFrameMergeExt;
19610
19611        let int_frame = |name: &str, times: Vec<i64>, vals: Vec<i64>| {
19612            fp_frame::DataFrame::from_dict(
19613                &["time", name],
19614                vec![
19615                    (
19616                        "time",
19617                        times.into_iter().map(Scalar::Int64).collect::<Vec<_>>(),
19618                    ),
19619                    (
19620                        name,
19621                        vals.into_iter().map(Scalar::Int64).collect::<Vec<_>>(),
19622                    ),
19623                ],
19624            )
19625            .unwrap()
19626        };
19627
19628        let left = int_frame("left_val", vec![1, 5, 10], vec![10, 50, 100]);
19629        let right = int_frame("right_val", vec![2, 6], vec![20, 60]);
19630        let forward = left.merge_asof(&right, "time", "forward").unwrap();
19631        assert_eq!(
19632            forward.columns.get("right_val").unwrap().values(),
19633            &[
19634                Scalar::Float64(20.0),
19635                Scalar::Float64(60.0),
19636                Scalar::Null(NullKind::NaN),
19637            ]
19638        );
19639        // The columns that gain NO gap keep int64 — this is per column, not
19640        // frame-wide.
19641        assert_eq!(
19642            forward.columns.get("left_val").unwrap().values(),
19643            &[Scalar::Int64(10), Scalar::Int64(50), Scalar::Int64(100)]
19644        );
19645        assert_eq!(
19646            forward.columns.get("time").unwrap().dtype(),
19647            fp_types::DType::Int64
19648        );
19649
19650        let backward = int_frame("left_val", vec![1, 5], vec![10, 50])
19651            .merge_asof(
19652                &int_frame("right_val", vec![2, 4], vec![20, 40]),
19653                "time",
19654                "backward",
19655            )
19656            .unwrap();
19657        assert_eq!(
19658            backward.columns.get("right_val").unwrap().values(),
19659            &[Scalar::Null(NullKind::NaN), Scalar::Float64(40.0)]
19660        );
19661
19662        // The control that this is about the GAP and not about merge_asof always
19663        // widening: with every left row matched, right_val stays int64.
19664        let matched = int_frame("left_val", vec![3, 7], vec![10, 50])
19665            .merge_asof(
19666                &int_frame("right_val", vec![2, 4], vec![20, 40]),
19667                "time",
19668                "backward",
19669            )
19670            .unwrap();
19671        assert_eq!(
19672            matched.columns.get("right_val").unwrap().values(),
19673            &[Scalar::Int64(20), Scalar::Int64(40)]
19674        );
19675    }
19676
19677    #[test]
19678    fn merge_asof_forward() {
19679        use super::AsofDirection;
19680
19681        let left = fp_frame::DataFrame::from_dict(
19682            &["time", "val"],
19683            vec![
19684                ("time", vec![Scalar::Int64(1), Scalar::Int64(3)]),
19685                ("val", vec![Scalar::Float64(10.0), Scalar::Float64(30.0)]),
19686            ],
19687        )
19688        .unwrap();
19689
19690        let right = fp_frame::DataFrame::from_dict(
19691            &["time", "quote"],
19692            vec![
19693                ("time", vec![Scalar::Int64(2), Scalar::Int64(5)]),
19694                ("quote", vec![Scalar::Float64(20.0), Scalar::Float64(50.0)]),
19695            ],
19696        )
19697        .unwrap();
19698
19699        let result = super::merge_asof(&left, &right, "time", AsofDirection::Forward).unwrap();
19700        // time=1: first right >= 1 is time=2 → quote=20
19701        // time=3: first right >= 3 is time=5 → quote=50
19702        let quote_col = result.columns.get("quote").unwrap();
19703        assert_eq!(quote_col.values()[0], Scalar::Float64(20.0));
19704        assert_eq!(quote_col.values()[1], Scalar::Float64(50.0));
19705    }
19706
19707    #[test]
19708    fn merge_asof_nearest() {
19709        use super::AsofDirection;
19710
19711        let left = fp_frame::DataFrame::from_dict(
19712            &["time", "val"],
19713            vec![
19714                ("time", vec![Scalar::Int64(3), Scalar::Int64(7)]),
19715                ("val", vec![Scalar::Float64(1.0), Scalar::Float64(2.0)]),
19716            ],
19717        )
19718        .unwrap();
19719
19720        let right = fp_frame::DataFrame::from_dict(
19721            &["time", "ref_val"],
19722            vec![
19723                (
19724                    "time",
19725                    vec![Scalar::Int64(1), Scalar::Int64(5), Scalar::Int64(10)],
19726                ),
19727                (
19728                    "ref_val",
19729                    vec![
19730                        Scalar::Float64(100.0),
19731                        Scalar::Float64(500.0),
19732                        Scalar::Float64(1000.0),
19733                    ],
19734                ),
19735            ],
19736        )
19737        .unwrap();
19738
19739        let result = super::merge_asof(&left, &right, "time", AsofDirection::Nearest).unwrap();
19740        // time=3: nearest is 1(dist=2) or 5(dist=2), first found = 1 → ref_val=100
19741        // Actually: for nearest, it finds the one with smallest dist. dist(3,1)=2, dist(3,5)=2
19742        // ties go to first found, so ref_val = 100
19743        // time=7: nearest is 5(dist=2) or 10(dist=3) → ref_val=500
19744        let ref_col = result.columns.get("ref_val").unwrap();
19745        assert_eq!(ref_col.values()[1], Scalar::Float64(500.0)); // time=7 → 5 is nearest
19746    }
19747
19748    #[test]
19749    fn merge_asof_nearest_excludes_exact_finds_neighbor() {
19750        // Regression: with direction=nearest and allow_exact_matches=false,
19751        // an exact-equal key must be skipped over to reach the nearest
19752        // non-equal key, rather than yielding no match. Verified against
19753        // pandas 2.2.3: merge_asof(left=5, right=[3,5,5], nearest,
19754        // allow_exact_matches=False) -> matches value 3.
19755        use super::{AsofDirection, MergeAsofOptions};
19756
19757        let left = fp_frame::DataFrame::from_dict(
19758            &["time", "val"],
19759            vec![
19760                ("time", vec![Scalar::Int64(5)]),
19761                ("val", vec![Scalar::Int64(1)]),
19762            ],
19763        )
19764        .unwrap();
19765        let right = fp_frame::DataFrame::from_dict(
19766            &["time", "ref_val"],
19767            vec![
19768                (
19769                    "time",
19770                    vec![Scalar::Int64(3), Scalar::Int64(5), Scalar::Int64(5)],
19771                ),
19772                (
19773                    "ref_val",
19774                    vec![
19775                        Scalar::Float64(10.0),
19776                        Scalar::Float64(20.0),
19777                        Scalar::Float64(30.0),
19778                    ],
19779                ),
19780            ],
19781        )
19782        .unwrap();
19783
19784        let opts = MergeAsofOptions::new().allow_exact_matches(false);
19785        let result =
19786            super::merge_asof_with_options(&left, &right, "time", AsofDirection::Nearest, opts)
19787                .unwrap();
19788        let ref_col = result.columns.get("ref_val").unwrap();
19789        assert_eq!(ref_col.values()[0], Scalar::Float64(10.0)); // value 3 is nearest non-exact
19790    }
19791
19792    #[test]
19793    fn merge_asof_exact_match() {
19794        use super::AsofDirection;
19795
19796        let left = fp_frame::DataFrame::from_dict(
19797            &["time", "val"],
19798            vec![
19799                ("time", vec![Scalar::Int64(2), Scalar::Int64(4)]),
19800                ("val", vec![Scalar::Float64(1.0), Scalar::Float64(2.0)]),
19801            ],
19802        )
19803        .unwrap();
19804
19805        let right = fp_frame::DataFrame::from_dict(
19806            &["time", "quote"],
19807            vec![
19808                ("time", vec![Scalar::Int64(2), Scalar::Int64(4)]),
19809                ("quote", vec![Scalar::Float64(20.0), Scalar::Float64(40.0)]),
19810            ],
19811        )
19812        .unwrap();
19813
19814        // Backward: exact match should work (right_val <= left_val includes ==).
19815        let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
19816        assert_eq!(
19817            result.columns.get("quote").unwrap().values()[0],
19818            Scalar::Float64(20.0)
19819        );
19820        assert_eq!(
19821            result.columns.get("quote").unwrap().values()[1],
19822            Scalar::Float64(40.0)
19823        );
19824
19825        // Forward: exact match should work (right_val >= left_val includes ==).
19826        let result = super::merge_asof(&left, &right, "time", AsofDirection::Forward).unwrap();
19827        assert_eq!(
19828            result.columns.get("quote").unwrap().values()[0],
19829            Scalar::Float64(20.0)
19830        );
19831    }
19832
19833    #[test]
19834    fn merge_asof_datetime64_wide_ns_range_uses_i64_path() {
19835        use super::AsofDirection;
19836
19837        let day_ns = 86_400_000_000_000i64;
19838        let base = 1_600_000_000_000_000_000i64;
19839        let dt = |days: i64| Scalar::Datetime64(base + days * day_ns);
19840
19841        let left = fp_frame::DataFrame::from_dict(
19842            &["time", "val"],
19843            vec![
19844                ("time", vec![dt(0), dt(200), dt(400)]),
19845                (
19846                    "val",
19847                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
19848                ),
19849            ],
19850        )
19851        .unwrap();
19852
19853        let right = fp_frame::DataFrame::from_dict(
19854            &["time", "quote"],
19855            vec![
19856                ("time", vec![dt(-1), dt(199), dt(401)]),
19857                (
19858                    "quote",
19859                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
19860                ),
19861            ],
19862        )
19863        .unwrap();
19864
19865        let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
19866        let quote_col = result.columns.get("quote").unwrap();
19867        assert_eq!(quote_col.values()[0], Scalar::Int64(10));
19868        assert_eq!(quote_col.values()[1], Scalar::Int64(20));
19869        assert_eq!(quote_col.values()[2], Scalar::Int64(20));
19870    }
19871
19872    #[test]
19873    fn merge_asof_no_matches_backward() {
19874        use super::AsofDirection;
19875
19876        let left = fp_frame::DataFrame::from_dict(
19877            &["time", "val"],
19878            vec![
19879                ("time", vec![Scalar::Int64(1)]),
19880                ("val", vec![Scalar::Float64(10.0)]),
19881            ],
19882        )
19883        .unwrap();
19884
19885        // Right starts at time=5, so backward from time=1 finds nothing.
19886        let right = fp_frame::DataFrame::from_dict(
19887            &["time", "quote"],
19888            vec![
19889                ("time", vec![Scalar::Int64(5)]),
19890                ("quote", vec![Scalar::Float64(50.0)]),
19891            ],
19892        )
19893        .unwrap();
19894
19895        let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
19896        assert!(result.columns.get("quote").unwrap().values()[0].is_missing());
19897    }
19898
19899    #[test]
19900    fn merge_asof_no_matches_forward() {
19901        use super::AsofDirection;
19902
19903        let left = fp_frame::DataFrame::from_dict(
19904            &["time", "val"],
19905            vec![
19906                ("time", vec![Scalar::Int64(10)]),
19907                ("val", vec![Scalar::Float64(10.0)]),
19908            ],
19909        )
19910        .unwrap();
19911
19912        // Right ends at time=5, so forward from time=10 finds nothing.
19913        let right = fp_frame::DataFrame::from_dict(
19914            &["time", "quote"],
19915            vec![
19916                ("time", vec![Scalar::Int64(5)]),
19917                ("quote", vec![Scalar::Float64(50.0)]),
19918            ],
19919        )
19920        .unwrap();
19921
19922        let result = super::merge_asof(&left, &right, "time", AsofDirection::Forward).unwrap();
19923        assert!(result.columns.get("quote").unwrap().values()[0].is_missing());
19924    }
19925
19926    #[test]
19927    fn merge_asof_nan_in_key() {
19928        use super::AsofDirection;
19929
19930        let left = fp_frame::DataFrame::from_dict(
19931            &["time", "val"],
19932            vec![
19933                (
19934                    "time",
19935                    vec![
19936                        Scalar::Int64(1),
19937                        Scalar::Null(NullKind::NaN),
19938                        Scalar::Int64(5),
19939                    ],
19940                ),
19941                (
19942                    "val",
19943                    vec![
19944                        Scalar::Float64(10.0),
19945                        Scalar::Float64(20.0),
19946                        Scalar::Float64(30.0),
19947                    ],
19948                ),
19949            ],
19950        )
19951        .unwrap();
19952
19953        let right = fp_frame::DataFrame::from_dict(
19954            &["time", "quote"],
19955            vec![
19956                ("time", vec![Scalar::Int64(2), Scalar::Int64(4)]),
19957                (
19958                    "quote",
19959                    vec![Scalar::Float64(200.0), Scalar::Float64(400.0)],
19960                ),
19961            ],
19962        )
19963        .unwrap();
19964
19965        // With matching key dtypes, pandas merge_asof accepts NaN keys: the
19966        // NaN row gets no match (null in joined columns).
19967        let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
19968        assert!(result.columns.get("quote").unwrap().values()[1].is_missing());
19969        // time=5 → backward match to time=4 → quote=400
19970        assert_eq!(
19971            result.columns.get("quote").unwrap().values()[2],
19972            Scalar::Float64(400.0)
19973        );
19974    }
19975
19976    #[test]
19977    fn merge_asof_rejects_incompatible_key_dtypes_sopel() {
19978        use super::{AsofDirection, MergeAsofOptions};
19979
19980        // pandas 2.2.3: a NaN makes the left `time` column float64, and
19981        // `merge_asof` refuses it against an int64 right key rather than
19982        // coercing both to a common numeric lane.
19983        let left = fp_frame::DataFrame::from_dict(
19984            &["time", "left_val", "group"],
19985            vec![
19986                (
19987                    "time",
19988                    vec![
19989                        Scalar::Float64(1.0),
19990                        Scalar::Null(NullKind::NaN),
19991                        Scalar::Float64(4.0),
19992                    ],
19993                ),
19994                (
19995                    "left_val",
19996                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
19997                ),
19998                (
19999                    "group",
20000                    vec![
20001                        Scalar::Utf8("a".into()),
20002                        Scalar::Utf8("a".into()),
20003                        Scalar::Utf8("a".into()),
20004                    ],
20005                ),
20006            ],
20007        )
20008        .unwrap();
20009        let right = fp_frame::DataFrame::from_dict(
20010            &["time", "right_val", "group"],
20011            vec![
20012                ("time", vec![Scalar::Int64(1), Scalar::Int64(3)]),
20013                ("right_val", vec![Scalar::Int64(100), Scalar::Int64(300)]),
20014                (
20015                    "group",
20016                    vec![Scalar::Utf8("a".into()), Scalar::Utf8("a".into())],
20017                ),
20018            ],
20019        )
20020        .unwrap();
20021
20022        for options in [
20023            MergeAsofOptions::new(),
20024            MergeAsofOptions::new().by(vec!["group".to_owned()]),
20025        ] {
20026            let error = super::merge_asof_with_options(
20027                &left,
20028                &right,
20029                "time",
20030                AsofDirection::Backward,
20031                options,
20032            )
20033            .expect_err("mixed float64/int64 asof keys must be rejected");
20034            assert!(matches!(
20035                error,
20036                super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(message))
20037                    if message.contains("incompatible merge keys")
20038                        && message.contains("float64")
20039                        && message.contains("int64")
20040            ));
20041        }
20042
20043        // This is the fixture-shaped representation: the null marker makes
20044        // the left lane nullable Int64, while the all-valid right lane stays
20045        // numpy int64. pandas rejects that pair as incompatible too.
20046        let mut nullable_columns = ColumnStore::new();
20047        nullable_columns.insert(
20048            "time".to_owned(),
20049            Column::new(
20050                DType::Int64Nullable,
20051                vec![
20052                    Scalar::Int64(1),
20053                    Scalar::Null(NullKind::NaN),
20054                    Scalar::Int64(4),
20055                ],
20056            )
20057            .unwrap(),
20058        );
20059        nullable_columns.insert(
20060            "left_val".to_owned(),
20061            Column::from_i64_values(vec![10, 20, 30]),
20062        );
20063        let nullable_left = fp_frame::DataFrame::new_with_column_order(
20064            Index::new_known_unique_int64_unit_range(0, 3),
20065            nullable_columns,
20066            vec!["time".to_owned(), "left_val".to_owned()],
20067        )
20068        .unwrap();
20069        let error = super::merge_asof(&nullable_left, &right, "time", AsofDirection::Backward)
20070            .expect_err("nullable Int64 and int64 asof keys must be rejected");
20071        assert!(matches!(
20072            error,
20073            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(message))
20074                if message.contains("incompatible merge keys")
20075                    && message.contains("left dtype('Int64')")
20076                    && message.contains("right dtype('int64')")
20077        ));
20078    }
20079
20080    #[test]
20081    fn merge_asof_nan_in_right_key() {
20082        use super::AsofDirection;
20083
20084        // Symmetric to merge_asof_nan_in_key: NaN keys on the right side
20085        // also get treated as no-candidate (pandas does NOT raise). Other
20086        // left rows still match to non-NaN right rows.
20087        let left = fp_frame::DataFrame::from_dict(
20088            &["time", "val"],
20089            vec![
20090                (
20091                    "time",
20092                    vec![Scalar::Int64(1), Scalar::Int64(3), Scalar::Int64(5)],
20093                ),
20094                (
20095                    "val",
20096                    vec![
20097                        Scalar::Float64(10.0),
20098                        Scalar::Float64(20.0),
20099                        Scalar::Float64(30.0),
20100                    ],
20101                ),
20102            ],
20103        )
20104        .unwrap();
20105
20106        let right = fp_frame::DataFrame::from_dict(
20107            &["time", "quote"],
20108            vec![
20109                (
20110                    "time",
20111                    vec![
20112                        Scalar::Int64(2),
20113                        Scalar::Null(NullKind::NaN),
20114                        Scalar::Int64(4),
20115                    ],
20116                ),
20117                (
20118                    "quote",
20119                    vec![
20120                        Scalar::Float64(200.0),
20121                        Scalar::Float64(999.0),
20122                        Scalar::Float64(400.0),
20123                    ],
20124                ),
20125            ],
20126        )
20127        .unwrap();
20128
20129        let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
20130        // left time=1 → no right ≤ 1 → null
20131        assert!(result.columns.get("quote").unwrap().values()[0].is_missing());
20132        // left time=3 → right time=2 → 200.0 (NaN right row never matches)
20133        assert_eq!(
20134            result.columns.get("quote").unwrap().values()[1],
20135            Scalar::Float64(200.0)
20136        );
20137        // left time=5 → right time=4 → 400.0
20138        assert_eq!(
20139            result.columns.get("quote").unwrap().values()[2],
20140            Scalar::Float64(400.0)
20141        );
20142    }
20143
20144    #[test]
20145    fn merge_asof_overlapping_columns_apply_suffixes() {
20146        use super::AsofDirection;
20147
20148        let left = fp_frame::DataFrame::from_dict(
20149            &["time", "shared", "left_only"],
20150            vec![
20151                ("time", vec![Scalar::Int64(1), Scalar::Int64(2)]),
20152                ("shared", vec![Scalar::Int64(10), Scalar::Int64(20)]),
20153                ("left_only", vec![Scalar::Int64(1), Scalar::Int64(2)]),
20154            ],
20155        )
20156        .unwrap();
20157
20158        let right = fp_frame::DataFrame::from_dict(
20159            &["time", "shared", "right_only"],
20160            vec![
20161                ("time", vec![Scalar::Int64(1), Scalar::Int64(2)]),
20162                ("shared", vec![Scalar::Int64(100), Scalar::Int64(200)]),
20163                ("right_only", vec![Scalar::Int64(9), Scalar::Int64(8)]),
20164            ],
20165        )
20166        .unwrap();
20167
20168        let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
20169        let shared_left = result.columns.get("shared_x").unwrap().values();
20170        let shared_right = result.columns.get("shared_y").unwrap().values();
20171
20172        assert_eq!(shared_left[0], Scalar::Int64(10));
20173        assert_eq!(shared_left[1], Scalar::Int64(20));
20174        assert_eq!(shared_right[0], Scalar::Int64(100));
20175        assert_eq!(shared_right[1], Scalar::Int64(200));
20176    }
20177
20178    #[test]
20179    fn merge_asof_duplicate_column_gets_suffix() {
20180        use super::AsofDirection;
20181
20182        // Both left and right have a "val" column besides the key.
20183        let left = fp_frame::DataFrame::from_dict(
20184            &["time", "val"],
20185            vec![
20186                ("time", vec![Scalar::Int64(1)]),
20187                ("val", vec![Scalar::Float64(10.0)]),
20188            ],
20189        )
20190        .unwrap();
20191
20192        let right = fp_frame::DataFrame::from_dict(
20193            &["time", "val"],
20194            vec![
20195                ("time", vec![Scalar::Int64(1)]),
20196                ("val", vec![Scalar::Float64(99.0)]),
20197            ],
20198        )
20199        .unwrap();
20200
20201        let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
20202        // Overlapping columns should receive default merge suffixes.
20203        assert!(result.columns.contains_key("val_x"));
20204        assert!(result.columns.contains_key("val_y"));
20205        assert_eq!(
20206            result.columns.get("val_x").unwrap().values()[0],
20207            Scalar::Float64(10.0)
20208        );
20209        assert_eq!(
20210            result.columns.get("val_y").unwrap().values()[0],
20211            Scalar::Float64(99.0)
20212        );
20213    }
20214
20215    #[test]
20216    fn merge_asof_missing_column_errors() {
20217        use super::AsofDirection;
20218
20219        let left =
20220            fp_frame::DataFrame::from_dict(&["a"], vec![("a", vec![Scalar::Int64(1)])]).unwrap();
20221
20222        let right =
20223            fp_frame::DataFrame::from_dict(&["b"], vec![("b", vec![Scalar::Int64(1)])]).unwrap();
20224
20225        let err = super::merge_asof(&left, &right, "time", AsofDirection::Backward);
20226        assert!(err.is_err());
20227    }
20228
20229    #[test]
20230    fn merge_asof_invalid_direction_errors() {
20231        let left =
20232            fp_frame::DataFrame::from_dict(&["time"], vec![("time", vec![Scalar::Int64(1)])])
20233                .unwrap();
20234        let right =
20235            fp_frame::DataFrame::from_dict(&["time"], vec![("time", vec![Scalar::Int64(1)])])
20236                .unwrap();
20237
20238        let err = left.merge_asof(&right, "time", "sideways");
20239        assert!(matches!(
20240            err,
20241            Err(super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(msg)))
20242                if msg.contains("invalid direction")
20243        ));
20244    }
20245
20246    #[test]
20247    fn merge_asof_unsorted_left_errors() {
20248        use super::AsofDirection;
20249
20250        let left = fp_frame::DataFrame::from_dict(
20251            &["time", "val"],
20252            vec![
20253                ("time", vec![Scalar::Int64(2), Scalar::Int64(1)]),
20254                ("val", vec![Scalar::Float64(10.0), Scalar::Float64(20.0)]),
20255            ],
20256        )
20257        .unwrap();
20258
20259        let right = fp_frame::DataFrame::from_dict(
20260            &["time", "quote"],
20261            vec![
20262                ("time", vec![Scalar::Int64(1), Scalar::Int64(2)]),
20263                (
20264                    "quote",
20265                    vec![Scalar::Float64(100.0), Scalar::Float64(200.0)],
20266                ),
20267            ],
20268        )
20269        .unwrap();
20270
20271        let err = super::merge_asof(&left, &right, "time", AsofDirection::Backward)
20272            .expect_err("unsorted left should error");
20273        assert!(matches!(
20274            err,
20275            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(msg))
20276                if msg.contains("sorted")
20277        ));
20278    }
20279
20280    #[test]
20281    fn merge_asof_unsorted_right_errors() {
20282        use super::AsofDirection;
20283
20284        let left = fp_frame::DataFrame::from_dict(
20285            &["time", "val"],
20286            vec![
20287                ("time", vec![Scalar::Int64(1), Scalar::Int64(2)]),
20288                ("val", vec![Scalar::Float64(10.0), Scalar::Float64(20.0)]),
20289            ],
20290        )
20291        .unwrap();
20292
20293        let right = fp_frame::DataFrame::from_dict(
20294            &["time", "quote"],
20295            vec![
20296                ("time", vec![Scalar::Int64(2), Scalar::Int64(1)]),
20297                (
20298                    "quote",
20299                    vec![Scalar::Float64(200.0), Scalar::Float64(100.0)],
20300                ),
20301            ],
20302        )
20303        .unwrap();
20304
20305        let err = super::merge_asof(&left, &right, "time", AsofDirection::Backward)
20306            .expect_err("unsorted right should error");
20307        assert!(matches!(
20308            err,
20309            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(msg))
20310                if msg.contains("sorted")
20311        ));
20312    }
20313
20314    #[test]
20315    fn merge_asof_non_numeric_key_errors() {
20316        use super::AsofDirection;
20317
20318        let left = fp_frame::DataFrame::from_dict(
20319            &["time", "val"],
20320            vec![
20321                ("time", vec![Scalar::Utf8("a".into())]),
20322                ("val", vec![Scalar::Float64(10.0)]),
20323            ],
20324        )
20325        .unwrap();
20326
20327        let right = fp_frame::DataFrame::from_dict(
20328            &["time", "quote"],
20329            vec![
20330                ("time", vec![Scalar::Utf8("b".into())]),
20331                ("quote", vec![Scalar::Float64(20.0)]),
20332            ],
20333        )
20334        .unwrap();
20335
20336        let err = super::merge_asof(&left, &right, "time", AsofDirection::Backward)
20337            .expect_err("non-numeric key should error");
20338        assert!(matches!(
20339            err,
20340            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(msg))
20341                if msg.contains("numeric")
20342        ));
20343    }
20344
20345    #[test]
20346    fn merge_asof_preserves_all_left_rows() {
20347        use super::AsofDirection;
20348
20349        let left = fp_frame::DataFrame::from_dict(
20350            &["time", "val"],
20351            vec![
20352                (
20353                    "time",
20354                    vec![
20355                        Scalar::Int64(1),
20356                        Scalar::Int64(2),
20357                        Scalar::Int64(3),
20358                        Scalar::Int64(4),
20359                        Scalar::Int64(5),
20360                    ],
20361                ),
20362                (
20363                    "val",
20364                    vec![
20365                        Scalar::Float64(10.0),
20366                        Scalar::Float64(20.0),
20367                        Scalar::Float64(30.0),
20368                        Scalar::Float64(40.0),
20369                        Scalar::Float64(50.0),
20370                    ],
20371                ),
20372            ],
20373        )
20374        .unwrap();
20375
20376        let right = fp_frame::DataFrame::from_dict(
20377            &["time", "quote"],
20378            vec![
20379                ("time", vec![Scalar::Int64(3)]),
20380                ("quote", vec![Scalar::Float64(300.0)]),
20381            ],
20382        )
20383        .unwrap();
20384
20385        let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
20386        // All 5 left rows should be present.
20387        assert_eq!(result.index.len(), 5);
20388    }
20389
20390    // ── merge_asof options tests ──
20391
20392    #[test]
20393    fn merge_asof_allow_exact_matches_false_backward() {
20394        use super::{AsofDirection, MergeAsofOptions, merge_asof_with_options};
20395
20396        // Left: keys 1, 2, 3
20397        let left = fp_frame::DataFrame::from_dict(
20398            &["time", "val"],
20399            vec![
20400                (
20401                    "time",
20402                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
20403                ),
20404                (
20405                    "val",
20406                    vec![
20407                        Scalar::Float64(10.0),
20408                        Scalar::Float64(20.0),
20409                        Scalar::Float64(30.0),
20410                    ],
20411                ),
20412            ],
20413        )
20414        .unwrap();
20415
20416        // Right: keys 1, 2, 3 (exact matches exist)
20417        let right = fp_frame::DataFrame::from_dict(
20418            &["time", "quote"],
20419            vec![
20420                (
20421                    "time",
20422                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
20423                ),
20424                (
20425                    "quote",
20426                    vec![
20427                        Scalar::Float64(100.0),
20428                        Scalar::Float64(200.0),
20429                        Scalar::Float64(300.0),
20430                    ],
20431                ),
20432            ],
20433        )
20434        .unwrap();
20435
20436        // With allow_exact_matches=true (default), all should match
20437        let result_with_exact = merge_asof_with_options(
20438            &left,
20439            &right,
20440            "time",
20441            AsofDirection::Backward,
20442            MergeAsofOptions::new(),
20443        )
20444        .unwrap();
20445
20446        let quote_col = result_with_exact.columns.get("quote").unwrap();
20447        assert_eq!(quote_col.values()[0], Scalar::Float64(100.0)); // 1 matches 1
20448        assert_eq!(quote_col.values()[1], Scalar::Float64(200.0)); // 2 matches 2
20449        assert_eq!(quote_col.values()[2], Scalar::Float64(300.0)); // 3 matches 3
20450
20451        // With allow_exact_matches=false, exact matches should be excluded
20452        let result_no_exact = merge_asof_with_options(
20453            &left,
20454            &right,
20455            "time",
20456            AsofDirection::Backward,
20457            MergeAsofOptions::new().allow_exact_matches(false),
20458        )
20459        .unwrap();
20460
20461        let quote_col_no_exact = result_no_exact.columns.get("quote").unwrap();
20462        // 1 has no previous right key, should be null
20463        assert!(matches!(quote_col_no_exact.values()[0], Scalar::Null(_)));
20464        // 2 should match previous (1)
20465        assert_eq!(quote_col_no_exact.values()[1], Scalar::Float64(100.0));
20466        // 3 should match previous (2)
20467        assert_eq!(quote_col_no_exact.values()[2], Scalar::Float64(200.0));
20468    }
20469
20470    #[test]
20471    fn merge_asof_tolerance() {
20472        use super::{AsofDirection, MergeAsofOptions, merge_asof_with_options};
20473
20474        // Left: keys 1, 5, 10
20475        let left = fp_frame::DataFrame::from_dict(
20476            &["time", "val"],
20477            vec![
20478                (
20479                    "time",
20480                    vec![Scalar::Int64(1), Scalar::Int64(5), Scalar::Int64(10)],
20481                ),
20482                (
20483                    "val",
20484                    vec![
20485                        Scalar::Float64(10.0),
20486                        Scalar::Float64(50.0),
20487                        Scalar::Float64(100.0),
20488                    ],
20489                ),
20490            ],
20491        )
20492        .unwrap();
20493
20494        // Right: keys 2, 6
20495        let right = fp_frame::DataFrame::from_dict(
20496            &["time", "quote"],
20497            vec![
20498                ("time", vec![Scalar::Int64(2), Scalar::Int64(6)]),
20499                (
20500                    "quote",
20501                    vec![Scalar::Float64(200.0), Scalar::Float64(600.0)],
20502                ),
20503            ],
20504        )
20505        .unwrap();
20506
20507        // With tolerance=2, matches within 2 units are valid
20508        let result = merge_asof_with_options(
20509            &left,
20510            &right,
20511            "time",
20512            AsofDirection::Backward,
20513            MergeAsofOptions::new().tolerance(2.0),
20514        )
20515        .unwrap();
20516
20517        let quote_col = result.columns.get("quote").unwrap();
20518        // 1 < 2, no previous match, null
20519        assert!(matches!(quote_col.values()[0], Scalar::Null(_)));
20520        // 5 finds 2 (diff = 3), but tolerance is 2, so null
20521        assert!(matches!(quote_col.values()[1], Scalar::Null(_)));
20522        // 10 finds 6 (diff = 4), but tolerance is 2, so null
20523        assert!(matches!(quote_col.values()[2], Scalar::Null(_)));
20524
20525        // With tolerance=5, all should match
20526        let result_wider = merge_asof_with_options(
20527            &left,
20528            &right,
20529            "time",
20530            AsofDirection::Backward,
20531            MergeAsofOptions::new().tolerance(5.0),
20532        )
20533        .unwrap();
20534
20535        let quote_col_wider = result_wider.columns.get("quote").unwrap();
20536        // 1 < 2, still no previous
20537        assert!(matches!(quote_col_wider.values()[0], Scalar::Null(_)));
20538        // 5 finds 2 (diff = 3 <= 5)
20539        assert_eq!(quote_col_wider.values()[1], Scalar::Float64(200.0));
20540        // 10 finds 6 (diff = 4 <= 5)
20541        assert_eq!(quote_col_wider.values()[2], Scalar::Float64(600.0));
20542    }
20543
20544    #[test]
20545    fn merge_asof_by_column() {
20546        use super::{AsofDirection, MergeAsofOptions, merge_asof_with_options};
20547
20548        // Left: two groups (A and B), each with times
20549        let left = fp_frame::DataFrame::from_dict(
20550            &["group", "time", "val"],
20551            vec![
20552                (
20553                    "group",
20554                    vec![
20555                        Scalar::Utf8("A".into()),
20556                        Scalar::Utf8("A".into()),
20557                        Scalar::Utf8("B".into()),
20558                        Scalar::Utf8("B".into()),
20559                    ],
20560                ),
20561                (
20562                    "time",
20563                    vec![
20564                        Scalar::Int64(1),
20565                        Scalar::Int64(2),
20566                        Scalar::Int64(3),
20567                        Scalar::Int64(4),
20568                    ],
20569                ),
20570                (
20571                    "val",
20572                    vec![
20573                        Scalar::Float64(10.0),
20574                        Scalar::Float64(30.0),
20575                        Scalar::Float64(20.0),
20576                        Scalar::Float64(40.0),
20577                    ],
20578                ),
20579            ],
20580        )
20581        .unwrap();
20582
20583        // Right: same groups with quotes
20584        let right = fp_frame::DataFrame::from_dict(
20585            &["group", "time", "quote"],
20586            vec![
20587                (
20588                    "group",
20589                    vec![
20590                        Scalar::Utf8("A".into()),
20591                        Scalar::Utf8("B".into()),
20592                        Scalar::Utf8("A".into()),
20593                    ],
20594                ),
20595                (
20596                    "time",
20597                    vec![Scalar::Int64(2), Scalar::Int64(3), Scalar::Int64(4)],
20598                ),
20599                (
20600                    "quote",
20601                    vec![
20602                        Scalar::Float64(200.0),
20603                        Scalar::Float64(400.0),
20604                        Scalar::Float64(300.0),
20605                    ],
20606                ),
20607            ],
20608        )
20609        .unwrap();
20610
20611        // Merge with 'by' column
20612        let result = merge_asof_with_options(
20613            &left,
20614            &right,
20615            "time",
20616            AsofDirection::Backward,
20617            MergeAsofOptions::new().by(vec!["group".to_string()]),
20618        )
20619        .unwrap();
20620
20621        let quote_col = result.columns.get("quote").unwrap();
20622        // Left after 2d3338b1's reorder is (A,1), (A,2), (B,3), (B,4) — globally
20623        // sorted by time. Right is (A,2), (B,3), (A,4). Backward grouped asof:
20624        // Row 0: (A,1) → no right A with time <= 1 → null
20625        assert!(matches!(quote_col.values()[0], Scalar::Null(_)));
20626        // Row 1: (A,2) → right A time=2 → 200.0
20627        assert_eq!(quote_col.values()[1], Scalar::Float64(200.0));
20628        // Row 2: (B,3) → right B time=3 → 400.0
20629        assert_eq!(quote_col.values()[2], Scalar::Float64(400.0));
20630        // Row 3: (B,4) → right B time=3 (latest <= 4) → 400.0
20631        assert_eq!(quote_col.values()[3], Scalar::Float64(400.0));
20632    }
20633
20634    #[test]
20635    fn merge_asof_by_column_requires_globally_sorted_left_keys() {
20636        use super::{AsofDirection, MergeAsofOptions, merge_asof_with_options};
20637
20638        let left = fp_frame::DataFrame::from_dict(
20639            &["group", "time"],
20640            vec![
20641                (
20642                    "group",
20643                    vec![
20644                        Scalar::Utf8("A".into()),
20645                        Scalar::Utf8("A".into()),
20646                        Scalar::Utf8("B".into()),
20647                        Scalar::Utf8("B".into()),
20648                    ],
20649                ),
20650                (
20651                    "time",
20652                    vec![
20653                        Scalar::Int64(1),
20654                        Scalar::Int64(3),
20655                        Scalar::Int64(1),
20656                        Scalar::Int64(2),
20657                    ],
20658                ),
20659            ],
20660        )
20661        .unwrap();
20662        let right = fp_frame::DataFrame::from_dict(
20663            &["group", "time", "quote"],
20664            vec![
20665                (
20666                    "group",
20667                    vec![
20668                        Scalar::Utf8("A".into()),
20669                        Scalar::Utf8("B".into()),
20670                        Scalar::Utf8("A".into()),
20671                    ],
20672                ),
20673                (
20674                    "time",
20675                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
20676                ),
20677                (
20678                    "quote",
20679                    vec![
20680                        Scalar::Float64(10.0),
20681                        Scalar::Float64(20.0),
20682                        Scalar::Float64(30.0),
20683                    ],
20684                ),
20685            ],
20686        )
20687        .unwrap();
20688
20689        let err = merge_asof_with_options(
20690            &left,
20691            &right,
20692            "time",
20693            AsofDirection::Backward,
20694            MergeAsofOptions::new().by(vec!["group".to_string()]),
20695        )
20696        .expect_err("pandas requires globally sorted left keys even with by=");
20697        assert!(matches!(
20698            err,
20699            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(message))
20700                if message.contains("left") && message.contains("sorted")
20701        ));
20702    }
20703
20704    #[test]
20705    fn merge_asof_by_column_requires_globally_sorted_right_keys() {
20706        use super::{AsofDirection, MergeAsofOptions, merge_asof_with_options};
20707
20708        let left = fp_frame::DataFrame::from_dict(
20709            &["group", "time"],
20710            vec![
20711                (
20712                    "group",
20713                    vec![
20714                        Scalar::Utf8("A".into()),
20715                        Scalar::Utf8("B".into()),
20716                        Scalar::Utf8("A".into()),
20717                    ],
20718                ),
20719                (
20720                    "time",
20721                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
20722                ),
20723            ],
20724        )
20725        .unwrap();
20726        let right = fp_frame::DataFrame::from_dict(
20727            &["group", "time", "quote"],
20728            vec![
20729                (
20730                    "group",
20731                    vec![
20732                        Scalar::Utf8("A".into()),
20733                        Scalar::Utf8("A".into()),
20734                        Scalar::Utf8("B".into()),
20735                    ],
20736                ),
20737                (
20738                    "time",
20739                    vec![Scalar::Int64(1), Scalar::Int64(3), Scalar::Int64(2)],
20740                ),
20741                (
20742                    "quote",
20743                    vec![
20744                        Scalar::Float64(10.0),
20745                        Scalar::Float64(30.0),
20746                        Scalar::Float64(20.0),
20747                    ],
20748                ),
20749            ],
20750        )
20751        .unwrap();
20752
20753        let err = merge_asof_with_options(
20754            &left,
20755            &right,
20756            "time",
20757            AsofDirection::Backward,
20758            MergeAsofOptions::new().by(vec!["group".to_string()]),
20759        )
20760        .expect_err("pandas requires globally sorted right keys even with by=");
20761        assert!(matches!(
20762            err,
20763            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(message))
20764                if message.contains("right") && message.contains("sorted")
20765        ));
20766    }
20767
20768    #[test]
20769    fn merge_ordered_sorts_and_ffills_values() {
20770        let left = fp_frame::DataFrame::from_dict(
20771            &["date", "left_val"],
20772            vec![
20773                ("date", vec![Scalar::Int64(1), Scalar::Int64(3)]),
20774                ("left_val", vec![Scalar::Int64(10), Scalar::Int64(30)]),
20775            ],
20776        )
20777        .unwrap();
20778
20779        let right = fp_frame::DataFrame::from_dict(
20780            &["date", "right_val"],
20781            vec![
20782                ("date", vec![Scalar::Int64(2), Scalar::Int64(3)]),
20783                ("right_val", vec![Scalar::Int64(200), Scalar::Int64(300)]),
20784            ],
20785        )
20786        .unwrap();
20787
20788        let result = super::merge_ordered(&left, &right, &["date"], Some("ffill")).unwrap();
20789        let frame = fp_frame::DataFrame::new(result.index, result.columns).unwrap();
20790
20791        assert_eq!(
20792            frame.column("date").unwrap().values(),
20793            &[Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)]
20794        );
20795        assert_eq!(
20796            frame.column("left_val").unwrap().values(),
20797            &[
20798                Scalar::Float64(10.0),
20799                Scalar::Float64(10.0),
20800                Scalar::Float64(30.0),
20801            ]
20802        );
20803        assert_eq!(
20804            frame.column("right_val").unwrap().values(),
20805            &[
20806                Scalar::Null(NullKind::NaN),
20807                Scalar::Float64(200.0),
20808                Scalar::Float64(300.0),
20809            ]
20810        );
20811    }
20812
20813    #[test]
20814    fn merge_ordered_invalid_fill_method_errors() {
20815        let left = fp_frame::DataFrame::from_dict(
20816            &["date", "left_val"],
20817            vec![
20818                ("date", vec![Scalar::Int64(1)]),
20819                ("left_val", vec![Scalar::Int64(10)]),
20820            ],
20821        )
20822        .unwrap();
20823
20824        let right = fp_frame::DataFrame::from_dict(
20825            &["date", "right_val"],
20826            vec![
20827                ("date", vec![Scalar::Int64(2)]),
20828                ("right_val", vec![Scalar::Int64(200)]),
20829            ],
20830        )
20831        .unwrap();
20832
20833        let err = super::merge_ordered(&left, &right, &["date"], Some("sideways"))
20834            .expect_err("invalid fill method should error");
20835        assert!(matches!(
20836            err,
20837            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(message))
20838                if message.contains("fill_method must be 'ffill' or None")
20839        ));
20840    }
20841
20842    #[test]
20843    fn merge_ordered_rejects_bfill_like_pandas() {
20844        let left = fp_frame::DataFrame::from_dict(
20845            &["date", "left_val"],
20846            vec![
20847                ("date", vec![Scalar::Int64(1), Scalar::Int64(3)]),
20848                ("left_val", vec![Scalar::Int64(10), Scalar::Int64(30)]),
20849            ],
20850        )
20851        .unwrap();
20852
20853        let right = fp_frame::DataFrame::from_dict(
20854            &["date", "right_val"],
20855            vec![
20856                ("date", vec![Scalar::Int64(2), Scalar::Int64(3)]),
20857                ("right_val", vec![Scalar::Int64(200), Scalar::Int64(300)]),
20858            ],
20859        )
20860        .unwrap();
20861
20862        let err = super::merge_ordered(&left, &right, &["date"], Some("bfill"))
20863            .expect_err("pandas only accepts fill_method='ffill' or None");
20864        assert!(matches!(
20865            err,
20866            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(message))
20867                if message.contains("fill_method must be 'ffill' or None")
20868        ));
20869    }
20870
20871    // ── join() pandas-named alias (br-frankenpandas-nk54a) ──────────────
20872
20873    #[test]
20874    fn dataframe_join_aliases_join_on_index() {
20875        use std::collections::BTreeMap;
20876
20877        use fp_columnar::Column;
20878        use fp_frame::DataFrame;
20879        use fp_index::Index;
20880        use fp_types::{DType, Scalar};
20881
20882        use super::DataFrameMergeExt;
20883
20884        fn build(name1: &str, name2: &str, vals1: &[i64], vals2: &[i64]) -> DataFrame {
20885            let mut cols = BTreeMap::new();
20886            cols.insert(
20887                name1.to_owned(),
20888                Column::new(
20889                    DType::Int64,
20890                    vals1.iter().map(|v| Scalar::Int64(*v)).collect(),
20891                )
20892                .unwrap(),
20893            );
20894            cols.insert(
20895                name2.to_owned(),
20896                Column::new(
20897                    DType::Int64,
20898                    vals2.iter().map(|v| Scalar::Int64(*v)).collect(),
20899                )
20900                .unwrap(),
20901            );
20902            DataFrame::new_with_column_order(
20903                Index::new(
20904                    (0..vals1.len() as i64)
20905                        .map(fp_index::IndexLabel::Int64)
20906                        .collect(),
20907                ),
20908                cols,
20909                vec![name1.to_owned(), name2.to_owned()],
20910            )
20911            .unwrap()
20912        }
20913
20914        let left = build("a", "b", &[10, 20, 30], &[1, 2, 3]);
20915        let right = build("c", "d", &[100, 200, 300], &[7, 8, 9]);
20916
20917        let via_join = left.join(&right, super::JoinType::Inner).unwrap();
20918        let via_join_on_index = left.join_on_index(&right, super::JoinType::Inner).unwrap();
20919
20920        // Both produce the same MergedDataFrame shape & values.
20921        let join_keys: Vec<&String> = via_join.columns.keys().collect();
20922        let idx_keys: Vec<&String> = via_join_on_index.columns.keys().collect();
20923        assert_eq!(join_keys, idx_keys);
20924        assert_eq!(via_join.index, via_join_on_index.index);
20925        for k in via_join.columns.keys() {
20926            assert_eq!(
20927                via_join.columns.get(k).unwrap().values(),
20928                via_join_on_index.columns.get(k).unwrap().values(),
20929                "column {k} differs"
20930            );
20931        }
20932    }
20933}
20934
20935#[cfg(test)]
20936mod typed_validate_cardinality_uza04 {
20937    //! `validate=` must stop costing the whole fast-path family.
20938    //!
20939    //! br-frankenpandas-uza04. `validate_merge_cardinality` lives in exactly
20940    //! one place — the generic `collect_composite_keys` branch — so
20941    //! `validate_mode_allows_fast_positions` returned false for every enforcing
20942    //! mode purely to route execution there. Asking for a cardinality guarantee
20943    //! therefore disabled `dense_packed_int64_inner_positions`, the typed
20944    //! two-key and multi-key position paths, and the single-key inner/left
20945    //! shortcuts, and additionally built a `Vec<CompositeJoinKey>` off
20946    //! `column.values()[row]` on both sides.
20947    //!
20948    //! `typed_validate_merge_cardinality` settles the common shape (one
20949    //! all-valid Int64 key) off the raw buffer, so a PASSING validation lets
20950    //! the merge take the same path it would have taken with no `validate=`.
20951    //! These tests pin the two things that has to preserve: the rejections, and
20952    //! the output.
20953
20954    use fp_columnar::Column;
20955    use fp_frame::DataFrame;
20956    use fp_index::Index;
20957    use fp_types::{NullKind, Scalar};
20958
20959    use super::{
20960        JoinType, MergeExecutionOptions, MergeValidateMode, merge_dataframes_on_with_options,
20961        typed_single_int64_key_has_duplicates,
20962    };
20963
20964    fn int_frame(name: &str, keys: Vec<i64>, payload: Vec<i64>) -> DataFrame {
20965        let index = Index::new_known_unique_int64_unit_range(0, keys.len());
20966        DataFrame::new_with_column_order(
20967            index,
20968            std::collections::BTreeMap::from([
20969                ("id".to_owned(), Column::from_i64_values(keys)),
20970                (name.to_owned(), Column::from_i64_values(payload)),
20971            ]),
20972            vec!["id".to_owned(), name.to_owned()],
20973        )
20974        .expect("typed int frame")
20975    }
20976
20977    fn merge(
20978        left: &DataFrame,
20979        right: &DataFrame,
20980        validate: Option<MergeValidateMode>,
20981    ) -> Result<super::MergedDataFrame, super::JoinError> {
20982        merge_dataframes_on_with_options(
20983            left,
20984            right,
20985            &["id"],
20986            &["id"],
20987            JoinType::Inner,
20988            MergeExecutionOptions {
20989                validate_mode: validate,
20990                ..MergeExecutionOptions::default()
20991            },
20992        )
20993    }
20994
20995    /// THE DUPLICATE-KEY NEGATIVE CASE. The typed checker is now what rejects a
20996    /// non-unique left key under `one_to_many`, so it has to reject with the
20997    /// same message the generic checker produced — a caller cannot tell which
20998    /// one ran.
20999    #[test]
21000    fn duplicate_left_keys_still_reject_under_one_to_many_uza04() {
21001        let left = int_frame("left_v", vec![1, 2, 2, 3], vec![10, 20, 21, 30]);
21002        let right = int_frame("right_v", vec![1, 2, 3], vec![100, 200, 300]);
21003        let error = merge(&left, &right, Some(MergeValidateMode::OneToMany))
21004            .expect_err("duplicate left keys must be rejected");
21005        assert!(
21006            format!("{error}")
21007                .contains("merge validate='one_to_many' failed: left keys are not unique"),
21008            "message must match the generic checker exactly, got: {error}"
21009        );
21010    }
21011
21012    #[test]
21013    fn duplicate_right_keys_still_reject_under_many_to_one_uza04() {
21014        let left = int_frame("left_v", vec![1, 2, 3], vec![10, 20, 30]);
21015        let right = int_frame("right_v", vec![1, 2, 2], vec![100, 200, 201]);
21016        let error = merge(&left, &right, Some(MergeValidateMode::ManyToOne))
21017            .expect_err("duplicate right keys must be rejected");
21018        assert!(
21019            format!("{error}")
21020                .contains("merge validate='many_to_one' failed: right keys are not unique"),
21021            "message must match the generic checker exactly, got: {error}"
21022        );
21023    }
21024
21025    /// PRECEDENCE. With BOTH sides duplicated under `one_to_one`, pandas — and
21026    /// the generic checker — report the LEFT failure. The typed checker must
21027    /// not answer from whichever side it happened to inspect first.
21028    #[test]
21029    fn one_to_one_reports_the_left_failure_first_uza04() {
21030        let left = int_frame("left_v", vec![1, 1, 2], vec![10, 11, 20]);
21031        let right = int_frame("right_v", vec![1, 1, 2], vec![100, 101, 200]);
21032        let error = merge(&left, &right, Some(MergeValidateMode::OneToOne))
21033            .expect_err("both sides duplicated must be rejected");
21034        let message = format!("{error}");
21035        assert!(
21036            message.contains("left keys are not unique"),
21037            "left-before-right precedence must hold, got: {message}"
21038        );
21039        assert!(
21040            !message.contains("right keys are not unique"),
21041            "the right-side message must not pre-empt the left one, got: {message}"
21042        );
21043    }
21044
21045    #[test]
21046    fn one_to_one_still_catches_a_right_only_duplicate_uza04() {
21047        let left = int_frame("left_v", vec![1, 2, 3], vec![10, 20, 30]);
21048        let right = int_frame("right_v", vec![1, 2, 2], vec![100, 200, 201]);
21049        let error = merge(&left, &right, Some(MergeValidateMode::OneToOne))
21050            .expect_err("right duplicate must be rejected");
21051        assert!(
21052            format!("{error}")
21053                .contains("merge validate='one_to_one' failed: right keys are not unique"),
21054            "got: {error}"
21055        );
21056    }
21057
21058    /// THE SAFETY PROPERTY OF THE WHOLE LEVER: a validation that PASSES must
21059    /// leave the merge output byte-identical to the unvalidated merge, because
21060    /// it now takes the same fast path. If enabling those paths changed row
21061    /// order, pairing, or column content, this is what catches it.
21062    #[test]
21063    fn a_passing_validation_produces_the_unvalidated_output_uza04() {
21064        let left = int_frame("left_v", vec![5, 1, 4, 2, 3], vec![50, 10, 40, 20, 30]);
21065        let right = int_frame("right_v", vec![3, 1, 2, 9], vec![300, 100, 200, 900]);
21066
21067        let unvalidated = merge(&left, &right, None).expect("plain merge");
21068        for mode in [
21069            MergeValidateMode::OneToOne,
21070            MergeValidateMode::OneToMany,
21071            MergeValidateMode::ManyToOne,
21072            MergeValidateMode::ManyToMany,
21073        ] {
21074            let validated = merge(&left, &right, Some(mode)).expect("validation should pass");
21075            assert_eq!(
21076                validated.index.len(),
21077                unvalidated.index.len(),
21078                "{mode:?}: row count changed"
21079            );
21080            assert_eq!(
21081                validated.column_order, unvalidated.column_order,
21082                "{mode:?}: column order changed"
21083            );
21084            for name in ["id", "left_v", "right_v"] {
21085                assert_eq!(
21086                    validated.columns.get(name).expect("column").values(),
21087                    unvalidated.columns.get(name).expect("column").values(),
21088                    "{mode:?}: column {name} differs from the unvalidated merge"
21089                );
21090            }
21091        }
21092    }
21093
21094    /// NON-VACUITY, both directions. Every assertion above would still pass if
21095    /// the typed checker declined everything and the generic path did all the
21096    /// work — the lever would simply not exist.
21097    #[test]
21098    fn the_typed_checker_fires_on_typed_keys_and_declines_otherwise_uza04() {
21099        let unique = Column::from_i64_values(vec![1, 2, 3]);
21100        assert_eq!(
21101            typed_single_int64_key_has_duplicates(&[&unique]),
21102            Some(false),
21103            "an all-valid Int64 key must be answered typed"
21104        );
21105        let duplicated = Column::from_i64_values(vec![1, 2, 2]);
21106        assert_eq!(
21107            typed_single_int64_key_has_duplicates(&[&duplicated]),
21108            Some(true),
21109            "and duplicates must be seen"
21110        );
21111
21112        // A key with a missing value has no contiguous all-valid buffer, so the
21113        // typed checker declines and null-key duplicate semantics stay owned by
21114        // the generic path.
21115        let nullable = Column::from_values(vec![
21116            Scalar::Int64(1),
21117            Scalar::Null(NullKind::Null),
21118            Scalar::Int64(3),
21119        ])
21120        .expect("nullable int column");
21121        assert_eq!(
21122            typed_single_int64_key_has_duplicates(&[&nullable]),
21123            None,
21124            "a nullable key must decline"
21125        );
21126
21127        // Utf8 keys decline too (this lever is Int64-only for now).
21128        let text = Column::from_values(vec![
21129            Scalar::Utf8("a".to_owned()),
21130            Scalar::Utf8("b".to_owned()),
21131        ])
21132        .expect("utf8 column");
21133        assert_eq!(
21134            typed_single_int64_key_has_duplicates(&[&text]),
21135            None,
21136            "a Utf8 key must decline"
21137        );
21138
21139        // Multi-key merges decline: the composite question is not this one.
21140        assert_eq!(
21141            typed_single_int64_key_has_duplicates(&[&unique, &duplicated]),
21142            None,
21143            "more than one key column must decline"
21144        );
21145    }
21146
21147    /// A shape the typed checker DECLINES must still be validated — the generic
21148    /// path has to keep running for it. A nullable left key with a repeated
21149    /// value under `one_to_many` is the case that would silently start passing
21150    /// if the skip flag were set too broadly.
21151    #[test]
21152    fn a_declined_shape_is_still_validated_by_the_generic_path_uza04() {
21153        let index = Index::new_known_unique_int64_unit_range(0, 3);
21154        let left = DataFrame::new_with_column_order(
21155            index,
21156            std::collections::BTreeMap::from([
21157                (
21158                    "id".to_owned(),
21159                    Column::from_values(vec![
21160                        Scalar::Int64(1),
21161                        Scalar::Int64(1),
21162                        Scalar::Null(NullKind::Null),
21163                    ])
21164                    .expect("nullable id column"),
21165                ),
21166                (
21167                    "left_v".to_owned(),
21168                    Column::from_i64_values(vec![10, 11, 30]),
21169                ),
21170            ]),
21171            vec!["id".to_owned(), "left_v".to_owned()],
21172        )
21173        .expect("nullable left frame");
21174        let right = int_frame("right_v", vec![1, 2, 3], vec![100, 200, 300]);
21175
21176        let error = merge(&left, &right, Some(MergeValidateMode::OneToMany))
21177            .expect_err("a duplicated nullable left key must still be rejected");
21178        assert!(
21179            format!("{error}").contains("left keys are not unique"),
21180            "the generic checker must still own declined shapes, got: {error}"
21181        );
21182    }
21183}