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::{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
307fn reindex_outer_join_column(
308    column: &Column,
309    positions: &[Option<usize>],
310) -> Result<Column, JoinError> {
311    if !matches!(
312        column.dtype(),
313        fp_types::DType::Int64 | fp_types::DType::Float64
314    ) {
315        return Ok(column.reindex_by_positions(positions)?);
316    }
317
318    let has_missing = positions
319        .iter()
320        .any(|slot| slot.is_none_or(|idx| idx >= column.len()));
321    if !has_missing {
322        return Ok(column.reindex_by_positions(positions)?);
323    }
324
325    // Typed Float64-promote gather (br-frankenpandas-1bvcl): all-valid
326    // Int64/Float64 sources skip the per-row Scalar clone + cast +
327    // Column::new revalidation below — bit-identical (see the method's
328    // isomorphism notes in fp-columnar).
329    if let Some(column) = column.reindex_promote_float64_by_optional_positions(positions) {
330        return Ok(column);
331    }
332
333    let values = positions
334        .iter()
335        .map(|slot| match slot {
336            Some(idx) => column
337                .values()
338                .get(*idx)
339                .cloned()
340                .unwrap_or(fp_types::Scalar::Null(fp_types::NullKind::NaN)),
341            None => fp_types::Scalar::Null(fp_types::NullKind::NaN),
342        })
343        .map(|value| {
344            fp_types::cast_scalar_owned(value, fp_types::DType::Float64).map_err(ColumnError::from)
345        })
346        .collect::<Result<Vec<_>, ColumnError>>()?;
347
348    Ok(Column::new(fp_types::DType::Float64, values)?)
349}
350
351enum SharedOptionalUtf8GatherPlan {
352    NullableRange {
353        null_prefix: usize,
354        source_start: usize,
355        source_len: usize,
356        null_suffix: usize,
357    },
358    Positions {
359        positions: Arc<[usize]>,
360        validity: ValidityMask,
361    },
362}
363
364fn shared_optional_utf8_gather_plan(
365    positions: &[Option<usize>],
366    source_len: usize,
367) -> Option<SharedOptionalUtf8GatherPlan> {
368    let mut first_valid = None;
369    let mut last_valid_exclusive = 0usize;
370    let mut has_missing = false;
371    for (out_idx, slot) in positions.iter().enumerate() {
372        match slot {
373            Some(idx) if *idx < source_len => {
374                first_valid.get_or_insert(out_idx);
375                last_valid_exclusive = out_idx + 1;
376            }
377            _ => has_missing = true,
378        }
379    }
380    if !has_missing {
381        return None;
382    }
383    if let Some(first_valid) = first_valid {
384        let source_start = positions.get(first_valid).copied().flatten()?;
385        let valid_len = last_valid_exclusive - first_valid;
386        let valid_window = positions.get(first_valid..last_valid_exclusive)?;
387        let contiguous = valid_window
388            .iter()
389            .enumerate()
390            .all(|(offset, slot)| *slot == Some(source_start + offset));
391        if contiguous
392            && source_start
393                .checked_add(valid_len)
394                .is_some_and(|end| end <= source_len)
395        {
396            return Some(SharedOptionalUtf8GatherPlan::NullableRange {
397                null_prefix: first_valid,
398                source_start,
399                source_len: valid_len,
400                null_suffix: positions.len() - last_valid_exclusive,
401            });
402        }
403    } else {
404        return Some(SharedOptionalUtf8GatherPlan::NullableRange {
405            null_prefix: positions.len(),
406            source_start: 0,
407            source_len: 0,
408            null_suffix: 0,
409        });
410    }
411
412    let mut plan = Vec::with_capacity(positions.len());
413    let mut words = vec![0_u64; positions.len().div_ceil(64)];
414    for (out_idx, slot) in positions.iter().enumerate() {
415        match slot {
416            Some(idx) if *idx < source_len => {
417                plan.push(*idx);
418                words[out_idx / 64] |= 1_u64 << (out_idx % 64);
419            }
420            _ => plan.push(usize::MAX),
421        }
422    }
423    Some(SharedOptionalUtf8GatherPlan::Positions {
424        positions: Arc::from(plan),
425        validity: ValidityMask::from_words(words, positions.len()),
426    })
427}
428
429fn reindex_with_shared_utf8_plan(
430    column: &Column,
431    positions: &[Option<usize>],
432    plan: Option<&SharedOptionalUtf8GatherPlan>,
433) -> Result<Column, JoinError> {
434    if let Some(column) = plan.and_then(|plan| reindex_eager_utf8_with_plan(column, plan)) {
435        return Ok(column);
436    }
437    Ok(column.reindex_by_positions(positions)?)
438}
439
440fn reindex_outer_with_shared_utf8_plan(
441    column: &Column,
442    positions: &[Option<usize>],
443    plan: Option<&SharedOptionalUtf8GatherPlan>,
444) -> Result<Column, JoinError> {
445    if let Some(column) = plan.and_then(|plan| reindex_eager_utf8_with_plan(column, plan)) {
446        return Ok(column);
447    }
448    reindex_outer_join_column(column, positions)
449}
450
451fn reindex_eager_utf8_with_plan(
452    column: &Column,
453    plan: &SharedOptionalUtf8GatherPlan,
454) -> Option<Column> {
455    match plan {
456        SharedOptionalUtf8GatherPlan::NullableRange {
457            null_prefix,
458            source_start,
459            source_len,
460            null_suffix,
461        } => column.reindex_eager_utf8_with_nullable_range(
462            *null_prefix,
463            *source_start,
464            *source_len,
465            *null_suffix,
466        ),
467        SharedOptionalUtf8GatherPlan::Positions {
468            positions,
469            validity,
470        } => column.reindex_eager_utf8_with_shared_plan(Arc::clone(positions), validity.clone()),
471    }
472}
473
474fn sort_outer_join_rows(
475    out_labels: &mut Vec<IndexLabel>,
476    left_positions: &mut [Option<usize>],
477    right_positions: &mut [Option<usize>],
478) {
479    if out_labels.len() <= 1 {
480        return;
481    }
482
483    let mut rows = out_labels
484        .drain(..)
485        .zip(left_positions.iter().copied())
486        .zip(right_positions.iter().copied())
487        .map(|((label, left_pos), right_pos)| (label, left_pos, right_pos))
488        .collect::<Vec<_>>();
489    rows.sort_by(|left, right| left.0.cmp(&right.0));
490
491    for (idx, (label, left_pos, right_pos)) in rows.into_iter().enumerate() {
492        out_labels.push(label);
493        left_positions[idx] = left_pos;
494        right_positions[idx] = right_pos;
495    }
496}
497
498fn join_series_with_global_allocator(
499    left: &Series,
500    right: &Series,
501    join_type: JoinType,
502    right_map: &FxHashMap<&IndexLabel, Vec<usize>>,
503    left_map: Option<&FxHashMap<&IndexLabel, Vec<usize>>>,
504    output_rows: usize,
505) -> Result<JoinedSeries, JoinError> {
506    let mut out_labels = Vec::with_capacity(output_rows);
507    let mut left_positions = Vec::<Option<usize>>::with_capacity(output_rows);
508    let mut right_positions = Vec::<Option<usize>>::with_capacity(output_rows);
509
510    match join_type {
511        JoinType::Inner | JoinType::Left | JoinType::Outer => {
512            // Iterate left labels: emit matches and (for Left/Outer) unmatched left rows.
513            for (left_pos, label) in left.index().labels().iter().enumerate() {
514                if let Some(matches) = right_map.get(label) {
515                    for right_pos in matches {
516                        out_labels.push(label.clone());
517                        left_positions.push(Some(left_pos));
518                        right_positions.push(Some(*right_pos));
519                    }
520                    continue;
521                }
522
523                if matches!(join_type, JoinType::Left | JoinType::Outer) {
524                    out_labels.push(label.clone());
525                    left_positions.push(Some(left_pos));
526                    right_positions.push(None);
527                }
528            }
529
530            // For Outer: append right labels that have no match in left.
531            if matches!(join_type, JoinType::Outer) {
532                let left_map = left_map.as_ref().expect("left_map required for Outer join");
533                for (right_pos, label) in right.index().labels().iter().enumerate() {
534                    if !left_map.contains_key(label) {
535                        out_labels.push(label.clone());
536                        left_positions.push(None);
537                        right_positions.push(Some(right_pos));
538                    }
539                }
540            }
541        }
542        JoinType::Right => {
543            // Iterate right labels: emit matches and unmatched right rows.
544            let left_map = left_map.expect("left_map required for Right join");
545            for (right_pos, label) in right.index().labels().iter().enumerate() {
546                if let Some(matches) = left_map.get(label) {
547                    for left_pos in matches {
548                        out_labels.push(label.clone());
549                        left_positions.push(Some(*left_pos));
550                        right_positions.push(Some(right_pos));
551                    }
552                    continue;
553                }
554
555                out_labels.push(label.clone());
556                left_positions.push(None);
557                right_positions.push(Some(right_pos));
558            }
559        }
560        JoinType::Cross => {
561            for (left_pos, left_label) in left.index().labels().iter().enumerate() {
562                for (right_pos, _) in right.index().labels().iter().enumerate() {
563                    out_labels.push(left_label.clone());
564                    left_positions.push(Some(left_pos));
565                    right_positions.push(Some(right_pos));
566                }
567            }
568        }
569    }
570
571    if matches!(join_type, JoinType::Outer) {
572        sort_outer_join_rows(&mut out_labels, &mut left_positions, &mut right_positions);
573    }
574
575    let left_values = if matches!(join_type, JoinType::Outer) {
576        reindex_outer_join_column(left.column(), &left_positions)?
577    } else {
578        left.column().reindex_by_positions(&left_positions)?
579    };
580    let right_values = if matches!(join_type, JoinType::Outer) {
581        reindex_outer_join_column(right.column(), &right_positions)?
582    } else {
583        right.column().reindex_by_positions(&right_positions)?
584    };
585
586    // Per br-frankenpandas-wp0n6: pandas Series.join preserves shared
587    // index name (preserved when both operands agree, None when they differ).
588    let shared_name = if left.index().name().eq(&right.index().name()) {
589        left.index().name().map(str::to_owned)
590    } else {
591        None
592    };
593    Ok(JoinedSeries {
594        index: Index::new(out_labels).rename_index(shared_name.as_deref()),
595        left_values,
596        right_values,
597    })
598}
599
600fn join_series_with_arena(
601    left: &Series,
602    right: &Series,
603    join_type: JoinType,
604    right_map: &FxHashMap<&IndexLabel, Vec<usize>>,
605    left_map: Option<&FxHashMap<&IndexLabel, Vec<usize>>>,
606    output_rows: usize,
607) -> Result<JoinedSeries, JoinError> {
608    let arena = Bump::new();
609    let mut out_labels = Vec::with_capacity(output_rows);
610    let mut left_positions = BumpVec::<Option<usize>>::with_capacity_in(output_rows, &arena);
611    let mut right_positions = BumpVec::<Option<usize>>::with_capacity_in(output_rows, &arena);
612
613    match join_type {
614        JoinType::Inner | JoinType::Left | JoinType::Outer => {
615            for (left_pos, label) in left.index().labels().iter().enumerate() {
616                if let Some(matches) = right_map.get(label) {
617                    for right_pos in matches {
618                        out_labels.push(label.clone());
619                        left_positions.push(Some(left_pos));
620                        right_positions.push(Some(*right_pos));
621                    }
622                    continue;
623                }
624
625                if matches!(join_type, JoinType::Left | JoinType::Outer) {
626                    out_labels.push(label.clone());
627                    left_positions.push(Some(left_pos));
628                    right_positions.push(None);
629                }
630            }
631
632            if matches!(join_type, JoinType::Outer) {
633                let left_map = left_map.as_ref().expect("left_map required for Outer join");
634                for (right_pos, label) in right.index().labels().iter().enumerate() {
635                    if !left_map.contains_key(label) {
636                        out_labels.push(label.clone());
637                        left_positions.push(None);
638                        right_positions.push(Some(right_pos));
639                    }
640                }
641            }
642        }
643        JoinType::Right => {
644            let left_map = left_map.expect("left_map required for Right join");
645            for (right_pos, label) in right.index().labels().iter().enumerate() {
646                if let Some(matches) = left_map.get(label) {
647                    for left_pos in matches {
648                        out_labels.push(label.clone());
649                        left_positions.push(Some(*left_pos));
650                        right_positions.push(Some(right_pos));
651                    }
652                    continue;
653                }
654
655                out_labels.push(label.clone());
656                left_positions.push(None);
657                right_positions.push(Some(right_pos));
658            }
659        }
660        JoinType::Cross => {
661            for (left_pos, left_label) in left.index().labels().iter().enumerate() {
662                for (right_pos, _) in right.index().labels().iter().enumerate() {
663                    out_labels.push(left_label.clone());
664                    left_positions.push(Some(left_pos));
665                    right_positions.push(Some(right_pos));
666                }
667            }
668        }
669    }
670
671    if matches!(join_type, JoinType::Outer) {
672        sort_outer_join_rows(
673            &mut out_labels,
674            left_positions.as_mut_slice(),
675            right_positions.as_mut_slice(),
676        );
677    }
678
679    let left_values = if matches!(join_type, JoinType::Outer) {
680        reindex_outer_join_column(left.column(), left_positions.as_slice())?
681    } else {
682        left.column()
683            .reindex_by_positions(left_positions.as_slice())?
684    };
685    let right_values = if matches!(join_type, JoinType::Outer) {
686        reindex_outer_join_column(right.column(), right_positions.as_slice())?
687    } else {
688        right
689            .column()
690            .reindex_by_positions(right_positions.as_slice())?
691    };
692
693    // Per br-frankenpandas-ceces: pandas Series.join preserves shared
694    // index name. Sister to join_series fix (wp0n6).
695    let shared_name = if left.index().name().eq(&right.index().name()) {
696        left.index().name().map(str::to_owned)
697    } else {
698        None
699    };
700    Ok(JoinedSeries {
701        index: Index::new(out_labels).rename_index(shared_name.as_deref()),
702        left_values,
703        right_values,
704    })
705}
706
707/// Result of a DataFrame merge operation.
708#[derive(Debug, Clone, PartialEq)]
709pub struct MergedDataFrame {
710    pub index: Index,
711    pub columns: std::collections::BTreeMap<String, Column>,
712    /// Output column order in pandas' convention (key/left columns in their
713    /// source order, then right non-key columns). The `columns` map is sorted,
714    /// so this Vec carries the real order for materialization — br-691lh.
715    pub column_order: Vec<String>,
716}
717
718#[derive(Debug, Clone, PartialEq, Eq, Hash)]
719enum JoinKeyComponent {
720    Present(IndexLabel),
721    FloatBits(u64),
722    Missing,
723}
724
725impl Ord for JoinKeyComponent {
726    fn cmp(&self, other: &Self) -> Ordering {
727        use JoinKeyComponent::{FloatBits, Missing, Present};
728        match (self, other) {
729            (Missing, Missing) => Ordering::Equal,
730            (Missing, _) => Ordering::Greater,
731            (_, Missing) => Ordering::Less,
732            (Present(IndexLabel::Int64(a)), Present(IndexLabel::Int64(b))) => a.cmp(b),
733            (Present(IndexLabel::Utf8(a)), Present(IndexLabel::Utf8(b))) => a.cmp(b),
734            (Present(IndexLabel::Timedelta64(a)), Present(IndexLabel::Timedelta64(b))) => a.cmp(b),
735            (Present(IndexLabel::Datetime64(a)), Present(IndexLabel::Datetime64(b))) => a.cmp(b),
736            // Typed-null labels sort after every concrete label (nulls-last,
737            // consistent with the derived IndexLabel Ord) but before Missing.
738            // Unreachable today: join key extraction maps missing to Missing,
739            // never Present(Null).
740            (Present(IndexLabel::Null(a)), Present(IndexLabel::Null(b))) => a.cmp(b),
741            (Present(IndexLabel::Null(_)), Present(_)) => Ordering::Greater,
742            (Present(_), Present(IndexLabel::Null(_))) => Ordering::Less,
743            (Present(IndexLabel::Null(_)), FloatBits(_)) => Ordering::Greater,
744            (FloatBits(_), Present(IndexLabel::Null(_))) => Ordering::Less,
745            (Present(IndexLabel::Int64(_)), Present(IndexLabel::Utf8(_))) => Ordering::Less,
746            (Present(IndexLabel::Utf8(_)), Present(IndexLabel::Int64(_))) => Ordering::Greater,
747            (Present(IndexLabel::Timedelta64(_)), Present(IndexLabel::Int64(_))) => {
748                Ordering::Greater
749            }
750            (Present(IndexLabel::Timedelta64(_)), Present(IndexLabel::Utf8(_))) => {
751                Ordering::Greater
752            }
753            (Present(IndexLabel::Int64(_)), Present(IndexLabel::Timedelta64(_))) => Ordering::Less,
754            (Present(IndexLabel::Utf8(_)), Present(IndexLabel::Timedelta64(_))) => Ordering::Less,
755            (Present(IndexLabel::Datetime64(_)), Present(IndexLabel::Int64(_))) => {
756                Ordering::Greater
757            }
758            (Present(IndexLabel::Datetime64(_)), Present(IndexLabel::Utf8(_))) => Ordering::Greater,
759            (Present(IndexLabel::Datetime64(_)), Present(IndexLabel::Timedelta64(_))) => {
760                Ordering::Greater
761            }
762            (Present(IndexLabel::Int64(_)), Present(IndexLabel::Datetime64(_))) => Ordering::Less,
763            (Present(IndexLabel::Utf8(_)), Present(IndexLabel::Datetime64(_))) => Ordering::Less,
764            (Present(IndexLabel::Timedelta64(_)), Present(IndexLabel::Datetime64(_))) => {
765                Ordering::Less
766            }
767            (Present(IndexLabel::Int64(a)), FloatBits(bits)) => {
768                let ord = (*a as f64).total_cmp(&f64::from_bits(*bits));
769                if ord == Ordering::Equal {
770                    Ordering::Less
771                } else {
772                    ord
773                }
774            }
775            (FloatBits(bits), Present(IndexLabel::Int64(a))) => {
776                let ord = f64::from_bits(*bits).total_cmp(&(*a as f64));
777                if ord == Ordering::Equal {
778                    Ordering::Greater
779                } else {
780                    ord
781                }
782            }
783            (Present(IndexLabel::Timedelta64(a)), FloatBits(bits)) => {
784                let ord = (*a as f64).total_cmp(&f64::from_bits(*bits));
785                if ord == Ordering::Equal {
786                    Ordering::Less
787                } else {
788                    ord
789                }
790            }
791            (FloatBits(bits), Present(IndexLabel::Timedelta64(a))) => {
792                let ord = f64::from_bits(*bits).total_cmp(&(*a as f64));
793                if ord == Ordering::Equal {
794                    Ordering::Greater
795                } else {
796                    ord
797                }
798            }
799            (Present(IndexLabel::Datetime64(a)), FloatBits(bits)) => {
800                let ord = (*a as f64).total_cmp(&f64::from_bits(*bits));
801                if ord == Ordering::Equal {
802                    Ordering::Less
803                } else {
804                    ord
805                }
806            }
807            (FloatBits(bits), Present(IndexLabel::Datetime64(a))) => {
808                let ord = f64::from_bits(*bits).total_cmp(&(*a as f64));
809                if ord == Ordering::Equal {
810                    Ordering::Greater
811                } else {
812                    ord
813                }
814            }
815            (FloatBits(a_bits), FloatBits(b_bits)) => {
816                f64::from_bits(*a_bits).total_cmp(&f64::from_bits(*b_bits))
817            }
818            (FloatBits(_), Present(IndexLabel::Utf8(_))) => Ordering::Less,
819            (Present(IndexLabel::Utf8(_)), FloatBits(_)) => Ordering::Greater,
820            // Float64/Bool index labels (br-frankenpandas-i10en). Join key
821            // extraction maps float keys to FloatBits and bool keys to Int64, so
822            // a Present(Float64)/Present(Bool) join key is unreachable today;
823            // these arms only keep the manual `Ord` total (same-variant compares
824            // by value, cross-variant by a stable variant rank).
825            (Present(IndexLabel::Float64(a)), Present(IndexLabel::Float64(b))) => a.cmp(b),
826            (Present(IndexLabel::Bool(a)), Present(IndexLabel::Bool(b))) => a.cmp(b),
827            (a, b) => join_component_rank(a).cmp(&join_component_rank(b)),
828        }
829    }
830}
831
832/// Stable per-variant rank used only as the cross-variant fallback for the
833/// (unreachable) Float64/Bool join-key cases above, keeping `Ord` total.
834fn join_component_rank(c: &JoinKeyComponent) -> u8 {
835    use JoinKeyComponent::{FloatBits, Missing, Present};
836    match c {
837        Present(IndexLabel::Int64(_)) => 0,
838        Present(IndexLabel::Float64(_)) => 1,
839        Present(IndexLabel::Bool(_)) => 2,
840        Present(IndexLabel::Utf8(_)) => 3,
841        Present(IndexLabel::Timedelta64(_)) => 4,
842        Present(IndexLabel::Datetime64(_)) => 5,
843        Present(IndexLabel::Null(_)) => 6,
844        FloatBits(_) => 7,
845        Missing => 8,
846    }
847}
848
849impl PartialOrd for JoinKeyComponent {
850    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
851        Some(self.cmp(other))
852    }
853}
854
855fn scalar_to_key_component(s: &fp_types::Scalar) -> JoinKeyComponent {
856    match s {
857        fp_types::Scalar::Int64(v) => JoinKeyComponent::Present(IndexLabel::Int64(*v)),
858        fp_types::Scalar::Float64(v) if !v.is_nan() => {
859            if *v == v.trunc() && *v >= i64::MIN as f64 && *v < 9223372036854775808.0 {
860                JoinKeyComponent::Present(IndexLabel::Int64(*v as i64))
861            } else {
862                JoinKeyComponent::FloatBits(v.to_bits())
863            }
864        }
865        fp_types::Scalar::Utf8(v) => JoinKeyComponent::Present(IndexLabel::Utf8(v.clone())),
866        fp_types::Scalar::Bool(b) => JoinKeyComponent::Present(IndexLabel::Int64(i64::from(*b))),
867        _ => JoinKeyComponent::Missing, // Null, NaN, NaT
868    }
869}
870
871/// A row's composite join key. Inline storage for the single-key case (the
872/// overwhelmingly common join shape) avoids a heap allocation per row during
873/// key extraction; multi-column keys spill to the heap as before. `SmallVec`
874/// shares `Vec`'s `Hash`/`Eq`/`Ord`/`Deref<[T]>` semantics, so the join result
875/// (key equality, grouping, output order) is bit-identical.
876type CompositeJoinKey = smallvec::SmallVec<[JoinKeyComponent; 1]>;
877
878/// `(left_positions, right_positions, out_row_keys)` produced by the merge
879/// position-computation phase. `out_row_keys` is `Some` only when the rows must
880/// be reordered by join key (sort or outer join).
881type MergeRowPositions = (
882    Vec<Option<usize>>,
883    Vec<Option<usize>>,
884    Option<Vec<CompositeJoinKey>>,
885);
886type JoinPositionBucket = smallvec::SmallVec<[usize; 1]>;
887
888fn collect_join_key_columns<'a>(
889    frame: &'a fp_frame::DataFrame,
890    on: &[&str],
891    side: &str,
892) -> Result<Vec<&'a Column>, JoinError> {
893    let mut key_columns = Vec::with_capacity(on.len());
894    for key_name in on {
895        let key_column = frame.column(key_name).ok_or_else(|| {
896            JoinError::Frame(FrameError::CompatibilityRejected(format!(
897                "{side} DataFrame missing key column '{key_name}'"
898            )))
899        })?;
900        key_columns.push(key_column);
901    }
902    Ok(key_columns)
903}
904
905fn collect_composite_keys(key_columns: &[&Column]) -> Vec<CompositeJoinKey> {
906    let row_count = key_columns.first().map_or(0, |column| column.len());
907    let mut out = Vec::with_capacity(row_count);
908
909    for row in 0..row_count {
910        let mut parts: CompositeJoinKey = smallvec::SmallVec::with_capacity(key_columns.len());
911        for column in key_columns {
912            parts.push(scalar_to_key_component(&column.values()[row]));
913        }
914        out.push(parts);
915    }
916
917    out
918}
919
920fn collect_single_join_keys(column: &Column) -> Vec<JoinKeyComponent> {
921    column
922        .values()
923        .iter()
924        .map(scalar_to_key_component)
925        .collect()
926}
927
928fn has_duplicate_composite_keys(keys: &[CompositeJoinKey]) -> bool {
929    let mut seen = FxHashSet::with_capacity_and_hasher(keys.len(), Default::default());
930    for key in keys {
931        if !seen.insert(key) {
932            return true;
933        }
934    }
935    false
936}
937
938fn validate_merge_cardinality(
939    validate_mode: MergeValidateMode,
940    left_keys: &[CompositeJoinKey],
941    right_keys: &[CompositeJoinKey],
942) -> Result<(), JoinError> {
943    let left_has_duplicates = has_duplicate_composite_keys(left_keys);
944    let right_has_duplicates = has_duplicate_composite_keys(right_keys);
945
946    let fail = |message: &str| {
947        Err(JoinError::Frame(FrameError::CompatibilityRejected(
948            message.to_owned(),
949        )))
950    };
951
952    match validate_mode {
953        MergeValidateMode::OneToOne => {
954            if left_has_duplicates {
955                return fail("merge validate='one_to_one' failed: left keys are not unique");
956            }
957            if right_has_duplicates {
958                return fail("merge validate='one_to_one' failed: right keys are not unique");
959            }
960        }
961        MergeValidateMode::OneToMany => {
962            if left_has_duplicates {
963                return fail("merge validate='one_to_many' failed: left keys are not unique");
964            }
965        }
966        MergeValidateMode::ManyToOne => {
967            if right_has_duplicates {
968                return fail("merge validate='many_to_one' failed: right keys are not unique");
969            }
970        }
971        MergeValidateMode::ManyToMany => {}
972    }
973
974    Ok(())
975}
976
977fn validate_mode_allows_fast_positions(validate_mode: Option<MergeValidateMode>) -> bool {
978    matches!(validate_mode, None | Some(MergeValidateMode::ManyToMany))
979}
980
981fn reorder_vec_by_index<T: Clone>(values: &mut Vec<T>, order: &[usize]) {
982    let existing = values.clone();
983    values.clear();
984    values.reserve(order.len());
985    for &idx in order {
986        values.push(existing[idx].clone());
987    }
988}
989
990fn sort_merge_rows_by_join_keys(
991    out_row_keys: &[CompositeJoinKey],
992    left_positions: &mut Vec<Option<usize>>,
993    right_positions: &mut Vec<Option<usize>>,
994) {
995    if out_row_keys.is_empty() {
996        return;
997    }
998    let mut order: Vec<usize> = (0..out_row_keys.len()).collect();
999    order.sort_by(|a, b| out_row_keys[*a].cmp(&out_row_keys[*b]));
1000    reorder_vec_by_index(left_positions, &order);
1001    reorder_vec_by_index(right_positions, &order);
1002}
1003
1004fn push_merge_row_key(out_row_keys: &mut Option<Vec<CompositeJoinKey>>, key: &CompositeJoinKey) {
1005    if let Some(out_row_keys) = out_row_keys {
1006        out_row_keys.push(key.clone());
1007    }
1008}
1009
1010#[derive(Debug, Clone, PartialEq, Eq)]
1011struct ResolvedMergeSuffixes {
1012    left: Option<String>,
1013    right: Option<String>,
1014}
1015
1016impl Default for ResolvedMergeSuffixes {
1017    fn default() -> Self {
1018        Self {
1019            left: Some("_x".to_owned()),
1020            right: Some("_y".to_owned()),
1021        }
1022    }
1023}
1024
1025fn resolve_merge_suffixes(suffixes: Option<[Option<String>; 2]>) -> ResolvedMergeSuffixes {
1026    match suffixes {
1027        Some([left, right]) => ResolvedMergeSuffixes { left, right },
1028        None => ResolvedMergeSuffixes::default(),
1029    }
1030}
1031
1032fn suffix_is_present(suffix: Option<&str>) -> bool {
1033    suffix.is_some_and(|value| !value.is_empty())
1034}
1035
1036fn apply_merge_suffix(name: &str, suffix: Option<&str>) -> String {
1037    match suffix {
1038        Some(value) if !value.is_empty() => format!("{name}{value}"),
1039        _ => name.to_owned(),
1040    }
1041}
1042
1043fn collect_overlapping_column_names(
1044    left_col_names: &HashSet<&String>,
1045    right_col_names: &HashSet<&String>,
1046    excluded_names: &HashSet<&str>,
1047) -> Vec<String> {
1048    let mut overlaps = left_col_names
1049        .iter()
1050        .filter(|name| right_col_names.contains(*name) && !excluded_names.contains(name.as_str()))
1051        .map(|name| (*name).clone())
1052        .collect::<Vec<_>>();
1053    overlaps.sort();
1054    overlaps
1055}
1056
1057const SMALL_SCHEMA_LINEAR_COLUMN_LOOKUP_LIMIT: usize = 8;
1058
1059fn column_name_lookup_contains(
1060    names: &[&String],
1061    hashed_names: Option<&HashSet<&str>>,
1062    target: &str,
1063) -> bool {
1064    if let Some(hashed_names) = hashed_names {
1065        hashed_names.contains(target)
1066    } else {
1067        names.iter().any(|name| name.as_str() == target)
1068    }
1069}
1070
1071fn ensure_merge_suffixes_for_overlaps(
1072    overlap_names: &[String],
1073    suffixes: &ResolvedMergeSuffixes,
1074) -> Result<(), JoinError> {
1075    if overlap_names.is_empty() {
1076        return Ok(());
1077    }
1078    if !suffix_is_present(suffixes.left.as_deref()) && !suffix_is_present(suffixes.right.as_deref())
1079    {
1080        return Err(JoinError::Frame(FrameError::CompatibilityRejected(
1081            format!(
1082                "columns overlap but no suffix specified: {}",
1083                overlap_names.join(", ")
1084            ),
1085        )));
1086    }
1087    Ok(())
1088}
1089
1090fn insert_merged_output_column(
1091    output_columns: &mut std::collections::BTreeMap<String, Column>,
1092    order: &mut Vec<String>,
1093    name: String,
1094    column: Column,
1095) -> Result<(), JoinError> {
1096    if output_columns.contains_key(&name) {
1097        return Err(JoinError::Frame(FrameError::CompatibilityRejected(
1098            format!("merge suffixes cause duplicate output column '{name}'"),
1099        )));
1100    }
1101    order.push(name.clone());
1102    output_columns.insert(name, column);
1103    Ok(())
1104}
1105
1106fn ordered_identity_int64_keys_match(left_key: &Column, right_key: &Column) -> bool {
1107    if left_key.len() != right_key.len()
1108        || !matches!(left_key.dtype(), DType::Int64)
1109        || !matches!(right_key.dtype(), DType::Int64)
1110        || !left_key.validity().all()
1111        || !right_key.validity().all()
1112    {
1113        return false;
1114    }
1115
1116    if let (Some(left), Some(right)) = (left_key.as_i64_slice(), right_key.as_i64_slice()) {
1117        let mut previous = None;
1118        let mut strictly_increasing = true;
1119        for (&left_value, &right_value) in left.iter().zip(right) {
1120            if left_value != right_value {
1121                return false;
1122            }
1123            if previous.is_some_and(|previous| left_value <= previous) {
1124                strictly_increasing = false;
1125                break;
1126            }
1127            previous = Some(left_value);
1128        }
1129        if strictly_increasing {
1130            return true;
1131        }
1132    }
1133
1134    // The identity fast path emits a 1:1 positional merge, which is only correct
1135    // when keys are UNIQUE. With duplicate keys pandas multiplies cardinality
1136    // (each duplicate on the left cross-joins every duplicate on the right), so
1137    // identical-but-duplicated keys must fall through to the general cartesian
1138    // path. (br-frankenpandas-jdupk)
1139    let mut seen = FxHashSet::<i64>::with_capacity_and_hasher(left_key.len(), Default::default());
1140    for (left, right) in left_key.values().iter().zip(right_key.values()) {
1141        match (left, right) {
1142            (Scalar::Int64(left), Scalar::Int64(right))
1143                if matches!(left.cmp(right), Ordering::Equal) =>
1144            {
1145                if !seen.insert(*left) {
1146                    return false;
1147                }
1148            }
1149            _ => return false,
1150        }
1151    }
1152    true
1153}
1154
1155fn strictly_increasing_int64_key_values(column: &Column) -> Option<&[Scalar]> {
1156    if column.dtype() != DType::Int64 || !column.validity().all() {
1157        return None;
1158    }
1159
1160    let values = column.values();
1161    let mut previous = None;
1162    for value in values {
1163        let current = match value {
1164            Scalar::Int64(value) => *value,
1165            _ => return None,
1166        };
1167        if previous.is_some_and(|previous| current <= previous) {
1168            return None;
1169        }
1170        previous = Some(current);
1171    }
1172    Some(values)
1173}
1174
1175fn all_valid_int64_key_values(column: &Column) -> Option<&[Scalar]> {
1176    if column.dtype() != DType::Int64 || !column.validity().all() {
1177        return None;
1178    }
1179
1180    let values = column.values();
1181    if values.iter().all(|value| matches!(value, Scalar::Int64(_))) {
1182        Some(values)
1183    } else {
1184        None
1185    }
1186}
1187
1188fn ordered_unique_int64_inner_positions(
1189    left_key: &Column,
1190    right_key: &Column,
1191) -> Option<(Vec<usize>, Vec<usize>)> {
1192    // Typed fast path (see ordered_unique_int64_left_match_positions): walk the
1193    // ordered intersection over raw &[i64] when both keys carry a contiguous
1194    // Int64 backing, skipping the Vec<Scalar> materialization (32 B/elem, ~64 MB
1195    // per merge at 1M rows). Bit-identical: same strictly-increasing gate and
1196    // the same monotone merge emitting the same (left_idx, right_idx) pairs.
1197    if let (Some(left_values), Some(right_values)) = (
1198        strictly_increasing_i64_slice(left_key),
1199        strictly_increasing_i64_slice(right_key),
1200    ) {
1201        let mut left_positions =
1202            Vec::<usize>::with_capacity(left_values.len().min(right_values.len()));
1203        let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
1204        let (mut left_idx, mut right_idx) = (0usize, 0usize);
1205        while left_idx < left_values.len() && right_idx < right_values.len() {
1206            match left_values[left_idx].cmp(&right_values[right_idx]) {
1207                Ordering::Equal => {
1208                    left_positions.push(left_idx);
1209                    right_positions.push(right_idx);
1210                    left_idx += 1;
1211                    right_idx += 1;
1212                }
1213                Ordering::Less => left_idx += 1,
1214                Ordering::Greater => right_idx += 1,
1215            }
1216        }
1217        return Some((left_positions, right_positions));
1218    }
1219
1220    let left_values = strictly_increasing_int64_key_values(left_key)?;
1221    let right_values = strictly_increasing_int64_key_values(right_key)?;
1222
1223    let mut left_positions = Vec::<usize>::with_capacity(left_values.len().min(right_values.len()));
1224    let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
1225    let mut left_idx = 0usize;
1226    let mut right_idx = 0usize;
1227
1228    while left_idx < left_values.len() && right_idx < right_values.len() {
1229        let left_value = match &left_values[left_idx] {
1230            Scalar::Int64(value) => *value,
1231            _ => return None,
1232        };
1233        let right_value = match &right_values[right_idx] {
1234            Scalar::Int64(value) => *value,
1235            _ => return None,
1236        };
1237
1238        match left_value.cmp(&right_value) {
1239            Ordering::Equal => {
1240                left_positions.push(left_idx);
1241                right_positions.push(right_idx);
1242                left_idx += 1;
1243                right_idx += 1;
1244            }
1245            Ordering::Less => left_idx += 1,
1246            Ordering::Greater => right_idx += 1,
1247        }
1248    }
1249
1250    Some((left_positions, right_positions))
1251}
1252
1253fn strictly_increasing_utf8_key_spans(column: &Column) -> Option<(&[u8], &[usize])> {
1254    column.as_strictly_increasing_utf8_contiguous()
1255}
1256
1257fn utf8_span<'a>(bytes: &'a [u8], offsets: &[usize], pos: usize) -> &'a [u8] {
1258    &bytes[offsets[pos]..offsets[pos + 1]]
1259}
1260
1261fn utf8_span_lower_bound(bytes: &[u8], offsets: &[usize], needle: &[u8]) -> usize {
1262    let mut lo = 0usize;
1263    let mut hi = offsets.len() - 1;
1264    while lo < hi {
1265        let mid = lo + (hi - lo) / 2;
1266        if utf8_span(bytes, offsets, mid) < needle {
1267            lo = mid + 1;
1268        } else {
1269            hi = mid;
1270        }
1271    }
1272    lo
1273}
1274
1275fn ordered_unique_utf8_fixed_width(left_key: &Column, right_key: &Column) -> Option<usize> {
1276    let (_, _, left_width) = left_key.as_fixed_width_strictly_increasing_utf8_contiguous()?;
1277    let (_, _, right_width) = right_key.as_fixed_width_strictly_increasing_utf8_contiguous()?;
1278    (left_width == right_width && left_width > 0).then_some(left_width)
1279}
1280
1281fn ordered_utf8_lower_hex_overlap_len(
1282    left_cert: Utf8LowerHexSequence,
1283    right_cert: Utf8LowerHexSequence,
1284    left_idx: usize,
1285    left_n: usize,
1286    right_idx: usize,
1287    right_n: usize,
1288) -> Option<usize> {
1289    if !left_cert.same_shape(right_cert) {
1290        return None;
1291    }
1292    let left_value = left_cert.value_at(left_idx)?;
1293    let right_value = right_cert.value_at(right_idx)?;
1294    if left_value != right_value {
1295        return None;
1296    }
1297    Some(left_n.saturating_sub(left_idx).min(right_n - right_idx))
1298}
1299
1300fn lower_hex_overlap_plan_from_certificates(
1301    left_key: &Column,
1302    right_key: &Column,
1303) -> Option<InnerPositionPlan> {
1304    let (left_prefix, left_cert, left_n) = left_key.as_lower_hex_sequence_utf8()?;
1305    let (right_prefix, right_cert, right_n) = right_key.as_lower_hex_sequence_utf8()?;
1306    if !left_cert.same_shape(right_cert) {
1307        return None;
1308    }
1309    if left_prefix != right_prefix {
1310        return None;
1311    }
1312
1313    let left_n = u64::try_from(left_n).ok()?;
1314    let right_n = u64::try_from(right_n).ok()?;
1315    if left_n == 0 || right_n == 0 {
1316        return Some(InnerPositionPlan::Gather {
1317            left_positions: Vec::new(),
1318            right_positions: Vec::new(),
1319        });
1320    }
1321
1322    let left_start_value = left_cert.start();
1323    let right_start_value = right_cert.start();
1324    let left_end_value = left_start_value.checked_add(left_n)?;
1325    let right_end_value = right_start_value.checked_add(right_n)?;
1326    let overlap_start = left_start_value.max(right_start_value);
1327    let overlap_end = left_end_value.min(right_end_value);
1328    if overlap_start >= overlap_end {
1329        return Some(InnerPositionPlan::Gather {
1330            left_positions: Vec::new(),
1331            right_positions: Vec::new(),
1332        });
1333    }
1334
1335    let len = usize::try_from(overlap_end.checked_sub(overlap_start)?).ok()?;
1336    let left_start = usize::try_from(overlap_start.checked_sub(left_start_value)?).ok()?;
1337    let right_start = usize::try_from(overlap_start.checked_sub(right_start_value)?).ok()?;
1338    let left_len = usize::try_from(left_n).ok()?;
1339    let right_len = usize::try_from(right_n).ok()?;
1340    let left_end = left_start.checked_add(len)?;
1341    let right_end = right_start.checked_add(len)?;
1342    if left_end > left_len || right_end > right_len {
1343        return None;
1344    }
1345
1346    Some(InnerPositionPlan::ContiguousRanges {
1347        left_start,
1348        right_start,
1349        len,
1350    })
1351}
1352
1353#[derive(Debug, Clone, PartialEq, Eq)]
1354enum InnerPositionPlan {
1355    Gather {
1356        left_positions: Vec<usize>,
1357        right_positions: Vec<usize>,
1358    },
1359    ContiguousRanges {
1360        left_start: usize,
1361        right_start: usize,
1362        len: usize,
1363    },
1364}
1365
1366impl InnerPositionPlan {
1367    #[cfg(test)]
1368    fn into_positions(self) -> (Vec<usize>, Vec<usize>) {
1369        match self {
1370            Self::Gather {
1371                left_positions,
1372                right_positions,
1373            } => (left_positions, right_positions),
1374            Self::ContiguousRanges {
1375                left_start,
1376                right_start,
1377                len,
1378            } => (
1379                (left_start..left_start + len).collect(),
1380                (right_start..right_start + len).collect(),
1381            ),
1382        }
1383    }
1384}
1385
1386/// Hash-free ordered merge for all-valid, strictly increasing contiguous-Utf8
1387/// keys. This is the string-key analogue of
1388/// [`ordered_unique_int64_inner_positions`]: each side is unique and already in
1389/// key order, so a two-cursor byte-span merge emits the exact same 1:1
1390/// `(left_pos, right_pos)` pairs as the hash path while skipping hash table
1391/// build/probe entirely. Duplicate or unsorted inputs fall back to the
1392/// left-major byte-span hash path, preserving pandas row order.
1393fn ordered_unique_utf8_inner_position_plan(
1394    left_key: &Column,
1395    right_key: &Column,
1396) -> Option<InnerPositionPlan> {
1397    if let Some(plan) = lower_hex_overlap_plan_from_certificates(left_key, right_key) {
1398        return Some(plan);
1399    }
1400
1401    let (left_bytes, left_offsets) = strictly_increasing_utf8_key_spans(left_key)?;
1402    let (right_bytes, right_offsets) = strictly_increasing_utf8_key_spans(right_key)?;
1403    let left_n = left_offsets.len() - 1;
1404    let right_n = right_offsets.len() - 1;
1405    let fixed_width = ordered_unique_utf8_fixed_width(left_key, right_key);
1406
1407    if left_n == 0 || right_n == 0 {
1408        return Some(InnerPositionPlan::Gather {
1409            left_positions: Vec::new(),
1410            right_positions: Vec::new(),
1411        });
1412    }
1413
1414    let mut left_positions = Vec::<usize>::with_capacity(left_n.min(right_n));
1415    let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
1416
1417    let first_left = utf8_span(left_bytes, left_offsets, 0);
1418    let last_left = utf8_span(left_bytes, left_offsets, left_n - 1);
1419    let first_right = utf8_span(right_bytes, right_offsets, 0);
1420    let last_right = utf8_span(right_bytes, right_offsets, right_n - 1);
1421    if last_left < first_right || last_right < first_left {
1422        return Some(InnerPositionPlan::Gather {
1423            left_positions,
1424            right_positions,
1425        });
1426    }
1427
1428    let mut left_idx = utf8_span_lower_bound(left_bytes, left_offsets, first_right);
1429    let mut right_idx = if left_idx < left_n {
1430        utf8_span_lower_bound(
1431            right_bytes,
1432            right_offsets,
1433            utf8_span(left_bytes, left_offsets, left_idx),
1434        )
1435    } else {
1436        right_n
1437    };
1438    let mut fixed_width_bulk_attempted = false;
1439
1440    while left_idx < left_n && right_idx < right_n {
1441        let left_span = utf8_span(left_bytes, left_offsets, left_idx);
1442        let right_span = utf8_span(right_bytes, right_offsets, right_idx);
1443
1444        match left_span.cmp(right_span) {
1445            Ordering::Equal => {
1446                if let Some(width) = fixed_width
1447                    && !fixed_width_bulk_attempted
1448                {
1449                    fixed_width_bulk_attempted = true;
1450                    // This branch is reached only after the current left/right
1451                    // key spans compare equal. Matching lower-hex shapes then
1452                    // prove the remaining shifted windows without a full
1453                    // byte-window memcmp.
1454                    let lower_hex_sequences = match (
1455                        left_key.as_lower_hex_sequence_utf8_contiguous(),
1456                        right_key.as_lower_hex_sequence_utf8_contiguous(),
1457                    ) {
1458                        (Some((_, _, left_cert)), Some((_, _, right_cert))) => {
1459                            Some((left_cert, right_cert))
1460                        }
1461                        _ => None,
1462                    };
1463                    if let Some((left_cert, right_cert)) = lower_hex_sequences
1464                        && let Some(run_len) = ordered_utf8_lower_hex_overlap_len(
1465                            left_cert, right_cert, left_idx, left_n, right_idx, right_n,
1466                        )
1467                        && run_len > 1
1468                    {
1469                        if left_positions.is_empty() {
1470                            return Some(InnerPositionPlan::ContiguousRanges {
1471                                left_start: left_idx,
1472                                right_start: right_idx,
1473                                len: run_len,
1474                            });
1475                        }
1476                        left_positions.extend(left_idx..left_idx + run_len);
1477                        right_positions.extend(right_idx..right_idx + run_len);
1478                        left_idx += run_len;
1479                        right_idx += run_len;
1480                        continue;
1481                    }
1482                    let run_len = left_n.saturating_sub(left_idx).min(right_n - right_idx);
1483                    if run_len > 1
1484                        && let Some(byte_len) = run_len.checked_mul(width)
1485                    {
1486                        let left_start = left_offsets[left_idx];
1487                        let right_start = right_offsets[right_idx];
1488                        let left_end = left_start + byte_len;
1489                        let right_end = right_start + byte_len;
1490                        if left_end <= left_bytes.len()
1491                            && right_end <= right_bytes.len()
1492                            && left_bytes[left_start..left_end]
1493                                == right_bytes[right_start..right_end]
1494                        {
1495                            if left_positions.is_empty() {
1496                                return Some(InnerPositionPlan::ContiguousRanges {
1497                                    left_start: left_idx,
1498                                    right_start: right_idx,
1499                                    len: run_len,
1500                                });
1501                            }
1502                            left_positions.extend(left_idx..left_idx + run_len);
1503                            right_positions.extend(right_idx..right_idx + run_len);
1504                            left_idx += run_len;
1505                            right_idx += run_len;
1506                            continue;
1507                        }
1508                    }
1509                }
1510                left_positions.push(left_idx);
1511                right_positions.push(right_idx);
1512                left_idx += 1;
1513                right_idx += 1;
1514            }
1515            Ordering::Less => left_idx += 1,
1516            Ordering::Greater => right_idx += 1,
1517        }
1518    }
1519
1520    Some(InnerPositionPlan::Gather {
1521        left_positions,
1522        right_positions,
1523    })
1524}
1525
1526#[cfg(test)]
1527fn ordered_unique_utf8_inner_positions(
1528    left_key: &Column,
1529    right_key: &Column,
1530) -> Option<(Vec<usize>, Vec<usize>)> {
1531    ordered_unique_utf8_inner_position_plan(left_key, right_key)
1532        .map(InnerPositionPlan::into_positions)
1533}
1534
1535/// Strictly-increasing check over a column's contiguous `&[i64]` backing,
1536/// returning the raw slice. The typed analogue of
1537/// `strictly_increasing_int64_key_values` that skips the `Vec<Scalar>`
1538/// materialization (32 B/elem) — `as_i64_slice` is `Some` only for an
1539/// all-valid contiguous Int64 column, the same gate as the Scalar version
1540/// (dtype Int64 + `validity().all()` + every value `Scalar::Int64`).
1541fn strictly_increasing_i64_slice(column: &Column) -> Option<&[i64]> {
1542    let data = column.as_i64_slice()?;
1543    if data.windows(2).any(|pair| pair[1] <= pair[0]) {
1544        return None;
1545    }
1546    Some(data)
1547}
1548
1549fn ordered_unique_int64_left_match_positions(
1550    left_key: &Column,
1551    right_key: &Column,
1552) -> Option<Vec<Option<usize>>> {
1553    // Typed fast path: both keys carry a contiguous Int64 backing, so run the
1554    // ordered two-pointer match over raw `&[i64]` (8 B/elem, cache-friendly)
1555    // instead of materializing two `Vec<Scalar>` (32 B/elem — ~32 MB per side
1556    // at 1M rows, the tax that left-join paid but the typed inner path did
1557    // not). Bit-identical: same strictly-increasing gate and the same
1558    // monotone walk producing the same `right_idx` per left row.
1559    if let (Some(left_values), Some(right_values)) = (
1560        strictly_increasing_i64_slice(left_key),
1561        strictly_increasing_i64_slice(right_key),
1562    ) {
1563        let mut right_positions = Vec::<Option<usize>>::with_capacity(left_values.len());
1564        let mut right_idx = 0usize;
1565        for &left_value in left_values {
1566            while right_idx < right_values.len() && right_values[right_idx] < left_value {
1567                right_idx += 1;
1568            }
1569            let matched = match right_values.get(right_idx) {
1570                Some(&right_value) if right_value == left_value => Some(right_idx),
1571                _ => None,
1572            };
1573            right_positions.push(matched);
1574        }
1575        return Some(right_positions);
1576    }
1577
1578    let left_values = strictly_increasing_int64_key_values(left_key)?;
1579    let right_values = strictly_increasing_int64_key_values(right_key)?;
1580
1581    let mut right_positions = Vec::<Option<usize>>::with_capacity(left_values.len());
1582    let mut right_idx = 0usize;
1583
1584    for left_value in left_values {
1585        let Scalar::Int64(left_value) = left_value else {
1586            return None;
1587        };
1588        while let Some(Scalar::Int64(right_value)) = right_values.get(right_idx)
1589            && right_value < left_value
1590        {
1591            right_idx += 1;
1592        }
1593
1594        let matched = match right_values.get(right_idx) {
1595            Some(Scalar::Int64(right_value)) if right_value == left_value => Some(right_idx),
1596            Some(Scalar::Int64(_)) | None => None,
1597            Some(_) => return None,
1598        };
1599        right_positions.push(matched);
1600    }
1601
1602    Some(right_positions)
1603}
1604
1605fn ordered_unique_int64_right_match_positions(
1606    left_key: &Column,
1607    right_key: &Column,
1608) -> Option<Vec<Option<usize>>> {
1609    // Typed fast path (mirror of ordered_unique_int64_left_match_positions):
1610    // walk over raw &[i64] when both keys carry a contiguous Int64 backing,
1611    // skipping the Vec<Scalar> materialization (32 B/elem, ~64 MB per merge at
1612    // 1M rows). Bit-identical: same strictly-increasing gate and the same
1613    // monotone walk producing the same left_idx per right row.
1614    if let (Some(left_values), Some(right_values)) = (
1615        strictly_increasing_i64_slice(left_key),
1616        strictly_increasing_i64_slice(right_key),
1617    ) {
1618        let mut left_positions = Vec::<Option<usize>>::with_capacity(right_values.len());
1619        let mut left_idx = 0usize;
1620        for &right_value in right_values {
1621            while left_idx < left_values.len() && left_values[left_idx] < right_value {
1622                left_idx += 1;
1623            }
1624            let matched = match left_values.get(left_idx) {
1625                Some(&left_value) if left_value == right_value => Some(left_idx),
1626                _ => None,
1627            };
1628            left_positions.push(matched);
1629        }
1630        return Some(left_positions);
1631    }
1632
1633    let left_values = strictly_increasing_int64_key_values(left_key)?;
1634    let right_values = strictly_increasing_int64_key_values(right_key)?;
1635
1636    let mut left_positions = Vec::<Option<usize>>::with_capacity(right_values.len());
1637    let mut left_idx = 0usize;
1638
1639    for right_value in right_values {
1640        let Scalar::Int64(right_value) = right_value else {
1641            return None;
1642        };
1643        while let Some(Scalar::Int64(left_value)) = left_values.get(left_idx)
1644            && left_value < right_value
1645        {
1646            left_idx += 1;
1647        }
1648
1649        let matched = match left_values.get(left_idx) {
1650            Some(Scalar::Int64(left_value)) if left_value == right_value => Some(left_idx),
1651            Some(Scalar::Int64(_)) | None => None,
1652            Some(_) => return None,
1653        };
1654        left_positions.push(matched);
1655    }
1656
1657    Some(left_positions)
1658}
1659
1660type OptionalJoinPositions = (Vec<Option<usize>>, Vec<Option<usize>>);
1661
1662/// Direct-address unique-key fast path for a bounded-span Int64 left/inner
1663/// join. When the right keys are *unique* within their value span, the
1664/// counting-sort CSR (count + prefix-sum + scatter + per-bucket emit, over
1665/// several span-sized `usize` arrays) collapses to a single fill pass over one
1666/// compact `u32` table (`pos+1`, `0` == empty) plus a single probe pass — ~14x
1667/// faster at 1M (and faster than open-addressing hashing, no hash/probe).
1668///
1669/// Returns `None` (caller falls back to the CSR path) when: a key column is not
1670/// a contiguous `&[i64]`, the right side is empty, the span exceeds the dense
1671/// gate, the row count would overflow `u32`, or a *duplicate* right key is seen
1672/// (then the CSR path's per-bucket emission is required). For unique right keys
1673/// the emitted `(Some(left_pos), match)` pairs are byte-identical to the CSR
1674/// path: one row per left key in left order, matching the single right position
1675/// in its bucket (or `None` when absent / out of span).
1676fn dense_int64_unique_right_left_positions(
1677    left_key: &Column,
1678    right_key: &Column,
1679) -> Option<OptionalJoinPositions> {
1680    let left_values = left_key.as_i64_slice()?;
1681    let right_values = right_key.as_i64_slice()?;
1682    if right_values.is_empty() || left_values.len() > u32::MAX as usize {
1683        return None;
1684    }
1685
1686    let mut min_key = i64::MAX;
1687    let mut max_key = i64::MIN;
1688    for &key in right_values {
1689        min_key = min_key.min(key);
1690        max_key = max_key.max(key);
1691    }
1692
1693    let span = i128::from(max_key)
1694        .checked_sub(i128::from(min_key))?
1695        .checked_add(1)?;
1696    let row_count = left_values.len().saturating_add(right_values.len());
1697    let max_dense_span = row_count.saturating_mul(4).max(1024);
1698    if span > max_dense_span as i128 {
1699        return None;
1700    }
1701    let span = usize::try_from(span).ok()?;
1702    let span_i128 = i128::try_from(span).ok()?;
1703
1704    // Fill the direct-address table; a non-empty slot means a duplicate right
1705    // key, so bail to the CSR path (which handles many-to-many emission).
1706    let mut table = vec![0u32; span];
1707    for (pos, &key) in right_values.iter().enumerate() {
1708        let bucket = usize::try_from(i128::from(key) - i128::from(min_key)).ok()?;
1709        if table[bucket] != 0 {
1710            return None;
1711        }
1712        table[bucket] = (pos as u32).checked_add(1)?;
1713    }
1714
1715    let mut left_positions = Vec::<Option<usize>>::with_capacity(left_values.len());
1716    let mut right_positions = Vec::<Option<usize>>::with_capacity(left_values.len());
1717    for (left_pos, &key) in left_values.iter().enumerate() {
1718        let offset = i128::from(key) - i128::from(min_key);
1719        let matched = if (0..span_i128).contains(&offset) {
1720            match table[offset as usize] {
1721                0 => None,
1722                slot => Some(slot as usize - 1),
1723            }
1724        } else {
1725            None
1726        };
1727        left_positions.push(Some(left_pos));
1728        right_positions.push(matched);
1729    }
1730
1731    Some((left_positions, right_positions))
1732}
1733
1734fn dense_int64_left_positions(
1735    left_key: &Column,
1736    right_key: &Column,
1737) -> Option<OptionalJoinPositions> {
1738    if let Some(direct) = dense_int64_unique_right_left_positions(left_key, right_key) {
1739        return Some(direct);
1740    }
1741    let left_values = all_valid_int64_key_values(left_key)?;
1742    let right_values = all_valid_int64_key_values(right_key)?;
1743
1744    if right_values.is_empty() {
1745        let left_positions = (0..left_values.len()).map(Some).collect::<Vec<_>>();
1746        let right_positions = vec![None; left_values.len()];
1747        return Some((left_positions, right_positions));
1748    }
1749
1750    let mut min_key = i64::MAX;
1751    let mut max_key = i64::MIN;
1752    for value in right_values {
1753        let Scalar::Int64(key) = value else {
1754            return None;
1755        };
1756        min_key = min_key.min(*key);
1757        max_key = max_key.max(*key);
1758    }
1759
1760    let span = i128::from(max_key)
1761        .checked_sub(i128::from(min_key))?
1762        .checked_add(1)?;
1763    let row_count = left_values.len().saturating_add(right_values.len());
1764    let max_dense_span = row_count.saturating_mul(4).max(1024);
1765    if span > max_dense_span as i128 {
1766        return None;
1767    }
1768    let span = usize::try_from(span).ok()?;
1769    let span_i128 = i128::try_from(span).ok()?;
1770
1771    let mut right_counts = vec![0usize; span];
1772    for value in right_values {
1773        let Scalar::Int64(key) = value else {
1774            return None;
1775        };
1776        let bucket = usize::try_from(i128::from(*key) - i128::from(min_key)).ok()?;
1777        right_counts[bucket] = right_counts[bucket].checked_add(1)?;
1778    }
1779
1780    let mut right_offsets = Vec::<usize>::with_capacity(span + 1);
1781    right_offsets.push(0);
1782    let mut running = 0usize;
1783    for count in &right_counts {
1784        running = running.checked_add(*count)?;
1785        right_offsets.push(running);
1786    }
1787
1788    let mut write_offsets = right_offsets[..span].to_vec();
1789    let mut right_positions_by_bucket = vec![0usize; right_values.len()];
1790    for (pos, value) in right_values.iter().enumerate() {
1791        let Scalar::Int64(key) = value else {
1792            return None;
1793        };
1794        let bucket = usize::try_from(i128::from(*key) - i128::from(min_key)).ok()?;
1795        let write_idx = write_offsets[bucket];
1796        right_positions_by_bucket[write_idx] = pos;
1797        write_offsets[bucket] = write_offsets[bucket].checked_add(1)?;
1798    }
1799
1800    let mut output_len = 0usize;
1801    for value in left_values {
1802        let Scalar::Int64(key) = value else {
1803            return None;
1804        };
1805        let offset = i128::from(*key) - i128::from(min_key);
1806        let bucket_rows = if (0..span_i128).contains(&offset) {
1807            let bucket = usize::try_from(offset).ok()?;
1808            right_counts[bucket].max(1)
1809        } else {
1810            1
1811        };
1812        output_len = output_len.checked_add(bucket_rows)?;
1813    }
1814
1815    let mut left_positions = Vec::<Option<usize>>::with_capacity(output_len);
1816    let mut right_positions = Vec::<Option<usize>>::with_capacity(output_len);
1817    for (left_pos, value) in left_values.iter().enumerate() {
1818        let Scalar::Int64(key) = value else {
1819            return None;
1820        };
1821        let offset = i128::from(*key) - i128::from(min_key);
1822        if (0..span_i128).contains(&offset) {
1823            let bucket = usize::try_from(offset).ok()?;
1824            let start = right_offsets[bucket];
1825            let end = right_offsets[bucket + 1];
1826            if start != end {
1827                for &right_pos in &right_positions_by_bucket[start..end] {
1828                    left_positions.push(Some(left_pos));
1829                    right_positions.push(Some(right_pos));
1830                }
1831                continue;
1832            }
1833        }
1834        left_positions.push(Some(left_pos));
1835        right_positions.push(None);
1836    }
1837
1838    Some((left_positions, right_positions))
1839}
1840
1841/// Direct-address unique-key fast path for a bounded-span Int64 right join —
1842/// the mirror of [`dense_int64_unique_right_left_positions`]. When the *left*
1843/// (build-side) keys are unique within their span, a single fill + single probe
1844/// over one compact `u32` table replaces the CSR. Keeps every right row; bails
1845/// (caller falls back to the CSR path) on a duplicate left key, non-contiguous
1846/// backing, empty left, oversized span, or `u32` row overflow.
1847fn dense_int64_unique_left_right_positions(
1848    left_key: &Column,
1849    right_key: &Column,
1850) -> Option<OptionalJoinPositions> {
1851    let left_values = left_key.as_i64_slice()?;
1852    let right_values = right_key.as_i64_slice()?;
1853    if left_values.is_empty() || left_values.len() > u32::MAX as usize {
1854        return None;
1855    }
1856
1857    let mut min_key = i64::MAX;
1858    let mut max_key = i64::MIN;
1859    for &key in left_values {
1860        min_key = min_key.min(key);
1861        max_key = max_key.max(key);
1862    }
1863
1864    let span = i128::from(max_key)
1865        .checked_sub(i128::from(min_key))?
1866        .checked_add(1)?;
1867    let row_count = left_values.len().saturating_add(right_values.len());
1868    let max_dense_span = row_count.saturating_mul(4).max(1024);
1869    if span > max_dense_span as i128 {
1870        return None;
1871    }
1872    let span = usize::try_from(span).ok()?;
1873    let span_i128 = i128::try_from(span).ok()?;
1874
1875    let mut table = vec![0u32; span];
1876    for (pos, &key) in left_values.iter().enumerate() {
1877        let bucket = usize::try_from(i128::from(key) - i128::from(min_key)).ok()?;
1878        if table[bucket] != 0 {
1879            return None;
1880        }
1881        table[bucket] = (pos as u32).checked_add(1)?;
1882    }
1883
1884    let mut left_positions = Vec::<Option<usize>>::with_capacity(right_values.len());
1885    let mut right_positions = Vec::<Option<usize>>::with_capacity(right_values.len());
1886    for (right_pos, &key) in right_values.iter().enumerate() {
1887        let offset = i128::from(key) - i128::from(min_key);
1888        let matched = if (0..span_i128).contains(&offset) {
1889            match table[offset as usize] {
1890                0 => None,
1891                slot => Some(slot as usize - 1),
1892            }
1893        } else {
1894            None
1895        };
1896        left_positions.push(matched);
1897        right_positions.push(Some(right_pos));
1898    }
1899
1900    Some((left_positions, right_positions))
1901}
1902
1903fn dense_int64_right_positions(
1904    left_key: &Column,
1905    right_key: &Column,
1906) -> Option<OptionalJoinPositions> {
1907    if let Some(direct) = dense_int64_unique_left_right_positions(left_key, right_key) {
1908        return Some(direct);
1909    }
1910    let left_values = all_valid_int64_key_values(left_key)?;
1911    let right_values = all_valid_int64_key_values(right_key)?;
1912
1913    if left_values.is_empty() {
1914        let left_positions = vec![None; right_values.len()];
1915        let right_positions = (0..right_values.len()).map(Some).collect::<Vec<_>>();
1916        return Some((left_positions, right_positions));
1917    }
1918
1919    let mut min_key = i64::MAX;
1920    let mut max_key = i64::MIN;
1921    for value in left_values {
1922        let Scalar::Int64(key) = value else {
1923            return None;
1924        };
1925        min_key = min_key.min(*key);
1926        max_key = max_key.max(*key);
1927    }
1928
1929    let span = i128::from(max_key)
1930        .checked_sub(i128::from(min_key))?
1931        .checked_add(1)?;
1932    let row_count = left_values.len().saturating_add(right_values.len());
1933    let max_dense_span = row_count.saturating_mul(4).max(1024);
1934    if span > max_dense_span as i128 {
1935        return None;
1936    }
1937    let span = usize::try_from(span).ok()?;
1938    let span_i128 = i128::try_from(span).ok()?;
1939
1940    let mut left_counts = vec![0usize; span];
1941    for value in left_values {
1942        let Scalar::Int64(key) = value else {
1943            return None;
1944        };
1945        let bucket = usize::try_from(i128::from(*key) - i128::from(min_key)).ok()?;
1946        left_counts[bucket] = left_counts[bucket].checked_add(1)?;
1947    }
1948
1949    let mut left_offsets = Vec::<usize>::with_capacity(span + 1);
1950    left_offsets.push(0);
1951    let mut running = 0usize;
1952    for count in &left_counts {
1953        running = running.checked_add(*count)?;
1954        left_offsets.push(running);
1955    }
1956
1957    let mut write_offsets = left_offsets[..span].to_vec();
1958    let mut left_positions_by_bucket = vec![0usize; left_values.len()];
1959    for (pos, value) in left_values.iter().enumerate() {
1960        let Scalar::Int64(key) = value else {
1961            return None;
1962        };
1963        let bucket = usize::try_from(i128::from(*key) - i128::from(min_key)).ok()?;
1964        let write_idx = write_offsets[bucket];
1965        left_positions_by_bucket[write_idx] = pos;
1966        write_offsets[bucket] = write_offsets[bucket].checked_add(1)?;
1967    }
1968
1969    let mut output_len = 0usize;
1970    for value in right_values {
1971        let Scalar::Int64(key) = value else {
1972            return None;
1973        };
1974        let offset = i128::from(*key) - i128::from(min_key);
1975        let bucket_rows = if (0..span_i128).contains(&offset) {
1976            let bucket = usize::try_from(offset).ok()?;
1977            left_counts[bucket].max(1)
1978        } else {
1979            1
1980        };
1981        output_len = output_len.checked_add(bucket_rows)?;
1982    }
1983
1984    let mut left_positions = Vec::<Option<usize>>::with_capacity(output_len);
1985    let mut right_positions = Vec::<Option<usize>>::with_capacity(output_len);
1986    for (right_pos, value) in right_values.iter().enumerate() {
1987        let Scalar::Int64(key) = value else {
1988            return None;
1989        };
1990        let offset = i128::from(*key) - i128::from(min_key);
1991        if (0..span_i128).contains(&offset) {
1992            let bucket = usize::try_from(offset).ok()?;
1993            let start = left_offsets[bucket];
1994            let end = left_offsets[bucket + 1];
1995            if start != end {
1996                for &left_pos in &left_positions_by_bucket[start..end] {
1997                    left_positions.push(Some(left_pos));
1998                    right_positions.push(Some(right_pos));
1999                }
2000                continue;
2001            }
2002        }
2003        left_positions.push(None);
2004        right_positions.push(Some(right_pos));
2005    }
2006
2007    Some((left_positions, right_positions))
2008}
2009
2010/// Direct-address unique-key fast path for a bounded-span Int64 full-outer join.
2011/// When BOTH key sides are unique within the joint span, two compact `u32`
2012/// tables (`pos+1`, `0` == empty) plus a single ascending scan over `0..span`
2013/// replace the CSR's `Vec<Vec<usize>>` (one heap `Vec` per bucket — `span`
2014/// allocations) and the `Vec<Scalar>` materialization. Bails (caller falls back
2015/// to the bucket-list CSR) on a duplicate key on either side, non-contiguous
2016/// backing, oversized span, or `u32` row overflow.
2017///
2018/// Bit-identical for unique keys: the CSR emits one row per bucket in ascending
2019/// key (bucket) order — matched `(Some,Some)`, left-only `(Some,None)`,
2020/// right-only `(None,Some)` — which is exactly the per-bucket scan here.
2021fn dense_int64_unique_outer_positions(
2022    left_key: &Column,
2023    right_key: &Column,
2024) -> Option<OptionalJoinPositions> {
2025    let left_values = left_key.as_i64_slice()?;
2026    let right_values = right_key.as_i64_slice()?;
2027    if left_values.len() > u32::MAX as usize || right_values.len() > u32::MAX as usize {
2028        return None;
2029    }
2030
2031    let mut min_key = i64::MAX;
2032    let mut max_key = i64::MIN;
2033    let mut any = false;
2034    for &key in left_values.iter().chain(right_values.iter()) {
2035        min_key = min_key.min(key);
2036        max_key = max_key.max(key);
2037        any = true;
2038    }
2039    if !any {
2040        return Some((Vec::new(), Vec::new()));
2041    }
2042
2043    let span = i128::from(max_key)
2044        .checked_sub(i128::from(min_key))?
2045        .checked_add(1)?;
2046    let row_count = left_values.len().saturating_add(right_values.len());
2047    let max_dense_span = row_count.saturating_mul(4).max(1024);
2048    if span > max_dense_span as i128 {
2049        return None;
2050    }
2051    let span = usize::try_from(span).ok()?;
2052
2053    let mut left_table = vec![0u32; span];
2054    let mut right_table = vec![0u32; span];
2055    for (pos, &key) in left_values.iter().enumerate() {
2056        let bucket = usize::try_from(i128::from(key) - i128::from(min_key)).ok()?;
2057        if left_table[bucket] != 0 {
2058            return None;
2059        }
2060        left_table[bucket] = (pos as u32).checked_add(1)?;
2061    }
2062    for (pos, &key) in right_values.iter().enumerate() {
2063        let bucket = usize::try_from(i128::from(key) - i128::from(min_key)).ok()?;
2064        if right_table[bucket] != 0 {
2065            return None;
2066        }
2067        right_table[bucket] = (pos as u32).checked_add(1)?;
2068    }
2069
2070    let mut left_positions = Vec::<Option<usize>>::new();
2071    let mut right_positions = Vec::<Option<usize>>::new();
2072    for bucket in 0..span {
2073        match (left_table[bucket], right_table[bucket]) {
2074            (0, 0) => {}
2075            (l, 0) => {
2076                left_positions.push(Some(l as usize - 1));
2077                right_positions.push(None);
2078            }
2079            (0, r) => {
2080                left_positions.push(None);
2081                right_positions.push(Some(r as usize - 1));
2082            }
2083            (l, r) => {
2084                left_positions.push(Some(l as usize - 1));
2085                right_positions.push(Some(r as usize - 1));
2086            }
2087        }
2088    }
2089
2090    Some((left_positions, right_positions))
2091}
2092
2093fn dense_int64_outer_positions(
2094    left_key: &Column,
2095    right_key: &Column,
2096) -> Option<OptionalJoinPositions> {
2097    if let Some(direct) = dense_int64_unique_outer_positions(left_key, right_key) {
2098        return Some(direct);
2099    }
2100    let left_values = all_valid_int64_key_values(left_key)?;
2101    let right_values = all_valid_int64_key_values(right_key)?;
2102
2103    let mut min_key = None::<i64>;
2104    let mut max_key = None::<i64>;
2105    for value in left_values.iter().chain(right_values.iter()) {
2106        let Scalar::Int64(key) = value else {
2107            return None;
2108        };
2109        min_key = Some(min_key.map_or(*key, |current| current.min(*key)));
2110        max_key = Some(max_key.map_or(*key, |current| current.max(*key)));
2111    }
2112
2113    let Some(min_key) = min_key else {
2114        return Some((Vec::new(), Vec::new()));
2115    };
2116    let max_key = max_key.expect("max key exists when min key exists");
2117    let span = i128::from(max_key)
2118        .checked_sub(i128::from(min_key))?
2119        .checked_add(1)?;
2120    let row_count = left_values.len().saturating_add(right_values.len());
2121    let max_dense_span = row_count.saturating_mul(4).max(1024);
2122    if span > max_dense_span as i128 {
2123        return None;
2124    }
2125    let span = usize::try_from(span).ok()?;
2126
2127    let mut left_buckets = (0..span).map(|_| Vec::<usize>::new()).collect::<Vec<_>>();
2128    let mut right_buckets = (0..span).map(|_| Vec::<usize>::new()).collect::<Vec<_>>();
2129
2130    for (pos, value) in left_values.iter().enumerate() {
2131        let Scalar::Int64(key) = value else {
2132            return None;
2133        };
2134        let bucket = usize::try_from(i128::from(*key) - i128::from(min_key)).ok()?;
2135        left_buckets[bucket].push(pos);
2136    }
2137    for (pos, value) in right_values.iter().enumerate() {
2138        let Scalar::Int64(key) = value else {
2139            return None;
2140        };
2141        let bucket = usize::try_from(i128::from(*key) - i128::from(min_key)).ok()?;
2142        right_buckets[bucket].push(pos);
2143    }
2144
2145    let mut output_len = 0usize;
2146    for (left_bucket, right_bucket) in left_buckets.iter().zip(right_buckets.iter()) {
2147        let bucket_rows = match (left_bucket.is_empty(), right_bucket.is_empty()) {
2148            (false, false) => left_bucket.len().checked_mul(right_bucket.len())?,
2149            (false, true) => left_bucket.len(),
2150            (true, false) => right_bucket.len(),
2151            (true, true) => 0,
2152        };
2153        output_len = output_len.checked_add(bucket_rows)?;
2154    }
2155
2156    let mut left_positions = Vec::<Option<usize>>::with_capacity(output_len);
2157    let mut right_positions = Vec::<Option<usize>>::with_capacity(output_len);
2158    for (left_bucket, right_bucket) in left_buckets.into_iter().zip(right_buckets) {
2159        match (left_bucket.is_empty(), right_bucket.is_empty()) {
2160            (false, false) => {
2161                for left_pos in left_bucket {
2162                    for &right_pos in &right_bucket {
2163                        left_positions.push(Some(left_pos));
2164                        right_positions.push(Some(right_pos));
2165                    }
2166                }
2167            }
2168            (false, true) => {
2169                for left_pos in left_bucket {
2170                    left_positions.push(Some(left_pos));
2171                    right_positions.push(None);
2172                }
2173            }
2174            (true, false) => {
2175                for right_pos in right_bucket {
2176                    left_positions.push(None);
2177                    right_positions.push(Some(right_pos));
2178                }
2179            }
2180            (true, true) => {}
2181        }
2182    }
2183
2184    Some((left_positions, right_positions))
2185}
2186
2187fn ordered_unique_int64_outer_positions(
2188    left_key: &Column,
2189    right_key: &Column,
2190) -> Option<OptionalJoinPositions> {
2191    // Typed fast path (see ordered_unique_int64_left_match_positions): merge the
2192    // ordered union over raw &[i64] when both keys carry a contiguous Int64
2193    // backing, skipping the Vec<Scalar> materialization (32 B/elem, ~64 MB per
2194    // merge at 1M rows). Bit-identical: same strictly-increasing gate and the
2195    // same three-way merge emitting the same (Option,Option) position pairs and
2196    // the same drain order.
2197    if let (Some(left_values), Some(right_values)) = (
2198        strictly_increasing_i64_slice(left_key),
2199        strictly_increasing_i64_slice(right_key),
2200    ) {
2201        let cap = left_values.len().saturating_add(right_values.len());
2202        let mut left_positions = Vec::<Option<usize>>::with_capacity(cap);
2203        let mut right_positions = Vec::<Option<usize>>::with_capacity(cap);
2204        let (mut left_idx, mut right_idx) = (0usize, 0usize);
2205        while left_idx < left_values.len() && right_idx < right_values.len() {
2206            match left_values[left_idx].cmp(&right_values[right_idx]) {
2207                Ordering::Equal => {
2208                    left_positions.push(Some(left_idx));
2209                    right_positions.push(Some(right_idx));
2210                    left_idx += 1;
2211                    right_idx += 1;
2212                }
2213                Ordering::Less => {
2214                    left_positions.push(Some(left_idx));
2215                    right_positions.push(None);
2216                    left_idx += 1;
2217                }
2218                Ordering::Greater => {
2219                    left_positions.push(None);
2220                    right_positions.push(Some(right_idx));
2221                    right_idx += 1;
2222                }
2223            }
2224        }
2225        while left_idx < left_values.len() {
2226            left_positions.push(Some(left_idx));
2227            right_positions.push(None);
2228            left_idx += 1;
2229        }
2230        while right_idx < right_values.len() {
2231            left_positions.push(None);
2232            right_positions.push(Some(right_idx));
2233            right_idx += 1;
2234        }
2235        return Some((left_positions, right_positions));
2236    }
2237
2238    let left_values = strictly_increasing_int64_key_values(left_key)?;
2239    let right_values = strictly_increasing_int64_key_values(right_key)?;
2240
2241    let mut left_positions =
2242        Vec::<Option<usize>>::with_capacity(left_values.len().saturating_add(right_values.len()));
2243    let mut right_positions = Vec::<Option<usize>>::with_capacity(left_positions.capacity());
2244    let mut left_idx = 0usize;
2245    let mut right_idx = 0usize;
2246
2247    while left_idx < left_values.len() && right_idx < right_values.len() {
2248        let left_value = match &left_values[left_idx] {
2249            Scalar::Int64(value) => *value,
2250            _ => return None,
2251        };
2252        let right_value = match &right_values[right_idx] {
2253            Scalar::Int64(value) => *value,
2254            _ => return None,
2255        };
2256
2257        match left_value.cmp(&right_value) {
2258            Ordering::Equal => {
2259                left_positions.push(Some(left_idx));
2260                right_positions.push(Some(right_idx));
2261                left_idx += 1;
2262                right_idx += 1;
2263            }
2264            Ordering::Less => {
2265                left_positions.push(Some(left_idx));
2266                right_positions.push(None);
2267                left_idx += 1;
2268            }
2269            Ordering::Greater => {
2270                left_positions.push(None);
2271                right_positions.push(Some(right_idx));
2272                right_idx += 1;
2273            }
2274        }
2275    }
2276
2277    while left_idx < left_values.len() {
2278        left_positions.push(Some(left_idx));
2279        right_positions.push(None);
2280        left_idx += 1;
2281    }
2282    while right_idx < right_values.len() {
2283        left_positions.push(None);
2284        right_positions.push(Some(right_idx));
2285        right_idx += 1;
2286    }
2287
2288    Some((left_positions, right_positions))
2289}
2290
2291fn identity_merge_column(
2292    column: &Column,
2293    row_count: usize,
2294    identity_positions: &mut Option<Vec<usize>>,
2295) -> Column {
2296    if column.validity().all() {
2297        return column.clone();
2298    }
2299
2300    let positions = identity_positions.get_or_insert_with(|| (0..row_count).collect());
2301    column.take_positions(positions)
2302}
2303
2304fn resolve_merge_indicator_name(indicator_name: Option<&str>) -> Result<Option<String>, JoinError> {
2305    let Some(name) = indicator_name else {
2306        return Ok(None);
2307    };
2308    if name.trim().is_empty() {
2309        return Err(JoinError::Frame(FrameError::CompatibilityRejected(
2310            "merge indicator column name must be non-empty".to_owned(),
2311        )));
2312    }
2313    Ok(Some(name.to_owned()))
2314}
2315
2316fn build_merge_indicator_column(
2317    left_positions: &[Option<usize>],
2318    right_positions: &[Option<usize>],
2319) -> Result<Column, JoinError> {
2320    let values = left_positions
2321        .iter()
2322        .zip(right_positions.iter())
2323        .map(|(left_pos, right_pos)| match (left_pos, right_pos) {
2324            (Some(_), Some(_)) => fp_types::Scalar::Utf8("both".to_owned()),
2325            (Some(_), None) => fp_types::Scalar::Utf8("left_only".to_owned()),
2326            (None, Some(_)) => fp_types::Scalar::Utf8("right_only".to_owned()),
2327            (None, None) => fp_types::Scalar::Null(fp_types::NullKind::Null),
2328        })
2329        .collect::<Vec<_>>();
2330    Column::from_values(values).map_err(JoinError::from)
2331}
2332
2333fn ensure_indicator_name_available(
2334    indicator_name: &str,
2335    left_col_names: &HashSet<&String>,
2336    right_col_names: &HashSet<&String>,
2337    output_columns: &std::collections::BTreeMap<String, Column>,
2338) -> Result<(), JoinError> {
2339    if left_col_names
2340        .iter()
2341        .any(|name| name.as_str() == indicator_name)
2342        || right_col_names
2343            .iter()
2344            .any(|name| name.as_str() == indicator_name)
2345        || output_columns.contains_key(indicator_name)
2346    {
2347        return Err(JoinError::Frame(FrameError::CompatibilityRejected(
2348            format!("merge indicator column '{indicator_name}' conflicts with an existing column"),
2349        )));
2350    }
2351    Ok(())
2352}
2353
2354/// Positional gather that keeps an all-valid Int64 output column TYPED.
2355///
2356/// `Column::take_positions` already typed-fast-paths all-valid Float64 (it
2357/// gathers into a contiguous `Vec<f64>` behind `lazy_all_valid_float64`), but
2358/// for all-valid Int64 it materializes a `Vec<Scalar::Int64>` (32 B/elem). On
2359/// the inner-merge output build — one gather per carried column — that Scalar
2360/// rebuild dominates for integer payloads. Here we gather the contiguous `i64`
2361/// buffer directly and hand it to `from_i64_values`, which yields the same
2362/// lazy-typed all-valid Int64 column.
2363///
2364/// Bit-identical to `take_positions`: for an all-valid Int64 column the latter
2365/// produces `Scalar::Int64(slice[pos])` at every output slot with an all-valid
2366/// mask; `from_i64_values(gathered)` materializes exactly those scalars with the
2367/// same all-valid mask (no NaN coercion path for i64), and `Column` equality
2368/// ignores the internal data cache. `as_i64_slice` returns `Some` only for an
2369/// all-valid, typed-backed Int64 column, so every other dtype / any-missing
2370/// column falls through to the unchanged `take_positions`.
2371fn take_positions_typed(column: &Column, positions: &[usize]) -> Column {
2372    if let Some(slice) = column.as_i64_slice() {
2373        let mut data = Vec::with_capacity(positions.len());
2374        for &pos in positions {
2375            data.push(slice[pos]);
2376        }
2377        return Column::from_i64_values(data);
2378    }
2379    column.take_positions(positions)
2380}
2381
2382#[derive(Clone, Copy)]
2383enum PositionSelection<'a> {
2384    Positions(&'a [usize]),
2385    ContiguousRange { start: usize, len: usize },
2386}
2387
2388impl PositionSelection<'_> {
2389    fn len(self) -> usize {
2390        match self {
2391            Self::Positions(positions) => positions.len(),
2392            Self::ContiguousRange { len, .. } => len,
2393        }
2394    }
2395}
2396
2397fn take_position_selection_typed(column: &Column, selection: PositionSelection<'_>) -> Column {
2398    match selection {
2399        PositionSelection::Positions(positions) => take_positions_typed(column, positions),
2400        PositionSelection::ContiguousRange { start, len } => {
2401            column.take_contiguous_range(start, len)
2402        }
2403    }
2404}
2405
2406fn take_lower_hex_sequence_range(column: &Column, start: usize, len: usize) -> Option<Column> {
2407    let (prefix, certificate, source_len) = column.as_lower_hex_sequence_utf8()?;
2408    let end = start.checked_add(len)?;
2409    if end > source_len {
2410        return None;
2411    }
2412    let start_value = certificate.value_at(start)?;
2413    Column::from_lower_hex_sequence_utf8(prefix, start_value, len, certificate.hex_width())
2414}
2415
2416#[derive(Clone, Copy)]
2417enum FusedInt64Side {
2418    Left,
2419    Right,
2420}
2421
2422struct FusedInt64OutputColumn<'a> {
2423    name: String,
2424    side: FusedInt64Side,
2425    values: &'a [i64],
2426}
2427
2428struct FusedInt64MergeOptions<'a> {
2429    suffixes: &'a ResolvedMergeSuffixes,
2430    require_all_left_keys_matched: bool,
2431}
2432
2433#[cfg(not(test))]
2434const DENSE_I64_INNER_PARALLEL_MIN_VALUES: usize = 1 << 18;
2435#[cfg(test)]
2436const DENSE_I64_INNER_PARALLEL_MIN_VALUES: usize = 1;
2437const DENSE_I64_INNER_PARALLEL_MAX_CHUNKS: usize = 16;
2438
2439fn join_parallel_thread_count() -> usize {
2440    static THREAD_COUNT: OnceLock<usize> = OnceLock::new();
2441    *THREAD_COUNT.get_or_init(|| {
2442        std::thread::available_parallelism()
2443            .map_or(1, usize::from)
2444            .min(DENSE_I64_INNER_PARALLEL_MAX_CHUNKS)
2445    })
2446}
2447
2448struct DenseI64InnerOutputPlan<'a> {
2449    left_keys: &'a [i64],
2450    min: i64,
2451    max: i64,
2452    offsets: &'a [usize],
2453    positions: &'a [usize],
2454    output_len: usize,
2455}
2456
2457/// One output lane of the dense i64 inner merge.
2458enum DenseI64LaneData {
2459    /// Left lane carried as per-run values plus a shared run-length descriptor
2460    /// — O(matched) memory, expanded lazily by column consumers
2461    /// (br-frankenpandas-3ad4n, br-frankenpandas-l4adm).
2462    RepeatRunLengths {
2463        values: Vec<i64>,
2464        run_lens: Arc<[usize]>,
2465    },
2466    /// Right lane carried as repeated slices of one bucket-order value tape —
2467    /// O(right + matched) memory until a consumer forces a contiguous view.
2468    RepeatedSlices {
2469        data: Vec<i64>,
2470        segments: Arc<[(usize, usize)]>,
2471    },
2472    /// Fully materialized contiguous values.
2473    Full(Vec<i64>),
2474}
2475
2476/// Row-chunked disjoint-write fill (br-frankenpandas-6bsw3) with lazy
2477/// repeat-run left lanes (br-frankenpandas-3ad4n).
2478///
2479/// One probe walk records every matched left row as `(left_pos,
2480/// bucket_start, run_len)`. Left lanes are pure repeat runs (each left value
2481/// repeated `run_len` times), so when the average fanout is >= 2 they are
2482/// emitted as `(value, run_len)` pairs — O(matched) memory instead of
2483/// O(output) — and expanded only if a downstream consumer reads the values.
2484/// Remaining lanes (right lanes always; left lanes too on low-fanout joins
2485/// where a 16 B run would exceed the expanded bytes) are materialized by the
2486/// 6bsw3 scheme: up to [`DENSE_I64_INNER_PARALLEL_MAX_CHUNKS`] output-size-
2487/// balanced chunks of the matched list, each worker filling its disjoint
2488/// `split_at_mut` slice of every full lane (left repeat-runs via
2489/// `slice::fill`, right bucket ranges via `copy_from_slice` from the shared
2490/// muis1 value tapes).
2491///
2492/// Bit-identical: the matched list IS the left probe order; expanding a
2493/// `RepeatRunLengths` lane reproduces exactly the values the `Full` fill
2494/// writes, and chunks partition the matched list so concatenated output equals
2495/// the single-threaded walk byte for byte.
2496fn build_dense_i64_inner_output_data(
2497    specs: &[FusedInt64OutputColumn<'_>],
2498    plan: &DenseI64InnerOutputPlan<'_>,
2499) -> Vec<DenseI64LaneData> {
2500    // Single probe walk shared by every lane: matched left rows in probe
2501    // order as (left_pos, bucket_start, run_len).
2502    let mut matched: Vec<(usize, usize, usize)> = Vec::new();
2503    for (left_pos, &v) in plan.left_keys.iter().enumerate() {
2504        if v < plan.min || v > plan.max {
2505            continue;
2506        }
2507        let bucket = (v - plan.min) as usize;
2508        if bucket + 1 >= plan.offsets.len() {
2509            continue;
2510        }
2511        let start = plan.offsets[bucket];
2512        let run_len = plan.offsets[bucket + 1] - start;
2513        if run_len == 0 {
2514            continue;
2515        }
2516        matched.push((left_pos, start, run_len));
2517    }
2518    debug_assert_eq!(
2519        matched
2520            .iter()
2521            .map(|&(_, _, run_len)| run_len)
2522            .sum::<usize>(),
2523        plan.output_len
2524    );
2525
2526    // A (value, run_len) pair is 16 B vs 8 B x run_len expanded: repeat runs
2527    // only pay when the average fanout is >= 2 (1:1 joins stay materialized).
2528    let use_repeat_runs = plan.output_len >= matched.len().saturating_mul(2);
2529
2530    let use_repeated_slices = use_repeat_runs;
2531    let repeat_run_lens: Option<Arc<[usize]>> = if use_repeat_runs {
2532        Some(
2533            matched
2534                .iter()
2535                .map(|&(_, _, run_len)| run_len)
2536                .collect::<Vec<_>>()
2537                .into(),
2538        )
2539    } else {
2540        None
2541    };
2542    let repeated_segments: Option<Arc<[(usize, usize)]>> = if use_repeated_slices {
2543        Some(
2544            matched
2545                .iter()
2546                .map(|&(_, start, run_len)| (start, run_len))
2547                .collect::<Vec<_>>()
2548                .into(),
2549        )
2550    } else {
2551        None
2552    };
2553
2554    let full_specs: Vec<usize> = specs
2555        .iter()
2556        .enumerate()
2557        .filter(|(_, spec)| {
2558            !(use_repeat_runs && matches!(spec.side, FusedInt64Side::Left))
2559                && !(use_repeated_slices && matches!(spec.side, FusedInt64Side::Right))
2560        })
2561        .map(|(idx, _)| idx)
2562        .collect();
2563
2564    // Fill the full lanes first (right lanes always; left lanes on
2565    // low-fanout joins).
2566    let mut full_data: Vec<Vec<i64>> = Vec::new();
2567    let thread_count = join_parallel_thread_count();
2568    if !full_specs.is_empty()
2569        && plan.output_len >= DENSE_I64_INNER_PARALLEL_MIN_VALUES
2570        && thread_count > 1
2571    {
2572        // Replay buckets from a value tape per right-side column (one gather
2573        // of right values into bucket order, per br-frankenpandas-muis1),
2574        // shared read-only across all chunk workers.
2575        let tapes: Vec<Option<Vec<i64>>> = full_specs
2576            .iter()
2577            .map(|&spec_idx| match specs[spec_idx].side {
2578                FusedInt64Side::Left => None,
2579                FusedInt64Side::Right => Some(
2580                    plan.positions
2581                        .iter()
2582                        .map(|&right_pos| specs[spec_idx].values[right_pos])
2583                        .collect(),
2584                ),
2585            })
2586            .collect();
2587
2588        // Chunk boundaries (matched_idx, out_pos), balanced by OUTPUT size
2589        // so a few hot buckets cannot starve the other workers.
2590        let target = plan.output_len.div_ceil(thread_count).max(1);
2591        let mut boundaries = vec![(0usize, 0usize)];
2592        let mut cumulative = 0usize;
2593        let mut next_target = target;
2594        for (matched_idx, &(_, _, run_len)) in matched.iter().enumerate() {
2595            cumulative += run_len;
2596            if cumulative >= next_target && matched_idx + 1 < matched.len() {
2597                boundaries.push((matched_idx + 1, cumulative));
2598                next_target = cumulative.saturating_add(target);
2599            }
2600        }
2601        boundaries.push((matched.len(), plan.output_len));
2602        let chunk_count = boundaries.len() - 1;
2603
2604        // Pre-size every full lane, then hand each chunk worker its disjoint
2605        // slice of every lane via progressive split_at_mut.
2606        let mut column_bufs: Vec<Vec<i64>> = full_specs
2607            .iter()
2608            .map(|_| vec![0i64; plan.output_len])
2609            .collect();
2610        let mut bundles: Vec<Vec<&mut [i64]>> = (0..chunk_count)
2611            .map(|_| Vec::with_capacity(full_specs.len()))
2612            .collect();
2613        for buf in &mut column_bufs {
2614            let mut rest: &mut [i64] = buf.as_mut_slice();
2615            let mut prev = 0usize;
2616            for (chunk_idx, window) in boundaries.windows(2).enumerate() {
2617                let (chunk_slice, tail) = rest.split_at_mut(window[1].1 - prev);
2618                prev = window[1].1;
2619                rest = tail;
2620                bundles[chunk_idx].push(chunk_slice);
2621            }
2622        }
2623
2624        let matched = &matched;
2625        let full_specs = &full_specs;
2626        std::thread::scope(|scope| {
2627            let mut handles = Vec::with_capacity(chunk_count);
2628            for (chunk_idx, mut bundle) in bundles.into_iter().enumerate() {
2629                let (matched_start, out_start) = boundaries[chunk_idx];
2630                let (matched_end, out_end) = boundaries[chunk_idx + 1];
2631                let tapes = &tapes;
2632                handles.push(scope.spawn(move || {
2633                    let mut cursor = 0usize;
2634                    for &(left_pos, start, run_len) in &matched[matched_start..matched_end] {
2635                        for (slice, (&spec_idx, tape)) in
2636                            bundle.iter_mut().zip(full_specs.iter().zip(tapes.iter()))
2637                        {
2638                            match specs[spec_idx].side {
2639                                FusedInt64Side::Left => {
2640                                    slice[cursor..cursor + run_len]
2641                                        .fill(specs[spec_idx].values[left_pos]);
2642                                }
2643                                FusedInt64Side::Right => {
2644                                    slice[cursor..cursor + run_len].copy_from_slice(
2645                                        &tape.as_ref().expect("right spec must have a bucket tape")
2646                                            [start..start + run_len],
2647                                    );
2648                                }
2649                            }
2650                        }
2651                        cursor += run_len;
2652                    }
2653                    debug_assert_eq!(cursor, out_end - out_start);
2654                }));
2655            }
2656            for handle in handles {
2657                handle
2658                    .join()
2659                    .expect("dense i64 output worker must not panic");
2660            }
2661        });
2662        full_data = column_bufs;
2663    } else if !full_specs.is_empty() {
2664        full_data = full_specs
2665            .iter()
2666            .map(|_| Vec::<i64>::with_capacity(plan.output_len))
2667            .collect();
2668        for &(left_pos, start, run_len) in &matched {
2669            for (out, &spec_idx) in full_data.iter_mut().zip(full_specs.iter()) {
2670                match specs[spec_idx].side {
2671                    FusedInt64Side::Left => {
2672                        out.resize(out.len() + run_len, specs[spec_idx].values[left_pos]);
2673                    }
2674                    FusedInt64Side::Right => {
2675                        for &right_pos in &plan.positions[start..start + run_len] {
2676                            out.push(specs[spec_idx].values[right_pos]);
2677                        }
2678                    }
2679                }
2680            }
2681        }
2682        debug_assert!(full_data.iter().all(|data| data.len() == plan.output_len));
2683    }
2684
2685    // Assemble lanes in spec order: repeat runs for the lazy left lanes,
2686    // filled buffers for everything else.
2687    let mut full_iter = full_data.into_iter();
2688    specs
2689        .iter()
2690        .map(|spec| {
2691            if use_repeat_runs && matches!(spec.side, FusedInt64Side::Left) {
2692                DenseI64LaneData::RepeatRunLengths {
2693                    values: matched
2694                        .iter()
2695                        .map(|&(left_pos, _, _)| spec.values[left_pos])
2696                        .collect(),
2697                    run_lens: Arc::clone(
2698                        repeat_run_lens
2699                            .as_ref()
2700                            .expect("repeat run lengths must exist"),
2701                    ),
2702                }
2703            } else if use_repeated_slices && matches!(spec.side, FusedInt64Side::Right) {
2704                DenseI64LaneData::RepeatedSlices {
2705                    data: plan
2706                        .positions
2707                        .iter()
2708                        .map(|&right_pos| spec.values[right_pos])
2709                        .collect(),
2710                    segments: Arc::clone(
2711                        repeated_segments
2712                            .as_ref()
2713                            .expect("repeated slice segments must exist"),
2714                    ),
2715                }
2716            } else {
2717                DenseI64LaneData::Full(
2718                    full_iter
2719                        .next()
2720                        .expect("full lane buffer must exist for every non-run spec"),
2721                )
2722            }
2723        })
2724        .collect()
2725}
2726
2727/// Which typed lane an output column of the dense inner merge uses, recorded in
2728/// column-encounter order so the i64 (lazy) and f64 (materialized) builds can be
2729/// re-interleaved into the original column order (br-frankenpandas-jzrem).
2730enum DenseInnerSpecKind {
2731    I64,
2732    F64,
2733}
2734
2735/// One Float64 output lane of the dense inner merge (br-frankenpandas-jzrem).
2736struct FusedF64OutputColumn<'a> {
2737    name: String,
2738    side: FusedInt64Side,
2739    values: &'a [f64],
2740}
2741
2742/// The matched-left-row list `(left_pos, bucket_start, run_len)` in probe order
2743/// — identical to the walk inside [`build_dense_i64_inner_output_data`], so the
2744/// Float64 lanes materialize in the exact same row order as the i64 lanes and
2745/// the flat `take_positions` path.
2746fn dense_inner_matched_runs(plan: &DenseI64InnerOutputPlan<'_>) -> Vec<(usize, usize, usize)> {
2747    let mut matched = Vec::new();
2748    for (left_pos, &v) in plan.left_keys.iter().enumerate() {
2749        if v < plan.min || v > plan.max {
2750            continue;
2751        }
2752        let bucket = (v - plan.min) as usize;
2753        if bucket + 1 >= plan.offsets.len() {
2754            continue;
2755        }
2756        let start = plan.offsets[bucket];
2757        let run_len = plan.offsets[bucket + 1] - start;
2758        if run_len == 0 {
2759            continue;
2760        }
2761        matched.push((left_pos, start, run_len));
2762    }
2763    matched
2764}
2765
2766/// Build one Float64 inner-merge output column as a LAZY representation
2767/// (br-frankenpandas-jzrem) — O(matched + right_len), never the O(output_len)
2768/// materialization:
2769///   * a Left column becomes a repeat-values lane: one value per matched run
2770///     (`values[left_pos]`) over the shared `run_lens` descriptor;
2771///   * a Right column becomes a repeated-slices lane over the bucket-ordered
2772///     value tape (`values` gathered by `positions`, one scattered pass) with
2773///     the shared `segments` descriptor.
2774///
2775/// Both materialize, only when a consumer reads them, to exactly the values
2776/// `take_position_selection_typed` would produce on the flat `(left_positions,
2777/// right_positions)` vectors — same values, same row order (matched-run probe
2778/// order == flat position order). Mirrors the i64 lazy lanes the all-Int64 path
2779/// already emits, so a join whose output is only sized (not consumed) stays
2780/// near-free instead of writing the whole fanned-out column.
2781fn build_dense_inner_f64_column(
2782    side: FusedInt64Side,
2783    values: &[f64],
2784    matched: &[(usize, usize, usize)],
2785    positions: &[usize],
2786    run_lens: &Arc<[usize]>,
2787    segments: &Arc<[(usize, usize)]>,
2788    output_len: usize,
2789) -> Column {
2790    match side {
2791        FusedInt64Side::Left => {
2792            let run_values: Vec<f64> = matched
2793                .iter()
2794                .map(|&(left_pos, _, _)| values[left_pos])
2795                .collect();
2796            Column::from_f64_repeat_values_run_lengths(run_values, Arc::clone(run_lens))
2797        }
2798        FusedInt64Side::Right => {
2799            let tape: Vec<f64> = positions.iter().map(|&p| values[p]).collect();
2800            Column::from_f64_repeated_slices_shared(tape, Arc::clone(segments), output_len)
2801        }
2802    }
2803}
2804
2805/// Build every Float64 inner-merge output column, one worker per column when the
2806/// pool is worth it (the fu8f5 column-parallel pattern). Returns `(name, column)`
2807/// pairs in `specs` order. `run_lens`/`segments` are the shared lazy-lane
2808/// descriptors derived from the matched-run list (one per matched run).
2809fn build_dense_inner_f64_columns(
2810    specs: Vec<FusedF64OutputColumn<'_>>,
2811    matched: &[(usize, usize, usize)],
2812    positions: &[usize],
2813    output_len: usize,
2814) -> Vec<(String, Column)> {
2815    if specs.is_empty() {
2816        return Vec::new();
2817    }
2818    let run_lens: Arc<[usize]> = matched.iter().map(|&(_, _, run_len)| run_len).collect();
2819    let segments: Arc<[(usize, usize)]> = matched
2820        .iter()
2821        .map(|&(_, bucket_start, run_len)| (bucket_start, run_len))
2822        .collect();
2823
2824    let worker_count = join_parallel_thread_count().min(specs.len());
2825    if worker_count < 2 {
2826        return specs
2827            .into_iter()
2828            .map(|s| {
2829                (
2830                    s.name,
2831                    build_dense_inner_f64_column(
2832                        s.side, s.values, matched, positions, &run_lens, &segments, output_len,
2833                    ),
2834                )
2835            })
2836            .collect();
2837    }
2838
2839    let next = std::sync::atomic::AtomicUsize::new(0);
2840    let specs_ref = &specs;
2841    let run_lens_ref = &run_lens;
2842    let segments_ref = &segments;
2843    let built_by_worker = std::thread::scope(|scope| {
2844        let mut handles = Vec::with_capacity(worker_count);
2845        for _ in 0..worker_count {
2846            let next = &next;
2847            handles.push(scope.spawn(move || {
2848                let mut local: Vec<(usize, Column)> = Vec::new();
2849                loop {
2850                    let idx = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2851                    if idx >= specs_ref.len() {
2852                        break;
2853                    }
2854                    let s = &specs_ref[idx];
2855                    local.push((
2856                        idx,
2857                        build_dense_inner_f64_column(
2858                            s.side,
2859                            s.values,
2860                            matched,
2861                            positions,
2862                            run_lens_ref,
2863                            segments_ref,
2864                            output_len,
2865                        ),
2866                    ));
2867                }
2868                local
2869            }));
2870        }
2871        let mut all: Vec<(usize, Column)> = Vec::new();
2872        for handle in handles {
2873            all.extend(
2874                handle
2875                    .join()
2876                    .expect("f64 inner-merge column worker panicked"),
2877            );
2878        }
2879        all
2880    });
2881
2882    let mut built: Vec<Option<Column>> = (0..specs.len()).map(|_| None).collect();
2883    for (idx, column) in built_by_worker {
2884        built[idx] = Some(column);
2885    }
2886    specs
2887        .into_iter()
2888        .zip(built)
2889        .map(|(s, column)| {
2890            (
2891                s.name,
2892                column.expect("every f64 column index is built once"),
2893            )
2894        })
2895        .collect()
2896}
2897
2898fn build_single_key_dense_i64_inner_merge_output(
2899    left: &fp_frame::DataFrame,
2900    right: &fp_frame::DataFrame,
2901    left_on: &[&str],
2902    right_on: &[&str],
2903    left_key: &Column,
2904    right_key: &Column,
2905    options: FusedInt64MergeOptions<'_>,
2906) -> Result<Option<MergedDataFrame>, JoinError> {
2907    debug_assert_eq!(left_on.len(), 1);
2908    debug_assert_eq!(right_on.len(), 1);
2909
2910    let Some(left_keys) = left_key.as_i64_slice() else {
2911        return Ok(None);
2912    };
2913    let Some(right_keys) = right_key.as_i64_slice() else {
2914        return Ok(None);
2915    };
2916
2917    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
2918    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
2919    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
2920    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
2921    let shared_key_names = if left_on[0] == right_on[0] {
2922        [left_on[0]].into_iter().collect::<HashSet<&str>>()
2923    } else {
2924        HashSet::new()
2925    };
2926    let overlapping_names =
2927        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
2928
2929    // Collect output specs in column-encounter order, accepting BOTH typed
2930    // all-valid Int64 and typed all-valid Float64 columns (br-frankenpandas-jzrem).
2931    // Int64 columns keep the lazy repeat-run / repeated-slice representation;
2932    // Float64 columns are materialized cache-efficiently below. Any other dtype,
2933    // a nullable column, or a NaN-bearing Float64 (as_f64_slice gates on
2934    // validity.all()) declines the whole fast path (Ok(None)) and falls back to
2935    // the flat gather, exactly as before.
2936    let mut i64_specs = Vec::<FusedInt64OutputColumn<'_>>::new();
2937    let mut f64_specs = Vec::<FusedF64OutputColumn<'_>>::new();
2938    let mut order_kinds = Vec::<DenseInnerSpecKind>::new();
2939
2940    for name in left.column_names() {
2941        let col = left
2942            .columns()
2943            .get(name)
2944            .expect("left column listed in column_names must exist");
2945        let out_name = if left_key_name_set.contains(name.as_str()) {
2946            name.clone()
2947        } else if right_col_names.contains(name) {
2948            apply_merge_suffix(name, options.suffixes.left.as_deref())
2949        } else {
2950            name.clone()
2951        };
2952        if let Some(values) = col.as_i64_slice() {
2953            i64_specs.push(FusedInt64OutputColumn {
2954                name: out_name,
2955                side: FusedInt64Side::Left,
2956                values,
2957            });
2958            order_kinds.push(DenseInnerSpecKind::I64);
2959        } else if let Some(values) = col.as_f64_slice() {
2960            f64_specs.push(FusedF64OutputColumn {
2961                name: out_name,
2962                side: FusedInt64Side::Left,
2963                values,
2964            });
2965            order_kinds.push(DenseInnerSpecKind::F64);
2966        } else {
2967            return Ok(None);
2968        }
2969    }
2970
2971    for name in right.column_names() {
2972        let col = right
2973            .columns()
2974            .get(name)
2975            .expect("right column listed in column_names must exist");
2976        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
2977            continue;
2978        }
2979        let out_name = if left_col_names.contains(name) {
2980            apply_merge_suffix(name, options.suffixes.right.as_deref())
2981        } else {
2982            name.clone()
2983        };
2984        if let Some(values) = col.as_i64_slice() {
2985            i64_specs.push(FusedInt64OutputColumn {
2986                name: out_name,
2987                side: FusedInt64Side::Right,
2988                values,
2989            });
2990            order_kinds.push(DenseInnerSpecKind::I64);
2991        } else if let Some(values) = col.as_f64_slice() {
2992            f64_specs.push(FusedF64OutputColumn {
2993                name: out_name,
2994                side: FusedInt64Side::Right,
2995                values,
2996            });
2997            order_kinds.push(DenseInnerSpecKind::F64);
2998        } else {
2999            return Ok(None);
3000        }
3001    }
3002
3003    ensure_merge_suffixes_for_overlaps(&overlapping_names, options.suffixes)?;
3004
3005    if left_keys.is_empty() || right_keys.is_empty() {
3006        if options.require_all_left_keys_matched && !left_keys.is_empty() {
3007            return Ok(None);
3008        }
3009        let mut columns = std::collections::BTreeMap::new();
3010        let mut column_order = Vec::with_capacity(order_kinds.len());
3011        let mut i64_it = i64_specs.into_iter();
3012        let mut f64_it = f64_specs.into_iter();
3013        for kind in &order_kinds {
3014            match kind {
3015                DenseInnerSpecKind::I64 => {
3016                    let spec = i64_it.next().expect("i64 spec for each I64 kind");
3017                    insert_merged_output_column(
3018                        &mut columns,
3019                        &mut column_order,
3020                        spec.name,
3021                        Column::from_i64_values(Vec::new()),
3022                    )?;
3023                }
3024                DenseInnerSpecKind::F64 => {
3025                    let spec = f64_it.next().expect("f64 spec for each F64 kind");
3026                    insert_merged_output_column(
3027                        &mut columns,
3028                        &mut column_order,
3029                        spec.name,
3030                        Column::from_f64_values(Vec::new()),
3031                    )?;
3032                }
3033            }
3034        }
3035        return Ok(Some(MergedDataFrame {
3036            index: Index::new(Vec::new()),
3037            columns,
3038            column_order,
3039        }));
3040    }
3041
3042    let mut min = right_keys[0];
3043    let mut max = right_keys[0];
3044    for &v in right_keys {
3045        if v < min {
3046            min = v;
3047        }
3048        if v > max {
3049            max = v;
3050        }
3051    }
3052    let span = (max as i128) - (min as i128) + 1;
3053    if span > (1i128 << 24) || span > 16 * (right_keys.len() as i128) {
3054        return Ok(None);
3055    }
3056    let range = span as usize;
3057
3058    let mut offsets = vec![0usize; range + 1];
3059    for &v in right_keys {
3060        offsets[(v - min) as usize + 1] += 1;
3061    }
3062    for i in 0..range {
3063        offsets[i + 1] += offsets[i];
3064    }
3065    let mut positions = vec![0usize; right_keys.len()];
3066    let mut cursor = offsets.clone();
3067    for (pos, &v) in right_keys.iter().enumerate() {
3068        let bucket = (v - min) as usize;
3069        positions[cursor[bucket]] = pos;
3070        cursor[bucket] += 1;
3071    }
3072
3073    let mut output_len = 0usize;
3074    for &v in left_keys {
3075        if v < min || v > max {
3076            if options.require_all_left_keys_matched {
3077                return Ok(None);
3078            }
3079            continue;
3080        }
3081        let bucket = (v - min) as usize;
3082        let bucket_len = offsets[bucket + 1] - offsets[bucket];
3083        if bucket_len == 0 {
3084            if options.require_all_left_keys_matched {
3085                return Ok(None);
3086            }
3087            continue;
3088        }
3089        let Some(new_output_len) = output_len.checked_add(bucket_len) else {
3090            return Ok(None);
3091        };
3092        output_len = new_output_len;
3093    }
3094
3095    let output_plan = DenseI64InnerOutputPlan {
3096        left_keys,
3097        min,
3098        max,
3099        offsets: &offsets,
3100        positions: &positions,
3101        output_len,
3102    };
3103    let i64_lanes = build_dense_i64_inner_output_data(&i64_specs, &output_plan);
3104    // Float64 lanes materialized cache-efficiently in the same probe row order
3105    // (br-frankenpandas-jzrem); the matched-run walk is only needed when there
3106    // are Float64 columns to build.
3107    let matched = if f64_specs.is_empty() {
3108        Vec::new()
3109    } else {
3110        dense_inner_matched_runs(&output_plan)
3111    };
3112    let f64_columns = build_dense_inner_f64_columns(f64_specs, &matched, &positions, output_len);
3113
3114    // Lazy unit-range output index: identical labels (0..output_len as
3115    // IndexLabel::Int64, materialized on demand), pre-proven unique and
3116    // ascending — skips the eager Vec<IndexLabel> build for huge join outputs.
3117    let index = Index::new_known_unique_int64_unit_range(0, output_len);
3118    let mut columns = std::collections::BTreeMap::new();
3119    let mut column_order = Vec::with_capacity(order_kinds.len());
3120    let mut i64_it = i64_specs.into_iter().zip(i64_lanes);
3121    let mut f64_it = f64_columns.into_iter();
3122    for kind in &order_kinds {
3123        match kind {
3124            DenseInnerSpecKind::I64 => {
3125                let (spec, lane) = i64_it.next().expect("i64 lane for each I64 kind");
3126                let column = match lane {
3127                    DenseI64LaneData::RepeatRunLengths { values, run_lens } => {
3128                        Column::from_i64_repeat_values_run_lengths(values, run_lens)
3129                    }
3130                    DenseI64LaneData::RepeatedSlices { data, segments } => {
3131                        Column::from_i64_repeated_slices_shared(data, segments, output_len)
3132                    }
3133                    DenseI64LaneData::Full(data) => Column::from_i64_values(data),
3134                };
3135                debug_assert_eq!(column.len(), output_len);
3136                insert_merged_output_column(&mut columns, &mut column_order, spec.name, column)?;
3137            }
3138            DenseInnerSpecKind::F64 => {
3139                let (name, column) = f64_it.next().expect("f64 column for each F64 kind");
3140                debug_assert_eq!(column.len(), output_len);
3141                insert_merged_output_column(&mut columns, &mut column_order, name, column)?;
3142            }
3143        }
3144    }
3145
3146    Ok(Some(MergedDataFrame {
3147        index,
3148        columns,
3149        column_order,
3150    }))
3151}
3152
3153fn push_join_invalid_range(ranges: &mut Vec<(usize, usize)>, start: usize, len: usize) {
3154    if len == 0 {
3155        return;
3156    }
3157    if let Some((last_start, last_len)) = ranges.last_mut()
3158        && last_start.checked_add(*last_len) == Some(start)
3159    {
3160        *last_len += len;
3161        return;
3162    }
3163    ranges.push((start, len));
3164}
3165
3166fn dense_cycle_key_at(witness: Int64DenseCycleWitness, row: usize) -> Option<i64> {
3167    let offset = i64::try_from(row % witness.period).ok()?;
3168    witness.start.checked_add(offset)
3169}
3170
3171fn dense_cycle_left_join_shape(
3172    left_witness: Int64DenseCycleWitness,
3173    right_witness: Int64DenseCycleWitness,
3174) -> Option<(usize, ValidityMask)> {
3175    let mut output_len = 0usize;
3176    let mut invalid_ranges = Vec::<(usize, usize)>::new();
3177    for left_pos in 0..left_witness.len {
3178        let key = dense_cycle_key_at(left_witness, left_pos)?;
3179        if let Some((_, right_count)) = right_witness.offset_count_for_key(key) {
3180            output_len = output_len.checked_add(right_count)?;
3181        } else {
3182            push_join_invalid_range(&mut invalid_ranges, output_len, 1);
3183            output_len = output_len.checked_add(1)?;
3184        }
3185    }
3186    let right_validity = ValidityMask::from_invalid_ranges(Arc::from(invalid_ranges), output_len);
3187    Some((output_len, right_validity))
3188}
3189
3190/// Dense-cycle LEFT merge builder (br-frankenpandas-yq96z).
3191///
3192/// For certified `key[row] = start + (row % period)` Int64 keys, the previous
3193/// high-fanout left path still built an O(left_rows) plan, right segment tape,
3194/// and one repeat-run descriptor per left lane. This path keeps the same
3195/// left-major pandas order but stores only the two key witnesses:
3196///
3197/// - output length/right validity are derived by scanning the left witness once;
3198/// - left lanes read `source[left_pos]` and repeat by the matching right count;
3199/// - right lanes replay positions `right_offset + k * right_period`;
3200/// - unmatched left rows emit one right null at the same output slot.
3201///
3202/// The route accepts only all-valid Int64 columns. Any other dtype/null shape
3203/// falls back to the existing materialized-plan builder.
3204fn build_single_key_dense_cycle_i64_left_merge_output(
3205    left: &fp_frame::DataFrame,
3206    right: &fp_frame::DataFrame,
3207    left_on: &[&str],
3208    right_on: &[&str],
3209    left_key: &Column,
3210    right_key: &Column,
3211    suffixes: &ResolvedMergeSuffixes,
3212) -> Result<Option<MergedDataFrame>, JoinError> {
3213    debug_assert_eq!(left_on.len(), 1);
3214    debug_assert_eq!(right_on.len(), 1);
3215
3216    let Some(left_witness) = left_key
3217        .int64_dense_cycle_witness()
3218        .filter(|witness| witness.len == left_key.len())
3219    else {
3220        return Ok(None);
3221    };
3222    let Some(right_witness) = right_key
3223        .int64_dense_cycle_witness()
3224        .filter(|witness| witness.len == right_key.len())
3225    else {
3226        return Ok(None);
3227    };
3228    let Some((output_len, right_validity)) =
3229        dense_cycle_left_join_shape(left_witness, right_witness)
3230    else {
3231        return Ok(None);
3232    };
3233
3234    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
3235    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
3236    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
3237    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
3238    let shared_key_names = if left_on[0] == right_on[0] {
3239        [left_on[0]].into_iter().collect::<HashSet<&str>>()
3240    } else {
3241        HashSet::new()
3242    };
3243    let overlapping_names =
3244        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
3245
3246    enum DenseCycleLeftLane {
3247        Left,
3248        Right,
3249    }
3250    let mut spec_names = Vec::<String>::new();
3251    let mut spec_kinds = Vec::<DenseCycleLeftLane>::new();
3252    let mut spec_sources = Vec::<Arc<[i64]>>::new();
3253
3254    for name in left.column_names() {
3255        let col = left
3256            .columns()
3257            .get(name)
3258            .expect("left column listed in column_names must exist");
3259        let Some(source) = col.as_i64_arc() else {
3260            return Ok(None);
3261        };
3262        let out_name = if left_key_name_set.contains(name.as_str()) {
3263            name.clone()
3264        } else if right_col_names.contains(name) {
3265            apply_merge_suffix(name, suffixes.left.as_deref())
3266        } else {
3267            name.clone()
3268        };
3269        spec_names.push(out_name);
3270        spec_kinds.push(DenseCycleLeftLane::Left);
3271        spec_sources.push(source);
3272    }
3273
3274    for name in right.column_names() {
3275        let col = right
3276            .columns()
3277            .get(name)
3278            .expect("right column listed in column_names must exist");
3279        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
3280            continue;
3281        }
3282        let Some(source) = col.as_i64_arc() else {
3283            return Ok(None);
3284        };
3285        let out_name = if left_col_names.contains(name) {
3286            apply_merge_suffix(name, suffixes.right.as_deref())
3287        } else {
3288            name.clone()
3289        };
3290        spec_names.push(out_name);
3291        spec_kinds.push(DenseCycleLeftLane::Right);
3292        spec_sources.push(source);
3293    }
3294    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
3295
3296    let index = Index::new_known_unique_int64_unit_range(0, output_len);
3297    let mut columns = std::collections::BTreeMap::new();
3298    let mut column_order = Vec::with_capacity(spec_names.len());
3299    for ((name, kind), source) in spec_names.into_iter().zip(spec_kinds).zip(spec_sources) {
3300        let column = match kind {
3301            DenseCycleLeftLane::Left => Column::from_i64_left_join_dense_cycle_left(
3302                source,
3303                left_witness,
3304                right_witness,
3305                output_len,
3306            ),
3307            DenseCycleLeftLane::Right => Column::from_i64_left_join_dense_cycle_right_nullable(
3308                source,
3309                left_witness,
3310                right_witness,
3311                right_validity.clone(),
3312                output_len,
3313            ),
3314        };
3315        debug_assert_eq!(column.len(), output_len);
3316        insert_merged_output_column(&mut columns, &mut column_order, name, column)?;
3317    }
3318
3319    Ok(Some(MergedDataFrame {
3320        index,
3321        columns,
3322        column_order,
3323    }))
3324}
3325
3326/// Fused dense-i64 LEFT merge builder (br-frankenpandas-7wxoc).
3327///
3328/// The partial-match left join previously materialized TWO
3329/// `Vec<Option<usize>>` of output length (16 B/slot each — ~627 MB of
3330/// intermediate on a 19.6M-row join) in `dense_int64_left_positions`, then
3331/// re-walked them per column through `reindex_by_positions`. Here the probe
3332/// emits a compact matched plan (`(left_pos, bucket_start, run_len)`, with
3333/// `usize::MAX` as the bucket sentinel for unmatched left rows that emit one
3334/// null-right row), and the output lanes are built with the proven inner-
3335/// builder machinery: muis1 right value tapes, 6bsw3 row-chunked disjoint
3336/// `split_at_mut` fills, 3ad4n lazy repeat-run left lanes, plus ONE shared
3337/// validity mask for every right lane (the null pattern is identical across
3338/// them — word-wise run fills, cloned per lane).
3339///
3340/// Bit-identical to the position-vector path: the plan is the same left
3341/// probe order; matched runs replay the same CSR bucket ranges; right lanes
3342/// keep dtype Int64 with `Null(NullKind::Null)` at unmatched rows (exactly
3343/// `reindex_by_positions`' missing semantics); left lanes repeat the left
3344/// value `run_len` times as `take_positions` would.
3345fn build_single_key_dense_i64_left_merge_output(
3346    left: &fp_frame::DataFrame,
3347    right: &fp_frame::DataFrame,
3348    left_on: &[&str],
3349    right_on: &[&str],
3350    left_key: &Column,
3351    right_key: &Column,
3352    suffixes: &ResolvedMergeSuffixes,
3353) -> Result<Option<MergedDataFrame>, JoinError> {
3354    debug_assert_eq!(left_on.len(), 1);
3355    debug_assert_eq!(right_on.len(), 1);
3356
3357    let Some(left_keys) = left_key.as_i64_slice() else {
3358        return Ok(None);
3359    };
3360    let Some(right_keys) = right_key.as_i64_slice() else {
3361        return Ok(None);
3362    };
3363    // Empty sides are rare and the position-vector path handles their edge
3364    // semantics; the dense-span gate below also needs a non-empty right.
3365    if left_keys.is_empty() || right_keys.is_empty() {
3366        return Ok(None);
3367    }
3368
3369    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
3370    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
3371    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
3372    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
3373    let shared_key_names = if left_on[0] == right_on[0] {
3374        [left_on[0]].into_iter().collect::<HashSet<&str>>()
3375    } else {
3376        HashSet::new()
3377    };
3378    let overlapping_names =
3379        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
3380
3381    let mut specs = Vec::<FusedInt64OutputColumn<'_>>::new();
3382    let mut sources = Vec::<Arc<[i64]>>::new();
3383    for name in left.column_names() {
3384        let col = left
3385            .columns()
3386            .get(name)
3387            .expect("left column listed in column_names must exist");
3388        let Some(values) = col.as_i64_slice() else {
3389            return Ok(None);
3390        };
3391        let source = col.as_i64_arc().unwrap_or_else(|| Arc::from(values));
3392        let out_name = if left_key_name_set.contains(name.as_str()) {
3393            name.clone()
3394        } else if right_col_names.contains(name) {
3395            apply_merge_suffix(name, suffixes.left.as_deref())
3396        } else {
3397            name.clone()
3398        };
3399        specs.push(FusedInt64OutputColumn {
3400            name: out_name,
3401            side: FusedInt64Side::Left,
3402            values,
3403        });
3404        sources.push(source);
3405    }
3406    for name in right.column_names() {
3407        let col = right
3408            .columns()
3409            .get(name)
3410            .expect("right column listed in column_names must exist");
3411        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
3412            continue;
3413        }
3414        let Some(values) = col.as_i64_slice() else {
3415            return Ok(None);
3416        };
3417        let source = col.as_i64_arc().unwrap_or_else(|| Arc::from(values));
3418        let out_name = if left_col_names.contains(name) {
3419            apply_merge_suffix(name, suffixes.right.as_deref())
3420        } else {
3421            name.clone()
3422        };
3423        specs.push(FusedInt64OutputColumn {
3424            name: out_name,
3425            side: FusedInt64Side::Right,
3426            values,
3427        });
3428        sources.push(source);
3429    }
3430    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
3431
3432    let row_count = left_keys.len().saturating_add(right_keys.len());
3433    let max_dense_span = row_count.saturating_mul(4).max(1024);
3434    let left_witness = left_key
3435        .int64_dense_cycle_witness()
3436        .filter(|witness| witness.len == left_keys.len());
3437    let right_witness = right_key
3438        .int64_dense_cycle_witness()
3439        .filter(|witness| witness.len == right_keys.len());
3440    if let (Some(left_witness), Some(right_witness), Some((right_min, right_max))) = (
3441        left_witness,
3442        right_witness,
3443        right_witness.and_then(dense_cycle_domain),
3444    ) {
3445        let right_span = i128::from(right_max) - i128::from(right_min) + 1;
3446        if right_span <= max_dense_span as i128
3447            && let Some((output_len, right_validity)) =
3448                dense_cycle_probe_output_len_and_validity(left_witness, right_witness)
3449        {
3450            let index = Index::new_known_unique_int64_unit_range(0, output_len);
3451            let mut columns = std::collections::BTreeMap::new();
3452            let mut column_order = Vec::with_capacity(specs.len());
3453            for (spec, source) in specs.into_iter().zip(sources) {
3454                let column = match spec.side {
3455                    FusedInt64Side::Left => Column::from_i64_dense_cycle_probe_repeat(
3456                        source,
3457                        left_witness,
3458                        right_witness,
3459                        output_len,
3460                    ),
3461                    FusedInt64Side::Right => {
3462                        Column::from_i64_nullable_dense_cycle_probe_build_with_sparse_validity(
3463                            source,
3464                            left_witness,
3465                            right_witness,
3466                            right_validity.clone(),
3467                            output_len,
3468                        )
3469                    }
3470                };
3471                debug_assert_eq!(column.len(), output_len);
3472                insert_merged_output_column(&mut columns, &mut column_order, spec.name, column)?;
3473            }
3474            return Ok(Some(MergedDataFrame {
3475                index,
3476                columns,
3477                column_order,
3478            }));
3479        }
3480    }
3481
3482    // Dense CSR over the RIGHT key range — same gate as the position path
3483    // (span <= 4*(rows)+1024) so routing between fused/fallback matches
3484    // dense_int64_left_positions' accept set.
3485    let mut min_key = right_keys[0];
3486    let mut max_key = right_keys[0];
3487    for &key in right_keys {
3488        min_key = min_key.min(key);
3489        max_key = max_key.max(key);
3490    }
3491    let span = (i128::from(max_key)) - (i128::from(min_key)) + 1;
3492    if span > max_dense_span as i128 {
3493        return Ok(None);
3494    }
3495    let span = usize::try_from(span).expect("span bounded by max_dense_span");
3496
3497    let mut offsets = vec![0usize; span + 1];
3498    for &key in right_keys {
3499        offsets[(key - min_key) as usize + 1] += 1;
3500    }
3501    for i in 0..span {
3502        offsets[i + 1] += offsets[i];
3503    }
3504    let mut positions = vec![0usize; right_keys.len()];
3505    let mut cursor = offsets[..span].to_vec();
3506    for (pos, &key) in right_keys.iter().enumerate() {
3507        let bucket = (key - min_key) as usize;
3508        positions[cursor[bucket]] = pos;
3509        cursor[bucket] += 1;
3510    }
3511
3512    // Matched plan: (left_pos, bucket_start, run_len); bucket_start ==
3513    // usize::MAX marks an unmatched left row (one output row, null right).
3514    const UNMATCHED: usize = usize::MAX;
3515    let mut plan = Vec::<(usize, usize, usize)>::with_capacity(left_keys.len());
3516    let mut output_len = 0usize;
3517    for (left_pos, &key) in left_keys.iter().enumerate() {
3518        let offset = i128::from(key) - i128::from(min_key);
3519        let run = if offset >= 0 && offset < span as i128 {
3520            let bucket = offset as usize;
3521            let start = offsets[bucket];
3522            let len = offsets[bucket + 1] - start;
3523            if len == 0 {
3524                (left_pos, UNMATCHED, 1)
3525            } else {
3526                (left_pos, start, len)
3527            }
3528        } else {
3529            (left_pos, UNMATCHED, 1)
3530        };
3531        let Some(new_len) = output_len.checked_add(run.2) else {
3532            return Ok(None);
3533        };
3534        output_len = new_len;
3535        plan.push(run);
3536    }
3537
3538    // Shared right-lane segment descriptor (br-frankenpandas-yiqv5): the plan's
3539    // `(bucket_start, run_len)` pairs are exactly the nullable repeated-slices
3540    // segment format (`bucket_start == usize::MAX` == UNMATCHED ⇒ a null run), so
3541    // every right lane is emitted as a LAZY `LazyNullableRepeatedSlicesInt64`
3542    // over its bucket-order value tape instead of a materialized O(output_len)
3543    // buffer. The validity mask is rebuilt from these segments inside the column
3544    // ctor (matched runs valid, unmatched rows null) — identical to the prior
3545    // word-wise fill.
3546    let right_segments: Arc<[(usize, usize)]> = plan
3547        .iter()
3548        .map(|&(_, start, run_len)| (start, run_len))
3549        .collect();
3550
3551    // Left lanes as lazy repeat runs when the average fanout pays (3ad4n
3552    // gate); unmatched rows are singleton runs so the representation is
3553    // uniform.
3554    let use_repeat_runs = output_len >= plan.len().saturating_mul(2);
3555
3556    // Only LOW-FANOUT LEFT lanes still materialize into O(output_len) buffers;
3557    // right lanes are always lazy (nullable repeated-slices) and high-fanout
3558    // left lanes are lazy repeat runs.
3559    let full_specs: Vec<usize> = specs
3560        .iter()
3561        .enumerate()
3562        .filter(|(_, spec)| matches!(spec.side, FusedInt64Side::Left) && !use_repeat_runs)
3563        .map(|(idx, _)| idx)
3564        .collect();
3565
3566    let mut full_data: Vec<Vec<i64>> = Vec::new();
3567    let thread_count = join_parallel_thread_count();
3568    if !full_specs.is_empty() {
3569        // Right value tapes in bucket order (muis1), shared read-only.
3570        let tapes: Vec<Option<Vec<i64>>> = full_specs
3571            .iter()
3572            .map(|&spec_idx| match specs[spec_idx].side {
3573                FusedInt64Side::Left => None,
3574                FusedInt64Side::Right => Some(
3575                    positions
3576                        .iter()
3577                        .map(|&right_pos| specs[spec_idx].values[right_pos])
3578                        .collect(),
3579                ),
3580            })
3581            .collect();
3582
3583        if output_len >= DENSE_I64_INNER_PARALLEL_MIN_VALUES && thread_count > 1 {
3584            // Output-balanced chunk boundaries over the plan (6bsw3).
3585            let target = output_len.div_ceil(thread_count).max(1);
3586            let mut boundaries = vec![(0usize, 0usize)];
3587            let mut cumulative = 0usize;
3588            let mut next_target = target;
3589            for (plan_idx, &(_, _, run_len)) in plan.iter().enumerate() {
3590                cumulative += run_len;
3591                if cumulative >= next_target && plan_idx + 1 < plan.len() {
3592                    boundaries.push((plan_idx + 1, cumulative));
3593                    next_target = cumulative.saturating_add(target);
3594                }
3595            }
3596            boundaries.push((plan.len(), output_len));
3597            let chunk_count = boundaries.len() - 1;
3598
3599            let mut column_bufs: Vec<Vec<i64>> =
3600                full_specs.iter().map(|_| vec![0i64; output_len]).collect();
3601            let mut bundles: Vec<Vec<&mut [i64]>> = (0..chunk_count)
3602                .map(|_| Vec::with_capacity(full_specs.len()))
3603                .collect();
3604            for buf in &mut column_bufs {
3605                let mut rest: &mut [i64] = buf.as_mut_slice();
3606                let mut prev = 0usize;
3607                for (chunk_idx, window) in boundaries.windows(2).enumerate() {
3608                    let (chunk_slice, tail) = rest.split_at_mut(window[1].1 - prev);
3609                    prev = window[1].1;
3610                    rest = tail;
3611                    bundles[chunk_idx].push(chunk_slice);
3612                }
3613            }
3614
3615            let plan = &plan;
3616            let specs_ref = &specs;
3617            let full_specs_ref = &full_specs;
3618            std::thread::scope(|scope| {
3619                let mut handles = Vec::with_capacity(chunk_count);
3620                for (chunk_idx, mut bundle) in bundles.into_iter().enumerate() {
3621                    let (plan_start, out_start) = boundaries[chunk_idx];
3622                    let (plan_end, out_end) = boundaries[chunk_idx + 1];
3623                    let tapes = &tapes;
3624                    handles.push(scope.spawn(move || {
3625                        let mut cursor = 0usize;
3626                        for &(left_pos, start, run_len) in &plan[plan_start..plan_end] {
3627                            for (slice, (&spec_idx, tape)) in bundle
3628                                .iter_mut()
3629                                .zip(full_specs_ref.iter().zip(tapes.iter()))
3630                            {
3631                                match specs_ref[spec_idx].side {
3632                                    FusedInt64Side::Left => {
3633                                        slice[cursor..cursor + run_len]
3634                                            .fill(specs_ref[spec_idx].values[left_pos]);
3635                                    }
3636                                    FusedInt64Side::Right => {
3637                                        if start != UNMATCHED {
3638                                            slice[cursor..cursor + run_len].copy_from_slice(
3639                                                &tape
3640                                                    .as_ref()
3641                                                    .expect("right spec must have a bucket tape")
3642                                                    [start..start + run_len],
3643                                            );
3644                                        }
3645                                        // Unmatched rows keep the zeroed
3646                                        // datum; the shared validity mask
3647                                        // marks them null.
3648                                    }
3649                                }
3650                            }
3651                            cursor += run_len;
3652                        }
3653                        debug_assert_eq!(cursor, out_end - out_start);
3654                    }));
3655                }
3656                for handle in handles {
3657                    handle
3658                        .join()
3659                        .expect("dense i64 left output worker must not panic");
3660                }
3661            });
3662            full_data = column_bufs;
3663        } else {
3664            full_data = full_specs.iter().map(|_| vec![0i64; output_len]).collect();
3665            let mut cursor = 0usize;
3666            for &(left_pos, start, run_len) in &plan {
3667                for (buf, (&spec_idx, tape)) in full_data
3668                    .iter_mut()
3669                    .zip(full_specs.iter().zip(tapes.iter()))
3670                {
3671                    match specs[spec_idx].side {
3672                        FusedInt64Side::Left => {
3673                            buf[cursor..cursor + run_len].fill(specs[spec_idx].values[left_pos]);
3674                        }
3675                        FusedInt64Side::Right => {
3676                            if start != UNMATCHED {
3677                                buf[cursor..cursor + run_len].copy_from_slice(
3678                                    &tape.as_ref().expect("right spec must have a bucket tape")
3679                                        [start..start + run_len],
3680                                );
3681                            }
3682                        }
3683                    }
3684                }
3685                cursor += run_len;
3686            }
3687            debug_assert_eq!(cursor, output_len);
3688        }
3689    }
3690
3691    // Lazy unit-range output index (see build_single_key_dense_i64 site).
3692    let index = Index::new_known_unique_int64_unit_range(0, output_len);
3693    let mut columns = std::collections::BTreeMap::new();
3694    let mut column_order = Vec::with_capacity(specs.len());
3695    let mut full_iter = full_data.into_iter();
3696    for spec in specs {
3697        let column = match spec.side {
3698            FusedInt64Side::Right => {
3699                // Lazy nullable repeated-slices over the bucket-order tape
3700                // (br-frankenpandas-yiqv5): O(matched) descriptor, no O(output)
3701                // materialization.
3702                let tape: Vec<i64> = positions
3703                    .iter()
3704                    .map(|&right_pos| spec.values[right_pos])
3705                    .collect();
3706                Column::from_i64_nullable_repeated_slices_shared(
3707                    tape,
3708                    Arc::clone(&right_segments),
3709                    output_len,
3710                )
3711            }
3712            FusedInt64Side::Left if use_repeat_runs => Column::from_i64_repeat_runs(
3713                plan.iter()
3714                    .map(|&(left_pos, _, run_len)| (spec.values[left_pos], run_len))
3715                    .collect(),
3716            ),
3717            FusedInt64Side::Left => {
3718                let data = full_iter
3719                    .next()
3720                    .expect("full lane buffer must exist for every non-run left spec");
3721                Column::from_i64_values(data)
3722            }
3723        };
3724        debug_assert_eq!(column.len(), output_len);
3725        insert_merged_output_column(&mut columns, &mut column_order, spec.name, column)?;
3726    }
3727
3728    Ok(Some(MergedDataFrame {
3729        index,
3730        columns,
3731        column_order,
3732    }))
3733}
3734
3735/// Fused dense-i64 RIGHT merge builder (br-frankenpandas-4p3ie) — the
3736/// side-swapped mirror of [`build_single_key_dense_i64_left_merge_output`]:
3737/// the probe walks RIGHT keys in probe order against a dense CSR over the
3738/// LEFT key range, emitting `(right_pos, left_bucket_start, run_len)` plan
3739/// rows (`usize::MAX` sentinel = unmatched right row, one null-left output
3740/// row). Right lanes (including the shared key column, which pandas fills
3741/// from the RIGHT side under the LEFT name) are all-valid repeat runs; left
3742/// lanes fill from muis1-style left value tapes with ONE shared validity
3743/// mask and keep dtype Int64 with `Null(NullKind::Null)` at unmatched rows
3744/// (`reindex_by_positions` missing semantics — NOT Float64-promoted).
3745fn build_single_key_dense_i64_right_merge_output(
3746    left: &fp_frame::DataFrame,
3747    right: &fp_frame::DataFrame,
3748    left_on: &[&str],
3749    right_on: &[&str],
3750    left_key: &Column,
3751    right_key: &Column,
3752    suffixes: &ResolvedMergeSuffixes,
3753) -> Result<Option<MergedDataFrame>, JoinError> {
3754    debug_assert_eq!(left_on.len(), 1);
3755    debug_assert_eq!(right_on.len(), 1);
3756
3757    let Some(left_keys) = left_key.as_i64_slice() else {
3758        return Ok(None);
3759    };
3760    let Some(right_keys) = right_key.as_i64_slice() else {
3761        return Ok(None);
3762    };
3763    if left_keys.is_empty() || right_keys.is_empty() {
3764        return Ok(None);
3765    }
3766
3767    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
3768    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
3769    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
3770    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
3771    let shared_key_names = if left_on[0] == right_on[0] {
3772        [left_on[0]].into_iter().collect::<HashSet<&str>>()
3773    } else {
3774        HashSet::new()
3775    };
3776    let overlapping_names =
3777        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
3778
3779    // Lane specs in output order. The shared key slot keeps the LEFT name
3780    // but carries RIGHT key values (all output rows have a right row), so it
3781    // is a Right-side lane on right_keys.
3782    let mut specs = Vec::<FusedInt64OutputColumn<'_>>::new();
3783    let mut sources = Vec::<Arc<[i64]>>::new();
3784    for name in left.column_names() {
3785        let col = left
3786            .columns()
3787            .get(name)
3788            .expect("left column listed in column_names must exist");
3789        let Some(values) = col.as_i64_slice() else {
3790            return Ok(None);
3791        };
3792        if left_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
3793            let right_key_col = right
3794                .columns()
3795                .get(right_on[0])
3796                .expect("right key column must exist");
3797            let source = right_key_col
3798                .as_i64_arc()
3799                .unwrap_or_else(|| Arc::from(right_keys));
3800            specs.push(FusedInt64OutputColumn {
3801                name: name.clone(),
3802                side: FusedInt64Side::Right,
3803                values: right_keys,
3804            });
3805            sources.push(source);
3806            continue;
3807        }
3808        let source = col.as_i64_arc().unwrap_or_else(|| Arc::from(values));
3809        let out_name = if left_key_name_set.contains(name.as_str()) {
3810            name.clone()
3811        } else if right_col_names.contains(name) {
3812            apply_merge_suffix(name, suffixes.left.as_deref())
3813        } else {
3814            name.clone()
3815        };
3816        specs.push(FusedInt64OutputColumn {
3817            name: out_name,
3818            side: FusedInt64Side::Left,
3819            values,
3820        });
3821        sources.push(source);
3822    }
3823    for name in right.column_names() {
3824        let col = right
3825            .columns()
3826            .get(name)
3827            .expect("right column listed in column_names must exist");
3828        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
3829            continue;
3830        }
3831        let Some(values) = col.as_i64_slice() else {
3832            return Ok(None);
3833        };
3834        let source = col.as_i64_arc().unwrap_or_else(|| Arc::from(values));
3835        let out_name = if left_col_names.contains(name) {
3836            apply_merge_suffix(name, suffixes.right.as_deref())
3837        } else {
3838            name.clone()
3839        };
3840        specs.push(FusedInt64OutputColumn {
3841            name: out_name,
3842            side: FusedInt64Side::Right,
3843            values,
3844        });
3845        sources.push(source);
3846    }
3847    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
3848
3849    let row_count = left_keys.len().saturating_add(right_keys.len());
3850    let max_dense_span = row_count.saturating_mul(4).max(1024);
3851    let left_witness = left_key
3852        .int64_dense_cycle_witness()
3853        .filter(|witness| witness.len == left_keys.len());
3854    let right_witness = right_key
3855        .int64_dense_cycle_witness()
3856        .filter(|witness| witness.len == right_keys.len());
3857    if let (Some(left_witness), Some(right_witness), Some((left_min, left_max))) = (
3858        left_witness,
3859        right_witness,
3860        left_witness.and_then(dense_cycle_domain),
3861    ) {
3862        let left_span = i128::from(left_max) - i128::from(left_min) + 1;
3863        if left_span <= max_dense_span as i128
3864            && let Some((output_len, left_validity)) =
3865                dense_cycle_probe_output_len_and_validity(right_witness, left_witness)
3866        {
3867            let index = Index::new_known_unique_int64_unit_range(0, output_len);
3868            let mut columns = std::collections::BTreeMap::new();
3869            let mut column_order = Vec::with_capacity(specs.len());
3870            for (spec, source) in specs.into_iter().zip(sources) {
3871                let column = match spec.side {
3872                    FusedInt64Side::Left => {
3873                        Column::from_i64_nullable_dense_cycle_probe_build_with_sparse_validity(
3874                            source,
3875                            right_witness,
3876                            left_witness,
3877                            left_validity.clone(),
3878                            output_len,
3879                        )
3880                    }
3881                    FusedInt64Side::Right => Column::from_i64_dense_cycle_probe_repeat(
3882                        source,
3883                        right_witness,
3884                        left_witness,
3885                        output_len,
3886                    ),
3887                };
3888                debug_assert_eq!(column.len(), output_len);
3889                insert_merged_output_column(&mut columns, &mut column_order, spec.name, column)?;
3890            }
3891            return Ok(Some(MergedDataFrame {
3892                index,
3893                columns,
3894                column_order,
3895            }));
3896        }
3897    }
3898
3899    // Dense CSR over the LEFT key range — same gate as
3900    // dense_int64_right_positions (span <= 4*rows+1024).
3901    let mut min_key = left_keys[0];
3902    let mut max_key = left_keys[0];
3903    for &key in left_keys {
3904        min_key = min_key.min(key);
3905        max_key = max_key.max(key);
3906    }
3907    let span = (i128::from(max_key)) - (i128::from(min_key)) + 1;
3908    if span > max_dense_span as i128 {
3909        return Ok(None);
3910    }
3911    let span = usize::try_from(span).expect("span bounded by max_dense_span");
3912
3913    let mut offsets = vec![0usize; span + 1];
3914    for &key in left_keys {
3915        offsets[(key - min_key) as usize + 1] += 1;
3916    }
3917    for i in 0..span {
3918        offsets[i + 1] += offsets[i];
3919    }
3920    let mut positions = vec![0usize; left_keys.len()];
3921    let mut cursor = offsets[..span].to_vec();
3922    for (pos, &key) in left_keys.iter().enumerate() {
3923        let bucket = (key - min_key) as usize;
3924        positions[cursor[bucket]] = pos;
3925        cursor[bucket] += 1;
3926    }
3927
3928    // Plan over RIGHT probe order: (right_pos, left_bucket_start, run_len);
3929    // usize::MAX = unmatched right row (one null-left output row).
3930    const UNMATCHED: usize = usize::MAX;
3931    let mut plan = Vec::<(usize, usize, usize)>::with_capacity(right_keys.len());
3932    let mut output_len = 0usize;
3933    for (right_pos, &key) in right_keys.iter().enumerate() {
3934        let offset = i128::from(key) - i128::from(min_key);
3935        let run = if offset >= 0 && offset < span as i128 {
3936            let bucket = offset as usize;
3937            let start = offsets[bucket];
3938            let len = offsets[bucket + 1] - start;
3939            if len == 0 {
3940                (right_pos, UNMATCHED, 1)
3941            } else {
3942                (right_pos, start, len)
3943            }
3944        } else {
3945            (right_pos, UNMATCHED, 1)
3946        };
3947        let Some(new_len) = output_len.checked_add(run.2) else {
3948            return Ok(None);
3949        };
3950        output_len = new_len;
3951        plan.push(run);
3952    }
3953
3954    // One shared validity mask for every left lane.
3955    // Shared left-lane segment descriptor (br-frankenpandas-yiqv5): mirror of
3956    // the left builder — every null-introduced LEFT lane is a LAZY
3957    // `LazyNullableRepeatedSlicesInt64` over its bucket-order tape (plan's
3958    // `(bucket_start, run_len)`, `usize::MAX` ⇒ null run) instead of a
3959    // materialized O(output_len) buffer; validity rebuilt in the ctor.
3960    let left_segments: Arc<[(usize, usize)]> = plan
3961        .iter()
3962        .map(|&(_, start, run_len)| (start, run_len))
3963        .collect();
3964
3965    // Right lanes (all-valid) as lazy repeat runs when the fanout pays.
3966    let use_repeat_runs = output_len >= plan.len().saturating_mul(2);
3967
3968    // Only LOW-FANOUT RIGHT lanes still materialize; left lanes are always lazy
3969    // (nullable repeated-slices) and high-fanout right lanes are lazy repeat runs.
3970    let full_specs: Vec<usize> = specs
3971        .iter()
3972        .enumerate()
3973        .filter(|(_, spec)| matches!(spec.side, FusedInt64Side::Right) && !use_repeat_runs)
3974        .map(|(idx, _)| idx)
3975        .collect();
3976
3977    let mut full_data: Vec<Vec<i64>> = Vec::new();
3978    let thread_count = join_parallel_thread_count();
3979    if !full_specs.is_empty() {
3980        // LEFT value tapes in bucket order, shared read-only.
3981        let tapes: Vec<Option<Vec<i64>>> = full_specs
3982            .iter()
3983            .map(|&spec_idx| match specs[spec_idx].side {
3984                FusedInt64Side::Right => None,
3985                FusedInt64Side::Left => Some(
3986                    positions
3987                        .iter()
3988                        .map(|&left_pos| specs[spec_idx].values[left_pos])
3989                        .collect(),
3990                ),
3991            })
3992            .collect();
3993
3994        if output_len >= DENSE_I64_INNER_PARALLEL_MIN_VALUES && thread_count > 1 {
3995            let target = output_len.div_ceil(thread_count).max(1);
3996            let mut boundaries = vec![(0usize, 0usize)];
3997            let mut cumulative = 0usize;
3998            let mut next_target = target;
3999            for (plan_idx, &(_, _, run_len)) in plan.iter().enumerate() {
4000                cumulative += run_len;
4001                if cumulative >= next_target && plan_idx + 1 < plan.len() {
4002                    boundaries.push((plan_idx + 1, cumulative));
4003                    next_target = cumulative.saturating_add(target);
4004                }
4005            }
4006            boundaries.push((plan.len(), output_len));
4007            let chunk_count = boundaries.len() - 1;
4008
4009            let mut column_bufs: Vec<Vec<i64>> =
4010                full_specs.iter().map(|_| vec![0i64; output_len]).collect();
4011            let mut bundles: Vec<Vec<&mut [i64]>> = (0..chunk_count)
4012                .map(|_| Vec::with_capacity(full_specs.len()))
4013                .collect();
4014            for buf in &mut column_bufs {
4015                let mut rest: &mut [i64] = buf.as_mut_slice();
4016                let mut prev = 0usize;
4017                for (chunk_idx, window) in boundaries.windows(2).enumerate() {
4018                    let (chunk_slice, tail) = rest.split_at_mut(window[1].1 - prev);
4019                    prev = window[1].1;
4020                    rest = tail;
4021                    bundles[chunk_idx].push(chunk_slice);
4022                }
4023            }
4024
4025            let plan = &plan;
4026            let specs_ref = &specs;
4027            let full_specs_ref = &full_specs;
4028            std::thread::scope(|scope| {
4029                let mut handles = Vec::with_capacity(chunk_count);
4030                for (chunk_idx, mut bundle) in bundles.into_iter().enumerate() {
4031                    let (plan_start, out_start) = boundaries[chunk_idx];
4032                    let (plan_end, out_end) = boundaries[chunk_idx + 1];
4033                    let tapes = &tapes;
4034                    handles.push(scope.spawn(move || {
4035                        let mut cursor = 0usize;
4036                        for &(right_pos, start, run_len) in &plan[plan_start..plan_end] {
4037                            for (slice, (&spec_idx, tape)) in bundle
4038                                .iter_mut()
4039                                .zip(full_specs_ref.iter().zip(tapes.iter()))
4040                            {
4041                                match specs_ref[spec_idx].side {
4042                                    FusedInt64Side::Right => {
4043                                        slice[cursor..cursor + run_len]
4044                                            .fill(specs_ref[spec_idx].values[right_pos]);
4045                                    }
4046                                    FusedInt64Side::Left => {
4047                                        if start != UNMATCHED {
4048                                            slice[cursor..cursor + run_len].copy_from_slice(
4049                                                &tape
4050                                                    .as_ref()
4051                                                    .expect("left spec must have a bucket tape")
4052                                                    [start..start + run_len],
4053                                            );
4054                                        }
4055                                    }
4056                                }
4057                            }
4058                            cursor += run_len;
4059                        }
4060                        debug_assert_eq!(cursor, out_end - out_start);
4061                    }));
4062                }
4063                for handle in handles {
4064                    handle
4065                        .join()
4066                        .expect("dense i64 right output worker must not panic");
4067                }
4068            });
4069            full_data = column_bufs;
4070        } else {
4071            full_data = full_specs.iter().map(|_| vec![0i64; output_len]).collect();
4072            let mut cursor = 0usize;
4073            for &(right_pos, start, run_len) in &plan {
4074                for (buf, (&spec_idx, tape)) in full_data
4075                    .iter_mut()
4076                    .zip(full_specs.iter().zip(tapes.iter()))
4077                {
4078                    match specs[spec_idx].side {
4079                        FusedInt64Side::Right => {
4080                            buf[cursor..cursor + run_len].fill(specs[spec_idx].values[right_pos]);
4081                        }
4082                        FusedInt64Side::Left => {
4083                            if start != UNMATCHED {
4084                                buf[cursor..cursor + run_len].copy_from_slice(
4085                                    &tape.as_ref().expect("left spec must have a bucket tape")
4086                                        [start..start + run_len],
4087                                );
4088                            }
4089                        }
4090                    }
4091                }
4092                cursor += run_len;
4093            }
4094            debug_assert_eq!(cursor, output_len);
4095        }
4096    }
4097
4098    // Lazy unit-range output index (see build_single_key_dense_i64 site).
4099    let index = Index::new_known_unique_int64_unit_range(0, output_len);
4100    let mut columns = std::collections::BTreeMap::new();
4101    let mut column_order = Vec::with_capacity(specs.len());
4102    let mut full_iter = full_data.into_iter();
4103    for spec in specs {
4104        let column = match spec.side {
4105            FusedInt64Side::Left => {
4106                // Lazy nullable repeated-slices over the left bucket-order tape
4107                // (br-frankenpandas-yiqv5). When no left row is missing the
4108                // segments carry no `usize::MAX` sentinel, so the ctor yields an
4109                // all-valid mask — identical to the prior `from_i64_values`.
4110                let tape: Vec<i64> = positions
4111                    .iter()
4112                    .map(|&left_pos| spec.values[left_pos])
4113                    .collect();
4114                Column::from_i64_nullable_repeated_slices_shared(
4115                    tape,
4116                    Arc::clone(&left_segments),
4117                    output_len,
4118                )
4119            }
4120            FusedInt64Side::Right if use_repeat_runs => Column::from_i64_repeat_runs(
4121                plan.iter()
4122                    .map(|&(right_pos, _, run_len)| (spec.values[right_pos], run_len))
4123                    .collect(),
4124            ),
4125            FusedInt64Side::Right => {
4126                let data = full_iter
4127                    .next()
4128                    .expect("full lane buffer must exist for every non-run right spec");
4129                Column::from_i64_values(data)
4130            }
4131        };
4132        debug_assert_eq!(column.len(), output_len);
4133        insert_merged_output_column(&mut columns, &mut column_order, spec.name, column)?;
4134    }
4135
4136    Ok(Some(MergedDataFrame {
4137        index,
4138        columns,
4139        column_order,
4140    }))
4141}
4142
4143fn dense_cycle_domain(witness: Int64DenseCycleWitness) -> Option<(i64, i64)> {
4144    let last_offset = i64::try_from(witness.period.checked_sub(1)?).ok()?;
4145    Some((witness.start, witness.start.checked_add(last_offset)?))
4146}
4147
4148fn dense_cycle_probe_output_len_and_validity(
4149    probe_witness: Int64DenseCycleWitness,
4150    build_witness: Int64DenseCycleWitness,
4151) -> Option<(usize, ValidityMask)> {
4152    let mut output_len = 0usize;
4153    let mut invalid_ranges = Vec::<(usize, usize)>::new();
4154    for probe_pos in 0..probe_witness.len {
4155        let offset = i64::try_from(probe_pos % probe_witness.period).ok()?;
4156        let key = probe_witness.start.checked_add(offset)?;
4157        let run_len = build_witness
4158            .offset_count_for_key(key)
4159            .map_or(1, |(_, count)| count);
4160        if build_witness.offset_count_for_key(key).is_none() {
4161            push_dense_outer_invalid_range(&mut invalid_ranges, output_len, 1);
4162        }
4163        output_len = output_len.checked_add(run_len)?;
4164    }
4165    Some((
4166        output_len,
4167        ValidityMask::from_invalid_ranges(Arc::from(invalid_ranges), output_len),
4168    ))
4169}
4170
4171struct DenseOuterRunTape {
4172    run_lens: Option<Arc<[usize]>>,
4173    left_run_valid: Option<Arc<[bool]>>,
4174    left_run_positions: Option<Arc<[usize]>>,
4175    right_positions_csr: Option<Arc<[usize]>>,
4176    right_segments: Option<Arc<[(usize, usize)]>>,
4177    key_runs: Vec<(i64, usize)>,
4178    left_sparse_validity: ValidityMask,
4179    right_sparse_validity: ValidityMask,
4180    output_len: usize,
4181    has_left_missing: bool,
4182    has_right_missing: bool,
4183}
4184
4185fn push_dense_outer_invalid_range(ranges: &mut Vec<(usize, usize)>, start: usize, len: usize) {
4186    if len == 0 {
4187        return;
4188    }
4189    if let Some((last_start, last_len)) = ranges.last_mut()
4190        && last_start.checked_add(*last_len) == Some(start)
4191    {
4192        *last_len += len;
4193        return;
4194    }
4195    ranges.push((start, len));
4196}
4197
4198fn append_dense_cycle_positions(
4199    positions: &mut Vec<usize>,
4200    witness: Int64DenseCycleWitness,
4201    key: i64,
4202) -> Option<usize> {
4203    let (mut pos, count) = witness.offset_count_for_key(key)?;
4204    for _ in 0..count {
4205        positions.push(pos);
4206        pos = pos.checked_add(witness.period)?;
4207    }
4208    Some(count)
4209}
4210
4211fn build_dense_cycle_outer_run_tape(
4212    left_witness: Int64DenseCycleWitness,
4213    right_witness: Int64DenseCycleWitness,
4214    min_key: i64,
4215    span: usize,
4216) -> Option<DenseOuterRunTape> {
4217    let mut run_count = 0usize;
4218    let mut active_key_count = 0usize;
4219    let mut output_len = 0usize;
4220    let mut has_left_missing = false;
4221    let mut has_right_missing = false;
4222    for bucket in 0..span {
4223        let key = min_key.checked_add(i64::try_from(bucket).ok()?)?;
4224        let ll = left_witness
4225            .offset_count_for_key(key)
4226            .map_or(0, |(_, count)| count);
4227        let rl = right_witness
4228            .offset_count_for_key(key)
4229            .map_or(0, |(_, count)| count);
4230        let rows = match (ll > 0, rl > 0) {
4231            (true, true) => {
4232                run_count = run_count.checked_add(ll)?;
4233                ll.checked_mul(rl)?
4234            }
4235            (true, false) => {
4236                has_right_missing = true;
4237                run_count = run_count.checked_add(ll)?;
4238                ll
4239            }
4240            (false, true) => {
4241                has_left_missing = true;
4242                run_count = run_count.checked_add(1)?;
4243                rl
4244            }
4245            (false, false) => continue,
4246        };
4247        active_key_count = active_key_count.checked_add(1)?;
4248        output_len = output_len.checked_add(rows)?;
4249    }
4250
4251    let build_left_tape = !has_left_missing;
4252    let mut run_lens = Vec::with_capacity(if build_left_tape { run_count } else { 0 });
4253    let mut left_run_valid = Vec::with_capacity(if build_left_tape { run_count } else { 0 });
4254    let mut left_run_positions = Vec::with_capacity(if build_left_tape { run_count } else { 0 });
4255    let mut right_positions_csr = Vec::with_capacity(right_witness.len);
4256    let mut right_segments = Vec::with_capacity(run_count);
4257    let mut key_runs = Vec::with_capacity(active_key_count);
4258    let mut left_invalid_ranges = Vec::<(usize, usize)>::new();
4259    let mut right_invalid_ranges = Vec::<(usize, usize)>::new();
4260    let mut out_pos = 0usize;
4261    let build_right_tape = !has_right_missing;
4262    for bucket in 0..span {
4263        let key = min_key.checked_add(i64::try_from(bucket).ok()?)?;
4264        let left_span = left_witness.offset_count_for_key(key);
4265        let right_span = right_witness.offset_count_for_key(key);
4266        let ll = left_span.map_or(0, |(_, count)| count);
4267        let rl = right_span.map_or(0, |(_, count)| count);
4268        if ll == 0 && rl == 0 {
4269            continue;
4270        }
4271
4272        let right_start = if rl > 0 {
4273            if build_right_tape {
4274                let start = right_positions_csr.len();
4275                let appended =
4276                    append_dense_cycle_positions(&mut right_positions_csr, right_witness, key)?;
4277                debug_assert_eq!(appended, rl);
4278                start
4279            } else {
4280                0
4281            }
4282        } else {
4283            usize::MAX
4284        };
4285
4286        let rows = match (left_span, right_span) {
4287            (Some((mut left_pos, left_count)), Some((_, right_count))) => {
4288                let rows = left_count.checked_mul(right_count)?;
4289                if build_left_tape {
4290                    run_lens.extend(std::iter::repeat_n(right_count, left_count));
4291                    left_run_valid.extend(std::iter::repeat_n(true, left_count));
4292                }
4293                if build_right_tape {
4294                    right_segments
4295                        .extend(std::iter::repeat_n((right_start, right_count), left_count));
4296                }
4297                if build_left_tape {
4298                    for _ in 0..left_count {
4299                        left_run_positions.push(left_pos);
4300                        left_pos = left_pos.checked_add(left_witness.period)?;
4301                    }
4302                }
4303                rows
4304            }
4305            (Some((mut left_pos, left_count)), None) => {
4306                push_dense_outer_invalid_range(&mut right_invalid_ranges, out_pos, left_count);
4307                if build_left_tape {
4308                    run_lens.extend(std::iter::repeat_n(1, left_count));
4309                    left_run_valid.extend(std::iter::repeat_n(true, left_count));
4310                }
4311                if build_right_tape {
4312                    right_segments.extend(std::iter::repeat_n((usize::MAX, 1), left_count));
4313                }
4314                if build_left_tape {
4315                    for _ in 0..left_count {
4316                        left_run_positions.push(left_pos);
4317                        left_pos = left_pos.checked_add(left_witness.period)?;
4318                    }
4319                }
4320                left_count
4321            }
4322            (None, Some((_, right_count))) => {
4323                push_dense_outer_invalid_range(&mut left_invalid_ranges, out_pos, right_count);
4324                if build_left_tape {
4325                    run_lens.push(right_count);
4326                    left_run_valid.push(false);
4327                    left_run_positions.push(0);
4328                }
4329                if build_right_tape {
4330                    right_segments.push((right_start, right_count));
4331                }
4332                right_count
4333            }
4334            (None, None) => unreachable!("empty buckets are skipped above"),
4335        };
4336        key_runs.push((key, rows));
4337        out_pos = out_pos.checked_add(rows)?;
4338    }
4339    if out_pos != output_len
4340        || (build_left_tape
4341            && (run_lens.len() != run_count
4342                || left_run_valid.len() != run_count
4343                || left_run_positions.len() != run_count))
4344        || (!build_left_tape
4345            && (!run_lens.is_empty()
4346                || !left_run_valid.is_empty()
4347                || !left_run_positions.is_empty()))
4348        || (build_right_tape
4349            && (right_segments.len() != run_count
4350                || right_positions_csr.len() != right_witness.len))
4351        || (!build_right_tape && (!right_segments.is_empty() || !right_positions_csr.is_empty()))
4352    {
4353        return None;
4354    }
4355
4356    Some(DenseOuterRunTape {
4357        run_lens: build_left_tape.then(|| Arc::from(run_lens)),
4358        left_run_valid: build_left_tape.then(|| Arc::from(left_run_valid)),
4359        left_run_positions: build_left_tape.then(|| Arc::from(left_run_positions)),
4360        right_positions_csr: build_right_tape.then(|| Arc::from(right_positions_csr)),
4361        right_segments: build_right_tape.then(|| Arc::from(right_segments)),
4362        key_runs,
4363        left_sparse_validity: ValidityMask::from_invalid_ranges(
4364            Arc::from(left_invalid_ranges),
4365            output_len,
4366        ),
4367        right_sparse_validity: ValidityMask::from_invalid_ranges(
4368            Arc::from(right_invalid_ranges),
4369            output_len,
4370        ),
4371        output_len,
4372        has_left_missing,
4373        has_right_missing,
4374    })
4375}
4376
4377/// Fused dense-i64 OUTER merge builder (br-frankenpandas-343ho).
4378///
4379/// `dense_int64_outer_positions` + the position-vector outer builder cost:
4380/// per-bucket `Vec<Vec<usize>>` heap allocs, two `Vec<Option<usize>>` of
4381/// output length, a per-row Scalar coalesce for the shared key column, and
4382/// per-column reindex walks. Here the bucket walk (ascending key order —
4383/// the dense outer output IS bucket order) emits a compact plan
4384/// (`(left_pos | MAX, right_bucket_start | MAX, run_len)`), and:
4385///
4386/// - the SHARED KEY lane is synthesized as `(min_key + bucket, bucket_rows)`
4387///   repeat runs — every row in a bucket has the bucket's key, whichever
4388///   side it came from, so the coalesce is a closed form (all-valid Int64);
4389/// - left lanes promote to nullable Float64 ONLY when right-only buckets
4390///   exist, right lanes ONLY when left-only rows exist — matching
4391///   `reindex_outer_join_column`'s per-positions `has_missing` check (a
4392///   side with no missing rows keeps dtype Int64 via the all-present
4393///   take_positions path);
4394/// - per-side shared validity masks are word-filled once from the plan and
4395///   cloned per lane;
4396/// - lanes fill via the 6bsw3 row-chunked disjoint `split_at_mut` scheme
4397///   (an i64 group and an f64 group, sharing plan/boundaries), with muis1
4398///   right value tapes (i64, plus a once-cast f64 tape for promoted lanes).
4399///
4400/// Bit-identical: bucket walk order == `dense_int64_outer_positions`
4401/// (cross products left-major, then left-only rows, then right-only rows,
4402/// per ascending bucket); promoted slots use `v as f64` + the 0.0-datum
4403/// gap (`Null(NaN)`), preserved slots `Null(NullKind::Null)` — the exact
4404/// eager semantics per br-frankenpandas-1bvcl/lt5qx.
4405fn build_single_key_dense_i64_outer_merge_output(
4406    left: &fp_frame::DataFrame,
4407    right: &fp_frame::DataFrame,
4408    left_on: &[&str],
4409    right_on: &[&str],
4410    left_key: &Column,
4411    right_key: &Column,
4412    suffixes: &ResolvedMergeSuffixes,
4413) -> Result<Option<MergedDataFrame>, JoinError> {
4414    debug_assert_eq!(left_on.len(), 1);
4415    debug_assert_eq!(right_on.len(), 1);
4416
4417    // The closed-form key lane needs the coalesced shared-key shape; the
4418    // non-shared-name variant keeps the position-vector path.
4419    if left_on[0] != right_on[0] {
4420        return Ok(None);
4421    }
4422    let Some(left_keys) = left_key.as_i64_slice() else {
4423        return Ok(None);
4424    };
4425    let Some(right_keys) = right_key.as_i64_slice() else {
4426        return Ok(None);
4427    };
4428    if left_keys.is_empty() || right_keys.is_empty() {
4429        return Ok(None);
4430    }
4431
4432    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
4433    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
4434    let key_name = left_on[0];
4435    let shared_key_names = [key_name].into_iter().collect::<HashSet<&str>>();
4436    let overlapping_names =
4437        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
4438
4439    // Lane specs in output order: left columns (the key slot handled as the
4440    // synthetic coalesced lane), then right non-key columns.
4441    enum OuterLaneKind {
4442        SharedKey,
4443        Lane(FusedInt64Side),
4444    }
4445    let mut spec_names = Vec::<String>::new();
4446    let mut spec_kinds = Vec::<OuterLaneKind>::new();
4447    let mut spec_values = Vec::<&[i64]>::new();
4448    let mut spec_sources = Vec::<Arc<[i64]>>::new();
4449    for name in left.column_names() {
4450        let col = left
4451            .columns()
4452            .get(name)
4453            .expect("left column listed in column_names must exist");
4454        let Some(values) = col.as_i64_slice() else {
4455            return Ok(None);
4456        };
4457        let source = col.as_i64_arc().unwrap_or_else(|| Arc::from(values));
4458        if name.as_str() == key_name {
4459            spec_names.push(name.clone());
4460            spec_kinds.push(OuterLaneKind::SharedKey);
4461            spec_values.push(values);
4462            spec_sources.push(Arc::clone(&source));
4463            continue;
4464        }
4465        let out_name = if right_col_names.contains(name) {
4466            apply_merge_suffix(name, suffixes.left.as_deref())
4467        } else {
4468            name.clone()
4469        };
4470        spec_names.push(out_name);
4471        spec_kinds.push(OuterLaneKind::Lane(FusedInt64Side::Left));
4472        spec_values.push(values);
4473        spec_sources.push(source);
4474    }
4475    for name in right.column_names() {
4476        let col = right
4477            .columns()
4478            .get(name)
4479            .expect("right column listed in column_names must exist");
4480        let Some(values) = col.as_i64_slice() else {
4481            return Ok(None);
4482        };
4483        let source = col.as_i64_arc().unwrap_or_else(|| Arc::from(values));
4484        if name.as_str() == key_name {
4485            continue;
4486        }
4487        let out_name = if left_col_names.contains(name) {
4488            apply_merge_suffix(name, suffixes.right.as_deref())
4489        } else {
4490            name.clone()
4491        };
4492        spec_names.push(out_name);
4493        spec_kinds.push(OuterLaneKind::Lane(FusedInt64Side::Right));
4494        spec_values.push(values);
4495        spec_sources.push(source);
4496    }
4497    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
4498
4499    // Dense span over BOTH key sets (same gate as dense_int64_outer_positions
4500    // so fused/fallback routing matches).
4501    let left_witness = left_key
4502        .int64_dense_cycle_witness()
4503        .filter(|witness| witness.len == left_keys.len());
4504    let right_witness = right_key
4505        .int64_dense_cycle_witness()
4506        .filter(|witness| witness.len == right_keys.len());
4507    let (min_key, max_key) = match (
4508        left_witness.and_then(dense_cycle_domain),
4509        right_witness.and_then(dense_cycle_domain),
4510    ) {
4511        (Some((left_min, left_max)), Some((right_min, right_max))) => {
4512            (left_min.min(right_min), left_max.max(right_max))
4513        }
4514        _ => {
4515            let mut min_key = left_keys[0];
4516            let mut max_key = left_keys[0];
4517            for &key in left_keys.iter().chain(right_keys.iter()) {
4518                min_key = min_key.min(key);
4519                max_key = max_key.max(key);
4520            }
4521            (min_key, max_key)
4522        }
4523    };
4524    let span = (i128::from(max_key)) - (i128::from(min_key)) + 1;
4525    let row_count = left_keys.len().saturating_add(right_keys.len());
4526    let max_dense_span = row_count.saturating_mul(4).max(1024);
4527    if span > max_dense_span as i128 {
4528        return Ok(None);
4529    }
4530    let span = usize::try_from(span).expect("span bounded by max_dense_span");
4531
4532    const NONE_POS: usize = usize::MAX;
4533    let Some(DenseOuterRunTape {
4534        run_lens,
4535        left_run_valid,
4536        left_run_positions,
4537        right_positions_csr,
4538        right_segments,
4539        key_runs,
4540        left_sparse_validity,
4541        right_sparse_validity,
4542        output_len,
4543        has_left_missing,
4544        has_right_missing,
4545    }) = (match (left_witness, right_witness) {
4546        (Some(left_witness), Some(right_witness)) => {
4547            build_dense_cycle_outer_run_tape(left_witness, right_witness, min_key, span)
4548        }
4549        _ => None,
4550    })
4551    .or_else(|| {
4552        // CSR layouts for both sides (replaces the per-bucket Vec<Vec<usize>>).
4553        let build_dense_cycle_csr =
4554            |witness: Int64DenseCycleWitness| -> Option<(Vec<usize>, Vec<usize>)> {
4555                let mut offsets = Vec::with_capacity(span + 1);
4556                offsets.push(0);
4557                let mut total = 0usize;
4558                for bucket in 0..span {
4559                    let key = min_key.checked_add(i64::try_from(bucket).ok()?)?;
4560                    let count = witness
4561                        .offset_count_for_key(key)
4562                        .map_or(0, |(_, count)| count);
4563                    total = total.checked_add(count)?;
4564                    offsets.push(total);
4565                }
4566                if total != witness.len {
4567                    return None;
4568                }
4569                let mut positions = Vec::with_capacity(witness.len);
4570                for bucket in 0..span {
4571                    let key = min_key.checked_add(i64::try_from(bucket).ok()?)?;
4572                    let appended =
4573                        append_dense_cycle_positions(&mut positions, witness, key).unwrap_or(0);
4574                    debug_assert_eq!(
4575                        appended,
4576                        witness
4577                            .offset_count_for_key(key)
4578                            .map_or(0, |(_, count)| count)
4579                    );
4580                }
4581                (positions.len() == witness.len).then_some((offsets, positions))
4582            };
4583        let build_csr = |keys: &[i64], witness: Option<Int64DenseCycleWitness>| {
4584            if let Some(csr) = witness
4585                .filter(|witness| witness.len == keys.len())
4586                .and_then(&build_dense_cycle_csr)
4587            {
4588                return csr;
4589            }
4590            let mut offsets = vec![0usize; span + 1];
4591            for &key in keys {
4592                offsets[(key - min_key) as usize + 1] += 1;
4593            }
4594            for i in 0..span {
4595                offsets[i + 1] += offsets[i];
4596            }
4597            let mut positions = vec![0usize; keys.len()];
4598            let mut cursor = offsets[..span].to_vec();
4599            for (pos, &key) in keys.iter().enumerate() {
4600                let bucket = (key - min_key) as usize;
4601                positions[cursor[bucket]] = pos;
4602                cursor[bucket] += 1;
4603            }
4604            (offsets, positions)
4605        };
4606        let (left_offsets, left_positions_csr) = build_csr(left_keys, left_witness);
4607        let (right_offsets, right_positions_csr) = build_csr(right_keys, right_witness);
4608
4609        // Bucket walk -> compact plan + closed-form key runs + output length.
4610        let mut plan = Vec::<(usize, usize, usize)>::new();
4611        let mut key_runs = Vec::<(i64, usize)>::new();
4612        let mut left_invalid_ranges = Vec::<(usize, usize)>::new();
4613        let mut right_invalid_ranges = Vec::<(usize, usize)>::new();
4614        let mut output_len = 0usize;
4615        let mut has_left_missing = false; // right-only buckets exist
4616        let mut has_right_missing = false; // left-only rows exist
4617        for bucket in 0..span {
4618            let ll = left_offsets[bucket + 1] - left_offsets[bucket];
4619            let rl = right_offsets[bucket + 1] - right_offsets[bucket];
4620            let bucket_rows = match (ll > 0, rl > 0) {
4621                (true, true) => {
4622                    let rows = ll.checked_mul(rl)?;
4623                    let rs = right_offsets[bucket];
4624                    for &lp in &left_positions_csr[left_offsets[bucket]..left_offsets[bucket + 1]] {
4625                        plan.push((lp, rs, rl));
4626                    }
4627                    rows
4628                }
4629                (true, false) => {
4630                    has_right_missing = true;
4631                    push_dense_outer_invalid_range(&mut right_invalid_ranges, output_len, ll);
4632                    for &lp in &left_positions_csr[left_offsets[bucket]..left_offsets[bucket + 1]] {
4633                        plan.push((lp, NONE_POS, 1));
4634                    }
4635                    ll
4636                }
4637                (false, true) => {
4638                    has_left_missing = true;
4639                    push_dense_outer_invalid_range(&mut left_invalid_ranges, output_len, rl);
4640                    plan.push((NONE_POS, right_offsets[bucket], rl));
4641                    rl
4642                }
4643                (false, false) => continue,
4644            };
4645            output_len = output_len.checked_add(bucket_rows)?;
4646            key_runs.push((min_key + bucket as i64, bucket_rows));
4647        }
4648
4649        // Shared lazy-lane descriptors (br-frankenpandas-yiqv5): the plan drives
4650        // every value lane as a LAZY column rather than an O(output_len)
4651        // materialized buffer. The kept side stays all-valid; the promoted
4652        // side becomes the matching nullable lazy lane.
4653        let run_lens: Arc<[usize]> = plan.iter().map(|&(_, _, run_len)| run_len).collect();
4654        let left_run_valid: Arc<[bool]> = plan.iter().map(|&(lp, _, _)| lp < NONE_POS).collect();
4655        let left_run_positions: Arc<[usize]> = plan
4656            .iter()
4657            .map(|&(lp, _, _)| if lp == NONE_POS { 0 } else { lp })
4658            .collect();
4659        let right_segments: Arc<[(usize, usize)]> =
4660            plan.iter().map(|&(_, rs, run_len)| (rs, run_len)).collect();
4661        Some(DenseOuterRunTape {
4662            run_lens: Some(run_lens),
4663            left_run_valid: Some(left_run_valid),
4664            left_run_positions: Some(left_run_positions),
4665            right_positions_csr: Some(Arc::from(right_positions_csr)),
4666            right_segments: Some(right_segments),
4667            key_runs,
4668            left_sparse_validity: ValidityMask::from_invalid_ranges(
4669                Arc::from(left_invalid_ranges),
4670                output_len,
4671            ),
4672            right_sparse_validity: ValidityMask::from_invalid_ranges(
4673                Arc::from(right_invalid_ranges),
4674                output_len,
4675            ),
4676            output_len,
4677            has_left_missing,
4678            has_right_missing,
4679        })
4680    })
4681    else {
4682        return Ok(None);
4683    };
4684
4685    // Promoted (nullable Float64) when that side has missing rows, preserved
4686    // (all-valid Int64) otherwise.
4687    let promoted = |side: FusedInt64Side| match side {
4688        FusedInt64Side::Left => has_left_missing,
4689        FusedInt64Side::Right => has_right_missing,
4690    };
4691
4692    // Left broadcast run values (one per run): i64 (preserved) or f64 (promoted).
4693    let left_run_values_i64 = |idx: usize| -> Option<Vec<i64>> {
4694        Some(
4695            left_run_positions
4696                .as_ref()?
4697                .iter()
4698                .zip(left_run_valid.as_ref()?.iter())
4699                .map(|(&lp, &valid)| if valid { spec_values[idx][lp] } else { 0 })
4700                .collect(),
4701        )
4702    };
4703    // Assemble columns in spec order, each a lazy lane.
4704    let index = Index::new_known_unique_int64_unit_range(0, output_len);
4705    let mut columns = std::collections::BTreeMap::new();
4706    let mut column_order = Vec::with_capacity(spec_names.len());
4707    for (idx, (name, kind)) in spec_names.into_iter().zip(spec_kinds.iter()).enumerate() {
4708        let column = match kind {
4709            OuterLaneKind::SharedKey => {
4710                // Closed-form coalesced key: all-valid, bucket key repeated in
4711                // ascending bucket order. Lazy repeat-runs when the fanout pays.
4712                if output_len >= key_runs.len().saturating_mul(2) {
4713                    Column::from_i64_repeat_runs(key_runs.clone())
4714                } else {
4715                    let mut data = Vec::with_capacity(output_len);
4716                    for &(key, run_len) in &key_runs {
4717                        data.resize(data.len() + run_len, key);
4718                    }
4719                    Column::from_i64_values(data)
4720                }
4721            }
4722            OuterLaneKind::Lane(side) => match (side, promoted(*side)) {
4723                (FusedInt64Side::Left, false) => {
4724                    let Some(run_lens) = run_lens.as_ref() else {
4725                        return Ok(None);
4726                    };
4727                    let Some(run_values) = left_run_values_i64(idx) else {
4728                        return Ok(None);
4729                    };
4730                    Column::from_i64_repeat_values_run_lengths(run_values, Arc::clone(run_lens))
4731                }
4732                (FusedInt64Side::Left, true) => {
4733                    if left_run_positions.is_none()
4734                        && let (Some(left_witness), Some(right_witness)) =
4735                            (left_witness, right_witness)
4736                    {
4737                        Column::from_i64_nullable_dense_cycle_left_as_f64_with_sparse_validity(
4738                            Arc::clone(&spec_sources[idx]),
4739                            left_witness,
4740                            right_witness,
4741                            min_key,
4742                            span,
4743                            left_sparse_validity.clone(),
4744                            output_len,
4745                        )
4746                    } else {
4747                        let Some(run_lens) = run_lens.as_ref() else {
4748                            return Ok(None);
4749                        };
4750                        let Some(left_run_positions) = left_run_positions.as_ref() else {
4751                            return Ok(None);
4752                        };
4753                        let Some(left_run_valid) = left_run_valid.as_ref() else {
4754                            return Ok(None);
4755                        };
4756                        Column::from_i64_nullable_repeat_positions_as_f64_with_sparse_validity(
4757                            Arc::clone(&spec_sources[idx]),
4758                            Arc::clone(left_run_positions),
4759                            Arc::clone(left_run_valid),
4760                            Arc::clone(run_lens),
4761                            left_sparse_validity.clone(),
4762                            output_len,
4763                        )
4764                    }
4765                }
4766                (FusedInt64Side::Right, false) => {
4767                    let Some(right_positions_csr) = right_positions_csr.as_ref() else {
4768                        return Ok(None);
4769                    };
4770                    let Some(right_segments) = right_segments.as_ref() else {
4771                        return Ok(None);
4772                    };
4773                    let tape_i64 = right_positions_csr
4774                        .iter()
4775                        .map(|&pos| spec_values[idx][pos])
4776                        .collect();
4777                    Column::from_i64_repeated_slices_shared(
4778                        tape_i64,
4779                        Arc::clone(right_segments),
4780                        output_len,
4781                    )
4782                }
4783                (FusedInt64Side::Right, true) => {
4784                    if right_positions_csr.is_none()
4785                        && let (Some(left_witness), Some(right_witness)) =
4786                            (left_witness, right_witness)
4787                    {
4788                        Column::from_i64_nullable_dense_cycle_right_as_f64_with_sparse_validity(
4789                            Arc::clone(&spec_sources[idx]),
4790                            left_witness,
4791                            right_witness,
4792                            min_key,
4793                            span,
4794                            right_sparse_validity.clone(),
4795                            output_len,
4796                        )
4797                    } else {
4798                        let Some(right_positions_csr) = right_positions_csr.as_ref() else {
4799                            return Ok(None);
4800                        };
4801                        let Some(right_segments) = right_segments.as_ref() else {
4802                            return Ok(None);
4803                        };
4804                        Column::from_i64_nullable_repeated_positions_as_f64_with_sparse_validity(
4805                            Arc::clone(&spec_sources[idx]),
4806                            Arc::clone(right_positions_csr),
4807                            Arc::clone(right_segments),
4808                            right_sparse_validity.clone(),
4809                            output_len,
4810                        )
4811                    }
4812                }
4813            },
4814        };
4815        debug_assert_eq!(column.len(), output_len);
4816        insert_merged_output_column(&mut columns, &mut column_order, name, column)?;
4817    }
4818
4819    Ok(Some(MergedDataFrame {
4820        index,
4821        columns,
4822        column_order,
4823    }))
4824}
4825
4826fn build_single_key_dense_i64_right_all_matched_merge_output(
4827    left: &fp_frame::DataFrame,
4828    right: &fp_frame::DataFrame,
4829    left_on: &[&str],
4830    right_on: &[&str],
4831    left_key: &Column,
4832    right_key: &Column,
4833    suffixes: &ResolvedMergeSuffixes,
4834) -> Result<Option<MergedDataFrame>, JoinError> {
4835    debug_assert_eq!(left_on.len(), 1);
4836    debug_assert_eq!(right_on.len(), 1);
4837
4838    let Some(left_keys) = left_key.as_i64_slice() else {
4839        return Ok(None);
4840    };
4841    let Some(right_keys) = right_key.as_i64_slice() else {
4842        return Ok(None);
4843    };
4844
4845    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
4846    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
4847    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
4848    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
4849    let shared_key_names = if left_on[0] == right_on[0] {
4850        [left_on[0]].into_iter().collect::<HashSet<&str>>()
4851    } else {
4852        HashSet::new()
4853    };
4854    let overlapping_names =
4855        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
4856
4857    let mut specs = Vec::<FusedInt64OutputColumn<'_>>::new();
4858    for name in left.column_names() {
4859        let col = left
4860            .columns()
4861            .get(name)
4862            .expect("left column listed in column_names must exist");
4863        let (values, side) = if left_key_name_set.contains(name.as_str())
4864            && shared_key_names.contains(name.as_str())
4865        {
4866            let right_key_col = right
4867                .columns()
4868                .get(right_on[0])
4869                .expect("right key column must exist");
4870            let Some(values) = right_key_col.as_i64_slice() else {
4871                return Ok(None);
4872            };
4873            (values, FusedInt64Side::Right)
4874        } else {
4875            let Some(values) = col.as_i64_slice() else {
4876                return Ok(None);
4877            };
4878            (values, FusedInt64Side::Left)
4879        };
4880        let out_name = if left_key_name_set.contains(name.as_str()) {
4881            name.clone()
4882        } else if right_col_names.contains(name) {
4883            apply_merge_suffix(name, suffixes.left.as_deref())
4884        } else {
4885            name.clone()
4886        };
4887        specs.push(FusedInt64OutputColumn {
4888            name: out_name,
4889            side,
4890            values,
4891        });
4892    }
4893
4894    for name in right.column_names() {
4895        let col = right
4896            .columns()
4897            .get(name)
4898            .expect("right column listed in column_names must exist");
4899        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
4900            continue;
4901        }
4902        let Some(values) = col.as_i64_slice() else {
4903            return Ok(None);
4904        };
4905        let out_name = if left_col_names.contains(name) {
4906            apply_merge_suffix(name, suffixes.right.as_deref())
4907        } else {
4908            name.clone()
4909        };
4910        specs.push(FusedInt64OutputColumn {
4911            name: out_name,
4912            side: FusedInt64Side::Right,
4913            values,
4914        });
4915    }
4916
4917    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
4918
4919    if right_keys.is_empty() {
4920        let mut columns = std::collections::BTreeMap::new();
4921        let mut column_order = Vec::with_capacity(specs.len());
4922        for spec in specs {
4923            insert_merged_output_column(
4924                &mut columns,
4925                &mut column_order,
4926                spec.name,
4927                Column::from_i64_values(Vec::new()),
4928            )?;
4929        }
4930        return Ok(Some(MergedDataFrame {
4931            index: Index::new(Vec::new()),
4932            columns,
4933            column_order,
4934        }));
4935    }
4936    if left_keys.is_empty() {
4937        return Ok(None);
4938    }
4939
4940    let mut min = left_keys[0];
4941    let mut max = left_keys[0];
4942    for &v in left_keys {
4943        if v < min {
4944            min = v;
4945        }
4946        if v > max {
4947            max = v;
4948        }
4949    }
4950    let span = (max as i128) - (min as i128) + 1;
4951    if span > (1i128 << 24) || span > 16 * (left_keys.len() as i128) {
4952        return Ok(None);
4953    }
4954    let range = span as usize;
4955
4956    let mut offsets = vec![0usize; range + 1];
4957    for &v in left_keys {
4958        offsets[(v - min) as usize + 1] += 1;
4959    }
4960    for i in 0..range {
4961        offsets[i + 1] += offsets[i];
4962    }
4963    let mut positions = vec![0usize; left_keys.len()];
4964    let mut cursor = offsets.clone();
4965    for (pos, &v) in left_keys.iter().enumerate() {
4966        let bucket = (v - min) as usize;
4967        positions[cursor[bucket]] = pos;
4968        cursor[bucket] += 1;
4969    }
4970
4971    let mut output_len = 0usize;
4972    for &v in right_keys {
4973        if v < min || v > max {
4974            return Ok(None);
4975        }
4976        let bucket = (v - min) as usize;
4977        let bucket_len = offsets[bucket + 1] - offsets[bucket];
4978        if bucket_len == 0 {
4979            return Ok(None);
4980        }
4981        let Some(new_output_len) = output_len.checked_add(bucket_len) else {
4982            return Ok(None);
4983        };
4984        output_len = new_output_len;
4985    }
4986
4987    let mut output_data = specs
4988        .iter()
4989        .map(|_| Vec::<i64>::with_capacity(output_len))
4990        .collect::<Vec<_>>();
4991    for (right_pos, &v) in right_keys.iter().enumerate() {
4992        let bucket = (v - min) as usize;
4993        for &left_pos in &positions[offsets[bucket]..offsets[bucket + 1]] {
4994            for (out, spec) in output_data.iter_mut().zip(specs.iter()) {
4995                match spec.side {
4996                    FusedInt64Side::Left => out.push(spec.values[left_pos]),
4997                    FusedInt64Side::Right => out.push(spec.values[right_pos]),
4998                }
4999            }
5000        }
5001    }
5002
5003    // Lazy unit-range output index: identical labels (0..output_len as
5004    // IndexLabel::Int64, materialized on demand), pre-proven unique and
5005    // ascending — skips the eager Vec<IndexLabel> build for huge join outputs.
5006    let index = Index::new_known_unique_int64_unit_range(0, output_len);
5007    let mut columns = std::collections::BTreeMap::new();
5008    let mut column_order = Vec::with_capacity(specs.len());
5009    for (spec, data) in specs.into_iter().zip(output_data) {
5010        debug_assert_eq!(data.len(), output_len);
5011        insert_merged_output_column(
5012            &mut columns,
5013            &mut column_order,
5014            spec.name,
5015            Column::from_i64_values(data),
5016        )?;
5017    }
5018
5019    Ok(Some(MergedDataFrame {
5020        index,
5021        columns,
5022        column_order,
5023    }))
5024}
5025
5026fn build_single_key_dense_i64_outer_all_matched_merge_output(
5027    left: &fp_frame::DataFrame,
5028    right: &fp_frame::DataFrame,
5029    left_on: &[&str],
5030    right_on: &[&str],
5031    left_key: &Column,
5032    right_key: &Column,
5033    suffixes: &ResolvedMergeSuffixes,
5034) -> Result<Option<MergedDataFrame>, JoinError> {
5035    debug_assert_eq!(left_on.len(), 1);
5036    debug_assert_eq!(right_on.len(), 1);
5037
5038    let Some(left_keys) = left_key.as_i64_slice() else {
5039        return Ok(None);
5040    };
5041    let Some(right_keys) = right_key.as_i64_slice() else {
5042        return Ok(None);
5043    };
5044
5045    if left_keys.is_empty() != right_keys.is_empty() {
5046        return Ok(None);
5047    }
5048    let dense_domain = if left_keys.is_empty() {
5049        None
5050    } else {
5051        let left_witness = left_key
5052            .int64_dense_cycle_witness()
5053            .filter(|witness| witness.len == left_keys.len());
5054        let right_witness = right_key
5055            .int64_dense_cycle_witness()
5056            .filter(|witness| witness.len == right_keys.len());
5057        match (
5058            left_witness.and_then(dense_cycle_domain),
5059            right_witness.and_then(dense_cycle_domain),
5060        ) {
5061            (Some(left_domain), Some(right_domain)) => {
5062                if left_domain != right_domain {
5063                    return Ok(None);
5064                }
5065                Some(left_domain)
5066            }
5067            _ => {
5068                let min_max = |keys: &[i64]| {
5069                    let mut min_key = keys[0];
5070                    let mut max_key = keys[0];
5071                    for &key in &keys[1..] {
5072                        min_key = min_key.min(key);
5073                        max_key = max_key.max(key);
5074                    }
5075                    (min_key, max_key)
5076                };
5077                let (left_min_key, left_max_key) = min_max(left_keys);
5078                let (right_min_key, right_max_key) = min_max(right_keys);
5079                if left_min_key != right_min_key || left_max_key != right_max_key {
5080                    return Ok(None);
5081                }
5082                Some((left_min_key, left_max_key))
5083            }
5084        }
5085    };
5086
5087    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
5088    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
5089    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
5090    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
5091    let shared_key_names = if left_on[0] == right_on[0] {
5092        [left_on[0]].into_iter().collect::<HashSet<&str>>()
5093    } else {
5094        HashSet::new()
5095    };
5096    let overlapping_names =
5097        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
5098
5099    let mut specs = Vec::<FusedInt64OutputColumn<'_>>::new();
5100    for name in left.column_names() {
5101        let col = left
5102            .columns()
5103            .get(name)
5104            .expect("left column listed in column_names must exist");
5105        let Some(values) = col.as_i64_slice() else {
5106            return Ok(None);
5107        };
5108        let out_name = if left_key_name_set.contains(name.as_str()) {
5109            name.clone()
5110        } else if right_col_names.contains(name) {
5111            apply_merge_suffix(name, suffixes.left.as_deref())
5112        } else {
5113            name.clone()
5114        };
5115        specs.push(FusedInt64OutputColumn {
5116            name: out_name,
5117            side: FusedInt64Side::Left,
5118            values,
5119        });
5120    }
5121
5122    for name in right.column_names() {
5123        let col = right
5124            .columns()
5125            .get(name)
5126            .expect("right column listed in column_names must exist");
5127        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
5128            continue;
5129        }
5130        let Some(values) = col.as_i64_slice() else {
5131            return Ok(None);
5132        };
5133        let out_name = if left_col_names.contains(name) {
5134            apply_merge_suffix(name, suffixes.right.as_deref())
5135        } else {
5136            name.clone()
5137        };
5138        specs.push(FusedInt64OutputColumn {
5139            name: out_name,
5140            side: FusedInt64Side::Right,
5141            values,
5142        });
5143    }
5144
5145    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
5146
5147    if left_keys.is_empty() || right_keys.is_empty() {
5148        if !left_keys.is_empty() || !right_keys.is_empty() {
5149            return Ok(None);
5150        }
5151        let mut columns = std::collections::BTreeMap::new();
5152        let mut column_order = Vec::with_capacity(specs.len());
5153        for spec in specs {
5154            insert_merged_output_column(
5155                &mut columns,
5156                &mut column_order,
5157                spec.name,
5158                Column::from_i64_values(Vec::new()),
5159            )?;
5160        }
5161        return Ok(Some(MergedDataFrame {
5162            index: Index::new(Vec::new()),
5163            columns,
5164            column_order,
5165        }));
5166    }
5167
5168    let (min_key, max_key) = dense_domain.expect("empty dense outer case returned above");
5169
5170    let span = i128::from(max_key)
5171        .checked_sub(i128::from(min_key))
5172        .and_then(|span| span.checked_add(1));
5173    let Some(span) = span else {
5174        return Ok(None);
5175    };
5176    let row_count = left_keys.len().saturating_add(right_keys.len());
5177    let max_dense_span = row_count.saturating_mul(4).max(1024);
5178    if span > max_dense_span as i128 {
5179        return Ok(None);
5180    }
5181    let Ok(span) = usize::try_from(span) else {
5182        return Ok(None);
5183    };
5184
5185    let mut left_buckets = (0..span).map(|_| Vec::<usize>::new()).collect::<Vec<_>>();
5186    let mut right_buckets = (0..span).map(|_| Vec::<usize>::new()).collect::<Vec<_>>();
5187    for (pos, &key) in left_keys.iter().enumerate() {
5188        let Ok(bucket) = usize::try_from(i128::from(key) - i128::from(min_key)) else {
5189            return Ok(None);
5190        };
5191        left_buckets[bucket].push(pos);
5192    }
5193    for (pos, &key) in right_keys.iter().enumerate() {
5194        let Ok(bucket) = usize::try_from(i128::from(key) - i128::from(min_key)) else {
5195            return Ok(None);
5196        };
5197        right_buckets[bucket].push(pos);
5198    }
5199
5200    let mut output_len = 0usize;
5201    for (left_bucket, right_bucket) in left_buckets.iter().zip(right_buckets.iter()) {
5202        match (left_bucket.is_empty(), right_bucket.is_empty()) {
5203            (false, false) => {
5204                let Some(bucket_rows) = left_bucket.len().checked_mul(right_bucket.len()) else {
5205                    return Ok(None);
5206                };
5207                let Some(new_output_len) = output_len.checked_add(bucket_rows) else {
5208                    return Ok(None);
5209                };
5210                output_len = new_output_len;
5211            }
5212            (false, true) | (true, false) => return Ok(None),
5213            (true, true) => {}
5214        }
5215    }
5216
5217    // Lazy unit-range output index: identical labels (0..output_len as
5218    // IndexLabel::Int64, materialized on demand), pre-proven unique and
5219    // ascending — skips the eager Vec<IndexLabel> build for huge join outputs.
5220    let index = Index::new_known_unique_int64_unit_range(0, output_len);
5221    let mut columns = std::collections::BTreeMap::new();
5222    let mut column_order = Vec::with_capacity(specs.len());
5223    for spec in specs {
5224        let FusedInt64OutputColumn { name, side, values } = spec;
5225        let mut data = Vec::<i64>::with_capacity(output_len);
5226        match side {
5227            FusedInt64Side::Left => {
5228                for (left_bucket, right_bucket) in left_buckets.iter().zip(right_buckets.iter()) {
5229                    if left_bucket.is_empty() {
5230                        continue;
5231                    }
5232                    let repeat_count = right_bucket.len();
5233                    for &left_pos in left_bucket {
5234                        let value = values[left_pos];
5235                        for _ in 0..repeat_count {
5236                            data.push(value);
5237                        }
5238                    }
5239                }
5240            }
5241            FusedInt64Side::Right => {
5242                for (left_bucket, right_bucket) in left_buckets.iter().zip(right_buckets.iter()) {
5243                    if left_bucket.is_empty() {
5244                        continue;
5245                    }
5246                    for _ in left_bucket {
5247                        for &right_pos in right_bucket {
5248                            data.push(values[right_pos]);
5249                        }
5250                    }
5251                }
5252            }
5253        }
5254        debug_assert_eq!(data.len(), output_len);
5255        insert_merged_output_column(
5256            &mut columns,
5257            &mut column_order,
5258            name,
5259            Column::from_i64_values(data),
5260        )?;
5261    }
5262
5263    Ok(Some(MergedDataFrame {
5264        index,
5265        columns,
5266        column_order,
5267    }))
5268}
5269
5270fn build_single_key_inner_merge_output(
5271    left: &fp_frame::DataFrame,
5272    right: &fp_frame::DataFrame,
5273    left_on: &[&str],
5274    right_on: &[&str],
5275    left_positions: &[usize],
5276    right_positions: &[usize],
5277    suffixes: &ResolvedMergeSuffixes,
5278) -> Result<MergedDataFrame, JoinError> {
5279    build_single_key_inner_merge_output_with_selections(
5280        left,
5281        right,
5282        left_on,
5283        right_on,
5284        PositionSelection::Positions(left_positions),
5285        PositionSelection::Positions(right_positions),
5286        suffixes,
5287    )
5288}
5289
5290fn build_single_key_inner_contiguous_no_overlap_output(
5291    left: &fp_frame::DataFrame,
5292    right: &fp_frame::DataFrame,
5293    left_on: &[&str],
5294    right_on: &[&str],
5295    left_positions: PositionSelection<'_>,
5296    right_positions: PositionSelection<'_>,
5297) -> Option<MergedDataFrame> {
5298    let (
5299        PositionSelection::ContiguousRange {
5300            start: left_start,
5301            len,
5302        },
5303        PositionSelection::ContiguousRange {
5304            start: right_start,
5305            len: right_len,
5306        },
5307    ) = (left_positions, right_positions)
5308    else {
5309        return None;
5310    };
5311    if left_on[0] != right_on[0] || len != right_len {
5312        return None;
5313    }
5314
5315    let left_col_names = left.column_names();
5316    let right_col_names = right.column_names();
5317    if left_col_names.iter().any(|left_name| {
5318        left_name.as_str() != left_on[0]
5319            && right_col_names
5320                .iter()
5321                .any(|right_name| right_name.as_str() == left_name.as_str())
5322    }) {
5323        return None;
5324    }
5325
5326    let mut columns = std::collections::BTreeMap::new();
5327    let mut column_order =
5328        Vec::with_capacity(left_col_names.len() + right_col_names.len().saturating_sub(1));
5329    let left_selection = PositionSelection::ContiguousRange {
5330        start: left_start,
5331        len,
5332    };
5333    let right_selection = PositionSelection::ContiguousRange {
5334        start: right_start,
5335        len,
5336    };
5337
5338    for name in left_col_names.iter().copied() {
5339        let column = left
5340            .columns()
5341            .get(name)
5342            .expect("left column listed in column_names must exist");
5343        let output_column = if name.as_str() == left_on[0] {
5344            take_lower_hex_sequence_range(column, left_start, len)
5345                .unwrap_or_else(|| take_position_selection_typed(column, left_selection))
5346        } else {
5347            take_position_selection_typed(column, left_selection)
5348        };
5349        column_order.push(name.clone());
5350        let previous = columns.insert(name.clone(), output_column);
5351        debug_assert!(previous.is_none());
5352    }
5353    for name in right_col_names.iter().copied() {
5354        if name.as_str() == right_on[0] {
5355            continue;
5356        }
5357        let column = right
5358            .columns()
5359            .get(name)
5360            .expect("right column listed in column_names must exist");
5361        column_order.push(name.clone());
5362        let previous = columns.insert(
5363            name.clone(),
5364            take_position_selection_typed(column, right_selection),
5365        );
5366        debug_assert!(previous.is_none());
5367    }
5368
5369    Some(MergedDataFrame {
5370        index: Index::new_known_unique_int64_unit_range(0, len),
5371        columns,
5372        column_order,
5373    })
5374}
5375
5376fn build_single_key_inner_merge_output_with_selections(
5377    left: &fp_frame::DataFrame,
5378    right: &fp_frame::DataFrame,
5379    left_on: &[&str],
5380    right_on: &[&str],
5381    left_positions: PositionSelection<'_>,
5382    right_positions: PositionSelection<'_>,
5383    suffixes: &ResolvedMergeSuffixes,
5384) -> Result<MergedDataFrame, JoinError> {
5385    debug_assert_eq!(left_on.len(), 1);
5386    debug_assert_eq!(right_on.len(), 1);
5387    debug_assert_eq!(left_positions.len(), right_positions.len());
5388
5389    if let Some(merged) = build_single_key_inner_contiguous_no_overlap_output(
5390        left,
5391        right,
5392        left_on,
5393        right_on,
5394        left_positions,
5395        right_positions,
5396    ) {
5397        return Ok(merged);
5398    }
5399
5400    let n = left_positions.len();
5401    // Lazy unit-range output index (see build_single_key_dense_i64 site).
5402    let index = Index::new_known_unique_int64_unit_range(0, n);
5403
5404    let left_col_names = left.column_names();
5405    let right_col_names = right.column_names();
5406    let use_linear_name_lookup =
5407        left_col_names.len() + right_col_names.len() <= SMALL_SCHEMA_LINEAR_COLUMN_LOOKUP_LIMIT;
5408    let left_hashed_col_names = (!use_linear_name_lookup).then(|| {
5409        left_col_names
5410            .iter()
5411            .map(|name| name.as_str())
5412            .collect::<HashSet<_>>()
5413    });
5414    let right_hashed_col_names = (!use_linear_name_lookup).then(|| {
5415        right_col_names
5416            .iter()
5417            .map(|name| name.as_str())
5418            .collect::<HashSet<_>>()
5419    });
5420    let shared_key_name = (left_on[0] == right_on[0]).then_some(left_on[0]);
5421    let mut overlapping_names = left_col_names
5422        .iter()
5423        .filter_map(|name| {
5424            let name = name.as_str();
5425            (Some(name) != shared_key_name
5426                && column_name_lookup_contains(
5427                    &right_col_names,
5428                    right_hashed_col_names.as_ref(),
5429                    name,
5430                ))
5431            .then(|| name.to_owned())
5432        })
5433        .collect::<Vec<_>>();
5434    overlapping_names.sort();
5435    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
5436
5437    // Resolve output column specs in order (name/suffix resolution is cheap),
5438    // then gather them. Each output column is an independent typed gather over
5439    // the position vector, so wide/large outputs build every column in parallel
5440    // (one column per worker) — the same disjoint-fill pattern as the dense-i64
5441    // fused builder (br-frankenpandas-j3jnd). Bit-identical to the serial loop:
5442    // identical per-column take_positions_typed result, inserted in spec order.
5443    let mut specs: Vec<(String, &Column, PositionSelection<'_>)> = Vec::new();
5444    for name in left_col_names.iter().copied() {
5445        let col = left
5446            .columns()
5447            .get(name)
5448            .expect("left column listed in column_names must exist");
5449        let out_name = if name.as_str() == left_on[0] {
5450            name.clone()
5451        } else if column_name_lookup_contains(
5452            &right_col_names,
5453            right_hashed_col_names.as_ref(),
5454            name.as_str(),
5455        ) {
5456            apply_merge_suffix(name, suffixes.left.as_deref())
5457        } else {
5458            name.clone()
5459        };
5460        specs.push((out_name, col, left_positions));
5461    }
5462    for name in right_col_names.iter().copied() {
5463        if name.as_str() == right_on[0] && shared_key_name == Some(name.as_str()) {
5464            continue;
5465        }
5466        let col = right
5467            .columns()
5468            .get(name)
5469            .expect("right column listed in column_names must exist");
5470        let out_name = if column_name_lookup_contains(
5471            &left_col_names,
5472            left_hashed_col_names.as_ref(),
5473            name.as_str(),
5474        ) {
5475            apply_merge_suffix(name, suffixes.right.as_deref())
5476        } else {
5477            name.clone()
5478        };
5479        specs.push((out_name, col, right_positions));
5480    }
5481
5482    let built: Vec<Column> = {
5483        let thread_count = join_parallel_thread_count();
5484        if specs.len() > 1 && n >= DENSE_I64_INNER_PARALLEL_MIN_VALUES && thread_count > 1 {
5485            let mut slots: Vec<Option<Column>> = (0..specs.len()).map(|_| None).collect();
5486            let chunk = specs.len().div_ceil(thread_count).max(1);
5487            std::thread::scope(|scope| {
5488                for (spec_chunk, slot_chunk) in specs.chunks(chunk).zip(slots.chunks_mut(chunk)) {
5489                    scope.spawn(move || {
5490                        for ((_, col, positions), slot) in spec_chunk.iter().zip(slot_chunk) {
5491                            *slot = Some(take_position_selection_typed(col, *positions));
5492                        }
5493                    });
5494                }
5495            });
5496            slots
5497                .into_iter()
5498                .map(|c| c.expect("every spec column must be built"))
5499                .collect()
5500        } else {
5501            specs
5502                .iter()
5503                .map(|(_, col, positions)| take_position_selection_typed(col, *positions))
5504                .collect()
5505        }
5506    };
5507
5508    let mut columns = std::collections::BTreeMap::new();
5509    let mut column_order: Vec<String> = Vec::with_capacity(specs.len());
5510    for ((out_name, _, _), column) in specs.into_iter().zip(built) {
5511        insert_merged_output_column(&mut columns, &mut column_order, out_name, column)?;
5512    }
5513
5514    Ok(MergedDataFrame {
5515        index,
5516        columns,
5517        column_order,
5518    })
5519}
5520
5521fn build_single_key_dense_left_merge_output(
5522    left: &fp_frame::DataFrame,
5523    right: &fp_frame::DataFrame,
5524    left_on: &[&str],
5525    right_on: &[&str],
5526    left_positions: &[Option<usize>],
5527    right_positions: &[Option<usize>],
5528    suffixes: &ResolvedMergeSuffixes,
5529) -> Result<MergedDataFrame, JoinError> {
5530    debug_assert_eq!(left_on.len(), 1);
5531    debug_assert_eq!(right_on.len(), 1);
5532    debug_assert_eq!(left_positions.len(), right_positions.len());
5533
5534    let n = left_positions.len();
5535    // Lazy unit-range output index (see build_single_key_dense_i64 site).
5536    let index = Index::new_known_unique_int64_unit_range(0, n);
5537    let mut columns = std::collections::BTreeMap::new();
5538    let mut column_order: Vec<String> = Vec::new();
5539
5540    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
5541    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
5542    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
5543    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
5544    let shared_key_names = if left_on[0] == right_on[0] {
5545        [left_on[0]].into_iter().collect::<HashSet<&str>>()
5546    } else {
5547        HashSet::new()
5548    };
5549    let overlapping_names =
5550        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
5551    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
5552    for name in left.column_names() {
5553        let col = left
5554            .columns()
5555            .get(name)
5556            .expect("left column listed in column_names must exist");
5557        let out_name = if left_key_name_set.contains(name.as_str()) {
5558            name.clone()
5559        } else if right_col_names.contains(name) {
5560            apply_merge_suffix(name, suffixes.left.as_deref())
5561        } else {
5562            name.clone()
5563        };
5564        let output = col.reindex_by_positions(left_positions)?;
5565        insert_merged_output_column(&mut columns, &mut column_order, out_name, output)?;
5566    }
5567
5568    for name in right.column_names() {
5569        let col = right
5570            .columns()
5571            .get(name)
5572            .expect("right column listed in column_names must exist");
5573        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
5574            continue;
5575        }
5576
5577        let reindexed = col.reindex_by_positions(right_positions)?;
5578        let out_name = if left_col_names.contains(name) {
5579            apply_merge_suffix(name, suffixes.right.as_deref())
5580        } else {
5581            name.clone()
5582        };
5583        insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
5584    }
5585
5586    Ok(MergedDataFrame {
5587        index,
5588        columns,
5589        column_order,
5590    })
5591}
5592
5593fn build_single_key_ordered_unique_left_merge_output(
5594    left: &fp_frame::DataFrame,
5595    right: &fp_frame::DataFrame,
5596    left_on: &[&str],
5597    right_on: &[&str],
5598    right_positions: &[Option<usize>],
5599    suffixes: &ResolvedMergeSuffixes,
5600) -> Result<MergedDataFrame, JoinError> {
5601    debug_assert_eq!(left_on.len(), 1);
5602    debug_assert_eq!(right_on.len(), 1);
5603    debug_assert_eq!(left.len(), right_positions.len());
5604
5605    let n = left.len();
5606    // Lazy unit-range output index (see build_single_key_dense_i64 site).
5607    let index = Index::new_known_unique_int64_unit_range(0, n);
5608    let mut columns = std::collections::BTreeMap::new();
5609    let mut column_order: Vec<String> = Vec::new();
5610    let mut identity_positions = None;
5611
5612    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
5613    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
5614    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
5615    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
5616    let shared_key_names = if left_on[0] == right_on[0] {
5617        [left_on[0]].into_iter().collect::<HashSet<&str>>()
5618    } else {
5619        HashSet::new()
5620    };
5621    let overlapping_names =
5622        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
5623    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
5624    let right_utf8_plan = shared_optional_utf8_gather_plan(right_positions, right.len());
5625
5626    for name in left.column_names() {
5627        let col = left
5628            .columns()
5629            .get(name)
5630            .expect("left column listed in column_names must exist");
5631        let out_name = if left_key_name_set.contains(name.as_str()) {
5632            name.clone()
5633        } else if right_col_names.contains(name) {
5634            apply_merge_suffix(name, suffixes.left.as_deref())
5635        } else {
5636            name.clone()
5637        };
5638        let output = identity_merge_column(col, n, &mut identity_positions);
5639        insert_merged_output_column(&mut columns, &mut column_order, out_name, output)?;
5640    }
5641
5642    for name in right.column_names() {
5643        let col = right
5644            .columns()
5645            .get(name)
5646            .expect("right column listed in column_names must exist");
5647        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
5648            continue;
5649        }
5650
5651        let reindexed =
5652            reindex_with_shared_utf8_plan(col, right_positions, right_utf8_plan.as_ref())?;
5653        let out_name = if left_col_names.contains(name) {
5654            apply_merge_suffix(name, suffixes.right.as_deref())
5655        } else {
5656            name.clone()
5657        };
5658        insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
5659    }
5660
5661    Ok(MergedDataFrame {
5662        index,
5663        columns,
5664        column_order,
5665    })
5666}
5667
5668fn build_single_key_ordered_unique_right_merge_output(
5669    left: &fp_frame::DataFrame,
5670    right: &fp_frame::DataFrame,
5671    left_on: &[&str],
5672    right_on: &[&str],
5673    left_positions: &[Option<usize>],
5674    suffixes: &ResolvedMergeSuffixes,
5675) -> Result<MergedDataFrame, JoinError> {
5676    debug_assert_eq!(left_on.len(), 1);
5677    debug_assert_eq!(right_on.len(), 1);
5678    debug_assert_eq!(right.len(), left_positions.len());
5679
5680    let n = right.len();
5681    // Lazy unit-range output index (see build_single_key_dense_i64 site).
5682    let index = Index::new_known_unique_int64_unit_range(0, n);
5683    let mut columns = std::collections::BTreeMap::new();
5684    let mut column_order: Vec<String> = Vec::new();
5685    let mut identity_positions = None;
5686
5687    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
5688    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
5689    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
5690    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
5691    let shared_key_names = if left_on[0] == right_on[0] {
5692        [left_on[0]].into_iter().collect::<HashSet<&str>>()
5693    } else {
5694        HashSet::new()
5695    };
5696    let overlapping_names =
5697        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
5698    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
5699
5700    for name in left.column_names() {
5701        let col = left
5702            .columns()
5703            .get(name)
5704            .expect("left column listed in column_names must exist");
5705        let out_name = if left_key_name_set.contains(name.as_str()) {
5706            name.clone()
5707        } else if right_col_names.contains(name) {
5708            apply_merge_suffix(name, suffixes.left.as_deref())
5709        } else {
5710            name.clone()
5711        };
5712        let output = if left_key_name_set.contains(name.as_str())
5713            && shared_key_names.contains(name.as_str())
5714        {
5715            let right_key_col = right
5716                .columns()
5717                .get(right_on[0])
5718                .expect("right key column must exist");
5719            identity_merge_column(right_key_col, n, &mut identity_positions)
5720        } else {
5721            col.reindex_by_positions(left_positions)?
5722        };
5723        insert_merged_output_column(&mut columns, &mut column_order, out_name, output)?;
5724    }
5725
5726    for name in right.column_names() {
5727        let col = right
5728            .columns()
5729            .get(name)
5730            .expect("right column listed in column_names must exist");
5731        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
5732            continue;
5733        }
5734
5735        let reindexed = identity_merge_column(col, n, &mut identity_positions);
5736        let out_name = if left_col_names.contains(name) {
5737            apply_merge_suffix(name, suffixes.right.as_deref())
5738        } else {
5739            name.clone()
5740        };
5741        insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
5742    }
5743
5744    Ok(MergedDataFrame {
5745        index,
5746        columns,
5747        column_order,
5748    })
5749}
5750
5751fn build_single_key_dense_right_merge_output(
5752    left: &fp_frame::DataFrame,
5753    right: &fp_frame::DataFrame,
5754    left_on: &[&str],
5755    right_on: &[&str],
5756    left_positions: &[Option<usize>],
5757    right_positions: &[Option<usize>],
5758    suffixes: &ResolvedMergeSuffixes,
5759) -> Result<MergedDataFrame, JoinError> {
5760    debug_assert_eq!(left_on.len(), 1);
5761    debug_assert_eq!(right_on.len(), 1);
5762    debug_assert_eq!(left_positions.len(), right_positions.len());
5763
5764    let n = left_positions.len();
5765    // Lazy unit-range output index (see build_single_key_dense_i64 site).
5766    let index = Index::new_known_unique_int64_unit_range(0, n);
5767    let mut columns = std::collections::BTreeMap::new();
5768    let mut column_order: Vec<String> = Vec::new();
5769
5770    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
5771    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
5772    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
5773    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
5774    let shared_key_names = if left_on[0] == right_on[0] {
5775        [left_on[0]].into_iter().collect::<HashSet<&str>>()
5776    } else {
5777        HashSet::new()
5778    };
5779    let overlapping_names =
5780        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
5781    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
5782
5783    for name in left.column_names() {
5784        let col = left
5785            .columns()
5786            .get(name)
5787            .expect("left column listed in column_names must exist");
5788        let out_name = if left_key_name_set.contains(name.as_str()) {
5789            name.clone()
5790        } else if right_col_names.contains(name) {
5791            apply_merge_suffix(name, suffixes.left.as_deref())
5792        } else {
5793            name.clone()
5794        };
5795        let output = if left_key_name_set.contains(name.as_str())
5796            && shared_key_names.contains(name.as_str())
5797        {
5798            let right_key_col = right
5799                .columns()
5800                .get(right_on[0])
5801                .expect("right key column must exist");
5802            right_key_col.reindex_by_positions(right_positions)?
5803        } else {
5804            col.reindex_by_positions(left_positions)?
5805        };
5806        insert_merged_output_column(&mut columns, &mut column_order, out_name, output)?;
5807    }
5808
5809    for name in right.column_names() {
5810        let col = right
5811            .columns()
5812            .get(name)
5813            .expect("right column listed in column_names must exist");
5814        if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
5815            continue;
5816        }
5817
5818        let reindexed = col.reindex_by_positions(right_positions)?;
5819        let out_name = if left_col_names.contains(name) {
5820            apply_merge_suffix(name, suffixes.right.as_deref())
5821        } else {
5822            name.clone()
5823        };
5824        insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
5825    }
5826
5827    Ok(MergedDataFrame {
5828        index,
5829        columns,
5830        column_order,
5831    })
5832}
5833
5834fn build_single_key_ordered_unique_outer_merge_output(
5835    left: &fp_frame::DataFrame,
5836    right: &fp_frame::DataFrame,
5837    left_on: &[&str],
5838    right_on: &[&str],
5839    left_positions: &[Option<usize>],
5840    right_positions: &[Option<usize>],
5841    suffixes: &ResolvedMergeSuffixes,
5842) -> Result<MergedDataFrame, JoinError> {
5843    debug_assert_eq!(left_on.len(), 1);
5844    debug_assert_eq!(right_on.len(), 1);
5845    debug_assert_eq!(left_positions.len(), right_positions.len());
5846
5847    let n = left_positions.len();
5848    // Lazy unit-range output index (see build_single_key_dense_i64 site).
5849    let index = Index::new_known_unique_int64_unit_range(0, n);
5850    let mut columns = std::collections::BTreeMap::new();
5851    let mut column_order: Vec<String> = Vec::new();
5852
5853    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
5854    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
5855    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
5856    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
5857
5858    let mut shared_name_positions = HashMap::<&str, (usize, usize)>::new();
5859    if left_on[0] == right_on[0] {
5860        shared_name_positions.insert(left_on[0], (0, 0));
5861    }
5862    let shared_key_names = shared_name_positions
5863        .keys()
5864        .copied()
5865        .collect::<HashSet<&str>>();
5866    let overlapping_names =
5867        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
5868    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
5869
5870    let mut left_take_positions = Vec::with_capacity(n);
5871    let mut right_take_positions = Vec::with_capacity(n);
5872    let mut all_positions_present = true;
5873    for (left_pos, right_pos) in left_positions.iter().zip(right_positions.iter()) {
5874        let (Some(left_pos), Some(right_pos)) = (*left_pos, *right_pos) else {
5875            all_positions_present = false;
5876            break;
5877        };
5878        left_take_positions.push(left_pos);
5879        right_take_positions.push(right_pos);
5880    }
5881    let all_present_take_positions =
5882        all_positions_present.then_some((left_take_positions, right_take_positions));
5883    let all_present_left_positions = all_present_take_positions
5884        .as_ref()
5885        .map(|(positions, _)| positions.as_slice());
5886    let all_present_right_positions = all_present_take_positions
5887        .as_ref()
5888        .map(|(_, positions)| positions.as_slice());
5889    let left_utf8_plan = all_present_left_positions
5890        .is_none()
5891        .then(|| shared_optional_utf8_gather_plan(left_positions, left.len()))
5892        .flatten();
5893    let right_utf8_plan = all_present_right_positions
5894        .is_none()
5895        .then(|| shared_optional_utf8_gather_plan(right_positions, right.len()))
5896        .flatten();
5897
5898    // Per-column output build is INDEPENDENT across columns and was the serial
5899    // hot phase of the join (~10.5ms of str_outer_join's reindex assembly at
5900    // n=150000, 12 Utf8 value columns). Build an ordered list of column specs
5901    // (cheap), compute each column — the O(output) `reindex_outer_join_column`
5902    // gather / take / key-coalesce — across workers, then insert in the SAME
5903    // first-seen order (br-frankenpandas-uza04.102). Byte-identical: each output
5904    // column is the same values in the same row order, inserted in the same
5905    // left-then-right column order, so `columns`/`column_order` are unchanged.
5906    enum ColBuild<'a> {
5907        KeyCoalesce {
5908            left_key_col: &'a Column,
5909            right_key_col: &'a Column,
5910        },
5911        Reindex {
5912            col: &'a Column,
5913            positions: &'a [Option<usize>],
5914            utf8_plan: Option<&'a SharedOptionalUtf8GatherPlan>,
5915        },
5916        Take {
5917            col: &'a Column,
5918            present: &'a [usize],
5919        },
5920    }
5921    let mut jobs: Vec<(String, ColBuild<'_>)> = Vec::new();
5922    for name in left.column_names() {
5923        let col = left
5924            .columns()
5925            .get(name)
5926            .expect("left column listed in column_names must exist");
5927        if left_key_name_set.contains(name.as_str()) {
5928            if let Some((left_key_idx, right_key_idx)) = shared_name_positions.get(name.as_str()) {
5929                let left_key_col = left
5930                    .columns()
5931                    .get(left_on[*left_key_idx])
5932                    .expect("left key column must exist");
5933                let spec = if let Some(positions) = all_present_left_positions {
5934                    ColBuild::Take {
5935                        col: left_key_col,
5936                        present: positions,
5937                    }
5938                } else {
5939                    let right_key_col = right
5940                        .columns()
5941                        .get(right_on[*right_key_idx])
5942                        .expect("right key column must exist");
5943                    ColBuild::KeyCoalesce {
5944                        left_key_col,
5945                        right_key_col,
5946                    }
5947                };
5948                jobs.push((name.clone(), spec));
5949            } else {
5950                let spec = if let Some(positions) = all_present_left_positions {
5951                    ColBuild::Take {
5952                        col,
5953                        present: positions,
5954                    }
5955                } else {
5956                    ColBuild::Reindex {
5957                        col,
5958                        positions: left_positions,
5959                        utf8_plan: left_utf8_plan.as_ref(),
5960                    }
5961                };
5962                jobs.push((name.clone(), spec));
5963            }
5964            continue;
5965        }
5966        let spec = if let Some(positions) = all_present_left_positions {
5967            ColBuild::Take {
5968                col,
5969                present: positions,
5970            }
5971        } else {
5972            ColBuild::Reindex {
5973                col,
5974                positions: left_positions,
5975                utf8_plan: left_utf8_plan.as_ref(),
5976            }
5977        };
5978        let out_name = if right_col_names.contains(name) {
5979            apply_merge_suffix(name, suffixes.left.as_deref())
5980        } else {
5981            name.clone()
5982        };
5983        jobs.push((out_name, spec));
5984    }
5985    for name in right.column_names() {
5986        let col = right
5987            .columns()
5988            .get(name)
5989            .expect("right column listed in column_names must exist");
5990        if right_key_name_set.contains(name.as_str())
5991            && shared_name_positions.contains_key(name.as_str())
5992        {
5993            continue;
5994        }
5995        let spec = if let Some(positions) = all_present_right_positions {
5996            ColBuild::Take {
5997                col,
5998                present: positions,
5999            }
6000        } else {
6001            ColBuild::Reindex {
6002                col,
6003                positions: right_positions,
6004                utf8_plan: right_utf8_plan.as_ref(),
6005            }
6006        };
6007        let out_name = if left_col_names.contains(name) {
6008            apply_merge_suffix(name, suffixes.right.as_deref())
6009        } else {
6010            name.clone()
6011        };
6012        jobs.push((out_name, spec));
6013    }
6014
6015    let compute = |spec: &ColBuild<'_>| -> Result<Column, JoinError> {
6016        match spec {
6017            ColBuild::KeyCoalesce {
6018                left_key_col,
6019                right_key_col,
6020            } => {
6021                if let (Some(left_keys), Some(right_keys)) =
6022                    (left_key_col.as_i64_slice(), right_key_col.as_i64_slice())
6023                {
6024                    let mut data = Vec::with_capacity(left_positions.len());
6025                    let mut all_positions_valid = true;
6026                    for (left_pos, right_pos) in left_positions.iter().zip(right_positions.iter()) {
6027                        match (*left_pos, *right_pos) {
6028                            (Some(pos), _) if pos < left_keys.len() => data.push(left_keys[pos]),
6029                            (None, Some(pos)) if pos < right_keys.len() => {
6030                                data.push(right_keys[pos])
6031                            }
6032                            _ => {
6033                                all_positions_valid = false;
6034                                break;
6035                            }
6036                        }
6037                    }
6038                    if all_positions_valid {
6039                        return Ok(Column::from_i64_values(data));
6040                    }
6041                }
6042
6043                let values = left_positions
6044                    .iter()
6045                    .zip(right_positions.iter())
6046                    .map(|(left_pos, right_pos)| match (left_pos, right_pos) {
6047                        (Some(pos), _) => left_key_col.values()[*pos].clone(),
6048                        (None, Some(pos)) => right_key_col.values()[*pos].clone(),
6049                        (None, None) => fp_types::Scalar::Null(fp_types::NullKind::Null),
6050                    })
6051                    .collect::<Vec<_>>();
6052                Ok(Column::from_values(values)?)
6053            }
6054            ColBuild::Reindex {
6055                col,
6056                positions,
6057                utf8_plan,
6058            } => reindex_outer_with_shared_utf8_plan(col, positions, *utf8_plan),
6059            ColBuild::Take { col, present } => Ok(take_positions_typed(col, present)),
6060        }
6061    };
6062
6063    let worker_count = std::thread::available_parallelism()
6064        .map_or(1, std::num::NonZeroUsize::get)
6065        .min(64)
6066        .min(jobs.len().max(1));
6067    let computed: Vec<Result<Column, JoinError>> = if worker_count >= 2 && jobs.len() >= 2 {
6068        let next = std::sync::atomic::AtomicUsize::new(0);
6069        let jobs_ref = &jobs;
6070        let compute_ref = &compute;
6071        let mut slots: Vec<Option<Result<Column, JoinError>>> =
6072            (0..jobs.len()).map(|_| None).collect();
6073        let parts = std::thread::scope(|scope| {
6074            let mut handles = Vec::with_capacity(worker_count);
6075            for _ in 0..worker_count {
6076                let next = &next;
6077                handles.push(scope.spawn(move || {
6078                    let mut out: Vec<(usize, Result<Column, JoinError>)> = Vec::new();
6079                    loop {
6080                        let i = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
6081                        if i >= jobs_ref.len() {
6082                            break;
6083                        }
6084                        out.push((i, compute_ref(&jobs_ref[i].1)));
6085                    }
6086                    out
6087                }));
6088            }
6089            handles
6090                .into_iter()
6091                .map(|h| h.join().expect("join assembly worker panicked"))
6092                .collect::<Vec<_>>()
6093        });
6094        for part in parts {
6095            for (i, r) in part {
6096                slots[i] = Some(r);
6097            }
6098        }
6099        slots
6100            .into_iter()
6101            .map(|s| s.expect("every output column computed"))
6102            .collect()
6103    } else {
6104        jobs.iter().map(|(_, spec)| compute(spec)).collect()
6105    };
6106
6107    for ((out_name, _), col_res) in jobs.into_iter().zip(computed) {
6108        insert_merged_output_column(&mut columns, &mut column_order, out_name, col_res?)?;
6109    }
6110
6111    Ok(MergedDataFrame {
6112        index,
6113        columns,
6114        column_order,
6115    })
6116}
6117
6118fn build_single_key_ordered_identity_inner_merge_output(
6119    left: &fp_frame::DataFrame,
6120    right: &fp_frame::DataFrame,
6121    left_on: &[&str],
6122    right_on: &[&str],
6123    suffixes: &ResolvedMergeSuffixes,
6124) -> Result<MergedDataFrame, JoinError> {
6125    debug_assert_eq!(left_on.len(), 1);
6126    debug_assert_eq!(right_on.len(), 1);
6127    debug_assert_eq!(left_on[0], right_on[0]);
6128
6129    let n = left.len();
6130    debug_assert_eq!(n, right.len());
6131    // Lazy unit-range output index (see build_single_key_dense_i64 site).
6132    let index = Index::new_known_unique_int64_unit_range(0, n);
6133    let mut columns = std::collections::BTreeMap::new();
6134    let mut column_order: Vec<String> = Vec::new();
6135    let mut identity_positions = None;
6136
6137    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
6138    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
6139    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
6140    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
6141    let shared_key_names = left_on.iter().copied().collect::<HashSet<&str>>();
6142    let overlapping_names =
6143        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
6144    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
6145
6146    for name in left.column_names() {
6147        let col = left
6148            .columns()
6149            .get(name)
6150            .expect("left column listed in column_names must exist");
6151        let out_name = if left_key_name_set.contains(name.as_str()) {
6152            name.clone()
6153        } else if right_col_names.contains(name) {
6154            apply_merge_suffix(name, suffixes.left.as_deref())
6155        } else {
6156            name.clone()
6157        };
6158        let output = identity_merge_column(col, n, &mut identity_positions);
6159        insert_merged_output_column(&mut columns, &mut column_order, out_name, output)?;
6160    }
6161
6162    for name in right.column_names() {
6163        if right_key_name_set.contains(name.as_str()) {
6164            continue;
6165        }
6166
6167        let col = right
6168            .columns()
6169            .get(name)
6170            .expect("right column listed in column_names must exist");
6171        let out_name = if left_col_names.contains(name) {
6172            apply_merge_suffix(name, suffixes.right.as_deref())
6173        } else {
6174            name.clone()
6175        };
6176        let output = identity_merge_column(col, n, &mut identity_positions);
6177        insert_merged_output_column(&mut columns, &mut column_order, out_name, output)?;
6178    }
6179
6180    Ok(MergedDataFrame {
6181        index,
6182        columns,
6183        column_order,
6184    })
6185}
6186
6187/// Hash-free inner-join position build for two all-valid, bounded-range Int64
6188/// key columns. Replaces the `FxHashMap<&JoinKeyComponent, _>` build+probe with
6189/// a counting-sort / CSR direct-address table indexed by `key - min`.
6190///
6191/// Bit-identical to the hash path's emitted `(left_pos, right_pos)` pairs: the
6192/// hash path buckets right positions in *insertion* order (ascending position),
6193/// and this CSR fill also writes right positions in ascending-position order,
6194/// so for every left row the matched right rows are emitted in the same order;
6195/// left rows are still probed in ascending order. All-valid Int64 keys map to
6196/// `Present(IndexLabel::Int64(v))` in the hash path, whose equality is plain
6197/// `i64 ==`, so membership/equality semantics are identical. A left key outside
6198/// the right key span matches nothing in either path. Returns `None` (caller
6199/// falls back to the hash path) for non-Int64, any-missing, or wide-span keys.
6200fn dense_int64_inner_positions(
6201    left_key: &Column,
6202    right_key: &Column,
6203) -> Option<(Vec<usize>, Vec<usize>)> {
6204    let left = left_key.as_i64_slice()?;
6205    let right = right_key.as_i64_slice()?;
6206    dense_i64_inner_positions_slices(left, right)
6207}
6208
6209/// Core counting-sort/CSR inner-join over two `i64` key slices (see
6210/// [`dense_int64_inner_positions`]). Emits `(left_pos, right_pos)` pairs with
6211/// right positions ascending per left key, left probed ascending — matching the
6212/// hash path's bucket-insertion order. Returns `None` for a span wider than the
6213/// bounded direct-address gate so the caller falls back to hashing.
6214fn dense_i64_inner_positions_slices(
6215    left: &[i64],
6216    right: &[i64],
6217) -> Option<(Vec<usize>, Vec<usize>)> {
6218    if right.is_empty() || left.is_empty() {
6219        return Some((Vec::new(), Vec::new()));
6220    }
6221
6222    let mut min = right[0];
6223    let mut max = right[0];
6224    for &v in right {
6225        if v < min {
6226            min = v;
6227        }
6228        if v > max {
6229            max = v;
6230        }
6231    }
6232    // Bounded-span gate (mirrors the fp-columnar direct-address tally gates):
6233    // the dense table costs O(span) memory, so only take it when the span is
6234    // small in absolute terms AND relative to the build (right) side.
6235    let span = (max as i128) - (min as i128) + 1;
6236    if span > (1i128 << 24) || span > 16 * (right.len() as i128) {
6237        return None;
6238    }
6239    let range = span as usize;
6240
6241    // CSR build over the right side: counts -> exclusive-prefix offsets ->
6242    // positions filled in ascending right-position order.
6243    let mut offsets = vec![0usize; range + 1];
6244    for &v in right {
6245        offsets[(v - min) as usize + 1] += 1;
6246    }
6247    for i in 0..range {
6248        offsets[i + 1] += offsets[i];
6249    }
6250    let mut positions = vec![0usize; right.len()];
6251    let mut cursor = offsets.clone();
6252    for (pos, &v) in right.iter().enumerate() {
6253        let bucket = (v - min) as usize;
6254        positions[cursor[bucket]] = pos;
6255        cursor[bucket] += 1;
6256    }
6257
6258    let mut left_positions = Vec::<usize>::with_capacity(left.len().min(right.len()));
6259    let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
6260    for (left_pos, &v) in left.iter().enumerate() {
6261        if v < min || v > max {
6262            continue;
6263        }
6264        let bucket = (v - min) as usize;
6265        for &right_pos in &positions[offsets[bucket]..offsets[bucket + 1]] {
6266            left_positions.push(left_pos);
6267            right_positions.push(right_pos);
6268        }
6269    }
6270    Some((left_positions, right_positions))
6271}
6272
6273/// Hash inner-join position build for the remaining all-valid Int64 single-key
6274/// shape after ordered/dense witnesses reject. This keeps the generic hash
6275/// path's left-major probe order and right-bucket insertion order, but hashes
6276/// raw `i64` keys instead of materializing `JoinKeyComponent::Present` wrappers.
6277fn hash_int64_inner_positions(
6278    left_key: &Column,
6279    right_key: &Column,
6280) -> Option<(Vec<usize>, Vec<usize>)> {
6281    let left = left_key.as_i64_slice()?;
6282    let right = right_key.as_i64_slice()?;
6283    Some(hash_i64_inner_positions_slices(left, right))
6284}
6285
6286/// Hash build+probe over raw UTF-8 byte spans for all-valid contiguous-Utf8
6287/// keys (br-frankenpandas-i388q). Mirrors the generic `JoinKeyComponent` inner
6288/// path exactly — right positions pushed ascending per key bucket, left probed
6289/// in order — but hashes `&[u8]` spans directly instead of materializing each
6290/// key column to `Vec<Scalar>` and cloning every string into a
6291/// `JoinKeyComponent::Present(IndexLabel::Utf8)` wrapper. Returns `None` unless
6292/// BOTH keys are all-valid contiguous Utf8; null-bearing keys keep the generic
6293/// path (which matches null-to-null — a case `as_utf8_contiguous` excludes).
6294fn contiguous_utf8_inner_positions(
6295    left_key: &Column,
6296    right_key: &Column,
6297) -> Option<(Vec<usize>, Vec<usize>)> {
6298    let (left_bytes, left_offsets) = left_key.as_utf8_contiguous()?;
6299    let (right_bytes, right_offsets) = right_key.as_utf8_contiguous()?;
6300    let left_n = left_offsets.len() - 1;
6301    let right_n = right_offsets.len() - 1;
6302    if left_n == 0 || right_n == 0 {
6303        return Some((Vec::new(), Vec::new()));
6304    }
6305
6306    let mut right_map = FxHashMap::<&[u8], JoinPositionBucket>::with_capacity_and_hasher(
6307        right_n,
6308        Default::default(),
6309    );
6310    for pos in 0..right_n {
6311        let span = &right_bytes[right_offsets[pos]..right_offsets[pos + 1]];
6312        right_map.entry(span).or_default().push(pos);
6313    }
6314
6315    let mut left_positions = Vec::<usize>::with_capacity(left_n.min(right_n));
6316    let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
6317    for left_pos in 0..left_n {
6318        let span = &left_bytes[left_offsets[left_pos]..left_offsets[left_pos + 1]];
6319        if let Some(matches) = right_map.get(span) {
6320            for &right_pos in matches {
6321                left_positions.push(left_pos);
6322                right_positions.push(right_pos);
6323            }
6324        }
6325    }
6326    Some((left_positions, right_positions))
6327}
6328
6329fn hash_i64_inner_positions_slices(left: &[i64], right: &[i64]) -> (Vec<usize>, Vec<usize>) {
6330    if right.is_empty() || left.is_empty() {
6331        return (Vec::new(), Vec::new());
6332    }
6333
6334    let mut right_map = FxHashMap::<i64, JoinPositionBucket>::with_capacity_and_hasher(
6335        right.len(),
6336        Default::default(),
6337    );
6338    for (pos, &key) in right.iter().enumerate() {
6339        right_map.entry(key).or_default().push(pos);
6340    }
6341
6342    let mut left_positions = Vec::<usize>::with_capacity(left.len().min(right.len()));
6343    let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
6344    for (left_pos, &key) in left.iter().enumerate() {
6345        if let Some(matches) = right_map.get(&key) {
6346            for &right_pos in matches {
6347                left_positions.push(left_pos);
6348                right_positions.push(right_pos);
6349            }
6350        }
6351    }
6352    (left_positions, right_positions)
6353}
6354
6355/// Hash-free inner-join positions for a MULTI-column key whose every component
6356/// is an all-valid, bounded-range Int64 column. Packs each row's composite key
6357/// into a single `i64` via a mixed-radix code over the per-column spans
6358/// (`packed = Σ_c (val_c - min_c) · stride_c`, `stride_0 = 1`, `stride_c =
6359/// stride_{c-1}·range_{c-1}`), then runs the dense CSR core on the packed keys.
6360///
6361/// The packing is a bijection on the joint key box (mins/ranges computed over
6362/// BOTH sides so left- and right-side codes are comparable), so two composite
6363/// keys collide under packing IFF every component is equal — identical to the
6364/// `CompositeJoinKey` equality the FxHashMap path uses. Pair order is therefore
6365/// byte-for-byte the same as the hash path. Returns `None` (caller falls back to
6366/// the composite-hash path) for any non-Int64 / any-missing component or when
6367/// the packed span exceeds the bounded direct-address gate.
6368fn dense_packed_int64_inner_positions(
6369    left_cols: &[&Column],
6370    right_cols: &[&Column],
6371) -> Option<(Vec<usize>, Vec<usize>)> {
6372    let k = left_cols.len();
6373    if k == 0 || k != right_cols.len() {
6374        return None;
6375    }
6376
6377    let left_slices: Vec<&[i64]> = left_cols
6378        .iter()
6379        .map(|c| c.as_i64_slice())
6380        .collect::<Option<Vec<_>>>()?;
6381    let right_slices: Vec<&[i64]> = right_cols
6382        .iter()
6383        .map(|c| c.as_i64_slice())
6384        .collect::<Option<Vec<_>>>()?;
6385
6386    let n_left = left_slices[0].len();
6387    let n_right = right_slices[0].len();
6388    if n_left == 0 || n_right == 0 {
6389        return Some((Vec::new(), Vec::new()));
6390    }
6391
6392    // Per-column min and span over BOTH sides; product = joint packed span.
6393    let mut mins = vec![0i64; k];
6394    let mut strides = vec![1i128; k];
6395    let mut total: i128 = 1;
6396    for c in 0..k {
6397        let mut mn = right_slices[c][0];
6398        let mut mx = right_slices[c][0];
6399        for &v in left_slices[c].iter().chain(right_slices[c].iter()) {
6400            if v < mn {
6401                mn = v;
6402            }
6403            if v > mx {
6404                mx = v;
6405            }
6406        }
6407        mins[c] = mn;
6408        let range = (mx as i128) - (mn as i128) + 1;
6409        strides[c] = total;
6410        total = total.checked_mul(range)?;
6411        // Gate the packed span the same way the single-key core does, up front
6412        // (the product can overflow the bounded table for wide multi-keys).
6413        if total > (1i128 << 24) {
6414            return None;
6415        }
6416    }
6417    if total > 16 * ((n_left + n_right) as i128) {
6418        return None;
6419    }
6420
6421    let pack = |slices: &[&[i64]], n: usize| -> Vec<i64> {
6422        (0..n)
6423            .map(|row| {
6424                let mut acc: i128 = 0;
6425                for c in 0..k {
6426                    acc += ((slices[c][row] as i128) - (mins[c] as i128)) * strides[c];
6427                }
6428                acc as i64
6429            })
6430            .collect()
6431    };
6432    let packed_left = pack(&left_slices, n_left);
6433    let packed_right = pack(&right_slices, n_right);
6434
6435    dense_i64_inner_positions_slices(&packed_left, &packed_right)
6436}
6437
6438fn merge_single_key_inner_unsorted(
6439    left: &fp_frame::DataFrame,
6440    right: &fp_frame::DataFrame,
6441    left_on: &[&str],
6442    right_on: &[&str],
6443    left_key_columns: &[&Column],
6444    right_key_columns: &[&Column],
6445    suffixes: &ResolvedMergeSuffixes,
6446) -> Result<MergedDataFrame, JoinError> {
6447    debug_assert_eq!(left_key_columns.len(), 1);
6448    debug_assert_eq!(right_key_columns.len(), 1);
6449
6450    if left_on[0] == right_on[0]
6451        && ordered_identity_int64_keys_match(left_key_columns[0], right_key_columns[0])
6452    {
6453        return build_single_key_ordered_identity_inner_merge_output(
6454            left, right, left_on, right_on, suffixes,
6455        );
6456    }
6457    if let Some((left_positions, right_positions)) =
6458        ordered_unique_int64_inner_positions(left_key_columns[0], right_key_columns[0])
6459    {
6460        return build_single_key_inner_merge_output(
6461            left,
6462            right,
6463            left_on,
6464            right_on,
6465            &left_positions,
6466            &right_positions,
6467            suffixes,
6468        );
6469    }
6470
6471    if let Some(merged) = build_single_key_dense_i64_inner_merge_output(
6472        left,
6473        right,
6474        left_on,
6475        right_on,
6476        left_key_columns[0],
6477        right_key_columns[0],
6478        FusedInt64MergeOptions {
6479            suffixes,
6480            require_all_left_keys_matched: false,
6481        },
6482    )? {
6483        return Ok(merged);
6484    }
6485
6486    // Hash-free dense direct-address build+probe for bounded all-valid Int64
6487    // keys (the common low-cardinality join-key shape). Bit-identical pairs.
6488    if let Some((left_positions, right_positions)) =
6489        dense_int64_inner_positions(left_key_columns[0], right_key_columns[0])
6490    {
6491        return build_single_key_inner_merge_output(
6492            left,
6493            right,
6494            left_on,
6495            right_on,
6496            &left_positions,
6497            &right_positions,
6498            suffixes,
6499        );
6500    }
6501    if let Some((left_positions, right_positions)) =
6502        hash_int64_inner_positions(left_key_columns[0], right_key_columns[0])
6503    {
6504        return build_single_key_inner_merge_output(
6505            left,
6506            right,
6507            left_on,
6508            right_on,
6509            &left_positions,
6510            &right_positions,
6511            suffixes,
6512        );
6513    }
6514
6515    if let Some(position_plan) =
6516        ordered_unique_utf8_inner_position_plan(left_key_columns[0], right_key_columns[0])
6517    {
6518        return match position_plan {
6519            InnerPositionPlan::Gather {
6520                left_positions,
6521                right_positions,
6522            } => build_single_key_inner_merge_output(
6523                left,
6524                right,
6525                left_on,
6526                right_on,
6527                &left_positions,
6528                &right_positions,
6529                suffixes,
6530            ),
6531            InnerPositionPlan::ContiguousRanges {
6532                left_start,
6533                right_start,
6534                len,
6535            } => build_single_key_inner_merge_output_with_selections(
6536                left,
6537                right,
6538                left_on,
6539                right_on,
6540                PositionSelection::ContiguousRange {
6541                    start: left_start,
6542                    len,
6543                },
6544                PositionSelection::ContiguousRange {
6545                    start: right_start,
6546                    len,
6547                },
6548                suffixes,
6549            ),
6550        };
6551    }
6552
6553    // Byte-span build+probe for all-valid contiguous-Utf8 string keys
6554    // (br-frankenpandas-i388q): skips the per-row String clone + Scalar
6555    // materialization of the JoinKeyComponent path. Same pairing -> same output.
6556    if let Some((left_positions, right_positions)) =
6557        contiguous_utf8_inner_positions(left_key_columns[0], right_key_columns[0])
6558    {
6559        return build_single_key_inner_merge_output(
6560            left,
6561            right,
6562            left_on,
6563            right_on,
6564            &left_positions,
6565            &right_positions,
6566            suffixes,
6567        );
6568    }
6569
6570    let left_keys = collect_single_join_keys(left_key_columns[0]);
6571    let right_keys = collect_single_join_keys(right_key_columns[0]);
6572    let mut right_map =
6573        FxHashMap::<&JoinKeyComponent, JoinPositionBucket>::with_capacity_and_hasher(
6574            right_keys.len(),
6575            Default::default(),
6576        );
6577    for (pos, key) in right_keys.iter().enumerate() {
6578        right_map.entry(key).or_default().push(pos);
6579    }
6580
6581    let mut left_positions = Vec::<usize>::with_capacity(left_keys.len().min(right_keys.len()));
6582    let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
6583    for (left_pos, key) in left_keys.iter().enumerate() {
6584        if let Some(matches) = right_map.get(key) {
6585            for &right_pos in matches {
6586                left_positions.push(left_pos);
6587                right_positions.push(right_pos);
6588            }
6589        }
6590    }
6591
6592    build_single_key_inner_merge_output(
6593        left,
6594        right,
6595        left_on,
6596        right_on,
6597        &left_positions,
6598        &right_positions,
6599        suffixes,
6600    )
6601}
6602
6603/// Merge two DataFrames on one or more key columns.
6604///
6605/// Matches `pd.merge(left, right, left_on=left_keys, right_on=right_keys, how=join_type)`.
6606/// - Key columns are used for matching rows (hash join).
6607/// - Non-key columns are carried through and reindexed.
6608/// - Column name conflicts use configurable suffixes (default `_x`/`_y`).
6609/// - The output index is auto-generated (0..n RangeIndex-style).
6610pub fn merge_dataframes_on_with(
6611    left: &fp_frame::DataFrame,
6612    right: &fp_frame::DataFrame,
6613    left_on: &[&str],
6614    right_on: &[&str],
6615    join_type: JoinType,
6616) -> Result<MergedDataFrame, JoinError> {
6617    merge_dataframes_on_with_options(
6618        left,
6619        right,
6620        left_on,
6621        right_on,
6622        join_type,
6623        MergeExecutionOptions::default(),
6624    )
6625}
6626
6627/// Merge two DataFrames on one or more key columns with execution options.
6628pub fn merge_dataframes_on_with_options(
6629    left: &fp_frame::DataFrame,
6630    right: &fp_frame::DataFrame,
6631    left_on: &[&str],
6632    right_on: &[&str],
6633    join_type: JoinType,
6634    options: MergeExecutionOptions,
6635) -> Result<MergedDataFrame, JoinError> {
6636    let MergeExecutionOptions {
6637        indicator_name,
6638        validate_mode,
6639        suffixes,
6640        sort,
6641    } = options;
6642    let indicator_name = resolve_merge_indicator_name(indicator_name.as_deref())?;
6643    let suffixes = resolve_merge_suffixes(suffixes);
6644
6645    if matches!(join_type, JoinType::Cross) {
6646        if let Some(validate_mode) = validate_mode
6647            && !matches!(validate_mode, MergeValidateMode::ManyToMany)
6648        {
6649            return Err(JoinError::Frame(FrameError::CompatibilityRejected(
6650                format!(
6651                    "merge validate='{}' is not supported for cross join",
6652                    validate_mode.as_str()
6653                ),
6654            )));
6655        }
6656        return merge_dataframes_cross(left, right, indicator_name.as_deref(), &suffixes);
6657    }
6658
6659    if left_on.is_empty() || right_on.is_empty() {
6660        return Err(JoinError::Frame(FrameError::CompatibilityRejected(
6661            "merge requires at least one key column".to_owned(),
6662        )));
6663    }
6664    if left_on.len() != right_on.len() {
6665        return Err(JoinError::Frame(FrameError::CompatibilityRejected(
6666            "merge requires left_on and right_on key lists with equal length".to_owned(),
6667        )));
6668    }
6669
6670    let mut seen_left_keys = HashSet::new();
6671    for key_name in left_on {
6672        if !seen_left_keys.insert(*key_name) {
6673            return Err(JoinError::Frame(FrameError::CompatibilityRejected(
6674                format!("merge left key column '{key_name}' is duplicated"),
6675            )));
6676        }
6677    }
6678    let mut seen_right_keys = HashSet::new();
6679    for key_name in right_on {
6680        if !seen_right_keys.insert(*key_name) {
6681            return Err(JoinError::Frame(FrameError::CompatibilityRejected(
6682                format!("merge right key column '{key_name}' is duplicated"),
6683            )));
6684        }
6685    }
6686
6687    let left_key_columns = collect_join_key_columns(left, left_on, "left")?;
6688    let right_key_columns = collect_join_key_columns(right, right_on, "right")?;
6689    let validate_allows_fast_positions = validate_mode_allows_fast_positions(validate_mode);
6690
6691    if matches!(join_type, JoinType::Inner)
6692        && left_on.len() == 1
6693        && right_on.len() == 1
6694        && !sort
6695        && indicator_name.is_none()
6696        && validate_allows_fast_positions
6697    {
6698        return merge_single_key_inner_unsorted(
6699            left,
6700            right,
6701            left_on,
6702            right_on,
6703            &left_key_columns,
6704            &right_key_columns,
6705            &suffixes,
6706        );
6707    }
6708    if matches!(join_type, JoinType::Left)
6709        && left_on.len() == 1
6710        && right_on.len() == 1
6711        && !sort
6712        && indicator_name.is_none()
6713        && validate_allows_fast_positions
6714        && let Some(right_positions) =
6715            ordered_unique_int64_left_match_positions(left_key_columns[0], right_key_columns[0])
6716    {
6717        return build_single_key_ordered_unique_left_merge_output(
6718            left,
6719            right,
6720            left_on,
6721            right_on,
6722            &right_positions,
6723            &suffixes,
6724        );
6725    }
6726    if matches!(join_type, JoinType::Left)
6727        && left_on.len() == 1
6728        && right_on.len() == 1
6729        && !sort
6730        && indicator_name.is_none()
6731        && validate_allows_fast_positions
6732        && let Some(merged) = build_single_key_dense_cycle_i64_left_merge_output(
6733            left,
6734            right,
6735            left_on,
6736            right_on,
6737            left_key_columns[0],
6738            right_key_columns[0],
6739            &suffixes,
6740        )?
6741    {
6742        return Ok(merged);
6743    }
6744    if matches!(join_type, JoinType::Left)
6745        && left_on.len() == 1
6746        && right_on.len() == 1
6747        && !sort
6748        && indicator_name.is_none()
6749        && validate_allows_fast_positions
6750        && let Some(merged) = build_single_key_dense_i64_inner_merge_output(
6751            left,
6752            right,
6753            left_on,
6754            right_on,
6755            left_key_columns[0],
6756            right_key_columns[0],
6757            FusedInt64MergeOptions {
6758                suffixes: &suffixes,
6759                require_all_left_keys_matched: true,
6760            },
6761        )?
6762    {
6763        return Ok(merged);
6764    }
6765    if matches!(join_type, JoinType::Left)
6766        && left_on.len() == 1
6767        && right_on.len() == 1
6768        && !sort
6769        && indicator_name.is_none()
6770        && validate_allows_fast_positions
6771        && let Some(merged) = build_single_key_dense_i64_left_merge_output(
6772            left,
6773            right,
6774            left_on,
6775            right_on,
6776            left_key_columns[0],
6777            right_key_columns[0],
6778            &suffixes,
6779        )?
6780    {
6781        return Ok(merged);
6782    }
6783    if matches!(join_type, JoinType::Left)
6784        && left_on.len() == 1
6785        && right_on.len() == 1
6786        && !sort
6787        && indicator_name.is_none()
6788        && validate_allows_fast_positions
6789        && let Some((left_positions, right_positions)) =
6790            dense_int64_left_positions(left_key_columns[0], right_key_columns[0])
6791    {
6792        return build_single_key_dense_left_merge_output(
6793            left,
6794            right,
6795            left_on,
6796            right_on,
6797            &left_positions,
6798            &right_positions,
6799            &suffixes,
6800        );
6801    }
6802    if matches!(join_type, JoinType::Right)
6803        && left_on.len() == 1
6804        && right_on.len() == 1
6805        && !sort
6806        && indicator_name.is_none()
6807        && validate_allows_fast_positions
6808        && let Some(left_positions) =
6809            ordered_unique_int64_right_match_positions(left_key_columns[0], right_key_columns[0])
6810    {
6811        return build_single_key_ordered_unique_right_merge_output(
6812            left,
6813            right,
6814            left_on,
6815            right_on,
6816            &left_positions,
6817            &suffixes,
6818        );
6819    }
6820    if matches!(join_type, JoinType::Right)
6821        && left_on.len() == 1
6822        && right_on.len() == 1
6823        && !sort
6824        && indicator_name.is_none()
6825        && validate_allows_fast_positions
6826        && let Some(merged) = build_single_key_dense_i64_right_all_matched_merge_output(
6827            left,
6828            right,
6829            left_on,
6830            right_on,
6831            left_key_columns[0],
6832            right_key_columns[0],
6833            &suffixes,
6834        )?
6835    {
6836        return Ok(merged);
6837    }
6838    if matches!(join_type, JoinType::Right)
6839        && left_on.len() == 1
6840        && right_on.len() == 1
6841        && !sort
6842        && indicator_name.is_none()
6843        && validate_allows_fast_positions
6844        && let Some(merged) = build_single_key_dense_i64_right_merge_output(
6845            left,
6846            right,
6847            left_on,
6848            right_on,
6849            left_key_columns[0],
6850            right_key_columns[0],
6851            &suffixes,
6852        )?
6853    {
6854        return Ok(merged);
6855    }
6856    if matches!(join_type, JoinType::Right)
6857        && left_on.len() == 1
6858        && right_on.len() == 1
6859        && !sort
6860        && indicator_name.is_none()
6861        && validate_allows_fast_positions
6862        && let Some((left_positions, right_positions)) =
6863            dense_int64_right_positions(left_key_columns[0], right_key_columns[0])
6864    {
6865        return build_single_key_dense_right_merge_output(
6866            left,
6867            right,
6868            left_on,
6869            right_on,
6870            &left_positions,
6871            &right_positions,
6872            &suffixes,
6873        );
6874    }
6875    if matches!(join_type, JoinType::Outer)
6876        && left_on.len() == 1
6877        && right_on.len() == 1
6878        && !sort
6879        && indicator_name.is_none()
6880        && validate_allows_fast_positions
6881        && let Some((left_positions, right_positions)) =
6882            ordered_unique_int64_outer_positions(left_key_columns[0], right_key_columns[0])
6883    {
6884        return build_single_key_ordered_unique_outer_merge_output(
6885            left,
6886            right,
6887            left_on,
6888            right_on,
6889            &left_positions,
6890            &right_positions,
6891            &suffixes,
6892        );
6893    }
6894    if matches!(join_type, JoinType::Outer)
6895        && left_on.len() == 1
6896        && right_on.len() == 1
6897        && !sort
6898        && indicator_name.is_none()
6899        && validate_allows_fast_positions
6900        && let Some(merged) = build_single_key_dense_i64_outer_all_matched_merge_output(
6901            left,
6902            right,
6903            left_on,
6904            right_on,
6905            left_key_columns[0],
6906            right_key_columns[0],
6907            &suffixes,
6908        )?
6909    {
6910        return Ok(merged);
6911    }
6912    if matches!(join_type, JoinType::Outer)
6913        && left_on.len() == 1
6914        && right_on.len() == 1
6915        && !sort
6916        && indicator_name.is_none()
6917        && validate_allows_fast_positions
6918        && let Some(merged) = build_single_key_dense_i64_outer_merge_output(
6919            left,
6920            right,
6921            left_on,
6922            right_on,
6923            left_key_columns[0],
6924            right_key_columns[0],
6925            &suffixes,
6926        )?
6927    {
6928        return Ok(merged);
6929    }
6930    if matches!(join_type, JoinType::Outer)
6931        && left_on.len() == 1
6932        && right_on.len() == 1
6933        && !sort
6934        && indicator_name.is_none()
6935        && validate_allows_fast_positions
6936        && let Some((left_positions, right_positions)) =
6937            dense_int64_outer_positions(left_key_columns[0], right_key_columns[0])
6938    {
6939        return build_single_key_ordered_unique_outer_merge_output(
6940            left,
6941            right,
6942            left_on,
6943            right_on,
6944            &left_positions,
6945            &right_positions,
6946            &suffixes,
6947        );
6948    }
6949
6950    let needs_key_order = sort || matches!(join_type, JoinType::Outer);
6951
6952    // Hash-free fast path: a plain inner join on all-valid bounded-Int64 key
6953    // column(s) packs the composite key into one i64 and runs the dense CSR
6954    // core, skipping CompositeJoinKey materialization + FxHashMap build/probe.
6955    // Gated to inner joins with no sort/indicator/enforcing validate, where the
6956    // emitted (left,right) pairs are byte-for-byte identical to the hash path.
6957    let packed_inner = if matches!(join_type, JoinType::Inner)
6958        && !sort
6959        && validate_allows_fast_positions
6960        && indicator_name.is_none()
6961    {
6962        dense_packed_int64_inner_positions(&left_key_columns, &right_key_columns)
6963    } else {
6964        None
6965    };
6966
6967    let (mut left_positions, mut right_positions, out_row_keys): MergeRowPositions =
6968        if let Some((lp, rp)) = packed_inner {
6969            (
6970                lp.into_iter().map(Some).collect(),
6971                rp.into_iter().map(Some).collect(),
6972                None,
6973            )
6974        } else {
6975            // Convert key columns to hashable composite keys.
6976            let left_keys = collect_composite_keys(&left_key_columns);
6977            let right_keys = collect_composite_keys(&right_key_columns);
6978            if let Some(validate_mode) = validate_mode {
6979                validate_merge_cardinality(validate_mode, &left_keys, &right_keys)?;
6980            }
6981
6982            // Build only the probe maps required by the selected join direction.
6983            let right_map = if matches!(
6984                join_type,
6985                JoinType::Inner | JoinType::Left | JoinType::Outer
6986            ) {
6987                let mut m =
6988                    FxHashMap::<&CompositeJoinKey, JoinPositionBucket>::with_capacity_and_hasher(
6989                        right_keys.len(),
6990                        Default::default(),
6991                    );
6992                for (pos, key) in right_keys.iter().enumerate() {
6993                    m.entry(key).or_default().push(pos);
6994                }
6995                Some(m)
6996            } else {
6997                None
6998            };
6999
7000            let left_map = if matches!(join_type, JoinType::Right | JoinType::Outer) {
7001                let mut m =
7002                    FxHashMap::<&CompositeJoinKey, JoinPositionBucket>::with_capacity_and_hasher(
7003                        left_keys.len(),
7004                        Default::default(),
7005                    );
7006                for (pos, key) in left_keys.iter().enumerate() {
7007                    m.entry(key).or_default().push(pos);
7008                }
7009                Some(m)
7010            } else {
7011                None
7012            };
7013
7014            // Compute row position mappings.
7015            let row_capacity = match join_type {
7016                JoinType::Inner => left_keys.len().min(right_keys.len()),
7017                JoinType::Left => left_keys.len(),
7018                JoinType::Right => right_keys.len(),
7019                JoinType::Outer => left_keys.len().saturating_add(right_keys.len()),
7020                JoinType::Cross => left_keys.len().saturating_mul(right_keys.len()),
7021            };
7022            let mut left_positions = Vec::<Option<usize>>::with_capacity(row_capacity);
7023            let mut right_positions = Vec::<Option<usize>>::with_capacity(row_capacity);
7024            let mut out_row_keys =
7025                needs_key_order.then(|| Vec::<CompositeJoinKey>::with_capacity(row_capacity));
7026
7027            match join_type {
7028                JoinType::Inner | JoinType::Left | JoinType::Outer => {
7029                    let right_map = right_map
7030                        .as_ref()
7031                        .expect("right_map required for Inner, Left, and Outer joins");
7032                    for (left_pos, key) in left_keys.iter().enumerate() {
7033                        if let Some(matches) = right_map.get(key) {
7034                            for &right_pos in matches {
7035                                push_merge_row_key(&mut out_row_keys, key);
7036                                left_positions.push(Some(left_pos));
7037                                right_positions.push(Some(right_pos));
7038                            }
7039                            continue;
7040                        }
7041
7042                        if matches!(join_type, JoinType::Left | JoinType::Outer) {
7043                            push_merge_row_key(&mut out_row_keys, key);
7044                            left_positions.push(Some(left_pos));
7045                            right_positions.push(None);
7046                        }
7047                    }
7048
7049                    if matches!(join_type, JoinType::Outer) {
7050                        let left_map = left_map.as_ref().expect("left_map required for Outer join");
7051                        for (right_pos, key) in right_keys.iter().enumerate() {
7052                            if !left_map.contains_key(key) {
7053                                push_merge_row_key(&mut out_row_keys, key);
7054                                left_positions.push(None);
7055                                right_positions.push(Some(right_pos));
7056                            }
7057                        }
7058                    }
7059                }
7060                JoinType::Right => {
7061                    let left_map = left_map.as_ref().expect("left_map required for Right join");
7062                    for (right_pos, key) in right_keys.iter().enumerate() {
7063                        if let Some(matches) = left_map.get(key) {
7064                            for &left_pos in matches {
7065                                push_merge_row_key(&mut out_row_keys, key);
7066                                left_positions.push(Some(left_pos));
7067                                right_positions.push(Some(right_pos));
7068                            }
7069                            continue;
7070                        }
7071
7072                        push_merge_row_key(&mut out_row_keys, key);
7073                        left_positions.push(None);
7074                        right_positions.push(Some(right_pos));
7075                    }
7076                }
7077                JoinType::Cross => {
7078                    return Err(JoinError::Frame(FrameError::CompatibilityRejected(
7079                        "cross join must be handled by merge_dataframes_cross".to_owned(),
7080                    )));
7081                }
7082            }
7083
7084            (left_positions, right_positions, out_row_keys)
7085        };
7086
7087    if needs_key_order {
7088        let out_row_keys = out_row_keys
7089            .as_ref()
7090            .expect("merge row keys required when sorting output rows");
7091        sort_merge_rows_by_join_keys(out_row_keys, &mut left_positions, &mut right_positions);
7092    }
7093
7094    let all_positions_present = matches!(join_type, JoinType::Inner)
7095        || (matches!(
7096            join_type,
7097            JoinType::Left | JoinType::Right | JoinType::Outer
7098        ) && left_positions.iter().all(Option::is_some)
7099            && right_positions.iter().all(Option::is_some));
7100    let all_present_take_positions = all_positions_present.then(|| {
7101        let left = left_positions
7102            .iter()
7103            .map(|position| position.expect("all-present join emits left positions for every row"))
7104            .collect::<Vec<_>>();
7105        let right = right_positions
7106            .iter()
7107            .map(|position| position.expect("all-present join emits right positions for every row"))
7108            .collect::<Vec<_>>();
7109        (left, right)
7110    });
7111    let all_present_left_positions = all_present_take_positions
7112        .as_ref()
7113        .map(|(positions, _)| positions.as_slice());
7114    let all_present_right_positions = all_present_take_positions
7115        .as_ref()
7116        .map(|(_, positions)| positions.as_slice());
7117
7118    // Build output columns by reindexing.
7119    let n = left_positions.len();
7120    // Lazy unit-range output index (see build_single_key_dense_i64 site).
7121    let index = Index::new_known_unique_int64_unit_range(0, n);
7122    let mut columns = std::collections::BTreeMap::new();
7123    let mut column_order: Vec<String> = Vec::new();
7124
7125    // Collect column names to handle conflicts.
7126    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
7127    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
7128    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
7129    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
7130
7131    // Track positional pairs where left_on[i] and right_on[i] share the same key name.
7132    let mut shared_name_positions = HashMap::<&str, (usize, usize)>::new();
7133    for (idx, (left_key_name, right_key_name)) in left_on.iter().zip(right_on.iter()).enumerate() {
7134        if left_key_name == right_key_name {
7135            shared_name_positions.insert(*left_key_name, (idx, idx));
7136        }
7137    }
7138    let shared_key_names = shared_name_positions
7139        .keys()
7140        .copied()
7141        .collect::<HashSet<&str>>();
7142    let overlapping_names =
7143        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
7144    ensure_merge_suffixes_for_overlaps(&overlapping_names, &suffixes)?;
7145
7146    // Add left columns (including left key columns) in the left frame's own
7147    // column order (pandas preserves it; the BTreeMap would re-sort) — br-691lh.
7148    for name in left.column_names() {
7149        let col = left
7150            .columns()
7151            .get(name)
7152            .expect("left column listed in column_names must exist");
7153        if left_key_name_set.contains(name.as_str()) {
7154            if let Some((left_key_idx, right_key_idx)) = shared_name_positions.get(name.as_str()) {
7155                // Shared key name: for rows emitted from right-only keys, source key values from
7156                // the right frame instead of leaving them null.
7157                let left_key_col = left_key_columns[*left_key_idx];
7158                let key_column = if let Some(positions) = all_present_left_positions {
7159                    take_positions_typed(left_key_col, positions)
7160                } else {
7161                    let right_key_col = right_key_columns[*right_key_idx];
7162                    let values = left_positions
7163                        .iter()
7164                        .zip(right_positions.iter())
7165                        .map(|(left_pos, right_pos)| match (left_pos, right_pos) {
7166                            (Some(pos), _) => left_key_col.values()[*pos].clone(),
7167                            (None, Some(pos)) => right_key_col.values()[*pos].clone(),
7168                            (None, None) => fp_types::Scalar::Null(fp_types::NullKind::Null),
7169                        })
7170                        .collect::<Vec<_>>();
7171                    Column::from_values(values)?
7172                };
7173                insert_merged_output_column(
7174                    &mut columns,
7175                    &mut column_order,
7176                    name.clone(),
7177                    key_column,
7178                )?;
7179            } else {
7180                let key_column = if let Some(positions) = all_present_left_positions {
7181                    take_positions_typed(col, positions)
7182                } else if matches!(join_type, JoinType::Outer) {
7183                    reindex_outer_join_column(col, &left_positions)?
7184                } else {
7185                    col.reindex_by_positions(&left_positions)?
7186                };
7187                insert_merged_output_column(
7188                    &mut columns,
7189                    &mut column_order,
7190                    name.clone(),
7191                    key_column,
7192                )?;
7193            }
7194            continue;
7195        }
7196        let reindexed = if let Some(positions) = all_present_left_positions {
7197            take_positions_typed(col, positions)
7198        } else if matches!(join_type, JoinType::Outer) {
7199            reindex_outer_join_column(col, &left_positions)?
7200        } else {
7201            col.reindex_by_positions(&left_positions)?
7202        };
7203        let out_name = if right_col_names.contains(name) {
7204            apply_merge_suffix(name, suffixes.left.as_deref())
7205        } else {
7206            name.clone()
7207        };
7208        insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
7209    }
7210
7211    // Add right non-key columns in the right frame's own column order — br-691lh.
7212    for name in right.column_names() {
7213        let col = right
7214            .columns()
7215            .get(name)
7216            .expect("right column listed in column_names must exist");
7217        if right_key_name_set.contains(name.as_str())
7218            && shared_name_positions.contains_key(name.as_str())
7219        {
7220            // Shared same-name key already emitted from the left side.
7221            continue;
7222        }
7223        let reindexed = if let Some(positions) = all_present_right_positions {
7224            take_positions_typed(col, positions)
7225        } else if matches!(join_type, JoinType::Outer) {
7226            reindex_outer_join_column(col, &right_positions)?
7227        } else {
7228            col.reindex_by_positions(&right_positions)?
7229        };
7230        let out_name = if left_col_names.contains(name) {
7231            apply_merge_suffix(name, suffixes.right.as_deref())
7232        } else {
7233            name.clone()
7234        };
7235        insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
7236    }
7237
7238    if let Some(indicator_name) = indicator_name.as_deref() {
7239        ensure_indicator_name_available(
7240            indicator_name,
7241            &left_col_names,
7242            &right_col_names,
7243            &columns,
7244        )?;
7245        let indicator_col = build_merge_indicator_column(&left_positions, &right_positions)?;
7246        insert_merged_output_column(
7247            &mut columns,
7248            &mut column_order,
7249            indicator_name.to_owned(),
7250            indicator_col,
7251        )?;
7252    }
7253
7254    Ok(MergedDataFrame {
7255        index,
7256        columns,
7257        column_order,
7258    })
7259}
7260
7261/// Merge two DataFrames on one or more key columns with identical key names.
7262///
7263/// Matches `pd.merge(left, right, on=keys, how=join_type)`.
7264pub fn merge_dataframes_on(
7265    left: &fp_frame::DataFrame,
7266    right: &fp_frame::DataFrame,
7267    on: &[&str],
7268    join_type: JoinType,
7269) -> Result<MergedDataFrame, JoinError> {
7270    merge_dataframes_on_with(left, right, on, on, join_type)
7271}
7272
7273/// Merge two DataFrames on a single key column.
7274pub fn merge_dataframes(
7275    left: &fp_frame::DataFrame,
7276    right: &fp_frame::DataFrame,
7277    on: &str,
7278    join_type: JoinType,
7279) -> Result<MergedDataFrame, JoinError> {
7280    if matches!(join_type, JoinType::Inner) {
7281        let left_key = left.column(on).ok_or_else(|| {
7282            JoinError::Frame(FrameError::CompatibilityRejected(format!(
7283                "left DataFrame missing key column '{on}'"
7284            )))
7285        })?;
7286        let right_key = right.column(on).ok_or_else(|| {
7287            JoinError::Frame(FrameError::CompatibilityRejected(format!(
7288                "right DataFrame missing key column '{on}'"
7289            )))
7290        })?;
7291        let suffixes = ResolvedMergeSuffixes::default();
7292        return merge_single_key_inner_unsorted(
7293            left,
7294            right,
7295            &[on],
7296            &[on],
7297            &[left_key],
7298            &[right_key],
7299            &suffixes,
7300        );
7301    }
7302    merge_dataframes_on(left, right, &[on], join_type)
7303}
7304
7305fn merge_dataframes_cross(
7306    left: &fp_frame::DataFrame,
7307    right: &fp_frame::DataFrame,
7308    indicator_name: Option<&str>,
7309    suffixes: &ResolvedMergeSuffixes,
7310) -> Result<MergedDataFrame, JoinError> {
7311    let left_rows = left.index().len();
7312    let right_rows = right.index().len();
7313    let out_rows = left_rows.saturating_mul(right_rows);
7314
7315    let mut left_positions = Vec::<Option<usize>>::with_capacity(out_rows);
7316    let mut right_positions = Vec::<Option<usize>>::with_capacity(out_rows);
7317    for left_pos in 0..left_rows {
7318        for right_pos in 0..right_rows {
7319            left_positions.push(Some(left_pos));
7320            right_positions.push(Some(right_pos));
7321        }
7322    }
7323
7324    let index = Index::new((0..out_rows as i64).map(IndexLabel::from).collect());
7325    let mut columns = std::collections::BTreeMap::new();
7326    let mut column_order: Vec<String> = Vec::new();
7327
7328    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
7329    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
7330    let overlapping_names =
7331        collect_overlapping_column_names(&left_col_names, &right_col_names, &HashSet::new());
7332    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
7333
7334    for (name, col) in left.columns() {
7335        let reindexed = col.reindex_by_positions(&left_positions)?;
7336        let out_name = if right_col_names.contains(name) {
7337            apply_merge_suffix(name, suffixes.left.as_deref())
7338        } else {
7339            name.clone()
7340        };
7341        insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
7342    }
7343
7344    for (name, col) in right.columns() {
7345        let reindexed = col.reindex_by_positions(&right_positions)?;
7346        let out_name = if left_col_names.contains(name) {
7347            apply_merge_suffix(name, suffixes.right.as_deref())
7348        } else {
7349            name.clone()
7350        };
7351        insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
7352    }
7353
7354    if let Some(indicator_name) = indicator_name {
7355        ensure_indicator_name_available(
7356            indicator_name,
7357            &left_col_names,
7358            &right_col_names,
7359            &columns,
7360        )?;
7361        let indicator_col = build_merge_indicator_column(&left_positions, &right_positions)?;
7362        insert_merged_output_column(
7363            &mut columns,
7364            &mut column_order,
7365            indicator_name.to_owned(),
7366            indicator_col,
7367        )?;
7368    }
7369
7370    Ok(MergedDataFrame {
7371        index,
7372        columns,
7373        column_order,
7374    })
7375}
7376
7377/// Extension trait adding `.merge()` and `.join()` instance methods to `DataFrame`.
7378///
7379/// Import this trait to get pandas-style `df.merge(other, ...)` and `df.join(other, ...)`
7380/// as instance methods.
7381pub trait DataFrameMergeExt {
7382    /// Merge this DataFrame with another on shared key columns.
7383    ///
7384    /// Matches `pd.DataFrame.merge(other, on=keys, how=join_type)`.
7385    fn merge(
7386        &self,
7387        other: &fp_frame::DataFrame,
7388        on: &[&str],
7389        how: JoinType,
7390    ) -> Result<MergedDataFrame, JoinError>;
7391
7392    /// Merge with separate left/right key columns and execution options.
7393    ///
7394    /// Matches `pd.DataFrame.merge(other, left_on=..., right_on=..., how=...)`.
7395    fn merge_with_options(
7396        &self,
7397        other: &fp_frame::DataFrame,
7398        left_on: &[&str],
7399        right_on: &[&str],
7400        how: JoinType,
7401        options: MergeExecutionOptions,
7402    ) -> Result<MergedDataFrame, JoinError>;
7403
7404    /// Join another DataFrame on the index.
7405    ///
7406    /// Matches `pd.DataFrame.join(other, how=join_type)` (index-based join).
7407    fn join_on_index(
7408        &self,
7409        other: &fp_frame::DataFrame,
7410        how: JoinType,
7411    ) -> Result<MergedDataFrame, JoinError>;
7412
7413    /// pandas-named alias for [`Self::join_on_index`]. Matches
7414    /// `pd.DataFrame.join(other, how=...)` directly. Per br-frankenpandas-nk54a.
7415    ///
7416    /// Default impl delegates to `join_on_index`. Implementors that already
7417    /// have an optimized index-based join can leave this default.
7418    fn join(
7419        &self,
7420        other: &fp_frame::DataFrame,
7421        how: JoinType,
7422    ) -> Result<MergedDataFrame, JoinError> {
7423        self.join_on_index(other, how)
7424    }
7425
7426    /// Perform an asof merge (nearest-match join) on a sorted key column.
7427    ///
7428    /// Matches `pd.merge_asof(left, right, on=key)`. Both DataFrames must
7429    /// be sorted by the key column. For each row in `left`, finds the last
7430    /// row in `right` where `right[on] <= left[on]` (backward direction)
7431    /// or the nearest row in the specified direction.
7432    ///
7433    /// `direction`: "backward" (default), "forward", "nearest".
7434    fn merge_asof(
7435        &self,
7436        other: &fp_frame::DataFrame,
7437        on: &str,
7438        direction: &str,
7439    ) -> Result<MergedDataFrame, JoinError>;
7440
7441    /// Perform an asof merge with additional options.
7442    ///
7443    /// Matches `pd.merge_asof(left, right, on=key, direction=...,
7444    /// allow_exact_matches=..., tolerance=..., by=...)`.
7445    ///
7446    /// # Parameters
7447    /// - `other`: Right DataFrame to merge with
7448    /// - `on`: Column name to merge on (must be numeric and sorted)
7449    /// - `direction`: "backward", "forward", or "nearest"
7450    /// - `options`: Additional options (allow_exact_matches, tolerance, by)
7451    fn merge_asof_with_options(
7452        &self,
7453        other: &fp_frame::DataFrame,
7454        on: &str,
7455        direction: &str,
7456        options: MergeAsofOptions,
7457    ) -> Result<MergedDataFrame, JoinError>;
7458
7459    /// Perform an ordered merge (outer join + sort by keys).
7460    ///
7461    /// Matches `pd.merge_ordered(left, right, on=keys, fill_method=...)`.
7462    fn merge_ordered(
7463        &self,
7464        other: &fp_frame::DataFrame,
7465        on: &[&str],
7466        fill_method: Option<&str>,
7467    ) -> Result<MergedDataFrame, JoinError>;
7468}
7469
7470/// Perform an ordered merge of two DataFrames.
7471///
7472/// Matches `pd.merge_ordered(left, right, on=keys, fill_method=...)`.
7473/// Performs an outer join and ensures the result is sorted by the join keys.
7474pub fn merge_ordered(
7475    left: &fp_frame::DataFrame,
7476    right: &fp_frame::DataFrame,
7477    on: &[&str],
7478    fill_method: Option<&str>,
7479) -> Result<MergedDataFrame, JoinError> {
7480    let options = MergeExecutionOptions {
7481        sort: true,
7482        ..MergeExecutionOptions::default()
7483    };
7484    let merged = merge_dataframes_on_with_options(left, right, on, on, JoinType::Outer, options)?;
7485
7486    if let Some(method) = fill_method {
7487        // Convert to DataFrame to apply fill
7488        let mut df = fp_frame::DataFrame::new_with_column_order(
7489            merged.index.clone(),
7490            merged.columns.clone(),
7491            merged.column_order.clone(),
7492        )
7493        .map_err(JoinError::Frame)?;
7494
7495        df = match method {
7496            "ffill" => df.ffill(None).map_err(JoinError::Frame)?,
7497            _ => {
7498                return Err(JoinError::Frame(FrameError::CompatibilityRejected(
7499                    format!("merge_ordered: fill_method must be 'ffill' or None, got '{method}'"),
7500                )));
7501            }
7502        };
7503
7504        let column_order = df.column_names().into_iter().cloned().collect();
7505        Ok(MergedDataFrame {
7506            index: df.index().clone(),
7507            columns: df.columns().clone(),
7508            column_order,
7509        })
7510    } else {
7511        Ok(merged)
7512    }
7513}
7514
7515/// Direction for asof merge matching.
7516#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7517pub enum AsofDirection {
7518    Backward,
7519    Forward,
7520    Nearest,
7521}
7522
7523/// Options for asof merge operations.
7524///
7525/// Matches pandas `merge_asof` parameters:
7526/// - `allow_exact_matches`: If true (default), allow matching with same key value
7527/// - `tolerance`: Maximum distance between keys for a match
7528/// - `by`: Columns to match exactly before asof matching
7529#[derive(Debug, Clone, Default)]
7530pub struct MergeAsofOptions {
7531    /// If true (default), allow matching with the same 'on' value.
7532    /// If false, don't match rows where left key == right key exactly.
7533    pub allow_exact_matches: bool,
7534    /// Maximum distance between left and right keys for a valid match.
7535    /// None means no tolerance limit.
7536    pub tolerance: Option<f64>,
7537    /// Columns to match exactly before performing asof merge.
7538    /// Acts like an equi-join on these columns first.
7539    pub by: Option<Vec<String>>,
7540}
7541
7542impl MergeAsofOptions {
7543    /// Create options with defaults matching pandas behavior.
7544    pub fn new() -> Self {
7545        Self {
7546            allow_exact_matches: true,
7547            tolerance: None,
7548            by: None,
7549        }
7550    }
7551
7552    /// Set whether exact matches are allowed.
7553    pub fn allow_exact_matches(mut self, allow: bool) -> Self {
7554        self.allow_exact_matches = allow;
7555        self
7556    }
7557
7558    /// Set the tolerance for matching.
7559    pub fn tolerance(mut self, tol: f64) -> Self {
7560        self.tolerance = Some(tol);
7561        self
7562    }
7563
7564    /// Set the columns to match exactly before asof merge.
7565    pub fn by(mut self, cols: Vec<String>) -> Self {
7566        self.by = Some(cols);
7567        self
7568    }
7569}
7570
7571fn asof_numeric_values(column: &Column, side: &str, on: &str) -> Result<Vec<f64>, JoinError> {
7572    let mut out = Vec::with_capacity(column.len());
7573    for value in column.values() {
7574        // pandas merge_asof accepts Timedelta64 (and datetime) `on` columns
7575        // and orders them by ns count. Scalar::Timedelta64.to_f64() returns
7576        // NonNumericValue, so the default branch would reject the join.
7577        // Extract ns directly for non-NaT Timedelta values; treat NaT as NaN
7578        // (matches the ValueIsMissing arm below).
7579        if let Scalar::Timedelta64(ns) = value {
7580            if *ns == fp_types::Timedelta::NAT {
7581                out.push(f64::NAN);
7582            } else {
7583                out.push(*ns as f64);
7584            }
7585            continue;
7586        }
7587        match value.to_f64() {
7588            Ok(v) => out.push(v),
7589            Err(TypeError::ValueIsMissing { .. }) => out.push(f64::NAN),
7590            Err(_) => {
7591                return Err(JoinError::Frame(FrameError::CompatibilityRejected(
7592                    format!("merge_asof: {side} column '{on}' must be numeric"),
7593                )));
7594            }
7595        }
7596    }
7597    Ok(out)
7598}
7599
7600fn ensure_sorted_non_decreasing(values: &[f64], side: &str, on: &str) -> Result<(), JoinError> {
7601    let mut prev: Option<f64> = None;
7602    for &value in values {
7603        if value.is_nan() {
7604            continue;
7605        }
7606        if let Some(prev_value) = prev
7607            && value < prev_value
7608        {
7609            return Err(JoinError::Frame(FrameError::CompatibilityRejected(
7610                format!("merge_asof: {side} column '{on}' must be sorted"),
7611            )));
7612        }
7613        prev = Some(value);
7614    }
7615    Ok(())
7616}
7617
7618/// Perform an asof merge between two DataFrames.
7619pub fn merge_asof(
7620    left: &fp_frame::DataFrame,
7621    right: &fp_frame::DataFrame,
7622    on: &str,
7623    direction: AsofDirection,
7624) -> Result<MergedDataFrame, JoinError> {
7625    merge_asof_with_options(left, right, on, direction, MergeAsofOptions::new())
7626}
7627
7628/// Perform an asof merge between two DataFrames with additional options.
7629///
7630/// # Parameters
7631/// - `left`: Left DataFrame
7632/// - `right`: Right DataFrame
7633/// - `on`: Column name to merge on (must be numeric and sorted)
7634/// - `direction`: Match direction (Backward, Forward, Nearest)
7635/// - `options`: Additional merge options (allow_exact_matches, tolerance, by)
7636pub fn merge_asof_with_options(
7637    left: &fp_frame::DataFrame,
7638    right: &fp_frame::DataFrame,
7639    on: &str,
7640    direction: AsofDirection,
7641    options: MergeAsofOptions,
7642) -> Result<MergedDataFrame, JoinError> {
7643    // If `by` columns are specified, we need to do grouped asof merge
7644    if let Some(ref by_cols) = options.by {
7645        return merge_asof_grouped(left, right, on, direction, &options, by_cols);
7646    }
7647
7648    merge_asof_simple(left, right, on, direction, &options)
7649}
7650
7651/// Simple asof merge without grouping.
7652fn merge_asof_simple(
7653    left: &fp_frame::DataFrame,
7654    right: &fp_frame::DataFrame,
7655    on: &str,
7656    direction: AsofDirection,
7657    options: &MergeAsofOptions,
7658) -> Result<MergedDataFrame, JoinError> {
7659    let left_key = left.columns().get(on).ok_or_else(|| {
7660        JoinError::Frame(FrameError::CompatibilityRejected(format!(
7661            "merge_asof: column '{on}' not found in left"
7662        )))
7663    })?;
7664    let right_key = right.columns().get(on).ok_or_else(|| {
7665        JoinError::Frame(FrameError::CompatibilityRejected(format!(
7666            "merge_asof: column '{on}' not found in right"
7667        )))
7668    })?;
7669
7670    let left_vals = asof_numeric_values(left_key, "left", on)?;
7671    let right_vals = asof_numeric_values(right_key, "right", on)?;
7672
7673    // pandas pd.merge_asof accepts NaN keys: the NaN row gets a null in
7674    // the joined columns (no match). The strict "reject null keys" check
7675    // previously enforced here diverged from the FP-P2D-056 oracle.
7676    ensure_sorted_non_decreasing(&left_vals, "left", on)?;
7677    ensure_sorted_non_decreasing(&right_vals, "right", on)?;
7678
7679    let right_matches = compute_asof_matches(
7680        &left_vals,
7681        &right_vals,
7682        direction,
7683        options.allow_exact_matches,
7684        options.tolerance,
7685    );
7686
7687    build_asof_output(left, right, on, &right_matches, None)
7688}
7689
7690/// Grouped asof merge: match on `by` columns first, then asof within groups.
7691fn merge_asof_grouped(
7692    left: &fp_frame::DataFrame,
7693    right: &fp_frame::DataFrame,
7694    on: &str,
7695    direction: AsofDirection,
7696    options: &MergeAsofOptions,
7697    by_cols: &[String],
7698) -> Result<MergedDataFrame, JoinError> {
7699    // Validate by columns exist
7700    for col in by_cols {
7701        if left.columns().get(col).is_none() {
7702            return Err(JoinError::Frame(FrameError::CompatibilityRejected(
7703                format!("merge_asof: 'by' column '{col}' not found in left"),
7704            )));
7705        }
7706        if right.columns().get(col).is_none() {
7707            return Err(JoinError::Frame(FrameError::CompatibilityRejected(
7708                format!("merge_asof: 'by' column '{col}' not found in right"),
7709            )));
7710        }
7711    }
7712
7713    let left_key = left.columns().get(on).ok_or_else(|| {
7714        JoinError::Frame(FrameError::CompatibilityRejected(format!(
7715            "merge_asof: column '{on}' not found in left"
7716        )))
7717    })?;
7718    let right_key = right.columns().get(on).ok_or_else(|| {
7719        JoinError::Frame(FrameError::CompatibilityRejected(format!(
7720            "merge_asof: column '{on}' not found in right"
7721        )))
7722    })?;
7723
7724    let left_vals = asof_numeric_values(left_key, "left", on)?;
7725    let right_vals = asof_numeric_values(right_key, "right", on)?;
7726
7727    // pandas pd.merge_asof accepts NaN keys: the NaN row gets a null in
7728    // the joined columns (no match). The strict "reject null keys" check
7729    // previously enforced here diverged from the FP-P2D-056 oracle.
7730    ensure_sorted_non_decreasing(&left_vals, "left", on)?;
7731    ensure_sorted_non_decreasing(&right_vals, "right", on)?;
7732
7733    // Dense u32 group ids over the `by` columns (shared id space for left and
7734    // right). The single non-float `by` column case factorizes the column's
7735    // scalars with a borrowed typed key — no per-row `format!`/`Vec<String>`
7736    // allocation — and is bit-identical to the Debug-string grouping (see
7737    // `build_group_ids`). Everything else falls back to the string path.
7738    let (left_ids, right_ids) = build_group_ids(left, right, by_cols)?;
7739
7740    // Group right rows by their `by` group id for asof matching (looked up by
7741    // `.get()` per left group below). No per-group sort validation is needed:
7742    // the global `ensure_sorted_non_decreasing` checks above already require the
7743    // `on` column to be non-decreasing over the whole frame, and every
7744    // per-group subsequence of a sorted column is itself sorted — so the old
7745    // per-group checks were unreachable (the global check fires first on any
7746    // unsorted input). FxHashMap (vs std SipHash) speeds the build.
7747    let mut right_groups: FxHashMap<u32, Vec<usize>> = FxHashMap::default();
7748    for (idx, &id) in right_ids.iter().enumerate() {
7749        right_groups.entry(id).or_default().push(idx);
7750    }
7751
7752    // Group LEFT rows by their `by` group id (preserving the globally-sorted
7753    // order within each group), then run the monotonic two-pointer asof sweep
7754    // ONCE per group over all of the group's left values — instead of rebuilding
7755    // the group's right-value vector and re-scanning it from scratch for every
7756    // individual left row (the old O(L·R) per group). compute_asof_matches
7757    // already drives a single left array with a monotonic cursor and handles
7758    // NaN left keys (→ None, cursor unchanged); because every per-group left
7759    // subsequence is sorted (the global `on` column is non-decreasing), the
7760    // grouped sweep yields the identical match for each left row as the old
7761    // fresh-per-row scan. Results are scattered by absolute left index, so the
7762    // output order is independent of group-iteration order.
7763    let mut left_groups: FxHashMap<u32, Vec<usize>> = FxHashMap::default();
7764    for (left_idx, &id) in left_ids.iter().enumerate() {
7765        left_groups.entry(id).or_default().push(left_idx);
7766    }
7767
7768    let mut right_matches: Vec<Option<usize>> = vec![None; left_vals.len()];
7769    for (group_id, left_positions) in &left_groups {
7770        let Some(group_indices) = right_groups.get(group_id) else {
7771            continue; // no right rows for this group -> all matches stay None
7772        };
7773        let group_right_vals: Vec<f64> = group_indices.iter().map(|&i| right_vals[i]).collect();
7774        let group_left_vals: Vec<f64> = left_positions.iter().map(|&i| left_vals[i]).collect();
7775
7776        let group_matches = compute_asof_matches(
7777            &group_left_vals,
7778            &group_right_vals,
7779            direction,
7780            options.allow_exact_matches,
7781            options.tolerance,
7782        );
7783
7784        for (k, &left_idx) in left_positions.iter().enumerate() {
7785            if let Some(Some(group_idx)) = group_matches.get(k) {
7786                right_matches[left_idx] = Some(group_indices[*group_idx]);
7787            }
7788        }
7789    }
7790
7791    build_asof_output(left, right, on, &right_matches, Some(by_cols))
7792}
7793
7794/// Borrowed, allocation-free `by`-key for the single-column factorize fast
7795/// path. Each variant is the typed payload of a `Scalar` whose *derived*
7796/// `Debug` is injective and equality-consistent — so two scalars share a
7797/// `ByKey` iff their `format!("{val:?}")` strings (the legacy group key) are
7798/// equal. `Float64` (`-0.0` vs `0.0`, `NaN`) and `Interval` Debug strings
7799/// disagree with value equality, so `from_scalar` returns `None` for them and
7800/// the caller falls back to the string path.
7801#[derive(PartialEq, Eq, Hash)]
7802enum ByKey<'a> {
7803    Null(u8),
7804    Bool(bool),
7805    Int(i64),
7806    Str(&'a str),
7807    Timedelta(i64),
7808    Datetime(i64),
7809    Period(i64),
7810}
7811
7812impl<'a> ByKey<'a> {
7813    fn from_scalar(s: &'a Scalar) -> Option<Self> {
7814        Some(match s {
7815            Scalar::Null(NullKind::Null) => ByKey::Null(0),
7816            Scalar::Null(NullKind::NaN) => ByKey::Null(1),
7817            Scalar::Null(NullKind::NaT) => ByKey::Null(2),
7818            Scalar::Bool(b) => ByKey::Bool(*b),
7819            Scalar::Int64(v) => ByKey::Int(*v),
7820            Scalar::Utf8(s) => ByKey::Str(s.as_str()),
7821            Scalar::Timedelta64(v) => ByKey::Timedelta(*v),
7822            Scalar::Datetime64(v) => ByKey::Datetime(*v),
7823            Scalar::Period(v) => ByKey::Period(v.ordinal),
7824            Scalar::Float64(_) | Scalar::Interval(_) => return None,
7825        })
7826    }
7827}
7828
7829/// Factorize a single `by` column over both frames into a shared u32 id space.
7830/// Returns `None` (caller falls back to the string path) if any value is a
7831/// `Float64`/`Interval` whose Debug string would not agree with typed equality.
7832fn try_factorize_typed<'a>(
7833    left: &'a [Scalar],
7834    right: &'a [Scalar],
7835) -> Option<(Vec<u32>, Vec<u32>)> {
7836    let mut codes: FxHashMap<ByKey<'a>, u32> = FxHashMap::default();
7837    let mut next = 0u32;
7838    let mut left_ids = Vec::with_capacity(left.len());
7839    for v in left {
7840        let id = *codes.entry(ByKey::from_scalar(v)?).or_insert_with(|| {
7841            let i = next;
7842            next += 1;
7843            i
7844        });
7845        left_ids.push(id);
7846    }
7847    let mut right_ids = Vec::with_capacity(right.len());
7848    for v in right {
7849        let id = *codes.entry(ByKey::from_scalar(v)?).or_insert_with(|| {
7850            let i = next;
7851            next += 1;
7852            i
7853        });
7854        right_ids.push(id);
7855    }
7856    Some((left_ids, right_ids))
7857}
7858
7859/// Build dense u32 group ids for the left and right frames over the `by`
7860/// columns, sharing one id space. Returns `(left_ids, right_ids)`.
7861///
7862/// Fast path (a single non-float `by` column): factorize the column's scalars
7863/// directly with the borrowed typed [`ByKey`] — zero per-row string formatting
7864/// or allocation. Bit-identical to the `format!("{val:?}")` grouping because
7865/// the typed key induces the exact same equality classes. Multi-column or
7866/// float/interval `by` keys route to the original Debug-string builder, whose
7867/// per-row composite keys are then interned to u32 (one clone per *distinct*
7868/// group, not per row).
7869fn build_group_ids(
7870    left: &fp_frame::DataFrame,
7871    right: &fp_frame::DataFrame,
7872    by_cols: &[String],
7873) -> Result<(Vec<u32>, Vec<u32>), JoinError> {
7874    if by_cols.len() == 1
7875        && let (Some(lcol), Some(rcol)) = (
7876            left.columns().get(&by_cols[0]),
7877            right.columns().get(&by_cols[0]),
7878        )
7879        && let Some(ids) = try_factorize_typed(lcol.values(), rcol.values())
7880    {
7881        return Ok(ids);
7882    }
7883
7884    let left_keys = build_group_keys(left, by_cols)?;
7885    let right_keys = build_group_keys(right, by_cols)?;
7886    let mut codes: FxHashMap<Vec<String>, u32> = FxHashMap::default();
7887    let mut next = 0u32;
7888    let mut intern = |k: &Vec<String>, codes: &mut FxHashMap<Vec<String>, u32>| -> u32 {
7889        if let Some(&id) = codes.get(k) {
7890            id
7891        } else {
7892            let id = next;
7893            next += 1;
7894            codes.insert(k.clone(), id);
7895            id
7896        }
7897    };
7898    let left_ids = left_keys.iter().map(|k| intern(k, &mut codes)).collect();
7899    let right_ids = right_keys.iter().map(|k| intern(k, &mut codes)).collect();
7900    Ok((left_ids, right_ids))
7901}
7902
7903/// Build group keys from the `by` columns.
7904fn build_group_keys(
7905    df: &fp_frame::DataFrame,
7906    by_cols: &[String],
7907) -> Result<Vec<Vec<String>>, JoinError> {
7908    let n = df.len();
7909    let mut keys = vec![Vec::with_capacity(by_cols.len()); n];
7910
7911    for col_name in by_cols {
7912        let col = df.columns().get(col_name).ok_or_else(|| {
7913            JoinError::Frame(FrameError::CompatibilityRejected(format!(
7914                "merge_asof: column '{col_name}' not found"
7915            )))
7916        })?;
7917        for (i, val) in col.values().iter().enumerate() {
7918            keys[i].push(format!("{val:?}"));
7919        }
7920    }
7921
7922    Ok(keys)
7923}
7924
7925/// Compute asof matches for a single group or the whole dataset.
7926fn compute_asof_matches(
7927    left_vals: &[f64],
7928    right_vals: &[f64],
7929    direction: AsofDirection,
7930    allow_exact_matches: bool,
7931    tolerance: Option<f64>,
7932) -> Vec<Option<usize>> {
7933    let mut right_non_nan_values = Vec::new();
7934    let mut right_non_nan_positions = Vec::new();
7935    for (pos, &rv) in right_vals.iter().enumerate() {
7936        if !rv.is_nan() {
7937            right_non_nan_values.push(rv);
7938            right_non_nan_positions.push(pos);
7939        }
7940    }
7941
7942    let mut right_matches: Vec<Option<usize>> = Vec::with_capacity(left_vals.len());
7943
7944    match direction {
7945        AsofDirection::Backward => {
7946            let mut best: Option<usize> = None;
7947            let mut best_val: Option<f64> = None;
7948            let mut j = 0usize;
7949            for &lv in left_vals {
7950                if lv.is_nan() {
7951                    right_matches.push(None);
7952                    continue;
7953                }
7954                // Advance while right <= left (or right < left if !allow_exact_matches)
7955                while j < right_non_nan_values.len() {
7956                    let rv = right_non_nan_values[j];
7957                    let should_include = if allow_exact_matches {
7958                        rv <= lv
7959                    } else {
7960                        rv < lv
7961                    };
7962                    if !should_include {
7963                        break;
7964                    }
7965                    best = Some(right_non_nan_positions[j]);
7966                    best_val = Some(rv);
7967                    j += 1;
7968                }
7969
7970                // Check tolerance
7971                let matched = match (best, best_val, tolerance) {
7972                    (Some(idx), Some(rv), Some(tol)) if (lv - rv).abs() <= tol => Some(idx),
7973                    (Some(idx), _, None) => Some(idx),
7974                    _ => None,
7975                };
7976                right_matches.push(matched);
7977            }
7978        }
7979        AsofDirection::Forward => {
7980            let mut j = 0usize;
7981            for &lv in left_vals {
7982                if lv.is_nan() {
7983                    right_matches.push(None);
7984                    continue;
7985                }
7986                // Advance while right < left (or right <= left if !allow_exact_matches)
7987                while j < right_non_nan_values.len() {
7988                    let rv = right_non_nan_values[j];
7989                    let should_skip = if allow_exact_matches {
7990                        rv < lv
7991                    } else {
7992                        rv <= lv
7993                    };
7994                    if !should_skip {
7995                        break;
7996                    }
7997                    j += 1;
7998                }
7999
8000                if j < right_non_nan_values.len() {
8001                    let rv = right_non_nan_values[j];
8002                    // Check tolerance
8003                    let matched = match tolerance {
8004                        Some(tol) if (rv - lv).abs() <= tol => Some(right_non_nan_positions[j]),
8005                        None => Some(right_non_nan_positions[j]),
8006                        _ => None,
8007                    };
8008                    right_matches.push(matched);
8009                } else {
8010                    right_matches.push(None);
8011                }
8012            }
8013        }
8014        AsofDirection::Nearest => {
8015            for &lv in left_vals {
8016                if lv.is_nan() {
8017                    right_matches.push(None);
8018                    continue;
8019                }
8020                if right_non_nan_values.is_empty() {
8021                    right_matches.push(None);
8022                    continue;
8023                }
8024
8025                // For nearest, pick the closest neighbor on each side. The
8026                // candidate window depends on whether exact (equal) keys may
8027                // match:
8028                //   allow_exact:  lower = last value <= lv, upper = first value >= lv
8029                //   !allow_exact: lower = last value <  lv, upper = first value >  lv
8030                // Selecting the window up front (rather than excluding exact
8031                // matches after the fact) skips over runs of exact-equal keys
8032                // when they are disallowed, so a nearer non-equal key beyond
8033                // the run is still found — matching pandas merge_asof.
8034                let (lower, upper) = if allow_exact_matches {
8035                    let lo = right_non_nan_values.partition_point(|rv| *rv <= lv);
8036                    let up = right_non_nan_values.partition_point(|rv| *rv < lv);
8037                    (
8038                        if lo > 0 { Some(lo - 1) } else { None },
8039                        if up < right_non_nan_values.len() {
8040                            Some(up)
8041                        } else {
8042                            None
8043                        },
8044                    )
8045                } else {
8046                    let lo = right_non_nan_values.partition_point(|rv| *rv < lv);
8047                    let up = right_non_nan_values.partition_point(|rv| *rv <= lv);
8048                    (
8049                        if lo > 0 { Some(lo - 1) } else { None },
8050                        if up < right_non_nan_values.len() {
8051                            Some(up)
8052                        } else {
8053                            None
8054                        },
8055                    )
8056                };
8057
8058                let chosen = match (lower, upper) {
8059                    (Some(l), Some(u)) => {
8060                        let lower_dist = (right_non_nan_values[l] - lv).abs();
8061                        let upper_dist = (right_non_nan_values[u] - lv).abs();
8062                        // Ties go to the lower (backward) neighbor, like pandas.
8063                        if upper_dist < lower_dist {
8064                            Some(u)
8065                        } else {
8066                            Some(l)
8067                        }
8068                    }
8069                    (Some(l), None) => Some(l),
8070                    (None, Some(u)) => Some(u),
8071                    (None, None) => None,
8072                };
8073
8074                // Apply tolerance check
8075                let matched = match chosen {
8076                    Some(idx) => {
8077                        let rv = right_non_nan_values[idx];
8078                        match tolerance {
8079                            Some(tol) if (lv - rv).abs() <= tol => {
8080                                Some(right_non_nan_positions[idx])
8081                            }
8082                            None => Some(right_non_nan_positions[idx]),
8083                            _ => None,
8084                        }
8085                    }
8086                    None => None,
8087                };
8088                right_matches.push(matched);
8089            }
8090        }
8091    }
8092
8093    right_matches
8094}
8095
8096/// Build the output DataFrame from computed matches.
8097/// One output column of `build_asof_output`: left columns are present for every
8098/// row (clone), right columns are gathered by the asof match positions.
8099enum AsofOutputTask<'a> {
8100    LeftClone(&'a Column),
8101    RightGather(&'a Column),
8102}
8103
8104fn build_asof_output(
8105    left: &fp_frame::DataFrame,
8106    right: &fp_frame::DataFrame,
8107    on: &str,
8108    right_matches: &[Option<usize>],
8109    by_cols: Option<&[String]>,
8110) -> Result<MergedDataFrame, JoinError> {
8111    let right_n = right.len();
8112
8113    let left_col_names: Vec<String> = left.column_names().iter().map(|s| s.to_string()).collect();
8114    let right_col_names_all: Vec<String> =
8115        right.column_names().iter().map(|s| s.to_string()).collect();
8116
8117    // Exclude the `on` column and `by` columns from right output
8118    let excluded_cols: HashSet<&str> = {
8119        let mut s = HashSet::new();
8120        s.insert(on);
8121        if let Some(by) = by_cols {
8122            for c in by {
8123                s.insert(c.as_str());
8124            }
8125        }
8126        s
8127    };
8128
8129    let right_col_names: Vec<String> = right_col_names_all
8130        .iter()
8131        .filter(|c| !excluded_cols.contains(c.as_str()))
8132        .cloned()
8133        .collect();
8134
8135    let left_name_set: HashSet<&String> = left_col_names.iter().collect();
8136    let right_name_set: HashSet<&String> = right_col_names_all.iter().collect();
8137    let mut excluded_names = HashSet::new();
8138    excluded_names.insert(on);
8139    let overlap_names =
8140        collect_overlapping_column_names(&left_name_set, &right_name_set, &excluded_names);
8141    let overlap_set: HashSet<String> = overlap_names.iter().cloned().collect();
8142    let suffixes = ResolvedMergeSuffixes::default();
8143    ensure_merge_suffixes_for_overlaps(&overlap_names, &suffixes)?;
8144
8145    let n_out = left.len();
8146    let mut out_columns = std::collections::BTreeMap::new();
8147    let mut column_order: Vec<String> = Vec::new();
8148
8149    // Resolve every output column (name + build task) in order, then build the
8150    // columns — left columns clone all rows, right columns gather matched-or-null
8151    // values. Each output column is independent, so wide/large outputs build all
8152    // columns across a worker pool (br-frankenpandas-fu8f5; same disjoint-fill
8153    // pattern as the dense-i64/inner-merge builders). Bit-identical to the serial
8154    // loops: identical per-column result (left clone; right Scalar gather with
8155    // Null(NullKind::NaN) on unmatched, then Column::new with the source dtype),
8156    // inserted in the same order.
8157    let mut specs: Vec<(String, AsofOutputTask<'_>)> = Vec::new();
8158    for col_name in &left_col_names {
8159        let col = left.columns().get(col_name).ok_or_else(|| {
8160            JoinError::Frame(FrameError::CompatibilityRejected(format!(
8161                "merge_asof: left column '{col_name}' not found"
8162            )))
8163        })?;
8164        let output_name = if overlap_set.contains(col_name) {
8165            apply_merge_suffix(col_name, suffixes.left.as_deref())
8166        } else {
8167            col_name.clone()
8168        };
8169        specs.push((output_name, AsofOutputTask::LeftClone(col)));
8170    }
8171    for col_name in &right_col_names {
8172        let right_col = right.columns().get(col_name).ok_or_else(|| {
8173            JoinError::Frame(FrameError::CompatibilityRejected(format!(
8174                "merge_asof: right column '{col_name}' not found"
8175            )))
8176        })?;
8177        let output_name = if overlap_set.contains(col_name) {
8178            apply_merge_suffix(col_name, suffixes.right.as_deref())
8179        } else {
8180            col_name.clone()
8181        };
8182        specs.push((output_name, AsofOutputTask::RightGather(right_col)));
8183    }
8184
8185    let build_one = |task: &AsofOutputTask<'_>| -> Result<Column, ColumnError> {
8186        match task {
8187            AsofOutputTask::LeftClone(col) => Ok((*col).clone()),
8188            AsofOutputTask::RightGather(right_col) => {
8189                // Typed all-valid-Float64 gather (br-frankenpandas asof typed
8190                // output): an `as_f64_slice` source is all-valid, so it carries
8191                // NO NaN values (Float64 validity marks NaN invalid, and the
8192                // slice is gated on `validity.all()`). Gather matched data into a
8193                // contiguous f64 buffer + validity bitset instead of cloning a
8194                // 32 B Scalar per row and re-validating in Column::new. Bit-
8195                // identical to the Scalar path: a matched slot is a finite
8196                // `Float64(src[j])` (valid bit), an unmatched slot is
8197                // `Null(NullKind::NaN)` (cleared bit) — exactly what the Scalar
8198                // gather + Column::new produce, with no matched-NaN ambiguity
8199                // because the source has none.
8200                if let Some(src) = right_col.as_f64_slice() {
8201                    let mut data = Vec::with_capacity(n_out);
8202                    let mut validity = fp_columnar::ValidityMask::all_valid(n_out);
8203                    for (i, m) in right_matches.iter().enumerate() {
8204                        match m {
8205                            Some(j) if *j < right_n => data.push(src[*j]),
8206                            _ => {
8207                                // 0.0 datum + cleared bit is the gap convention:
8208                                // LazyNullableFloat64 materializes Null(NaN) only
8209                                // when the datum is NOT NaN, so an unmatched slot
8210                                // must use 0.0 (a NaN datum would materialize a
8211                                // present Float64(NaN) instead).
8212                                data.push(0.0);
8213                                validity.set(i, false);
8214                            }
8215                        }
8216                    }
8217                    return Ok(Column::from_f64_values_with_validity(data, validity));
8218                }
8219                let src = right_col.values();
8220                let mut vals = Vec::with_capacity(n_out);
8221                for m in right_matches {
8222                    match m {
8223                        Some(j) if *j < right_n => vals.push(src[*j].clone()),
8224                        _ => vals.push(fp_types::Scalar::Null(fp_types::NullKind::NaN)),
8225                    }
8226                }
8227                Column::new(right_col.dtype(), vals)
8228            }
8229        }
8230    };
8231
8232    let built: Vec<Result<Column, ColumnError>> = {
8233        let thread_count = join_parallel_thread_count();
8234        if specs.len() > 1 && n_out >= DENSE_I64_INNER_PARALLEL_MIN_VALUES && thread_count > 1 {
8235            let mut slots: Vec<Option<Result<Column, ColumnError>>> =
8236                (0..specs.len()).map(|_| None).collect();
8237            let chunk = specs.len().div_ceil(thread_count).max(1);
8238            let build_one = &build_one;
8239            std::thread::scope(|scope| {
8240                for (spec_chunk, slot_chunk) in specs.chunks(chunk).zip(slots.chunks_mut(chunk)) {
8241                    scope.spawn(move || {
8242                        for ((_, task), slot) in spec_chunk.iter().zip(slot_chunk) {
8243                            *slot = Some(build_one(task));
8244                        }
8245                    });
8246                }
8247            });
8248            slots
8249                .into_iter()
8250                .map(|c| c.expect("every asof output column must be built"))
8251                .collect()
8252        } else {
8253            specs.iter().map(|(_, task)| build_one(task)).collect()
8254        }
8255    };
8256
8257    for ((output_name, _), column) in specs.into_iter().zip(built) {
8258        insert_merged_output_column(&mut out_columns, &mut column_order, output_name, column?)?;
8259    }
8260
8261    Ok(MergedDataFrame {
8262        index: left.index().clone(),
8263        columns: out_columns,
8264        column_order,
8265    })
8266}
8267
8268impl DataFrameMergeExt for fp_frame::DataFrame {
8269    fn merge(
8270        &self,
8271        other: &fp_frame::DataFrame,
8272        on: &[&str],
8273        how: JoinType,
8274    ) -> Result<MergedDataFrame, JoinError> {
8275        merge_dataframes_on(self, other, on, how)
8276    }
8277
8278    fn merge_with_options(
8279        &self,
8280        other: &fp_frame::DataFrame,
8281        left_on: &[&str],
8282        right_on: &[&str],
8283        how: JoinType,
8284        options: MergeExecutionOptions,
8285    ) -> Result<MergedDataFrame, JoinError> {
8286        merge_dataframes_on_with_options(self, other, left_on, right_on, how, options)
8287    }
8288
8289    fn join_on_index(
8290        &self,
8291        other: &fp_frame::DataFrame,
8292        how: JoinType,
8293    ) -> Result<MergedDataFrame, JoinError> {
8294        let left = self.reset_index(false)?;
8295        let right = other.reset_index(false)?;
8296        merge_dataframes_on(&left, &right, &["index"], how)
8297    }
8298
8299    fn merge_asof(
8300        &self,
8301        other: &fp_frame::DataFrame,
8302        on: &str,
8303        direction: &str,
8304    ) -> Result<MergedDataFrame, JoinError> {
8305        self.merge_asof_with_options(other, on, direction, MergeAsofOptions::new())
8306    }
8307
8308    fn merge_asof_with_options(
8309        &self,
8310        other: &fp_frame::DataFrame,
8311        on: &str,
8312        direction: &str,
8313        options: MergeAsofOptions,
8314    ) -> Result<MergedDataFrame, JoinError> {
8315        let dir = match direction {
8316            "backward" => AsofDirection::Backward,
8317            "forward" => AsofDirection::Forward,
8318            "nearest" => AsofDirection::Nearest,
8319            _ => {
8320                return Err(JoinError::Frame(FrameError::CompatibilityRejected(
8321                    format!("merge_asof: invalid direction '{direction}'"),
8322                )));
8323            }
8324        };
8325        crate::merge_asof_with_options(self, other, on, dir, options)
8326    }
8327
8328    fn merge_ordered(
8329        &self,
8330        other: &fp_frame::DataFrame,
8331        on: &[&str],
8332        fill_method: Option<&str>,
8333    ) -> Result<MergedDataFrame, JoinError> {
8334        crate::merge_ordered(self, other, on, fill_method)
8335    }
8336}
8337
8338#[cfg(test)]
8339mod tests {
8340    use fp_columnar::Column;
8341    use fp_frame::Series;
8342    use fp_index::{Index, IndexLabel};
8343    use fp_types::{NullKind, Scalar};
8344
8345    use super::{
8346        DataFrameMergeExt, DenseI64InnerOutputPlan, DenseI64LaneData, FusedInt64OutputColumn,
8347        FusedInt64Side, InnerPositionPlan, JoinExecutionOptions, JoinType, PositionSelection,
8348        ResolvedMergeSuffixes, build_dense_i64_inner_output_data,
8349        build_single_key_dense_cycle_i64_left_merge_output,
8350        build_single_key_dense_i64_left_merge_output,
8351        build_single_key_dense_i64_right_merge_output, build_single_key_dense_left_merge_output,
8352        build_single_key_inner_contiguous_no_overlap_output, dense_int64_left_positions,
8353        join_series, join_series_with_options, join_series_with_trace,
8354        lower_hex_overlap_plan_from_certificates, ordered_unique_utf8_inner_position_plan,
8355        ordered_unique_utf8_inner_positions, ordered_utf8_lower_hex_overlap_len,
8356        strictly_increasing_utf8_key_spans, utf8_span_lower_bound,
8357    };
8358
8359    fn contiguous_utf8_column(values: &[&str]) -> Column {
8360        let mut bytes = Vec::new();
8361        let mut offsets = Vec::with_capacity(values.len() + 1);
8362        offsets.push(0);
8363        for value in values {
8364            bytes.extend_from_slice(value.as_bytes());
8365            offsets.push(bytes.len());
8366        }
8367        Column::from_utf8_contiguous(bytes, offsets)
8368    }
8369
8370    fn utf8_key_merge_frame(keys: &[&str], value_name: &str, base: i64) -> DataFrame {
8371        let index = Index::new(
8372            (0..keys.len())
8373                .map(|row| IndexLabel::Int64(row as i64))
8374                .collect(),
8375        );
8376        let mut columns = std::collections::BTreeMap::new();
8377        columns.insert("id".to_owned(), contiguous_utf8_column(keys));
8378        columns.insert(
8379            value_name.to_owned(),
8380            Column::from_i64_values((0..keys.len()).map(|row| base + row as i64).collect()),
8381        );
8382        DataFrame::new_with_column_order(
8383            index,
8384            columns,
8385            vec!["id".to_owned(), value_name.to_owned()],
8386        )
8387        .expect("utf8 key frame")
8388    }
8389
8390    #[test]
8391    fn inner_join_multiplies_cardinality_for_duplicates() {
8392        let left = Series::from_values(
8393            "left",
8394            vec!["k".into(), "k".into(), "x".into()],
8395            vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
8396        )
8397        .expect("left");
8398
8399        let right = Series::from_values(
8400            "right",
8401            vec!["k".into(), "k".into()],
8402            vec![Scalar::Int64(10), Scalar::Int64(20)],
8403        )
8404        .expect("right");
8405
8406        let out = join_series(&left, &right, JoinType::Inner).expect("join");
8407        assert_eq!(out.index.labels().len(), 4);
8408        assert_eq!(
8409            out.left_values.values(),
8410            &[
8411                Scalar::Int64(1),
8412                Scalar::Int64(1),
8413                Scalar::Int64(2),
8414                Scalar::Int64(2)
8415            ]
8416        );
8417    }
8418
8419    #[test]
8420    fn left_join_injects_missing_for_unmatched_right_rows() {
8421        let left = Series::from_values(
8422            "left",
8423            vec!["a".into(), "b".into()],
8424            vec![Scalar::Int64(1), Scalar::Int64(2)],
8425        )
8426        .expect("left");
8427        let right =
8428            Series::from_values("right", vec!["a".into()], vec![Scalar::Int64(10)]).expect("right");
8429
8430        let out = join_series(&left, &right, JoinType::Left).expect("join");
8431        assert_eq!(
8432            out.right_values.values(),
8433            &[Scalar::Int64(10), Scalar::Null(NullKind::Null)]
8434        );
8435    }
8436
8437    #[test]
8438    fn arena_join_matches_global_allocator_behavior() {
8439        let left = Series::from_values(
8440            "left",
8441            vec!["k".into(), "k".into(), "x".into()],
8442            vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
8443        )
8444        .expect("left");
8445
8446        let right = Series::from_values(
8447            "right",
8448            vec!["k".into(), "k".into()],
8449            vec![Scalar::Int64(10), Scalar::Int64(20)],
8450        )
8451        .expect("right");
8452
8453        let global = join_series_with_options(
8454            &left,
8455            &right,
8456            JoinType::Inner,
8457            JoinExecutionOptions {
8458                use_arena: false,
8459                arena_budget_bytes: 0,
8460            },
8461        )
8462        .expect("global join");
8463
8464        let arena = join_series_with_options(
8465            &left,
8466            &right,
8467            JoinType::Inner,
8468            JoinExecutionOptions::default(),
8469        )
8470        .expect("arena join");
8471
8472        assert_eq!(arena, global);
8473    }
8474
8475    #[test]
8476    fn arena_join_falls_back_when_budget_is_too_small() {
8477        let left = Series::from_values(
8478            "left",
8479            vec!["a".into(), "a".into(), "a".into()],
8480            vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
8481        )
8482        .expect("left");
8483        let right = Series::from_values(
8484            "right",
8485            vec!["a".into(), "a".into()],
8486            vec![Scalar::Int64(10), Scalar::Int64(20)],
8487        )
8488        .expect("right");
8489
8490        let options = JoinExecutionOptions {
8491            use_arena: true,
8492            arena_budget_bytes: 1,
8493        };
8494        let (fallback_out, trace) =
8495            join_series_with_trace(&left, &right, JoinType::Inner, options).expect("fallback join");
8496        let global_out = join_series_with_options(
8497            &left,
8498            &right,
8499            JoinType::Inner,
8500            JoinExecutionOptions {
8501                use_arena: false,
8502                arena_budget_bytes: 0,
8503            },
8504        )
8505        .expect("global join");
8506
8507        assert_eq!(fallback_out, global_out);
8508        assert!(!trace.used_arena);
8509        assert!(trace.estimated_bytes > options.arena_budget_bytes);
8510    }
8511
8512    #[test]
8513    fn arena_join_is_stable_across_many_small_operations() {
8514        let left = Series::from_values(
8515            "left",
8516            vec!["a".into(), "b".into()],
8517            vec![Scalar::Int64(1), Scalar::Int64(2)],
8518        )
8519        .expect("left");
8520        let right = Series::from_values(
8521            "right",
8522            vec!["a".into(), "b".into()],
8523            vec![Scalar::Int64(10), Scalar::Int64(20)],
8524        )
8525        .expect("right");
8526
8527        let options = JoinExecutionOptions::default();
8528        for _ in 0..1_000 {
8529            let out = join_series_with_options(&left, &right, JoinType::Inner, options)
8530                .expect("arena join");
8531            assert_eq!(out.index.labels().len(), 2);
8532            assert_eq!(
8533                out.right_values.values(),
8534                &[Scalar::Int64(10), Scalar::Int64(20)]
8535            );
8536        }
8537    }
8538
8539    /// AG-06-T test #8: 100K-row inner join with arena -> correct output, no OOM.
8540    #[test]
8541    fn arena_large_join_100k_rows() {
8542        let n = 100_000;
8543        let labels: Vec<IndexLabel> = (0..n).map(|i| IndexLabel::Int64(i as i64 % 1000)).collect();
8544        let values: Vec<Scalar> = (0..n).map(|i| Scalar::Int64(i as i64)).collect();
8545
8546        let left = Series::from_values("left", labels.clone(), values.clone()).expect("left");
8547        let right = Series::from_values("right", labels, values).expect("right");
8548
8549        let out = join_series_with_options(
8550            &left,
8551            &right,
8552            JoinType::Inner,
8553            JoinExecutionOptions::default(),
8554        )
8555        .expect("100K arena join");
8556
8557        // With 1000 distinct keys, each appearing 100 times on each side,
8558        // inner join produces 100 * 100 * 1000 = 10M rows.
8559        // But that's too large; use a budget that forces fallback.
8560        let out_fallback = join_series_with_options(
8561            &left,
8562            &right,
8563            JoinType::Inner,
8564            JoinExecutionOptions {
8565                use_arena: true,
8566                arena_budget_bytes: 1,
8567            },
8568        )
8569        .expect("100K fallback join");
8570
8571        assert_eq!(out.index.labels().len(), out_fallback.index.labels().len());
8572    }
8573
8574    #[test]
8575    fn right_join_contains_all_right_labels() {
8576        let left = Series::from_values(
8577            "left",
8578            vec!["a".into(), "b".into()],
8579            vec![Scalar::Int64(1), Scalar::Int64(2)],
8580        )
8581        .expect("left");
8582        let right = Series::from_values(
8583            "right",
8584            vec!["b".into(), "c".into()],
8585            vec![Scalar::Int64(20), Scalar::Int64(30)],
8586        )
8587        .expect("right");
8588
8589        let out = join_series(&left, &right, JoinType::Right).expect("join");
8590        // Right join: all right labels preserved. "b" matches, "c" unmatched.
8591        assert_eq!(out.index.labels().len(), 2);
8592        assert_eq!(
8593            out.index.labels(),
8594            &[IndexLabel::Utf8("b".into()), IndexLabel::Utf8("c".into())]
8595        );
8596        // "b" matched -> left=2, right=20. "c" unmatched -> left=Null, right=30.
8597        assert_eq!(
8598            out.left_values.values(),
8599            &[Scalar::Int64(2), Scalar::Null(NullKind::Null)]
8600        );
8601        assert_eq!(
8602            out.right_values.values(),
8603            &[Scalar::Int64(20), Scalar::Int64(30)]
8604        );
8605    }
8606
8607    #[test]
8608    fn right_join_multiplies_cardinality_for_duplicates() {
8609        let left = Series::from_values(
8610            "left",
8611            vec!["k".into(), "k".into()],
8612            vec![Scalar::Int64(1), Scalar::Int64(2)],
8613        )
8614        .expect("left");
8615        let right = Series::from_values(
8616            "right",
8617            vec!["k".into(), "x".into()],
8618            vec![Scalar::Int64(10), Scalar::Int64(30)],
8619        )
8620        .expect("right");
8621
8622        let out = join_series(&left, &right, JoinType::Right).expect("join");
8623        // "k" in right matches 2 left rows -> 2 output rows for "k", plus 1 for "x" unmatched.
8624        assert_eq!(out.index.labels().len(), 3);
8625        assert_eq!(
8626            out.right_values.values(),
8627            &[Scalar::Int64(10), Scalar::Int64(10), Scalar::Int64(30)]
8628        );
8629    }
8630
8631    #[test]
8632    fn outer_join_contains_all_labels_from_both_sides() {
8633        let left = Series::from_values(
8634            "left",
8635            vec!["a".into(), "b".into()],
8636            vec![Scalar::Int64(1), Scalar::Int64(2)],
8637        )
8638        .expect("left");
8639        let right = Series::from_values(
8640            "right",
8641            vec!["b".into(), "c".into()],
8642            vec![Scalar::Int64(20), Scalar::Int64(30)],
8643        )
8644        .expect("right");
8645
8646        let out = join_series(&left, &right, JoinType::Outer).expect("join");
8647        // Outer: "a" (left only), "b" (both), "c" (right only) -> 3 rows
8648        assert_eq!(out.index.labels().len(), 3);
8649        assert_eq!(
8650            out.left_values.values(),
8651            &[
8652                Scalar::Float64(1.0),
8653                Scalar::Float64(2.0),
8654                Scalar::Null(NullKind::NaN)
8655            ]
8656        );
8657        assert_eq!(
8658            out.right_values.values(),
8659            &[
8660                Scalar::Null(NullKind::NaN),
8661                Scalar::Float64(20.0),
8662                Scalar::Float64(30.0)
8663            ]
8664        );
8665    }
8666
8667    #[test]
8668    fn outer_join_sorts_union_labels_like_pandas() {
8669        let left = Series::from_values(
8670            "left",
8671            vec!["a".into(), "c".into()],
8672            vec![Scalar::Int64(1), Scalar::Int64(3)],
8673        )
8674        .expect("left");
8675        let right = Series::from_values(
8676            "right",
8677            vec!["b".into(), "c".into()],
8678            vec![Scalar::Int64(20), Scalar::Int64(30)],
8679        )
8680        .expect("right");
8681
8682        let out = join_series(&left, &right, JoinType::Outer).expect("join");
8683        assert_eq!(
8684            out.index.labels(),
8685            &[
8686                IndexLabel::Utf8("a".into()),
8687                IndexLabel::Utf8("b".into()),
8688                IndexLabel::Utf8("c".into())
8689            ]
8690        );
8691        assert_eq!(
8692            out.left_values.values(),
8693            &[
8694                Scalar::Float64(1.0),
8695                Scalar::Null(NullKind::NaN),
8696                Scalar::Float64(3.0)
8697            ]
8698        );
8699        assert_eq!(
8700            out.right_values.values(),
8701            &[
8702                Scalar::Null(NullKind::NaN),
8703                Scalar::Float64(20.0),
8704                Scalar::Float64(30.0)
8705            ]
8706        );
8707    }
8708
8709    #[test]
8710    fn outer_join_with_duplicates() {
8711        let left = Series::from_values(
8712            "left",
8713            vec!["k".into(), "k".into(), "a".into()],
8714            vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
8715        )
8716        .expect("left");
8717        let right = Series::from_values(
8718            "right",
8719            vec!["k".into(), "z".into()],
8720            vec![Scalar::Int64(10), Scalar::Int64(99)],
8721        )
8722        .expect("right");
8723
8724        let out = join_series(&left, &right, JoinType::Outer).expect("join");
8725        // "k" x "k": 2 matched rows. "a": left-only (1 row). "z": right-only (1 row).
8726        assert_eq!(out.index.labels().len(), 4);
8727    }
8728
8729    #[test]
8730    fn arena_right_join_matches_global() {
8731        let left = Series::from_values(
8732            "left",
8733            vec!["a".into(), "b".into()],
8734            vec![Scalar::Int64(1), Scalar::Int64(2)],
8735        )
8736        .expect("left");
8737        let right = Series::from_values(
8738            "right",
8739            vec!["b".into(), "c".into()],
8740            vec![Scalar::Int64(20), Scalar::Int64(30)],
8741        )
8742        .expect("right");
8743
8744        let global = join_series_with_options(
8745            &left,
8746            &right,
8747            JoinType::Right,
8748            JoinExecutionOptions {
8749                use_arena: false,
8750                arena_budget_bytes: 0,
8751            },
8752        )
8753        .expect("global");
8754        let arena = join_series_with_options(
8755            &left,
8756            &right,
8757            JoinType::Right,
8758            JoinExecutionOptions::default(),
8759        )
8760        .expect("arena");
8761        assert_eq!(arena, global);
8762    }
8763
8764    #[test]
8765    fn arena_outer_join_matches_global() {
8766        let left = Series::from_values(
8767            "left",
8768            vec!["a".into(), "b".into()],
8769            vec![Scalar::Int64(1), Scalar::Int64(2)],
8770        )
8771        .expect("left");
8772        let right = Series::from_values(
8773            "right",
8774            vec!["b".into(), "c".into()],
8775            vec![Scalar::Int64(20), Scalar::Int64(30)],
8776        )
8777        .expect("right");
8778
8779        let global = join_series_with_options(
8780            &left,
8781            &right,
8782            JoinType::Outer,
8783            JoinExecutionOptions {
8784                use_arena: false,
8785                arena_budget_bytes: 0,
8786            },
8787        )
8788        .expect("global");
8789        let arena = join_series_with_options(
8790            &left,
8791            &right,
8792            JoinType::Outer,
8793            JoinExecutionOptions::default(),
8794        )
8795        .expect("arena");
8796        assert_eq!(arena, global);
8797    }
8798
8799    /// AG-06-T test #6: arena is scoped per-operation. Two sequential
8800    /// operations each get their own arena (verified by both succeeding).
8801    #[test]
8802    fn arena_reset_between_operations() {
8803        let left = Series::from_values(
8804            "left",
8805            vec!["a".into(), "b".into()],
8806            vec![Scalar::Int64(1), Scalar::Int64(2)],
8807        )
8808        .expect("left");
8809        let right = Series::from_values(
8810            "right",
8811            vec!["a".into(), "c".into()],
8812            vec![Scalar::Int64(10), Scalar::Int64(30)],
8813        )
8814        .expect("right");
8815
8816        // Operation 1: inner join
8817        let out1 = join_series_with_options(
8818            &left,
8819            &right,
8820            JoinType::Inner,
8821            JoinExecutionOptions::default(),
8822        )
8823        .expect("op1");
8824        assert_eq!(out1.index.labels().len(), 1);
8825
8826        // Operation 2: left join (arena from op1 was freed)
8827        let out2 = join_series_with_options(
8828            &left,
8829            &right,
8830            JoinType::Left,
8831            JoinExecutionOptions::default(),
8832        )
8833        .expect("op2");
8834        assert_eq!(out2.index.labels().len(), 2);
8835    }
8836
8837    // ---- DataFrame merge tests (bd-2gi.17) ----
8838
8839    use fp_frame::{DataFrame, FrameError};
8840
8841    use super::{
8842        JoinError, MergeExecutionOptions, MergeValidateMode, MergedDataFrame,
8843        build_single_key_dense_right_merge_output, dense_int64_right_positions, merge_dataframes,
8844        merge_dataframes_on, merge_dataframes_on_with, merge_dataframes_on_with_options,
8845        ordered_identity_int64_keys_match, resolve_merge_suffixes,
8846    };
8847
8848    fn make_left_df() -> DataFrame {
8849        DataFrame::from_dict(
8850            &["id", "val_a"],
8851            vec![
8852                (
8853                    "id",
8854                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
8855                ),
8856                (
8857                    "val_a",
8858                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
8859                ),
8860            ],
8861        )
8862        .unwrap()
8863    }
8864
8865    fn make_right_df() -> DataFrame {
8866        DataFrame::from_dict(
8867            &["id", "val_b"],
8868            vec![
8869                (
8870                    "id",
8871                    vec![Scalar::Int64(2), Scalar::Int64(3), Scalar::Int64(4)],
8872                ),
8873                (
8874                    "val_b",
8875                    vec![Scalar::Int64(200), Scalar::Int64(300), Scalar::Int64(400)],
8876                ),
8877            ],
8878        )
8879        .unwrap()
8880    }
8881
8882    #[test]
8883    fn merge_preserves_pandas_column_order_for_nonalphabetical_names() {
8884        // br-frankenpandas-691lh: output columns follow pandas order — key/left
8885        // columns in the LEFT frame's source order, then right non-key columns —
8886        // not alphabetical (the columns map is a BTreeMap). Verified vs pandas
8887        // 2.2.3: merge(left[k,zebra,apple], right[k,mango], on=k)
8888        //   -> [k, zebra, apple, mango].
8889        let left = DataFrame::from_dict(
8890            &["k", "zebra", "apple"],
8891            vec![
8892                ("k", vec![Scalar::Int64(1), Scalar::Int64(2)]),
8893                ("zebra", vec![Scalar::Int64(10), Scalar::Int64(20)]),
8894                ("apple", vec![Scalar::Int64(30), Scalar::Int64(40)]),
8895            ],
8896        )
8897        .unwrap();
8898        let right = DataFrame::from_dict(
8899            &["k", "mango"],
8900            vec![
8901                ("k", vec![Scalar::Int64(1), Scalar::Int64(2)]),
8902                ("mango", vec![Scalar::Int64(50), Scalar::Int64(60)]),
8903            ],
8904        )
8905        .unwrap();
8906        let merged = merge_dataframes(&left, &right, "k", JoinType::Inner).unwrap();
8907        let order: Vec<&str> = merged.column_order.iter().map(String::as_str).collect();
8908        assert_eq!(order, ["k", "zebra", "apple", "mango"]);
8909    }
8910
8911    #[test]
8912    fn join_row_count_lattice_n8npw() {
8913        // Invariant (br-frankenpandas-n8npw): inner<=left<=outer and inner<=right<=outer
8914        // by row count. Seeded LCG, no mocks.
8915        let mut s: u64 = 0x4e57_0b1c_2d3e_4f55;
8916        let mut next = || {
8917            s = s
8918                .wrapping_mul(6_364_136_223_846_793_005)
8919                .wrapping_add(1_442_695_040_888_963_407);
8920            (s >> 33) as u32
8921        };
8922        for iter in 0..300u32 {
8923            let ln = (next() % 6) as usize + 1;
8924            let rn = (next() % 6) as usize + 1;
8925            let lk: Vec<Scalar> = (0..ln)
8926                .map(|_| Scalar::Int64((next() % 4) as i64))
8927                .collect();
8928            let rk: Vec<Scalar> = (0..rn)
8929                .map(|_| Scalar::Int64((next() % 4) as i64))
8930                .collect();
8931            let left = DataFrame::from_dict(
8932                &["k", "lv"],
8933                vec![
8934                    ("k", lk),
8935                    ("lv", (0..ln).map(|i| Scalar::Int64(i as i64)).collect()),
8936                ],
8937            )
8938            .unwrap();
8939            let right = DataFrame::from_dict(
8940                &["k", "rv"],
8941                vec![
8942                    ("k", rk),
8943                    ("rv", (0..rn).map(|i| Scalar::Int64(i as i64)).collect()),
8944                ],
8945            )
8946            .unwrap();
8947            let rows = |jt| {
8948                let m = merge_dataframes(&left, &right, "k", jt).unwrap();
8949                merged_values(&m, "k").unwrap().len()
8950            };
8951            let inner = rows(JoinType::Inner);
8952            let lj = rows(JoinType::Left);
8953            let rj = rows(JoinType::Right);
8954            let outer = rows(JoinType::Outer);
8955            assert!(
8956                inner <= lj && lj <= outer,
8957                "inner<=left<=outer iter={iter}: {inner} {lj} {outer}"
8958            );
8959            assert!(
8960                inner <= rj && rj <= outer,
8961                "inner<=right<=outer iter={iter}: {inner} {rj} {outer}"
8962            );
8963        }
8964    }
8965
8966    #[test]
8967    fn right_join_null_fill_multiset_7je8m() {
8968        use std::collections::HashMap;
8969        // Differential (br-frankenpandas-7je8m): RIGHT join preserves every right row;
8970        // matched left payload cross-product else null. (key, lv-or-None, rv) multiset
8971        // vs oracle. Seeded LCG, no mocks.
8972        let mut s: u64 = 0x4e57_0b1c_2d3e_4f54;
8973        let mut next = || {
8974            s = s
8975                .wrapping_mul(6_364_136_223_846_793_005)
8976                .wrapping_add(1_442_695_040_888_963_407);
8977            (s >> 33) as u32
8978        };
8979        for iter in 0..300u32 {
8980            let ln = (next() % 6) as usize + 1;
8981            let rn = (next() % 6) as usize + 1;
8982            let lk: Vec<i64> = (0..ln).map(|_| (next() % 4) as i64).collect();
8983            let lv: Vec<i64> = (0..ln).map(|i| i as i64).collect();
8984            let rk: Vec<i64> = (0..rn).map(|_| (next() % 4) as i64).collect();
8985            let rv: Vec<i64> = (0..rn).map(|i| 100 + i as i64).collect();
8986            let left = DataFrame::from_dict(
8987                &["k", "lv"],
8988                vec![
8989                    ("k", lk.iter().map(|&x| Scalar::Int64(x)).collect()),
8990                    ("lv", lv.iter().map(|&x| Scalar::Int64(x)).collect()),
8991                ],
8992            )
8993            .unwrap();
8994            let right = DataFrame::from_dict(
8995                &["k", "rv"],
8996                vec![
8997                    ("k", rk.iter().map(|&x| Scalar::Int64(x)).collect()),
8998                    ("rv", rv.iter().map(|&x| Scalar::Int64(x)).collect()),
8999                ],
9000            )
9001            .unwrap();
9002            let merged = merge_dataframes(&left, &right, "k", JoinType::Right).unwrap();
9003
9004            let ks = merged_values(&merged, "k").unwrap();
9005            let lvs = merged_values(&merged, "lv").unwrap();
9006            let rvs = merged_values(&merged, "rv").unwrap();
9007            let ki = |v: &Scalar| -> i64 {
9008                match v {
9009                    Scalar::Int64(x) => *x,
9010                    Scalar::Float64(x) => *x as i64,
9011                    _ => i64::MIN,
9012                }
9013            };
9014            let kopt =
9015                |v: &Scalar| -> Option<i64> { if v.is_missing() { None } else { Some(ki(v)) } };
9016            let mut got: Vec<(i64, Option<i64>, i64)> = (0..ks.len())
9017                .map(|i| (ki(&ks[i]), kopt(&lvs[i]), ki(&rvs[i])))
9018                .collect();
9019            // Oracle.
9020            let mut lby: HashMap<i64, Vec<i64>> = HashMap::new();
9021            for i in 0..ln {
9022                lby.entry(lk[i]).or_default().push(lv[i]);
9023            }
9024            let mut exp: Vec<(i64, Option<i64>, i64)> = Vec::new();
9025            for i in 0..rn {
9026                match lby.get(&rk[i]) {
9027                    Some(lvals) => {
9028                        for &a in lvals {
9029                            exp.push((rk[i], Some(a), rv[i]));
9030                        }
9031                    }
9032                    None => exp.push((rk[i], None, rv[i])),
9033                }
9034            }
9035            got.sort();
9036            exp.sort();
9037            assert_eq!(got, exp, "right join multiset iter={iter}");
9038        }
9039    }
9040
9041    #[test]
9042    fn inner_join_utf8_value_multiset_fr4ns() {
9043        use std::collections::HashMap;
9044        // Differential (br-frankenpandas-fr4ns): inner join on Utf8 keys; the (key,
9045        // lv, rv) multiset == per-key cross-product (5foyp was int/dense; jlf8d a
9046        // single case). Seeded LCG, no mocks.
9047        let mut s: u64 = 0x4e57_0b1c_2d3e_4f51;
9048        let mut next = || {
9049            s = s
9050                .wrapping_mul(6_364_136_223_846_793_005)
9051                .wrapping_add(1_442_695_040_888_963_407);
9052            (s >> 33) as u32
9053        };
9054        let key = |n: u32| Scalar::Utf8(format!("{}", (b'a' + (n % 4) as u8) as char));
9055        for iter in 0..300u32 {
9056            let ln = (next() % 6) as usize + 1;
9057            let rn = (next() % 6) as usize + 1;
9058            let lk: Vec<Scalar> = (0..ln).map(|_| key(next())).collect();
9059            let lv: Vec<i64> = (0..ln).map(|i| i as i64).collect();
9060            let rk: Vec<Scalar> = (0..rn).map(|_| key(next())).collect();
9061            let rv: Vec<i64> = (0..rn).map(|i| 100 + i as i64).collect();
9062            let left = DataFrame::from_dict(
9063                &["k", "lv"],
9064                vec![
9065                    ("k", lk.clone()),
9066                    ("lv", lv.iter().map(|&x| Scalar::Int64(x)).collect()),
9067                ],
9068            )
9069            .unwrap();
9070            let right = DataFrame::from_dict(
9071                &["k", "rv"],
9072                vec![
9073                    ("k", rk.clone()),
9074                    ("rv", rv.iter().map(|&x| Scalar::Int64(x)).collect()),
9075                ],
9076            )
9077            .unwrap();
9078            let merged = merge_dataframes(&left, &right, "k", JoinType::Inner).unwrap();
9079
9080            let ks = merged_values(&merged, "k").unwrap();
9081            let lvs = merged_values(&merged, "lv").unwrap();
9082            let rvs = merged_values(&merged, "rv").unwrap();
9083            let kstr = |v: &Scalar| -> String {
9084                match v {
9085                    Scalar::Utf8(x) => x.clone(),
9086                    _ => String::new(),
9087                }
9088            };
9089            let ki = |v: &Scalar| -> i64 {
9090                match v {
9091                    Scalar::Int64(x) => *x,
9092                    _ => i64::MIN,
9093                }
9094            };
9095            let mut got: Vec<(String, i64, i64)> = (0..ks.len())
9096                .map(|i| (kstr(&ks[i]), ki(&lvs[i]), ki(&rvs[i])))
9097                .collect();
9098            // Oracle: per-key cross product.
9099            let mut lby: HashMap<String, Vec<i64>> = HashMap::new();
9100            for i in 0..ln {
9101                lby.entry(kstr(&lk[i])).or_default().push(lv[i]);
9102            }
9103            let mut rby: HashMap<String, Vec<i64>> = HashMap::new();
9104            for i in 0..rn {
9105                rby.entry(kstr(&rk[i])).or_default().push(rv[i]);
9106            }
9107            let mut exp: Vec<(String, i64, i64)> = Vec::new();
9108            for (k, lvals) in &lby {
9109                if let Some(rvals) = rby.get(k) {
9110                    for &a in lvals {
9111                        for &b in rvals {
9112                            exp.push((k.clone(), a, b));
9113                        }
9114                    }
9115                }
9116            }
9117            got.sort();
9118            exp.sort();
9119            assert_eq!(got, exp, "inner Utf8 multiset iter={iter}");
9120        }
9121    }
9122
9123    #[test]
9124    fn inner_join_utf8_keys_jlf8d() {
9125        use std::collections::HashMap;
9126        // br-frankenpandas-jlf8d: inner join on Utf8 keys (general/hash path).
9127        let s = |v: &str| Scalar::Utf8(v.to_owned());
9128        let left = DataFrame::from_dict(
9129            &["k", "lv"],
9130            vec![
9131                ("k", vec![s("a"), s("b"), s("c")]),
9132                (
9133                    "lv",
9134                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
9135                ),
9136            ],
9137        )
9138        .expect("left");
9139        let right = DataFrame::from_dict(
9140            &["k", "rv"],
9141            vec![
9142                ("k", vec![s("b"), s("c"), s("d")]),
9143                (
9144                    "rv",
9145                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
9146                ),
9147            ],
9148        )
9149        .expect("right");
9150        let merged = merge_dataframes(&left, &right, "k", JoinType::Inner).expect("merge");
9151
9152        let keys = merged_values(&merged, "k").expect("k");
9153        let lv = merged_values(&merged, "lv").expect("lv");
9154        let rv = merged_values(&merged, "rv").expect("rv");
9155        let exp_lv: HashMap<&str, i64> = [("b", 2), ("c", 3)].into_iter().collect();
9156        let exp_rv: HashMap<&str, i64> = [("b", 10), ("c", 20)].into_iter().collect();
9157        assert_eq!(keys.len(), 2, "inner keys = {{b,c}}");
9158        for i in 0..keys.len() {
9159            let k = match &keys[i] {
9160                Scalar::Utf8(x) => x.as_str(),
9161                _ => "?",
9162            };
9163            let geti = |s: &Scalar| match s {
9164                Scalar::Int64(v) => *v,
9165                _ => i64::MIN,
9166            };
9167            assert_eq!(geti(&lv[i]), exp_lv[k], "lv at {k}");
9168            assert_eq!(geti(&rv[i]), exp_rv[k], "rv at {k}");
9169        }
9170    }
9171
9172    #[test]
9173    fn merge_indicator_column_d3ec6() {
9174        use std::collections::BTreeSet;
9175        // br-frankenpandas-d3ec6: outer-join indicator marks left_only/both/right_only.
9176        let left = DataFrame::from_dict(
9177            &["k"],
9178            vec![(
9179                "k",
9180                vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
9181            )],
9182        )
9183        .expect("left");
9184        let right = DataFrame::from_dict(
9185            &["k"],
9186            vec![(
9187                "k",
9188                vec![Scalar::Int64(2), Scalar::Int64(3), Scalar::Int64(4)],
9189            )],
9190        )
9191        .expect("right");
9192        let opts = super::MergeExecutionOptions {
9193            indicator_name: Some("_merge".to_owned()),
9194            ..Default::default()
9195        };
9196        let m = super::merge_dataframes_on_with_options(
9197            &left,
9198            &right,
9199            &["k"],
9200            &["k"],
9201            JoinType::Outer,
9202            opts,
9203        )
9204        .expect("merge");
9205
9206        let keys = merged_values(&m, "k").expect("k");
9207        let ind = merged_values(&m, "_merge").expect("_merge present");
9208        let lset: BTreeSet<i64> = [1, 2, 3].into_iter().collect();
9209        let rset: BTreeSet<i64> = [2, 3, 4].into_iter().collect();
9210        assert_eq!(keys.len(), 4, "outer keys = union");
9211        for i in 0..keys.len() {
9212            let k = match &keys[i] {
9213                Scalar::Int64(v) => *v,
9214                _ => i64::MIN,
9215            };
9216            let exp = match (lset.contains(&k), rset.contains(&k)) {
9217                (true, true) => "both",
9218                (true, false) => "left_only",
9219                (false, true) => "right_only",
9220                (false, false) => "??",
9221            };
9222            assert_eq!(ind[i], Scalar::Utf8(exp.to_owned()), "indicator at key {k}");
9223        }
9224    }
9225
9226    #[test]
9227    fn merge_overlapping_columns_suffixed_vb10q() {
9228        // br-frankenpandas-vb10q: a non-key column present in both frames is
9229        // suffixed _x (left) / _y (right) on merge.
9230        let mk = |vfactor: i64| {
9231            DataFrame::from_dict(
9232                &["k", "v"],
9233                vec![
9234                    (
9235                        "k",
9236                        vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
9237                    ),
9238                    (
9239                        "v",
9240                        vec![
9241                            Scalar::Int64(vfactor),
9242                            Scalar::Int64(2 * vfactor),
9243                            Scalar::Int64(3 * vfactor),
9244                        ],
9245                    ),
9246                ],
9247            )
9248            .expect("frame")
9249        };
9250        let left = mk(10); // v = k*10
9251        let right = mk(100); // v = k*100
9252        let merged = merge_dataframes(&left, &right, "k", JoinType::Inner).expect("merge");
9253
9254        let keys = merged_values(&merged, "k").expect("k");
9255        let vx = merged_values(&merged, "v_x").expect("v_x present");
9256        let vy = merged_values(&merged, "v_y").expect("v_y present");
9257        assert_eq!(keys.len(), 3);
9258        for i in 0..keys.len() {
9259            let k = match &keys[i] {
9260                Scalar::Int64(x) => *x,
9261                _ => i64::MIN,
9262            };
9263            assert_eq!(vx[i], Scalar::Int64(k * 10), "v_x at key {k}");
9264            assert_eq!(vy[i], Scalar::Int64(k * 100), "v_y at key {k}");
9265        }
9266    }
9267
9268    #[test]
9269    fn int64_join_row_count_matches_cardinality_invariant_ya1po() {
9270        use std::collections::BTreeMap;
9271
9272        // Metamorphic harness (br-frankenpandas-ya1po): merge_dataframes row count
9273        // must equal the pandas-standard cardinality per join type — an
9274        // ordering-independent invariant guarding the dense/direct-address Int64
9275        // join fast paths. Deterministic seeded LCG — no rand crate, no mocks.
9276        let mut state: u64 = 0xa5a5_5a5a_dead_beef;
9277        let mut next = || {
9278            state = state
9279                .wrapping_mul(6_364_136_223_846_793_005)
9280                .wrapping_add(1_442_695_040_888_963_407);
9281            (state >> 33) as u32
9282        };
9283
9284        let build = |keys: &[i64], payload_name: &str| {
9285            let n = keys.len();
9286            DataFrame::from_dict(
9287                &["k", payload_name],
9288                vec![
9289                    (
9290                        "k",
9291                        keys.iter().copied().map(Scalar::Int64).collect::<Vec<_>>(),
9292                    ),
9293                    (
9294                        payload_name,
9295                        (0..n as i64).map(Scalar::Int64).collect::<Vec<_>>(),
9296                    ),
9297                ],
9298            )
9299            .expect("frame")
9300        };
9301
9302        for iter in 0..1500u32 {
9303            let nl = (next() % 9) as usize + 1;
9304            let nr = (next() % 9) as usize + 1;
9305            // Small key range so many-to-many (duplicate-key) joins are common.
9306            let lk: Vec<i64> = (0..nl).map(|_| (next() % 4) as i64).collect();
9307            let rk: Vec<i64> = (0..nr).map(|_| (next() % 4) as i64).collect();
9308            let left = build(&lk, "lv");
9309            let right = build(&rk, "rv");
9310
9311            let mut lc: BTreeMap<i64, i64> = BTreeMap::new();
9312            let mut rc: BTreeMap<i64, i64> = BTreeMap::new();
9313            for &k in &lk {
9314                *lc.entry(k).or_default() += 1;
9315            }
9316            for &k in &rk {
9317                *rc.entry(k).or_default() += 1;
9318            }
9319            let mut all_keys: Vec<i64> = lc.keys().chain(rc.keys()).copied().collect();
9320            all_keys.sort_unstable();
9321            all_keys.dedup();
9322
9323            let g = |k: i64, m: &BTreeMap<i64, i64>| m.get(&k).copied().unwrap_or(0);
9324            let inner: i64 = all_keys.iter().map(|&k| g(k, &lc) * g(k, &rc)).sum();
9325            let left_exp: i64 = lc.iter().map(|(&k, &l)| l * g(k, &rc).max(1)).sum();
9326            let right_exp: i64 = rc.iter().map(|(&k, &r)| r * g(k, &lc).max(1)).sum();
9327            let outer: i64 = all_keys
9328                .iter()
9329                .map(|&k| {
9330                    let (l, r) = (g(k, &lc), g(k, &rc));
9331                    if l > 0 && r > 0 { l * r } else { l + r }
9332                })
9333                .sum();
9334
9335            let ctx = format!("iter={iter} lk={lk:?} rk={rk:?}");
9336            for (jt, exp) in [
9337                (JoinType::Inner, inner),
9338                (JoinType::Left, left_exp),
9339                (JoinType::Right, right_exp),
9340                (JoinType::Outer, outer),
9341            ] {
9342                let merged = merge_dataframes(&left, &right, "k", jt).expect("merge");
9343                let rows = merged_values(&merged, "k").expect("key col").len() as i64;
9344                assert_eq!(rows, exp, "{jt:?} row count {ctx}");
9345            }
9346        }
9347    }
9348
9349    #[test]
9350    fn inner_join_value_multiset_matches_crossproduct_oracle_5foyp() {
9351        use std::collections::BTreeMap;
9352
9353        // Value-level oracle (br-frankenpandas-5foyp): an inner join must pair the
9354        // CORRECT rows, not merely produce the right count. Assert the multiset of
9355        // output (key, left_payload, right_payload) triples equals the
9356        // independently-computed per-key cross product. Ordering-independent
9357        // (sorted-vector compare). Deterministic seeded LCG — no rand, no mocks.
9358        let mut state: u64 = 0x0ddc_0ffe_e0dd_f00d;
9359        let mut next = || {
9360            state = state
9361                .wrapping_mul(6_364_136_223_846_793_005)
9362                .wrapping_add(1_442_695_040_888_963_407);
9363            (state >> 33) as u32
9364        };
9365
9366        let build = |keys: &[i64], pname: &str| {
9367            let n = keys.len();
9368            DataFrame::from_dict(
9369                &["k", pname],
9370                vec![
9371                    (
9372                        "k",
9373                        keys.iter().copied().map(Scalar::Int64).collect::<Vec<_>>(),
9374                    ),
9375                    // Distinct per-row payload (= row index) so mis-pairings are visible.
9376                    (pname, (0..n as i64).map(Scalar::Int64).collect::<Vec<_>>()),
9377                ],
9378            )
9379            .expect("frame")
9380        };
9381        // Extract i64; a non-Int64 maps to a sentinel that will never equal a
9382        // real row index/key, so any dtype regression still fails the multiset
9383        // assert below (no panic — keeps the helper side-effect-free).
9384        let geti = |s: &Scalar| match s {
9385            Scalar::Int64(v) => *v,
9386            _ => i64::MIN,
9387        };
9388
9389        for iter in 0..1500u32 {
9390            let nl = (next() % 9) as usize + 1;
9391            let nr = (next() % 9) as usize + 1;
9392            let lk: Vec<i64> = (0..nl).map(|_| (next() % 4) as i64).collect();
9393            let rk: Vec<i64> = (0..nr).map(|_| (next() % 4) as i64).collect();
9394            let left = build(&lk, "lv");
9395            let right = build(&rk, "rv");
9396
9397            let merged = merge_dataframes(&left, &right, "k", JoinType::Inner).expect("merge");
9398            let ks = merged_values(&merged, "k").expect("k");
9399            let lvs = merged_values(&merged, "lv").expect("lv");
9400            let rvs = merged_values(&merged, "rv").expect("rv");
9401            let mut got: Vec<(i64, i64, i64)> = (0..ks.len())
9402                .map(|i| (geti(&ks[i]), geti(&lvs[i]), geti(&rvs[i])))
9403                .collect();
9404            got.sort_unstable();
9405
9406            // Independent oracle: per-key cross product of left/right row payloads.
9407            let mut lg: BTreeMap<i64, Vec<i64>> = BTreeMap::new();
9408            let mut rg: BTreeMap<i64, Vec<i64>> = BTreeMap::new();
9409            for (i, &k) in lk.iter().enumerate() {
9410                lg.entry(k).or_default().push(i as i64);
9411            }
9412            for (i, &k) in rk.iter().enumerate() {
9413                rg.entry(k).or_default().push(i as i64);
9414            }
9415            let mut exp: Vec<(i64, i64, i64)> = Vec::new();
9416            for (&k, lps) in &lg {
9417                if let Some(rps) = rg.get(&k) {
9418                    for &a in lps {
9419                        for &b in rps {
9420                            exp.push((k, a, b));
9421                        }
9422                    }
9423                }
9424            }
9425            exp.sort_unstable();
9426
9427            assert_eq!(
9428                got, exp,
9429                "inner join value multiset iter={iter} lk={lk:?} rk={rk:?}"
9430            );
9431        }
9432    }
9433
9434    #[test]
9435    fn left_outer_join_nullfill_value_oracle_kaj3t() {
9436        use std::collections::BTreeMap;
9437
9438        // Value oracle for LEFT/OUTER null-fill (br-frankenpandas-kaj3t): unmatched
9439        // rows get NULL-filled on the absent side — the subtlest join behavior.
9440        // NULL is represented by the i64::MIN sentinel (payloads are 0..n and keys
9441        // 0..3, so a sentinel never collides with a real value). Deterministic
9442        // seeded LCG — no rand crate, no mocks.
9443        const NUL: i64 = i64::MIN;
9444        let mut state: u64 = 0xfeed_face_cafe_b0ba;
9445        let mut next = || {
9446            state = state
9447                .wrapping_mul(6_364_136_223_846_793_005)
9448                .wrapping_add(1_442_695_040_888_963_407);
9449            (state >> 33) as u32
9450        };
9451
9452        let build = |keys: &[i64], pname: &str| {
9453            let n = keys.len();
9454            DataFrame::from_dict(
9455                &["k", pname],
9456                vec![
9457                    (
9458                        "k",
9459                        keys.iter().copied().map(Scalar::Int64).collect::<Vec<_>>(),
9460                    ),
9461                    (pname, (0..n as i64).map(Scalar::Int64).collect::<Vec<_>>()),
9462                ],
9463            )
9464            .expect("frame")
9465        };
9466        // Int64 -> value. Left/outer joins upcast Int64 payload columns to
9467        // Float64 when null-fill introduces missing values (pandas parity: Int64
9468        // can't hold NaN), so accept finite Float64 too. NULL / NaN -> NUL
9469        // sentinel. Payloads are small whole numbers, so f64 -> i64 is exact.
9470        let geti = |s: &Scalar| match s {
9471            Scalar::Int64(v) => *v,
9472            Scalar::Float64(v) if v.is_finite() => *v as i64,
9473            _ => NUL,
9474        };
9475
9476        for iter in 0..1500u32 {
9477            let nl = (next() % 9) as usize + 1;
9478            let nr = (next() % 9) as usize + 1;
9479            let lk: Vec<i64> = (0..nl).map(|_| (next() % 4) as i64).collect();
9480            let rk: Vec<i64> = (0..nr).map(|_| (next() % 4) as i64).collect();
9481            let left = build(&lk, "lv");
9482            let right = build(&rk, "rv");
9483
9484            // Right rows grouped by key (payload = row index).
9485            let mut rg: BTreeMap<i64, Vec<i64>> = BTreeMap::new();
9486            for (j, &k) in rk.iter().enumerate() {
9487                rg.entry(k).or_default().push(j as i64);
9488            }
9489            let lkeys: std::collections::BTreeSet<i64> = lk.iter().copied().collect();
9490
9491            let read = |jt: JoinType| -> Vec<(i64, i64, i64)> {
9492                let merged = merge_dataframes(&left, &right, "k", jt).expect("merge");
9493                let ks = merged_values(&merged, "k").expect("k");
9494                let lvs = merged_values(&merged, "lv").expect("lv");
9495                let rvs = merged_values(&merged, "rv").expect("rv");
9496                let mut got: Vec<(i64, i64, i64)> = (0..ks.len())
9497                    .map(|i| (geti(&ks[i]), geti(&lvs[i]), geti(&rvs[i])))
9498                    .collect();
9499                got.sort_unstable();
9500                got
9501            };
9502
9503            // LEFT oracle: every left row appears; matched -> one row per right
9504            // match, unmatched -> NULL right payload (key still the left key).
9505            let mut exp_left: Vec<(i64, i64, i64)> = Vec::new();
9506            for (i, &k) in lk.iter().enumerate() {
9507                match rg.get(&k) {
9508                    Some(rps) => {
9509                        for &j in rps {
9510                            exp_left.push((k, i as i64, j));
9511                        }
9512                    }
9513                    None => exp_left.push((k, i as i64, NUL)),
9514                }
9515            }
9516            exp_left.sort_unstable();
9517            assert_eq!(
9518                read(JoinType::Left),
9519                exp_left,
9520                "left join value oracle iter={iter} lk={lk:?} rk={rk:?}"
9521            );
9522
9523            // OUTER oracle: LEFT plus right-only rows (no left match) with NULL
9524            // left payload and the coalesced key.
9525            let mut exp_outer = exp_left.clone();
9526            for (j, &k) in rk.iter().enumerate() {
9527                if !lkeys.contains(&k) {
9528                    exp_outer.push((k, NUL, j as i64));
9529                }
9530            }
9531            exp_outer.sort_unstable();
9532            assert_eq!(
9533                read(JoinType::Outer),
9534                exp_outer,
9535                "outer join value oracle iter={iter} lk={lk:?} rk={rk:?}"
9536            );
9537        }
9538    }
9539
9540    #[test]
9541    fn left_join_value_multiset_matches_unmatched_oracle_gp0ik() {
9542        use std::collections::BTreeMap;
9543
9544        // Value-level LEFT join oracle (br-frankenpandas-gp0ik): matched keys
9545        // emit the left/right cross product; unmatched left rows emit exactly one
9546        // row with a missing right payload. Ordering-independent sorted multiset.
9547        let mut state: u64 = 0x51de_cafe_2026_0618;
9548        let mut next = || {
9549            state = state
9550                .wrapping_mul(6_364_136_223_846_793_005)
9551                .wrapping_add(1_442_695_040_888_963_407);
9552            (state >> 33) as u32
9553        };
9554
9555        let build = |keys: &[i64], pname: &str| {
9556            let n = keys.len();
9557            DataFrame::from_dict(
9558                &["k", pname],
9559                vec![
9560                    (
9561                        "k",
9562                        keys.iter().copied().map(Scalar::Int64).collect::<Vec<_>>(),
9563                    ),
9564                    (pname, (0..n as i64).map(Scalar::Int64).collect::<Vec<_>>()),
9565                ],
9566            )
9567            .expect("frame")
9568        };
9569        let geti = |s: &Scalar| match s {
9570            Scalar::Int64(v) => *v,
9571            _ => i64::MIN,
9572        };
9573        let get_optional_i64 = |s: &Scalar| match s {
9574            Scalar::Int64(v) => Some(*v),
9575            value if value.is_missing() => None,
9576            _ => Some(i64::MIN),
9577        };
9578
9579        for iter in 0..1500u32 {
9580            let nl = (next() % 9) as usize + 1;
9581            let nr = (next() % 9) as usize + 1;
9582            let lk: Vec<i64> = (0..nl).map(|_| (next() % 5) as i64).collect();
9583            let rk: Vec<i64> = (0..nr).map(|_| (next() % 3) as i64).collect();
9584            let left = build(&lk, "lv");
9585            let right = build(&rk, "rv");
9586
9587            let merged = merge_dataframes(&left, &right, "k", JoinType::Left).expect("merge");
9588            let ks = merged_values(&merged, "k").expect("k");
9589            let lvs = merged_values(&merged, "lv").expect("lv");
9590            let rvs = merged_values(&merged, "rv").expect("rv");
9591            let mut got: Vec<(i64, i64, Option<i64>)> = (0..ks.len())
9592                .map(|i| (geti(&ks[i]), geti(&lvs[i]), get_optional_i64(&rvs[i])))
9593                .collect();
9594            got.sort_unstable();
9595
9596            let mut rg: BTreeMap<i64, Vec<i64>> = BTreeMap::new();
9597            for (i, &k) in rk.iter().enumerate() {
9598                rg.entry(k).or_default().push(i as i64);
9599            }
9600            let mut exp: Vec<(i64, i64, Option<i64>)> = Vec::new();
9601            for (left_pos, &k) in lk.iter().enumerate() {
9602                if let Some(right_positions) = rg.get(&k) {
9603                    for &right_pos in right_positions {
9604                        exp.push((k, left_pos as i64, Some(right_pos)));
9605                    }
9606                } else {
9607                    exp.push((k, left_pos as i64, None));
9608                }
9609            }
9610            exp.sort_unstable();
9611
9612            assert_eq!(
9613                got, exp,
9614                "left join value multiset iter={iter} lk={lk:?} rk={rk:?}"
9615            );
9616        }
9617    }
9618
9619    #[test]
9620    fn right_join_value_multiset_matches_unmatched_oracle_pd1h5() {
9621        use std::collections::BTreeMap;
9622
9623        // Value-level RIGHT join oracle (br-frankenpandas-pd1h5): matched keys
9624        // emit the left/right cross product; unmatched right rows emit exactly one
9625        // row with a missing left payload. Ordering-independent sorted multiset.
9626        let mut state: u64 = 0x7191_2026_0618_a015;
9627        let mut next = || {
9628            state = state
9629                .wrapping_mul(6_364_136_223_846_793_005)
9630                .wrapping_add(1_442_695_040_888_963_407);
9631            (state >> 33) as u32
9632        };
9633
9634        let build = |keys: &[i64], pname: &str| {
9635            let n = keys.len();
9636            DataFrame::from_dict(
9637                &["k", pname],
9638                vec![
9639                    (
9640                        "k",
9641                        keys.iter().copied().map(Scalar::Int64).collect::<Vec<_>>(),
9642                    ),
9643                    (pname, (0..n as i64).map(Scalar::Int64).collect::<Vec<_>>()),
9644                ],
9645            )
9646            .expect("frame")
9647        };
9648        let geti = |s: &Scalar| match s {
9649            Scalar::Int64(v) => *v,
9650            Scalar::Float64(v) if v.is_finite() => *v as i64,
9651            _ => i64::MIN,
9652        };
9653        let get_optional_i64 = |s: &Scalar| match s {
9654            Scalar::Int64(v) => Some(*v),
9655            Scalar::Float64(v) if v.is_finite() => Some(*v as i64),
9656            value if value.is_missing() => None,
9657            _ => Some(i64::MIN),
9658        };
9659
9660        for iter in 0..1500u32 {
9661            let nl = (next() % 9) as usize + 1;
9662            let nr = (next() % 9) as usize + 1;
9663            let lk: Vec<i64> = (0..nl).map(|_| (next() % 4) as i64).collect();
9664            let rk: Vec<i64> = (0..nr).map(|_| (next() % 5) as i64).collect();
9665            let left = build(&lk, "lv");
9666            let right = build(&rk, "rv");
9667
9668            let merged = merge_dataframes(&left, &right, "k", JoinType::Right).expect("merge");
9669            let ks = merged_values(&merged, "k").expect("k");
9670            let lvs = merged_values(&merged, "lv").expect("lv");
9671            let rvs = merged_values(&merged, "rv").expect("rv");
9672            let mut got: Vec<(i64, Option<i64>, i64)> = (0..ks.len())
9673                .map(|i| (geti(&ks[i]), get_optional_i64(&lvs[i]), geti(&rvs[i])))
9674                .collect();
9675            got.sort_unstable();
9676
9677            let mut lg: BTreeMap<i64, Vec<i64>> = BTreeMap::new();
9678            for (i, &k) in lk.iter().enumerate() {
9679                lg.entry(k).or_default().push(i as i64);
9680            }
9681            let mut exp: Vec<(i64, Option<i64>, i64)> = Vec::new();
9682            for (right_pos, &k) in rk.iter().enumerate() {
9683                if let Some(left_positions) = lg.get(&k) {
9684                    for &left_pos in left_positions {
9685                        exp.push((k, Some(left_pos), right_pos as i64));
9686                    }
9687                } else {
9688                    exp.push((k, None, right_pos as i64));
9689                }
9690            }
9691            exp.sort_unstable();
9692
9693            assert_eq!(
9694                got, exp,
9695                "right join value multiset iter={iter} lk={lk:?} rk={rk:?}"
9696            );
9697        }
9698    }
9699
9700    fn merged_values<'a>(
9701        merged: &'a MergedDataFrame,
9702        name: &str,
9703    ) -> Result<&'a [Scalar], JoinError> {
9704        Ok(merged
9705            .columns
9706            .get(name)
9707            .ok_or_else(|| {
9708                JoinError::Frame(FrameError::CompatibilityRejected(format!(
9709                    "missing merged column '{name}'"
9710                )))
9711            })?
9712            .values())
9713    }
9714
9715    fn merged_values_where_indicator(
9716        merged: &MergedDataFrame,
9717        column_name: &str,
9718        indicator_name: &str,
9719        indicator_value: &str,
9720    ) -> Result<Vec<Scalar>, JoinError> {
9721        let values = merged_values(merged, column_name)?;
9722        let indicators = merged_values(merged, indicator_name)?;
9723        Ok(values
9724            .iter()
9725            .zip(indicators.iter())
9726            .filter_map(|(value, indicator)| {
9727                if matches!(indicator, Scalar::Utf8(v) if v == indicator_value) {
9728                    Some(value.clone())
9729                } else {
9730                    None
9731                }
9732            })
9733            .collect())
9734    }
9735
9736    #[test]
9737    fn merge_inner_basic() {
9738        let left = make_left_df();
9739        let right = make_right_df();
9740        let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
9741
9742        assert_eq!(merged.columns.get("id").unwrap().len(), 2);
9743        assert_eq!(
9744            merged.columns.get("id").unwrap().values(),
9745            &[Scalar::Int64(2), Scalar::Int64(3)]
9746        );
9747        assert_eq!(
9748            merged.columns.get("val_a").unwrap().values(),
9749            &[Scalar::Int64(20), Scalar::Int64(30)]
9750        );
9751        assert_eq!(
9752            merged.columns.get("val_b").unwrap().values(),
9753            &[Scalar::Int64(200), Scalar::Int64(300)]
9754        );
9755    }
9756
9757    #[test]
9758    fn merge_inner_single_key_preserves_duplicate_probe_order() {
9759        let left = DataFrame::from_dict(
9760            &["id", "left_value"],
9761            vec![
9762                (
9763                    "id",
9764                    vec![Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(2)],
9765                ),
9766                (
9767                    "left_value",
9768                    vec![Scalar::Int64(20), Scalar::Int64(10), Scalar::Int64(21)],
9769                ),
9770            ],
9771        )
9772        .unwrap();
9773        let right = DataFrame::from_dict(
9774            &["id", "right_value"],
9775            vec![
9776                (
9777                    "id",
9778                    vec![Scalar::Int64(2), Scalar::Int64(2), Scalar::Int64(1)],
9779                ),
9780                (
9781                    "right_value",
9782                    vec![Scalar::Int64(200), Scalar::Int64(201), Scalar::Int64(100)],
9783                ),
9784            ],
9785        )
9786        .unwrap();
9787
9788        let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
9789
9790        assert_eq!(
9791            merged.columns.get("id").unwrap().values(),
9792            &[
9793                Scalar::Int64(2),
9794                Scalar::Int64(2),
9795                Scalar::Int64(1),
9796                Scalar::Int64(2),
9797                Scalar::Int64(2),
9798            ]
9799        );
9800        assert_eq!(
9801            merged.columns.get("left_value").unwrap().values(),
9802            &[
9803                Scalar::Int64(20),
9804                Scalar::Int64(20),
9805                Scalar::Int64(10),
9806                Scalar::Int64(21),
9807                Scalar::Int64(21),
9808            ]
9809        );
9810        assert_eq!(
9811            merged.columns.get("right_value").unwrap().values(),
9812            &[
9813                Scalar::Int64(200),
9814                Scalar::Int64(201),
9815                Scalar::Int64(100),
9816                Scalar::Int64(200),
9817                Scalar::Int64(201),
9818            ]
9819        );
9820    }
9821
9822    #[test]
9823    fn merge_inner_wide_sparse_int64_hash_matches_generic_validated_route() {
9824        let stride = 1_i64 << 30;
9825        let left = DataFrame::from_dict(
9826            &["id", "left_value"],
9827            vec![
9828                (
9829                    "id",
9830                    vec![3, 1, 3, 0, 2]
9831                        .into_iter()
9832                        .map(|v| Scalar::Int64(v * stride))
9833                        .collect(),
9834                ),
9835                (
9836                    "left_value",
9837                    vec![
9838                        Scalar::Int64(10),
9839                        Scalar::Int64(11),
9840                        Scalar::Int64(12),
9841                        Scalar::Int64(13),
9842                        Scalar::Int64(14),
9843                    ],
9844                ),
9845            ],
9846        )
9847        .unwrap();
9848        let right = DataFrame::from_dict(
9849            &["id", "right_value"],
9850            vec![
9851                (
9852                    "id",
9853                    vec![3, 2, 3, 1]
9854                        .into_iter()
9855                        .map(|v| Scalar::Int64(v * stride))
9856                        .collect(),
9857                ),
9858                (
9859                    "right_value",
9860                    vec![
9861                        Scalar::Int64(100),
9862                        Scalar::Int64(101),
9863                        Scalar::Int64(102),
9864                        Scalar::Int64(103),
9865                    ],
9866                ),
9867            ],
9868        )
9869        .unwrap();
9870
9871        let fast = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
9872        let generic = merge_dataframes_on_with_options(
9873            &left,
9874            &right,
9875            &["id"],
9876            &["id"],
9877            JoinType::Inner,
9878            MergeExecutionOptions {
9879                validate_mode: Some(MergeValidateMode::ManyToMany),
9880                ..MergeExecutionOptions::default()
9881            },
9882        )
9883        .unwrap();
9884
9885        assert_eq!(fast.index, generic.index);
9886        assert_eq!(fast.column_order, generic.column_order);
9887        assert_eq!(fast.columns, generic.columns);
9888        assert_eq!(
9889            fast.columns.get("id").unwrap().values(),
9890            &[
9891                Scalar::Int64(3 * stride),
9892                Scalar::Int64(3 * stride),
9893                Scalar::Int64(stride),
9894                Scalar::Int64(3 * stride),
9895                Scalar::Int64(3 * stride),
9896                Scalar::Int64(2 * stride),
9897            ]
9898        );
9899        assert_eq!(
9900            fast.columns.get("left_value").unwrap().values(),
9901            &[
9902                Scalar::Int64(10),
9903                Scalar::Int64(10),
9904                Scalar::Int64(11),
9905                Scalar::Int64(12),
9906                Scalar::Int64(12),
9907                Scalar::Int64(14),
9908            ]
9909        );
9910        assert_eq!(
9911            fast.columns.get("right_value").unwrap().values(),
9912            &[
9913                Scalar::Int64(100),
9914                Scalar::Int64(102),
9915                Scalar::Int64(103),
9916                Scalar::Int64(100),
9917                Scalar::Int64(102),
9918                Scalar::Int64(101),
9919            ]
9920        );
9921    }
9922
9923    #[test]
9924    fn dense_i64_inner_parallel_output_data_preserves_row_major_order() {
9925        let left_keys = vec![-1, 2, 1, 2, 3, 9];
9926        let min = 1;
9927        let max = 3;
9928        let offsets = vec![0, 2, 3, 5];
9929        let positions = vec![1usize, 4, 0, 2, 3];
9930        let left_values = vec![10, 20, 30, 40, 50, 60];
9931        let right_values = vec![100, 101, 102, 103, 104];
9932        let specs = vec![
9933            FusedInt64OutputColumn {
9934                name: "left".to_string(),
9935                side: FusedInt64Side::Left,
9936                values: &left_values,
9937            },
9938            FusedInt64OutputColumn {
9939                name: "right".to_string(),
9940                side: FusedInt64Side::Right,
9941                values: &right_values,
9942            },
9943        ];
9944
9945        let plan = DenseI64InnerOutputPlan {
9946            left_keys: &left_keys,
9947            min,
9948            max,
9949            offsets: &offsets,
9950            positions: &positions,
9951            output_len: 6,
9952        };
9953        let actual = build_dense_i64_inner_output_data(&specs, &plan);
9954
9955        // 4 matched left rows -> 6 output rows: avg fanout < 2, so the left
9956        // lane stays fully materialized alongside the right lane.
9957        assert_eq!(lane_expanded(&actual[0]), vec![20, 30, 30, 40, 50, 50]);
9958        assert_eq!(
9959            lane_expanded(&actual[1]),
9960            vec![100, 101, 104, 100, 102, 103]
9961        );
9962        assert!(matches!(actual[0], DenseI64LaneData::Full(_)));
9963        assert!(matches!(actual[1], DenseI64LaneData::Full(_)));
9964    }
9965
9966    fn lane_expanded(lane: &DenseI64LaneData) -> Vec<i64> {
9967        match lane {
9968            DenseI64LaneData::RepeatRunLengths { values, run_lens } => {
9969                let mut out = Vec::new();
9970                for (&value, &run_len) in values.iter().zip(run_lens.iter()) {
9971                    out.resize(out.len() + run_len, value);
9972                }
9973                out
9974            }
9975            DenseI64LaneData::RepeatedSlices { data, segments } => {
9976                let mut out = Vec::new();
9977                for &(start, len) in segments.iter() {
9978                    out.extend_from_slice(&data[start..start + len]);
9979                }
9980                out
9981            }
9982            DenseI64LaneData::Full(data) => data.clone(),
9983        }
9984    }
9985
9986    #[test]
9987    fn dense_i64_inner_high_fanout_emits_repeat_run_left_lanes() {
9988        // 2 matched left rows, each matching 3 right rows -> avg fanout 3:
9989        // left lane must come back as repeat runs and the right lane as
9990        // repeated slices. Their expansion equals the old full fill.
9991        let left_keys = vec![1, 7, 2];
9992        let min = 1;
9993        let max = 2;
9994        let offsets = vec![0, 3, 6];
9995        let positions = vec![0usize, 2, 4, 1, 3, 5];
9996        let left_values = vec![10, 20, 30];
9997        let right_values = vec![100, 101, 102, 103, 104, 105];
9998        let specs = vec![
9999            FusedInt64OutputColumn {
10000                name: "left".to_string(),
10001                side: FusedInt64Side::Left,
10002                values: &left_values,
10003            },
10004            FusedInt64OutputColumn {
10005                name: "right".to_string(),
10006                side: FusedInt64Side::Right,
10007                values: &right_values,
10008            },
10009        ];
10010
10011        let plan = DenseI64InnerOutputPlan {
10012            left_keys: &left_keys,
10013            min,
10014            max,
10015            offsets: &offsets,
10016            positions: &positions,
10017            output_len: 6,
10018        };
10019        let actual = build_dense_i64_inner_output_data(&specs, &plan);
10020
10021        assert!(matches!(
10022            actual[0],
10023            DenseI64LaneData::RepeatRunLengths { .. }
10024        ));
10025        assert!(matches!(actual[1], DenseI64LaneData::RepeatedSlices { .. }));
10026        assert_eq!(lane_expanded(&actual[0]), vec![10, 10, 10, 30, 30, 30]);
10027        assert_eq!(
10028            lane_expanded(&actual[1]),
10029            vec![100, 102, 104, 101, 103, 105]
10030        );
10031
10032        // The lazy Column built from shared run lengths is indistinguishable
10033        // from the eagerly materialized one (values, slice view, length,
10034        // equality).
10035        let lazy = fp_columnar::Column::from_i64_repeat_values_run_lengths(
10036            vec![10, 30],
10037            std::sync::Arc::from([3usize, 3]),
10038        );
10039        let eager = fp_columnar::Column::from_i64_values(vec![10, 10, 10, 30, 30, 30]);
10040        assert_eq!(lazy.len(), eager.len());
10041        assert_eq!(lazy.as_i64_slice(), eager.as_i64_slice());
10042        assert_eq!(lazy.values(), eager.values());
10043        assert_eq!(lazy, eager);
10044    }
10045
10046    #[test]
10047    fn dense_cycle_left_join_output_matches_dense_left_builder() {
10048        let left = DataFrame::from_dict(
10049            &["id", "v"],
10050            vec![
10051                (
10052                    "id",
10053                    vec![
10054                        Scalar::Int64(0),
10055                        Scalar::Int64(1),
10056                        Scalar::Int64(2),
10057                        Scalar::Int64(0),
10058                        Scalar::Int64(1),
10059                        Scalar::Int64(2),
10060                        Scalar::Int64(0),
10061                    ],
10062                ),
10063                (
10064                    "v",
10065                    vec![
10066                        Scalar::Int64(10),
10067                        Scalar::Int64(11),
10068                        Scalar::Int64(12),
10069                        Scalar::Int64(13),
10070                        Scalar::Int64(14),
10071                        Scalar::Int64(15),
10072                        Scalar::Int64(16),
10073                    ],
10074                ),
10075            ],
10076        )
10077        .unwrap();
10078        let right = DataFrame::from_dict(
10079            &["id", "rv"],
10080            vec![
10081                (
10082                    "id",
10083                    vec![
10084                        Scalar::Int64(1),
10085                        Scalar::Int64(2),
10086                        Scalar::Int64(1),
10087                        Scalar::Int64(2),
10088                    ],
10089                ),
10090                (
10091                    "rv",
10092                    vec![
10093                        Scalar::Int64(100),
10094                        Scalar::Int64(200),
10095                        Scalar::Int64(101),
10096                        Scalar::Int64(201),
10097                    ],
10098                ),
10099            ],
10100        )
10101        .unwrap();
10102        let suffixes = ResolvedMergeSuffixes::default();
10103        let left_key = left.column("id").unwrap();
10104        let right_key = right.column("id").unwrap();
10105
10106        let fast = build_single_key_dense_cycle_i64_left_merge_output(
10107            &left,
10108            &right,
10109            &["id"],
10110            &["id"],
10111            left_key,
10112            right_key,
10113            &suffixes,
10114        )
10115        .unwrap()
10116        .expect("dense-cycle route");
10117        let old = build_single_key_dense_i64_left_merge_output(
10118            &left,
10119            &right,
10120            &["id"],
10121            &["id"],
10122            left_key,
10123            right_key,
10124            &suffixes,
10125        )
10126        .unwrap()
10127        .expect("dense left route");
10128
10129        assert_eq!(fast.index, old.index);
10130        assert_eq!(fast.column_order, old.column_order);
10131        assert_eq!(fast.columns, old.columns);
10132        assert_eq!(
10133            fast.columns.get("v").unwrap().as_i64_slice(),
10134            old.columns.get("v").unwrap().as_i64_slice()
10135        );
10136        assert_eq!(
10137            fast.columns.get("rv").unwrap().values(),
10138            &[
10139                Scalar::Null(NullKind::Null),
10140                Scalar::Int64(100),
10141                Scalar::Int64(101),
10142                Scalar::Int64(200),
10143                Scalar::Int64(201),
10144                Scalar::Null(NullKind::Null),
10145                Scalar::Int64(100),
10146                Scalar::Int64(101),
10147                Scalar::Int64(200),
10148                Scalar::Int64(201),
10149                Scalar::Null(NullKind::Null),
10150            ]
10151        );
10152    }
10153
10154    #[test]
10155    fn merge_inner_ordered_identity_matches_generic_validated_route() {
10156        let left = DataFrame::from_dict(
10157            &["id", "v"],
10158            vec![
10159                (
10160                    "id",
10161                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
10162                ),
10163                (
10164                    "v",
10165                    vec![
10166                        Scalar::Int64(10),
10167                        Scalar::Null(NullKind::Null),
10168                        Scalar::Int64(30),
10169                    ],
10170                ),
10171            ],
10172        )
10173        .unwrap();
10174        let right = DataFrame::from_dict(
10175            &["id", "w"],
10176            vec![
10177                (
10178                    "id",
10179                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
10180                ),
10181                (
10182                    "w",
10183                    vec![Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(300)],
10184                ),
10185            ],
10186        )
10187        .unwrap();
10188
10189        let fast = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
10190        let generic = merge_dataframes_on_with_options(
10191            &left,
10192            &right,
10193            &["id"],
10194            &["id"],
10195            JoinType::Inner,
10196            MergeExecutionOptions {
10197                validate_mode: Some(MergeValidateMode::OneToOne),
10198                ..MergeExecutionOptions::default()
10199            },
10200        )
10201        .unwrap();
10202
10203        assert_eq!(fast.index, generic.index);
10204        assert_eq!(fast.column_order, generic.column_order);
10205        assert_eq!(fast.columns, generic.columns);
10206    }
10207
10208    #[test]
10209    fn merge_inner_dense_int64_fused_materialization_matches_generic_route() {
10210        let left = DataFrame::from_dict(
10211            &["id", "v", "overlap"],
10212            vec![
10213                (
10214                    "id",
10215                    vec![
10216                        Scalar::Int64(2),
10217                        Scalar::Int64(1),
10218                        Scalar::Int64(2),
10219                        Scalar::Int64(3),
10220                    ],
10221                ),
10222                (
10223                    "v",
10224                    vec![
10225                        Scalar::Int64(20),
10226                        Scalar::Int64(10),
10227                        Scalar::Int64(21),
10228                        Scalar::Int64(30),
10229                    ],
10230                ),
10231                (
10232                    "overlap",
10233                    vec![
10234                        Scalar::Int64(200),
10235                        Scalar::Int64(100),
10236                        Scalar::Int64(201),
10237                        Scalar::Int64(300),
10238                    ],
10239                ),
10240            ],
10241        )
10242        .unwrap();
10243        let right = DataFrame::from_dict(
10244            &["id", "w", "overlap"],
10245            vec![
10246                (
10247                    "id",
10248                    vec![
10249                        Scalar::Int64(2),
10250                        Scalar::Int64(2),
10251                        Scalar::Int64(1),
10252                        Scalar::Int64(4),
10253                    ],
10254                ),
10255                (
10256                    "w",
10257                    vec![
10258                        Scalar::Int64(2000),
10259                        Scalar::Int64(2001),
10260                        Scalar::Int64(1000),
10261                        Scalar::Int64(4000),
10262                    ],
10263                ),
10264                (
10265                    "overlap",
10266                    vec![
10267                        Scalar::Int64(20_000),
10268                        Scalar::Int64(20_001),
10269                        Scalar::Int64(10_000),
10270                        Scalar::Int64(40_000),
10271                    ],
10272                ),
10273            ],
10274        )
10275        .unwrap();
10276
10277        let fast = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
10278        let generic = merge_dataframes_on_with_options(
10279            &left,
10280            &right,
10281            &["id"],
10282            &["id"],
10283            JoinType::Inner,
10284            MergeExecutionOptions {
10285                validate_mode: Some(MergeValidateMode::ManyToMany),
10286                ..MergeExecutionOptions::default()
10287            },
10288        )
10289        .unwrap();
10290
10291        assert_eq!(fast.index, generic.index);
10292        assert_eq!(fast.column_order, generic.column_order);
10293        assert_eq!(fast.columns, generic.columns);
10294        assert_eq!(
10295            fast.column_order,
10296            ["id", "v", "overlap_x", "w", "overlap_y"]
10297        );
10298        assert_eq!(
10299            fast.columns.get("id").unwrap().values(),
10300            &[
10301                Scalar::Int64(2),
10302                Scalar::Int64(2),
10303                Scalar::Int64(1),
10304                Scalar::Int64(2),
10305                Scalar::Int64(2),
10306            ]
10307        );
10308        assert_eq!(
10309            fast.columns.get("w").unwrap().values(),
10310            &[
10311                Scalar::Int64(2000),
10312                Scalar::Int64(2001),
10313                Scalar::Int64(1000),
10314                Scalar::Int64(2000),
10315                Scalar::Int64(2001),
10316            ]
10317        );
10318        assert!(
10319            fast.columns
10320                .values()
10321                .all(|column| column.as_i64_slice().is_some())
10322        );
10323    }
10324
10325    #[test]
10326    fn merge_inner_ordered_unique_int64_subset_matches_generic_validated_route() {
10327        let left = DataFrame::from_dict(
10328            &["id", "v"],
10329            vec![
10330                (
10331                    "id",
10332                    vec![
10333                        Scalar::Int64(0),
10334                        Scalar::Int64(1),
10335                        Scalar::Int64(2),
10336                        Scalar::Int64(3),
10337                        Scalar::Int64(4),
10338                    ],
10339                ),
10340                (
10341                    "v",
10342                    vec![
10343                        Scalar::Int64(10),
10344                        Scalar::Int64(11),
10345                        Scalar::Int64(12),
10346                        Scalar::Int64(13),
10347                        Scalar::Int64(14),
10348                    ],
10349                ),
10350            ],
10351        )
10352        .unwrap();
10353        let right = DataFrame::from_dict(
10354            &["id", "w"],
10355            vec![
10356                (
10357                    "id",
10358                    vec![
10359                        Scalar::Int64(0),
10360                        Scalar::Int64(2),
10361                        Scalar::Int64(4),
10362                        Scalar::Int64(6),
10363                    ],
10364                ),
10365                (
10366                    "w",
10367                    vec![
10368                        Scalar::Int64(100),
10369                        Scalar::Int64(200),
10370                        Scalar::Int64(300),
10371                        Scalar::Int64(400),
10372                    ],
10373                ),
10374            ],
10375        )
10376        .unwrap();
10377
10378        let fast = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
10379        let generic = merge_dataframes_on_with_options(
10380            &left,
10381            &right,
10382            &["id"],
10383            &["id"],
10384            JoinType::Inner,
10385            MergeExecutionOptions {
10386                validate_mode: Some(MergeValidateMode::OneToOne),
10387                ..MergeExecutionOptions::default()
10388            },
10389        )
10390        .unwrap();
10391
10392        assert_eq!(fast.index, generic.index);
10393        assert_eq!(fast.column_order, generic.column_order);
10394        assert_eq!(fast.columns, generic.columns);
10395        assert_eq!(
10396            fast.columns.get("id").unwrap().values(),
10397            &[Scalar::Int64(0), Scalar::Int64(2), Scalar::Int64(4)]
10398        );
10399        assert_eq!(
10400            fast.columns.get("v").unwrap().values(),
10401            &[Scalar::Int64(10), Scalar::Int64(12), Scalar::Int64(14)]
10402        );
10403        assert_eq!(
10404            fast.columns.get("w").unwrap().values(),
10405            &[Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(300)]
10406        );
10407    }
10408
10409    #[test]
10410    fn merge_inner_ordered_identity_falls_back_for_non_identity_keys() {
10411        let cases = [
10412            (
10413                vec![Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(4)],
10414                vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
10415            ),
10416            (
10417                vec![
10418                    Scalar::Int64(1),
10419                    Scalar::Null(NullKind::Null),
10420                    Scalar::Int64(3),
10421                ],
10422                vec![
10423                    Scalar::Int64(1),
10424                    Scalar::Null(NullKind::Null),
10425                    Scalar::Int64(3),
10426                ],
10427            ),
10428        ];
10429
10430        for (left_keys, right_keys) in cases {
10431            let left = DataFrame::from_dict(
10432                &["id", "v"],
10433                vec![
10434                    ("id", left_keys),
10435                    (
10436                        "v",
10437                        vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
10438                    ),
10439                ],
10440            )
10441            .unwrap();
10442            let right = DataFrame::from_dict(
10443                &["id", "w"],
10444                vec![
10445                    ("id", right_keys),
10446                    (
10447                        "w",
10448                        vec![Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(300)],
10449                    ),
10450                ],
10451            )
10452            .unwrap();
10453
10454            let maybe_fast = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
10455            let generic = merge_dataframes_on_with_options(
10456                &left,
10457                &right,
10458                &["id"],
10459                &["id"],
10460                JoinType::Inner,
10461                MergeExecutionOptions {
10462                    validate_mode: Some(MergeValidateMode::OneToOne),
10463                    ..MergeExecutionOptions::default()
10464                },
10465            )
10466            .unwrap();
10467
10468            assert_eq!(maybe_fast.index, generic.index);
10469            assert_eq!(maybe_fast.column_order, generic.column_order);
10470            assert_eq!(maybe_fast.columns, generic.columns);
10471        }
10472    }
10473
10474    #[test]
10475    fn merge_default_suffixes_match_pandas() {
10476        // Overlapping non-key column "v" gets pandas default _x/_y suffixes.
10477        // Verified vs pandas 2.2.3: left{k:[1,2,3],v:[10,20,30]} merged inner on
10478        // k with right{k:[2,3,4],v:[200,300,400]} -> cols [k,v_x,v_y],
10479        // k=[2,3], v_x=[20,30], v_y=[200,300].
10480        let idx: Vec<_> = (0..3).map(|i| (i as i64).into()).collect();
10481        let left = fp_frame::DataFrame::from_series(vec![
10482            fp_frame::Series::from_values(
10483                "k",
10484                idx.clone(),
10485                vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
10486            )
10487            .unwrap(),
10488            fp_frame::Series::from_values(
10489                "v",
10490                idx.clone(),
10491                vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
10492            )
10493            .unwrap(),
10494        ])
10495        .unwrap();
10496        let right = fp_frame::DataFrame::from_series(vec![
10497            fp_frame::Series::from_values(
10498                "k",
10499                idx.clone(),
10500                vec![Scalar::Int64(2), Scalar::Int64(3), Scalar::Int64(4)],
10501            )
10502            .unwrap(),
10503            fp_frame::Series::from_values(
10504                "v",
10505                idx,
10506                vec![Scalar::Int64(200), Scalar::Int64(300), Scalar::Int64(400)],
10507            )
10508            .unwrap(),
10509        ])
10510        .unwrap();
10511        let merged = merge_dataframes(&left, &right, "k", JoinType::Inner).unwrap();
10512
10513        assert_eq!(
10514            merged.columns.get("k").unwrap().values(),
10515            &[Scalar::Int64(2), Scalar::Int64(3)],
10516            "k"
10517        );
10518        assert_eq!(
10519            merged.columns.get("v_x").unwrap().values(),
10520            &[Scalar::Int64(20), Scalar::Int64(30)],
10521            "v_x"
10522        );
10523        assert_eq!(
10524            merged.columns.get("v_y").unwrap().values(),
10525            &[Scalar::Int64(200), Scalar::Int64(300)],
10526            "v_y"
10527        );
10528        assert!(
10529            !merged.columns.contains_key("v"),
10530            "bare 'v' should be suffixed away"
10531        );
10532    }
10533
10534    #[test]
10535    fn merge_left_preserves_all_left_rows() {
10536        let left = make_left_df();
10537        let right = make_right_df();
10538        let merged = merge_dataframes(&left, &right, "id", JoinType::Left).unwrap();
10539
10540        assert_eq!(merged.columns.get("id").unwrap().len(), 3);
10541        assert_eq!(
10542            merged.columns.get("val_a").unwrap().values(),
10543            &[Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)]
10544        );
10545        // val_b: null for id=1, 200 for id=2, 300 for id=3
10546        assert!(merged.columns.get("val_b").unwrap().values()[0].is_missing());
10547        assert_eq!(
10548            merged.columns.get("val_b").unwrap().values()[1],
10549            Scalar::Int64(200)
10550        );
10551        assert_eq!(
10552            merged.columns.get("val_b").unwrap().values()[2],
10553            Scalar::Int64(300)
10554        );
10555    }
10556
10557    #[test]
10558    fn merge_left_ordered_unique_int64_subset_matches_generic_validated_route() {
10559        let left = DataFrame::from_dict(
10560            &["id", "v"],
10561            vec![
10562                (
10563                    "id",
10564                    vec![
10565                        Scalar::Int64(0),
10566                        Scalar::Int64(1),
10567                        Scalar::Int64(2),
10568                        Scalar::Int64(3),
10569                        Scalar::Int64(4),
10570                    ],
10571                ),
10572                (
10573                    "v",
10574                    vec![
10575                        Scalar::Int64(10),
10576                        Scalar::Int64(11),
10577                        Scalar::Int64(12),
10578                        Scalar::Int64(13),
10579                        Scalar::Int64(14),
10580                    ],
10581                ),
10582            ],
10583        )
10584        .unwrap();
10585        let right = DataFrame::from_dict(
10586            &["id", "w"],
10587            vec![
10588                (
10589                    "id",
10590                    vec![
10591                        Scalar::Int64(0),
10592                        Scalar::Int64(2),
10593                        Scalar::Int64(4),
10594                        Scalar::Int64(6),
10595                    ],
10596                ),
10597                (
10598                    "w",
10599                    vec![
10600                        Scalar::Int64(100),
10601                        Scalar::Int64(200),
10602                        Scalar::Int64(300),
10603                        Scalar::Int64(400),
10604                    ],
10605                ),
10606            ],
10607        )
10608        .unwrap();
10609
10610        let fast = merge_dataframes(&left, &right, "id", JoinType::Left).unwrap();
10611        let generic = merge_dataframes_on_with_options(
10612            &left,
10613            &right,
10614            &["id"],
10615            &["id"],
10616            JoinType::Left,
10617            MergeExecutionOptions {
10618                validate_mode: Some(MergeValidateMode::OneToOne),
10619                ..MergeExecutionOptions::default()
10620            },
10621        )
10622        .unwrap();
10623
10624        assert_eq!(fast.index, generic.index);
10625        assert_eq!(fast.column_order, generic.column_order);
10626        assert_eq!(fast.columns, generic.columns);
10627        assert_eq!(
10628            fast.columns.get("id").unwrap().values(),
10629            &[
10630                Scalar::Int64(0),
10631                Scalar::Int64(1),
10632                Scalar::Int64(2),
10633                Scalar::Int64(3),
10634                Scalar::Int64(4)
10635            ]
10636        );
10637        let right_values = fast.columns.get("w").unwrap().values();
10638        assert_eq!(right_values[0], Scalar::Int64(100));
10639        assert!(right_values[1].is_missing());
10640        assert_eq!(right_values[2], Scalar::Int64(200));
10641        assert!(right_values[3].is_missing());
10642        assert_eq!(right_values[4], Scalar::Int64(300));
10643    }
10644
10645    #[test]
10646    fn merge_left_dense_int64_duplicates_matches_generic_validated_route() {
10647        let left = DataFrame::from_dict(
10648            &["id", "v"],
10649            vec![
10650                (
10651                    "id",
10652                    vec![
10653                        Scalar::Int64(2),
10654                        Scalar::Int64(0),
10655                        Scalar::Int64(2),
10656                        Scalar::Int64(1),
10657                        Scalar::Int64(5),
10658                    ],
10659                ),
10660                (
10661                    "v",
10662                    vec![
10663                        Scalar::Int64(10),
10664                        Scalar::Int64(11),
10665                        Scalar::Int64(12),
10666                        Scalar::Int64(13),
10667                        Scalar::Int64(15),
10668                    ],
10669                ),
10670            ],
10671        )
10672        .unwrap();
10673        let right = DataFrame::from_dict(
10674            &["id", "w"],
10675            vec![
10676                (
10677                    "id",
10678                    vec![
10679                        Scalar::Int64(2),
10680                        Scalar::Int64(2),
10681                        Scalar::Int64(3),
10682                        Scalar::Int64(0),
10683                    ],
10684                ),
10685                (
10686                    "w",
10687                    vec![
10688                        Scalar::Int64(200),
10689                        Scalar::Int64(201),
10690                        Scalar::Int64(300),
10691                        Scalar::Int64(400),
10692                    ],
10693                ),
10694            ],
10695        )
10696        .unwrap();
10697
10698        let fast = merge_dataframes(&left, &right, "id", JoinType::Left).unwrap();
10699        let generic = merge_dataframes_on_with_options(
10700            &left,
10701            &right,
10702            &["id"],
10703            &["id"],
10704            JoinType::Left,
10705            MergeExecutionOptions {
10706                validate_mode: Some(MergeValidateMode::ManyToMany),
10707                ..MergeExecutionOptions::default()
10708            },
10709        )
10710        .unwrap();
10711
10712        assert_eq!(fast.index, generic.index);
10713        assert_eq!(fast.column_order, generic.column_order);
10714        assert_eq!(fast.columns, generic.columns);
10715        assert_eq!(
10716            fast.columns.get("id").unwrap().values(),
10717            &[
10718                Scalar::Int64(2),
10719                Scalar::Int64(2),
10720                Scalar::Int64(0),
10721                Scalar::Int64(2),
10722                Scalar::Int64(2),
10723                Scalar::Int64(1),
10724                Scalar::Int64(5),
10725            ]
10726        );
10727        let left_values = fast.columns.get("v").unwrap().values();
10728        assert_eq!(left_values[0], Scalar::Int64(10));
10729        assert_eq!(left_values[1], Scalar::Int64(10));
10730        assert_eq!(left_values[2], Scalar::Int64(11));
10731        assert_eq!(left_values[4], Scalar::Int64(12));
10732        assert_eq!(left_values[6], Scalar::Int64(15));
10733        let right_values = fast.columns.get("w").unwrap().values();
10734        assert_eq!(right_values[0], Scalar::Int64(200));
10735        assert_eq!(right_values[1], Scalar::Int64(201));
10736        assert_eq!(right_values[2], Scalar::Int64(400));
10737        assert!(right_values[5].is_missing());
10738        assert!(right_values[6].is_missing());
10739    }
10740
10741    #[test]
10742    fn merge_left_dense_cycle_probe_output_matches_materialized_positions_yq96z() {
10743        let left = DataFrame::from_dict(
10744            &["id", "v"],
10745            vec![
10746                (
10747                    "id",
10748                    vec![
10749                        Scalar::Int64(0),
10750                        Scalar::Int64(1),
10751                        Scalar::Int64(2),
10752                        Scalar::Int64(0),
10753                        Scalar::Int64(1),
10754                    ],
10755                ),
10756                (
10757                    "v",
10758                    vec![
10759                        Scalar::Int64(10),
10760                        Scalar::Int64(11),
10761                        Scalar::Int64(12),
10762                        Scalar::Int64(13),
10763                        Scalar::Int64(14),
10764                    ],
10765                ),
10766            ],
10767        )
10768        .unwrap();
10769        let right = DataFrame::from_dict(
10770            &["id", "w"],
10771            vec![
10772                (
10773                    "id",
10774                    vec![
10775                        Scalar::Int64(1),
10776                        Scalar::Int64(2),
10777                        Scalar::Int64(1),
10778                        Scalar::Int64(2),
10779                    ],
10780                ),
10781                (
10782                    "w",
10783                    vec![
10784                        Scalar::Int64(100),
10785                        Scalar::Int64(200),
10786                        Scalar::Int64(101),
10787                        Scalar::Int64(201),
10788                    ],
10789                ),
10790            ],
10791        )
10792        .unwrap();
10793        let left_key = left.columns().get("id").unwrap();
10794        let right_key = right.columns().get("id").unwrap();
10795        assert!(left_key.int64_dense_cycle_witness().is_some());
10796        assert!(right_key.int64_dense_cycle_witness().is_some());
10797        let suffixes = resolve_merge_suffixes(None);
10798
10799        let fused = build_single_key_dense_i64_left_merge_output(
10800            &left,
10801            &right,
10802            &["id"],
10803            &["id"],
10804            left_key,
10805            right_key,
10806            &suffixes,
10807        )
10808        .unwrap()
10809        .expect("dense-cycle left route should accept");
10810        let (left_positions, right_positions) =
10811            dense_int64_left_positions(left_key, right_key).unwrap();
10812        let materialized = build_single_key_dense_left_merge_output(
10813            &left,
10814            &right,
10815            &["id"],
10816            &["id"],
10817            &left_positions,
10818            &right_positions,
10819            &suffixes,
10820        )
10821        .unwrap();
10822
10823        assert_eq!(fused.index, materialized.index);
10824        assert_eq!(fused.column_order, materialized.column_order);
10825        assert_eq!(fused.columns, materialized.columns);
10826        assert_eq!(
10827            fused.columns.get("w").unwrap().values(),
10828            &[
10829                Scalar::Null(NullKind::Null),
10830                Scalar::Int64(100),
10831                Scalar::Int64(101),
10832                Scalar::Int64(200),
10833                Scalar::Int64(201),
10834                Scalar::Null(NullKind::Null),
10835                Scalar::Int64(100),
10836                Scalar::Int64(101),
10837            ]
10838        );
10839    }
10840
10841    #[test]
10842    fn merge_left_all_matched_dense_int64_fused_output_matches_sorted_generic_route() {
10843        let left = DataFrame::from_dict(
10844            &["id", "v"],
10845            vec![
10846                (
10847                    "id",
10848                    vec![
10849                        Scalar::Int64(0),
10850                        Scalar::Int64(0),
10851                        Scalar::Int64(1),
10852                        Scalar::Int64(1),
10853                        Scalar::Int64(2),
10854                    ],
10855                ),
10856                (
10857                    "v",
10858                    vec![
10859                        Scalar::Int64(10),
10860                        Scalar::Int64(11),
10861                        Scalar::Int64(20),
10862                        Scalar::Int64(21),
10863                        Scalar::Int64(30),
10864                    ],
10865                ),
10866            ],
10867        )
10868        .unwrap();
10869        let right = DataFrame::from_dict(
10870            &["id", "w"],
10871            vec![
10872                (
10873                    "id",
10874                    vec![
10875                        Scalar::Int64(0),
10876                        Scalar::Int64(0),
10877                        Scalar::Int64(1),
10878                        Scalar::Int64(2),
10879                        Scalar::Int64(2),
10880                    ],
10881                ),
10882                (
10883                    "w",
10884                    vec![
10885                        Scalar::Int64(100),
10886                        Scalar::Int64(101),
10887                        Scalar::Int64(200),
10888                        Scalar::Int64(300),
10889                        Scalar::Int64(301),
10890                    ],
10891                ),
10892            ],
10893        )
10894        .unwrap();
10895
10896        let fast = merge_dataframes(&left, &right, "id", JoinType::Left).unwrap();
10897        let generic = merge_dataframes_on_with_options(
10898            &left,
10899            &right,
10900            &["id"],
10901            &["id"],
10902            JoinType::Left,
10903            MergeExecutionOptions {
10904                sort: true,
10905                ..MergeExecutionOptions::default()
10906            },
10907        )
10908        .unwrap();
10909
10910        assert_eq!(fast.index, generic.index);
10911        assert_eq!(fast.column_order, generic.column_order);
10912        assert_eq!(fast.columns, generic.columns);
10913        assert_eq!(
10914            fast.columns.get("id").unwrap().values(),
10915            &[
10916                Scalar::Int64(0),
10917                Scalar::Int64(0),
10918                Scalar::Int64(0),
10919                Scalar::Int64(0),
10920                Scalar::Int64(1),
10921                Scalar::Int64(1),
10922                Scalar::Int64(2),
10923                Scalar::Int64(2),
10924            ]
10925        );
10926        assert_eq!(
10927            fast.columns.get("v").unwrap().values(),
10928            &[
10929                Scalar::Int64(10),
10930                Scalar::Int64(10),
10931                Scalar::Int64(11),
10932                Scalar::Int64(11),
10933                Scalar::Int64(20),
10934                Scalar::Int64(21),
10935                Scalar::Int64(30),
10936                Scalar::Int64(30),
10937            ]
10938        );
10939        assert_eq!(
10940            fast.columns.get("w").unwrap().values(),
10941            &[
10942                Scalar::Int64(100),
10943                Scalar::Int64(101),
10944                Scalar::Int64(100),
10945                Scalar::Int64(101),
10946                Scalar::Int64(200),
10947                Scalar::Int64(200),
10948                Scalar::Int64(300),
10949                Scalar::Int64(301),
10950            ]
10951        );
10952    }
10953
10954    #[test]
10955    fn merge_outer_ordered_unique_int64_subset_matches_generic_validated_route() {
10956        let left = DataFrame::from_dict(
10957            &["id", "v"],
10958            vec![
10959                (
10960                    "id",
10961                    vec![Scalar::Int64(0), Scalar::Int64(1), Scalar::Int64(3)],
10962                ),
10963                (
10964                    "v",
10965                    vec![Scalar::Int64(10), Scalar::Int64(11), Scalar::Int64(13)],
10966                ),
10967            ],
10968        )
10969        .unwrap();
10970        let right = DataFrame::from_dict(
10971            &["id", "w"],
10972            vec![
10973                (
10974                    "id",
10975                    vec![
10976                        Scalar::Int64(0),
10977                        Scalar::Int64(2),
10978                        Scalar::Int64(3),
10979                        Scalar::Int64(5),
10980                    ],
10981                ),
10982                (
10983                    "w",
10984                    vec![
10985                        Scalar::Int64(100),
10986                        Scalar::Int64(200),
10987                        Scalar::Int64(300),
10988                        Scalar::Int64(500),
10989                    ],
10990                ),
10991            ],
10992        )
10993        .unwrap();
10994
10995        let fast = merge_dataframes(&left, &right, "id", JoinType::Outer).unwrap();
10996        let generic = merge_dataframes_on_with_options(
10997            &left,
10998            &right,
10999            &["id"],
11000            &["id"],
11001            JoinType::Outer,
11002            MergeExecutionOptions {
11003                validate_mode: Some(MergeValidateMode::OneToOne),
11004                ..MergeExecutionOptions::default()
11005            },
11006        )
11007        .unwrap();
11008
11009        assert_eq!(fast.index, generic.index);
11010        assert_eq!(fast.column_order, generic.column_order);
11011        assert_eq!(fast.columns, generic.columns);
11012        assert_eq!(
11013            fast.columns.get("id").unwrap().values(),
11014            &[
11015                Scalar::Int64(0),
11016                Scalar::Int64(1),
11017                Scalar::Int64(2),
11018                Scalar::Int64(3),
11019                Scalar::Int64(5)
11020            ]
11021        );
11022        let left_values = fast.columns.get("v").unwrap().values();
11023        assert_eq!(left_values[0], Scalar::Float64(10.0));
11024        assert_eq!(left_values[1], Scalar::Float64(11.0));
11025        assert!(left_values[2].is_missing());
11026        assert_eq!(left_values[3], Scalar::Float64(13.0));
11027        assert!(left_values[4].is_missing());
11028        let right_values = fast.columns.get("w").unwrap().values();
11029        assert_eq!(right_values[0], Scalar::Float64(100.0));
11030        assert!(right_values[1].is_missing());
11031        assert_eq!(right_values[2], Scalar::Float64(200.0));
11032        assert_eq!(right_values[3], Scalar::Float64(300.0));
11033        assert_eq!(right_values[4], Scalar::Float64(500.0));
11034    }
11035
11036    #[test]
11037    fn merge_outer_dense_int64_duplicates_matches_generic_validated_route() {
11038        let left = DataFrame::from_dict(
11039            &["id", "v"],
11040            vec![
11041                (
11042                    "id",
11043                    vec![
11044                        Scalar::Int64(2),
11045                        Scalar::Int64(0),
11046                        Scalar::Int64(2),
11047                        Scalar::Int64(1),
11048                        Scalar::Int64(5),
11049                    ],
11050                ),
11051                (
11052                    "v",
11053                    vec![
11054                        Scalar::Int64(10),
11055                        Scalar::Int64(11),
11056                        Scalar::Int64(12),
11057                        Scalar::Int64(13),
11058                        Scalar::Int64(15),
11059                    ],
11060                ),
11061            ],
11062        )
11063        .unwrap();
11064        let right = DataFrame::from_dict(
11065            &["id", "w"],
11066            vec![
11067                (
11068                    "id",
11069                    vec![
11070                        Scalar::Int64(2),
11071                        Scalar::Int64(2),
11072                        Scalar::Int64(3),
11073                        Scalar::Int64(0),
11074                    ],
11075                ),
11076                (
11077                    "w",
11078                    vec![
11079                        Scalar::Int64(200),
11080                        Scalar::Int64(201),
11081                        Scalar::Int64(300),
11082                        Scalar::Int64(400),
11083                    ],
11084                ),
11085            ],
11086        )
11087        .unwrap();
11088
11089        let fast = merge_dataframes(&left, &right, "id", JoinType::Outer).unwrap();
11090        let generic = merge_dataframes_on_with_options(
11091            &left,
11092            &right,
11093            &["id"],
11094            &["id"],
11095            JoinType::Outer,
11096            MergeExecutionOptions {
11097                validate_mode: Some(MergeValidateMode::ManyToMany),
11098                ..MergeExecutionOptions::default()
11099            },
11100        )
11101        .unwrap();
11102
11103        assert_eq!(fast.index, generic.index);
11104        assert_eq!(fast.column_order, generic.column_order);
11105        assert_eq!(fast.columns, generic.columns);
11106        assert_eq!(
11107            fast.columns.get("id").unwrap().values(),
11108            &[
11109                Scalar::Int64(0),
11110                Scalar::Int64(1),
11111                Scalar::Int64(2),
11112                Scalar::Int64(2),
11113                Scalar::Int64(2),
11114                Scalar::Int64(2),
11115                Scalar::Int64(3),
11116                Scalar::Int64(5),
11117            ]
11118        );
11119        let left_values = fast.columns.get("v").unwrap().values();
11120        assert_eq!(left_values[0], Scalar::Float64(11.0));
11121        assert_eq!(left_values[1], Scalar::Float64(13.0));
11122        assert_eq!(left_values[2], Scalar::Float64(10.0));
11123        assert_eq!(left_values[5], Scalar::Float64(12.0));
11124        assert!(left_values[6].is_missing());
11125        assert_eq!(left_values[7], Scalar::Float64(15.0));
11126        let right_values = fast.columns.get("w").unwrap().values();
11127        assert_eq!(right_values[0], Scalar::Float64(400.0));
11128        assert!(right_values[1].is_missing());
11129        assert_eq!(right_values[2], Scalar::Float64(200.0));
11130        assert_eq!(right_values[3], Scalar::Float64(201.0));
11131        assert!(right_values[7].is_missing());
11132    }
11133
11134    #[test]
11135    fn merge_outer_all_matched_dense_int64_duplicates_matches_generic_validated_route() {
11136        let left = DataFrame::from_dict(
11137            &["id", "v"],
11138            vec![
11139                (
11140                    "id",
11141                    vec![
11142                        Scalar::Int64(2),
11143                        Scalar::Int64(1),
11144                        Scalar::Int64(2),
11145                        Scalar::Int64(1),
11146                    ],
11147                ),
11148                (
11149                    "v",
11150                    vec![
11151                        Scalar::Int64(20),
11152                        Scalar::Int64(10),
11153                        Scalar::Int64(21),
11154                        Scalar::Int64(11),
11155                    ],
11156                ),
11157            ],
11158        )
11159        .unwrap();
11160        let right = DataFrame::from_dict(
11161            &["id", "w"],
11162            vec![
11163                (
11164                    "id",
11165                    vec![
11166                        Scalar::Int64(1),
11167                        Scalar::Int64(2),
11168                        Scalar::Int64(1),
11169                        Scalar::Int64(2),
11170                    ],
11171                ),
11172                (
11173                    "w",
11174                    vec![
11175                        Scalar::Int64(100),
11176                        Scalar::Int64(200),
11177                        Scalar::Int64(101),
11178                        Scalar::Int64(201),
11179                    ],
11180                ),
11181            ],
11182        )
11183        .unwrap();
11184
11185        let fast = merge_dataframes(&left, &right, "id", JoinType::Outer).unwrap();
11186        let generic = merge_dataframes_on_with_options(
11187            &left,
11188            &right,
11189            &["id"],
11190            &["id"],
11191            JoinType::Outer,
11192            MergeExecutionOptions {
11193                validate_mode: Some(MergeValidateMode::ManyToMany),
11194                ..MergeExecutionOptions::default()
11195            },
11196        )
11197        .unwrap();
11198
11199        assert_eq!(fast.index, generic.index);
11200        assert_eq!(fast.column_order, generic.column_order);
11201        assert_eq!(fast.columns, generic.columns);
11202        assert_eq!(
11203            generic.columns.get("id").unwrap().values(),
11204            &[
11205                Scalar::Int64(1),
11206                Scalar::Int64(1),
11207                Scalar::Int64(1),
11208                Scalar::Int64(1),
11209                Scalar::Int64(2),
11210                Scalar::Int64(2),
11211                Scalar::Int64(2),
11212                Scalar::Int64(2),
11213            ]
11214        );
11215        assert!(
11216            generic
11217                .columns
11218                .values()
11219                .all(|column| column.as_i64_slice().is_some())
11220        );
11221    }
11222
11223    #[test]
11224    fn merge_outer_all_matched_dense_int64_fused_output_matches_sorted_generic_route() {
11225        let left = DataFrame::from_dict(
11226            &["id", "v"],
11227            vec![
11228                (
11229                    "id",
11230                    vec![
11231                        Scalar::Int64(2),
11232                        Scalar::Int64(1),
11233                        Scalar::Int64(2),
11234                        Scalar::Int64(1),
11235                    ],
11236                ),
11237                (
11238                    "v",
11239                    vec![
11240                        Scalar::Int64(20),
11241                        Scalar::Int64(10),
11242                        Scalar::Int64(21),
11243                        Scalar::Int64(11),
11244                    ],
11245                ),
11246            ],
11247        )
11248        .unwrap();
11249        let right = DataFrame::from_dict(
11250            &["id", "w"],
11251            vec![
11252                (
11253                    "id",
11254                    vec![
11255                        Scalar::Int64(1),
11256                        Scalar::Int64(2),
11257                        Scalar::Int64(1),
11258                        Scalar::Int64(2),
11259                    ],
11260                ),
11261                (
11262                    "w",
11263                    vec![
11264                        Scalar::Int64(100),
11265                        Scalar::Int64(200),
11266                        Scalar::Int64(101),
11267                        Scalar::Int64(201),
11268                    ],
11269                ),
11270            ],
11271        )
11272        .unwrap();
11273
11274        let fused = merge_dataframes(&left, &right, "id", JoinType::Outer).unwrap();
11275        let generic = merge_dataframes_on_with_options(
11276            &left,
11277            &right,
11278            &["id"],
11279            &["id"],
11280            JoinType::Outer,
11281            MergeExecutionOptions {
11282                validate_mode: Some(MergeValidateMode::ManyToMany),
11283                sort: true,
11284                ..MergeExecutionOptions::default()
11285            },
11286        )
11287        .unwrap();
11288
11289        assert_eq!(fused.index, generic.index);
11290        assert_eq!(fused.column_order, generic.column_order);
11291        assert_eq!(fused.columns, generic.columns);
11292    }
11293
11294    #[test]
11295    fn merge_right_dense_int64_duplicates_matches_generic_validated_route() {
11296        let left = DataFrame::from_dict(
11297            &["id", "v"],
11298            vec![
11299                (
11300                    "id",
11301                    vec![
11302                        Scalar::Int64(2),
11303                        Scalar::Int64(0),
11304                        Scalar::Int64(2),
11305                        Scalar::Int64(1),
11306                        Scalar::Int64(5),
11307                    ],
11308                ),
11309                (
11310                    "v",
11311                    vec![
11312                        Scalar::Int64(10),
11313                        Scalar::Int64(11),
11314                        Scalar::Int64(12),
11315                        Scalar::Int64(13),
11316                        Scalar::Int64(15),
11317                    ],
11318                ),
11319            ],
11320        )
11321        .unwrap();
11322        let right = DataFrame::from_dict(
11323            &["id", "w"],
11324            vec![
11325                (
11326                    "id",
11327                    vec![
11328                        Scalar::Int64(2),
11329                        Scalar::Int64(2),
11330                        Scalar::Int64(3),
11331                        Scalar::Int64(0),
11332                    ],
11333                ),
11334                (
11335                    "w",
11336                    vec![
11337                        Scalar::Int64(200),
11338                        Scalar::Int64(201),
11339                        Scalar::Int64(300),
11340                        Scalar::Int64(400),
11341                    ],
11342                ),
11343            ],
11344        )
11345        .unwrap();
11346
11347        let fast = merge_dataframes(&left, &right, "id", JoinType::Right).unwrap();
11348        let generic = merge_dataframes_on_with_options(
11349            &left,
11350            &right,
11351            &["id"],
11352            &["id"],
11353            JoinType::Right,
11354            MergeExecutionOptions {
11355                validate_mode: Some(MergeValidateMode::ManyToMany),
11356                ..MergeExecutionOptions::default()
11357            },
11358        )
11359        .unwrap();
11360
11361        assert_eq!(fast.index, generic.index);
11362        assert_eq!(fast.column_order, generic.column_order);
11363        assert_eq!(fast.columns, generic.columns);
11364        assert_eq!(
11365            fast.columns.get("id").unwrap().values(),
11366            &[
11367                Scalar::Int64(2),
11368                Scalar::Int64(2),
11369                Scalar::Int64(2),
11370                Scalar::Int64(2),
11371                Scalar::Int64(3),
11372                Scalar::Int64(0),
11373            ]
11374        );
11375        let left_values = fast.columns.get("v").unwrap().values();
11376        assert_eq!(left_values[0], Scalar::Int64(10));
11377        assert_eq!(left_values[1], Scalar::Int64(12));
11378        assert_eq!(left_values[2], Scalar::Int64(10));
11379        assert_eq!(left_values[3], Scalar::Int64(12));
11380        assert!(left_values[4].is_missing());
11381        assert_eq!(left_values[5], Scalar::Int64(11));
11382        let right_values = fast.columns.get("w").unwrap().values();
11383        assert_eq!(right_values[0], Scalar::Int64(200));
11384        assert_eq!(right_values[1], Scalar::Int64(200));
11385        assert_eq!(right_values[2], Scalar::Int64(201));
11386        assert_eq!(right_values[3], Scalar::Int64(201));
11387        assert_eq!(right_values[4], Scalar::Int64(300));
11388        assert_eq!(right_values[5], Scalar::Int64(400));
11389    }
11390
11391    #[test]
11392    fn merge_right_dense_cycle_probe_output_matches_materialized_positions_yq96z() {
11393        let left = DataFrame::from_dict(
11394            &["id", "v"],
11395            vec![
11396                (
11397                    "id",
11398                    vec![
11399                        Scalar::Int64(1),
11400                        Scalar::Int64(2),
11401                        Scalar::Int64(1),
11402                        Scalar::Int64(2),
11403                    ],
11404                ),
11405                (
11406                    "v",
11407                    vec![
11408                        Scalar::Int64(100),
11409                        Scalar::Int64(200),
11410                        Scalar::Int64(101),
11411                        Scalar::Int64(201),
11412                    ],
11413                ),
11414            ],
11415        )
11416        .unwrap();
11417        let right = DataFrame::from_dict(
11418            &["id", "w"],
11419            vec![
11420                (
11421                    "id",
11422                    vec![
11423                        Scalar::Int64(0),
11424                        Scalar::Int64(1),
11425                        Scalar::Int64(2),
11426                        Scalar::Int64(0),
11427                        Scalar::Int64(1),
11428                    ],
11429                ),
11430                (
11431                    "w",
11432                    vec![
11433                        Scalar::Int64(10),
11434                        Scalar::Int64(11),
11435                        Scalar::Int64(12),
11436                        Scalar::Int64(13),
11437                        Scalar::Int64(14),
11438                    ],
11439                ),
11440            ],
11441        )
11442        .unwrap();
11443        let left_key = left.columns().get("id").unwrap();
11444        let right_key = right.columns().get("id").unwrap();
11445        assert!(left_key.int64_dense_cycle_witness().is_some());
11446        assert!(right_key.int64_dense_cycle_witness().is_some());
11447        let suffixes = resolve_merge_suffixes(None);
11448
11449        let fused = build_single_key_dense_i64_right_merge_output(
11450            &left,
11451            &right,
11452            &["id"],
11453            &["id"],
11454            left_key,
11455            right_key,
11456            &suffixes,
11457        )
11458        .unwrap()
11459        .expect("dense-cycle right route should accept");
11460        let (left_positions, right_positions) =
11461            dense_int64_right_positions(left_key, right_key).unwrap();
11462        let materialized = build_single_key_dense_right_merge_output(
11463            &left,
11464            &right,
11465            &["id"],
11466            &["id"],
11467            &left_positions,
11468            &right_positions,
11469            &suffixes,
11470        )
11471        .unwrap();
11472
11473        assert_eq!(fused.index, materialized.index);
11474        assert_eq!(fused.column_order, materialized.column_order);
11475        assert_eq!(fused.columns, materialized.columns);
11476        assert_eq!(
11477            fused.columns.get("v").unwrap().values(),
11478            &[
11479                Scalar::Null(NullKind::Null),
11480                Scalar::Int64(100),
11481                Scalar::Int64(101),
11482                Scalar::Int64(200),
11483                Scalar::Int64(201),
11484                Scalar::Null(NullKind::Null),
11485                Scalar::Int64(100),
11486                Scalar::Int64(101),
11487            ]
11488        );
11489    }
11490
11491    #[test]
11492    fn merge_left_right_all_matched_dense_int64_duplicates_match_generic_validated_route() {
11493        let left = DataFrame::from_dict(
11494            &["id", "v"],
11495            vec![
11496                (
11497                    "id",
11498                    vec![
11499                        Scalar::Int64(2),
11500                        Scalar::Int64(1),
11501                        Scalar::Int64(2),
11502                        Scalar::Int64(1),
11503                    ],
11504                ),
11505                (
11506                    "v",
11507                    vec![
11508                        Scalar::Int64(20),
11509                        Scalar::Int64(10),
11510                        Scalar::Int64(21),
11511                        Scalar::Int64(11),
11512                    ],
11513                ),
11514            ],
11515        )
11516        .unwrap();
11517        let right = DataFrame::from_dict(
11518            &["id", "w"],
11519            vec![
11520                (
11521                    "id",
11522                    vec![
11523                        Scalar::Int64(1),
11524                        Scalar::Int64(2),
11525                        Scalar::Int64(1),
11526                        Scalar::Int64(2),
11527                    ],
11528                ),
11529                (
11530                    "w",
11531                    vec![
11532                        Scalar::Int64(100),
11533                        Scalar::Int64(200),
11534                        Scalar::Int64(101),
11535                        Scalar::Int64(201),
11536                    ],
11537                ),
11538            ],
11539        )
11540        .unwrap();
11541
11542        for join_type in [JoinType::Left, JoinType::Right] {
11543            let fast = merge_dataframes(&left, &right, "id", join_type).unwrap();
11544            let generic = merge_dataframes_on_with_options(
11545                &left,
11546                &right,
11547                &["id"],
11548                &["id"],
11549                join_type,
11550                MergeExecutionOptions {
11551                    validate_mode: Some(MergeValidateMode::ManyToMany),
11552                    ..MergeExecutionOptions::default()
11553                },
11554            )
11555            .unwrap();
11556
11557            assert_eq!(fast.index, generic.index);
11558            assert_eq!(fast.column_order, generic.column_order);
11559            assert_eq!(fast.columns, generic.columns);
11560            assert!(
11561                generic
11562                    .columns
11563                    .values()
11564                    .all(|column| column.as_i64_slice().is_some())
11565            );
11566        }
11567    }
11568
11569    #[test]
11570    fn merge_right_all_matched_dense_int64_fused_output_matches_dense_materialization() {
11571        let left = DataFrame::from_dict(
11572            &["id", "v"],
11573            vec![
11574                (
11575                    "id",
11576                    vec![
11577                        Scalar::Int64(2),
11578                        Scalar::Int64(1),
11579                        Scalar::Int64(2),
11580                        Scalar::Int64(1),
11581                    ],
11582                ),
11583                (
11584                    "v",
11585                    vec![
11586                        Scalar::Int64(20),
11587                        Scalar::Int64(10),
11588                        Scalar::Int64(21),
11589                        Scalar::Int64(11),
11590                    ],
11591                ),
11592            ],
11593        )
11594        .unwrap();
11595        let right = DataFrame::from_dict(
11596            &["id", "w"],
11597            vec![
11598                (
11599                    "id",
11600                    vec![
11601                        Scalar::Int64(1),
11602                        Scalar::Int64(2),
11603                        Scalar::Int64(1),
11604                        Scalar::Int64(2),
11605                    ],
11606                ),
11607                (
11608                    "w",
11609                    vec![
11610                        Scalar::Int64(100),
11611                        Scalar::Int64(200),
11612                        Scalar::Int64(101),
11613                        Scalar::Int64(201),
11614                    ],
11615                ),
11616            ],
11617        )
11618        .unwrap();
11619
11620        let fused = merge_dataframes(&left, &right, "id", JoinType::Right).unwrap();
11621        let left_key = left.columns().get("id").unwrap();
11622        let right_key = right.columns().get("id").unwrap();
11623        let (left_positions, right_positions) =
11624            dense_int64_right_positions(left_key, right_key).unwrap();
11625        let suffixes = resolve_merge_suffixes(None);
11626        let materialized = build_single_key_dense_right_merge_output(
11627            &left,
11628            &right,
11629            &["id"],
11630            &["id"],
11631            &left_positions,
11632            &right_positions,
11633            &suffixes,
11634        )
11635        .unwrap();
11636
11637        assert_eq!(fused.index, materialized.index);
11638        assert_eq!(fused.column_order, materialized.column_order);
11639        assert_eq!(fused.columns, materialized.columns);
11640        assert_eq!(
11641            fused.columns.get("id").unwrap().values(),
11642            &[
11643                Scalar::Int64(1),
11644                Scalar::Int64(1),
11645                Scalar::Int64(2),
11646                Scalar::Int64(2),
11647                Scalar::Int64(1),
11648                Scalar::Int64(1),
11649                Scalar::Int64(2),
11650                Scalar::Int64(2),
11651            ]
11652        );
11653        assert!(
11654            fused
11655                .columns
11656                .values()
11657                .all(|column| column.as_i64_slice().is_some())
11658        );
11659    }
11660
11661    #[test]
11662    fn merge_right_ordered_unique_int64_subset_matches_generic_validated_route() {
11663        let left = DataFrame::from_dict(
11664            &["id", "v"],
11665            vec![
11666                (
11667                    "id",
11668                    vec![Scalar::Int64(0), Scalar::Int64(1), Scalar::Int64(3)],
11669                ),
11670                (
11671                    "v",
11672                    vec![Scalar::Int64(10), Scalar::Int64(11), Scalar::Int64(13)],
11673                ),
11674            ],
11675        )
11676        .unwrap();
11677        let right = DataFrame::from_dict(
11678            &["id", "w"],
11679            vec![
11680                (
11681                    "id",
11682                    vec![
11683                        Scalar::Int64(0),
11684                        Scalar::Int64(2),
11685                        Scalar::Int64(3),
11686                        Scalar::Int64(5),
11687                    ],
11688                ),
11689                (
11690                    "w",
11691                    vec![
11692                        Scalar::Int64(100),
11693                        Scalar::Int64(200),
11694                        Scalar::Int64(300),
11695                        Scalar::Int64(500),
11696                    ],
11697                ),
11698            ],
11699        )
11700        .unwrap();
11701
11702        let fast = merge_dataframes(&left, &right, "id", JoinType::Right).unwrap();
11703        let generic = merge_dataframes_on_with_options(
11704            &left,
11705            &right,
11706            &["id"],
11707            &["id"],
11708            JoinType::Right,
11709            MergeExecutionOptions {
11710                validate_mode: Some(MergeValidateMode::OneToOne),
11711                ..MergeExecutionOptions::default()
11712            },
11713        )
11714        .unwrap();
11715
11716        assert_eq!(fast.index, generic.index);
11717        assert_eq!(fast.column_order, generic.column_order);
11718        assert_eq!(fast.columns, generic.columns);
11719        assert_eq!(
11720            fast.columns.get("id").unwrap().values(),
11721            &[
11722                Scalar::Int64(0),
11723                Scalar::Int64(2),
11724                Scalar::Int64(3),
11725                Scalar::Int64(5)
11726            ]
11727        );
11728        let left_values = fast.columns.get("v").unwrap().values();
11729        assert_eq!(left_values[0], Scalar::Int64(10));
11730        assert!(left_values[1].is_missing());
11731        assert_eq!(left_values[2], Scalar::Int64(13));
11732        assert!(left_values[3].is_missing());
11733        let right_values = fast.columns.get("w").unwrap().values();
11734        assert_eq!(right_values[0], Scalar::Int64(100));
11735        assert_eq!(right_values[1], Scalar::Int64(200));
11736        assert_eq!(right_values[2], Scalar::Int64(300));
11737        assert_eq!(right_values[3], Scalar::Int64(500));
11738    }
11739
11740    #[test]
11741    fn merge_right_preserves_all_right_rows() {
11742        let left = make_left_df();
11743        let right = make_right_df();
11744        let merged = merge_dataframes(&left, &right, "id", JoinType::Right).unwrap();
11745
11746        assert_eq!(merged.columns.get("id").unwrap().len(), 3);
11747        assert_eq!(
11748            merged.columns.get("val_b").unwrap().values(),
11749            &[Scalar::Int64(200), Scalar::Int64(300), Scalar::Int64(400)]
11750        );
11751        // val_a: 20 for id=2, 30 for id=3, null for id=4
11752        assert_eq!(
11753            merged.columns.get("val_a").unwrap().values()[0],
11754            Scalar::Int64(20)
11755        );
11756        assert_eq!(
11757            merged.columns.get("val_a").unwrap().values()[1],
11758            Scalar::Int64(30)
11759        );
11760        assert!(merged.columns.get("val_a").unwrap().values()[2].is_missing());
11761    }
11762
11763    #[test]
11764    fn merge_outer_contains_all_rows() {
11765        let left = make_left_df();
11766        let right = make_right_df();
11767        let merged = merge_dataframes(&left, &right, "id", JoinType::Outer).unwrap();
11768
11769        // ids: 1, 2, 3 from left + 4 from right = 4 rows
11770        assert_eq!(merged.columns.get("id").unwrap().len(), 4);
11771    }
11772
11773    #[test]
11774    fn merge_inner_sort_false_preserves_left_key_order() {
11775        let left = DataFrame::from_dict(
11776            &["id", "left_v"],
11777            vec![
11778                (
11779                    "id",
11780                    vec![Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(2)],
11781                ),
11782                (
11783                    "left_v",
11784                    vec![Scalar::Int64(20), Scalar::Int64(10), Scalar::Int64(21)],
11785                ),
11786            ],
11787        )
11788        .expect("left");
11789        let right = DataFrame::from_dict(
11790            &["id", "right_v"],
11791            vec![
11792                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
11793                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
11794            ],
11795        )
11796        .expect("right");
11797
11798        let merged = merge_dataframes_on_with_options(
11799            &left,
11800            &right,
11801            &["id"],
11802            &["id"],
11803            JoinType::Inner,
11804            MergeExecutionOptions::default(),
11805        )
11806        .expect("merge");
11807        assert_eq!(
11808            merged.columns.get("id").expect("id").values(),
11809            &[Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(2)]
11810        );
11811        assert_eq!(
11812            merged.columns.get("left_v").expect("left_v").values(),
11813            &[Scalar::Int64(20), Scalar::Int64(10), Scalar::Int64(21)]
11814        );
11815        assert_eq!(
11816            merged.columns.get("right_v").expect("right_v").values(),
11817            &[Scalar::Int64(200), Scalar::Int64(100), Scalar::Int64(200)]
11818        );
11819    }
11820
11821    #[test]
11822    fn merge_inner_sort_true_orders_join_keys_lexicographically() {
11823        let left = DataFrame::from_dict(
11824            &["id", "left_v"],
11825            vec![
11826                (
11827                    "id",
11828                    vec![Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(2)],
11829                ),
11830                (
11831                    "left_v",
11832                    vec![Scalar::Int64(20), Scalar::Int64(10), Scalar::Int64(21)],
11833                ),
11834            ],
11835        )
11836        .expect("left");
11837        let right = DataFrame::from_dict(
11838            &["id", "right_v"],
11839            vec![
11840                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
11841                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
11842            ],
11843        )
11844        .expect("right");
11845
11846        let merged = merge_dataframes_on_with_options(
11847            &left,
11848            &right,
11849            &["id"],
11850            &["id"],
11851            JoinType::Inner,
11852            MergeExecutionOptions {
11853                sort: true,
11854                ..MergeExecutionOptions::default()
11855            },
11856        )
11857        .expect("merge");
11858        assert_eq!(
11859            merged.columns.get("id").expect("id").values(),
11860            &[Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(2)]
11861        );
11862        assert_eq!(
11863            merged.columns.get("left_v").expect("left_v").values(),
11864            &[Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(21)]
11865        );
11866        assert_eq!(
11867            merged.columns.get("right_v").expect("right_v").values(),
11868            &[Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(200)]
11869        );
11870    }
11871
11872    #[test]
11873    fn merge_inner_sort_true_orders_float_keys_numerically() {
11874        let left = DataFrame::from_dict(
11875            &["id", "left_v"],
11876            vec![
11877                (
11878                    "id",
11879                    vec![
11880                        Scalar::Float64(1.5),
11881                        Scalar::Float64(-2.5),
11882                        Scalar::Float64(0.25),
11883                    ],
11884                ),
11885                (
11886                    "left_v",
11887                    vec![Scalar::Int64(15), Scalar::Int64(-25), Scalar::Int64(2)],
11888                ),
11889            ],
11890        )
11891        .expect("left");
11892        let right = DataFrame::from_dict(
11893            &["id", "right_v"],
11894            vec![
11895                (
11896                    "id",
11897                    vec![
11898                        Scalar::Float64(-2.5),
11899                        Scalar::Float64(0.25),
11900                        Scalar::Float64(1.5),
11901                    ],
11902                ),
11903                (
11904                    "right_v",
11905                    vec![Scalar::Int64(250), Scalar::Int64(25), Scalar::Int64(150)],
11906                ),
11907            ],
11908        )
11909        .expect("right");
11910
11911        let merged = merge_dataframes_on_with_options(
11912            &left,
11913            &right,
11914            &["id"],
11915            &["id"],
11916            JoinType::Inner,
11917            MergeExecutionOptions {
11918                sort: true,
11919                ..MergeExecutionOptions::default()
11920            },
11921        )
11922        .expect("merge");
11923
11924        assert_eq!(
11925            merged.columns.get("id").expect("id").values(),
11926            &[
11927                Scalar::Float64(-2.5),
11928                Scalar::Float64(0.25),
11929                Scalar::Float64(1.5)
11930            ]
11931        );
11932        assert_eq!(
11933            merged.columns.get("left_v").expect("left_v").values(),
11934            &[Scalar::Int64(-25), Scalar::Int64(2), Scalar::Int64(15)]
11935        );
11936        assert_eq!(
11937            merged.columns.get("right_v").expect("right_v").values(),
11938            &[Scalar::Int64(250), Scalar::Int64(25), Scalar::Int64(150)]
11939        );
11940    }
11941
11942    #[test]
11943    fn merge_right_sort_true_orders_join_keys_lexicographically() {
11944        let left = DataFrame::from_dict(
11945            &["id", "left_v"],
11946            vec![
11947                ("id", vec![Scalar::Int64(3), Scalar::Int64(1)]),
11948                ("left_v", vec![Scalar::Int64(30), Scalar::Int64(10)]),
11949            ],
11950        )
11951        .expect("left");
11952        let right = DataFrame::from_dict(
11953            &["id", "right_v"],
11954            vec![
11955                (
11956                    "id",
11957                    vec![Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(3)],
11958                ),
11959                (
11960                    "right_v",
11961                    vec![Scalar::Int64(200), Scalar::Int64(100), Scalar::Int64(300)],
11962                ),
11963            ],
11964        )
11965        .expect("right");
11966
11967        let merged = merge_dataframes_on_with_options(
11968            &left,
11969            &right,
11970            &["id"],
11971            &["id"],
11972            JoinType::Right,
11973            MergeExecutionOptions {
11974                sort: true,
11975                ..MergeExecutionOptions::default()
11976            },
11977        )
11978        .expect("merge");
11979        assert_eq!(
11980            merged.columns.get("id").expect("id").values(),
11981            &[Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)]
11982        );
11983        assert_eq!(
11984            merged.columns.get("left_v").expect("left_v").values(),
11985            &[
11986                Scalar::Int64(10),
11987                Scalar::Null(NullKind::Null),
11988                Scalar::Int64(30)
11989            ]
11990        );
11991        assert_eq!(
11992            merged.columns.get("right_v").expect("right_v").values(),
11993            &[Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(300)]
11994        );
11995    }
11996
11997    #[test]
11998    fn merge_column_name_conflict_adds_suffixes() {
11999        let left = DataFrame::from_dict(
12000            &["id", "val"],
12001            vec![
12002                ("id", vec![Scalar::Int64(1)]),
12003                ("val", vec![Scalar::Int64(10)]),
12004            ],
12005        )
12006        .unwrap();
12007        let right = DataFrame::from_dict(
12008            &["id", "val"],
12009            vec![
12010                ("id", vec![Scalar::Int64(1)]),
12011                ("val", vec![Scalar::Int64(99)]),
12012            ],
12013        )
12014        .unwrap();
12015
12016        let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
12017        assert!(merged.columns.contains_key("val_x"));
12018        assert!(merged.columns.contains_key("val_y"));
12019        assert_eq!(
12020            merged.columns.get("val_x").unwrap().values(),
12021            &[Scalar::Int64(10)]
12022        );
12023        assert_eq!(
12024            merged.columns.get("val_y").unwrap().values(),
12025            &[Scalar::Int64(99)]
12026        );
12027    }
12028
12029    #[test]
12030    fn merge_column_name_conflict_honors_custom_suffixes() {
12031        let left = DataFrame::from_dict(
12032            &["id", "val"],
12033            vec![
12034                ("id", vec![Scalar::Int64(1)]),
12035                ("val", vec![Scalar::Int64(10)]),
12036            ],
12037        )
12038        .expect("left");
12039        let right = DataFrame::from_dict(
12040            &["id", "val"],
12041            vec![
12042                ("id", vec![Scalar::Int64(1)]),
12043                ("val", vec![Scalar::Int64(99)]),
12044            ],
12045        )
12046        .expect("right");
12047
12048        let merged = merge_dataframes_on_with_options(
12049            &left,
12050            &right,
12051            &["id"],
12052            &["id"],
12053            JoinType::Inner,
12054            MergeExecutionOptions {
12055                suffixes: Some([Some("_L".to_owned()), Some("_R".to_owned())]),
12056                ..MergeExecutionOptions::default()
12057            },
12058        )
12059        .expect("merge");
12060        assert!(merged.columns.contains_key("val_L"));
12061        assert!(merged.columns.contains_key("val_R"));
12062        assert_eq!(
12063            merged.columns.get("val_L").expect("left suffixed").values(),
12064            &[Scalar::Int64(10)]
12065        );
12066        assert_eq!(
12067            merged
12068                .columns
12069                .get("val_R")
12070                .expect("right suffixed")
12071                .values(),
12072            &[Scalar::Int64(99)]
12073        );
12074    }
12075
12076    #[test]
12077    fn merge_column_name_conflict_allows_one_sided_suffix() {
12078        let left = DataFrame::from_dict(
12079            &["id", "val"],
12080            vec![
12081                ("id", vec![Scalar::Int64(1)]),
12082                ("val", vec![Scalar::Int64(10)]),
12083            ],
12084        )
12085        .expect("left");
12086        let right = DataFrame::from_dict(
12087            &["id", "val"],
12088            vec![
12089                ("id", vec![Scalar::Int64(1)]),
12090                ("val", vec![Scalar::Int64(99)]),
12091            ],
12092        )
12093        .expect("right");
12094
12095        let merged = merge_dataframes_on_with_options(
12096            &left,
12097            &right,
12098            &["id"],
12099            &["id"],
12100            JoinType::Inner,
12101            MergeExecutionOptions {
12102                suffixes: Some([None, Some("_r".to_owned())]),
12103                ..MergeExecutionOptions::default()
12104            },
12105        )
12106        .expect("merge");
12107        assert!(merged.columns.contains_key("val"));
12108        assert!(merged.columns.contains_key("val_r"));
12109        assert_eq!(
12110            merged.columns.get("val").expect("left unsuffixed").values(),
12111            &[Scalar::Int64(10)]
12112        );
12113        assert_eq!(
12114            merged
12115                .columns
12116                .get("val_r")
12117                .expect("right suffixed")
12118                .values(),
12119            &[Scalar::Int64(99)]
12120        );
12121    }
12122
12123    #[test]
12124    fn merge_column_name_conflict_rejects_missing_suffixes_for_overlap() {
12125        let left = DataFrame::from_dict(
12126            &["id", "val"],
12127            vec![
12128                ("id", vec![Scalar::Int64(1)]),
12129                ("val", vec![Scalar::Int64(10)]),
12130            ],
12131        )
12132        .expect("left");
12133        let right = DataFrame::from_dict(
12134            &["id", "val"],
12135            vec![
12136                ("id", vec![Scalar::Int64(1)]),
12137                ("val", vec![Scalar::Int64(99)]),
12138            ],
12139        )
12140        .expect("right");
12141
12142        let err = merge_dataframes_on_with_options(
12143            &left,
12144            &right,
12145            &["id"],
12146            &["id"],
12147            JoinType::Inner,
12148            MergeExecutionOptions {
12149                suffixes: Some([Some(String::new()), Some(String::new())]),
12150                ..MergeExecutionOptions::default()
12151            },
12152        )
12153        .expect_err("merge should reject overlapping columns without suffixes");
12154        assert!(format!("{err}").contains("columns overlap but no suffix specified"));
12155    }
12156
12157    #[test]
12158    fn merge_column_name_conflict_rejects_duplicate_output_columns_from_suffixes() {
12159        let left = DataFrame::from_dict(
12160            &["id", "val", "val_L"],
12161            vec![
12162                ("id", vec![Scalar::Int64(1)]),
12163                ("val", vec![Scalar::Int64(10)]),
12164                ("val_L", vec![Scalar::Int64(77)]),
12165            ],
12166        )
12167        .expect("left");
12168        let right = DataFrame::from_dict(
12169            &["id", "val"],
12170            vec![
12171                ("id", vec![Scalar::Int64(1)]),
12172                ("val", vec![Scalar::Int64(99)]),
12173            ],
12174        )
12175        .expect("right");
12176
12177        let err = merge_dataframes_on_with_options(
12178            &left,
12179            &right,
12180            &["id"],
12181            &["id"],
12182            JoinType::Inner,
12183            MergeExecutionOptions {
12184                suffixes: Some([Some("_L".to_owned()), Some("_R".to_owned())]),
12185                ..MergeExecutionOptions::default()
12186            },
12187        )
12188        .expect_err("merge should reject duplicate output names caused by suffixes");
12189        assert!(format!("{err}").contains("duplicate output column"));
12190    }
12191
12192    #[test]
12193    fn merge_missing_key_column_errors() {
12194        let left = make_left_df();
12195        let right = make_right_df();
12196        let err = merge_dataframes(&left, &right, "nonexistent", JoinType::Inner)
12197            .expect_err("should fail");
12198        assert!(format!("{err}").contains("nonexistent"));
12199    }
12200
12201    #[test]
12202    fn merge_duplicate_keys_multiply_cardinality() {
12203        let left = DataFrame::from_dict(
12204            &["id", "a"],
12205            vec![
12206                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
12207                ("a", vec![Scalar::Int64(10), Scalar::Int64(20)]),
12208            ],
12209        )
12210        .unwrap();
12211        let right = DataFrame::from_dict(
12212            &["id", "b"],
12213            vec![
12214                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
12215                ("b", vec![Scalar::Int64(100), Scalar::Int64(200)]),
12216            ],
12217        )
12218        .unwrap();
12219
12220        let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
12221        // 2 left × 2 right = 4 rows
12222        assert_eq!(merged.columns.get("id").unwrap().len(), 4);
12223    }
12224
12225    #[test]
12226    fn ordered_identity_int64_guard_uses_strict_unique_certificate() {
12227        let left = fp_columnar::Column::from_i64_values(vec![1, 2, 3, 4]);
12228        let right = fp_columnar::Column::from_i64_values(vec![1, 2, 3, 4]);
12229        assert!(ordered_identity_int64_keys_match(&left, &right));
12230
12231        let duplicate_left = fp_columnar::Column::from_i64_values(vec![1, 1, 2]);
12232        let duplicate_right = fp_columnar::Column::from_i64_values(vec![1, 1, 2]);
12233        assert!(!ordered_identity_int64_keys_match(
12234            &duplicate_left,
12235            &duplicate_right
12236        ));
12237
12238        let unsorted_left = fp_columnar::Column::from_i64_values(vec![2, 1, 3]);
12239        let unsorted_right = fp_columnar::Column::from_i64_values(vec![2, 1, 3]);
12240        assert!(ordered_identity_int64_keys_match(
12241            &unsorted_left,
12242            &unsorted_right
12243        ));
12244    }
12245
12246    #[test]
12247    fn merge_identical_duplicate_keys_cross_join_values_jdupk() {
12248        // Identical left/right key columns that contain duplicates must NOT take
12249        // the identity 1:1 fast path: pandas cross-joins each duplicate, so a=10
12250        // and a=20 each pair with b=100 and b=200. (br-frankenpandas-jdupk)
12251        let left = DataFrame::from_dict(
12252            &["id", "a"],
12253            vec![
12254                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
12255                ("a", vec![Scalar::Int64(10), Scalar::Int64(20)]),
12256            ],
12257        )
12258        .unwrap();
12259        let right = DataFrame::from_dict(
12260            &["id", "b"],
12261            vec![
12262                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
12263                ("b", vec![Scalar::Int64(100), Scalar::Int64(200)]),
12264            ],
12265        )
12266        .unwrap();
12267
12268        let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
12269        assert_eq!(
12270            merged.columns.get("a").unwrap().values(),
12271            &[
12272                Scalar::Int64(10),
12273                Scalar::Int64(10),
12274                Scalar::Int64(20),
12275                Scalar::Int64(20)
12276            ]
12277        );
12278        assert_eq!(
12279            merged.columns.get("b").unwrap().values(),
12280            &[
12281                Scalar::Int64(100),
12282                Scalar::Int64(200),
12283                Scalar::Int64(100),
12284                Scalar::Int64(200)
12285            ]
12286        );
12287    }
12288
12289    #[test]
12290    fn ordered_unique_utf8_inner_positions_match_left_major_hash_order_53lat() {
12291        let left = contiguous_utf8_column(&["a", "b", "d", "f"]);
12292        let right = contiguous_utf8_column(&["b", "c", "f"]);
12293        let (left_positions, right_positions) =
12294            ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
12295
12296        assert_eq!(left_positions, vec![1, 3]);
12297        assert_eq!(right_positions, vec![0, 2]);
12298
12299        let merged = merge_dataframes(
12300            &utf8_key_merge_frame(&["a", "b", "d", "f"], "lv", 10),
12301            &utf8_key_merge_frame(&["b", "c", "f"], "rv", 20),
12302            "id",
12303            JoinType::Inner,
12304        )
12305        .unwrap();
12306        assert_eq!(
12307            merged.columns.get("lv").unwrap().values(),
12308            &[Scalar::Int64(11), Scalar::Int64(13)]
12309        );
12310        assert_eq!(
12311            merged.columns.get("rv").unwrap().values(),
12312            &[Scalar::Int64(20), Scalar::Int64(22)]
12313        );
12314    }
12315
12316    #[test]
12317    fn ordered_unique_utf8_seek_bound_preserves_late_overlap_lr52z() {
12318        let left = contiguous_utf8_column(&["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]);
12319        let right = contiguous_utf8_column(&["h", "i", "j", "k"]);
12320        let (left_bytes, left_offsets) =
12321            strictly_increasing_utf8_key_spans(&left).expect("sorted left");
12322
12323        assert_eq!(utf8_span_lower_bound(left_bytes, left_offsets, b"h"), 7);
12324
12325        let (left_positions, right_positions) =
12326            ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
12327        assert_eq!(left_positions, vec![7, 8, 9]);
12328        assert_eq!(right_positions, vec![0, 1, 2]);
12329
12330        let disjoint_left = contiguous_utf8_column(&["a", "b"]);
12331        let disjoint_right = contiguous_utf8_column(&["c", "d"]);
12332        let (left_positions, right_positions) =
12333            ordered_unique_utf8_inner_positions(&disjoint_left, &disjoint_right)
12334                .expect("ordered disjoint utf8 positions");
12335        assert!(left_positions.is_empty());
12336        assert!(right_positions.is_empty());
12337    }
12338
12339    #[test]
12340    fn ordered_unique_utf8_bulk_fixed_width_window_jbyuc11() {
12341        let left = contiguous_utf8_column(&["k000", "k001", "k002", "k003", "k004"]);
12342        let right = contiguous_utf8_column(&["k002", "k003", "k004", "k005"]);
12343
12344        let (left_positions, right_positions) =
12345            ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
12346        assert_eq!(left_positions, vec![2, 3, 4]);
12347        assert_eq!(right_positions, vec![0, 1, 2]);
12348    }
12349
12350    #[test]
12351    fn ordered_unique_utf8_bulk_window_returns_range_plan_jbyuc11111() {
12352        let left = contiguous_utf8_column(&["k000", "k001", "k002", "k003", "k004"]);
12353        let right = contiguous_utf8_column(&["k002", "k003", "k004", "k005"]);
12354
12355        let plan =
12356            ordered_unique_utf8_inner_position_plan(&left, &right).expect("ordered utf8 plan");
12357
12358        assert_eq!(
12359            plan,
12360            InnerPositionPlan::ContiguousRanges {
12361                left_start: 2,
12362                right_start: 0,
12363                len: 3
12364            }
12365        );
12366    }
12367
12368    #[test]
12369    fn ordered_unique_utf8_lower_hex_certificate_returns_range_plan_jbyuc111111() {
12370        let left =
12371            contiguous_utf8_column(&["id_0000000a", "id_0000000b", "id_0000000c", "id_0000000d"]);
12372        let right = contiguous_utf8_column(&["id_0000000c", "id_0000000d", "id_0000000e"]);
12373        let (_, _, left_cert) = left
12374            .as_lower_hex_sequence_utf8_contiguous()
12375            .expect("left sequence certificate");
12376        let (_, _, right_cert) = right
12377            .as_lower_hex_sequence_utf8_contiguous()
12378            .expect("right sequence certificate");
12379
12380        assert_eq!(
12381            ordered_utf8_lower_hex_overlap_len(left_cert, right_cert, 2, 4, 0, 3),
12382            Some(2)
12383        );
12384        assert_eq!(
12385            lower_hex_overlap_plan_from_certificates(&left, &right),
12386            Some(InnerPositionPlan::ContiguousRanges {
12387                left_start: 2,
12388                right_start: 0,
12389                len: 2
12390            })
12391        );
12392        let plan =
12393            ordered_unique_utf8_inner_position_plan(&left, &right).expect("ordered utf8 plan");
12394        assert_eq!(
12395            plan,
12396            InnerPositionPlan::ContiguousRanges {
12397                left_start: 2,
12398                right_start: 0,
12399                len: 2
12400            }
12401        );
12402    }
12403
12404    #[test]
12405    fn ordered_unique_utf8_lower_hex_arithmetic_empty_overlap_jbyuc1111111111() {
12406        let left = contiguous_utf8_column(&["id_00000001", "id_00000002", "id_00000003"]);
12407        let right = contiguous_utf8_column(&["id_00000008", "id_00000009"]);
12408
12409        assert_eq!(
12410            lower_hex_overlap_plan_from_certificates(&left, &right),
12411            Some(InnerPositionPlan::Gather {
12412                left_positions: Vec::new(),
12413                right_positions: Vec::new(),
12414            })
12415        );
12416        let (left_positions, right_positions) =
12417            ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
12418        assert!(left_positions.is_empty());
12419        assert!(right_positions.is_empty());
12420    }
12421
12422    #[test]
12423    fn ordered_unique_utf8_lower_hex_prefix_mismatch_falls_back_jbyuc1111111111() {
12424        let left = contiguous_utf8_column(&["aa_00000001", "aa_00000002", "aa_00000003"]);
12425        let right = contiguous_utf8_column(&["bb_00000001", "bb_00000002", "bb_00000003"]);
12426
12427        assert!(
12428            lower_hex_overlap_plan_from_certificates(&left, &right).is_none(),
12429            "matching lower-hex counters with different prefixes must not use arithmetic overlap"
12430        );
12431        let (left_positions, right_positions) =
12432            ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
12433        assert!(left_positions.is_empty());
12434        assert!(right_positions.is_empty());
12435    }
12436
12437    #[test]
12438    fn ordered_utf8_contiguous_no_overlap_output_fast_path_jbyuc111111111() -> Result<(), String> {
12439        let left = utf8_key_merge_frame(
12440            &["id_00000000", "id_00000001", "id_00000002", "id_00000003"],
12441            "lv",
12442            10,
12443        );
12444        let right = utf8_key_merge_frame(&["id_00000002", "id_00000003", "id_00000004"], "rv", 100);
12445        let plan = ordered_unique_utf8_inner_position_plan(
12446            left.columns()
12447                .get("id")
12448                .ok_or_else(|| "left key column missing".to_owned())?,
12449            right
12450                .columns()
12451                .get("id")
12452                .ok_or_else(|| "right key column missing".to_owned())?,
12453        )
12454        .ok_or_else(|| "ordered utf8 plan unavailable".to_owned())?;
12455        let InnerPositionPlan::ContiguousRanges {
12456            left_start,
12457            right_start,
12458            len,
12459        } = plan
12460        else {
12461            return Err("expected contiguous range plan".to_owned());
12462        };
12463
12464        let merged = build_single_key_inner_contiguous_no_overlap_output(
12465            &left,
12466            &right,
12467            &["id"],
12468            &["id"],
12469            PositionSelection::ContiguousRange {
12470                start: left_start,
12471                len,
12472            },
12473            PositionSelection::ContiguousRange {
12474                start: right_start,
12475                len,
12476            },
12477        )
12478        .ok_or_else(|| "no-overlap contiguous output fast path missed".to_owned())?;
12479
12480        assert_eq!(merged.column_order, ["id", "lv", "rv"]);
12481        let id_output = merged
12482            .columns
12483            .get("id")
12484            .ok_or_else(|| "id output missing".to_owned())?;
12485        let (prefix, certificate, certificate_len) = id_output
12486            .as_lower_hex_sequence_utf8()
12487            .ok_or_else(|| "id output lost lower-hex sequence witness".to_owned())?;
12488        assert_eq!(prefix, b"id_");
12489        assert_eq!(certificate.start(), 2);
12490        assert_eq!(certificate.hex_width(), 8);
12491        assert_eq!(certificate_len, 2);
12492        assert_eq!(
12493            id_output.values(),
12494            &[
12495                Scalar::Utf8("id_00000002".to_owned()),
12496                Scalar::Utf8("id_00000003".to_owned())
12497            ]
12498        );
12499        assert_eq!(
12500            merged
12501                .columns
12502                .get("lv")
12503                .ok_or_else(|| "lv output missing".to_owned())?
12504                .values(),
12505            &[Scalar::Int64(12), Scalar::Int64(13)]
12506        );
12507        assert_eq!(
12508            merged
12509                .columns
12510                .get("rv")
12511                .ok_or_else(|| "rv output missing".to_owned())?
12512                .values(),
12513            &[Scalar::Int64(100), Scalar::Int64(101)]
12514        );
12515
12516        let overlapping_right =
12517            utf8_key_merge_frame(&["id_00000002", "id_00000003", "id_00000004"], "lv", 100);
12518        assert!(
12519            build_single_key_inner_contiguous_no_overlap_output(
12520                &left,
12521                &overlapping_right,
12522                &["id"],
12523                &["id"],
12524                PositionSelection::ContiguousRange {
12525                    start: left_start,
12526                    len,
12527                },
12528                PositionSelection::ContiguousRange {
12529                    start: right_start,
12530                    len,
12531                },
12532            )
12533            .is_none(),
12534            "overlapping non-key columns must keep the suffix/error generic path"
12535        );
12536        Ok(())
12537    }
12538
12539    #[test]
12540    fn ordered_unique_utf8_uncertified_fixed_width_still_matches_jbyuc111111() {
12541        let left = contiguous_utf8_column(&["k00A", "k00B", "k00C", "k00D"]);
12542        let right = contiguous_utf8_column(&["k00B", "k00D"]);
12543
12544        assert!(left.as_lower_hex_sequence_utf8_contiguous().is_none());
12545        assert!(right.as_lower_hex_sequence_utf8_contiguous().is_none());
12546        let (left_positions, right_positions) =
12547            ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
12548        assert_eq!(left_positions, vec![1, 3]);
12549        assert_eq!(right_positions, vec![0, 1]);
12550    }
12551
12552    #[test]
12553    fn ordered_unique_utf8_fixed_width_gap_falls_back_jbyuc11() {
12554        let left = contiguous_utf8_column(&["k000", "k001", "k003", "k004"]);
12555        let right = contiguous_utf8_column(&["k001", "k002", "k004"]);
12556
12557        let (left_positions, right_positions) =
12558            ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
12559        assert_eq!(left_positions, vec![1, 3]);
12560        assert_eq!(right_positions, vec![0, 2]);
12561    }
12562
12563    #[test]
12564    fn ordered_unique_utf8_rejects_unsorted_or_duplicate_keys_53lat() {
12565        let unsorted_left = contiguous_utf8_column(&["b", "a", "b"]);
12566        let duplicate_right = contiguous_utf8_column(&["b", "b", "a"]);
12567        assert!(ordered_unique_utf8_inner_positions(&unsorted_left, &duplicate_right).is_none());
12568
12569        let left = utf8_key_merge_frame(&["b", "a", "b"], "lv", 10);
12570        let right = utf8_key_merge_frame(&["b", "b", "a"], "rv", 20);
12571        let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
12572
12573        assert_eq!(
12574            merged.columns.get("lv").unwrap().values(),
12575            &[
12576                Scalar::Int64(10),
12577                Scalar::Int64(10),
12578                Scalar::Int64(11),
12579                Scalar::Int64(12),
12580                Scalar::Int64(12)
12581            ]
12582        );
12583        assert_eq!(
12584            merged.columns.get("rv").unwrap().values(),
12585            &[
12586                Scalar::Int64(20),
12587                Scalar::Int64(21),
12588                Scalar::Int64(22),
12589                Scalar::Int64(20),
12590                Scalar::Int64(21)
12591            ]
12592        );
12593    }
12594
12595    #[test]
12596    fn merge_inner_int64_fast_paths_match_naive_reference_fuzz_jdupk() {
12597        // Differential guard: merge_dataframes dispatches int64 single-key inner
12598        // merges to ordered/identity/dense fast paths. Each MUST equal a naive
12599        // left-major nested-loop join for arbitrary int64 keys (sorted/unsorted,
12600        // unique/duplicate, overlapping/disjoint, negative). This is the
12601        // isomorphism proof those perf paths owe; it caught the identity-path
12602        // row-loss bug. (br-frankenpandas-rw0r5)
12603        let mut state: u64 = 0x9E37_79B9_7F4A_7C15;
12604        let mut next = || {
12605            state = state
12606                .wrapping_mul(6_364_136_223_846_793_005)
12607                .wrapping_add(1_442_695_040_888_963_407);
12608            state >> 33
12609        };
12610        for _ in 0..400 {
12611            let nl = (next() % 6 + 1) as usize;
12612            let nr = (next() % 6 + 1) as usize;
12613            // small key range forces collisions; offset gives negatives too
12614            let lk: Vec<i64> = (0..nl).map(|_| (next() % 5) as i64 - 2).collect();
12615            let rk: Vec<i64> = (0..nr).map(|_| (next() % 5) as i64 - 2).collect();
12616
12617            let left = DataFrame::from_dict(
12618                &["id", "a"],
12619                vec![
12620                    ("id", lk.iter().map(|&k| Scalar::Int64(k)).collect()),
12621                    (
12622                        "a",
12623                        (0..nl).map(|i| Scalar::Int64(i as i64 + 1000)).collect(),
12624                    ),
12625                ],
12626            )
12627            .unwrap();
12628            let right = DataFrame::from_dict(
12629                &["id", "b"],
12630                vec![
12631                    ("id", rk.iter().map(|&k| Scalar::Int64(k)).collect()),
12632                    (
12633                        "b",
12634                        (0..nr).map(|j| Scalar::Int64(j as i64 + 2000)).collect(),
12635                    ),
12636                ],
12637            )
12638            .unwrap();
12639
12640            let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
12641
12642            // Naive reference: pandas inner merge is left-major, right-minor.
12643            let mut exp_a = Vec::new();
12644            let mut exp_b = Vec::new();
12645            for (i, &left_value) in lk.iter().enumerate() {
12646                for (j, &right_value) in rk.iter().enumerate() {
12647                    if left_value == right_value {
12648                        exp_a.push(Scalar::Int64(i as i64 + 1000));
12649                        exp_b.push(Scalar::Int64(j as i64 + 2000));
12650                    }
12651                }
12652            }
12653            assert_eq!(
12654                merged.columns.get("a").unwrap().values(),
12655                exp_a.as_slice(),
12656                "left payload mismatch for lk={lk:?} rk={rk:?}"
12657            );
12658            assert_eq!(
12659                merged.columns.get("b").unwrap().values(),
12660                exp_b.as_slice(),
12661                "right payload mismatch for lk={lk:?} rk={rk:?}"
12662            );
12663
12664            // Cardinality guard for left/right/outer (dtype/order independent —
12665            // catches the row-loss class regardless of int->float promotion).
12666            let inner_pairs = exp_a.len();
12667            let left_only = lk.iter().filter(|&key| !rk.contains(key)).count();
12668            let right_only = rk.iter().filter(|&key| !lk.contains(key)).count();
12669            for (how, expected_rows) in [
12670                (JoinType::Left, inner_pairs + left_only),
12671                (JoinType::Right, inner_pairs + right_only),
12672                (JoinType::Outer, inner_pairs + left_only + right_only),
12673            ] {
12674                let m = merge_dataframes(&left, &right, "id", how).unwrap();
12675                assert_eq!(
12676                    m.columns.get("id").unwrap().len(),
12677                    expected_rows,
12678                    "{how:?} cardinality mismatch for lk={lk:?} rk={rk:?}"
12679                );
12680            }
12681        }
12682    }
12683
12684    #[test]
12685    fn merge_null_nan_keys_metamorphic_unmatched_rows_do_not_disturb_inner_tn6qb8()
12686    -> Result<(), JoinError> {
12687        let left = DataFrame::from_dict(
12688            &["id", "left_v"],
12689            vec![
12690                (
12691                    "id",
12692                    vec![
12693                        Scalar::Float64(1.0),
12694                        Scalar::Null(NullKind::NaN),
12695                        Scalar::Null(NullKind::Null),
12696                        Scalar::Float64(2.0),
12697                    ],
12698                ),
12699                (
12700                    "left_v",
12701                    vec![
12702                        Scalar::Int64(10),
12703                        Scalar::Int64(20),
12704                        Scalar::Int64(21),
12705                        Scalar::Int64(30),
12706                    ],
12707                ),
12708            ],
12709        )?;
12710        let right = DataFrame::from_dict(
12711            &["id", "right_v"],
12712            vec![
12713                (
12714                    "id",
12715                    vec![
12716                        Scalar::Null(NullKind::Null),
12717                        Scalar::Float64(2.0),
12718                        Scalar::Float64(f64::NAN),
12719                    ],
12720                ),
12721                (
12722                    "right_v",
12723                    vec![Scalar::Int64(200), Scalar::Int64(300), Scalar::Int64(201)],
12724                ),
12725            ],
12726        )?;
12727
12728        let baseline = merge_dataframes(&left, &right, "id", JoinType::Inner)?;
12729
12730        let left_with_unmatched = DataFrame::from_dict(
12731            &["id", "left_v"],
12732            vec![
12733                (
12734                    "id",
12735                    vec![
12736                        Scalar::Float64(1.0),
12737                        Scalar::Null(NullKind::NaN),
12738                        Scalar::Null(NullKind::Null),
12739                        Scalar::Float64(2.0),
12740                        Scalar::Float64(99.0),
12741                    ],
12742                ),
12743                (
12744                    "left_v",
12745                    vec![
12746                        Scalar::Int64(10),
12747                        Scalar::Int64(20),
12748                        Scalar::Int64(21),
12749                        Scalar::Int64(30),
12750                        Scalar::Int64(990),
12751                    ],
12752                ),
12753            ],
12754        )?;
12755        let right_with_unmatched = DataFrame::from_dict(
12756            &["id", "right_v"],
12757            vec![
12758                (
12759                    "id",
12760                    vec![
12761                        Scalar::Null(NullKind::Null),
12762                        Scalar::Float64(2.0),
12763                        Scalar::Float64(f64::NAN),
12764                        Scalar::Float64(100.0),
12765                    ],
12766                ),
12767                (
12768                    "right_v",
12769                    vec![
12770                        Scalar::Int64(200),
12771                        Scalar::Int64(300),
12772                        Scalar::Int64(201),
12773                        Scalar::Int64(1000),
12774                    ],
12775                ),
12776            ],
12777        )?;
12778
12779        let transformed = merge_dataframes(
12780            &left_with_unmatched,
12781            &right_with_unmatched,
12782            "id",
12783            JoinType::Inner,
12784        )?;
12785
12786        assert_eq!(
12787            merged_values(&baseline, "left_v")?,
12788            merged_values(&transformed, "left_v")?
12789        );
12790        assert_eq!(
12791            merged_values(&baseline, "right_v")?,
12792            merged_values(&transformed, "right_v")?
12793        );
12794        assert_eq!(
12795            merged_values(&baseline, "left_v")?,
12796            &[
12797                Scalar::Int64(20),
12798                Scalar::Int64(20),
12799                Scalar::Int64(21),
12800                Scalar::Int64(21),
12801                Scalar::Int64(30),
12802            ]
12803        );
12804        assert_eq!(
12805            merged_values(&baseline, "right_v")?,
12806            &[
12807                Scalar::Int64(200),
12808                Scalar::Int64(201),
12809                Scalar::Int64(200),
12810                Scalar::Int64(201),
12811                Scalar::Int64(300),
12812            ]
12813        );
12814
12815        Ok(())
12816    }
12817
12818    #[test]
12819    fn merge_mixed_dtype_missing_keys_metamorphic_outer_both_equals_inner_tn6qb8()
12820    -> Result<(), JoinError> {
12821        let left = DataFrame::from_dict(
12822            &["id", "left_v"],
12823            vec![
12824                (
12825                    "id",
12826                    vec![
12827                        Scalar::Int64(1),
12828                        Scalar::Int64(2),
12829                        Scalar::Null(NullKind::NaN),
12830                        Scalar::Int64(3),
12831                    ],
12832                ),
12833                (
12834                    "left_v",
12835                    vec![
12836                        Scalar::Float64(10.0),
12837                        Scalar::Float64(20.0),
12838                        Scalar::Float64(30.0),
12839                        Scalar::Float64(40.0),
12840                    ],
12841                ),
12842            ],
12843        )?;
12844        let right = DataFrame::from_dict(
12845            &["id", "right_v"],
12846            vec![
12847                (
12848                    "id",
12849                    vec![
12850                        Scalar::Float64(1.0),
12851                        Scalar::Float64(2.5),
12852                        Scalar::Null(NullKind::Null),
12853                        Scalar::Float64(3.0),
12854                    ],
12855                ),
12856                (
12857                    "right_v",
12858                    vec![
12859                        Scalar::Float64(100.0),
12860                        Scalar::Float64(250.0),
12861                        Scalar::Float64(300.0),
12862                        Scalar::Float64(400.0),
12863                    ],
12864                ),
12865            ],
12866        )?;
12867        let options = MergeExecutionOptions {
12868            indicator_name: Some("_merge".to_owned()),
12869            sort: true,
12870            ..MergeExecutionOptions::default()
12871        };
12872
12873        let inner = merge_dataframes_on_with_options(
12874            &left,
12875            &right,
12876            &["id"],
12877            &["id"],
12878            JoinType::Inner,
12879            options.clone(),
12880        )?;
12881        let outer = merge_dataframes_on_with_options(
12882            &left,
12883            &right,
12884            &["id"],
12885            &["id"],
12886            JoinType::Outer,
12887            options,
12888        )?;
12889
12890        assert_eq!(
12891            merged_values(&inner, "left_v")?,
12892            merged_values_where_indicator(&outer, "left_v", "_merge", "both")?
12893        );
12894        assert_eq!(
12895            merged_values(&inner, "right_v")?,
12896            merged_values_where_indicator(&outer, "right_v", "_merge", "both")?
12897        );
12898        assert_eq!(
12899            merged_values(&inner, "left_v")?,
12900            &[
12901                Scalar::Float64(10.0),
12902                Scalar::Float64(40.0),
12903                Scalar::Float64(30.0)
12904            ]
12905        );
12906        assert_eq!(
12907            merged_values(&inner, "right_v")?,
12908            &[
12909                Scalar::Float64(100.0),
12910                Scalar::Float64(400.0),
12911                Scalar::Float64(300.0)
12912            ]
12913        );
12914        assert_eq!(
12915            merged_values(&outer, "_merge")?,
12916            &[
12917                Scalar::Utf8("both".to_owned()),
12918                Scalar::Utf8("left_only".to_owned()),
12919                Scalar::Utf8("right_only".to_owned()),
12920                Scalar::Utf8("both".to_owned()),
12921                Scalar::Utf8("both".to_owned()),
12922            ]
12923        );
12924
12925        Ok(())
12926    }
12927
12928    #[test]
12929    fn merge_cross_cartesian_product() {
12930        let left = make_left_df();
12931        let right = make_right_df();
12932
12933        let merged = merge_dataframes(&left, &right, "unused_key", JoinType::Cross).unwrap();
12934
12935        assert_eq!(merged.columns.get("id_x").unwrap().len(), 9);
12936        assert_eq!(
12937            &merged.columns.get("id_x").unwrap().values()[0..3],
12938            &[Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(1)]
12939        );
12940        assert_eq!(
12941            &merged.columns.get("id_y").unwrap().values()[0..3],
12942            &[Scalar::Int64(2), Scalar::Int64(3), Scalar::Int64(4)]
12943        );
12944        assert_eq!(
12945            &merged.columns.get("val_a").unwrap().values()[0..3],
12946            &[Scalar::Int64(10), Scalar::Int64(10), Scalar::Int64(10)]
12947        );
12948        assert_eq!(
12949            &merged.columns.get("val_b").unwrap().values()[0..3],
12950            &[Scalar::Int64(200), Scalar::Int64(300), Scalar::Int64(400)]
12951        );
12952    }
12953
12954    #[test]
12955    fn merge_cross_does_not_require_on_column() {
12956        let left = make_left_df();
12957        let right = make_right_df();
12958
12959        let merged =
12960            merge_dataframes(&left, &right, "definitely_missing", JoinType::Cross).unwrap();
12961        assert_eq!(merged.columns.get("id_x").unwrap().len(), 9);
12962    }
12963
12964    #[test]
12965    fn merge_cross_with_empty_side_yields_empty_rows() {
12966        let left = DataFrame::from_dict(
12967            &["l"],
12968            vec![("l", vec![Scalar::Int64(1), Scalar::Int64(2)])],
12969        )
12970        .unwrap();
12971        let right = DataFrame::from_dict(&["r"], vec![("r", vec![])]).unwrap();
12972
12973        let merged = merge_dataframes(&left, &right, "ignored", JoinType::Cross).unwrap();
12974        assert_eq!(merged.index.labels().len(), 0);
12975        assert!(merged.columns.get("l").unwrap().values().is_empty());
12976        assert!(merged.columns.get("r").unwrap().values().is_empty());
12977    }
12978
12979    #[test]
12980    fn merge_composite_inner_multiplies_cardinality_for_duplicates() {
12981        let left = DataFrame::from_dict(
12982            &["k1", "k2", "left_v"],
12983            vec![
12984                (
12985                    "k1",
12986                    vec![Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(1)],
12987                ),
12988                (
12989                    "k2",
12990                    vec![
12991                        Scalar::Utf8("a".to_owned()),
12992                        Scalar::Utf8("a".to_owned()),
12993                        Scalar::Utf8("b".to_owned()),
12994                    ],
12995                ),
12996                (
12997                    "left_v",
12998                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
12999                ),
13000            ],
13001        )
13002        .unwrap();
13003        let right = DataFrame::from_dict(
13004            &["k1", "k2", "right_v"],
13005            vec![
13006                (
13007                    "k1",
13008                    vec![Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(1)],
13009                ),
13010                (
13011                    "k2",
13012                    vec![
13013                        Scalar::Utf8("a".to_owned()),
13014                        Scalar::Utf8("a".to_owned()),
13015                        Scalar::Utf8("c".to_owned()),
13016                    ],
13017                ),
13018                (
13019                    "right_v",
13020                    vec![Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(300)],
13021                ),
13022            ],
13023        )
13024        .unwrap();
13025
13026        let merged = merge_dataframes_on(&left, &right, &["k1", "k2"], JoinType::Inner).unwrap();
13027        assert_eq!(merged.columns.get("k1").unwrap().len(), 4);
13028        assert_eq!(
13029            merged.columns.get("k1").unwrap().values(),
13030            &[
13031                Scalar::Int64(1),
13032                Scalar::Int64(1),
13033                Scalar::Int64(1),
13034                Scalar::Int64(1)
13035            ]
13036        );
13037        assert_eq!(
13038            merged.columns.get("k2").unwrap().values(),
13039            &[
13040                Scalar::Utf8("a".to_owned()),
13041                Scalar::Utf8("a".to_owned()),
13042                Scalar::Utf8("a".to_owned()),
13043                Scalar::Utf8("a".to_owned())
13044            ]
13045        );
13046        assert_eq!(
13047            merged.columns.get("left_v").unwrap().values(),
13048            &[
13049                Scalar::Int64(10),
13050                Scalar::Int64(10),
13051                Scalar::Int64(20),
13052                Scalar::Int64(20)
13053            ]
13054        );
13055        assert_eq!(
13056            merged.columns.get("right_v").unwrap().values(),
13057            &[
13058                Scalar::Int64(100),
13059                Scalar::Int64(200),
13060                Scalar::Int64(100),
13061                Scalar::Int64(200)
13062            ]
13063        );
13064    }
13065
13066    #[test]
13067    fn merge_composite_outer_sorts_join_keys_lexicographically() {
13068        let left = DataFrame::from_dict(
13069            &["k1", "k2", "left_v"],
13070            vec![
13071                ("k1", vec![Scalar::Int64(2), Scalar::Int64(1)]),
13072                (
13073                    "k2",
13074                    vec![Scalar::Utf8("y".to_owned()), Scalar::Utf8("x".to_owned())],
13075                ),
13076                ("left_v", vec![Scalar::Int64(20), Scalar::Int64(10)]),
13077            ],
13078        )
13079        .unwrap();
13080        let right = DataFrame::from_dict(
13081            &["k1", "k2", "right_v"],
13082            vec![
13083                ("k1", vec![Scalar::Int64(2), Scalar::Int64(3)]),
13084                (
13085                    "k2",
13086                    vec![Scalar::Utf8("y".to_owned()), Scalar::Utf8("z".to_owned())],
13087                ),
13088                ("right_v", vec![Scalar::Int64(200), Scalar::Int64(300)]),
13089            ],
13090        )
13091        .unwrap();
13092
13093        let merged = merge_dataframes_on(&left, &right, &["k1", "k2"], JoinType::Outer).unwrap();
13094        assert_eq!(
13095            merged.columns.get("k1").unwrap().values(),
13096            &[Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)]
13097        );
13098        assert_eq!(
13099            merged.columns.get("k2").unwrap().values(),
13100            &[
13101                Scalar::Utf8("x".to_owned()),
13102                Scalar::Utf8("y".to_owned()),
13103                Scalar::Utf8("z".to_owned())
13104            ]
13105        );
13106        assert_eq!(
13107            merged.columns.get("left_v").unwrap().values(),
13108            &[
13109                Scalar::Float64(10.0),
13110                Scalar::Float64(20.0),
13111                Scalar::Null(NullKind::NaN)
13112            ]
13113        );
13114        assert_eq!(
13115            merged.columns.get("right_v").unwrap().values(),
13116            &[
13117                Scalar::Null(NullKind::NaN),
13118                Scalar::Float64(200.0),
13119                Scalar::Float64(300.0)
13120            ]
13121        );
13122    }
13123
13124    #[test]
13125    fn merge_composite_inner_matches_missing_key_components() {
13126        let left = DataFrame::from_dict(
13127            &["k1", "k2", "left_v"],
13128            vec![
13129                ("k1", vec![Scalar::Int64(1), Scalar::Int64(1)]),
13130                (
13131                    "k2",
13132                    vec![Scalar::Null(NullKind::Null), Scalar::Utf8("a".to_owned())],
13133                ),
13134                ("left_v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
13135            ],
13136        )
13137        .unwrap();
13138        let right = DataFrame::from_dict(
13139            &["k1", "k2", "right_v"],
13140            vec![
13141                (
13142                    "k1",
13143                    vec![Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(2)],
13144                ),
13145                (
13146                    "k2",
13147                    vec![
13148                        Scalar::Null(NullKind::Null),
13149                        Scalar::Utf8("a".to_owned()),
13150                        Scalar::Null(NullKind::Null),
13151                    ],
13152                ),
13153                (
13154                    "right_v",
13155                    vec![Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(300)],
13156                ),
13157            ],
13158        )
13159        .unwrap();
13160
13161        let merged = merge_dataframes_on(&left, &right, &["k1", "k2"], JoinType::Inner).unwrap();
13162        assert_eq!(
13163            merged.columns.get("k1").unwrap().values(),
13164            &[Scalar::Int64(1), Scalar::Int64(1)]
13165        );
13166        assert_eq!(
13167            merged.columns.get("k2").unwrap().values(),
13168            &[Scalar::Null(NullKind::Null), Scalar::Utf8("a".to_owned())]
13169        );
13170        assert_eq!(
13171            merged.columns.get("left_v").unwrap().values(),
13172            &[Scalar::Int64(10), Scalar::Int64(20)]
13173        );
13174        assert_eq!(
13175            merged.columns.get("right_v").unwrap().values(),
13176            &[Scalar::Int64(100), Scalar::Int64(200)]
13177        );
13178    }
13179
13180    #[test]
13181    fn merge_composite_outer_keeps_right_only_rows_with_missing_keys() {
13182        let left = DataFrame::from_dict(
13183            &["k1", "k2", "left_v"],
13184            vec![
13185                ("k1", vec![Scalar::Int64(1)]),
13186                ("k2", vec![Scalar::Null(NullKind::Null)]),
13187                ("left_v", vec![Scalar::Int64(10)]),
13188            ],
13189        )
13190        .unwrap();
13191        let right = DataFrame::from_dict(
13192            &["k1", "k2", "right_v"],
13193            vec![
13194                ("k1", vec![Scalar::Int64(1), Scalar::Int64(2)]),
13195                (
13196                    "k2",
13197                    vec![Scalar::Null(NullKind::Null), Scalar::Null(NullKind::Null)],
13198                ),
13199                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
13200            ],
13201        )
13202        .unwrap();
13203
13204        let merged = merge_dataframes_on(&left, &right, &["k1", "k2"], JoinType::Outer).unwrap();
13205        assert_eq!(
13206            merged.columns.get("k1").unwrap().values(),
13207            &[Scalar::Int64(1), Scalar::Int64(2)]
13208        );
13209        assert_eq!(
13210            merged.columns.get("k2").unwrap().values(),
13211            &[Scalar::Null(NullKind::Null), Scalar::Null(NullKind::Null)]
13212        );
13213        assert_eq!(
13214            merged.columns.get("left_v").unwrap().values(),
13215            &[Scalar::Float64(10.0), Scalar::Null(NullKind::NaN)]
13216        );
13217        assert_eq!(
13218            merged.columns.get("right_v").unwrap().values(),
13219            &[Scalar::Int64(100), Scalar::Int64(200)]
13220        );
13221    }
13222
13223    #[test]
13224    fn merge_composite_missing_key_column_errors() {
13225        let left = DataFrame::from_dict(
13226            &["k1", "k2", "left_v"],
13227            vec![
13228                ("k1", vec![Scalar::Int64(1)]),
13229                ("k2", vec![Scalar::Utf8("x".to_owned())]),
13230                ("left_v", vec![Scalar::Int64(10)]),
13231            ],
13232        )
13233        .unwrap();
13234        let right = DataFrame::from_dict(
13235            &["k1", "right_v"],
13236            vec![
13237                ("k1", vec![Scalar::Int64(1)]),
13238                ("right_v", vec![Scalar::Int64(100)]),
13239            ],
13240        )
13241        .unwrap();
13242
13243        let err = merge_dataframes_on(&left, &right, &["k1", "k2"], JoinType::Inner)
13244            .expect_err("should fail");
13245        assert!(format!("{err}").contains("right DataFrame missing key column 'k2'"));
13246    }
13247
13248    #[test]
13249    fn merge_composite_key_alias_inner_keeps_both_key_sets() {
13250        let left = DataFrame::from_dict(
13251            &["lk1", "lk2", "left_v"],
13252            vec![
13253                (
13254                    "lk1",
13255                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
13256                ),
13257                (
13258                    "lk2",
13259                    vec![
13260                        Scalar::Utf8("a".to_owned()),
13261                        Scalar::Utf8("b".to_owned()),
13262                        Scalar::Utf8("c".to_owned()),
13263                    ],
13264                ),
13265                (
13266                    "left_v",
13267                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
13268                ),
13269            ],
13270        )
13271        .unwrap();
13272        let right = DataFrame::from_dict(
13273            &["rk1", "rk2", "right_v"],
13274            vec![
13275                (
13276                    "rk1",
13277                    vec![Scalar::Int64(2), Scalar::Int64(3), Scalar::Int64(4)],
13278                ),
13279                (
13280                    "rk2",
13281                    vec![
13282                        Scalar::Utf8("b".to_owned()),
13283                        Scalar::Utf8("c".to_owned()),
13284                        Scalar::Utf8("d".to_owned()),
13285                    ],
13286                ),
13287                (
13288                    "right_v",
13289                    vec![Scalar::Int64(200), Scalar::Int64(300), Scalar::Int64(400)],
13290                ),
13291            ],
13292        )
13293        .unwrap();
13294
13295        let merged = merge_dataframes_on_with(
13296            &left,
13297            &right,
13298            &["lk1", "lk2"],
13299            &["rk1", "rk2"],
13300            JoinType::Inner,
13301        )
13302        .unwrap();
13303        assert_eq!(
13304            merged.columns.get("lk1").unwrap().values(),
13305            &[Scalar::Int64(2), Scalar::Int64(3)]
13306        );
13307        assert_eq!(
13308            merged.columns.get("lk2").unwrap().values(),
13309            &[Scalar::Utf8("b".to_owned()), Scalar::Utf8("c".to_owned())]
13310        );
13311        assert_eq!(
13312            merged.columns.get("left_v").unwrap().values(),
13313            &[Scalar::Int64(20), Scalar::Int64(30)]
13314        );
13315        assert_eq!(
13316            merged.columns.get("rk1").unwrap().values(),
13317            &[Scalar::Int64(2), Scalar::Int64(3)]
13318        );
13319        assert_eq!(
13320            merged.columns.get("rk2").unwrap().values(),
13321            &[Scalar::Utf8("b".to_owned()), Scalar::Utf8("c".to_owned())]
13322        );
13323        assert_eq!(
13324            merged.columns.get("right_v").unwrap().values(),
13325            &[Scalar::Int64(200), Scalar::Int64(300)]
13326        );
13327    }
13328
13329    #[test]
13330    fn merge_composite_key_alias_outer_propagates_missing_per_side() {
13331        let left = DataFrame::from_dict(
13332            &["lk1", "lk2", "left_v"],
13333            vec![
13334                (
13335                    "lk1",
13336                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
13337                ),
13338                (
13339                    "lk2",
13340                    vec![
13341                        Scalar::Utf8("a".to_owned()),
13342                        Scalar::Null(NullKind::Null),
13343                        Scalar::Utf8("c".to_owned()),
13344                    ],
13345                ),
13346                (
13347                    "left_v",
13348                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
13349                ),
13350            ],
13351        )
13352        .unwrap();
13353        let right = DataFrame::from_dict(
13354            &["rk1", "rk2", "right_v"],
13355            vec![
13356                (
13357                    "rk1",
13358                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(4)],
13359                ),
13360                (
13361                    "rk2",
13362                    vec![
13363                        Scalar::Utf8("a".to_owned()),
13364                        Scalar::Null(NullKind::Null),
13365                        Scalar::Utf8("d".to_owned()),
13366                    ],
13367                ),
13368                (
13369                    "right_v",
13370                    vec![Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(400)],
13371                ),
13372            ],
13373        )
13374        .unwrap();
13375
13376        let merged = merge_dataframes_on_with(
13377            &left,
13378            &right,
13379            &["lk1", "lk2"],
13380            &["rk1", "rk2"],
13381            JoinType::Outer,
13382        )
13383        .unwrap();
13384
13385        assert_eq!(
13386            merged.columns.get("lk1").unwrap().values(),
13387            &[
13388                Scalar::Float64(1.0),
13389                Scalar::Float64(2.0),
13390                Scalar::Float64(3.0),
13391                Scalar::Null(NullKind::NaN)
13392            ]
13393        );
13394        assert_eq!(
13395            merged.columns.get("rk1").unwrap().values(),
13396            &[
13397                Scalar::Float64(1.0),
13398                Scalar::Float64(2.0),
13399                Scalar::Null(NullKind::NaN),
13400                Scalar::Float64(4.0)
13401            ]
13402        );
13403        assert_eq!(
13404            merged.columns.get("left_v").unwrap().values(),
13405            &[
13406                Scalar::Float64(10.0),
13407                Scalar::Float64(20.0),
13408                Scalar::Float64(30.0),
13409                Scalar::Null(NullKind::NaN)
13410            ]
13411        );
13412        assert_eq!(
13413            merged.columns.get("right_v").unwrap().values(),
13414            &[
13415                Scalar::Float64(100.0),
13416                Scalar::Float64(200.0),
13417                Scalar::Null(NullKind::NaN),
13418                Scalar::Float64(400.0)
13419            ]
13420        );
13421    }
13422
13423    #[test]
13424    fn merge_key_alias_lists_must_have_equal_lengths() {
13425        let left = make_left_df();
13426        let right = make_right_df();
13427        let err = merge_dataframes_on_with(&left, &right, &["id", "id"], &["id"], JoinType::Inner)
13428            .expect_err("should fail");
13429        assert!(format!("{err}").contains("equal length"));
13430    }
13431
13432    #[test]
13433    fn merge_indicator_default_name_tracks_row_provenance() {
13434        let left = make_left_df();
13435        let right = make_right_df();
13436
13437        let merged = merge_dataframes_on_with_options(
13438            &left,
13439            &right,
13440            &["id"],
13441            &["id"],
13442            JoinType::Outer,
13443            MergeExecutionOptions {
13444                indicator_name: Some("_merge".to_owned()),
13445                ..MergeExecutionOptions::default()
13446            },
13447        )
13448        .expect("merge");
13449
13450        assert_eq!(
13451            merged.columns.get("_merge").expect("indicator").values(),
13452            &[
13453                Scalar::Utf8("left_only".to_owned()),
13454                Scalar::Utf8("both".to_owned()),
13455                Scalar::Utf8("both".to_owned()),
13456                Scalar::Utf8("right_only".to_owned())
13457            ]
13458        );
13459    }
13460
13461    #[test]
13462    fn merge_indicator_custom_name_preserves_suffix_behavior() {
13463        let left = DataFrame::from_dict(
13464            &["id", "val"],
13465            vec![
13466                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
13467                ("val", vec![Scalar::Int64(10), Scalar::Int64(20)]),
13468            ],
13469        )
13470        .unwrap();
13471        let right = DataFrame::from_dict(
13472            &["id", "val"],
13473            vec![
13474                ("id", vec![Scalar::Int64(2), Scalar::Int64(3)]),
13475                ("val", vec![Scalar::Int64(200), Scalar::Int64(300)]),
13476            ],
13477        )
13478        .unwrap();
13479
13480        let merged = merge_dataframes_on_with_options(
13481            &left,
13482            &right,
13483            &["id"],
13484            &["id"],
13485            JoinType::Outer,
13486            MergeExecutionOptions {
13487                indicator_name: Some("origin".to_owned()),
13488                ..MergeExecutionOptions::default()
13489            },
13490        )
13491        .expect("merge");
13492
13493        assert!(merged.columns.contains_key("val_x"));
13494        assert!(merged.columns.contains_key("val_y"));
13495        assert_eq!(
13496            merged.columns.get("origin").expect("indicator").values(),
13497            &[
13498                Scalar::Utf8("left_only".to_owned()),
13499                Scalar::Utf8("both".to_owned()),
13500                Scalar::Utf8("right_only".to_owned())
13501            ]
13502        );
13503    }
13504
13505    #[test]
13506    fn merge_indicator_rejects_conflicting_column_name() {
13507        let left = make_left_df();
13508        let right = make_right_df();
13509
13510        let err = merge_dataframes_on_with_options(
13511            &left,
13512            &right,
13513            &["id"],
13514            &["id"],
13515            JoinType::Inner,
13516            MergeExecutionOptions {
13517                indicator_name: Some("id".to_owned()),
13518                ..MergeExecutionOptions::default()
13519            },
13520        )
13521        .expect_err("expected indicator name conflict");
13522        assert!(format!("{err}").contains("conflicts with an existing column"));
13523    }
13524
13525    #[test]
13526    fn merge_cross_indicator_marks_all_rows_both() {
13527        // Restored after br-frankenpandas-glsam revert: pandas 2.2.3
13528        // supports `how='cross', indicator=...` and emits "both" for every
13529        // cross-product row (verified against FP-P2D-039 fixture provenance
13530        // pandas_version=2.2.3). The Explore-agent claim that pandas raises
13531        // was incorrect; this test locks in the actual pandas behavior.
13532        let left = DataFrame::from_dict(
13533            &["l"],
13534            vec![("l", vec![Scalar::Int64(1), Scalar::Int64(2)])],
13535        )
13536        .unwrap();
13537        let right = DataFrame::from_dict(&["r"], vec![("r", vec![Scalar::Int64(9)])]).unwrap();
13538
13539        let merged = merge_dataframes_on_with_options(
13540            &left,
13541            &right,
13542            &["ignored"],
13543            &["ignored"],
13544            JoinType::Cross,
13545            MergeExecutionOptions {
13546                indicator_name: Some("_merge".to_owned()),
13547                ..MergeExecutionOptions::default()
13548            },
13549        )
13550        .expect("cross merge");
13551        assert_eq!(
13552            merged.columns.get("_merge").expect("indicator").values(),
13553            &[
13554                Scalar::Utf8("both".to_owned()),
13555                Scalar::Utf8("both".to_owned())
13556            ]
13557        );
13558    }
13559
13560    #[test]
13561    fn merge_cross_validate_mode_contract_ohb5f() {
13562        let left = DataFrame::from_dict(
13563            &["l"],
13564            vec![("l", vec![Scalar::Int64(1), Scalar::Int64(2)])],
13565        )
13566        .expect("left");
13567        let right = DataFrame::from_dict(
13568            &["r"],
13569            vec![("r", vec![Scalar::Int64(10), Scalar::Int64(20)])],
13570        )
13571        .expect("right");
13572
13573        let many_to_many = merge_dataframes_on_with_options(
13574            &left,
13575            &right,
13576            &["missing_left_key"],
13577            &["missing_right_key"],
13578            JoinType::Cross,
13579            MergeExecutionOptions {
13580                validate_mode: Some(MergeValidateMode::ManyToMany),
13581                ..MergeExecutionOptions::default()
13582            },
13583        )
13584        .expect("cross merge validate=many_to_many");
13585        assert_eq!(many_to_many.index.len(), 4);
13586
13587        for validate_mode in [
13588            MergeValidateMode::OneToOne,
13589            MergeValidateMode::OneToMany,
13590            MergeValidateMode::ManyToOne,
13591        ] {
13592            let err = merge_dataframes_on_with_options(
13593                &left,
13594                &right,
13595                &["missing_left_key"],
13596                &["missing_right_key"],
13597                JoinType::Cross,
13598                MergeExecutionOptions {
13599                    validate_mode: Some(validate_mode),
13600                    ..MergeExecutionOptions::default()
13601                },
13602            )
13603            .expect_err("enforcing validate modes are not meaningful for cross joins");
13604            let message = format!("{err}");
13605            assert!(message.contains(validate_mode.as_str()));
13606            assert!(message.contains("not supported for cross join"));
13607        }
13608    }
13609
13610    #[test]
13611    fn merge_validate_one_to_one_rejects_duplicate_left_keys() {
13612        let left = DataFrame::from_dict(
13613            &["id", "left_v"],
13614            vec![
13615                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
13616                ("left_v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
13617            ],
13618        )
13619        .expect("left frame");
13620        let right = DataFrame::from_dict(
13621            &["id", "right_v"],
13622            vec![
13623                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
13624                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
13625            ],
13626        )
13627        .expect("right frame");
13628
13629        let err = merge_dataframes_on_with_options(
13630            &left,
13631            &right,
13632            &["id"],
13633            &["id"],
13634            JoinType::Inner,
13635            MergeExecutionOptions {
13636                validate_mode: Some(MergeValidateMode::OneToOne),
13637                ..MergeExecutionOptions::default()
13638            },
13639        )
13640        .expect_err("one_to_one must reject duplicate left keys");
13641        assert!(format!("{err}").contains("left keys are not unique"));
13642    }
13643
13644    #[test]
13645    fn merge_validate_one_to_many_allows_duplicate_right_keys() {
13646        let left = DataFrame::from_dict(
13647            &["id", "left_v"],
13648            vec![
13649                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
13650                ("left_v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
13651            ],
13652        )
13653        .expect("left frame");
13654        let right = DataFrame::from_dict(
13655            &["id", "right_v"],
13656            vec![
13657                (
13658                    "id",
13659                    vec![Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(2)],
13660                ),
13661                (
13662                    "right_v",
13663                    vec![Scalar::Int64(100), Scalar::Int64(101), Scalar::Int64(200)],
13664                ),
13665            ],
13666        )
13667        .expect("right frame");
13668
13669        let merged = merge_dataframes_on_with_options(
13670            &left,
13671            &right,
13672            &["id"],
13673            &["id"],
13674            JoinType::Inner,
13675            MergeExecutionOptions {
13676                validate_mode: Some(MergeValidateMode::OneToMany),
13677                ..MergeExecutionOptions::default()
13678            },
13679        )
13680        .expect("one_to_many should allow duplicate right keys");
13681        assert_eq!(merged.columns.get("id").expect("id").values().len(), 3);
13682    }
13683
13684    #[test]
13685    fn merge_validate_one_to_many_rejects_duplicate_left_keys_9hsb3() {
13686        let left = DataFrame::from_dict(
13687            &["id", "left_v"],
13688            vec![
13689                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
13690                ("left_v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
13691            ],
13692        )
13693        .expect("left frame");
13694        let right = DataFrame::from_dict(
13695            &["id", "right_v"],
13696            vec![
13697                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
13698                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
13699            ],
13700        )
13701        .expect("right frame");
13702
13703        let err = merge_dataframes_on_with_options(
13704            &left,
13705            &right,
13706            &["id"],
13707            &["id"],
13708            JoinType::Inner,
13709            MergeExecutionOptions {
13710                validate_mode: Some(MergeValidateMode::OneToMany),
13711                ..MergeExecutionOptions::default()
13712            },
13713        )
13714        .expect_err("one_to_many must reject duplicate left keys");
13715        assert!(format!("{err}").contains("left keys are not unique"));
13716    }
13717
13718    #[test]
13719    fn merge_validate_many_to_one_rejects_duplicate_right_keys() {
13720        let left = DataFrame::from_dict(
13721            &["id", "left_v"],
13722            vec![
13723                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
13724                ("left_v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
13725            ],
13726        )
13727        .expect("left frame");
13728        let right = DataFrame::from_dict(
13729            &["id", "right_v"],
13730            vec![
13731                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
13732                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(101)]),
13733            ],
13734        )
13735        .expect("right frame");
13736
13737        let err = merge_dataframes_on_with_options(
13738            &left,
13739            &right,
13740            &["id"],
13741            &["id"],
13742            JoinType::Inner,
13743            MergeExecutionOptions {
13744                validate_mode: Some(MergeValidateMode::ManyToOne),
13745                ..MergeExecutionOptions::default()
13746            },
13747        )
13748        .expect_err("many_to_one must reject duplicate right keys");
13749        assert!(format!("{err}").contains("right keys are not unique"));
13750    }
13751
13752    #[test]
13753    fn merge_validate_many_to_one_allows_duplicate_left_keys_9hsb3() {
13754        let left = DataFrame::from_dict(
13755            &["id", "left_v"],
13756            vec![
13757                (
13758                    "id",
13759                    vec![Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(2)],
13760                ),
13761                (
13762                    "left_v",
13763                    vec![Scalar::Int64(10), Scalar::Int64(11), Scalar::Int64(20)],
13764                ),
13765            ],
13766        )
13767        .expect("left frame");
13768        let right = DataFrame::from_dict(
13769            &["id", "right_v"],
13770            vec![
13771                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
13772                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
13773            ],
13774        )
13775        .expect("right frame");
13776
13777        let merged = merge_dataframes_on_with_options(
13778            &left,
13779            &right,
13780            &["id"],
13781            &["id"],
13782            JoinType::Inner,
13783            MergeExecutionOptions {
13784                validate_mode: Some(MergeValidateMode::ManyToOne),
13785                ..MergeExecutionOptions::default()
13786            },
13787        )
13788        .expect("many_to_one should allow duplicate left keys");
13789        assert_eq!(merged.columns.get("id").expect("id").values().len(), 3);
13790    }
13791
13792    #[test]
13793    fn merge_validate_many_to_many_allows_duplicates_on_both_sides() {
13794        let left = DataFrame::from_dict(
13795            &["id", "left_v"],
13796            vec![
13797                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
13798                ("left_v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
13799            ],
13800        )
13801        .expect("left frame");
13802        let right = DataFrame::from_dict(
13803            &["id", "right_v"],
13804            vec![
13805                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
13806                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
13807            ],
13808        )
13809        .expect("right frame");
13810
13811        let merged = merge_dataframes_on_with_options(
13812            &left,
13813            &right,
13814            &["id"],
13815            &["id"],
13816            JoinType::Inner,
13817            MergeExecutionOptions {
13818                validate_mode: Some(MergeValidateMode::ManyToMany),
13819                ..MergeExecutionOptions::default()
13820            },
13821        )
13822        .expect("many_to_many should allow duplicate keys on both sides");
13823        assert_eq!(merged.columns.get("id").expect("id").values().len(), 4);
13824    }
13825
13826    #[test]
13827    fn join_series_cross_cartesian_product() {
13828        let left = Series::from_values(
13829            "left",
13830            vec!["a".into(), "b".into()],
13831            vec![Scalar::Int64(1), Scalar::Int64(2)],
13832        )
13833        .unwrap();
13834        let right = Series::from_values(
13835            "right",
13836            vec!["x".into(), "y".into()],
13837            vec![Scalar::Int64(10), Scalar::Int64(20)],
13838        )
13839        .unwrap();
13840
13841        let out = join_series(&left, &right, JoinType::Cross).unwrap();
13842        assert_eq!(out.index.labels().len(), 4);
13843        assert_eq!(
13844            out.left_values.values(),
13845            &[
13846                Scalar::Int64(1),
13847                Scalar::Int64(1),
13848                Scalar::Int64(2),
13849                Scalar::Int64(2)
13850            ]
13851        );
13852        assert_eq!(
13853            out.right_values.values(),
13854            &[
13855                Scalar::Int64(10),
13856                Scalar::Int64(20),
13857                Scalar::Int64(10),
13858                Scalar::Int64(20)
13859            ]
13860        );
13861    }
13862
13863    // ── DataFrameMergeExt trait tests ──
13864
13865    #[test]
13866    fn dataframe_merge_via_trait() {
13867        use fp_frame::DataFrame;
13868
13869        use super::{DataFrameMergeExt, merge_dataframes_on};
13870
13871        let left = DataFrame::from_series(vec![
13872            Series::from_values(
13873                "key",
13874                vec![0_i64.into(), 1_i64.into()],
13875                vec![Scalar::Int64(1), Scalar::Int64(2)],
13876            )
13877            .unwrap(),
13878            Series::from_values(
13879                "val_l",
13880                vec![0_i64.into(), 1_i64.into()],
13881                vec![Scalar::Int64(10), Scalar::Int64(20)],
13882            )
13883            .unwrap(),
13884        ])
13885        .unwrap();
13886
13887        let right = DataFrame::from_series(vec![
13888            Series::from_values(
13889                "key",
13890                vec![0_i64.into(), 1_i64.into()],
13891                vec![Scalar::Int64(1), Scalar::Int64(3)],
13892            )
13893            .unwrap(),
13894            Series::from_values(
13895                "val_r",
13896                vec![0_i64.into(), 1_i64.into()],
13897                vec![Scalar::Int64(100), Scalar::Int64(300)],
13898            )
13899            .unwrap(),
13900        ])
13901        .unwrap();
13902
13903        // Instance method
13904        let result = left.merge(&right, &["key"], JoinType::Inner).unwrap();
13905        assert_eq!(result.index.len(), 1); // only key=1 matches
13906
13907        // Standalone function should give same result
13908        let result2 = merge_dataframes_on(&left, &right, &["key"], JoinType::Inner).unwrap();
13909        assert_eq!(result.index.len(), result2.index.len());
13910    }
13911
13912    // ── merge_asof tests ──
13913
13914    #[test]
13915    fn merge_asof_backward() {
13916        use super::DataFrameMergeExt;
13917
13918        // Left: trades at times 1, 3, 5, 7
13919        let left = fp_frame::DataFrame::from_dict(
13920            &["time", "price"],
13921            vec![
13922                (
13923                    "time",
13924                    vec![
13925                        Scalar::Int64(1),
13926                        Scalar::Int64(3),
13927                        Scalar::Int64(5),
13928                        Scalar::Int64(7),
13929                    ],
13930                ),
13931                (
13932                    "price",
13933                    vec![
13934                        Scalar::Float64(100.0),
13935                        Scalar::Float64(101.0),
13936                        Scalar::Float64(102.0),
13937                        Scalar::Float64(103.0),
13938                    ],
13939                ),
13940            ],
13941        )
13942        .unwrap();
13943
13944        // Right: quotes at times 2, 4, 6
13945        let right = fp_frame::DataFrame::from_dict(
13946            &["time", "bid"],
13947            vec![
13948                (
13949                    "time",
13950                    vec![Scalar::Int64(2), Scalar::Int64(4), Scalar::Int64(6)],
13951                ),
13952                (
13953                    "bid",
13954                    vec![
13955                        Scalar::Float64(99.5),
13956                        Scalar::Float64(100.5),
13957                        Scalar::Float64(101.5),
13958                    ],
13959                ),
13960            ],
13961        )
13962        .unwrap();
13963
13964        let result = left.merge_asof(&right, "time", "backward").unwrap();
13965        // For time=1: no right row <= 1, so bid=NaN
13966        // For time=3: last right row <= 3 is time=2 → bid=99.5
13967        // For time=5: last right row <= 5 is time=4 → bid=100.5
13968        // For time=7: last right row <= 7 is time=6 → bid=101.5
13969        let bid_col = result.columns.get("bid").unwrap();
13970        assert!(bid_col.values()[0].is_missing());
13971        assert_eq!(bid_col.values()[1], Scalar::Float64(99.5));
13972        assert_eq!(bid_col.values()[2], Scalar::Float64(100.5));
13973        assert_eq!(bid_col.values()[3], Scalar::Float64(101.5));
13974    }
13975
13976    #[test]
13977    fn merge_asof_forward() {
13978        use super::AsofDirection;
13979
13980        let left = fp_frame::DataFrame::from_dict(
13981            &["time", "val"],
13982            vec![
13983                ("time", vec![Scalar::Int64(1), Scalar::Int64(3)]),
13984                ("val", vec![Scalar::Float64(10.0), Scalar::Float64(30.0)]),
13985            ],
13986        )
13987        .unwrap();
13988
13989        let right = fp_frame::DataFrame::from_dict(
13990            &["time", "quote"],
13991            vec![
13992                ("time", vec![Scalar::Int64(2), Scalar::Int64(5)]),
13993                ("quote", vec![Scalar::Float64(20.0), Scalar::Float64(50.0)]),
13994            ],
13995        )
13996        .unwrap();
13997
13998        let result = super::merge_asof(&left, &right, "time", AsofDirection::Forward).unwrap();
13999        // time=1: first right >= 1 is time=2 → quote=20
14000        // time=3: first right >= 3 is time=5 → quote=50
14001        let quote_col = result.columns.get("quote").unwrap();
14002        assert_eq!(quote_col.values()[0], Scalar::Float64(20.0));
14003        assert_eq!(quote_col.values()[1], Scalar::Float64(50.0));
14004    }
14005
14006    #[test]
14007    fn merge_asof_nearest() {
14008        use super::AsofDirection;
14009
14010        let left = fp_frame::DataFrame::from_dict(
14011            &["time", "val"],
14012            vec![
14013                ("time", vec![Scalar::Int64(3), Scalar::Int64(7)]),
14014                ("val", vec![Scalar::Float64(1.0), Scalar::Float64(2.0)]),
14015            ],
14016        )
14017        .unwrap();
14018
14019        let right = fp_frame::DataFrame::from_dict(
14020            &["time", "ref_val"],
14021            vec![
14022                (
14023                    "time",
14024                    vec![Scalar::Int64(1), Scalar::Int64(5), Scalar::Int64(10)],
14025                ),
14026                (
14027                    "ref_val",
14028                    vec![
14029                        Scalar::Float64(100.0),
14030                        Scalar::Float64(500.0),
14031                        Scalar::Float64(1000.0),
14032                    ],
14033                ),
14034            ],
14035        )
14036        .unwrap();
14037
14038        let result = super::merge_asof(&left, &right, "time", AsofDirection::Nearest).unwrap();
14039        // time=3: nearest is 1(dist=2) or 5(dist=2), first found = 1 → ref_val=100
14040        // Actually: for nearest, it finds the one with smallest dist. dist(3,1)=2, dist(3,5)=2
14041        // ties go to first found, so ref_val = 100
14042        // time=7: nearest is 5(dist=2) or 10(dist=3) → ref_val=500
14043        let ref_col = result.columns.get("ref_val").unwrap();
14044        assert_eq!(ref_col.values()[1], Scalar::Float64(500.0)); // time=7 → 5 is nearest
14045    }
14046
14047    #[test]
14048    fn merge_asof_nearest_excludes_exact_finds_neighbor() {
14049        // Regression: with direction=nearest and allow_exact_matches=false,
14050        // an exact-equal key must be skipped over to reach the nearest
14051        // non-equal key, rather than yielding no match. Verified against
14052        // pandas 2.2.3: merge_asof(left=5, right=[3,5,5], nearest,
14053        // allow_exact_matches=False) -> matches value 3.
14054        use super::{AsofDirection, MergeAsofOptions};
14055
14056        let left = fp_frame::DataFrame::from_dict(
14057            &["time", "val"],
14058            vec![
14059                ("time", vec![Scalar::Int64(5)]),
14060                ("val", vec![Scalar::Int64(1)]),
14061            ],
14062        )
14063        .unwrap();
14064        let right = fp_frame::DataFrame::from_dict(
14065            &["time", "ref_val"],
14066            vec![
14067                (
14068                    "time",
14069                    vec![Scalar::Int64(3), Scalar::Int64(5), Scalar::Int64(5)],
14070                ),
14071                (
14072                    "ref_val",
14073                    vec![
14074                        Scalar::Float64(10.0),
14075                        Scalar::Float64(20.0),
14076                        Scalar::Float64(30.0),
14077                    ],
14078                ),
14079            ],
14080        )
14081        .unwrap();
14082
14083        let opts = MergeAsofOptions::new().allow_exact_matches(false);
14084        let result =
14085            super::merge_asof_with_options(&left, &right, "time", AsofDirection::Nearest, opts)
14086                .unwrap();
14087        let ref_col = result.columns.get("ref_val").unwrap();
14088        assert_eq!(ref_col.values()[0], Scalar::Float64(10.0)); // value 3 is nearest non-exact
14089    }
14090
14091    #[test]
14092    fn merge_asof_exact_match() {
14093        use super::AsofDirection;
14094
14095        let left = fp_frame::DataFrame::from_dict(
14096            &["time", "val"],
14097            vec![
14098                ("time", vec![Scalar::Int64(2), Scalar::Int64(4)]),
14099                ("val", vec![Scalar::Float64(1.0), Scalar::Float64(2.0)]),
14100            ],
14101        )
14102        .unwrap();
14103
14104        let right = fp_frame::DataFrame::from_dict(
14105            &["time", "quote"],
14106            vec![
14107                ("time", vec![Scalar::Int64(2), Scalar::Int64(4)]),
14108                ("quote", vec![Scalar::Float64(20.0), Scalar::Float64(40.0)]),
14109            ],
14110        )
14111        .unwrap();
14112
14113        // Backward: exact match should work (right_val <= left_val includes ==).
14114        let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
14115        assert_eq!(
14116            result.columns.get("quote").unwrap().values()[0],
14117            Scalar::Float64(20.0)
14118        );
14119        assert_eq!(
14120            result.columns.get("quote").unwrap().values()[1],
14121            Scalar::Float64(40.0)
14122        );
14123
14124        // Forward: exact match should work (right_val >= left_val includes ==).
14125        let result = super::merge_asof(&left, &right, "time", AsofDirection::Forward).unwrap();
14126        assert_eq!(
14127            result.columns.get("quote").unwrap().values()[0],
14128            Scalar::Float64(20.0)
14129        );
14130    }
14131
14132    #[test]
14133    fn merge_asof_no_matches_backward() {
14134        use super::AsofDirection;
14135
14136        let left = fp_frame::DataFrame::from_dict(
14137            &["time", "val"],
14138            vec![
14139                ("time", vec![Scalar::Int64(1)]),
14140                ("val", vec![Scalar::Float64(10.0)]),
14141            ],
14142        )
14143        .unwrap();
14144
14145        // Right starts at time=5, so backward from time=1 finds nothing.
14146        let right = fp_frame::DataFrame::from_dict(
14147            &["time", "quote"],
14148            vec![
14149                ("time", vec![Scalar::Int64(5)]),
14150                ("quote", vec![Scalar::Float64(50.0)]),
14151            ],
14152        )
14153        .unwrap();
14154
14155        let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
14156        assert!(result.columns.get("quote").unwrap().values()[0].is_missing());
14157    }
14158
14159    #[test]
14160    fn merge_asof_no_matches_forward() {
14161        use super::AsofDirection;
14162
14163        let left = fp_frame::DataFrame::from_dict(
14164            &["time", "val"],
14165            vec![
14166                ("time", vec![Scalar::Int64(10)]),
14167                ("val", vec![Scalar::Float64(10.0)]),
14168            ],
14169        )
14170        .unwrap();
14171
14172        // Right ends at time=5, so forward from time=10 finds nothing.
14173        let right = fp_frame::DataFrame::from_dict(
14174            &["time", "quote"],
14175            vec![
14176                ("time", vec![Scalar::Int64(5)]),
14177                ("quote", vec![Scalar::Float64(50.0)]),
14178            ],
14179        )
14180        .unwrap();
14181
14182        let result = super::merge_asof(&left, &right, "time", AsofDirection::Forward).unwrap();
14183        assert!(result.columns.get("quote").unwrap().values()[0].is_missing());
14184    }
14185
14186    #[test]
14187    fn merge_asof_nan_in_key() {
14188        use super::AsofDirection;
14189
14190        let left = fp_frame::DataFrame::from_dict(
14191            &["time", "val"],
14192            vec![
14193                (
14194                    "time",
14195                    vec![
14196                        Scalar::Int64(1),
14197                        Scalar::Null(NullKind::NaN),
14198                        Scalar::Int64(5),
14199                    ],
14200                ),
14201                (
14202                    "val",
14203                    vec![
14204                        Scalar::Float64(10.0),
14205                        Scalar::Float64(20.0),
14206                        Scalar::Float64(30.0),
14207                    ],
14208                ),
14209            ],
14210        )
14211        .unwrap();
14212
14213        let right = fp_frame::DataFrame::from_dict(
14214            &["time", "quote"],
14215            vec![
14216                ("time", vec![Scalar::Int64(2), Scalar::Int64(4)]),
14217                (
14218                    "quote",
14219                    vec![Scalar::Float64(200.0), Scalar::Float64(400.0)],
14220                ),
14221            ],
14222        )
14223        .unwrap();
14224
14225        // pandas merge_asof accepts NaN keys: the NaN row gets no match
14226        // (null in joined columns) — verified against FP-P2D-056
14227        // backward_nan_left_key_strict (pandas 2.2.3 oracle).
14228        let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
14229        assert!(result.columns.get("quote").unwrap().values()[1].is_missing());
14230        // time=5 → backward match to time=4 → quote=400
14231        assert_eq!(
14232            result.columns.get("quote").unwrap().values()[2],
14233            Scalar::Float64(400.0)
14234        );
14235    }
14236
14237    #[test]
14238    fn merge_asof_nan_in_right_key() {
14239        use super::AsofDirection;
14240
14241        // Symmetric to merge_asof_nan_in_key: NaN keys on the right side
14242        // also get treated as no-candidate (pandas does NOT raise). Other
14243        // left rows still match to non-NaN right rows.
14244        let left = fp_frame::DataFrame::from_dict(
14245            &["time", "val"],
14246            vec![
14247                (
14248                    "time",
14249                    vec![Scalar::Int64(1), Scalar::Int64(3), Scalar::Int64(5)],
14250                ),
14251                (
14252                    "val",
14253                    vec![
14254                        Scalar::Float64(10.0),
14255                        Scalar::Float64(20.0),
14256                        Scalar::Float64(30.0),
14257                    ],
14258                ),
14259            ],
14260        )
14261        .unwrap();
14262
14263        let right = fp_frame::DataFrame::from_dict(
14264            &["time", "quote"],
14265            vec![
14266                (
14267                    "time",
14268                    vec![
14269                        Scalar::Int64(2),
14270                        Scalar::Null(NullKind::NaN),
14271                        Scalar::Int64(4),
14272                    ],
14273                ),
14274                (
14275                    "quote",
14276                    vec![
14277                        Scalar::Float64(200.0),
14278                        Scalar::Float64(999.0),
14279                        Scalar::Float64(400.0),
14280                    ],
14281                ),
14282            ],
14283        )
14284        .unwrap();
14285
14286        let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
14287        // left time=1 → no right ≤ 1 → null
14288        assert!(result.columns.get("quote").unwrap().values()[0].is_missing());
14289        // left time=3 → right time=2 → 200.0 (NaN right row never matches)
14290        assert_eq!(
14291            result.columns.get("quote").unwrap().values()[1],
14292            Scalar::Float64(200.0)
14293        );
14294        // left time=5 → right time=4 → 400.0
14295        assert_eq!(
14296            result.columns.get("quote").unwrap().values()[2],
14297            Scalar::Float64(400.0)
14298        );
14299    }
14300
14301    #[test]
14302    fn merge_asof_overlapping_columns_apply_suffixes() {
14303        use super::AsofDirection;
14304
14305        let left = fp_frame::DataFrame::from_dict(
14306            &["time", "shared", "left_only"],
14307            vec![
14308                ("time", vec![Scalar::Int64(1), Scalar::Int64(2)]),
14309                ("shared", vec![Scalar::Int64(10), Scalar::Int64(20)]),
14310                ("left_only", vec![Scalar::Int64(1), Scalar::Int64(2)]),
14311            ],
14312        )
14313        .unwrap();
14314
14315        let right = fp_frame::DataFrame::from_dict(
14316            &["time", "shared", "right_only"],
14317            vec![
14318                ("time", vec![Scalar::Int64(1), Scalar::Int64(2)]),
14319                ("shared", vec![Scalar::Int64(100), Scalar::Int64(200)]),
14320                ("right_only", vec![Scalar::Int64(9), Scalar::Int64(8)]),
14321            ],
14322        )
14323        .unwrap();
14324
14325        let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
14326        let shared_left = result.columns.get("shared_x").unwrap().values();
14327        let shared_right = result.columns.get("shared_y").unwrap().values();
14328
14329        assert_eq!(shared_left[0], Scalar::Int64(10));
14330        assert_eq!(shared_left[1], Scalar::Int64(20));
14331        assert_eq!(shared_right[0], Scalar::Int64(100));
14332        assert_eq!(shared_right[1], Scalar::Int64(200));
14333    }
14334
14335    #[test]
14336    fn merge_asof_duplicate_column_gets_suffix() {
14337        use super::AsofDirection;
14338
14339        // Both left and right have a "val" column besides the key.
14340        let left = fp_frame::DataFrame::from_dict(
14341            &["time", "val"],
14342            vec![
14343                ("time", vec![Scalar::Int64(1)]),
14344                ("val", vec![Scalar::Float64(10.0)]),
14345            ],
14346        )
14347        .unwrap();
14348
14349        let right = fp_frame::DataFrame::from_dict(
14350            &["time", "val"],
14351            vec![
14352                ("time", vec![Scalar::Int64(1)]),
14353                ("val", vec![Scalar::Float64(99.0)]),
14354            ],
14355        )
14356        .unwrap();
14357
14358        let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
14359        // Overlapping columns should receive default merge suffixes.
14360        assert!(result.columns.contains_key("val_x"));
14361        assert!(result.columns.contains_key("val_y"));
14362        assert_eq!(
14363            result.columns.get("val_x").unwrap().values()[0],
14364            Scalar::Float64(10.0)
14365        );
14366        assert_eq!(
14367            result.columns.get("val_y").unwrap().values()[0],
14368            Scalar::Float64(99.0)
14369        );
14370    }
14371
14372    #[test]
14373    fn merge_asof_missing_column_errors() {
14374        use super::AsofDirection;
14375
14376        let left =
14377            fp_frame::DataFrame::from_dict(&["a"], vec![("a", vec![Scalar::Int64(1)])]).unwrap();
14378
14379        let right =
14380            fp_frame::DataFrame::from_dict(&["b"], vec![("b", vec![Scalar::Int64(1)])]).unwrap();
14381
14382        let err = super::merge_asof(&left, &right, "time", AsofDirection::Backward);
14383        assert!(err.is_err());
14384    }
14385
14386    #[test]
14387    fn merge_asof_invalid_direction_errors() {
14388        let left =
14389            fp_frame::DataFrame::from_dict(&["time"], vec![("time", vec![Scalar::Int64(1)])])
14390                .unwrap();
14391        let right =
14392            fp_frame::DataFrame::from_dict(&["time"], vec![("time", vec![Scalar::Int64(1)])])
14393                .unwrap();
14394
14395        let err = left.merge_asof(&right, "time", "sideways");
14396        assert!(matches!(
14397            err,
14398            Err(super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(msg)))
14399                if msg.contains("invalid direction")
14400        ));
14401    }
14402
14403    #[test]
14404    fn merge_asof_unsorted_left_errors() {
14405        use super::AsofDirection;
14406
14407        let left = fp_frame::DataFrame::from_dict(
14408            &["time", "val"],
14409            vec![
14410                ("time", vec![Scalar::Int64(2), Scalar::Int64(1)]),
14411                ("val", vec![Scalar::Float64(10.0), Scalar::Float64(20.0)]),
14412            ],
14413        )
14414        .unwrap();
14415
14416        let right = fp_frame::DataFrame::from_dict(
14417            &["time", "quote"],
14418            vec![
14419                ("time", vec![Scalar::Int64(1), Scalar::Int64(2)]),
14420                (
14421                    "quote",
14422                    vec![Scalar::Float64(100.0), Scalar::Float64(200.0)],
14423                ),
14424            ],
14425        )
14426        .unwrap();
14427
14428        let err = super::merge_asof(&left, &right, "time", AsofDirection::Backward)
14429            .expect_err("unsorted left should error");
14430        assert!(matches!(
14431            err,
14432            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(msg))
14433                if msg.contains("sorted")
14434        ));
14435    }
14436
14437    #[test]
14438    fn merge_asof_unsorted_right_errors() {
14439        use super::AsofDirection;
14440
14441        let left = fp_frame::DataFrame::from_dict(
14442            &["time", "val"],
14443            vec![
14444                ("time", vec![Scalar::Int64(1), Scalar::Int64(2)]),
14445                ("val", vec![Scalar::Float64(10.0), Scalar::Float64(20.0)]),
14446            ],
14447        )
14448        .unwrap();
14449
14450        let right = fp_frame::DataFrame::from_dict(
14451            &["time", "quote"],
14452            vec![
14453                ("time", vec![Scalar::Int64(2), Scalar::Int64(1)]),
14454                (
14455                    "quote",
14456                    vec![Scalar::Float64(200.0), Scalar::Float64(100.0)],
14457                ),
14458            ],
14459        )
14460        .unwrap();
14461
14462        let err = super::merge_asof(&left, &right, "time", AsofDirection::Backward)
14463            .expect_err("unsorted right should error");
14464        assert!(matches!(
14465            err,
14466            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(msg))
14467                if msg.contains("sorted")
14468        ));
14469    }
14470
14471    #[test]
14472    fn merge_asof_non_numeric_key_errors() {
14473        use super::AsofDirection;
14474
14475        let left = fp_frame::DataFrame::from_dict(
14476            &["time", "val"],
14477            vec![
14478                ("time", vec![Scalar::Utf8("a".into())]),
14479                ("val", vec![Scalar::Float64(10.0)]),
14480            ],
14481        )
14482        .unwrap();
14483
14484        let right = fp_frame::DataFrame::from_dict(
14485            &["time", "quote"],
14486            vec![
14487                ("time", vec![Scalar::Utf8("b".into())]),
14488                ("quote", vec![Scalar::Float64(20.0)]),
14489            ],
14490        )
14491        .unwrap();
14492
14493        let err = super::merge_asof(&left, &right, "time", AsofDirection::Backward)
14494            .expect_err("non-numeric key should error");
14495        assert!(matches!(
14496            err,
14497            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(msg))
14498                if msg.contains("numeric")
14499        ));
14500    }
14501
14502    #[test]
14503    fn merge_asof_preserves_all_left_rows() {
14504        use super::AsofDirection;
14505
14506        let left = fp_frame::DataFrame::from_dict(
14507            &["time", "val"],
14508            vec![
14509                (
14510                    "time",
14511                    vec![
14512                        Scalar::Int64(1),
14513                        Scalar::Int64(2),
14514                        Scalar::Int64(3),
14515                        Scalar::Int64(4),
14516                        Scalar::Int64(5),
14517                    ],
14518                ),
14519                (
14520                    "val",
14521                    vec![
14522                        Scalar::Float64(10.0),
14523                        Scalar::Float64(20.0),
14524                        Scalar::Float64(30.0),
14525                        Scalar::Float64(40.0),
14526                        Scalar::Float64(50.0),
14527                    ],
14528                ),
14529            ],
14530        )
14531        .unwrap();
14532
14533        let right = fp_frame::DataFrame::from_dict(
14534            &["time", "quote"],
14535            vec![
14536                ("time", vec![Scalar::Int64(3)]),
14537                ("quote", vec![Scalar::Float64(300.0)]),
14538            ],
14539        )
14540        .unwrap();
14541
14542        let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
14543        // All 5 left rows should be present.
14544        assert_eq!(result.index.len(), 5);
14545    }
14546
14547    // ── merge_asof options tests ──
14548
14549    #[test]
14550    fn merge_asof_allow_exact_matches_false_backward() {
14551        use super::{AsofDirection, MergeAsofOptions, merge_asof_with_options};
14552
14553        // Left: keys 1, 2, 3
14554        let left = fp_frame::DataFrame::from_dict(
14555            &["time", "val"],
14556            vec![
14557                (
14558                    "time",
14559                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
14560                ),
14561                (
14562                    "val",
14563                    vec![
14564                        Scalar::Float64(10.0),
14565                        Scalar::Float64(20.0),
14566                        Scalar::Float64(30.0),
14567                    ],
14568                ),
14569            ],
14570        )
14571        .unwrap();
14572
14573        // Right: keys 1, 2, 3 (exact matches exist)
14574        let right = fp_frame::DataFrame::from_dict(
14575            &["time", "quote"],
14576            vec![
14577                (
14578                    "time",
14579                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
14580                ),
14581                (
14582                    "quote",
14583                    vec![
14584                        Scalar::Float64(100.0),
14585                        Scalar::Float64(200.0),
14586                        Scalar::Float64(300.0),
14587                    ],
14588                ),
14589            ],
14590        )
14591        .unwrap();
14592
14593        // With allow_exact_matches=true (default), all should match
14594        let result_with_exact = merge_asof_with_options(
14595            &left,
14596            &right,
14597            "time",
14598            AsofDirection::Backward,
14599            MergeAsofOptions::new(),
14600        )
14601        .unwrap();
14602
14603        let quote_col = result_with_exact.columns.get("quote").unwrap();
14604        assert_eq!(quote_col.values()[0], Scalar::Float64(100.0)); // 1 matches 1
14605        assert_eq!(quote_col.values()[1], Scalar::Float64(200.0)); // 2 matches 2
14606        assert_eq!(quote_col.values()[2], Scalar::Float64(300.0)); // 3 matches 3
14607
14608        // With allow_exact_matches=false, exact matches should be excluded
14609        let result_no_exact = merge_asof_with_options(
14610            &left,
14611            &right,
14612            "time",
14613            AsofDirection::Backward,
14614            MergeAsofOptions::new().allow_exact_matches(false),
14615        )
14616        .unwrap();
14617
14618        let quote_col_no_exact = result_no_exact.columns.get("quote").unwrap();
14619        // 1 has no previous right key, should be null
14620        assert!(matches!(quote_col_no_exact.values()[0], Scalar::Null(_)));
14621        // 2 should match previous (1)
14622        assert_eq!(quote_col_no_exact.values()[1], Scalar::Float64(100.0));
14623        // 3 should match previous (2)
14624        assert_eq!(quote_col_no_exact.values()[2], Scalar::Float64(200.0));
14625    }
14626
14627    #[test]
14628    fn merge_asof_tolerance() {
14629        use super::{AsofDirection, MergeAsofOptions, merge_asof_with_options};
14630
14631        // Left: keys 1, 5, 10
14632        let left = fp_frame::DataFrame::from_dict(
14633            &["time", "val"],
14634            vec![
14635                (
14636                    "time",
14637                    vec![Scalar::Int64(1), Scalar::Int64(5), Scalar::Int64(10)],
14638                ),
14639                (
14640                    "val",
14641                    vec![
14642                        Scalar::Float64(10.0),
14643                        Scalar::Float64(50.0),
14644                        Scalar::Float64(100.0),
14645                    ],
14646                ),
14647            ],
14648        )
14649        .unwrap();
14650
14651        // Right: keys 2, 6
14652        let right = fp_frame::DataFrame::from_dict(
14653            &["time", "quote"],
14654            vec![
14655                ("time", vec![Scalar::Int64(2), Scalar::Int64(6)]),
14656                (
14657                    "quote",
14658                    vec![Scalar::Float64(200.0), Scalar::Float64(600.0)],
14659                ),
14660            ],
14661        )
14662        .unwrap();
14663
14664        // With tolerance=2, matches within 2 units are valid
14665        let result = merge_asof_with_options(
14666            &left,
14667            &right,
14668            "time",
14669            AsofDirection::Backward,
14670            MergeAsofOptions::new().tolerance(2.0),
14671        )
14672        .unwrap();
14673
14674        let quote_col = result.columns.get("quote").unwrap();
14675        // 1 < 2, no previous match, null
14676        assert!(matches!(quote_col.values()[0], Scalar::Null(_)));
14677        // 5 finds 2 (diff = 3), but tolerance is 2, so null
14678        assert!(matches!(quote_col.values()[1], Scalar::Null(_)));
14679        // 10 finds 6 (diff = 4), but tolerance is 2, so null
14680        assert!(matches!(quote_col.values()[2], Scalar::Null(_)));
14681
14682        // With tolerance=5, all should match
14683        let result_wider = merge_asof_with_options(
14684            &left,
14685            &right,
14686            "time",
14687            AsofDirection::Backward,
14688            MergeAsofOptions::new().tolerance(5.0),
14689        )
14690        .unwrap();
14691
14692        let quote_col_wider = result_wider.columns.get("quote").unwrap();
14693        // 1 < 2, still no previous
14694        assert!(matches!(quote_col_wider.values()[0], Scalar::Null(_)));
14695        // 5 finds 2 (diff = 3 <= 5)
14696        assert_eq!(quote_col_wider.values()[1], Scalar::Float64(200.0));
14697        // 10 finds 6 (diff = 4 <= 5)
14698        assert_eq!(quote_col_wider.values()[2], Scalar::Float64(600.0));
14699    }
14700
14701    #[test]
14702    fn merge_asof_by_column() {
14703        use super::{AsofDirection, MergeAsofOptions, merge_asof_with_options};
14704
14705        // Left: two groups (A and B), each with times
14706        let left = fp_frame::DataFrame::from_dict(
14707            &["group", "time", "val"],
14708            vec![
14709                (
14710                    "group",
14711                    vec![
14712                        Scalar::Utf8("A".into()),
14713                        Scalar::Utf8("A".into()),
14714                        Scalar::Utf8("B".into()),
14715                        Scalar::Utf8("B".into()),
14716                    ],
14717                ),
14718                (
14719                    "time",
14720                    vec![
14721                        Scalar::Int64(1),
14722                        Scalar::Int64(2),
14723                        Scalar::Int64(3),
14724                        Scalar::Int64(4),
14725                    ],
14726                ),
14727                (
14728                    "val",
14729                    vec![
14730                        Scalar::Float64(10.0),
14731                        Scalar::Float64(30.0),
14732                        Scalar::Float64(20.0),
14733                        Scalar::Float64(40.0),
14734                    ],
14735                ),
14736            ],
14737        )
14738        .unwrap();
14739
14740        // Right: same groups with quotes
14741        let right = fp_frame::DataFrame::from_dict(
14742            &["group", "time", "quote"],
14743            vec![
14744                (
14745                    "group",
14746                    vec![
14747                        Scalar::Utf8("A".into()),
14748                        Scalar::Utf8("B".into()),
14749                        Scalar::Utf8("A".into()),
14750                    ],
14751                ),
14752                (
14753                    "time",
14754                    vec![Scalar::Int64(2), Scalar::Int64(3), Scalar::Int64(4)],
14755                ),
14756                (
14757                    "quote",
14758                    vec![
14759                        Scalar::Float64(200.0),
14760                        Scalar::Float64(400.0),
14761                        Scalar::Float64(300.0),
14762                    ],
14763                ),
14764            ],
14765        )
14766        .unwrap();
14767
14768        // Merge with 'by' column
14769        let result = merge_asof_with_options(
14770            &left,
14771            &right,
14772            "time",
14773            AsofDirection::Backward,
14774            MergeAsofOptions::new().by(vec!["group".to_string()]),
14775        )
14776        .unwrap();
14777
14778        let quote_col = result.columns.get("quote").unwrap();
14779        // Left after 2d3338b1's reorder is (A,1), (A,2), (B,3), (B,4) — globally
14780        // sorted by time. Right is (A,2), (B,3), (A,4). Backward grouped asof:
14781        // Row 0: (A,1) → no right A with time <= 1 → null
14782        assert!(matches!(quote_col.values()[0], Scalar::Null(_)));
14783        // Row 1: (A,2) → right A time=2 → 200.0
14784        assert_eq!(quote_col.values()[1], Scalar::Float64(200.0));
14785        // Row 2: (B,3) → right B time=3 → 400.0
14786        assert_eq!(quote_col.values()[2], Scalar::Float64(400.0));
14787        // Row 3: (B,4) → right B time=3 (latest <= 4) → 400.0
14788        assert_eq!(quote_col.values()[3], Scalar::Float64(400.0));
14789    }
14790
14791    #[test]
14792    fn merge_asof_by_column_requires_globally_sorted_left_keys() {
14793        use super::{AsofDirection, MergeAsofOptions, merge_asof_with_options};
14794
14795        let left = fp_frame::DataFrame::from_dict(
14796            &["group", "time"],
14797            vec![
14798                (
14799                    "group",
14800                    vec![
14801                        Scalar::Utf8("A".into()),
14802                        Scalar::Utf8("A".into()),
14803                        Scalar::Utf8("B".into()),
14804                        Scalar::Utf8("B".into()),
14805                    ],
14806                ),
14807                (
14808                    "time",
14809                    vec![
14810                        Scalar::Int64(1),
14811                        Scalar::Int64(3),
14812                        Scalar::Int64(1),
14813                        Scalar::Int64(2),
14814                    ],
14815                ),
14816            ],
14817        )
14818        .unwrap();
14819        let right = fp_frame::DataFrame::from_dict(
14820            &["group", "time", "quote"],
14821            vec![
14822                (
14823                    "group",
14824                    vec![
14825                        Scalar::Utf8("A".into()),
14826                        Scalar::Utf8("B".into()),
14827                        Scalar::Utf8("A".into()),
14828                    ],
14829                ),
14830                (
14831                    "time",
14832                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
14833                ),
14834                (
14835                    "quote",
14836                    vec![
14837                        Scalar::Float64(10.0),
14838                        Scalar::Float64(20.0),
14839                        Scalar::Float64(30.0),
14840                    ],
14841                ),
14842            ],
14843        )
14844        .unwrap();
14845
14846        let err = merge_asof_with_options(
14847            &left,
14848            &right,
14849            "time",
14850            AsofDirection::Backward,
14851            MergeAsofOptions::new().by(vec!["group".to_string()]),
14852        )
14853        .expect_err("pandas requires globally sorted left keys even with by=");
14854        assert!(matches!(
14855            err,
14856            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(message))
14857                if message.contains("left") && message.contains("sorted")
14858        ));
14859    }
14860
14861    #[test]
14862    fn merge_asof_by_column_requires_globally_sorted_right_keys() {
14863        use super::{AsofDirection, MergeAsofOptions, merge_asof_with_options};
14864
14865        let left = fp_frame::DataFrame::from_dict(
14866            &["group", "time"],
14867            vec![
14868                (
14869                    "group",
14870                    vec![
14871                        Scalar::Utf8("A".into()),
14872                        Scalar::Utf8("B".into()),
14873                        Scalar::Utf8("A".into()),
14874                    ],
14875                ),
14876                (
14877                    "time",
14878                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
14879                ),
14880            ],
14881        )
14882        .unwrap();
14883        let right = fp_frame::DataFrame::from_dict(
14884            &["group", "time", "quote"],
14885            vec![
14886                (
14887                    "group",
14888                    vec![
14889                        Scalar::Utf8("A".into()),
14890                        Scalar::Utf8("A".into()),
14891                        Scalar::Utf8("B".into()),
14892                    ],
14893                ),
14894                (
14895                    "time",
14896                    vec![Scalar::Int64(1), Scalar::Int64(3), Scalar::Int64(2)],
14897                ),
14898                (
14899                    "quote",
14900                    vec![
14901                        Scalar::Float64(10.0),
14902                        Scalar::Float64(30.0),
14903                        Scalar::Float64(20.0),
14904                    ],
14905                ),
14906            ],
14907        )
14908        .unwrap();
14909
14910        let err = merge_asof_with_options(
14911            &left,
14912            &right,
14913            "time",
14914            AsofDirection::Backward,
14915            MergeAsofOptions::new().by(vec!["group".to_string()]),
14916        )
14917        .expect_err("pandas requires globally sorted right keys even with by=");
14918        assert!(matches!(
14919            err,
14920            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(message))
14921                if message.contains("right") && message.contains("sorted")
14922        ));
14923    }
14924
14925    #[test]
14926    fn merge_ordered_sorts_and_ffills_values() {
14927        let left = fp_frame::DataFrame::from_dict(
14928            &["date", "left_val"],
14929            vec![
14930                ("date", vec![Scalar::Int64(1), Scalar::Int64(3)]),
14931                ("left_val", vec![Scalar::Int64(10), Scalar::Int64(30)]),
14932            ],
14933        )
14934        .unwrap();
14935
14936        let right = fp_frame::DataFrame::from_dict(
14937            &["date", "right_val"],
14938            vec![
14939                ("date", vec![Scalar::Int64(2), Scalar::Int64(3)]),
14940                ("right_val", vec![Scalar::Int64(200), Scalar::Int64(300)]),
14941            ],
14942        )
14943        .unwrap();
14944
14945        let result = super::merge_ordered(&left, &right, &["date"], Some("ffill")).unwrap();
14946        let frame = fp_frame::DataFrame::new(result.index, result.columns).unwrap();
14947
14948        assert_eq!(
14949            frame.column("date").unwrap().values(),
14950            &[Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)]
14951        );
14952        assert_eq!(
14953            frame.column("left_val").unwrap().values(),
14954            &[
14955                Scalar::Float64(10.0),
14956                Scalar::Float64(10.0),
14957                Scalar::Float64(30.0),
14958            ]
14959        );
14960        assert_eq!(
14961            frame.column("right_val").unwrap().values(),
14962            &[
14963                Scalar::Null(NullKind::NaN),
14964                Scalar::Float64(200.0),
14965                Scalar::Float64(300.0),
14966            ]
14967        );
14968    }
14969
14970    #[test]
14971    fn merge_ordered_invalid_fill_method_errors() {
14972        let left = fp_frame::DataFrame::from_dict(
14973            &["date", "left_val"],
14974            vec![
14975                ("date", vec![Scalar::Int64(1)]),
14976                ("left_val", vec![Scalar::Int64(10)]),
14977            ],
14978        )
14979        .unwrap();
14980
14981        let right = fp_frame::DataFrame::from_dict(
14982            &["date", "right_val"],
14983            vec![
14984                ("date", vec![Scalar::Int64(2)]),
14985                ("right_val", vec![Scalar::Int64(200)]),
14986            ],
14987        )
14988        .unwrap();
14989
14990        let err = super::merge_ordered(&left, &right, &["date"], Some("sideways"))
14991            .expect_err("invalid fill method should error");
14992        assert!(matches!(
14993            err,
14994            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(message))
14995                if message.contains("fill_method must be 'ffill' or None")
14996        ));
14997    }
14998
14999    #[test]
15000    fn merge_ordered_rejects_bfill_like_pandas() {
15001        let left = fp_frame::DataFrame::from_dict(
15002            &["date", "left_val"],
15003            vec![
15004                ("date", vec![Scalar::Int64(1), Scalar::Int64(3)]),
15005                ("left_val", vec![Scalar::Int64(10), Scalar::Int64(30)]),
15006            ],
15007        )
15008        .unwrap();
15009
15010        let right = fp_frame::DataFrame::from_dict(
15011            &["date", "right_val"],
15012            vec![
15013                ("date", vec![Scalar::Int64(2), Scalar::Int64(3)]),
15014                ("right_val", vec![Scalar::Int64(200), Scalar::Int64(300)]),
15015            ],
15016        )
15017        .unwrap();
15018
15019        let err = super::merge_ordered(&left, &right, &["date"], Some("bfill"))
15020            .expect_err("pandas only accepts fill_method='ffill' or None");
15021        assert!(matches!(
15022            err,
15023            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(message))
15024                if message.contains("fill_method must be 'ffill' or None")
15025        ));
15026    }
15027
15028    // ── join() pandas-named alias (br-frankenpandas-nk54a) ──────────────
15029
15030    #[test]
15031    fn dataframe_join_aliases_join_on_index() {
15032        use std::collections::BTreeMap;
15033
15034        use fp_columnar::Column;
15035        use fp_frame::DataFrame;
15036        use fp_index::Index;
15037        use fp_types::{DType, Scalar};
15038
15039        use super::DataFrameMergeExt;
15040
15041        fn build(name1: &str, name2: &str, vals1: &[i64], vals2: &[i64]) -> DataFrame {
15042            let mut cols = BTreeMap::new();
15043            cols.insert(
15044                name1.to_owned(),
15045                Column::new(
15046                    DType::Int64,
15047                    vals1.iter().map(|v| Scalar::Int64(*v)).collect(),
15048                )
15049                .unwrap(),
15050            );
15051            cols.insert(
15052                name2.to_owned(),
15053                Column::new(
15054                    DType::Int64,
15055                    vals2.iter().map(|v| Scalar::Int64(*v)).collect(),
15056                )
15057                .unwrap(),
15058            );
15059            DataFrame::new_with_column_order(
15060                Index::new(
15061                    (0..vals1.len() as i64)
15062                        .map(fp_index::IndexLabel::Int64)
15063                        .collect(),
15064                ),
15065                cols,
15066                vec![name1.to_owned(), name2.to_owned()],
15067            )
15068            .unwrap()
15069        }
15070
15071        let left = build("a", "b", &[10, 20, 30], &[1, 2, 3]);
15072        let right = build("c", "d", &[100, 200, 300], &[7, 8, 9]);
15073
15074        let via_join = left.join(&right, super::JoinType::Inner).unwrap();
15075        let via_join_on_index = left.join_on_index(&right, super::JoinType::Inner).unwrap();
15076
15077        // Both produce the same MergedDataFrame shape & values.
15078        let join_keys: Vec<&String> = via_join.columns.keys().collect();
15079        let idx_keys: Vec<&String> = via_join_on_index.columns.keys().collect();
15080        assert_eq!(join_keys, idx_keys);
15081        assert_eq!(via_join.index, via_join_on_index.index);
15082        for k in via_join.columns.keys() {
15083            assert_eq!(
15084                via_join.columns.get(k).unwrap().values(),
15085                via_join_on_index.columns.get(k).unwrap().values(),
15086                "column {k} differs"
15087            );
15088        }
15089    }
15090}