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 collect_contiguous_utf8_position_map<'a>(
6330    bytes: &'a [u8],
6331    offsets: &[usize],
6332) -> FxHashMap<&'a [u8], JoinPositionBucket> {
6333    let n = offsets.len() - 1;
6334    let mut map =
6335        FxHashMap::<&[u8], JoinPositionBucket>::with_capacity_and_hasher(n, Default::default());
6336    for pos in 0..n {
6337        let span = &bytes[offsets[pos]..offsets[pos + 1]];
6338        map.entry(span).or_default().push(pos);
6339    }
6340    map
6341}
6342
6343fn contiguous_utf8_left_positions(
6344    left_key: &Column,
6345    right_key: &Column,
6346) -> Option<OptionalJoinPositions> {
6347    let (left_bytes, left_offsets) = left_key.as_utf8_contiguous()?;
6348    let (right_bytes, right_offsets) = right_key.as_utf8_contiguous()?;
6349    let left_n = left_offsets.len() - 1;
6350    let right_map = collect_contiguous_utf8_position_map(right_bytes, right_offsets);
6351
6352    let mut out_len = 0usize;
6353    for left_pos in 0..left_n {
6354        let span = &left_bytes[left_offsets[left_pos]..left_offsets[left_pos + 1]];
6355        out_len += right_map.get(span).map_or(1, JoinPositionBucket::len);
6356    }
6357
6358    let mut left_positions = Vec::<Option<usize>>::with_capacity(out_len);
6359    let mut right_positions = Vec::<Option<usize>>::with_capacity(out_len);
6360    for left_pos in 0..left_n {
6361        let span = &left_bytes[left_offsets[left_pos]..left_offsets[left_pos + 1]];
6362        if let Some(matches) = right_map.get(span) {
6363            for &right_pos in matches {
6364                left_positions.push(Some(left_pos));
6365                right_positions.push(Some(right_pos));
6366            }
6367        } else {
6368            left_positions.push(Some(left_pos));
6369            right_positions.push(None);
6370        }
6371    }
6372    Some((left_positions, right_positions))
6373}
6374
6375fn contiguous_utf8_outer_positions(
6376    left_key: &Column,
6377    right_key: &Column,
6378) -> Option<OptionalJoinPositions> {
6379    let (left_bytes, left_offsets) = left_key.as_utf8_contiguous()?;
6380    let (right_bytes, right_offsets) = right_key.as_utf8_contiguous()?;
6381    let left_n = left_offsets.len() - 1;
6382    let right_n = right_offsets.len() - 1;
6383
6384    let left_map = collect_contiguous_utf8_position_map(left_bytes, left_offsets);
6385    let right_map = collect_contiguous_utf8_position_map(right_bytes, right_offsets);
6386    let mut seen = FxHashSet::<&[u8]>::with_capacity_and_hasher(
6387        left_map.len() + right_map.len(),
6388        Default::default(),
6389    );
6390    let mut keys = Vec::<&[u8]>::with_capacity(left_map.len() + right_map.len());
6391    for pos in 0..left_n {
6392        let span = &left_bytes[left_offsets[pos]..left_offsets[pos + 1]];
6393        if seen.insert(span) {
6394            keys.push(span);
6395        }
6396    }
6397    for pos in 0..right_n {
6398        let span = &right_bytes[right_offsets[pos]..right_offsets[pos + 1]];
6399        if seen.insert(span) {
6400            keys.push(span);
6401        }
6402    }
6403    keys.sort_unstable();
6404
6405    let mut out_len = 0usize;
6406    for &key in &keys {
6407        out_len += match (left_map.get(key), right_map.get(key)) {
6408            (Some(lefts), Some(rights)) => lefts.len() * rights.len(),
6409            (Some(lefts), None) => lefts.len(),
6410            (None, Some(rights)) => rights.len(),
6411            (None, None) => 0,
6412        };
6413    }
6414
6415    let mut left_positions = Vec::<Option<usize>>::with_capacity(out_len);
6416    let mut right_positions = Vec::<Option<usize>>::with_capacity(out_len);
6417    for key in keys {
6418        match (left_map.get(key), right_map.get(key)) {
6419            (Some(lefts), Some(rights)) => {
6420                for &left_pos in lefts {
6421                    for &right_pos in rights {
6422                        left_positions.push(Some(left_pos));
6423                        right_positions.push(Some(right_pos));
6424                    }
6425                }
6426            }
6427            (Some(lefts), None) => {
6428                for &left_pos in lefts {
6429                    left_positions.push(Some(left_pos));
6430                    right_positions.push(None);
6431                }
6432            }
6433            (None, Some(rights)) => {
6434                for &right_pos in rights {
6435                    left_positions.push(None);
6436                    right_positions.push(Some(right_pos));
6437                }
6438            }
6439            (None, None) => {}
6440        }
6441    }
6442    Some((left_positions, right_positions))
6443}
6444
6445fn hash_i64_inner_positions_slices(left: &[i64], right: &[i64]) -> (Vec<usize>, Vec<usize>) {
6446    if right.is_empty() || left.is_empty() {
6447        return (Vec::new(), Vec::new());
6448    }
6449
6450    let mut right_map = FxHashMap::<i64, JoinPositionBucket>::with_capacity_and_hasher(
6451        right.len(),
6452        Default::default(),
6453    );
6454    for (pos, &key) in right.iter().enumerate() {
6455        right_map.entry(key).or_default().push(pos);
6456    }
6457
6458    let mut left_positions = Vec::<usize>::with_capacity(left.len().min(right.len()));
6459    let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
6460    for (left_pos, &key) in left.iter().enumerate() {
6461        if let Some(matches) = right_map.get(&key) {
6462            for &right_pos in matches {
6463                left_positions.push(left_pos);
6464                right_positions.push(right_pos);
6465            }
6466        }
6467    }
6468    (left_positions, right_positions)
6469}
6470
6471/// Hash-free inner-join positions for a MULTI-column key whose every component
6472/// is an all-valid, bounded-range Int64 column. Packs each row's composite key
6473/// into a single `i64` via a mixed-radix code over the per-column spans
6474/// (`packed = Σ_c (val_c - min_c) · stride_c`, `stride_0 = 1`, `stride_c =
6475/// stride_{c-1}·range_{c-1}`), then runs the dense CSR core on the packed keys.
6476///
6477/// The packing is a bijection on the joint key box (mins/ranges computed over
6478/// BOTH sides so left- and right-side codes are comparable), so two composite
6479/// keys collide under packing IFF every component is equal — identical to the
6480/// `CompositeJoinKey` equality the FxHashMap path uses. Pair order is therefore
6481/// byte-for-byte the same as the hash path. Returns `None` (caller falls back to
6482/// the composite-hash path) for any non-Int64 / any-missing component or when
6483/// the packed span exceeds the bounded direct-address gate.
6484fn dense_packed_int64_inner_positions(
6485    left_cols: &[&Column],
6486    right_cols: &[&Column],
6487) -> Option<(Vec<usize>, Vec<usize>)> {
6488    let k = left_cols.len();
6489    if k == 0 || k != right_cols.len() {
6490        return None;
6491    }
6492
6493    let left_slices: Vec<&[i64]> = left_cols
6494        .iter()
6495        .map(|c| c.as_i64_slice())
6496        .collect::<Option<Vec<_>>>()?;
6497    let right_slices: Vec<&[i64]> = right_cols
6498        .iter()
6499        .map(|c| c.as_i64_slice())
6500        .collect::<Option<Vec<_>>>()?;
6501
6502    let n_left = left_slices[0].len();
6503    let n_right = right_slices[0].len();
6504    if n_left == 0 || n_right == 0 {
6505        return Some((Vec::new(), Vec::new()));
6506    }
6507
6508    // Per-column min and span over BOTH sides; product = joint packed span.
6509    let mut mins = vec![0i64; k];
6510    let mut strides = vec![1i128; k];
6511    let mut total: i128 = 1;
6512    for c in 0..k {
6513        let mut mn = right_slices[c][0];
6514        let mut mx = right_slices[c][0];
6515        for &v in left_slices[c].iter().chain(right_slices[c].iter()) {
6516            if v < mn {
6517                mn = v;
6518            }
6519            if v > mx {
6520                mx = v;
6521            }
6522        }
6523        mins[c] = mn;
6524        let range = (mx as i128) - (mn as i128) + 1;
6525        strides[c] = total;
6526        total = total.checked_mul(range)?;
6527        // Gate the packed span the same way the single-key core does, up front
6528        // (the product can overflow the bounded table for wide multi-keys).
6529        if total > (1i128 << 24) {
6530            return None;
6531        }
6532    }
6533    if total > 16 * ((n_left + n_right) as i128) {
6534        return None;
6535    }
6536
6537    let pack = |slices: &[&[i64]], n: usize| -> Vec<i64> {
6538        (0..n)
6539            .map(|row| {
6540                let mut acc: i128 = 0;
6541                for c in 0..k {
6542                    acc += ((slices[c][row] as i128) - (mins[c] as i128)) * strides[c];
6543                }
6544                acc as i64
6545            })
6546            .collect()
6547    };
6548    let packed_left = pack(&left_slices, n_left);
6549    let packed_right = pack(&right_slices, n_right);
6550
6551    dense_i64_inner_positions_slices(&packed_left, &packed_right)
6552}
6553
6554fn merge_single_key_inner_unsorted(
6555    left: &fp_frame::DataFrame,
6556    right: &fp_frame::DataFrame,
6557    left_on: &[&str],
6558    right_on: &[&str],
6559    left_key_columns: &[&Column],
6560    right_key_columns: &[&Column],
6561    suffixes: &ResolvedMergeSuffixes,
6562) -> Result<MergedDataFrame, JoinError> {
6563    debug_assert_eq!(left_key_columns.len(), 1);
6564    debug_assert_eq!(right_key_columns.len(), 1);
6565
6566    if left_on[0] == right_on[0]
6567        && ordered_identity_int64_keys_match(left_key_columns[0], right_key_columns[0])
6568    {
6569        return build_single_key_ordered_identity_inner_merge_output(
6570            left, right, left_on, right_on, suffixes,
6571        );
6572    }
6573    if let Some((left_positions, right_positions)) =
6574        ordered_unique_int64_inner_positions(left_key_columns[0], right_key_columns[0])
6575    {
6576        return build_single_key_inner_merge_output(
6577            left,
6578            right,
6579            left_on,
6580            right_on,
6581            &left_positions,
6582            &right_positions,
6583            suffixes,
6584        );
6585    }
6586
6587    if let Some(merged) = build_single_key_dense_i64_inner_merge_output(
6588        left,
6589        right,
6590        left_on,
6591        right_on,
6592        left_key_columns[0],
6593        right_key_columns[0],
6594        FusedInt64MergeOptions {
6595            suffixes,
6596            require_all_left_keys_matched: false,
6597        },
6598    )? {
6599        return Ok(merged);
6600    }
6601
6602    // Hash-free dense direct-address build+probe for bounded all-valid Int64
6603    // keys (the common low-cardinality join-key shape). Bit-identical pairs.
6604    if let Some((left_positions, right_positions)) =
6605        dense_int64_inner_positions(left_key_columns[0], right_key_columns[0])
6606    {
6607        return build_single_key_inner_merge_output(
6608            left,
6609            right,
6610            left_on,
6611            right_on,
6612            &left_positions,
6613            &right_positions,
6614            suffixes,
6615        );
6616    }
6617    if let Some((left_positions, right_positions)) =
6618        hash_int64_inner_positions(left_key_columns[0], right_key_columns[0])
6619    {
6620        return build_single_key_inner_merge_output(
6621            left,
6622            right,
6623            left_on,
6624            right_on,
6625            &left_positions,
6626            &right_positions,
6627            suffixes,
6628        );
6629    }
6630
6631    if let Some(position_plan) =
6632        ordered_unique_utf8_inner_position_plan(left_key_columns[0], right_key_columns[0])
6633    {
6634        return match position_plan {
6635            InnerPositionPlan::Gather {
6636                left_positions,
6637                right_positions,
6638            } => build_single_key_inner_merge_output(
6639                left,
6640                right,
6641                left_on,
6642                right_on,
6643                &left_positions,
6644                &right_positions,
6645                suffixes,
6646            ),
6647            InnerPositionPlan::ContiguousRanges {
6648                left_start,
6649                right_start,
6650                len,
6651            } => build_single_key_inner_merge_output_with_selections(
6652                left,
6653                right,
6654                left_on,
6655                right_on,
6656                PositionSelection::ContiguousRange {
6657                    start: left_start,
6658                    len,
6659                },
6660                PositionSelection::ContiguousRange {
6661                    start: right_start,
6662                    len,
6663                },
6664                suffixes,
6665            ),
6666        };
6667    }
6668
6669    // Byte-span build+probe for all-valid contiguous-Utf8 string keys
6670    // (br-frankenpandas-i388q): skips the per-row String clone + Scalar
6671    // materialization of the JoinKeyComponent path. Same pairing -> same output.
6672    if let Some((left_positions, right_positions)) =
6673        contiguous_utf8_inner_positions(left_key_columns[0], right_key_columns[0])
6674    {
6675        return build_single_key_inner_merge_output(
6676            left,
6677            right,
6678            left_on,
6679            right_on,
6680            &left_positions,
6681            &right_positions,
6682            suffixes,
6683        );
6684    }
6685
6686    let left_keys = collect_single_join_keys(left_key_columns[0]);
6687    let right_keys = collect_single_join_keys(right_key_columns[0]);
6688    let mut right_map =
6689        FxHashMap::<&JoinKeyComponent, JoinPositionBucket>::with_capacity_and_hasher(
6690            right_keys.len(),
6691            Default::default(),
6692        );
6693    for (pos, key) in right_keys.iter().enumerate() {
6694        right_map.entry(key).or_default().push(pos);
6695    }
6696
6697    let mut left_positions = Vec::<usize>::with_capacity(left_keys.len().min(right_keys.len()));
6698    let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
6699    for (left_pos, key) in left_keys.iter().enumerate() {
6700        if let Some(matches) = right_map.get(key) {
6701            for &right_pos in matches {
6702                left_positions.push(left_pos);
6703                right_positions.push(right_pos);
6704            }
6705        }
6706    }
6707
6708    build_single_key_inner_merge_output(
6709        left,
6710        right,
6711        left_on,
6712        right_on,
6713        &left_positions,
6714        &right_positions,
6715        suffixes,
6716    )
6717}
6718
6719/// Merge two DataFrames on one or more key columns.
6720///
6721/// Matches `pd.merge(left, right, left_on=left_keys, right_on=right_keys, how=join_type)`.
6722/// - Key columns are used for matching rows (hash join).
6723/// - Non-key columns are carried through and reindexed.
6724/// - Column name conflicts use configurable suffixes (default `_x`/`_y`).
6725/// - The output index is auto-generated (0..n RangeIndex-style).
6726pub fn merge_dataframes_on_with(
6727    left: &fp_frame::DataFrame,
6728    right: &fp_frame::DataFrame,
6729    left_on: &[&str],
6730    right_on: &[&str],
6731    join_type: JoinType,
6732) -> Result<MergedDataFrame, JoinError> {
6733    merge_dataframes_on_with_options(
6734        left,
6735        right,
6736        left_on,
6737        right_on,
6738        join_type,
6739        MergeExecutionOptions::default(),
6740    )
6741}
6742
6743/// Merge two DataFrames on one or more key columns with execution options.
6744pub fn merge_dataframes_on_with_options(
6745    left: &fp_frame::DataFrame,
6746    right: &fp_frame::DataFrame,
6747    left_on: &[&str],
6748    right_on: &[&str],
6749    join_type: JoinType,
6750    options: MergeExecutionOptions,
6751) -> Result<MergedDataFrame, JoinError> {
6752    let MergeExecutionOptions {
6753        indicator_name,
6754        validate_mode,
6755        suffixes,
6756        sort,
6757    } = options;
6758    let indicator_name = resolve_merge_indicator_name(indicator_name.as_deref())?;
6759    let suffixes = resolve_merge_suffixes(suffixes);
6760
6761    if matches!(join_type, JoinType::Cross) {
6762        if let Some(validate_mode) = validate_mode
6763            && !matches!(validate_mode, MergeValidateMode::ManyToMany)
6764        {
6765            return Err(JoinError::Frame(FrameError::CompatibilityRejected(
6766                format!(
6767                    "merge validate='{}' is not supported for cross join",
6768                    validate_mode.as_str()
6769                ),
6770            )));
6771        }
6772        return merge_dataframes_cross(left, right, indicator_name.as_deref(), &suffixes);
6773    }
6774
6775    if left_on.is_empty() || right_on.is_empty() {
6776        return Err(JoinError::Frame(FrameError::CompatibilityRejected(
6777            "merge requires at least one key column".to_owned(),
6778        )));
6779    }
6780    if left_on.len() != right_on.len() {
6781        return Err(JoinError::Frame(FrameError::CompatibilityRejected(
6782            "merge requires left_on and right_on key lists with equal length".to_owned(),
6783        )));
6784    }
6785
6786    let mut seen_left_keys = HashSet::new();
6787    for key_name in left_on {
6788        if !seen_left_keys.insert(*key_name) {
6789            return Err(JoinError::Frame(FrameError::CompatibilityRejected(
6790                format!("merge left key column '{key_name}' is duplicated"),
6791            )));
6792        }
6793    }
6794    let mut seen_right_keys = HashSet::new();
6795    for key_name in right_on {
6796        if !seen_right_keys.insert(*key_name) {
6797            return Err(JoinError::Frame(FrameError::CompatibilityRejected(
6798                format!("merge right key column '{key_name}' is duplicated"),
6799            )));
6800        }
6801    }
6802
6803    let left_key_columns = collect_join_key_columns(left, left_on, "left")?;
6804    let right_key_columns = collect_join_key_columns(right, right_on, "right")?;
6805    let validate_allows_fast_positions = validate_mode_allows_fast_positions(validate_mode);
6806
6807    if matches!(join_type, JoinType::Inner)
6808        && left_on.len() == 1
6809        && right_on.len() == 1
6810        && !sort
6811        && indicator_name.is_none()
6812        && validate_allows_fast_positions
6813    {
6814        return merge_single_key_inner_unsorted(
6815            left,
6816            right,
6817            left_on,
6818            right_on,
6819            &left_key_columns,
6820            &right_key_columns,
6821            &suffixes,
6822        );
6823    }
6824    if matches!(join_type, JoinType::Left)
6825        && left_on.len() == 1
6826        && right_on.len() == 1
6827        && !sort
6828        && indicator_name.is_none()
6829        && validate_allows_fast_positions
6830        && let Some(right_positions) =
6831            ordered_unique_int64_left_match_positions(left_key_columns[0], right_key_columns[0])
6832    {
6833        return build_single_key_ordered_unique_left_merge_output(
6834            left,
6835            right,
6836            left_on,
6837            right_on,
6838            &right_positions,
6839            &suffixes,
6840        );
6841    }
6842    if matches!(join_type, JoinType::Left)
6843        && left_on.len() == 1
6844        && right_on.len() == 1
6845        && !sort
6846        && indicator_name.is_none()
6847        && validate_allows_fast_positions
6848        && let Some(merged) = build_single_key_dense_cycle_i64_left_merge_output(
6849            left,
6850            right,
6851            left_on,
6852            right_on,
6853            left_key_columns[0],
6854            right_key_columns[0],
6855            &suffixes,
6856        )?
6857    {
6858        return Ok(merged);
6859    }
6860    if matches!(join_type, JoinType::Left)
6861        && left_on.len() == 1
6862        && right_on.len() == 1
6863        && !sort
6864        && indicator_name.is_none()
6865        && validate_allows_fast_positions
6866        && let Some(merged) = build_single_key_dense_i64_inner_merge_output(
6867            left,
6868            right,
6869            left_on,
6870            right_on,
6871            left_key_columns[0],
6872            right_key_columns[0],
6873            FusedInt64MergeOptions {
6874                suffixes: &suffixes,
6875                require_all_left_keys_matched: true,
6876            },
6877        )?
6878    {
6879        return Ok(merged);
6880    }
6881    if matches!(join_type, JoinType::Left)
6882        && left_on.len() == 1
6883        && right_on.len() == 1
6884        && !sort
6885        && indicator_name.is_none()
6886        && validate_allows_fast_positions
6887        && let Some(merged) = build_single_key_dense_i64_left_merge_output(
6888            left,
6889            right,
6890            left_on,
6891            right_on,
6892            left_key_columns[0],
6893            right_key_columns[0],
6894            &suffixes,
6895        )?
6896    {
6897        return Ok(merged);
6898    }
6899    if matches!(join_type, JoinType::Left)
6900        && left_on.len() == 1
6901        && right_on.len() == 1
6902        && !sort
6903        && indicator_name.is_none()
6904        && validate_allows_fast_positions
6905        && let Some((left_positions, right_positions)) =
6906            dense_int64_left_positions(left_key_columns[0], right_key_columns[0])
6907    {
6908        return build_single_key_dense_left_merge_output(
6909            left,
6910            right,
6911            left_on,
6912            right_on,
6913            &left_positions,
6914            &right_positions,
6915            &suffixes,
6916        );
6917    }
6918    if matches!(join_type, JoinType::Left)
6919        && left_on.len() == 1
6920        && right_on.len() == 1
6921        && !sort
6922        && indicator_name.is_none()
6923        && validate_allows_fast_positions
6924        && let Some((left_positions, right_positions)) =
6925            contiguous_utf8_left_positions(left_key_columns[0], right_key_columns[0])
6926    {
6927        return build_single_key_dense_left_merge_output(
6928            left,
6929            right,
6930            left_on,
6931            right_on,
6932            &left_positions,
6933            &right_positions,
6934            &suffixes,
6935        );
6936    }
6937    if matches!(join_type, JoinType::Right)
6938        && left_on.len() == 1
6939        && right_on.len() == 1
6940        && !sort
6941        && indicator_name.is_none()
6942        && validate_allows_fast_positions
6943        && let Some(left_positions) =
6944            ordered_unique_int64_right_match_positions(left_key_columns[0], right_key_columns[0])
6945    {
6946        return build_single_key_ordered_unique_right_merge_output(
6947            left,
6948            right,
6949            left_on,
6950            right_on,
6951            &left_positions,
6952            &suffixes,
6953        );
6954    }
6955    if matches!(join_type, JoinType::Right)
6956        && left_on.len() == 1
6957        && right_on.len() == 1
6958        && !sort
6959        && indicator_name.is_none()
6960        && validate_allows_fast_positions
6961        && let Some(merged) = build_single_key_dense_i64_right_all_matched_merge_output(
6962            left,
6963            right,
6964            left_on,
6965            right_on,
6966            left_key_columns[0],
6967            right_key_columns[0],
6968            &suffixes,
6969        )?
6970    {
6971        return Ok(merged);
6972    }
6973    if matches!(join_type, JoinType::Right)
6974        && left_on.len() == 1
6975        && right_on.len() == 1
6976        && !sort
6977        && indicator_name.is_none()
6978        && validate_allows_fast_positions
6979        && let Some(merged) = build_single_key_dense_i64_right_merge_output(
6980            left,
6981            right,
6982            left_on,
6983            right_on,
6984            left_key_columns[0],
6985            right_key_columns[0],
6986            &suffixes,
6987        )?
6988    {
6989        return Ok(merged);
6990    }
6991    if matches!(join_type, JoinType::Right)
6992        && left_on.len() == 1
6993        && right_on.len() == 1
6994        && !sort
6995        && indicator_name.is_none()
6996        && validate_allows_fast_positions
6997        && let Some((left_positions, right_positions)) =
6998            dense_int64_right_positions(left_key_columns[0], right_key_columns[0])
6999    {
7000        return build_single_key_dense_right_merge_output(
7001            left,
7002            right,
7003            left_on,
7004            right_on,
7005            &left_positions,
7006            &right_positions,
7007            &suffixes,
7008        );
7009    }
7010    if matches!(join_type, JoinType::Outer)
7011        && left_on.len() == 1
7012        && right_on.len() == 1
7013        && !sort
7014        && indicator_name.is_none()
7015        && validate_allows_fast_positions
7016        && let Some((left_positions, right_positions)) =
7017            ordered_unique_int64_outer_positions(left_key_columns[0], right_key_columns[0])
7018    {
7019        return build_single_key_ordered_unique_outer_merge_output(
7020            left,
7021            right,
7022            left_on,
7023            right_on,
7024            &left_positions,
7025            &right_positions,
7026            &suffixes,
7027        );
7028    }
7029    if matches!(join_type, JoinType::Outer)
7030        && left_on.len() == 1
7031        && right_on.len() == 1
7032        && !sort
7033        && indicator_name.is_none()
7034        && validate_allows_fast_positions
7035        && let Some(merged) = build_single_key_dense_i64_outer_all_matched_merge_output(
7036            left,
7037            right,
7038            left_on,
7039            right_on,
7040            left_key_columns[0],
7041            right_key_columns[0],
7042            &suffixes,
7043        )?
7044    {
7045        return Ok(merged);
7046    }
7047    if matches!(join_type, JoinType::Outer)
7048        && left_on.len() == 1
7049        && right_on.len() == 1
7050        && !sort
7051        && indicator_name.is_none()
7052        && validate_allows_fast_positions
7053        && let Some(merged) = build_single_key_dense_i64_outer_merge_output(
7054            left,
7055            right,
7056            left_on,
7057            right_on,
7058            left_key_columns[0],
7059            right_key_columns[0],
7060            &suffixes,
7061        )?
7062    {
7063        return Ok(merged);
7064    }
7065    if matches!(join_type, JoinType::Outer)
7066        && left_on.len() == 1
7067        && right_on.len() == 1
7068        && !sort
7069        && indicator_name.is_none()
7070        && validate_allows_fast_positions
7071        && let Some((left_positions, right_positions)) =
7072            dense_int64_outer_positions(left_key_columns[0], right_key_columns[0])
7073    {
7074        return build_single_key_ordered_unique_outer_merge_output(
7075            left,
7076            right,
7077            left_on,
7078            right_on,
7079            &left_positions,
7080            &right_positions,
7081            &suffixes,
7082        );
7083    }
7084    if matches!(join_type, JoinType::Outer)
7085        && left_on.len() == 1
7086        && right_on.len() == 1
7087        && !sort
7088        && indicator_name.is_none()
7089        && validate_allows_fast_positions
7090        && let Some((left_positions, right_positions)) =
7091            contiguous_utf8_outer_positions(left_key_columns[0], right_key_columns[0])
7092    {
7093        return build_single_key_ordered_unique_outer_merge_output(
7094            left,
7095            right,
7096            left_on,
7097            right_on,
7098            &left_positions,
7099            &right_positions,
7100            &suffixes,
7101        );
7102    }
7103
7104    let needs_key_order = sort || matches!(join_type, JoinType::Outer);
7105
7106    // Hash-free fast path: a plain inner join on all-valid bounded-Int64 key
7107    // column(s) packs the composite key into one i64 and runs the dense CSR
7108    // core, skipping CompositeJoinKey materialization + FxHashMap build/probe.
7109    // Gated to inner joins with no sort/indicator/enforcing validate, where the
7110    // emitted (left,right) pairs are byte-for-byte identical to the hash path.
7111    let packed_inner = if matches!(join_type, JoinType::Inner)
7112        && !sort
7113        && validate_allows_fast_positions
7114        && indicator_name.is_none()
7115    {
7116        dense_packed_int64_inner_positions(&left_key_columns, &right_key_columns)
7117    } else {
7118        None
7119    };
7120
7121    let (mut left_positions, mut right_positions, out_row_keys): MergeRowPositions =
7122        if let Some((lp, rp)) = packed_inner {
7123            (
7124                lp.into_iter().map(Some).collect(),
7125                rp.into_iter().map(Some).collect(),
7126                None,
7127            )
7128        } else {
7129            // Convert key columns to hashable composite keys.
7130            let left_keys = collect_composite_keys(&left_key_columns);
7131            let right_keys = collect_composite_keys(&right_key_columns);
7132            if let Some(validate_mode) = validate_mode {
7133                validate_merge_cardinality(validate_mode, &left_keys, &right_keys)?;
7134            }
7135
7136            // Build only the probe maps required by the selected join direction.
7137            let right_map = if matches!(
7138                join_type,
7139                JoinType::Inner | JoinType::Left | JoinType::Outer
7140            ) {
7141                let mut m =
7142                    FxHashMap::<&CompositeJoinKey, JoinPositionBucket>::with_capacity_and_hasher(
7143                        right_keys.len(),
7144                        Default::default(),
7145                    );
7146                for (pos, key) in right_keys.iter().enumerate() {
7147                    m.entry(key).or_default().push(pos);
7148                }
7149                Some(m)
7150            } else {
7151                None
7152            };
7153
7154            let left_map = if matches!(join_type, JoinType::Right | JoinType::Outer) {
7155                let mut m =
7156                    FxHashMap::<&CompositeJoinKey, JoinPositionBucket>::with_capacity_and_hasher(
7157                        left_keys.len(),
7158                        Default::default(),
7159                    );
7160                for (pos, key) in left_keys.iter().enumerate() {
7161                    m.entry(key).or_default().push(pos);
7162                }
7163                Some(m)
7164            } else {
7165                None
7166            };
7167
7168            // Compute row position mappings.
7169            let row_capacity = match join_type {
7170                JoinType::Inner => left_keys.len().min(right_keys.len()),
7171                JoinType::Left => left_keys.len(),
7172                JoinType::Right => right_keys.len(),
7173                JoinType::Outer => left_keys.len().saturating_add(right_keys.len()),
7174                JoinType::Cross => left_keys.len().saturating_mul(right_keys.len()),
7175            };
7176            let mut left_positions = Vec::<Option<usize>>::with_capacity(row_capacity);
7177            let mut right_positions = Vec::<Option<usize>>::with_capacity(row_capacity);
7178            let mut out_row_keys =
7179                needs_key_order.then(|| Vec::<CompositeJoinKey>::with_capacity(row_capacity));
7180
7181            match join_type {
7182                JoinType::Inner | JoinType::Left | JoinType::Outer => {
7183                    let right_map = right_map
7184                        .as_ref()
7185                        .expect("right_map required for Inner, Left, and Outer joins");
7186                    for (left_pos, key) in left_keys.iter().enumerate() {
7187                        if let Some(matches) = right_map.get(key) {
7188                            for &right_pos in matches {
7189                                push_merge_row_key(&mut out_row_keys, key);
7190                                left_positions.push(Some(left_pos));
7191                                right_positions.push(Some(right_pos));
7192                            }
7193                            continue;
7194                        }
7195
7196                        if matches!(join_type, JoinType::Left | JoinType::Outer) {
7197                            push_merge_row_key(&mut out_row_keys, key);
7198                            left_positions.push(Some(left_pos));
7199                            right_positions.push(None);
7200                        }
7201                    }
7202
7203                    if matches!(join_type, JoinType::Outer) {
7204                        let left_map = left_map.as_ref().expect("left_map required for Outer join");
7205                        for (right_pos, key) in right_keys.iter().enumerate() {
7206                            if !left_map.contains_key(key) {
7207                                push_merge_row_key(&mut out_row_keys, key);
7208                                left_positions.push(None);
7209                                right_positions.push(Some(right_pos));
7210                            }
7211                        }
7212                    }
7213                }
7214                JoinType::Right => {
7215                    let left_map = left_map.as_ref().expect("left_map required for Right join");
7216                    for (right_pos, key) in right_keys.iter().enumerate() {
7217                        if let Some(matches) = left_map.get(key) {
7218                            for &left_pos in matches {
7219                                push_merge_row_key(&mut out_row_keys, key);
7220                                left_positions.push(Some(left_pos));
7221                                right_positions.push(Some(right_pos));
7222                            }
7223                            continue;
7224                        }
7225
7226                        push_merge_row_key(&mut out_row_keys, key);
7227                        left_positions.push(None);
7228                        right_positions.push(Some(right_pos));
7229                    }
7230                }
7231                JoinType::Cross => {
7232                    return Err(JoinError::Frame(FrameError::CompatibilityRejected(
7233                        "cross join must be handled by merge_dataframes_cross".to_owned(),
7234                    )));
7235                }
7236            }
7237
7238            (left_positions, right_positions, out_row_keys)
7239        };
7240
7241    if needs_key_order {
7242        let out_row_keys = out_row_keys
7243            .as_ref()
7244            .expect("merge row keys required when sorting output rows");
7245        sort_merge_rows_by_join_keys(out_row_keys, &mut left_positions, &mut right_positions);
7246    }
7247
7248    let all_positions_present = matches!(join_type, JoinType::Inner)
7249        || (matches!(
7250            join_type,
7251            JoinType::Left | JoinType::Right | JoinType::Outer
7252        ) && left_positions.iter().all(Option::is_some)
7253            && right_positions.iter().all(Option::is_some));
7254    let all_present_take_positions = all_positions_present.then(|| {
7255        let left = left_positions
7256            .iter()
7257            .map(|position| position.expect("all-present join emits left positions for every row"))
7258            .collect::<Vec<_>>();
7259        let right = right_positions
7260            .iter()
7261            .map(|position| position.expect("all-present join emits right positions for every row"))
7262            .collect::<Vec<_>>();
7263        (left, right)
7264    });
7265    let all_present_left_positions = all_present_take_positions
7266        .as_ref()
7267        .map(|(positions, _)| positions.as_slice());
7268    let all_present_right_positions = all_present_take_positions
7269        .as_ref()
7270        .map(|(_, positions)| positions.as_slice());
7271
7272    // Build output columns by reindexing.
7273    let n = left_positions.len();
7274    // Lazy unit-range output index (see build_single_key_dense_i64 site).
7275    let index = Index::new_known_unique_int64_unit_range(0, n);
7276    let mut columns = std::collections::BTreeMap::new();
7277    let mut column_order: Vec<String> = Vec::new();
7278
7279    // Collect column names to handle conflicts.
7280    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
7281    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
7282    let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
7283    let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
7284
7285    // Track positional pairs where left_on[i] and right_on[i] share the same key name.
7286    let mut shared_name_positions = HashMap::<&str, (usize, usize)>::new();
7287    for (idx, (left_key_name, right_key_name)) in left_on.iter().zip(right_on.iter()).enumerate() {
7288        if left_key_name == right_key_name {
7289            shared_name_positions.insert(*left_key_name, (idx, idx));
7290        }
7291    }
7292    let shared_key_names = shared_name_positions
7293        .keys()
7294        .copied()
7295        .collect::<HashSet<&str>>();
7296    let overlapping_names =
7297        collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
7298    ensure_merge_suffixes_for_overlaps(&overlapping_names, &suffixes)?;
7299
7300    // Add left columns (including left key columns) in the left frame's own
7301    // column order (pandas preserves it; the BTreeMap would re-sort) — br-691lh.
7302    for name in left.column_names() {
7303        let col = left
7304            .columns()
7305            .get(name)
7306            .expect("left column listed in column_names must exist");
7307        if left_key_name_set.contains(name.as_str()) {
7308            if let Some((left_key_idx, right_key_idx)) = shared_name_positions.get(name.as_str()) {
7309                // Shared key name: for rows emitted from right-only keys, source key values from
7310                // the right frame instead of leaving them null.
7311                let left_key_col = left_key_columns[*left_key_idx];
7312                let key_column = if let Some(positions) = all_present_left_positions {
7313                    take_positions_typed(left_key_col, positions)
7314                } else {
7315                    let right_key_col = right_key_columns[*right_key_idx];
7316                    let values = left_positions
7317                        .iter()
7318                        .zip(right_positions.iter())
7319                        .map(|(left_pos, right_pos)| match (left_pos, right_pos) {
7320                            (Some(pos), _) => left_key_col.values()[*pos].clone(),
7321                            (None, Some(pos)) => right_key_col.values()[*pos].clone(),
7322                            (None, None) => fp_types::Scalar::Null(fp_types::NullKind::Null),
7323                        })
7324                        .collect::<Vec<_>>();
7325                    Column::from_values(values)?
7326                };
7327                insert_merged_output_column(
7328                    &mut columns,
7329                    &mut column_order,
7330                    name.clone(),
7331                    key_column,
7332                )?;
7333            } else {
7334                let key_column = if let Some(positions) = all_present_left_positions {
7335                    take_positions_typed(col, positions)
7336                } else if matches!(join_type, JoinType::Outer) {
7337                    reindex_outer_join_column(col, &left_positions)?
7338                } else {
7339                    col.reindex_by_positions(&left_positions)?
7340                };
7341                insert_merged_output_column(
7342                    &mut columns,
7343                    &mut column_order,
7344                    name.clone(),
7345                    key_column,
7346                )?;
7347            }
7348            continue;
7349        }
7350        let reindexed = if let Some(positions) = all_present_left_positions {
7351            take_positions_typed(col, positions)
7352        } else if matches!(join_type, JoinType::Outer) {
7353            reindex_outer_join_column(col, &left_positions)?
7354        } else {
7355            col.reindex_by_positions(&left_positions)?
7356        };
7357        let out_name = if right_col_names.contains(name) {
7358            apply_merge_suffix(name, suffixes.left.as_deref())
7359        } else {
7360            name.clone()
7361        };
7362        insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
7363    }
7364
7365    // Add right non-key columns in the right frame's own column order — br-691lh.
7366    for name in right.column_names() {
7367        let col = right
7368            .columns()
7369            .get(name)
7370            .expect("right column listed in column_names must exist");
7371        if right_key_name_set.contains(name.as_str())
7372            && shared_name_positions.contains_key(name.as_str())
7373        {
7374            // Shared same-name key already emitted from the left side.
7375            continue;
7376        }
7377        let reindexed = if let Some(positions) = all_present_right_positions {
7378            take_positions_typed(col, positions)
7379        } else if matches!(join_type, JoinType::Outer) {
7380            reindex_outer_join_column(col, &right_positions)?
7381        } else {
7382            col.reindex_by_positions(&right_positions)?
7383        };
7384        let out_name = if left_col_names.contains(name) {
7385            apply_merge_suffix(name, suffixes.right.as_deref())
7386        } else {
7387            name.clone()
7388        };
7389        insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
7390    }
7391
7392    if let Some(indicator_name) = indicator_name.as_deref() {
7393        ensure_indicator_name_available(
7394            indicator_name,
7395            &left_col_names,
7396            &right_col_names,
7397            &columns,
7398        )?;
7399        let indicator_col = build_merge_indicator_column(&left_positions, &right_positions)?;
7400        insert_merged_output_column(
7401            &mut columns,
7402            &mut column_order,
7403            indicator_name.to_owned(),
7404            indicator_col,
7405        )?;
7406    }
7407
7408    Ok(MergedDataFrame {
7409        index,
7410        columns,
7411        column_order,
7412    })
7413}
7414
7415/// Merge two DataFrames on one or more key columns with identical key names.
7416///
7417/// Matches `pd.merge(left, right, on=keys, how=join_type)`.
7418pub fn merge_dataframes_on(
7419    left: &fp_frame::DataFrame,
7420    right: &fp_frame::DataFrame,
7421    on: &[&str],
7422    join_type: JoinType,
7423) -> Result<MergedDataFrame, JoinError> {
7424    merge_dataframes_on_with(left, right, on, on, join_type)
7425}
7426
7427/// Merge two DataFrames on a single key column.
7428pub fn merge_dataframes(
7429    left: &fp_frame::DataFrame,
7430    right: &fp_frame::DataFrame,
7431    on: &str,
7432    join_type: JoinType,
7433) -> Result<MergedDataFrame, JoinError> {
7434    if matches!(join_type, JoinType::Inner) {
7435        let left_key = left.column(on).ok_or_else(|| {
7436            JoinError::Frame(FrameError::CompatibilityRejected(format!(
7437                "left DataFrame missing key column '{on}'"
7438            )))
7439        })?;
7440        let right_key = right.column(on).ok_or_else(|| {
7441            JoinError::Frame(FrameError::CompatibilityRejected(format!(
7442                "right DataFrame missing key column '{on}'"
7443            )))
7444        })?;
7445        let suffixes = ResolvedMergeSuffixes::default();
7446        return merge_single_key_inner_unsorted(
7447            left,
7448            right,
7449            &[on],
7450            &[on],
7451            &[left_key],
7452            &[right_key],
7453            &suffixes,
7454        );
7455    }
7456    merge_dataframes_on(left, right, &[on], join_type)
7457}
7458
7459fn merge_dataframes_cross(
7460    left: &fp_frame::DataFrame,
7461    right: &fp_frame::DataFrame,
7462    indicator_name: Option<&str>,
7463    suffixes: &ResolvedMergeSuffixes,
7464) -> Result<MergedDataFrame, JoinError> {
7465    let left_rows = left.index().len();
7466    let right_rows = right.index().len();
7467    let out_rows = left_rows.saturating_mul(right_rows);
7468
7469    let mut left_positions = Vec::<Option<usize>>::with_capacity(out_rows);
7470    let mut right_positions = Vec::<Option<usize>>::with_capacity(out_rows);
7471    for left_pos in 0..left_rows {
7472        for right_pos in 0..right_rows {
7473            left_positions.push(Some(left_pos));
7474            right_positions.push(Some(right_pos));
7475        }
7476    }
7477
7478    let index = Index::new((0..out_rows as i64).map(IndexLabel::from).collect());
7479    let mut columns = std::collections::BTreeMap::new();
7480    let mut column_order: Vec<String> = Vec::new();
7481
7482    let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
7483    let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
7484    let overlapping_names =
7485        collect_overlapping_column_names(&left_col_names, &right_col_names, &HashSet::new());
7486    ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
7487
7488    for (name, col) in left.columns() {
7489        let reindexed = col.reindex_by_positions(&left_positions)?;
7490        let out_name = if right_col_names.contains(name) {
7491            apply_merge_suffix(name, suffixes.left.as_deref())
7492        } else {
7493            name.clone()
7494        };
7495        insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
7496    }
7497
7498    for (name, col) in right.columns() {
7499        let reindexed = col.reindex_by_positions(&right_positions)?;
7500        let out_name = if left_col_names.contains(name) {
7501            apply_merge_suffix(name, suffixes.right.as_deref())
7502        } else {
7503            name.clone()
7504        };
7505        insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
7506    }
7507
7508    if let Some(indicator_name) = indicator_name {
7509        ensure_indicator_name_available(
7510            indicator_name,
7511            &left_col_names,
7512            &right_col_names,
7513            &columns,
7514        )?;
7515        let indicator_col = build_merge_indicator_column(&left_positions, &right_positions)?;
7516        insert_merged_output_column(
7517            &mut columns,
7518            &mut column_order,
7519            indicator_name.to_owned(),
7520            indicator_col,
7521        )?;
7522    }
7523
7524    Ok(MergedDataFrame {
7525        index,
7526        columns,
7527        column_order,
7528    })
7529}
7530
7531/// Extension trait adding `.merge()` and `.join()` instance methods to `DataFrame`.
7532///
7533/// Import this trait to get pandas-style `df.merge(other, ...)` and `df.join(other, ...)`
7534/// as instance methods.
7535pub trait DataFrameMergeExt {
7536    /// Merge this DataFrame with another on shared key columns.
7537    ///
7538    /// Matches `pd.DataFrame.merge(other, on=keys, how=join_type)`.
7539    fn merge(
7540        &self,
7541        other: &fp_frame::DataFrame,
7542        on: &[&str],
7543        how: JoinType,
7544    ) -> Result<MergedDataFrame, JoinError>;
7545
7546    /// Merge with separate left/right key columns and execution options.
7547    ///
7548    /// Matches `pd.DataFrame.merge(other, left_on=..., right_on=..., how=...)`.
7549    fn merge_with_options(
7550        &self,
7551        other: &fp_frame::DataFrame,
7552        left_on: &[&str],
7553        right_on: &[&str],
7554        how: JoinType,
7555        options: MergeExecutionOptions,
7556    ) -> Result<MergedDataFrame, JoinError>;
7557
7558    /// Join another DataFrame on the index.
7559    ///
7560    /// Matches `pd.DataFrame.join(other, how=join_type)` (index-based join).
7561    fn join_on_index(
7562        &self,
7563        other: &fp_frame::DataFrame,
7564        how: JoinType,
7565    ) -> Result<MergedDataFrame, JoinError>;
7566
7567    /// pandas-named alias for [`Self::join_on_index`]. Matches
7568    /// `pd.DataFrame.join(other, how=...)` directly. Per br-frankenpandas-nk54a.
7569    ///
7570    /// Default impl delegates to `join_on_index`. Implementors that already
7571    /// have an optimized index-based join can leave this default.
7572    fn join(
7573        &self,
7574        other: &fp_frame::DataFrame,
7575        how: JoinType,
7576    ) -> Result<MergedDataFrame, JoinError> {
7577        self.join_on_index(other, how)
7578    }
7579
7580    /// Perform an asof merge (nearest-match join) on a sorted key column.
7581    ///
7582    /// Matches `pd.merge_asof(left, right, on=key)`. Both DataFrames must
7583    /// be sorted by the key column. For each row in `left`, finds the last
7584    /// row in `right` where `right[on] <= left[on]` (backward direction)
7585    /// or the nearest row in the specified direction.
7586    ///
7587    /// `direction`: "backward" (default), "forward", "nearest".
7588    fn merge_asof(
7589        &self,
7590        other: &fp_frame::DataFrame,
7591        on: &str,
7592        direction: &str,
7593    ) -> Result<MergedDataFrame, JoinError>;
7594
7595    /// Perform an asof merge with additional options.
7596    ///
7597    /// Matches `pd.merge_asof(left, right, on=key, direction=...,
7598    /// allow_exact_matches=..., tolerance=..., by=...)`.
7599    ///
7600    /// # Parameters
7601    /// - `other`: Right DataFrame to merge with
7602    /// - `on`: Column name to merge on (must be numeric and sorted)
7603    /// - `direction`: "backward", "forward", or "nearest"
7604    /// - `options`: Additional options (allow_exact_matches, tolerance, by)
7605    fn merge_asof_with_options(
7606        &self,
7607        other: &fp_frame::DataFrame,
7608        on: &str,
7609        direction: &str,
7610        options: MergeAsofOptions,
7611    ) -> Result<MergedDataFrame, JoinError>;
7612
7613    /// Perform an ordered merge (outer join + sort by keys).
7614    ///
7615    /// Matches `pd.merge_ordered(left, right, on=keys, fill_method=...)`.
7616    fn merge_ordered(
7617        &self,
7618        other: &fp_frame::DataFrame,
7619        on: &[&str],
7620        fill_method: Option<&str>,
7621    ) -> Result<MergedDataFrame, JoinError>;
7622}
7623
7624/// Perform an ordered merge of two DataFrames.
7625///
7626/// Matches `pd.merge_ordered(left, right, on=keys, fill_method=...)`.
7627/// Performs an outer join and ensures the result is sorted by the join keys.
7628pub fn merge_ordered(
7629    left: &fp_frame::DataFrame,
7630    right: &fp_frame::DataFrame,
7631    on: &[&str],
7632    fill_method: Option<&str>,
7633) -> Result<MergedDataFrame, JoinError> {
7634    let options = MergeExecutionOptions {
7635        sort: true,
7636        ..MergeExecutionOptions::default()
7637    };
7638    let merged = merge_dataframes_on_with_options(left, right, on, on, JoinType::Outer, options)?;
7639
7640    if let Some(method) = fill_method {
7641        // Convert to DataFrame to apply fill
7642        let mut df = fp_frame::DataFrame::new_with_column_order(
7643            merged.index.clone(),
7644            merged.columns.clone(),
7645            merged.column_order.clone(),
7646        )
7647        .map_err(JoinError::Frame)?;
7648
7649        df = match method {
7650            "ffill" => df.ffill(None).map_err(JoinError::Frame)?,
7651            _ => {
7652                return Err(JoinError::Frame(FrameError::CompatibilityRejected(
7653                    format!("merge_ordered: fill_method must be 'ffill' or None, got '{method}'"),
7654                )));
7655            }
7656        };
7657
7658        let column_order = df.column_names().into_iter().cloned().collect();
7659        Ok(MergedDataFrame {
7660            index: df.index().clone(),
7661            columns: df.columns().clone(),
7662            column_order,
7663        })
7664    } else {
7665        Ok(merged)
7666    }
7667}
7668
7669/// Direction for asof merge matching.
7670#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7671pub enum AsofDirection {
7672    Backward,
7673    Forward,
7674    Nearest,
7675}
7676
7677/// Options for asof merge operations.
7678///
7679/// Matches pandas `merge_asof` parameters:
7680/// - `allow_exact_matches`: If true (default), allow matching with same key value
7681/// - `tolerance`: Maximum distance between keys for a match
7682/// - `by`: Columns to match exactly before asof matching
7683#[derive(Debug, Clone, Default)]
7684pub struct MergeAsofOptions {
7685    /// If true (default), allow matching with the same 'on' value.
7686    /// If false, don't match rows where left key == right key exactly.
7687    pub allow_exact_matches: bool,
7688    /// Maximum distance between left and right keys for a valid match.
7689    /// None means no tolerance limit.
7690    pub tolerance: Option<f64>,
7691    /// Columns to match exactly before performing asof merge.
7692    /// Acts like an equi-join on these columns first.
7693    pub by: Option<Vec<String>>,
7694}
7695
7696impl MergeAsofOptions {
7697    /// Create options with defaults matching pandas behavior.
7698    pub fn new() -> Self {
7699        Self {
7700            allow_exact_matches: true,
7701            tolerance: None,
7702            by: None,
7703        }
7704    }
7705
7706    /// Set whether exact matches are allowed.
7707    pub fn allow_exact_matches(mut self, allow: bool) -> Self {
7708        self.allow_exact_matches = allow;
7709        self
7710    }
7711
7712    /// Set the tolerance for matching.
7713    pub fn tolerance(mut self, tol: f64) -> Self {
7714        self.tolerance = Some(tol);
7715        self
7716    }
7717
7718    /// Set the columns to match exactly before asof merge.
7719    pub fn by(mut self, cols: Vec<String>) -> Self {
7720        self.by = Some(cols);
7721        self
7722    }
7723}
7724
7725fn asof_numeric_values(column: &Column, side: &str, on: &str) -> Result<Vec<f64>, JoinError> {
7726    let mut out = Vec::with_capacity(column.len());
7727    for value in column.values() {
7728        // pandas merge_asof accepts Timedelta64 (and datetime) `on` columns
7729        // and orders them by ns count. Scalar::Timedelta64.to_f64() returns
7730        // NonNumericValue, so the default branch would reject the join.
7731        // Extract ns directly for non-NaT Timedelta values; treat NaT as NaN
7732        // (matches the ValueIsMissing arm below).
7733        if let Scalar::Timedelta64(ns) = value {
7734            if *ns == fp_types::Timedelta::NAT {
7735                out.push(f64::NAN);
7736            } else {
7737                out.push(*ns as f64);
7738            }
7739            continue;
7740        }
7741        match value.to_f64() {
7742            Ok(v) => out.push(v),
7743            Err(TypeError::ValueIsMissing { .. }) => out.push(f64::NAN),
7744            Err(_) => {
7745                return Err(JoinError::Frame(FrameError::CompatibilityRejected(
7746                    format!("merge_asof: {side} column '{on}' must be numeric"),
7747                )));
7748            }
7749        }
7750    }
7751    Ok(out)
7752}
7753
7754fn ensure_sorted_non_decreasing(values: &[f64], side: &str, on: &str) -> Result<(), JoinError> {
7755    let mut prev: Option<f64> = None;
7756    for &value in values {
7757        if value.is_nan() {
7758            continue;
7759        }
7760        if let Some(prev_value) = prev
7761            && value < prev_value
7762        {
7763            return Err(JoinError::Frame(FrameError::CompatibilityRejected(
7764                format!("merge_asof: {side} column '{on}' must be sorted"),
7765            )));
7766        }
7767        prev = Some(value);
7768    }
7769    Ok(())
7770}
7771
7772/// Perform an asof merge between two DataFrames.
7773pub fn merge_asof(
7774    left: &fp_frame::DataFrame,
7775    right: &fp_frame::DataFrame,
7776    on: &str,
7777    direction: AsofDirection,
7778) -> Result<MergedDataFrame, JoinError> {
7779    merge_asof_with_options(left, right, on, direction, MergeAsofOptions::new())
7780}
7781
7782/// Perform an asof merge between two DataFrames with additional options.
7783///
7784/// # Parameters
7785/// - `left`: Left DataFrame
7786/// - `right`: Right DataFrame
7787/// - `on`: Column name to merge on (must be numeric and sorted)
7788/// - `direction`: Match direction (Backward, Forward, Nearest)
7789/// - `options`: Additional merge options (allow_exact_matches, tolerance, by)
7790pub fn merge_asof_with_options(
7791    left: &fp_frame::DataFrame,
7792    right: &fp_frame::DataFrame,
7793    on: &str,
7794    direction: AsofDirection,
7795    options: MergeAsofOptions,
7796) -> Result<MergedDataFrame, JoinError> {
7797    // If `by` columns are specified, we need to do grouped asof merge
7798    if let Some(ref by_cols) = options.by {
7799        return merge_asof_grouped(left, right, on, direction, &options, by_cols);
7800    }
7801
7802    merge_asof_simple(left, right, on, direction, &options)
7803}
7804
7805/// Simple asof merge without grouping.
7806fn merge_asof_simple(
7807    left: &fp_frame::DataFrame,
7808    right: &fp_frame::DataFrame,
7809    on: &str,
7810    direction: AsofDirection,
7811    options: &MergeAsofOptions,
7812) -> Result<MergedDataFrame, JoinError> {
7813    let left_key = left.columns().get(on).ok_or_else(|| {
7814        JoinError::Frame(FrameError::CompatibilityRejected(format!(
7815            "merge_asof: column '{on}' not found in left"
7816        )))
7817    })?;
7818    let right_key = right.columns().get(on).ok_or_else(|| {
7819        JoinError::Frame(FrameError::CompatibilityRejected(format!(
7820            "merge_asof: column '{on}' not found in right"
7821        )))
7822    })?;
7823
7824    let left_vals = asof_numeric_values(left_key, "left", on)?;
7825    let right_vals = asof_numeric_values(right_key, "right", on)?;
7826
7827    // pandas pd.merge_asof accepts NaN keys: the NaN row gets a null in
7828    // the joined columns (no match). The strict "reject null keys" check
7829    // previously enforced here diverged from the FP-P2D-056 oracle.
7830    ensure_sorted_non_decreasing(&left_vals, "left", on)?;
7831    ensure_sorted_non_decreasing(&right_vals, "right", on)?;
7832
7833    let right_matches = compute_asof_matches(
7834        &left_vals,
7835        &right_vals,
7836        direction,
7837        options.allow_exact_matches,
7838        options.tolerance,
7839    );
7840
7841    build_asof_output(left, right, on, &right_matches, None)
7842}
7843
7844/// Grouped asof merge: match on `by` columns first, then asof within groups.
7845fn merge_asof_grouped(
7846    left: &fp_frame::DataFrame,
7847    right: &fp_frame::DataFrame,
7848    on: &str,
7849    direction: AsofDirection,
7850    options: &MergeAsofOptions,
7851    by_cols: &[String],
7852) -> Result<MergedDataFrame, JoinError> {
7853    // Validate by columns exist
7854    for col in by_cols {
7855        if left.columns().get(col).is_none() {
7856            return Err(JoinError::Frame(FrameError::CompatibilityRejected(
7857                format!("merge_asof: 'by' column '{col}' not found in left"),
7858            )));
7859        }
7860        if right.columns().get(col).is_none() {
7861            return Err(JoinError::Frame(FrameError::CompatibilityRejected(
7862                format!("merge_asof: 'by' column '{col}' not found in right"),
7863            )));
7864        }
7865    }
7866
7867    let left_key = left.columns().get(on).ok_or_else(|| {
7868        JoinError::Frame(FrameError::CompatibilityRejected(format!(
7869            "merge_asof: column '{on}' not found in left"
7870        )))
7871    })?;
7872    let right_key = right.columns().get(on).ok_or_else(|| {
7873        JoinError::Frame(FrameError::CompatibilityRejected(format!(
7874            "merge_asof: column '{on}' not found in right"
7875        )))
7876    })?;
7877
7878    let left_vals = asof_numeric_values(left_key, "left", on)?;
7879    let right_vals = asof_numeric_values(right_key, "right", on)?;
7880
7881    // pandas pd.merge_asof accepts NaN keys: the NaN row gets a null in
7882    // the joined columns (no match). The strict "reject null keys" check
7883    // previously enforced here diverged from the FP-P2D-056 oracle.
7884    ensure_sorted_non_decreasing(&left_vals, "left", on)?;
7885    ensure_sorted_non_decreasing(&right_vals, "right", on)?;
7886
7887    // Dense u32 group ids over the `by` columns (shared id space for left and
7888    // right). The single non-float `by` column case factorizes the column's
7889    // scalars with a borrowed typed key — no per-row `format!`/`Vec<String>`
7890    // allocation — and is bit-identical to the Debug-string grouping (see
7891    // `build_group_ids`). Everything else falls back to the string path.
7892    let (left_ids, right_ids) = build_group_ids(left, right, by_cols)?;
7893
7894    // Group right rows by their `by` group id for asof matching (looked up by
7895    // `.get()` per left group below). No per-group sort validation is needed:
7896    // the global `ensure_sorted_non_decreasing` checks above already require the
7897    // `on` column to be non-decreasing over the whole frame, and every
7898    // per-group subsequence of a sorted column is itself sorted — so the old
7899    // per-group checks were unreachable (the global check fires first on any
7900    // unsorted input). FxHashMap (vs std SipHash) speeds the build.
7901    let mut right_groups: FxHashMap<u32, Vec<usize>> = FxHashMap::default();
7902    for (idx, &id) in right_ids.iter().enumerate() {
7903        right_groups.entry(id).or_default().push(idx);
7904    }
7905
7906    // Group LEFT rows by their `by` group id (preserving the globally-sorted
7907    // order within each group), then run the monotonic two-pointer asof sweep
7908    // ONCE per group over all of the group's left values — instead of rebuilding
7909    // the group's right-value vector and re-scanning it from scratch for every
7910    // individual left row (the old O(L·R) per group). compute_asof_matches
7911    // already drives a single left array with a monotonic cursor and handles
7912    // NaN left keys (→ None, cursor unchanged); because every per-group left
7913    // subsequence is sorted (the global `on` column is non-decreasing), the
7914    // grouped sweep yields the identical match for each left row as the old
7915    // fresh-per-row scan. Results are scattered by absolute left index, so the
7916    // output order is independent of group-iteration order.
7917    let mut left_groups: FxHashMap<u32, Vec<usize>> = FxHashMap::default();
7918    for (left_idx, &id) in left_ids.iter().enumerate() {
7919        left_groups.entry(id).or_default().push(left_idx);
7920    }
7921
7922    let mut right_matches: Vec<Option<usize>> = vec![None; left_vals.len()];
7923    for (group_id, left_positions) in &left_groups {
7924        let Some(group_indices) = right_groups.get(group_id) else {
7925            continue; // no right rows for this group -> all matches stay None
7926        };
7927        let group_right_vals: Vec<f64> = group_indices.iter().map(|&i| right_vals[i]).collect();
7928        let group_left_vals: Vec<f64> = left_positions.iter().map(|&i| left_vals[i]).collect();
7929
7930        let group_matches = compute_asof_matches(
7931            &group_left_vals,
7932            &group_right_vals,
7933            direction,
7934            options.allow_exact_matches,
7935            options.tolerance,
7936        );
7937
7938        for (k, &left_idx) in left_positions.iter().enumerate() {
7939            if let Some(Some(group_idx)) = group_matches.get(k) {
7940                right_matches[left_idx] = Some(group_indices[*group_idx]);
7941            }
7942        }
7943    }
7944
7945    build_asof_output(left, right, on, &right_matches, Some(by_cols))
7946}
7947
7948/// Borrowed, allocation-free `by`-key for the single-column factorize fast
7949/// path. Each variant is the typed payload of a `Scalar` whose *derived*
7950/// `Debug` is injective and equality-consistent — so two scalars share a
7951/// `ByKey` iff their `format!("{val:?}")` strings (the legacy group key) are
7952/// equal. `Float64` (`-0.0` vs `0.0`, `NaN`) and `Interval` Debug strings
7953/// disagree with value equality, so `from_scalar` returns `None` for them and
7954/// the caller falls back to the string path.
7955#[derive(PartialEq, Eq, Hash)]
7956enum ByKey<'a> {
7957    Null(u8),
7958    Bool(bool),
7959    Int(i64),
7960    Str(&'a str),
7961    Timedelta(i64),
7962    Datetime(i64),
7963    Period(i64),
7964}
7965
7966impl<'a> ByKey<'a> {
7967    fn from_scalar(s: &'a Scalar) -> Option<Self> {
7968        Some(match s {
7969            Scalar::Null(NullKind::Null) => ByKey::Null(0),
7970            Scalar::Null(NullKind::NaN) => ByKey::Null(1),
7971            Scalar::Null(NullKind::NaT) => ByKey::Null(2),
7972            Scalar::Bool(b) => ByKey::Bool(*b),
7973            Scalar::Int64(v) => ByKey::Int(*v),
7974            Scalar::Utf8(s) => ByKey::Str(s.as_str()),
7975            Scalar::Timedelta64(v) => ByKey::Timedelta(*v),
7976            Scalar::Datetime64(v) => ByKey::Datetime(*v),
7977            Scalar::Period(v) => ByKey::Period(v.ordinal),
7978            Scalar::Float64(_) | Scalar::Interval(_) => return None,
7979        })
7980    }
7981}
7982
7983/// Factorize a single `by` column over both frames into a shared u32 id space.
7984/// Returns `None` (caller falls back to the string path) if any value is a
7985/// `Float64`/`Interval` whose Debug string would not agree with typed equality.
7986fn try_factorize_typed<'a>(
7987    left: &'a [Scalar],
7988    right: &'a [Scalar],
7989) -> Option<(Vec<u32>, Vec<u32>)> {
7990    let mut codes: FxHashMap<ByKey<'a>, u32> = FxHashMap::default();
7991    let mut next = 0u32;
7992    let mut left_ids = Vec::with_capacity(left.len());
7993    for v in left {
7994        let id = *codes.entry(ByKey::from_scalar(v)?).or_insert_with(|| {
7995            let i = next;
7996            next += 1;
7997            i
7998        });
7999        left_ids.push(id);
8000    }
8001    let mut right_ids = Vec::with_capacity(right.len());
8002    for v in right {
8003        let id = *codes.entry(ByKey::from_scalar(v)?).or_insert_with(|| {
8004            let i = next;
8005            next += 1;
8006            i
8007        });
8008        right_ids.push(id);
8009    }
8010    Some((left_ids, right_ids))
8011}
8012
8013/// Build dense u32 group ids for the left and right frames over the `by`
8014/// columns, sharing one id space. Returns `(left_ids, right_ids)`.
8015///
8016/// Fast path (a single non-float `by` column): factorize the column's scalars
8017/// directly with the borrowed typed [`ByKey`] — zero per-row string formatting
8018/// or allocation. Bit-identical to the `format!("{val:?}")` grouping because
8019/// the typed key induces the exact same equality classes. Multi-column or
8020/// float/interval `by` keys route to the original Debug-string builder, whose
8021/// per-row composite keys are then interned to u32 (one clone per *distinct*
8022/// group, not per row).
8023fn build_group_ids(
8024    left: &fp_frame::DataFrame,
8025    right: &fp_frame::DataFrame,
8026    by_cols: &[String],
8027) -> Result<(Vec<u32>, Vec<u32>), JoinError> {
8028    if by_cols.len() == 1
8029        && let (Some(lcol), Some(rcol)) = (
8030            left.columns().get(&by_cols[0]),
8031            right.columns().get(&by_cols[0]),
8032        )
8033        && let Some(ids) = try_factorize_typed(lcol.values(), rcol.values())
8034    {
8035        return Ok(ids);
8036    }
8037
8038    let left_keys = build_group_keys(left, by_cols)?;
8039    let right_keys = build_group_keys(right, by_cols)?;
8040    let mut codes: FxHashMap<Vec<String>, u32> = FxHashMap::default();
8041    let mut next = 0u32;
8042    let mut intern = |k: &Vec<String>, codes: &mut FxHashMap<Vec<String>, u32>| -> u32 {
8043        if let Some(&id) = codes.get(k) {
8044            id
8045        } else {
8046            let id = next;
8047            next += 1;
8048            codes.insert(k.clone(), id);
8049            id
8050        }
8051    };
8052    let left_ids = left_keys.iter().map(|k| intern(k, &mut codes)).collect();
8053    let right_ids = right_keys.iter().map(|k| intern(k, &mut codes)).collect();
8054    Ok((left_ids, right_ids))
8055}
8056
8057/// Build group keys from the `by` columns.
8058fn build_group_keys(
8059    df: &fp_frame::DataFrame,
8060    by_cols: &[String],
8061) -> Result<Vec<Vec<String>>, JoinError> {
8062    let n = df.len();
8063    let mut keys = vec![Vec::with_capacity(by_cols.len()); n];
8064
8065    for col_name in by_cols {
8066        let col = df.columns().get(col_name).ok_or_else(|| {
8067            JoinError::Frame(FrameError::CompatibilityRejected(format!(
8068                "merge_asof: column '{col_name}' not found"
8069            )))
8070        })?;
8071        for (i, val) in col.values().iter().enumerate() {
8072            keys[i].push(format!("{val:?}"));
8073        }
8074    }
8075
8076    Ok(keys)
8077}
8078
8079/// Compute asof matches for a single group or the whole dataset.
8080fn compute_asof_matches(
8081    left_vals: &[f64],
8082    right_vals: &[f64],
8083    direction: AsofDirection,
8084    allow_exact_matches: bool,
8085    tolerance: Option<f64>,
8086) -> Vec<Option<usize>> {
8087    let mut right_non_nan_values = Vec::new();
8088    let mut right_non_nan_positions = Vec::new();
8089    for (pos, &rv) in right_vals.iter().enumerate() {
8090        if !rv.is_nan() {
8091            right_non_nan_values.push(rv);
8092            right_non_nan_positions.push(pos);
8093        }
8094    }
8095
8096    let mut right_matches: Vec<Option<usize>> = Vec::with_capacity(left_vals.len());
8097
8098    match direction {
8099        AsofDirection::Backward => {
8100            let mut best: Option<usize> = None;
8101            let mut best_val: Option<f64> = None;
8102            let mut j = 0usize;
8103            for &lv in left_vals {
8104                if lv.is_nan() {
8105                    right_matches.push(None);
8106                    continue;
8107                }
8108                // Advance while right <= left (or right < left if !allow_exact_matches)
8109                while j < right_non_nan_values.len() {
8110                    let rv = right_non_nan_values[j];
8111                    let should_include = if allow_exact_matches {
8112                        rv <= lv
8113                    } else {
8114                        rv < lv
8115                    };
8116                    if !should_include {
8117                        break;
8118                    }
8119                    best = Some(right_non_nan_positions[j]);
8120                    best_val = Some(rv);
8121                    j += 1;
8122                }
8123
8124                // Check tolerance
8125                let matched = match (best, best_val, tolerance) {
8126                    (Some(idx), Some(rv), Some(tol)) if (lv - rv).abs() <= tol => Some(idx),
8127                    (Some(idx), _, None) => Some(idx),
8128                    _ => None,
8129                };
8130                right_matches.push(matched);
8131            }
8132        }
8133        AsofDirection::Forward => {
8134            let mut j = 0usize;
8135            for &lv in left_vals {
8136                if lv.is_nan() {
8137                    right_matches.push(None);
8138                    continue;
8139                }
8140                // Advance while right < left (or right <= left if !allow_exact_matches)
8141                while j < right_non_nan_values.len() {
8142                    let rv = right_non_nan_values[j];
8143                    let should_skip = if allow_exact_matches {
8144                        rv < lv
8145                    } else {
8146                        rv <= lv
8147                    };
8148                    if !should_skip {
8149                        break;
8150                    }
8151                    j += 1;
8152                }
8153
8154                if j < right_non_nan_values.len() {
8155                    let rv = right_non_nan_values[j];
8156                    // Check tolerance
8157                    let matched = match tolerance {
8158                        Some(tol) if (rv - lv).abs() <= tol => Some(right_non_nan_positions[j]),
8159                        None => Some(right_non_nan_positions[j]),
8160                        _ => None,
8161                    };
8162                    right_matches.push(matched);
8163                } else {
8164                    right_matches.push(None);
8165                }
8166            }
8167        }
8168        AsofDirection::Nearest => {
8169            for &lv in left_vals {
8170                if lv.is_nan() {
8171                    right_matches.push(None);
8172                    continue;
8173                }
8174                if right_non_nan_values.is_empty() {
8175                    right_matches.push(None);
8176                    continue;
8177                }
8178
8179                // For nearest, pick the closest neighbor on each side. The
8180                // candidate window depends on whether exact (equal) keys may
8181                // match:
8182                //   allow_exact:  lower = last value <= lv, upper = first value >= lv
8183                //   !allow_exact: lower = last value <  lv, upper = first value >  lv
8184                // Selecting the window up front (rather than excluding exact
8185                // matches after the fact) skips over runs of exact-equal keys
8186                // when they are disallowed, so a nearer non-equal key beyond
8187                // the run is still found — matching pandas merge_asof.
8188                let (lower, upper) = if allow_exact_matches {
8189                    let lo = right_non_nan_values.partition_point(|rv| *rv <= lv);
8190                    let up = right_non_nan_values.partition_point(|rv| *rv < lv);
8191                    (
8192                        if lo > 0 { Some(lo - 1) } else { None },
8193                        if up < right_non_nan_values.len() {
8194                            Some(up)
8195                        } else {
8196                            None
8197                        },
8198                    )
8199                } else {
8200                    let lo = right_non_nan_values.partition_point(|rv| *rv < lv);
8201                    let up = right_non_nan_values.partition_point(|rv| *rv <= lv);
8202                    (
8203                        if lo > 0 { Some(lo - 1) } else { None },
8204                        if up < right_non_nan_values.len() {
8205                            Some(up)
8206                        } else {
8207                            None
8208                        },
8209                    )
8210                };
8211
8212                let chosen = match (lower, upper) {
8213                    (Some(l), Some(u)) => {
8214                        let lower_dist = (right_non_nan_values[l] - lv).abs();
8215                        let upper_dist = (right_non_nan_values[u] - lv).abs();
8216                        // Ties go to the lower (backward) neighbor, like pandas.
8217                        if upper_dist < lower_dist {
8218                            Some(u)
8219                        } else {
8220                            Some(l)
8221                        }
8222                    }
8223                    (Some(l), None) => Some(l),
8224                    (None, Some(u)) => Some(u),
8225                    (None, None) => None,
8226                };
8227
8228                // Apply tolerance check
8229                let matched = match chosen {
8230                    Some(idx) => {
8231                        let rv = right_non_nan_values[idx];
8232                        match tolerance {
8233                            Some(tol) if (lv - rv).abs() <= tol => {
8234                                Some(right_non_nan_positions[idx])
8235                            }
8236                            None => Some(right_non_nan_positions[idx]),
8237                            _ => None,
8238                        }
8239                    }
8240                    None => None,
8241                };
8242                right_matches.push(matched);
8243            }
8244        }
8245    }
8246
8247    right_matches
8248}
8249
8250/// Build the output DataFrame from computed matches.
8251/// One output column of `build_asof_output`: left columns are present for every
8252/// row (clone), right columns are gathered by the asof match positions.
8253enum AsofOutputTask<'a> {
8254    LeftClone(&'a Column),
8255    RightGather(&'a Column),
8256}
8257
8258fn build_asof_output(
8259    left: &fp_frame::DataFrame,
8260    right: &fp_frame::DataFrame,
8261    on: &str,
8262    right_matches: &[Option<usize>],
8263    by_cols: Option<&[String]>,
8264) -> Result<MergedDataFrame, JoinError> {
8265    let right_n = right.len();
8266
8267    let left_col_names: Vec<String> = left.column_names().iter().map(|s| s.to_string()).collect();
8268    let right_col_names_all: Vec<String> =
8269        right.column_names().iter().map(|s| s.to_string()).collect();
8270
8271    // Exclude the `on` column and `by` columns from right output
8272    let excluded_cols: HashSet<&str> = {
8273        let mut s = HashSet::new();
8274        s.insert(on);
8275        if let Some(by) = by_cols {
8276            for c in by {
8277                s.insert(c.as_str());
8278            }
8279        }
8280        s
8281    };
8282
8283    let right_col_names: Vec<String> = right_col_names_all
8284        .iter()
8285        .filter(|c| !excluded_cols.contains(c.as_str()))
8286        .cloned()
8287        .collect();
8288
8289    let left_name_set: HashSet<&String> = left_col_names.iter().collect();
8290    let right_name_set: HashSet<&String> = right_col_names_all.iter().collect();
8291    let mut excluded_names = HashSet::new();
8292    excluded_names.insert(on);
8293    let overlap_names =
8294        collect_overlapping_column_names(&left_name_set, &right_name_set, &excluded_names);
8295    let overlap_set: HashSet<String> = overlap_names.iter().cloned().collect();
8296    let suffixes = ResolvedMergeSuffixes::default();
8297    ensure_merge_suffixes_for_overlaps(&overlap_names, &suffixes)?;
8298
8299    let n_out = left.len();
8300    let mut out_columns = std::collections::BTreeMap::new();
8301    let mut column_order: Vec<String> = Vec::new();
8302
8303    // Resolve every output column (name + build task) in order, then build the
8304    // columns — left columns clone all rows, right columns gather matched-or-null
8305    // values. Each output column is independent, so wide/large outputs build all
8306    // columns across a worker pool (br-frankenpandas-fu8f5; same disjoint-fill
8307    // pattern as the dense-i64/inner-merge builders). Bit-identical to the serial
8308    // loops: identical per-column result (left clone; right Scalar gather with
8309    // Null(NullKind::NaN) on unmatched, then Column::new with the source dtype),
8310    // inserted in the same order.
8311    let mut specs: Vec<(String, AsofOutputTask<'_>)> = Vec::new();
8312    for col_name in &left_col_names {
8313        let col = left.columns().get(col_name).ok_or_else(|| {
8314            JoinError::Frame(FrameError::CompatibilityRejected(format!(
8315                "merge_asof: left column '{col_name}' not found"
8316            )))
8317        })?;
8318        let output_name = if overlap_set.contains(col_name) {
8319            apply_merge_suffix(col_name, suffixes.left.as_deref())
8320        } else {
8321            col_name.clone()
8322        };
8323        specs.push((output_name, AsofOutputTask::LeftClone(col)));
8324    }
8325    for col_name in &right_col_names {
8326        let right_col = right.columns().get(col_name).ok_or_else(|| {
8327            JoinError::Frame(FrameError::CompatibilityRejected(format!(
8328                "merge_asof: right column '{col_name}' not found"
8329            )))
8330        })?;
8331        let output_name = if overlap_set.contains(col_name) {
8332            apply_merge_suffix(col_name, suffixes.right.as_deref())
8333        } else {
8334            col_name.clone()
8335        };
8336        specs.push((output_name, AsofOutputTask::RightGather(right_col)));
8337    }
8338
8339    let build_one = |task: &AsofOutputTask<'_>| -> Result<Column, ColumnError> {
8340        match task {
8341            AsofOutputTask::LeftClone(col) => Ok((*col).clone()),
8342            AsofOutputTask::RightGather(right_col) => {
8343                // Typed all-valid-Float64 gather (br-frankenpandas asof typed
8344                // output): an `as_f64_slice` source is all-valid, so it carries
8345                // NO NaN values (Float64 validity marks NaN invalid, and the
8346                // slice is gated on `validity.all()`). Gather matched data into a
8347                // contiguous f64 buffer + validity bitset instead of cloning a
8348                // 32 B Scalar per row and re-validating in Column::new. Bit-
8349                // identical to the Scalar path: a matched slot is a finite
8350                // `Float64(src[j])` (valid bit), an unmatched slot is
8351                // `Null(NullKind::NaN)` (cleared bit) — exactly what the Scalar
8352                // gather + Column::new produce, with no matched-NaN ambiguity
8353                // because the source has none.
8354                if let Some(src) = right_col.as_f64_slice() {
8355                    let mut data = Vec::with_capacity(n_out);
8356                    let mut validity = fp_columnar::ValidityMask::all_valid(n_out);
8357                    for (i, m) in right_matches.iter().enumerate() {
8358                        match m {
8359                            Some(j) if *j < right_n => data.push(src[*j]),
8360                            _ => {
8361                                // 0.0 datum + cleared bit is the gap convention:
8362                                // LazyNullableFloat64 materializes Null(NaN) only
8363                                // when the datum is NOT NaN, so an unmatched slot
8364                                // must use 0.0 (a NaN datum would materialize a
8365                                // present Float64(NaN) instead).
8366                                data.push(0.0);
8367                                validity.set(i, false);
8368                            }
8369                        }
8370                    }
8371                    return Ok(Column::from_f64_values_with_validity(data, validity));
8372                }
8373                let src = right_col.values();
8374                let mut vals = Vec::with_capacity(n_out);
8375                for m in right_matches {
8376                    match m {
8377                        Some(j) if *j < right_n => vals.push(src[*j].clone()),
8378                        _ => vals.push(fp_types::Scalar::Null(fp_types::NullKind::NaN)),
8379                    }
8380                }
8381                Column::new(right_col.dtype(), vals)
8382            }
8383        }
8384    };
8385
8386    let built: Vec<Result<Column, ColumnError>> = {
8387        let thread_count = join_parallel_thread_count();
8388        if specs.len() > 1 && n_out >= DENSE_I64_INNER_PARALLEL_MIN_VALUES && thread_count > 1 {
8389            let mut slots: Vec<Option<Result<Column, ColumnError>>> =
8390                (0..specs.len()).map(|_| None).collect();
8391            let chunk = specs.len().div_ceil(thread_count).max(1);
8392            let build_one = &build_one;
8393            std::thread::scope(|scope| {
8394                for (spec_chunk, slot_chunk) in specs.chunks(chunk).zip(slots.chunks_mut(chunk)) {
8395                    scope.spawn(move || {
8396                        for ((_, task), slot) in spec_chunk.iter().zip(slot_chunk) {
8397                            *slot = Some(build_one(task));
8398                        }
8399                    });
8400                }
8401            });
8402            slots
8403                .into_iter()
8404                .map(|c| c.expect("every asof output column must be built"))
8405                .collect()
8406        } else {
8407            specs.iter().map(|(_, task)| build_one(task)).collect()
8408        }
8409    };
8410
8411    for ((output_name, _), column) in specs.into_iter().zip(built) {
8412        insert_merged_output_column(&mut out_columns, &mut column_order, output_name, column?)?;
8413    }
8414
8415    Ok(MergedDataFrame {
8416        index: left.index().clone(),
8417        columns: out_columns,
8418        column_order,
8419    })
8420}
8421
8422impl DataFrameMergeExt for fp_frame::DataFrame {
8423    fn merge(
8424        &self,
8425        other: &fp_frame::DataFrame,
8426        on: &[&str],
8427        how: JoinType,
8428    ) -> Result<MergedDataFrame, JoinError> {
8429        merge_dataframes_on(self, other, on, how)
8430    }
8431
8432    fn merge_with_options(
8433        &self,
8434        other: &fp_frame::DataFrame,
8435        left_on: &[&str],
8436        right_on: &[&str],
8437        how: JoinType,
8438        options: MergeExecutionOptions,
8439    ) -> Result<MergedDataFrame, JoinError> {
8440        merge_dataframes_on_with_options(self, other, left_on, right_on, how, options)
8441    }
8442
8443    fn join_on_index(
8444        &self,
8445        other: &fp_frame::DataFrame,
8446        how: JoinType,
8447    ) -> Result<MergedDataFrame, JoinError> {
8448        let left = self.reset_index(false)?;
8449        let right = other.reset_index(false)?;
8450        merge_dataframes_on(&left, &right, &["index"], how)
8451    }
8452
8453    fn merge_asof(
8454        &self,
8455        other: &fp_frame::DataFrame,
8456        on: &str,
8457        direction: &str,
8458    ) -> Result<MergedDataFrame, JoinError> {
8459        self.merge_asof_with_options(other, on, direction, MergeAsofOptions::new())
8460    }
8461
8462    fn merge_asof_with_options(
8463        &self,
8464        other: &fp_frame::DataFrame,
8465        on: &str,
8466        direction: &str,
8467        options: MergeAsofOptions,
8468    ) -> Result<MergedDataFrame, JoinError> {
8469        let dir = match direction {
8470            "backward" => AsofDirection::Backward,
8471            "forward" => AsofDirection::Forward,
8472            "nearest" => AsofDirection::Nearest,
8473            _ => {
8474                return Err(JoinError::Frame(FrameError::CompatibilityRejected(
8475                    format!("merge_asof: invalid direction '{direction}'"),
8476                )));
8477            }
8478        };
8479        crate::merge_asof_with_options(self, other, on, dir, options)
8480    }
8481
8482    fn merge_ordered(
8483        &self,
8484        other: &fp_frame::DataFrame,
8485        on: &[&str],
8486        fill_method: Option<&str>,
8487    ) -> Result<MergedDataFrame, JoinError> {
8488        crate::merge_ordered(self, other, on, fill_method)
8489    }
8490}
8491
8492#[cfg(test)]
8493mod tests {
8494    use fp_columnar::Column;
8495    use fp_frame::Series;
8496    use fp_index::{Index, IndexLabel};
8497    use fp_types::{NullKind, Scalar};
8498
8499    use super::{
8500        DataFrameMergeExt, DenseI64InnerOutputPlan, DenseI64LaneData, FusedInt64OutputColumn,
8501        FusedInt64Side, InnerPositionPlan, JoinExecutionOptions, JoinType, PositionSelection,
8502        ResolvedMergeSuffixes, build_dense_i64_inner_output_data,
8503        build_single_key_dense_cycle_i64_left_merge_output,
8504        build_single_key_dense_i64_left_merge_output,
8505        build_single_key_dense_i64_right_merge_output, build_single_key_dense_left_merge_output,
8506        build_single_key_inner_contiguous_no_overlap_output, dense_int64_left_positions,
8507        join_series, join_series_with_options, join_series_with_trace,
8508        lower_hex_overlap_plan_from_certificates, ordered_unique_utf8_inner_position_plan,
8509        ordered_unique_utf8_inner_positions, ordered_utf8_lower_hex_overlap_len,
8510        strictly_increasing_utf8_key_spans, utf8_span_lower_bound,
8511    };
8512
8513    fn contiguous_utf8_column(values: &[&str]) -> Column {
8514        let mut bytes = Vec::new();
8515        let mut offsets = Vec::with_capacity(values.len() + 1);
8516        offsets.push(0);
8517        for value in values {
8518            bytes.extend_from_slice(value.as_bytes());
8519            offsets.push(bytes.len());
8520        }
8521        Column::from_utf8_contiguous(bytes, offsets)
8522    }
8523
8524    fn utf8_key_merge_frame(keys: &[&str], value_name: &str, base: i64) -> DataFrame {
8525        let index = Index::new(
8526            (0..keys.len())
8527                .map(|row| IndexLabel::Int64(row as i64))
8528                .collect(),
8529        );
8530        let mut columns = std::collections::BTreeMap::new();
8531        columns.insert("id".to_owned(), contiguous_utf8_column(keys));
8532        columns.insert(
8533            value_name.to_owned(),
8534            Column::from_i64_values((0..keys.len()).map(|row| base + row as i64).collect()),
8535        );
8536        DataFrame::new_with_column_order(
8537            index,
8538            columns,
8539            vec!["id".to_owned(), value_name.to_owned()],
8540        )
8541        .expect("utf8 key frame")
8542    }
8543
8544    #[test]
8545    fn inner_join_multiplies_cardinality_for_duplicates() {
8546        let left = Series::from_values(
8547            "left",
8548            vec!["k".into(), "k".into(), "x".into()],
8549            vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
8550        )
8551        .expect("left");
8552
8553        let right = Series::from_values(
8554            "right",
8555            vec!["k".into(), "k".into()],
8556            vec![Scalar::Int64(10), Scalar::Int64(20)],
8557        )
8558        .expect("right");
8559
8560        let out = join_series(&left, &right, JoinType::Inner).expect("join");
8561        assert_eq!(out.index.labels().len(), 4);
8562        assert_eq!(
8563            out.left_values.values(),
8564            &[
8565                Scalar::Int64(1),
8566                Scalar::Int64(1),
8567                Scalar::Int64(2),
8568                Scalar::Int64(2)
8569            ]
8570        );
8571    }
8572
8573    #[test]
8574    fn left_join_injects_missing_for_unmatched_right_rows() {
8575        let left = Series::from_values(
8576            "left",
8577            vec!["a".into(), "b".into()],
8578            vec![Scalar::Int64(1), Scalar::Int64(2)],
8579        )
8580        .expect("left");
8581        let right =
8582            Series::from_values("right", vec!["a".into()], vec![Scalar::Int64(10)]).expect("right");
8583
8584        let out = join_series(&left, &right, JoinType::Left).expect("join");
8585        assert_eq!(
8586            out.right_values.values(),
8587            &[Scalar::Int64(10), Scalar::Null(NullKind::Null)]
8588        );
8589    }
8590
8591    #[test]
8592    fn arena_join_matches_global_allocator_behavior() {
8593        let left = Series::from_values(
8594            "left",
8595            vec!["k".into(), "k".into(), "x".into()],
8596            vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
8597        )
8598        .expect("left");
8599
8600        let right = Series::from_values(
8601            "right",
8602            vec!["k".into(), "k".into()],
8603            vec![Scalar::Int64(10), Scalar::Int64(20)],
8604        )
8605        .expect("right");
8606
8607        let global = join_series_with_options(
8608            &left,
8609            &right,
8610            JoinType::Inner,
8611            JoinExecutionOptions {
8612                use_arena: false,
8613                arena_budget_bytes: 0,
8614            },
8615        )
8616        .expect("global join");
8617
8618        let arena = join_series_with_options(
8619            &left,
8620            &right,
8621            JoinType::Inner,
8622            JoinExecutionOptions::default(),
8623        )
8624        .expect("arena join");
8625
8626        assert_eq!(arena, global);
8627    }
8628
8629    #[test]
8630    fn arena_join_falls_back_when_budget_is_too_small() {
8631        let left = Series::from_values(
8632            "left",
8633            vec!["a".into(), "a".into(), "a".into()],
8634            vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
8635        )
8636        .expect("left");
8637        let right = Series::from_values(
8638            "right",
8639            vec!["a".into(), "a".into()],
8640            vec![Scalar::Int64(10), Scalar::Int64(20)],
8641        )
8642        .expect("right");
8643
8644        let options = JoinExecutionOptions {
8645            use_arena: true,
8646            arena_budget_bytes: 1,
8647        };
8648        let (fallback_out, trace) =
8649            join_series_with_trace(&left, &right, JoinType::Inner, options).expect("fallback join");
8650        let global_out = join_series_with_options(
8651            &left,
8652            &right,
8653            JoinType::Inner,
8654            JoinExecutionOptions {
8655                use_arena: false,
8656                arena_budget_bytes: 0,
8657            },
8658        )
8659        .expect("global join");
8660
8661        assert_eq!(fallback_out, global_out);
8662        assert!(!trace.used_arena);
8663        assert!(trace.estimated_bytes > options.arena_budget_bytes);
8664    }
8665
8666    #[test]
8667    fn arena_join_is_stable_across_many_small_operations() {
8668        let left = Series::from_values(
8669            "left",
8670            vec!["a".into(), "b".into()],
8671            vec![Scalar::Int64(1), Scalar::Int64(2)],
8672        )
8673        .expect("left");
8674        let right = Series::from_values(
8675            "right",
8676            vec!["a".into(), "b".into()],
8677            vec![Scalar::Int64(10), Scalar::Int64(20)],
8678        )
8679        .expect("right");
8680
8681        let options = JoinExecutionOptions::default();
8682        for _ in 0..1_000 {
8683            let out = join_series_with_options(&left, &right, JoinType::Inner, options)
8684                .expect("arena join");
8685            assert_eq!(out.index.labels().len(), 2);
8686            assert_eq!(
8687                out.right_values.values(),
8688                &[Scalar::Int64(10), Scalar::Int64(20)]
8689            );
8690        }
8691    }
8692
8693    /// AG-06-T test #8: 100K-row inner join with arena -> correct output, no OOM.
8694    #[test]
8695    fn arena_large_join_100k_rows() {
8696        let n = 100_000;
8697        let labels: Vec<IndexLabel> = (0..n).map(|i| IndexLabel::Int64(i as i64 % 1000)).collect();
8698        let values: Vec<Scalar> = (0..n).map(|i| Scalar::Int64(i as i64)).collect();
8699
8700        let left = Series::from_values("left", labels.clone(), values.clone()).expect("left");
8701        let right = Series::from_values("right", labels, values).expect("right");
8702
8703        let out = join_series_with_options(
8704            &left,
8705            &right,
8706            JoinType::Inner,
8707            JoinExecutionOptions::default(),
8708        )
8709        .expect("100K arena join");
8710
8711        // With 1000 distinct keys, each appearing 100 times on each side,
8712        // inner join produces 100 * 100 * 1000 = 10M rows.
8713        // But that's too large; use a budget that forces fallback.
8714        let out_fallback = join_series_with_options(
8715            &left,
8716            &right,
8717            JoinType::Inner,
8718            JoinExecutionOptions {
8719                use_arena: true,
8720                arena_budget_bytes: 1,
8721            },
8722        )
8723        .expect("100K fallback join");
8724
8725        assert_eq!(out.index.labels().len(), out_fallback.index.labels().len());
8726    }
8727
8728    #[test]
8729    fn right_join_contains_all_right_labels() {
8730        let left = Series::from_values(
8731            "left",
8732            vec!["a".into(), "b".into()],
8733            vec![Scalar::Int64(1), Scalar::Int64(2)],
8734        )
8735        .expect("left");
8736        let right = Series::from_values(
8737            "right",
8738            vec!["b".into(), "c".into()],
8739            vec![Scalar::Int64(20), Scalar::Int64(30)],
8740        )
8741        .expect("right");
8742
8743        let out = join_series(&left, &right, JoinType::Right).expect("join");
8744        // Right join: all right labels preserved. "b" matches, "c" unmatched.
8745        assert_eq!(out.index.labels().len(), 2);
8746        assert_eq!(
8747            out.index.labels(),
8748            &[IndexLabel::Utf8("b".into()), IndexLabel::Utf8("c".into())]
8749        );
8750        // "b" matched -> left=2, right=20. "c" unmatched -> left=Null, right=30.
8751        assert_eq!(
8752            out.left_values.values(),
8753            &[Scalar::Int64(2), Scalar::Null(NullKind::Null)]
8754        );
8755        assert_eq!(
8756            out.right_values.values(),
8757            &[Scalar::Int64(20), Scalar::Int64(30)]
8758        );
8759    }
8760
8761    #[test]
8762    fn right_join_multiplies_cardinality_for_duplicates() {
8763        let left = Series::from_values(
8764            "left",
8765            vec!["k".into(), "k".into()],
8766            vec![Scalar::Int64(1), Scalar::Int64(2)],
8767        )
8768        .expect("left");
8769        let right = Series::from_values(
8770            "right",
8771            vec!["k".into(), "x".into()],
8772            vec![Scalar::Int64(10), Scalar::Int64(30)],
8773        )
8774        .expect("right");
8775
8776        let out = join_series(&left, &right, JoinType::Right).expect("join");
8777        // "k" in right matches 2 left rows -> 2 output rows for "k", plus 1 for "x" unmatched.
8778        assert_eq!(out.index.labels().len(), 3);
8779        assert_eq!(
8780            out.right_values.values(),
8781            &[Scalar::Int64(10), Scalar::Int64(10), Scalar::Int64(30)]
8782        );
8783    }
8784
8785    #[test]
8786    fn outer_join_contains_all_labels_from_both_sides() {
8787        let left = Series::from_values(
8788            "left",
8789            vec!["a".into(), "b".into()],
8790            vec![Scalar::Int64(1), Scalar::Int64(2)],
8791        )
8792        .expect("left");
8793        let right = Series::from_values(
8794            "right",
8795            vec!["b".into(), "c".into()],
8796            vec![Scalar::Int64(20), Scalar::Int64(30)],
8797        )
8798        .expect("right");
8799
8800        let out = join_series(&left, &right, JoinType::Outer).expect("join");
8801        // Outer: "a" (left only), "b" (both), "c" (right only) -> 3 rows
8802        assert_eq!(out.index.labels().len(), 3);
8803        assert_eq!(
8804            out.left_values.values(),
8805            &[
8806                Scalar::Float64(1.0),
8807                Scalar::Float64(2.0),
8808                Scalar::Null(NullKind::NaN)
8809            ]
8810        );
8811        assert_eq!(
8812            out.right_values.values(),
8813            &[
8814                Scalar::Null(NullKind::NaN),
8815                Scalar::Float64(20.0),
8816                Scalar::Float64(30.0)
8817            ]
8818        );
8819    }
8820
8821    #[test]
8822    fn outer_join_sorts_union_labels_like_pandas() {
8823        let left = Series::from_values(
8824            "left",
8825            vec!["a".into(), "c".into()],
8826            vec![Scalar::Int64(1), Scalar::Int64(3)],
8827        )
8828        .expect("left");
8829        let right = Series::from_values(
8830            "right",
8831            vec!["b".into(), "c".into()],
8832            vec![Scalar::Int64(20), Scalar::Int64(30)],
8833        )
8834        .expect("right");
8835
8836        let out = join_series(&left, &right, JoinType::Outer).expect("join");
8837        assert_eq!(
8838            out.index.labels(),
8839            &[
8840                IndexLabel::Utf8("a".into()),
8841                IndexLabel::Utf8("b".into()),
8842                IndexLabel::Utf8("c".into())
8843            ]
8844        );
8845        assert_eq!(
8846            out.left_values.values(),
8847            &[
8848                Scalar::Float64(1.0),
8849                Scalar::Null(NullKind::NaN),
8850                Scalar::Float64(3.0)
8851            ]
8852        );
8853        assert_eq!(
8854            out.right_values.values(),
8855            &[
8856                Scalar::Null(NullKind::NaN),
8857                Scalar::Float64(20.0),
8858                Scalar::Float64(30.0)
8859            ]
8860        );
8861    }
8862
8863    #[test]
8864    fn outer_join_with_duplicates() {
8865        let left = Series::from_values(
8866            "left",
8867            vec!["k".into(), "k".into(), "a".into()],
8868            vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
8869        )
8870        .expect("left");
8871        let right = Series::from_values(
8872            "right",
8873            vec!["k".into(), "z".into()],
8874            vec![Scalar::Int64(10), Scalar::Int64(99)],
8875        )
8876        .expect("right");
8877
8878        let out = join_series(&left, &right, JoinType::Outer).expect("join");
8879        // "k" x "k": 2 matched rows. "a": left-only (1 row). "z": right-only (1 row).
8880        assert_eq!(out.index.labels().len(), 4);
8881    }
8882
8883    #[test]
8884    fn arena_right_join_matches_global() {
8885        let left = Series::from_values(
8886            "left",
8887            vec!["a".into(), "b".into()],
8888            vec![Scalar::Int64(1), Scalar::Int64(2)],
8889        )
8890        .expect("left");
8891        let right = Series::from_values(
8892            "right",
8893            vec!["b".into(), "c".into()],
8894            vec![Scalar::Int64(20), Scalar::Int64(30)],
8895        )
8896        .expect("right");
8897
8898        let global = join_series_with_options(
8899            &left,
8900            &right,
8901            JoinType::Right,
8902            JoinExecutionOptions {
8903                use_arena: false,
8904                arena_budget_bytes: 0,
8905            },
8906        )
8907        .expect("global");
8908        let arena = join_series_with_options(
8909            &left,
8910            &right,
8911            JoinType::Right,
8912            JoinExecutionOptions::default(),
8913        )
8914        .expect("arena");
8915        assert_eq!(arena, global);
8916    }
8917
8918    #[test]
8919    fn arena_outer_join_matches_global() {
8920        let left = Series::from_values(
8921            "left",
8922            vec!["a".into(), "b".into()],
8923            vec![Scalar::Int64(1), Scalar::Int64(2)],
8924        )
8925        .expect("left");
8926        let right = Series::from_values(
8927            "right",
8928            vec!["b".into(), "c".into()],
8929            vec![Scalar::Int64(20), Scalar::Int64(30)],
8930        )
8931        .expect("right");
8932
8933        let global = join_series_with_options(
8934            &left,
8935            &right,
8936            JoinType::Outer,
8937            JoinExecutionOptions {
8938                use_arena: false,
8939                arena_budget_bytes: 0,
8940            },
8941        )
8942        .expect("global");
8943        let arena = join_series_with_options(
8944            &left,
8945            &right,
8946            JoinType::Outer,
8947            JoinExecutionOptions::default(),
8948        )
8949        .expect("arena");
8950        assert_eq!(arena, global);
8951    }
8952
8953    /// AG-06-T test #6: arena is scoped per-operation. Two sequential
8954    /// operations each get their own arena (verified by both succeeding).
8955    #[test]
8956    fn arena_reset_between_operations() {
8957        let left = Series::from_values(
8958            "left",
8959            vec!["a".into(), "b".into()],
8960            vec![Scalar::Int64(1), Scalar::Int64(2)],
8961        )
8962        .expect("left");
8963        let right = Series::from_values(
8964            "right",
8965            vec!["a".into(), "c".into()],
8966            vec![Scalar::Int64(10), Scalar::Int64(30)],
8967        )
8968        .expect("right");
8969
8970        // Operation 1: inner join
8971        let out1 = join_series_with_options(
8972            &left,
8973            &right,
8974            JoinType::Inner,
8975            JoinExecutionOptions::default(),
8976        )
8977        .expect("op1");
8978        assert_eq!(out1.index.labels().len(), 1);
8979
8980        // Operation 2: left join (arena from op1 was freed)
8981        let out2 = join_series_with_options(
8982            &left,
8983            &right,
8984            JoinType::Left,
8985            JoinExecutionOptions::default(),
8986        )
8987        .expect("op2");
8988        assert_eq!(out2.index.labels().len(), 2);
8989    }
8990
8991    // ---- DataFrame merge tests (bd-2gi.17) ----
8992
8993    use fp_frame::{DataFrame, FrameError};
8994
8995    use super::{
8996        JoinError, MergeExecutionOptions, MergeValidateMode, MergedDataFrame,
8997        build_single_key_dense_right_merge_output, dense_int64_right_positions, merge_dataframes,
8998        merge_dataframes_on, merge_dataframes_on_with, merge_dataframes_on_with_options,
8999        ordered_identity_int64_keys_match, resolve_merge_suffixes,
9000    };
9001
9002    fn make_left_df() -> DataFrame {
9003        DataFrame::from_dict(
9004            &["id", "val_a"],
9005            vec![
9006                (
9007                    "id",
9008                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
9009                ),
9010                (
9011                    "val_a",
9012                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
9013                ),
9014            ],
9015        )
9016        .unwrap()
9017    }
9018
9019    fn make_right_df() -> DataFrame {
9020        DataFrame::from_dict(
9021            &["id", "val_b"],
9022            vec![
9023                (
9024                    "id",
9025                    vec![Scalar::Int64(2), Scalar::Int64(3), Scalar::Int64(4)],
9026                ),
9027                (
9028                    "val_b",
9029                    vec![Scalar::Int64(200), Scalar::Int64(300), Scalar::Int64(400)],
9030                ),
9031            ],
9032        )
9033        .unwrap()
9034    }
9035
9036    #[test]
9037    fn merge_preserves_pandas_column_order_for_nonalphabetical_names() {
9038        // br-frankenpandas-691lh: output columns follow pandas order — key/left
9039        // columns in the LEFT frame's source order, then right non-key columns —
9040        // not alphabetical (the columns map is a BTreeMap). Verified vs pandas
9041        // 2.2.3: merge(left[k,zebra,apple], right[k,mango], on=k)
9042        //   -> [k, zebra, apple, mango].
9043        let left = DataFrame::from_dict(
9044            &["k", "zebra", "apple"],
9045            vec![
9046                ("k", vec![Scalar::Int64(1), Scalar::Int64(2)]),
9047                ("zebra", vec![Scalar::Int64(10), Scalar::Int64(20)]),
9048                ("apple", vec![Scalar::Int64(30), Scalar::Int64(40)]),
9049            ],
9050        )
9051        .unwrap();
9052        let right = DataFrame::from_dict(
9053            &["k", "mango"],
9054            vec![
9055                ("k", vec![Scalar::Int64(1), Scalar::Int64(2)]),
9056                ("mango", vec![Scalar::Int64(50), Scalar::Int64(60)]),
9057            ],
9058        )
9059        .unwrap();
9060        let merged = merge_dataframes(&left, &right, "k", JoinType::Inner).unwrap();
9061        let order: Vec<&str> = merged.column_order.iter().map(String::as_str).collect();
9062        assert_eq!(order, ["k", "zebra", "apple", "mango"]);
9063    }
9064
9065    #[test]
9066    fn join_row_count_lattice_n8npw() {
9067        // Invariant (br-frankenpandas-n8npw): inner<=left<=outer and inner<=right<=outer
9068        // by row count. Seeded LCG, no mocks.
9069        let mut s: u64 = 0x4e57_0b1c_2d3e_4f55;
9070        let mut next = || {
9071            s = s
9072                .wrapping_mul(6_364_136_223_846_793_005)
9073                .wrapping_add(1_442_695_040_888_963_407);
9074            (s >> 33) as u32
9075        };
9076        for iter in 0..300u32 {
9077            let ln = (next() % 6) as usize + 1;
9078            let rn = (next() % 6) as usize + 1;
9079            let lk: Vec<Scalar> = (0..ln)
9080                .map(|_| Scalar::Int64((next() % 4) as i64))
9081                .collect();
9082            let rk: Vec<Scalar> = (0..rn)
9083                .map(|_| Scalar::Int64((next() % 4) as i64))
9084                .collect();
9085            let left = DataFrame::from_dict(
9086                &["k", "lv"],
9087                vec![
9088                    ("k", lk),
9089                    ("lv", (0..ln).map(|i| Scalar::Int64(i as i64)).collect()),
9090                ],
9091            )
9092            .unwrap();
9093            let right = DataFrame::from_dict(
9094                &["k", "rv"],
9095                vec![
9096                    ("k", rk),
9097                    ("rv", (0..rn).map(|i| Scalar::Int64(i as i64)).collect()),
9098                ],
9099            )
9100            .unwrap();
9101            let rows = |jt| {
9102                let m = merge_dataframes(&left, &right, "k", jt).unwrap();
9103                merged_values(&m, "k").unwrap().len()
9104            };
9105            let inner = rows(JoinType::Inner);
9106            let lj = rows(JoinType::Left);
9107            let rj = rows(JoinType::Right);
9108            let outer = rows(JoinType::Outer);
9109            assert!(
9110                inner <= lj && lj <= outer,
9111                "inner<=left<=outer iter={iter}: {inner} {lj} {outer}"
9112            );
9113            assert!(
9114                inner <= rj && rj <= outer,
9115                "inner<=right<=outer iter={iter}: {inner} {rj} {outer}"
9116            );
9117        }
9118    }
9119
9120    #[test]
9121    fn right_join_null_fill_multiset_7je8m() {
9122        use std::collections::HashMap;
9123        // Differential (br-frankenpandas-7je8m): RIGHT join preserves every right row;
9124        // matched left payload cross-product else null. (key, lv-or-None, rv) multiset
9125        // vs oracle. Seeded LCG, no mocks.
9126        let mut s: u64 = 0x4e57_0b1c_2d3e_4f54;
9127        let mut next = || {
9128            s = s
9129                .wrapping_mul(6_364_136_223_846_793_005)
9130                .wrapping_add(1_442_695_040_888_963_407);
9131            (s >> 33) as u32
9132        };
9133        for iter in 0..300u32 {
9134            let ln = (next() % 6) as usize + 1;
9135            let rn = (next() % 6) as usize + 1;
9136            let lk: Vec<i64> = (0..ln).map(|_| (next() % 4) as i64).collect();
9137            let lv: Vec<i64> = (0..ln).map(|i| i as i64).collect();
9138            let rk: Vec<i64> = (0..rn).map(|_| (next() % 4) as i64).collect();
9139            let rv: Vec<i64> = (0..rn).map(|i| 100 + i as i64).collect();
9140            let left = DataFrame::from_dict(
9141                &["k", "lv"],
9142                vec![
9143                    ("k", lk.iter().map(|&x| Scalar::Int64(x)).collect()),
9144                    ("lv", lv.iter().map(|&x| Scalar::Int64(x)).collect()),
9145                ],
9146            )
9147            .unwrap();
9148            let right = DataFrame::from_dict(
9149                &["k", "rv"],
9150                vec![
9151                    ("k", rk.iter().map(|&x| Scalar::Int64(x)).collect()),
9152                    ("rv", rv.iter().map(|&x| Scalar::Int64(x)).collect()),
9153                ],
9154            )
9155            .unwrap();
9156            let merged = merge_dataframes(&left, &right, "k", JoinType::Right).unwrap();
9157
9158            let ks = merged_values(&merged, "k").unwrap();
9159            let lvs = merged_values(&merged, "lv").unwrap();
9160            let rvs = merged_values(&merged, "rv").unwrap();
9161            let ki = |v: &Scalar| -> i64 {
9162                match v {
9163                    Scalar::Int64(x) => *x,
9164                    Scalar::Float64(x) => *x as i64,
9165                    _ => i64::MIN,
9166                }
9167            };
9168            let kopt =
9169                |v: &Scalar| -> Option<i64> { if v.is_missing() { None } else { Some(ki(v)) } };
9170            let mut got: Vec<(i64, Option<i64>, i64)> = (0..ks.len())
9171                .map(|i| (ki(&ks[i]), kopt(&lvs[i]), ki(&rvs[i])))
9172                .collect();
9173            // Oracle.
9174            let mut lby: HashMap<i64, Vec<i64>> = HashMap::new();
9175            for i in 0..ln {
9176                lby.entry(lk[i]).or_default().push(lv[i]);
9177            }
9178            let mut exp: Vec<(i64, Option<i64>, i64)> = Vec::new();
9179            for i in 0..rn {
9180                match lby.get(&rk[i]) {
9181                    Some(lvals) => {
9182                        for &a in lvals {
9183                            exp.push((rk[i], Some(a), rv[i]));
9184                        }
9185                    }
9186                    None => exp.push((rk[i], None, rv[i])),
9187                }
9188            }
9189            got.sort();
9190            exp.sort();
9191            assert_eq!(got, exp, "right join multiset iter={iter}");
9192        }
9193    }
9194
9195    #[test]
9196    fn inner_join_utf8_value_multiset_fr4ns() {
9197        use std::collections::HashMap;
9198        // Differential (br-frankenpandas-fr4ns): inner join on Utf8 keys; the (key,
9199        // lv, rv) multiset == per-key cross-product (5foyp was int/dense; jlf8d a
9200        // single case). Seeded LCG, no mocks.
9201        let mut s: u64 = 0x4e57_0b1c_2d3e_4f51;
9202        let mut next = || {
9203            s = s
9204                .wrapping_mul(6_364_136_223_846_793_005)
9205                .wrapping_add(1_442_695_040_888_963_407);
9206            (s >> 33) as u32
9207        };
9208        let key = |n: u32| Scalar::Utf8(format!("{}", (b'a' + (n % 4) as u8) as char));
9209        for iter in 0..300u32 {
9210            let ln = (next() % 6) as usize + 1;
9211            let rn = (next() % 6) as usize + 1;
9212            let lk: Vec<Scalar> = (0..ln).map(|_| key(next())).collect();
9213            let lv: Vec<i64> = (0..ln).map(|i| i as i64).collect();
9214            let rk: Vec<Scalar> = (0..rn).map(|_| key(next())).collect();
9215            let rv: Vec<i64> = (0..rn).map(|i| 100 + i as i64).collect();
9216            let left = DataFrame::from_dict(
9217                &["k", "lv"],
9218                vec![
9219                    ("k", lk.clone()),
9220                    ("lv", lv.iter().map(|&x| Scalar::Int64(x)).collect()),
9221                ],
9222            )
9223            .unwrap();
9224            let right = DataFrame::from_dict(
9225                &["k", "rv"],
9226                vec![
9227                    ("k", rk.clone()),
9228                    ("rv", rv.iter().map(|&x| Scalar::Int64(x)).collect()),
9229                ],
9230            )
9231            .unwrap();
9232            let merged = merge_dataframes(&left, &right, "k", JoinType::Inner).unwrap();
9233
9234            let ks = merged_values(&merged, "k").unwrap();
9235            let lvs = merged_values(&merged, "lv").unwrap();
9236            let rvs = merged_values(&merged, "rv").unwrap();
9237            let kstr = |v: &Scalar| -> String {
9238                match v {
9239                    Scalar::Utf8(x) => x.clone(),
9240                    _ => String::new(),
9241                }
9242            };
9243            let ki = |v: &Scalar| -> i64 {
9244                match v {
9245                    Scalar::Int64(x) => *x,
9246                    _ => i64::MIN,
9247                }
9248            };
9249            let mut got: Vec<(String, i64, i64)> = (0..ks.len())
9250                .map(|i| (kstr(&ks[i]), ki(&lvs[i]), ki(&rvs[i])))
9251                .collect();
9252            // Oracle: per-key cross product.
9253            let mut lby: HashMap<String, Vec<i64>> = HashMap::new();
9254            for i in 0..ln {
9255                lby.entry(kstr(&lk[i])).or_default().push(lv[i]);
9256            }
9257            let mut rby: HashMap<String, Vec<i64>> = HashMap::new();
9258            for i in 0..rn {
9259                rby.entry(kstr(&rk[i])).or_default().push(rv[i]);
9260            }
9261            let mut exp: Vec<(String, i64, i64)> = Vec::new();
9262            for (k, lvals) in &lby {
9263                if let Some(rvals) = rby.get(k) {
9264                    for &a in lvals {
9265                        for &b in rvals {
9266                            exp.push((k.clone(), a, b));
9267                        }
9268                    }
9269                }
9270            }
9271            got.sort();
9272            exp.sort();
9273            assert_eq!(got, exp, "inner Utf8 multiset iter={iter}");
9274        }
9275    }
9276
9277    #[test]
9278    fn inner_join_utf8_keys_jlf8d() {
9279        use std::collections::HashMap;
9280        // br-frankenpandas-jlf8d: inner join on Utf8 keys (general/hash path).
9281        let s = |v: &str| Scalar::Utf8(v.to_owned());
9282        let left = DataFrame::from_dict(
9283            &["k", "lv"],
9284            vec![
9285                ("k", vec![s("a"), s("b"), s("c")]),
9286                (
9287                    "lv",
9288                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
9289                ),
9290            ],
9291        )
9292        .expect("left");
9293        let right = DataFrame::from_dict(
9294            &["k", "rv"],
9295            vec![
9296                ("k", vec![s("b"), s("c"), s("d")]),
9297                (
9298                    "rv",
9299                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
9300                ),
9301            ],
9302        )
9303        .expect("right");
9304        let merged = merge_dataframes(&left, &right, "k", JoinType::Inner).expect("merge");
9305
9306        let keys = merged_values(&merged, "k").expect("k");
9307        let lv = merged_values(&merged, "lv").expect("lv");
9308        let rv = merged_values(&merged, "rv").expect("rv");
9309        let exp_lv: HashMap<&str, i64> = [("b", 2), ("c", 3)].into_iter().collect();
9310        let exp_rv: HashMap<&str, i64> = [("b", 10), ("c", 20)].into_iter().collect();
9311        assert_eq!(keys.len(), 2, "inner keys = {{b,c}}");
9312        for i in 0..keys.len() {
9313            let k = match &keys[i] {
9314                Scalar::Utf8(x) => x.as_str(),
9315                _ => "?",
9316            };
9317            let geti = |s: &Scalar| match s {
9318                Scalar::Int64(v) => *v,
9319                _ => i64::MIN,
9320            };
9321            assert_eq!(geti(&lv[i]), exp_lv[k], "lv at {k}");
9322            assert_eq!(geti(&rv[i]), exp_rv[k], "rv at {k}");
9323        }
9324    }
9325
9326    #[test]
9327    fn merge_indicator_column_d3ec6() {
9328        use std::collections::BTreeSet;
9329        // br-frankenpandas-d3ec6: outer-join indicator marks left_only/both/right_only.
9330        let left = DataFrame::from_dict(
9331            &["k"],
9332            vec![(
9333                "k",
9334                vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
9335            )],
9336        )
9337        .expect("left");
9338        let right = DataFrame::from_dict(
9339            &["k"],
9340            vec![(
9341                "k",
9342                vec![Scalar::Int64(2), Scalar::Int64(3), Scalar::Int64(4)],
9343            )],
9344        )
9345        .expect("right");
9346        let opts = super::MergeExecutionOptions {
9347            indicator_name: Some("_merge".to_owned()),
9348            ..Default::default()
9349        };
9350        let m = super::merge_dataframes_on_with_options(
9351            &left,
9352            &right,
9353            &["k"],
9354            &["k"],
9355            JoinType::Outer,
9356            opts,
9357        )
9358        .expect("merge");
9359
9360        let keys = merged_values(&m, "k").expect("k");
9361        let ind = merged_values(&m, "_merge").expect("_merge present");
9362        let lset: BTreeSet<i64> = [1, 2, 3].into_iter().collect();
9363        let rset: BTreeSet<i64> = [2, 3, 4].into_iter().collect();
9364        assert_eq!(keys.len(), 4, "outer keys = union");
9365        for i in 0..keys.len() {
9366            let k = match &keys[i] {
9367                Scalar::Int64(v) => *v,
9368                _ => i64::MIN,
9369            };
9370            let exp = match (lset.contains(&k), rset.contains(&k)) {
9371                (true, true) => "both",
9372                (true, false) => "left_only",
9373                (false, true) => "right_only",
9374                (false, false) => "??",
9375            };
9376            assert_eq!(ind[i], Scalar::Utf8(exp.to_owned()), "indicator at key {k}");
9377        }
9378    }
9379
9380    #[test]
9381    fn merge_overlapping_columns_suffixed_vb10q() {
9382        // br-frankenpandas-vb10q: a non-key column present in both frames is
9383        // suffixed _x (left) / _y (right) on merge.
9384        let mk = |vfactor: i64| {
9385            DataFrame::from_dict(
9386                &["k", "v"],
9387                vec![
9388                    (
9389                        "k",
9390                        vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
9391                    ),
9392                    (
9393                        "v",
9394                        vec![
9395                            Scalar::Int64(vfactor),
9396                            Scalar::Int64(2 * vfactor),
9397                            Scalar::Int64(3 * vfactor),
9398                        ],
9399                    ),
9400                ],
9401            )
9402            .expect("frame")
9403        };
9404        let left = mk(10); // v = k*10
9405        let right = mk(100); // v = k*100
9406        let merged = merge_dataframes(&left, &right, "k", JoinType::Inner).expect("merge");
9407
9408        let keys = merged_values(&merged, "k").expect("k");
9409        let vx = merged_values(&merged, "v_x").expect("v_x present");
9410        let vy = merged_values(&merged, "v_y").expect("v_y present");
9411        assert_eq!(keys.len(), 3);
9412        for i in 0..keys.len() {
9413            let k = match &keys[i] {
9414                Scalar::Int64(x) => *x,
9415                _ => i64::MIN,
9416            };
9417            assert_eq!(vx[i], Scalar::Int64(k * 10), "v_x at key {k}");
9418            assert_eq!(vy[i], Scalar::Int64(k * 100), "v_y at key {k}");
9419        }
9420    }
9421
9422    #[test]
9423    fn int64_join_row_count_matches_cardinality_invariant_ya1po() {
9424        use std::collections::BTreeMap;
9425
9426        // Metamorphic harness (br-frankenpandas-ya1po): merge_dataframes row count
9427        // must equal the pandas-standard cardinality per join type — an
9428        // ordering-independent invariant guarding the dense/direct-address Int64
9429        // join fast paths. Deterministic seeded LCG — no rand crate, no mocks.
9430        let mut state: u64 = 0xa5a5_5a5a_dead_beef;
9431        let mut next = || {
9432            state = state
9433                .wrapping_mul(6_364_136_223_846_793_005)
9434                .wrapping_add(1_442_695_040_888_963_407);
9435            (state >> 33) as u32
9436        };
9437
9438        let build = |keys: &[i64], payload_name: &str| {
9439            let n = keys.len();
9440            DataFrame::from_dict(
9441                &["k", payload_name],
9442                vec![
9443                    (
9444                        "k",
9445                        keys.iter().copied().map(Scalar::Int64).collect::<Vec<_>>(),
9446                    ),
9447                    (
9448                        payload_name,
9449                        (0..n as i64).map(Scalar::Int64).collect::<Vec<_>>(),
9450                    ),
9451                ],
9452            )
9453            .expect("frame")
9454        };
9455
9456        for iter in 0..1500u32 {
9457            let nl = (next() % 9) as usize + 1;
9458            let nr = (next() % 9) as usize + 1;
9459            // Small key range so many-to-many (duplicate-key) joins are common.
9460            let lk: Vec<i64> = (0..nl).map(|_| (next() % 4) as i64).collect();
9461            let rk: Vec<i64> = (0..nr).map(|_| (next() % 4) as i64).collect();
9462            let left = build(&lk, "lv");
9463            let right = build(&rk, "rv");
9464
9465            let mut lc: BTreeMap<i64, i64> = BTreeMap::new();
9466            let mut rc: BTreeMap<i64, i64> = BTreeMap::new();
9467            for &k in &lk {
9468                *lc.entry(k).or_default() += 1;
9469            }
9470            for &k in &rk {
9471                *rc.entry(k).or_default() += 1;
9472            }
9473            let mut all_keys: Vec<i64> = lc.keys().chain(rc.keys()).copied().collect();
9474            all_keys.sort_unstable();
9475            all_keys.dedup();
9476
9477            let g = |k: i64, m: &BTreeMap<i64, i64>| m.get(&k).copied().unwrap_or(0);
9478            let inner: i64 = all_keys.iter().map(|&k| g(k, &lc) * g(k, &rc)).sum();
9479            let left_exp: i64 = lc.iter().map(|(&k, &l)| l * g(k, &rc).max(1)).sum();
9480            let right_exp: i64 = rc.iter().map(|(&k, &r)| r * g(k, &lc).max(1)).sum();
9481            let outer: i64 = all_keys
9482                .iter()
9483                .map(|&k| {
9484                    let (l, r) = (g(k, &lc), g(k, &rc));
9485                    if l > 0 && r > 0 { l * r } else { l + r }
9486                })
9487                .sum();
9488
9489            let ctx = format!("iter={iter} lk={lk:?} rk={rk:?}");
9490            for (jt, exp) in [
9491                (JoinType::Inner, inner),
9492                (JoinType::Left, left_exp),
9493                (JoinType::Right, right_exp),
9494                (JoinType::Outer, outer),
9495            ] {
9496                let merged = merge_dataframes(&left, &right, "k", jt).expect("merge");
9497                let rows = merged_values(&merged, "k").expect("key col").len() as i64;
9498                assert_eq!(rows, exp, "{jt:?} row count {ctx}");
9499            }
9500        }
9501    }
9502
9503    #[test]
9504    fn inner_join_value_multiset_matches_crossproduct_oracle_5foyp() {
9505        use std::collections::BTreeMap;
9506
9507        // Value-level oracle (br-frankenpandas-5foyp): an inner join must pair the
9508        // CORRECT rows, not merely produce the right count. Assert the multiset of
9509        // output (key, left_payload, right_payload) triples equals the
9510        // independently-computed per-key cross product. Ordering-independent
9511        // (sorted-vector compare). Deterministic seeded LCG — no rand, no mocks.
9512        let mut state: u64 = 0x0ddc_0ffe_e0dd_f00d;
9513        let mut next = || {
9514            state = state
9515                .wrapping_mul(6_364_136_223_846_793_005)
9516                .wrapping_add(1_442_695_040_888_963_407);
9517            (state >> 33) as u32
9518        };
9519
9520        let build = |keys: &[i64], pname: &str| {
9521            let n = keys.len();
9522            DataFrame::from_dict(
9523                &["k", pname],
9524                vec![
9525                    (
9526                        "k",
9527                        keys.iter().copied().map(Scalar::Int64).collect::<Vec<_>>(),
9528                    ),
9529                    // Distinct per-row payload (= row index) so mis-pairings are visible.
9530                    (pname, (0..n as i64).map(Scalar::Int64).collect::<Vec<_>>()),
9531                ],
9532            )
9533            .expect("frame")
9534        };
9535        // Extract i64; a non-Int64 maps to a sentinel that will never equal a
9536        // real row index/key, so any dtype regression still fails the multiset
9537        // assert below (no panic — keeps the helper side-effect-free).
9538        let geti = |s: &Scalar| match s {
9539            Scalar::Int64(v) => *v,
9540            _ => i64::MIN,
9541        };
9542
9543        for iter in 0..1500u32 {
9544            let nl = (next() % 9) as usize + 1;
9545            let nr = (next() % 9) as usize + 1;
9546            let lk: Vec<i64> = (0..nl).map(|_| (next() % 4) as i64).collect();
9547            let rk: Vec<i64> = (0..nr).map(|_| (next() % 4) as i64).collect();
9548            let left = build(&lk, "lv");
9549            let right = build(&rk, "rv");
9550
9551            let merged = merge_dataframes(&left, &right, "k", JoinType::Inner).expect("merge");
9552            let ks = merged_values(&merged, "k").expect("k");
9553            let lvs = merged_values(&merged, "lv").expect("lv");
9554            let rvs = merged_values(&merged, "rv").expect("rv");
9555            let mut got: Vec<(i64, i64, i64)> = (0..ks.len())
9556                .map(|i| (geti(&ks[i]), geti(&lvs[i]), geti(&rvs[i])))
9557                .collect();
9558            got.sort_unstable();
9559
9560            // Independent oracle: per-key cross product of left/right row payloads.
9561            let mut lg: BTreeMap<i64, Vec<i64>> = BTreeMap::new();
9562            let mut rg: BTreeMap<i64, Vec<i64>> = BTreeMap::new();
9563            for (i, &k) in lk.iter().enumerate() {
9564                lg.entry(k).or_default().push(i as i64);
9565            }
9566            for (i, &k) in rk.iter().enumerate() {
9567                rg.entry(k).or_default().push(i as i64);
9568            }
9569            let mut exp: Vec<(i64, i64, i64)> = Vec::new();
9570            for (&k, lps) in &lg {
9571                if let Some(rps) = rg.get(&k) {
9572                    for &a in lps {
9573                        for &b in rps {
9574                            exp.push((k, a, b));
9575                        }
9576                    }
9577                }
9578            }
9579            exp.sort_unstable();
9580
9581            assert_eq!(
9582                got, exp,
9583                "inner join value multiset iter={iter} lk={lk:?} rk={rk:?}"
9584            );
9585        }
9586    }
9587
9588    #[test]
9589    fn left_outer_join_nullfill_value_oracle_kaj3t() {
9590        use std::collections::BTreeMap;
9591
9592        // Value oracle for LEFT/OUTER null-fill (br-frankenpandas-kaj3t): unmatched
9593        // rows get NULL-filled on the absent side — the subtlest join behavior.
9594        // NULL is represented by the i64::MIN sentinel (payloads are 0..n and keys
9595        // 0..3, so a sentinel never collides with a real value). Deterministic
9596        // seeded LCG — no rand crate, no mocks.
9597        const NUL: i64 = i64::MIN;
9598        let mut state: u64 = 0xfeed_face_cafe_b0ba;
9599        let mut next = || {
9600            state = state
9601                .wrapping_mul(6_364_136_223_846_793_005)
9602                .wrapping_add(1_442_695_040_888_963_407);
9603            (state >> 33) as u32
9604        };
9605
9606        let build = |keys: &[i64], pname: &str| {
9607            let n = keys.len();
9608            DataFrame::from_dict(
9609                &["k", pname],
9610                vec![
9611                    (
9612                        "k",
9613                        keys.iter().copied().map(Scalar::Int64).collect::<Vec<_>>(),
9614                    ),
9615                    (pname, (0..n as i64).map(Scalar::Int64).collect::<Vec<_>>()),
9616                ],
9617            )
9618            .expect("frame")
9619        };
9620        // Int64 -> value. Left/outer joins upcast Int64 payload columns to
9621        // Float64 when null-fill introduces missing values (pandas parity: Int64
9622        // can't hold NaN), so accept finite Float64 too. NULL / NaN -> NUL
9623        // sentinel. Payloads are small whole numbers, so f64 -> i64 is exact.
9624        let geti = |s: &Scalar| match s {
9625            Scalar::Int64(v) => *v,
9626            Scalar::Float64(v) if v.is_finite() => *v as i64,
9627            _ => NUL,
9628        };
9629
9630        for iter in 0..1500u32 {
9631            let nl = (next() % 9) as usize + 1;
9632            let nr = (next() % 9) as usize + 1;
9633            let lk: Vec<i64> = (0..nl).map(|_| (next() % 4) as i64).collect();
9634            let rk: Vec<i64> = (0..nr).map(|_| (next() % 4) as i64).collect();
9635            let left = build(&lk, "lv");
9636            let right = build(&rk, "rv");
9637
9638            // Right rows grouped by key (payload = row index).
9639            let mut rg: BTreeMap<i64, Vec<i64>> = BTreeMap::new();
9640            for (j, &k) in rk.iter().enumerate() {
9641                rg.entry(k).or_default().push(j as i64);
9642            }
9643            let lkeys: std::collections::BTreeSet<i64> = lk.iter().copied().collect();
9644
9645            let read = |jt: JoinType| -> Vec<(i64, i64, i64)> {
9646                let merged = merge_dataframes(&left, &right, "k", jt).expect("merge");
9647                let ks = merged_values(&merged, "k").expect("k");
9648                let lvs = merged_values(&merged, "lv").expect("lv");
9649                let rvs = merged_values(&merged, "rv").expect("rv");
9650                let mut got: Vec<(i64, i64, i64)> = (0..ks.len())
9651                    .map(|i| (geti(&ks[i]), geti(&lvs[i]), geti(&rvs[i])))
9652                    .collect();
9653                got.sort_unstable();
9654                got
9655            };
9656
9657            // LEFT oracle: every left row appears; matched -> one row per right
9658            // match, unmatched -> NULL right payload (key still the left key).
9659            let mut exp_left: Vec<(i64, i64, i64)> = Vec::new();
9660            for (i, &k) in lk.iter().enumerate() {
9661                match rg.get(&k) {
9662                    Some(rps) => {
9663                        for &j in rps {
9664                            exp_left.push((k, i as i64, j));
9665                        }
9666                    }
9667                    None => exp_left.push((k, i as i64, NUL)),
9668                }
9669            }
9670            exp_left.sort_unstable();
9671            assert_eq!(
9672                read(JoinType::Left),
9673                exp_left,
9674                "left join value oracle iter={iter} lk={lk:?} rk={rk:?}"
9675            );
9676
9677            // OUTER oracle: LEFT plus right-only rows (no left match) with NULL
9678            // left payload and the coalesced key.
9679            let mut exp_outer = exp_left.clone();
9680            for (j, &k) in rk.iter().enumerate() {
9681                if !lkeys.contains(&k) {
9682                    exp_outer.push((k, NUL, j as i64));
9683                }
9684            }
9685            exp_outer.sort_unstable();
9686            assert_eq!(
9687                read(JoinType::Outer),
9688                exp_outer,
9689                "outer join value oracle iter={iter} lk={lk:?} rk={rk:?}"
9690            );
9691        }
9692    }
9693
9694    #[test]
9695    fn left_join_value_multiset_matches_unmatched_oracle_gp0ik() {
9696        use std::collections::BTreeMap;
9697
9698        // Value-level LEFT join oracle (br-frankenpandas-gp0ik): matched keys
9699        // emit the left/right cross product; unmatched left rows emit exactly one
9700        // row with a missing right payload. Ordering-independent sorted multiset.
9701        let mut state: u64 = 0x51de_cafe_2026_0618;
9702        let mut next = || {
9703            state = state
9704                .wrapping_mul(6_364_136_223_846_793_005)
9705                .wrapping_add(1_442_695_040_888_963_407);
9706            (state >> 33) as u32
9707        };
9708
9709        let build = |keys: &[i64], pname: &str| {
9710            let n = keys.len();
9711            DataFrame::from_dict(
9712                &["k", pname],
9713                vec![
9714                    (
9715                        "k",
9716                        keys.iter().copied().map(Scalar::Int64).collect::<Vec<_>>(),
9717                    ),
9718                    (pname, (0..n as i64).map(Scalar::Int64).collect::<Vec<_>>()),
9719                ],
9720            )
9721            .expect("frame")
9722        };
9723        let geti = |s: &Scalar| match s {
9724            Scalar::Int64(v) => *v,
9725            _ => i64::MIN,
9726        };
9727        let get_optional_i64 = |s: &Scalar| match s {
9728            Scalar::Int64(v) => Some(*v),
9729            value if value.is_missing() => None,
9730            _ => Some(i64::MIN),
9731        };
9732
9733        for iter in 0..1500u32 {
9734            let nl = (next() % 9) as usize + 1;
9735            let nr = (next() % 9) as usize + 1;
9736            let lk: Vec<i64> = (0..nl).map(|_| (next() % 5) as i64).collect();
9737            let rk: Vec<i64> = (0..nr).map(|_| (next() % 3) as i64).collect();
9738            let left = build(&lk, "lv");
9739            let right = build(&rk, "rv");
9740
9741            let merged = merge_dataframes(&left, &right, "k", JoinType::Left).expect("merge");
9742            let ks = merged_values(&merged, "k").expect("k");
9743            let lvs = merged_values(&merged, "lv").expect("lv");
9744            let rvs = merged_values(&merged, "rv").expect("rv");
9745            let mut got: Vec<(i64, i64, Option<i64>)> = (0..ks.len())
9746                .map(|i| (geti(&ks[i]), geti(&lvs[i]), get_optional_i64(&rvs[i])))
9747                .collect();
9748            got.sort_unstable();
9749
9750            let mut rg: BTreeMap<i64, Vec<i64>> = BTreeMap::new();
9751            for (i, &k) in rk.iter().enumerate() {
9752                rg.entry(k).or_default().push(i as i64);
9753            }
9754            let mut exp: Vec<(i64, i64, Option<i64>)> = Vec::new();
9755            for (left_pos, &k) in lk.iter().enumerate() {
9756                if let Some(right_positions) = rg.get(&k) {
9757                    for &right_pos in right_positions {
9758                        exp.push((k, left_pos as i64, Some(right_pos)));
9759                    }
9760                } else {
9761                    exp.push((k, left_pos as i64, None));
9762                }
9763            }
9764            exp.sort_unstable();
9765
9766            assert_eq!(
9767                got, exp,
9768                "left join value multiset iter={iter} lk={lk:?} rk={rk:?}"
9769            );
9770        }
9771    }
9772
9773    #[test]
9774    fn right_join_value_multiset_matches_unmatched_oracle_pd1h5() {
9775        use std::collections::BTreeMap;
9776
9777        // Value-level RIGHT join oracle (br-frankenpandas-pd1h5): matched keys
9778        // emit the left/right cross product; unmatched right rows emit exactly one
9779        // row with a missing left payload. Ordering-independent sorted multiset.
9780        let mut state: u64 = 0x7191_2026_0618_a015;
9781        let mut next = || {
9782            state = state
9783                .wrapping_mul(6_364_136_223_846_793_005)
9784                .wrapping_add(1_442_695_040_888_963_407);
9785            (state >> 33) as u32
9786        };
9787
9788        let build = |keys: &[i64], pname: &str| {
9789            let n = keys.len();
9790            DataFrame::from_dict(
9791                &["k", pname],
9792                vec![
9793                    (
9794                        "k",
9795                        keys.iter().copied().map(Scalar::Int64).collect::<Vec<_>>(),
9796                    ),
9797                    (pname, (0..n as i64).map(Scalar::Int64).collect::<Vec<_>>()),
9798                ],
9799            )
9800            .expect("frame")
9801        };
9802        let geti = |s: &Scalar| match s {
9803            Scalar::Int64(v) => *v,
9804            Scalar::Float64(v) if v.is_finite() => *v as i64,
9805            _ => i64::MIN,
9806        };
9807        let get_optional_i64 = |s: &Scalar| match s {
9808            Scalar::Int64(v) => Some(*v),
9809            Scalar::Float64(v) if v.is_finite() => Some(*v as i64),
9810            value if value.is_missing() => None,
9811            _ => Some(i64::MIN),
9812        };
9813
9814        for iter in 0..1500u32 {
9815            let nl = (next() % 9) as usize + 1;
9816            let nr = (next() % 9) as usize + 1;
9817            let lk: Vec<i64> = (0..nl).map(|_| (next() % 4) as i64).collect();
9818            let rk: Vec<i64> = (0..nr).map(|_| (next() % 5) as i64).collect();
9819            let left = build(&lk, "lv");
9820            let right = build(&rk, "rv");
9821
9822            let merged = merge_dataframes(&left, &right, "k", JoinType::Right).expect("merge");
9823            let ks = merged_values(&merged, "k").expect("k");
9824            let lvs = merged_values(&merged, "lv").expect("lv");
9825            let rvs = merged_values(&merged, "rv").expect("rv");
9826            let mut got: Vec<(i64, Option<i64>, i64)> = (0..ks.len())
9827                .map(|i| (geti(&ks[i]), get_optional_i64(&lvs[i]), geti(&rvs[i])))
9828                .collect();
9829            got.sort_unstable();
9830
9831            let mut lg: BTreeMap<i64, Vec<i64>> = BTreeMap::new();
9832            for (i, &k) in lk.iter().enumerate() {
9833                lg.entry(k).or_default().push(i as i64);
9834            }
9835            let mut exp: Vec<(i64, Option<i64>, i64)> = Vec::new();
9836            for (right_pos, &k) in rk.iter().enumerate() {
9837                if let Some(left_positions) = lg.get(&k) {
9838                    for &left_pos in left_positions {
9839                        exp.push((k, Some(left_pos), right_pos as i64));
9840                    }
9841                } else {
9842                    exp.push((k, None, right_pos as i64));
9843                }
9844            }
9845            exp.sort_unstable();
9846
9847            assert_eq!(
9848                got, exp,
9849                "right join value multiset iter={iter} lk={lk:?} rk={rk:?}"
9850            );
9851        }
9852    }
9853
9854    fn merged_values<'a>(
9855        merged: &'a MergedDataFrame,
9856        name: &str,
9857    ) -> Result<&'a [Scalar], JoinError> {
9858        Ok(merged
9859            .columns
9860            .get(name)
9861            .ok_or_else(|| {
9862                JoinError::Frame(FrameError::CompatibilityRejected(format!(
9863                    "missing merged column '{name}'"
9864                )))
9865            })?
9866            .values())
9867    }
9868
9869    fn merged_values_where_indicator(
9870        merged: &MergedDataFrame,
9871        column_name: &str,
9872        indicator_name: &str,
9873        indicator_value: &str,
9874    ) -> Result<Vec<Scalar>, JoinError> {
9875        let values = merged_values(merged, column_name)?;
9876        let indicators = merged_values(merged, indicator_name)?;
9877        Ok(values
9878            .iter()
9879            .zip(indicators.iter())
9880            .filter_map(|(value, indicator)| {
9881                if matches!(indicator, Scalar::Utf8(v) if v == indicator_value) {
9882                    Some(value.clone())
9883                } else {
9884                    None
9885                }
9886            })
9887            .collect())
9888    }
9889
9890    #[test]
9891    fn merge_inner_basic() {
9892        let left = make_left_df();
9893        let right = make_right_df();
9894        let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
9895
9896        assert_eq!(merged.columns.get("id").unwrap().len(), 2);
9897        assert_eq!(
9898            merged.columns.get("id").unwrap().values(),
9899            &[Scalar::Int64(2), Scalar::Int64(3)]
9900        );
9901        assert_eq!(
9902            merged.columns.get("val_a").unwrap().values(),
9903            &[Scalar::Int64(20), Scalar::Int64(30)]
9904        );
9905        assert_eq!(
9906            merged.columns.get("val_b").unwrap().values(),
9907            &[Scalar::Int64(200), Scalar::Int64(300)]
9908        );
9909    }
9910
9911    #[test]
9912    fn merge_inner_single_key_preserves_duplicate_probe_order() {
9913        let left = DataFrame::from_dict(
9914            &["id", "left_value"],
9915            vec![
9916                (
9917                    "id",
9918                    vec![Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(2)],
9919                ),
9920                (
9921                    "left_value",
9922                    vec![Scalar::Int64(20), Scalar::Int64(10), Scalar::Int64(21)],
9923                ),
9924            ],
9925        )
9926        .unwrap();
9927        let right = DataFrame::from_dict(
9928            &["id", "right_value"],
9929            vec![
9930                (
9931                    "id",
9932                    vec![Scalar::Int64(2), Scalar::Int64(2), Scalar::Int64(1)],
9933                ),
9934                (
9935                    "right_value",
9936                    vec![Scalar::Int64(200), Scalar::Int64(201), Scalar::Int64(100)],
9937                ),
9938            ],
9939        )
9940        .unwrap();
9941
9942        let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
9943
9944        assert_eq!(
9945            merged.columns.get("id").unwrap().values(),
9946            &[
9947                Scalar::Int64(2),
9948                Scalar::Int64(2),
9949                Scalar::Int64(1),
9950                Scalar::Int64(2),
9951                Scalar::Int64(2),
9952            ]
9953        );
9954        assert_eq!(
9955            merged.columns.get("left_value").unwrap().values(),
9956            &[
9957                Scalar::Int64(20),
9958                Scalar::Int64(20),
9959                Scalar::Int64(10),
9960                Scalar::Int64(21),
9961                Scalar::Int64(21),
9962            ]
9963        );
9964        assert_eq!(
9965            merged.columns.get("right_value").unwrap().values(),
9966            &[
9967                Scalar::Int64(200),
9968                Scalar::Int64(201),
9969                Scalar::Int64(100),
9970                Scalar::Int64(200),
9971                Scalar::Int64(201),
9972            ]
9973        );
9974    }
9975
9976    #[test]
9977    fn merge_inner_wide_sparse_int64_hash_matches_generic_validated_route() {
9978        let stride = 1_i64 << 30;
9979        let left = DataFrame::from_dict(
9980            &["id", "left_value"],
9981            vec![
9982                (
9983                    "id",
9984                    vec![3, 1, 3, 0, 2]
9985                        .into_iter()
9986                        .map(|v| Scalar::Int64(v * stride))
9987                        .collect(),
9988                ),
9989                (
9990                    "left_value",
9991                    vec![
9992                        Scalar::Int64(10),
9993                        Scalar::Int64(11),
9994                        Scalar::Int64(12),
9995                        Scalar::Int64(13),
9996                        Scalar::Int64(14),
9997                    ],
9998                ),
9999            ],
10000        )
10001        .unwrap();
10002        let right = DataFrame::from_dict(
10003            &["id", "right_value"],
10004            vec![
10005                (
10006                    "id",
10007                    vec![3, 2, 3, 1]
10008                        .into_iter()
10009                        .map(|v| Scalar::Int64(v * stride))
10010                        .collect(),
10011                ),
10012                (
10013                    "right_value",
10014                    vec![
10015                        Scalar::Int64(100),
10016                        Scalar::Int64(101),
10017                        Scalar::Int64(102),
10018                        Scalar::Int64(103),
10019                    ],
10020                ),
10021            ],
10022        )
10023        .unwrap();
10024
10025        let fast = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
10026        let generic = merge_dataframes_on_with_options(
10027            &left,
10028            &right,
10029            &["id"],
10030            &["id"],
10031            JoinType::Inner,
10032            MergeExecutionOptions {
10033                validate_mode: Some(MergeValidateMode::ManyToMany),
10034                ..MergeExecutionOptions::default()
10035            },
10036        )
10037        .unwrap();
10038
10039        assert_eq!(fast.index, generic.index);
10040        assert_eq!(fast.column_order, generic.column_order);
10041        assert_eq!(fast.columns, generic.columns);
10042        assert_eq!(
10043            fast.columns.get("id").unwrap().values(),
10044            &[
10045                Scalar::Int64(3 * stride),
10046                Scalar::Int64(3 * stride),
10047                Scalar::Int64(stride),
10048                Scalar::Int64(3 * stride),
10049                Scalar::Int64(3 * stride),
10050                Scalar::Int64(2 * stride),
10051            ]
10052        );
10053        assert_eq!(
10054            fast.columns.get("left_value").unwrap().values(),
10055            &[
10056                Scalar::Int64(10),
10057                Scalar::Int64(10),
10058                Scalar::Int64(11),
10059                Scalar::Int64(12),
10060                Scalar::Int64(12),
10061                Scalar::Int64(14),
10062            ]
10063        );
10064        assert_eq!(
10065            fast.columns.get("right_value").unwrap().values(),
10066            &[
10067                Scalar::Int64(100),
10068                Scalar::Int64(102),
10069                Scalar::Int64(103),
10070                Scalar::Int64(100),
10071                Scalar::Int64(102),
10072                Scalar::Int64(101),
10073            ]
10074        );
10075    }
10076
10077    #[test]
10078    fn dense_i64_inner_parallel_output_data_preserves_row_major_order() {
10079        let left_keys = vec![-1, 2, 1, 2, 3, 9];
10080        let min = 1;
10081        let max = 3;
10082        let offsets = vec![0, 2, 3, 5];
10083        let positions = vec![1usize, 4, 0, 2, 3];
10084        let left_values = vec![10, 20, 30, 40, 50, 60];
10085        let right_values = vec![100, 101, 102, 103, 104];
10086        let specs = vec![
10087            FusedInt64OutputColumn {
10088                name: "left".to_string(),
10089                side: FusedInt64Side::Left,
10090                values: &left_values,
10091            },
10092            FusedInt64OutputColumn {
10093                name: "right".to_string(),
10094                side: FusedInt64Side::Right,
10095                values: &right_values,
10096            },
10097        ];
10098
10099        let plan = DenseI64InnerOutputPlan {
10100            left_keys: &left_keys,
10101            min,
10102            max,
10103            offsets: &offsets,
10104            positions: &positions,
10105            output_len: 6,
10106        };
10107        let actual = build_dense_i64_inner_output_data(&specs, &plan);
10108
10109        // 4 matched left rows -> 6 output rows: avg fanout < 2, so the left
10110        // lane stays fully materialized alongside the right lane.
10111        assert_eq!(lane_expanded(&actual[0]), vec![20, 30, 30, 40, 50, 50]);
10112        assert_eq!(
10113            lane_expanded(&actual[1]),
10114            vec![100, 101, 104, 100, 102, 103]
10115        );
10116        assert!(matches!(actual[0], DenseI64LaneData::Full(_)));
10117        assert!(matches!(actual[1], DenseI64LaneData::Full(_)));
10118    }
10119
10120    fn lane_expanded(lane: &DenseI64LaneData) -> Vec<i64> {
10121        match lane {
10122            DenseI64LaneData::RepeatRunLengths { values, run_lens } => {
10123                let mut out = Vec::new();
10124                for (&value, &run_len) in values.iter().zip(run_lens.iter()) {
10125                    out.resize(out.len() + run_len, value);
10126                }
10127                out
10128            }
10129            DenseI64LaneData::RepeatedSlices { data, segments } => {
10130                let mut out = Vec::new();
10131                for &(start, len) in segments.iter() {
10132                    out.extend_from_slice(&data[start..start + len]);
10133                }
10134                out
10135            }
10136            DenseI64LaneData::Full(data) => data.clone(),
10137        }
10138    }
10139
10140    #[test]
10141    fn dense_i64_inner_high_fanout_emits_repeat_run_left_lanes() {
10142        // 2 matched left rows, each matching 3 right rows -> avg fanout 3:
10143        // left lane must come back as repeat runs and the right lane as
10144        // repeated slices. Their expansion equals the old full fill.
10145        let left_keys = vec![1, 7, 2];
10146        let min = 1;
10147        let max = 2;
10148        let offsets = vec![0, 3, 6];
10149        let positions = vec![0usize, 2, 4, 1, 3, 5];
10150        let left_values = vec![10, 20, 30];
10151        let right_values = vec![100, 101, 102, 103, 104, 105];
10152        let specs = vec![
10153            FusedInt64OutputColumn {
10154                name: "left".to_string(),
10155                side: FusedInt64Side::Left,
10156                values: &left_values,
10157            },
10158            FusedInt64OutputColumn {
10159                name: "right".to_string(),
10160                side: FusedInt64Side::Right,
10161                values: &right_values,
10162            },
10163        ];
10164
10165        let plan = DenseI64InnerOutputPlan {
10166            left_keys: &left_keys,
10167            min,
10168            max,
10169            offsets: &offsets,
10170            positions: &positions,
10171            output_len: 6,
10172        };
10173        let actual = build_dense_i64_inner_output_data(&specs, &plan);
10174
10175        assert!(matches!(
10176            actual[0],
10177            DenseI64LaneData::RepeatRunLengths { .. }
10178        ));
10179        assert!(matches!(actual[1], DenseI64LaneData::RepeatedSlices { .. }));
10180        assert_eq!(lane_expanded(&actual[0]), vec![10, 10, 10, 30, 30, 30]);
10181        assert_eq!(
10182            lane_expanded(&actual[1]),
10183            vec![100, 102, 104, 101, 103, 105]
10184        );
10185
10186        // The lazy Column built from shared run lengths is indistinguishable
10187        // from the eagerly materialized one (values, slice view, length,
10188        // equality).
10189        let lazy = fp_columnar::Column::from_i64_repeat_values_run_lengths(
10190            vec![10, 30],
10191            std::sync::Arc::from([3usize, 3]),
10192        );
10193        let eager = fp_columnar::Column::from_i64_values(vec![10, 10, 10, 30, 30, 30]);
10194        assert_eq!(lazy.len(), eager.len());
10195        assert_eq!(lazy.as_i64_slice(), eager.as_i64_slice());
10196        assert_eq!(lazy.values(), eager.values());
10197        assert_eq!(lazy, eager);
10198    }
10199
10200    #[test]
10201    fn dense_cycle_left_join_output_matches_dense_left_builder() {
10202        let left = DataFrame::from_dict(
10203            &["id", "v"],
10204            vec![
10205                (
10206                    "id",
10207                    vec![
10208                        Scalar::Int64(0),
10209                        Scalar::Int64(1),
10210                        Scalar::Int64(2),
10211                        Scalar::Int64(0),
10212                        Scalar::Int64(1),
10213                        Scalar::Int64(2),
10214                        Scalar::Int64(0),
10215                    ],
10216                ),
10217                (
10218                    "v",
10219                    vec![
10220                        Scalar::Int64(10),
10221                        Scalar::Int64(11),
10222                        Scalar::Int64(12),
10223                        Scalar::Int64(13),
10224                        Scalar::Int64(14),
10225                        Scalar::Int64(15),
10226                        Scalar::Int64(16),
10227                    ],
10228                ),
10229            ],
10230        )
10231        .unwrap();
10232        let right = DataFrame::from_dict(
10233            &["id", "rv"],
10234            vec![
10235                (
10236                    "id",
10237                    vec![
10238                        Scalar::Int64(1),
10239                        Scalar::Int64(2),
10240                        Scalar::Int64(1),
10241                        Scalar::Int64(2),
10242                    ],
10243                ),
10244                (
10245                    "rv",
10246                    vec![
10247                        Scalar::Int64(100),
10248                        Scalar::Int64(200),
10249                        Scalar::Int64(101),
10250                        Scalar::Int64(201),
10251                    ],
10252                ),
10253            ],
10254        )
10255        .unwrap();
10256        let suffixes = ResolvedMergeSuffixes::default();
10257        let left_key = left.column("id").unwrap();
10258        let right_key = right.column("id").unwrap();
10259
10260        let fast = build_single_key_dense_cycle_i64_left_merge_output(
10261            &left,
10262            &right,
10263            &["id"],
10264            &["id"],
10265            left_key,
10266            right_key,
10267            &suffixes,
10268        )
10269        .unwrap()
10270        .expect("dense-cycle route");
10271        let old = build_single_key_dense_i64_left_merge_output(
10272            &left,
10273            &right,
10274            &["id"],
10275            &["id"],
10276            left_key,
10277            right_key,
10278            &suffixes,
10279        )
10280        .unwrap()
10281        .expect("dense left route");
10282
10283        assert_eq!(fast.index, old.index);
10284        assert_eq!(fast.column_order, old.column_order);
10285        assert_eq!(fast.columns, old.columns);
10286        assert_eq!(
10287            fast.columns.get("v").unwrap().as_i64_slice(),
10288            old.columns.get("v").unwrap().as_i64_slice()
10289        );
10290        assert_eq!(
10291            fast.columns.get("rv").unwrap().values(),
10292            &[
10293                Scalar::Null(NullKind::Null),
10294                Scalar::Int64(100),
10295                Scalar::Int64(101),
10296                Scalar::Int64(200),
10297                Scalar::Int64(201),
10298                Scalar::Null(NullKind::Null),
10299                Scalar::Int64(100),
10300                Scalar::Int64(101),
10301                Scalar::Int64(200),
10302                Scalar::Int64(201),
10303                Scalar::Null(NullKind::Null),
10304            ]
10305        );
10306    }
10307
10308    #[test]
10309    fn merge_inner_ordered_identity_matches_generic_validated_route() {
10310        let left = DataFrame::from_dict(
10311            &["id", "v"],
10312            vec![
10313                (
10314                    "id",
10315                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
10316                ),
10317                (
10318                    "v",
10319                    vec![
10320                        Scalar::Int64(10),
10321                        Scalar::Null(NullKind::Null),
10322                        Scalar::Int64(30),
10323                    ],
10324                ),
10325            ],
10326        )
10327        .unwrap();
10328        let right = DataFrame::from_dict(
10329            &["id", "w"],
10330            vec![
10331                (
10332                    "id",
10333                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
10334                ),
10335                (
10336                    "w",
10337                    vec![Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(300)],
10338                ),
10339            ],
10340        )
10341        .unwrap();
10342
10343        let fast = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
10344        let generic = merge_dataframes_on_with_options(
10345            &left,
10346            &right,
10347            &["id"],
10348            &["id"],
10349            JoinType::Inner,
10350            MergeExecutionOptions {
10351                validate_mode: Some(MergeValidateMode::OneToOne),
10352                ..MergeExecutionOptions::default()
10353            },
10354        )
10355        .unwrap();
10356
10357        assert_eq!(fast.index, generic.index);
10358        assert_eq!(fast.column_order, generic.column_order);
10359        assert_eq!(fast.columns, generic.columns);
10360    }
10361
10362    #[test]
10363    fn merge_inner_dense_int64_fused_materialization_matches_generic_route() {
10364        let left = DataFrame::from_dict(
10365            &["id", "v", "overlap"],
10366            vec![
10367                (
10368                    "id",
10369                    vec![
10370                        Scalar::Int64(2),
10371                        Scalar::Int64(1),
10372                        Scalar::Int64(2),
10373                        Scalar::Int64(3),
10374                    ],
10375                ),
10376                (
10377                    "v",
10378                    vec![
10379                        Scalar::Int64(20),
10380                        Scalar::Int64(10),
10381                        Scalar::Int64(21),
10382                        Scalar::Int64(30),
10383                    ],
10384                ),
10385                (
10386                    "overlap",
10387                    vec![
10388                        Scalar::Int64(200),
10389                        Scalar::Int64(100),
10390                        Scalar::Int64(201),
10391                        Scalar::Int64(300),
10392                    ],
10393                ),
10394            ],
10395        )
10396        .unwrap();
10397        let right = DataFrame::from_dict(
10398            &["id", "w", "overlap"],
10399            vec![
10400                (
10401                    "id",
10402                    vec![
10403                        Scalar::Int64(2),
10404                        Scalar::Int64(2),
10405                        Scalar::Int64(1),
10406                        Scalar::Int64(4),
10407                    ],
10408                ),
10409                (
10410                    "w",
10411                    vec![
10412                        Scalar::Int64(2000),
10413                        Scalar::Int64(2001),
10414                        Scalar::Int64(1000),
10415                        Scalar::Int64(4000),
10416                    ],
10417                ),
10418                (
10419                    "overlap",
10420                    vec![
10421                        Scalar::Int64(20_000),
10422                        Scalar::Int64(20_001),
10423                        Scalar::Int64(10_000),
10424                        Scalar::Int64(40_000),
10425                    ],
10426                ),
10427            ],
10428        )
10429        .unwrap();
10430
10431        let fast = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
10432        let generic = merge_dataframes_on_with_options(
10433            &left,
10434            &right,
10435            &["id"],
10436            &["id"],
10437            JoinType::Inner,
10438            MergeExecutionOptions {
10439                validate_mode: Some(MergeValidateMode::ManyToMany),
10440                ..MergeExecutionOptions::default()
10441            },
10442        )
10443        .unwrap();
10444
10445        assert_eq!(fast.index, generic.index);
10446        assert_eq!(fast.column_order, generic.column_order);
10447        assert_eq!(fast.columns, generic.columns);
10448        assert_eq!(
10449            fast.column_order,
10450            ["id", "v", "overlap_x", "w", "overlap_y"]
10451        );
10452        assert_eq!(
10453            fast.columns.get("id").unwrap().values(),
10454            &[
10455                Scalar::Int64(2),
10456                Scalar::Int64(2),
10457                Scalar::Int64(1),
10458                Scalar::Int64(2),
10459                Scalar::Int64(2),
10460            ]
10461        );
10462        assert_eq!(
10463            fast.columns.get("w").unwrap().values(),
10464            &[
10465                Scalar::Int64(2000),
10466                Scalar::Int64(2001),
10467                Scalar::Int64(1000),
10468                Scalar::Int64(2000),
10469                Scalar::Int64(2001),
10470            ]
10471        );
10472        assert!(
10473            fast.columns
10474                .values()
10475                .all(|column| column.as_i64_slice().is_some())
10476        );
10477    }
10478
10479    #[test]
10480    fn merge_inner_ordered_unique_int64_subset_matches_generic_validated_route() {
10481        let left = DataFrame::from_dict(
10482            &["id", "v"],
10483            vec![
10484                (
10485                    "id",
10486                    vec![
10487                        Scalar::Int64(0),
10488                        Scalar::Int64(1),
10489                        Scalar::Int64(2),
10490                        Scalar::Int64(3),
10491                        Scalar::Int64(4),
10492                    ],
10493                ),
10494                (
10495                    "v",
10496                    vec![
10497                        Scalar::Int64(10),
10498                        Scalar::Int64(11),
10499                        Scalar::Int64(12),
10500                        Scalar::Int64(13),
10501                        Scalar::Int64(14),
10502                    ],
10503                ),
10504            ],
10505        )
10506        .unwrap();
10507        let right = DataFrame::from_dict(
10508            &["id", "w"],
10509            vec![
10510                (
10511                    "id",
10512                    vec![
10513                        Scalar::Int64(0),
10514                        Scalar::Int64(2),
10515                        Scalar::Int64(4),
10516                        Scalar::Int64(6),
10517                    ],
10518                ),
10519                (
10520                    "w",
10521                    vec![
10522                        Scalar::Int64(100),
10523                        Scalar::Int64(200),
10524                        Scalar::Int64(300),
10525                        Scalar::Int64(400),
10526                    ],
10527                ),
10528            ],
10529        )
10530        .unwrap();
10531
10532        let fast = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
10533        let generic = merge_dataframes_on_with_options(
10534            &left,
10535            &right,
10536            &["id"],
10537            &["id"],
10538            JoinType::Inner,
10539            MergeExecutionOptions {
10540                validate_mode: Some(MergeValidateMode::OneToOne),
10541                ..MergeExecutionOptions::default()
10542            },
10543        )
10544        .unwrap();
10545
10546        assert_eq!(fast.index, generic.index);
10547        assert_eq!(fast.column_order, generic.column_order);
10548        assert_eq!(fast.columns, generic.columns);
10549        assert_eq!(
10550            fast.columns.get("id").unwrap().values(),
10551            &[Scalar::Int64(0), Scalar::Int64(2), Scalar::Int64(4)]
10552        );
10553        assert_eq!(
10554            fast.columns.get("v").unwrap().values(),
10555            &[Scalar::Int64(10), Scalar::Int64(12), Scalar::Int64(14)]
10556        );
10557        assert_eq!(
10558            fast.columns.get("w").unwrap().values(),
10559            &[Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(300)]
10560        );
10561    }
10562
10563    #[test]
10564    fn merge_inner_ordered_identity_falls_back_for_non_identity_keys() {
10565        let cases = [
10566            (
10567                vec![Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(4)],
10568                vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
10569            ),
10570            (
10571                vec![
10572                    Scalar::Int64(1),
10573                    Scalar::Null(NullKind::Null),
10574                    Scalar::Int64(3),
10575                ],
10576                vec![
10577                    Scalar::Int64(1),
10578                    Scalar::Null(NullKind::Null),
10579                    Scalar::Int64(3),
10580                ],
10581            ),
10582        ];
10583
10584        for (left_keys, right_keys) in cases {
10585            let left = DataFrame::from_dict(
10586                &["id", "v"],
10587                vec![
10588                    ("id", left_keys),
10589                    (
10590                        "v",
10591                        vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
10592                    ),
10593                ],
10594            )
10595            .unwrap();
10596            let right = DataFrame::from_dict(
10597                &["id", "w"],
10598                vec![
10599                    ("id", right_keys),
10600                    (
10601                        "w",
10602                        vec![Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(300)],
10603                    ),
10604                ],
10605            )
10606            .unwrap();
10607
10608            let maybe_fast = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
10609            let generic = merge_dataframes_on_with_options(
10610                &left,
10611                &right,
10612                &["id"],
10613                &["id"],
10614                JoinType::Inner,
10615                MergeExecutionOptions {
10616                    validate_mode: Some(MergeValidateMode::OneToOne),
10617                    ..MergeExecutionOptions::default()
10618                },
10619            )
10620            .unwrap();
10621
10622            assert_eq!(maybe_fast.index, generic.index);
10623            assert_eq!(maybe_fast.column_order, generic.column_order);
10624            assert_eq!(maybe_fast.columns, generic.columns);
10625        }
10626    }
10627
10628    #[test]
10629    fn merge_default_suffixes_match_pandas() {
10630        // Overlapping non-key column "v" gets pandas default _x/_y suffixes.
10631        // Verified vs pandas 2.2.3: left{k:[1,2,3],v:[10,20,30]} merged inner on
10632        // k with right{k:[2,3,4],v:[200,300,400]} -> cols [k,v_x,v_y],
10633        // k=[2,3], v_x=[20,30], v_y=[200,300].
10634        let idx: Vec<_> = (0..3).map(|i| (i as i64).into()).collect();
10635        let left = fp_frame::DataFrame::from_series(vec![
10636            fp_frame::Series::from_values(
10637                "k",
10638                idx.clone(),
10639                vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
10640            )
10641            .unwrap(),
10642            fp_frame::Series::from_values(
10643                "v",
10644                idx.clone(),
10645                vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
10646            )
10647            .unwrap(),
10648        ])
10649        .unwrap();
10650        let right = fp_frame::DataFrame::from_series(vec![
10651            fp_frame::Series::from_values(
10652                "k",
10653                idx.clone(),
10654                vec![Scalar::Int64(2), Scalar::Int64(3), Scalar::Int64(4)],
10655            )
10656            .unwrap(),
10657            fp_frame::Series::from_values(
10658                "v",
10659                idx,
10660                vec![Scalar::Int64(200), Scalar::Int64(300), Scalar::Int64(400)],
10661            )
10662            .unwrap(),
10663        ])
10664        .unwrap();
10665        let merged = merge_dataframes(&left, &right, "k", JoinType::Inner).unwrap();
10666
10667        assert_eq!(
10668            merged.columns.get("k").unwrap().values(),
10669            &[Scalar::Int64(2), Scalar::Int64(3)],
10670            "k"
10671        );
10672        assert_eq!(
10673            merged.columns.get("v_x").unwrap().values(),
10674            &[Scalar::Int64(20), Scalar::Int64(30)],
10675            "v_x"
10676        );
10677        assert_eq!(
10678            merged.columns.get("v_y").unwrap().values(),
10679            &[Scalar::Int64(200), Scalar::Int64(300)],
10680            "v_y"
10681        );
10682        assert!(
10683            !merged.columns.contains_key("v"),
10684            "bare 'v' should be suffixed away"
10685        );
10686    }
10687
10688    #[test]
10689    fn merge_left_preserves_all_left_rows() {
10690        let left = make_left_df();
10691        let right = make_right_df();
10692        let merged = merge_dataframes(&left, &right, "id", JoinType::Left).unwrap();
10693
10694        assert_eq!(merged.columns.get("id").unwrap().len(), 3);
10695        assert_eq!(
10696            merged.columns.get("val_a").unwrap().values(),
10697            &[Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)]
10698        );
10699        // val_b: null for id=1, 200 for id=2, 300 for id=3
10700        assert!(merged.columns.get("val_b").unwrap().values()[0].is_missing());
10701        assert_eq!(
10702            merged.columns.get("val_b").unwrap().values()[1],
10703            Scalar::Int64(200)
10704        );
10705        assert_eq!(
10706            merged.columns.get("val_b").unwrap().values()[2],
10707            Scalar::Int64(300)
10708        );
10709    }
10710
10711    #[test]
10712    fn merge_left_ordered_unique_int64_subset_matches_generic_validated_route() {
10713        let left = DataFrame::from_dict(
10714            &["id", "v"],
10715            vec![
10716                (
10717                    "id",
10718                    vec![
10719                        Scalar::Int64(0),
10720                        Scalar::Int64(1),
10721                        Scalar::Int64(2),
10722                        Scalar::Int64(3),
10723                        Scalar::Int64(4),
10724                    ],
10725                ),
10726                (
10727                    "v",
10728                    vec![
10729                        Scalar::Int64(10),
10730                        Scalar::Int64(11),
10731                        Scalar::Int64(12),
10732                        Scalar::Int64(13),
10733                        Scalar::Int64(14),
10734                    ],
10735                ),
10736            ],
10737        )
10738        .unwrap();
10739        let right = DataFrame::from_dict(
10740            &["id", "w"],
10741            vec![
10742                (
10743                    "id",
10744                    vec![
10745                        Scalar::Int64(0),
10746                        Scalar::Int64(2),
10747                        Scalar::Int64(4),
10748                        Scalar::Int64(6),
10749                    ],
10750                ),
10751                (
10752                    "w",
10753                    vec![
10754                        Scalar::Int64(100),
10755                        Scalar::Int64(200),
10756                        Scalar::Int64(300),
10757                        Scalar::Int64(400),
10758                    ],
10759                ),
10760            ],
10761        )
10762        .unwrap();
10763
10764        let fast = merge_dataframes(&left, &right, "id", JoinType::Left).unwrap();
10765        let generic = merge_dataframes_on_with_options(
10766            &left,
10767            &right,
10768            &["id"],
10769            &["id"],
10770            JoinType::Left,
10771            MergeExecutionOptions {
10772                validate_mode: Some(MergeValidateMode::OneToOne),
10773                ..MergeExecutionOptions::default()
10774            },
10775        )
10776        .unwrap();
10777
10778        assert_eq!(fast.index, generic.index);
10779        assert_eq!(fast.column_order, generic.column_order);
10780        assert_eq!(fast.columns, generic.columns);
10781        assert_eq!(
10782            fast.columns.get("id").unwrap().values(),
10783            &[
10784                Scalar::Int64(0),
10785                Scalar::Int64(1),
10786                Scalar::Int64(2),
10787                Scalar::Int64(3),
10788                Scalar::Int64(4)
10789            ]
10790        );
10791        let right_values = fast.columns.get("w").unwrap().values();
10792        assert_eq!(right_values[0], Scalar::Int64(100));
10793        assert!(right_values[1].is_missing());
10794        assert_eq!(right_values[2], Scalar::Int64(200));
10795        assert!(right_values[3].is_missing());
10796        assert_eq!(right_values[4], Scalar::Int64(300));
10797    }
10798
10799    #[test]
10800    fn merge_left_dense_int64_duplicates_matches_generic_validated_route() {
10801        let left = DataFrame::from_dict(
10802            &["id", "v"],
10803            vec![
10804                (
10805                    "id",
10806                    vec![
10807                        Scalar::Int64(2),
10808                        Scalar::Int64(0),
10809                        Scalar::Int64(2),
10810                        Scalar::Int64(1),
10811                        Scalar::Int64(5),
10812                    ],
10813                ),
10814                (
10815                    "v",
10816                    vec![
10817                        Scalar::Int64(10),
10818                        Scalar::Int64(11),
10819                        Scalar::Int64(12),
10820                        Scalar::Int64(13),
10821                        Scalar::Int64(15),
10822                    ],
10823                ),
10824            ],
10825        )
10826        .unwrap();
10827        let right = DataFrame::from_dict(
10828            &["id", "w"],
10829            vec![
10830                (
10831                    "id",
10832                    vec![
10833                        Scalar::Int64(2),
10834                        Scalar::Int64(2),
10835                        Scalar::Int64(3),
10836                        Scalar::Int64(0),
10837                    ],
10838                ),
10839                (
10840                    "w",
10841                    vec![
10842                        Scalar::Int64(200),
10843                        Scalar::Int64(201),
10844                        Scalar::Int64(300),
10845                        Scalar::Int64(400),
10846                    ],
10847                ),
10848            ],
10849        )
10850        .unwrap();
10851
10852        let fast = merge_dataframes(&left, &right, "id", JoinType::Left).unwrap();
10853        let generic = merge_dataframes_on_with_options(
10854            &left,
10855            &right,
10856            &["id"],
10857            &["id"],
10858            JoinType::Left,
10859            MergeExecutionOptions {
10860                validate_mode: Some(MergeValidateMode::ManyToMany),
10861                ..MergeExecutionOptions::default()
10862            },
10863        )
10864        .unwrap();
10865
10866        assert_eq!(fast.index, generic.index);
10867        assert_eq!(fast.column_order, generic.column_order);
10868        assert_eq!(fast.columns, generic.columns);
10869        assert_eq!(
10870            fast.columns.get("id").unwrap().values(),
10871            &[
10872                Scalar::Int64(2),
10873                Scalar::Int64(2),
10874                Scalar::Int64(0),
10875                Scalar::Int64(2),
10876                Scalar::Int64(2),
10877                Scalar::Int64(1),
10878                Scalar::Int64(5),
10879            ]
10880        );
10881        let left_values = fast.columns.get("v").unwrap().values();
10882        assert_eq!(left_values[0], Scalar::Int64(10));
10883        assert_eq!(left_values[1], Scalar::Int64(10));
10884        assert_eq!(left_values[2], Scalar::Int64(11));
10885        assert_eq!(left_values[4], Scalar::Int64(12));
10886        assert_eq!(left_values[6], Scalar::Int64(15));
10887        let right_values = fast.columns.get("w").unwrap().values();
10888        assert_eq!(right_values[0], Scalar::Int64(200));
10889        assert_eq!(right_values[1], Scalar::Int64(201));
10890        assert_eq!(right_values[2], Scalar::Int64(400));
10891        assert!(right_values[5].is_missing());
10892        assert!(right_values[6].is_missing());
10893    }
10894
10895    #[test]
10896    fn merge_left_dense_cycle_probe_output_matches_materialized_positions_yq96z() {
10897        let left = DataFrame::from_dict(
10898            &["id", "v"],
10899            vec![
10900                (
10901                    "id",
10902                    vec![
10903                        Scalar::Int64(0),
10904                        Scalar::Int64(1),
10905                        Scalar::Int64(2),
10906                        Scalar::Int64(0),
10907                        Scalar::Int64(1),
10908                    ],
10909                ),
10910                (
10911                    "v",
10912                    vec![
10913                        Scalar::Int64(10),
10914                        Scalar::Int64(11),
10915                        Scalar::Int64(12),
10916                        Scalar::Int64(13),
10917                        Scalar::Int64(14),
10918                    ],
10919                ),
10920            ],
10921        )
10922        .unwrap();
10923        let right = DataFrame::from_dict(
10924            &["id", "w"],
10925            vec![
10926                (
10927                    "id",
10928                    vec![
10929                        Scalar::Int64(1),
10930                        Scalar::Int64(2),
10931                        Scalar::Int64(1),
10932                        Scalar::Int64(2),
10933                    ],
10934                ),
10935                (
10936                    "w",
10937                    vec![
10938                        Scalar::Int64(100),
10939                        Scalar::Int64(200),
10940                        Scalar::Int64(101),
10941                        Scalar::Int64(201),
10942                    ],
10943                ),
10944            ],
10945        )
10946        .unwrap();
10947        let left_key = left.columns().get("id").unwrap();
10948        let right_key = right.columns().get("id").unwrap();
10949        assert!(left_key.int64_dense_cycle_witness().is_some());
10950        assert!(right_key.int64_dense_cycle_witness().is_some());
10951        let suffixes = resolve_merge_suffixes(None);
10952
10953        let fused = build_single_key_dense_i64_left_merge_output(
10954            &left,
10955            &right,
10956            &["id"],
10957            &["id"],
10958            left_key,
10959            right_key,
10960            &suffixes,
10961        )
10962        .unwrap()
10963        .expect("dense-cycle left route should accept");
10964        let (left_positions, right_positions) =
10965            dense_int64_left_positions(left_key, right_key).unwrap();
10966        let materialized = build_single_key_dense_left_merge_output(
10967            &left,
10968            &right,
10969            &["id"],
10970            &["id"],
10971            &left_positions,
10972            &right_positions,
10973            &suffixes,
10974        )
10975        .unwrap();
10976
10977        assert_eq!(fused.index, materialized.index);
10978        assert_eq!(fused.column_order, materialized.column_order);
10979        assert_eq!(fused.columns, materialized.columns);
10980        assert_eq!(
10981            fused.columns.get("w").unwrap().values(),
10982            &[
10983                Scalar::Null(NullKind::Null),
10984                Scalar::Int64(100),
10985                Scalar::Int64(101),
10986                Scalar::Int64(200),
10987                Scalar::Int64(201),
10988                Scalar::Null(NullKind::Null),
10989                Scalar::Int64(100),
10990                Scalar::Int64(101),
10991            ]
10992        );
10993    }
10994
10995    #[test]
10996    fn merge_left_all_matched_dense_int64_fused_output_matches_sorted_generic_route() {
10997        let left = DataFrame::from_dict(
10998            &["id", "v"],
10999            vec![
11000                (
11001                    "id",
11002                    vec![
11003                        Scalar::Int64(0),
11004                        Scalar::Int64(0),
11005                        Scalar::Int64(1),
11006                        Scalar::Int64(1),
11007                        Scalar::Int64(2),
11008                    ],
11009                ),
11010                (
11011                    "v",
11012                    vec![
11013                        Scalar::Int64(10),
11014                        Scalar::Int64(11),
11015                        Scalar::Int64(20),
11016                        Scalar::Int64(21),
11017                        Scalar::Int64(30),
11018                    ],
11019                ),
11020            ],
11021        )
11022        .unwrap();
11023        let right = DataFrame::from_dict(
11024            &["id", "w"],
11025            vec![
11026                (
11027                    "id",
11028                    vec![
11029                        Scalar::Int64(0),
11030                        Scalar::Int64(0),
11031                        Scalar::Int64(1),
11032                        Scalar::Int64(2),
11033                        Scalar::Int64(2),
11034                    ],
11035                ),
11036                (
11037                    "w",
11038                    vec![
11039                        Scalar::Int64(100),
11040                        Scalar::Int64(101),
11041                        Scalar::Int64(200),
11042                        Scalar::Int64(300),
11043                        Scalar::Int64(301),
11044                    ],
11045                ),
11046            ],
11047        )
11048        .unwrap();
11049
11050        let fast = merge_dataframes(&left, &right, "id", JoinType::Left).unwrap();
11051        let generic = merge_dataframes_on_with_options(
11052            &left,
11053            &right,
11054            &["id"],
11055            &["id"],
11056            JoinType::Left,
11057            MergeExecutionOptions {
11058                sort: true,
11059                ..MergeExecutionOptions::default()
11060            },
11061        )
11062        .unwrap();
11063
11064        assert_eq!(fast.index, generic.index);
11065        assert_eq!(fast.column_order, generic.column_order);
11066        assert_eq!(fast.columns, generic.columns);
11067        assert_eq!(
11068            fast.columns.get("id").unwrap().values(),
11069            &[
11070                Scalar::Int64(0),
11071                Scalar::Int64(0),
11072                Scalar::Int64(0),
11073                Scalar::Int64(0),
11074                Scalar::Int64(1),
11075                Scalar::Int64(1),
11076                Scalar::Int64(2),
11077                Scalar::Int64(2),
11078            ]
11079        );
11080        assert_eq!(
11081            fast.columns.get("v").unwrap().values(),
11082            &[
11083                Scalar::Int64(10),
11084                Scalar::Int64(10),
11085                Scalar::Int64(11),
11086                Scalar::Int64(11),
11087                Scalar::Int64(20),
11088                Scalar::Int64(21),
11089                Scalar::Int64(30),
11090                Scalar::Int64(30),
11091            ]
11092        );
11093        assert_eq!(
11094            fast.columns.get("w").unwrap().values(),
11095            &[
11096                Scalar::Int64(100),
11097                Scalar::Int64(101),
11098                Scalar::Int64(100),
11099                Scalar::Int64(101),
11100                Scalar::Int64(200),
11101                Scalar::Int64(200),
11102                Scalar::Int64(300),
11103                Scalar::Int64(301),
11104            ]
11105        );
11106    }
11107
11108    #[test]
11109    fn merge_outer_ordered_unique_int64_subset_matches_generic_validated_route() {
11110        let left = DataFrame::from_dict(
11111            &["id", "v"],
11112            vec![
11113                (
11114                    "id",
11115                    vec![Scalar::Int64(0), Scalar::Int64(1), Scalar::Int64(3)],
11116                ),
11117                (
11118                    "v",
11119                    vec![Scalar::Int64(10), Scalar::Int64(11), Scalar::Int64(13)],
11120                ),
11121            ],
11122        )
11123        .unwrap();
11124        let right = DataFrame::from_dict(
11125            &["id", "w"],
11126            vec![
11127                (
11128                    "id",
11129                    vec![
11130                        Scalar::Int64(0),
11131                        Scalar::Int64(2),
11132                        Scalar::Int64(3),
11133                        Scalar::Int64(5),
11134                    ],
11135                ),
11136                (
11137                    "w",
11138                    vec![
11139                        Scalar::Int64(100),
11140                        Scalar::Int64(200),
11141                        Scalar::Int64(300),
11142                        Scalar::Int64(500),
11143                    ],
11144                ),
11145            ],
11146        )
11147        .unwrap();
11148
11149        let fast = merge_dataframes(&left, &right, "id", JoinType::Outer).unwrap();
11150        let generic = merge_dataframes_on_with_options(
11151            &left,
11152            &right,
11153            &["id"],
11154            &["id"],
11155            JoinType::Outer,
11156            MergeExecutionOptions {
11157                validate_mode: Some(MergeValidateMode::OneToOne),
11158                ..MergeExecutionOptions::default()
11159            },
11160        )
11161        .unwrap();
11162
11163        assert_eq!(fast.index, generic.index);
11164        assert_eq!(fast.column_order, generic.column_order);
11165        assert_eq!(fast.columns, generic.columns);
11166        assert_eq!(
11167            fast.columns.get("id").unwrap().values(),
11168            &[
11169                Scalar::Int64(0),
11170                Scalar::Int64(1),
11171                Scalar::Int64(2),
11172                Scalar::Int64(3),
11173                Scalar::Int64(5)
11174            ]
11175        );
11176        let left_values = fast.columns.get("v").unwrap().values();
11177        assert_eq!(left_values[0], Scalar::Float64(10.0));
11178        assert_eq!(left_values[1], Scalar::Float64(11.0));
11179        assert!(left_values[2].is_missing());
11180        assert_eq!(left_values[3], Scalar::Float64(13.0));
11181        assert!(left_values[4].is_missing());
11182        let right_values = fast.columns.get("w").unwrap().values();
11183        assert_eq!(right_values[0], Scalar::Float64(100.0));
11184        assert!(right_values[1].is_missing());
11185        assert_eq!(right_values[2], Scalar::Float64(200.0));
11186        assert_eq!(right_values[3], Scalar::Float64(300.0));
11187        assert_eq!(right_values[4], Scalar::Float64(500.0));
11188    }
11189
11190    #[test]
11191    fn merge_outer_dense_int64_duplicates_matches_generic_validated_route() {
11192        let left = DataFrame::from_dict(
11193            &["id", "v"],
11194            vec![
11195                (
11196                    "id",
11197                    vec![
11198                        Scalar::Int64(2),
11199                        Scalar::Int64(0),
11200                        Scalar::Int64(2),
11201                        Scalar::Int64(1),
11202                        Scalar::Int64(5),
11203                    ],
11204                ),
11205                (
11206                    "v",
11207                    vec![
11208                        Scalar::Int64(10),
11209                        Scalar::Int64(11),
11210                        Scalar::Int64(12),
11211                        Scalar::Int64(13),
11212                        Scalar::Int64(15),
11213                    ],
11214                ),
11215            ],
11216        )
11217        .unwrap();
11218        let right = DataFrame::from_dict(
11219            &["id", "w"],
11220            vec![
11221                (
11222                    "id",
11223                    vec![
11224                        Scalar::Int64(2),
11225                        Scalar::Int64(2),
11226                        Scalar::Int64(3),
11227                        Scalar::Int64(0),
11228                    ],
11229                ),
11230                (
11231                    "w",
11232                    vec![
11233                        Scalar::Int64(200),
11234                        Scalar::Int64(201),
11235                        Scalar::Int64(300),
11236                        Scalar::Int64(400),
11237                    ],
11238                ),
11239            ],
11240        )
11241        .unwrap();
11242
11243        let fast = merge_dataframes(&left, &right, "id", JoinType::Outer).unwrap();
11244        let generic = merge_dataframes_on_with_options(
11245            &left,
11246            &right,
11247            &["id"],
11248            &["id"],
11249            JoinType::Outer,
11250            MergeExecutionOptions {
11251                validate_mode: Some(MergeValidateMode::ManyToMany),
11252                ..MergeExecutionOptions::default()
11253            },
11254        )
11255        .unwrap();
11256
11257        assert_eq!(fast.index, generic.index);
11258        assert_eq!(fast.column_order, generic.column_order);
11259        assert_eq!(fast.columns, generic.columns);
11260        assert_eq!(
11261            fast.columns.get("id").unwrap().values(),
11262            &[
11263                Scalar::Int64(0),
11264                Scalar::Int64(1),
11265                Scalar::Int64(2),
11266                Scalar::Int64(2),
11267                Scalar::Int64(2),
11268                Scalar::Int64(2),
11269                Scalar::Int64(3),
11270                Scalar::Int64(5),
11271            ]
11272        );
11273        let left_values = fast.columns.get("v").unwrap().values();
11274        assert_eq!(left_values[0], Scalar::Float64(11.0));
11275        assert_eq!(left_values[1], Scalar::Float64(13.0));
11276        assert_eq!(left_values[2], Scalar::Float64(10.0));
11277        assert_eq!(left_values[5], Scalar::Float64(12.0));
11278        assert!(left_values[6].is_missing());
11279        assert_eq!(left_values[7], Scalar::Float64(15.0));
11280        let right_values = fast.columns.get("w").unwrap().values();
11281        assert_eq!(right_values[0], Scalar::Float64(400.0));
11282        assert!(right_values[1].is_missing());
11283        assert_eq!(right_values[2], Scalar::Float64(200.0));
11284        assert_eq!(right_values[3], Scalar::Float64(201.0));
11285        assert!(right_values[7].is_missing());
11286    }
11287
11288    #[test]
11289    fn merge_outer_all_matched_dense_int64_duplicates_matches_generic_validated_route() {
11290        let left = DataFrame::from_dict(
11291            &["id", "v"],
11292            vec![
11293                (
11294                    "id",
11295                    vec![
11296                        Scalar::Int64(2),
11297                        Scalar::Int64(1),
11298                        Scalar::Int64(2),
11299                        Scalar::Int64(1),
11300                    ],
11301                ),
11302                (
11303                    "v",
11304                    vec![
11305                        Scalar::Int64(20),
11306                        Scalar::Int64(10),
11307                        Scalar::Int64(21),
11308                        Scalar::Int64(11),
11309                    ],
11310                ),
11311            ],
11312        )
11313        .unwrap();
11314        let right = DataFrame::from_dict(
11315            &["id", "w"],
11316            vec![
11317                (
11318                    "id",
11319                    vec![
11320                        Scalar::Int64(1),
11321                        Scalar::Int64(2),
11322                        Scalar::Int64(1),
11323                        Scalar::Int64(2),
11324                    ],
11325                ),
11326                (
11327                    "w",
11328                    vec![
11329                        Scalar::Int64(100),
11330                        Scalar::Int64(200),
11331                        Scalar::Int64(101),
11332                        Scalar::Int64(201),
11333                    ],
11334                ),
11335            ],
11336        )
11337        .unwrap();
11338
11339        let fast = merge_dataframes(&left, &right, "id", JoinType::Outer).unwrap();
11340        let generic = merge_dataframes_on_with_options(
11341            &left,
11342            &right,
11343            &["id"],
11344            &["id"],
11345            JoinType::Outer,
11346            MergeExecutionOptions {
11347                validate_mode: Some(MergeValidateMode::ManyToMany),
11348                ..MergeExecutionOptions::default()
11349            },
11350        )
11351        .unwrap();
11352
11353        assert_eq!(fast.index, generic.index);
11354        assert_eq!(fast.column_order, generic.column_order);
11355        assert_eq!(fast.columns, generic.columns);
11356        assert_eq!(
11357            generic.columns.get("id").unwrap().values(),
11358            &[
11359                Scalar::Int64(1),
11360                Scalar::Int64(1),
11361                Scalar::Int64(1),
11362                Scalar::Int64(1),
11363                Scalar::Int64(2),
11364                Scalar::Int64(2),
11365                Scalar::Int64(2),
11366                Scalar::Int64(2),
11367            ]
11368        );
11369        assert!(
11370            generic
11371                .columns
11372                .values()
11373                .all(|column| column.as_i64_slice().is_some())
11374        );
11375    }
11376
11377    #[test]
11378    fn merge_outer_all_matched_dense_int64_fused_output_matches_sorted_generic_route() {
11379        let left = DataFrame::from_dict(
11380            &["id", "v"],
11381            vec![
11382                (
11383                    "id",
11384                    vec![
11385                        Scalar::Int64(2),
11386                        Scalar::Int64(1),
11387                        Scalar::Int64(2),
11388                        Scalar::Int64(1),
11389                    ],
11390                ),
11391                (
11392                    "v",
11393                    vec![
11394                        Scalar::Int64(20),
11395                        Scalar::Int64(10),
11396                        Scalar::Int64(21),
11397                        Scalar::Int64(11),
11398                    ],
11399                ),
11400            ],
11401        )
11402        .unwrap();
11403        let right = DataFrame::from_dict(
11404            &["id", "w"],
11405            vec![
11406                (
11407                    "id",
11408                    vec![
11409                        Scalar::Int64(1),
11410                        Scalar::Int64(2),
11411                        Scalar::Int64(1),
11412                        Scalar::Int64(2),
11413                    ],
11414                ),
11415                (
11416                    "w",
11417                    vec![
11418                        Scalar::Int64(100),
11419                        Scalar::Int64(200),
11420                        Scalar::Int64(101),
11421                        Scalar::Int64(201),
11422                    ],
11423                ),
11424            ],
11425        )
11426        .unwrap();
11427
11428        let fused = merge_dataframes(&left, &right, "id", JoinType::Outer).unwrap();
11429        let generic = merge_dataframes_on_with_options(
11430            &left,
11431            &right,
11432            &["id"],
11433            &["id"],
11434            JoinType::Outer,
11435            MergeExecutionOptions {
11436                validate_mode: Some(MergeValidateMode::ManyToMany),
11437                sort: true,
11438                ..MergeExecutionOptions::default()
11439            },
11440        )
11441        .unwrap();
11442
11443        assert_eq!(fused.index, generic.index);
11444        assert_eq!(fused.column_order, generic.column_order);
11445        assert_eq!(fused.columns, generic.columns);
11446    }
11447
11448    #[test]
11449    fn merge_left_contiguous_utf8_duplicates_matches_sorted_generic_route() {
11450        let s = |v: &str| Scalar::Utf8(v.to_owned());
11451        let left = DataFrame::from_dict(
11452            &["id", "v"],
11453            vec![
11454                ("id", vec![s("a"), s("a"), s("b"), s("c")]),
11455                (
11456                    "v",
11457                    vec![
11458                        Scalar::Int64(10),
11459                        Scalar::Int64(11),
11460                        Scalar::Int64(20),
11461                        Scalar::Int64(30),
11462                    ],
11463                ),
11464            ],
11465        )
11466        .unwrap();
11467        let right = DataFrame::from_dict(
11468            &["id", "w"],
11469            vec![
11470                ("id", vec![s("a"), s("a"), s("c")]),
11471                (
11472                    "w",
11473                    vec![Scalar::Int64(100), Scalar::Int64(101), Scalar::Int64(300)],
11474                ),
11475            ],
11476        )
11477        .unwrap();
11478
11479        let fast = merge_dataframes(&left, &right, "id", JoinType::Left).unwrap();
11480        let generic = merge_dataframes_on_with_options(
11481            &left,
11482            &right,
11483            &["id"],
11484            &["id"],
11485            JoinType::Left,
11486            MergeExecutionOptions {
11487                sort: true,
11488                ..MergeExecutionOptions::default()
11489            },
11490        )
11491        .unwrap();
11492
11493        assert_eq!(fast.index, generic.index);
11494        assert_eq!(fast.column_order, generic.column_order);
11495        assert_eq!(fast.columns, generic.columns);
11496        assert_eq!(
11497            fast.columns.get("id").unwrap().values(),
11498            &[s("a"), s("a"), s("a"), s("a"), s("b"), s("c")]
11499        );
11500        assert!(fast.columns.get("w").unwrap().values()[4].is_missing());
11501    }
11502
11503    #[test]
11504    fn merge_outer_contiguous_utf8_duplicates_matches_sorted_generic_route() {
11505        let s = |v: &str| Scalar::Utf8(v.to_owned());
11506        let left = DataFrame::from_dict(
11507            &["id", "v"],
11508            vec![
11509                ("id", vec![s("a"), s("a"), s("b"), s("d")]),
11510                (
11511                    "v",
11512                    vec![
11513                        Scalar::Int64(10),
11514                        Scalar::Int64(11),
11515                        Scalar::Int64(20),
11516                        Scalar::Int64(40),
11517                    ],
11518                ),
11519            ],
11520        )
11521        .unwrap();
11522        let right = DataFrame::from_dict(
11523            &["id", "w"],
11524            vec![
11525                ("id", vec![s("a"), s("c"), s("a")]),
11526                (
11527                    "w",
11528                    vec![Scalar::Int64(100), Scalar::Int64(300), Scalar::Int64(101)],
11529                ),
11530            ],
11531        )
11532        .unwrap();
11533
11534        let fast = merge_dataframes(&left, &right, "id", JoinType::Outer).unwrap();
11535        let generic = merge_dataframes_on_with_options(
11536            &left,
11537            &right,
11538            &["id"],
11539            &["id"],
11540            JoinType::Outer,
11541            MergeExecutionOptions {
11542                sort: true,
11543                ..MergeExecutionOptions::default()
11544            },
11545        )
11546        .unwrap();
11547
11548        assert_eq!(fast.index, generic.index);
11549        assert_eq!(fast.column_order, generic.column_order);
11550        assert_eq!(fast.columns, generic.columns);
11551        assert_eq!(
11552            fast.columns.get("id").unwrap().values(),
11553            &[s("a"), s("a"), s("a"), s("a"), s("b"), s("c"), s("d")]
11554        );
11555        assert!(fast.columns.get("v").unwrap().values()[5].is_missing());
11556        assert!(fast.columns.get("w").unwrap().values()[4].is_missing());
11557        assert!(fast.columns.get("w").unwrap().values()[6].is_missing());
11558    }
11559
11560    #[test]
11561    fn merge_right_dense_int64_duplicates_matches_generic_validated_route() {
11562        let left = DataFrame::from_dict(
11563            &["id", "v"],
11564            vec![
11565                (
11566                    "id",
11567                    vec![
11568                        Scalar::Int64(2),
11569                        Scalar::Int64(0),
11570                        Scalar::Int64(2),
11571                        Scalar::Int64(1),
11572                        Scalar::Int64(5),
11573                    ],
11574                ),
11575                (
11576                    "v",
11577                    vec![
11578                        Scalar::Int64(10),
11579                        Scalar::Int64(11),
11580                        Scalar::Int64(12),
11581                        Scalar::Int64(13),
11582                        Scalar::Int64(15),
11583                    ],
11584                ),
11585            ],
11586        )
11587        .unwrap();
11588        let right = DataFrame::from_dict(
11589            &["id", "w"],
11590            vec![
11591                (
11592                    "id",
11593                    vec![
11594                        Scalar::Int64(2),
11595                        Scalar::Int64(2),
11596                        Scalar::Int64(3),
11597                        Scalar::Int64(0),
11598                    ],
11599                ),
11600                (
11601                    "w",
11602                    vec![
11603                        Scalar::Int64(200),
11604                        Scalar::Int64(201),
11605                        Scalar::Int64(300),
11606                        Scalar::Int64(400),
11607                    ],
11608                ),
11609            ],
11610        )
11611        .unwrap();
11612
11613        let fast = merge_dataframes(&left, &right, "id", JoinType::Right).unwrap();
11614        let generic = merge_dataframes_on_with_options(
11615            &left,
11616            &right,
11617            &["id"],
11618            &["id"],
11619            JoinType::Right,
11620            MergeExecutionOptions {
11621                validate_mode: Some(MergeValidateMode::ManyToMany),
11622                ..MergeExecutionOptions::default()
11623            },
11624        )
11625        .unwrap();
11626
11627        assert_eq!(fast.index, generic.index);
11628        assert_eq!(fast.column_order, generic.column_order);
11629        assert_eq!(fast.columns, generic.columns);
11630        assert_eq!(
11631            fast.columns.get("id").unwrap().values(),
11632            &[
11633                Scalar::Int64(2),
11634                Scalar::Int64(2),
11635                Scalar::Int64(2),
11636                Scalar::Int64(2),
11637                Scalar::Int64(3),
11638                Scalar::Int64(0),
11639            ]
11640        );
11641        let left_values = fast.columns.get("v").unwrap().values();
11642        assert_eq!(left_values[0], Scalar::Int64(10));
11643        assert_eq!(left_values[1], Scalar::Int64(12));
11644        assert_eq!(left_values[2], Scalar::Int64(10));
11645        assert_eq!(left_values[3], Scalar::Int64(12));
11646        assert!(left_values[4].is_missing());
11647        assert_eq!(left_values[5], Scalar::Int64(11));
11648        let right_values = fast.columns.get("w").unwrap().values();
11649        assert_eq!(right_values[0], Scalar::Int64(200));
11650        assert_eq!(right_values[1], Scalar::Int64(200));
11651        assert_eq!(right_values[2], Scalar::Int64(201));
11652        assert_eq!(right_values[3], Scalar::Int64(201));
11653        assert_eq!(right_values[4], Scalar::Int64(300));
11654        assert_eq!(right_values[5], Scalar::Int64(400));
11655    }
11656
11657    #[test]
11658    fn merge_right_dense_cycle_probe_output_matches_materialized_positions_yq96z() {
11659        let left = DataFrame::from_dict(
11660            &["id", "v"],
11661            vec![
11662                (
11663                    "id",
11664                    vec![
11665                        Scalar::Int64(1),
11666                        Scalar::Int64(2),
11667                        Scalar::Int64(1),
11668                        Scalar::Int64(2),
11669                    ],
11670                ),
11671                (
11672                    "v",
11673                    vec![
11674                        Scalar::Int64(100),
11675                        Scalar::Int64(200),
11676                        Scalar::Int64(101),
11677                        Scalar::Int64(201),
11678                    ],
11679                ),
11680            ],
11681        )
11682        .unwrap();
11683        let right = DataFrame::from_dict(
11684            &["id", "w"],
11685            vec![
11686                (
11687                    "id",
11688                    vec![
11689                        Scalar::Int64(0),
11690                        Scalar::Int64(1),
11691                        Scalar::Int64(2),
11692                        Scalar::Int64(0),
11693                        Scalar::Int64(1),
11694                    ],
11695                ),
11696                (
11697                    "w",
11698                    vec![
11699                        Scalar::Int64(10),
11700                        Scalar::Int64(11),
11701                        Scalar::Int64(12),
11702                        Scalar::Int64(13),
11703                        Scalar::Int64(14),
11704                    ],
11705                ),
11706            ],
11707        )
11708        .unwrap();
11709        let left_key = left.columns().get("id").unwrap();
11710        let right_key = right.columns().get("id").unwrap();
11711        assert!(left_key.int64_dense_cycle_witness().is_some());
11712        assert!(right_key.int64_dense_cycle_witness().is_some());
11713        let suffixes = resolve_merge_suffixes(None);
11714
11715        let fused = build_single_key_dense_i64_right_merge_output(
11716            &left,
11717            &right,
11718            &["id"],
11719            &["id"],
11720            left_key,
11721            right_key,
11722            &suffixes,
11723        )
11724        .unwrap()
11725        .expect("dense-cycle right route should accept");
11726        let (left_positions, right_positions) =
11727            dense_int64_right_positions(left_key, right_key).unwrap();
11728        let materialized = build_single_key_dense_right_merge_output(
11729            &left,
11730            &right,
11731            &["id"],
11732            &["id"],
11733            &left_positions,
11734            &right_positions,
11735            &suffixes,
11736        )
11737        .unwrap();
11738
11739        assert_eq!(fused.index, materialized.index);
11740        assert_eq!(fused.column_order, materialized.column_order);
11741        assert_eq!(fused.columns, materialized.columns);
11742        assert_eq!(
11743            fused.columns.get("v").unwrap().values(),
11744            &[
11745                Scalar::Null(NullKind::Null),
11746                Scalar::Int64(100),
11747                Scalar::Int64(101),
11748                Scalar::Int64(200),
11749                Scalar::Int64(201),
11750                Scalar::Null(NullKind::Null),
11751                Scalar::Int64(100),
11752                Scalar::Int64(101),
11753            ]
11754        );
11755    }
11756
11757    #[test]
11758    fn merge_left_right_all_matched_dense_int64_duplicates_match_generic_validated_route() {
11759        let left = DataFrame::from_dict(
11760            &["id", "v"],
11761            vec![
11762                (
11763                    "id",
11764                    vec![
11765                        Scalar::Int64(2),
11766                        Scalar::Int64(1),
11767                        Scalar::Int64(2),
11768                        Scalar::Int64(1),
11769                    ],
11770                ),
11771                (
11772                    "v",
11773                    vec![
11774                        Scalar::Int64(20),
11775                        Scalar::Int64(10),
11776                        Scalar::Int64(21),
11777                        Scalar::Int64(11),
11778                    ],
11779                ),
11780            ],
11781        )
11782        .unwrap();
11783        let right = DataFrame::from_dict(
11784            &["id", "w"],
11785            vec![
11786                (
11787                    "id",
11788                    vec![
11789                        Scalar::Int64(1),
11790                        Scalar::Int64(2),
11791                        Scalar::Int64(1),
11792                        Scalar::Int64(2),
11793                    ],
11794                ),
11795                (
11796                    "w",
11797                    vec![
11798                        Scalar::Int64(100),
11799                        Scalar::Int64(200),
11800                        Scalar::Int64(101),
11801                        Scalar::Int64(201),
11802                    ],
11803                ),
11804            ],
11805        )
11806        .unwrap();
11807
11808        for join_type in [JoinType::Left, JoinType::Right] {
11809            let fast = merge_dataframes(&left, &right, "id", join_type).unwrap();
11810            let generic = merge_dataframes_on_with_options(
11811                &left,
11812                &right,
11813                &["id"],
11814                &["id"],
11815                join_type,
11816                MergeExecutionOptions {
11817                    validate_mode: Some(MergeValidateMode::ManyToMany),
11818                    ..MergeExecutionOptions::default()
11819                },
11820            )
11821            .unwrap();
11822
11823            assert_eq!(fast.index, generic.index);
11824            assert_eq!(fast.column_order, generic.column_order);
11825            assert_eq!(fast.columns, generic.columns);
11826            assert!(
11827                generic
11828                    .columns
11829                    .values()
11830                    .all(|column| column.as_i64_slice().is_some())
11831            );
11832        }
11833    }
11834
11835    #[test]
11836    fn merge_right_all_matched_dense_int64_fused_output_matches_dense_materialization() {
11837        let left = DataFrame::from_dict(
11838            &["id", "v"],
11839            vec![
11840                (
11841                    "id",
11842                    vec![
11843                        Scalar::Int64(2),
11844                        Scalar::Int64(1),
11845                        Scalar::Int64(2),
11846                        Scalar::Int64(1),
11847                    ],
11848                ),
11849                (
11850                    "v",
11851                    vec![
11852                        Scalar::Int64(20),
11853                        Scalar::Int64(10),
11854                        Scalar::Int64(21),
11855                        Scalar::Int64(11),
11856                    ],
11857                ),
11858            ],
11859        )
11860        .unwrap();
11861        let right = DataFrame::from_dict(
11862            &["id", "w"],
11863            vec![
11864                (
11865                    "id",
11866                    vec![
11867                        Scalar::Int64(1),
11868                        Scalar::Int64(2),
11869                        Scalar::Int64(1),
11870                        Scalar::Int64(2),
11871                    ],
11872                ),
11873                (
11874                    "w",
11875                    vec![
11876                        Scalar::Int64(100),
11877                        Scalar::Int64(200),
11878                        Scalar::Int64(101),
11879                        Scalar::Int64(201),
11880                    ],
11881                ),
11882            ],
11883        )
11884        .unwrap();
11885
11886        let fused = merge_dataframes(&left, &right, "id", JoinType::Right).unwrap();
11887        let left_key = left.columns().get("id").unwrap();
11888        let right_key = right.columns().get("id").unwrap();
11889        let (left_positions, right_positions) =
11890            dense_int64_right_positions(left_key, right_key).unwrap();
11891        let suffixes = resolve_merge_suffixes(None);
11892        let materialized = build_single_key_dense_right_merge_output(
11893            &left,
11894            &right,
11895            &["id"],
11896            &["id"],
11897            &left_positions,
11898            &right_positions,
11899            &suffixes,
11900        )
11901        .unwrap();
11902
11903        assert_eq!(fused.index, materialized.index);
11904        assert_eq!(fused.column_order, materialized.column_order);
11905        assert_eq!(fused.columns, materialized.columns);
11906        assert_eq!(
11907            fused.columns.get("id").unwrap().values(),
11908            &[
11909                Scalar::Int64(1),
11910                Scalar::Int64(1),
11911                Scalar::Int64(2),
11912                Scalar::Int64(2),
11913                Scalar::Int64(1),
11914                Scalar::Int64(1),
11915                Scalar::Int64(2),
11916                Scalar::Int64(2),
11917            ]
11918        );
11919        assert!(
11920            fused
11921                .columns
11922                .values()
11923                .all(|column| column.as_i64_slice().is_some())
11924        );
11925    }
11926
11927    #[test]
11928    fn merge_right_ordered_unique_int64_subset_matches_generic_validated_route() {
11929        let left = DataFrame::from_dict(
11930            &["id", "v"],
11931            vec![
11932                (
11933                    "id",
11934                    vec![Scalar::Int64(0), Scalar::Int64(1), Scalar::Int64(3)],
11935                ),
11936                (
11937                    "v",
11938                    vec![Scalar::Int64(10), Scalar::Int64(11), Scalar::Int64(13)],
11939                ),
11940            ],
11941        )
11942        .unwrap();
11943        let right = DataFrame::from_dict(
11944            &["id", "w"],
11945            vec![
11946                (
11947                    "id",
11948                    vec![
11949                        Scalar::Int64(0),
11950                        Scalar::Int64(2),
11951                        Scalar::Int64(3),
11952                        Scalar::Int64(5),
11953                    ],
11954                ),
11955                (
11956                    "w",
11957                    vec![
11958                        Scalar::Int64(100),
11959                        Scalar::Int64(200),
11960                        Scalar::Int64(300),
11961                        Scalar::Int64(500),
11962                    ],
11963                ),
11964            ],
11965        )
11966        .unwrap();
11967
11968        let fast = merge_dataframes(&left, &right, "id", JoinType::Right).unwrap();
11969        let generic = merge_dataframes_on_with_options(
11970            &left,
11971            &right,
11972            &["id"],
11973            &["id"],
11974            JoinType::Right,
11975            MergeExecutionOptions {
11976                validate_mode: Some(MergeValidateMode::OneToOne),
11977                ..MergeExecutionOptions::default()
11978            },
11979        )
11980        .unwrap();
11981
11982        assert_eq!(fast.index, generic.index);
11983        assert_eq!(fast.column_order, generic.column_order);
11984        assert_eq!(fast.columns, generic.columns);
11985        assert_eq!(
11986            fast.columns.get("id").unwrap().values(),
11987            &[
11988                Scalar::Int64(0),
11989                Scalar::Int64(2),
11990                Scalar::Int64(3),
11991                Scalar::Int64(5)
11992            ]
11993        );
11994        let left_values = fast.columns.get("v").unwrap().values();
11995        assert_eq!(left_values[0], Scalar::Int64(10));
11996        assert!(left_values[1].is_missing());
11997        assert_eq!(left_values[2], Scalar::Int64(13));
11998        assert!(left_values[3].is_missing());
11999        let right_values = fast.columns.get("w").unwrap().values();
12000        assert_eq!(right_values[0], Scalar::Int64(100));
12001        assert_eq!(right_values[1], Scalar::Int64(200));
12002        assert_eq!(right_values[2], Scalar::Int64(300));
12003        assert_eq!(right_values[3], Scalar::Int64(500));
12004    }
12005
12006    #[test]
12007    fn merge_right_preserves_all_right_rows() {
12008        let left = make_left_df();
12009        let right = make_right_df();
12010        let merged = merge_dataframes(&left, &right, "id", JoinType::Right).unwrap();
12011
12012        assert_eq!(merged.columns.get("id").unwrap().len(), 3);
12013        assert_eq!(
12014            merged.columns.get("val_b").unwrap().values(),
12015            &[Scalar::Int64(200), Scalar::Int64(300), Scalar::Int64(400)]
12016        );
12017        // val_a: 20 for id=2, 30 for id=3, null for id=4
12018        assert_eq!(
12019            merged.columns.get("val_a").unwrap().values()[0],
12020            Scalar::Int64(20)
12021        );
12022        assert_eq!(
12023            merged.columns.get("val_a").unwrap().values()[1],
12024            Scalar::Int64(30)
12025        );
12026        assert!(merged.columns.get("val_a").unwrap().values()[2].is_missing());
12027    }
12028
12029    #[test]
12030    fn merge_outer_contains_all_rows() {
12031        let left = make_left_df();
12032        let right = make_right_df();
12033        let merged = merge_dataframes(&left, &right, "id", JoinType::Outer).unwrap();
12034
12035        // ids: 1, 2, 3 from left + 4 from right = 4 rows
12036        assert_eq!(merged.columns.get("id").unwrap().len(), 4);
12037    }
12038
12039    #[test]
12040    fn merge_inner_sort_false_preserves_left_key_order() {
12041        let left = DataFrame::from_dict(
12042            &["id", "left_v"],
12043            vec![
12044                (
12045                    "id",
12046                    vec![Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(2)],
12047                ),
12048                (
12049                    "left_v",
12050                    vec![Scalar::Int64(20), Scalar::Int64(10), Scalar::Int64(21)],
12051                ),
12052            ],
12053        )
12054        .expect("left");
12055        let right = DataFrame::from_dict(
12056            &["id", "right_v"],
12057            vec![
12058                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
12059                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
12060            ],
12061        )
12062        .expect("right");
12063
12064        let merged = merge_dataframes_on_with_options(
12065            &left,
12066            &right,
12067            &["id"],
12068            &["id"],
12069            JoinType::Inner,
12070            MergeExecutionOptions::default(),
12071        )
12072        .expect("merge");
12073        assert_eq!(
12074            merged.columns.get("id").expect("id").values(),
12075            &[Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(2)]
12076        );
12077        assert_eq!(
12078            merged.columns.get("left_v").expect("left_v").values(),
12079            &[Scalar::Int64(20), Scalar::Int64(10), Scalar::Int64(21)]
12080        );
12081        assert_eq!(
12082            merged.columns.get("right_v").expect("right_v").values(),
12083            &[Scalar::Int64(200), Scalar::Int64(100), Scalar::Int64(200)]
12084        );
12085    }
12086
12087    #[test]
12088    fn merge_inner_sort_true_orders_join_keys_lexicographically() {
12089        let left = DataFrame::from_dict(
12090            &["id", "left_v"],
12091            vec![
12092                (
12093                    "id",
12094                    vec![Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(2)],
12095                ),
12096                (
12097                    "left_v",
12098                    vec![Scalar::Int64(20), Scalar::Int64(10), Scalar::Int64(21)],
12099                ),
12100            ],
12101        )
12102        .expect("left");
12103        let right = DataFrame::from_dict(
12104            &["id", "right_v"],
12105            vec![
12106                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
12107                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
12108            ],
12109        )
12110        .expect("right");
12111
12112        let merged = merge_dataframes_on_with_options(
12113            &left,
12114            &right,
12115            &["id"],
12116            &["id"],
12117            JoinType::Inner,
12118            MergeExecutionOptions {
12119                sort: true,
12120                ..MergeExecutionOptions::default()
12121            },
12122        )
12123        .expect("merge");
12124        assert_eq!(
12125            merged.columns.get("id").expect("id").values(),
12126            &[Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(2)]
12127        );
12128        assert_eq!(
12129            merged.columns.get("left_v").expect("left_v").values(),
12130            &[Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(21)]
12131        );
12132        assert_eq!(
12133            merged.columns.get("right_v").expect("right_v").values(),
12134            &[Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(200)]
12135        );
12136    }
12137
12138    #[test]
12139    fn merge_inner_sort_true_orders_float_keys_numerically() {
12140        let left = DataFrame::from_dict(
12141            &["id", "left_v"],
12142            vec![
12143                (
12144                    "id",
12145                    vec![
12146                        Scalar::Float64(1.5),
12147                        Scalar::Float64(-2.5),
12148                        Scalar::Float64(0.25),
12149                    ],
12150                ),
12151                (
12152                    "left_v",
12153                    vec![Scalar::Int64(15), Scalar::Int64(-25), Scalar::Int64(2)],
12154                ),
12155            ],
12156        )
12157        .expect("left");
12158        let right = DataFrame::from_dict(
12159            &["id", "right_v"],
12160            vec![
12161                (
12162                    "id",
12163                    vec![
12164                        Scalar::Float64(-2.5),
12165                        Scalar::Float64(0.25),
12166                        Scalar::Float64(1.5),
12167                    ],
12168                ),
12169                (
12170                    "right_v",
12171                    vec![Scalar::Int64(250), Scalar::Int64(25), Scalar::Int64(150)],
12172                ),
12173            ],
12174        )
12175        .expect("right");
12176
12177        let merged = merge_dataframes_on_with_options(
12178            &left,
12179            &right,
12180            &["id"],
12181            &["id"],
12182            JoinType::Inner,
12183            MergeExecutionOptions {
12184                sort: true,
12185                ..MergeExecutionOptions::default()
12186            },
12187        )
12188        .expect("merge");
12189
12190        assert_eq!(
12191            merged.columns.get("id").expect("id").values(),
12192            &[
12193                Scalar::Float64(-2.5),
12194                Scalar::Float64(0.25),
12195                Scalar::Float64(1.5)
12196            ]
12197        );
12198        assert_eq!(
12199            merged.columns.get("left_v").expect("left_v").values(),
12200            &[Scalar::Int64(-25), Scalar::Int64(2), Scalar::Int64(15)]
12201        );
12202        assert_eq!(
12203            merged.columns.get("right_v").expect("right_v").values(),
12204            &[Scalar::Int64(250), Scalar::Int64(25), Scalar::Int64(150)]
12205        );
12206    }
12207
12208    #[test]
12209    fn merge_right_sort_true_orders_join_keys_lexicographically() {
12210        let left = DataFrame::from_dict(
12211            &["id", "left_v"],
12212            vec![
12213                ("id", vec![Scalar::Int64(3), Scalar::Int64(1)]),
12214                ("left_v", vec![Scalar::Int64(30), Scalar::Int64(10)]),
12215            ],
12216        )
12217        .expect("left");
12218        let right = DataFrame::from_dict(
12219            &["id", "right_v"],
12220            vec![
12221                (
12222                    "id",
12223                    vec![Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(3)],
12224                ),
12225                (
12226                    "right_v",
12227                    vec![Scalar::Int64(200), Scalar::Int64(100), Scalar::Int64(300)],
12228                ),
12229            ],
12230        )
12231        .expect("right");
12232
12233        let merged = merge_dataframes_on_with_options(
12234            &left,
12235            &right,
12236            &["id"],
12237            &["id"],
12238            JoinType::Right,
12239            MergeExecutionOptions {
12240                sort: true,
12241                ..MergeExecutionOptions::default()
12242            },
12243        )
12244        .expect("merge");
12245        assert_eq!(
12246            merged.columns.get("id").expect("id").values(),
12247            &[Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)]
12248        );
12249        assert_eq!(
12250            merged.columns.get("left_v").expect("left_v").values(),
12251            &[
12252                Scalar::Int64(10),
12253                Scalar::Null(NullKind::Null),
12254                Scalar::Int64(30)
12255            ]
12256        );
12257        assert_eq!(
12258            merged.columns.get("right_v").expect("right_v").values(),
12259            &[Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(300)]
12260        );
12261    }
12262
12263    #[test]
12264    fn merge_column_name_conflict_adds_suffixes() {
12265        let left = DataFrame::from_dict(
12266            &["id", "val"],
12267            vec![
12268                ("id", vec![Scalar::Int64(1)]),
12269                ("val", vec![Scalar::Int64(10)]),
12270            ],
12271        )
12272        .unwrap();
12273        let right = DataFrame::from_dict(
12274            &["id", "val"],
12275            vec![
12276                ("id", vec![Scalar::Int64(1)]),
12277                ("val", vec![Scalar::Int64(99)]),
12278            ],
12279        )
12280        .unwrap();
12281
12282        let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
12283        assert!(merged.columns.contains_key("val_x"));
12284        assert!(merged.columns.contains_key("val_y"));
12285        assert_eq!(
12286            merged.columns.get("val_x").unwrap().values(),
12287            &[Scalar::Int64(10)]
12288        );
12289        assert_eq!(
12290            merged.columns.get("val_y").unwrap().values(),
12291            &[Scalar::Int64(99)]
12292        );
12293    }
12294
12295    #[test]
12296    fn merge_column_name_conflict_honors_custom_suffixes() {
12297        let left = DataFrame::from_dict(
12298            &["id", "val"],
12299            vec![
12300                ("id", vec![Scalar::Int64(1)]),
12301                ("val", vec![Scalar::Int64(10)]),
12302            ],
12303        )
12304        .expect("left");
12305        let right = DataFrame::from_dict(
12306            &["id", "val"],
12307            vec![
12308                ("id", vec![Scalar::Int64(1)]),
12309                ("val", vec![Scalar::Int64(99)]),
12310            ],
12311        )
12312        .expect("right");
12313
12314        let merged = merge_dataframes_on_with_options(
12315            &left,
12316            &right,
12317            &["id"],
12318            &["id"],
12319            JoinType::Inner,
12320            MergeExecutionOptions {
12321                suffixes: Some([Some("_L".to_owned()), Some("_R".to_owned())]),
12322                ..MergeExecutionOptions::default()
12323            },
12324        )
12325        .expect("merge");
12326        assert!(merged.columns.contains_key("val_L"));
12327        assert!(merged.columns.contains_key("val_R"));
12328        assert_eq!(
12329            merged.columns.get("val_L").expect("left suffixed").values(),
12330            &[Scalar::Int64(10)]
12331        );
12332        assert_eq!(
12333            merged
12334                .columns
12335                .get("val_R")
12336                .expect("right suffixed")
12337                .values(),
12338            &[Scalar::Int64(99)]
12339        );
12340    }
12341
12342    #[test]
12343    fn merge_column_name_conflict_allows_one_sided_suffix() {
12344        let left = DataFrame::from_dict(
12345            &["id", "val"],
12346            vec![
12347                ("id", vec![Scalar::Int64(1)]),
12348                ("val", vec![Scalar::Int64(10)]),
12349            ],
12350        )
12351        .expect("left");
12352        let right = DataFrame::from_dict(
12353            &["id", "val"],
12354            vec![
12355                ("id", vec![Scalar::Int64(1)]),
12356                ("val", vec![Scalar::Int64(99)]),
12357            ],
12358        )
12359        .expect("right");
12360
12361        let merged = merge_dataframes_on_with_options(
12362            &left,
12363            &right,
12364            &["id"],
12365            &["id"],
12366            JoinType::Inner,
12367            MergeExecutionOptions {
12368                suffixes: Some([None, Some("_r".to_owned())]),
12369                ..MergeExecutionOptions::default()
12370            },
12371        )
12372        .expect("merge");
12373        assert!(merged.columns.contains_key("val"));
12374        assert!(merged.columns.contains_key("val_r"));
12375        assert_eq!(
12376            merged.columns.get("val").expect("left unsuffixed").values(),
12377            &[Scalar::Int64(10)]
12378        );
12379        assert_eq!(
12380            merged
12381                .columns
12382                .get("val_r")
12383                .expect("right suffixed")
12384                .values(),
12385            &[Scalar::Int64(99)]
12386        );
12387    }
12388
12389    #[test]
12390    fn merge_column_name_conflict_rejects_missing_suffixes_for_overlap() {
12391        let left = DataFrame::from_dict(
12392            &["id", "val"],
12393            vec![
12394                ("id", vec![Scalar::Int64(1)]),
12395                ("val", vec![Scalar::Int64(10)]),
12396            ],
12397        )
12398        .expect("left");
12399        let right = DataFrame::from_dict(
12400            &["id", "val"],
12401            vec![
12402                ("id", vec![Scalar::Int64(1)]),
12403                ("val", vec![Scalar::Int64(99)]),
12404            ],
12405        )
12406        .expect("right");
12407
12408        let err = merge_dataframes_on_with_options(
12409            &left,
12410            &right,
12411            &["id"],
12412            &["id"],
12413            JoinType::Inner,
12414            MergeExecutionOptions {
12415                suffixes: Some([Some(String::new()), Some(String::new())]),
12416                ..MergeExecutionOptions::default()
12417            },
12418        )
12419        .expect_err("merge should reject overlapping columns without suffixes");
12420        assert!(format!("{err}").contains("columns overlap but no suffix specified"));
12421    }
12422
12423    #[test]
12424    fn merge_column_name_conflict_rejects_duplicate_output_columns_from_suffixes() {
12425        let left = DataFrame::from_dict(
12426            &["id", "val", "val_L"],
12427            vec![
12428                ("id", vec![Scalar::Int64(1)]),
12429                ("val", vec![Scalar::Int64(10)]),
12430                ("val_L", vec![Scalar::Int64(77)]),
12431            ],
12432        )
12433        .expect("left");
12434        let right = DataFrame::from_dict(
12435            &["id", "val"],
12436            vec![
12437                ("id", vec![Scalar::Int64(1)]),
12438                ("val", vec![Scalar::Int64(99)]),
12439            ],
12440        )
12441        .expect("right");
12442
12443        let err = merge_dataframes_on_with_options(
12444            &left,
12445            &right,
12446            &["id"],
12447            &["id"],
12448            JoinType::Inner,
12449            MergeExecutionOptions {
12450                suffixes: Some([Some("_L".to_owned()), Some("_R".to_owned())]),
12451                ..MergeExecutionOptions::default()
12452            },
12453        )
12454        .expect_err("merge should reject duplicate output names caused by suffixes");
12455        assert!(format!("{err}").contains("duplicate output column"));
12456    }
12457
12458    #[test]
12459    fn merge_missing_key_column_errors() {
12460        let left = make_left_df();
12461        let right = make_right_df();
12462        let err = merge_dataframes(&left, &right, "nonexistent", JoinType::Inner)
12463            .expect_err("should fail");
12464        assert!(format!("{err}").contains("nonexistent"));
12465    }
12466
12467    #[test]
12468    fn merge_duplicate_keys_multiply_cardinality() {
12469        let left = DataFrame::from_dict(
12470            &["id", "a"],
12471            vec![
12472                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
12473                ("a", vec![Scalar::Int64(10), Scalar::Int64(20)]),
12474            ],
12475        )
12476        .unwrap();
12477        let right = DataFrame::from_dict(
12478            &["id", "b"],
12479            vec![
12480                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
12481                ("b", vec![Scalar::Int64(100), Scalar::Int64(200)]),
12482            ],
12483        )
12484        .unwrap();
12485
12486        let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
12487        // 2 left × 2 right = 4 rows
12488        assert_eq!(merged.columns.get("id").unwrap().len(), 4);
12489    }
12490
12491    #[test]
12492    fn ordered_identity_int64_guard_uses_strict_unique_certificate() {
12493        let left = fp_columnar::Column::from_i64_values(vec![1, 2, 3, 4]);
12494        let right = fp_columnar::Column::from_i64_values(vec![1, 2, 3, 4]);
12495        assert!(ordered_identity_int64_keys_match(&left, &right));
12496
12497        let duplicate_left = fp_columnar::Column::from_i64_values(vec![1, 1, 2]);
12498        let duplicate_right = fp_columnar::Column::from_i64_values(vec![1, 1, 2]);
12499        assert!(!ordered_identity_int64_keys_match(
12500            &duplicate_left,
12501            &duplicate_right
12502        ));
12503
12504        let unsorted_left = fp_columnar::Column::from_i64_values(vec![2, 1, 3]);
12505        let unsorted_right = fp_columnar::Column::from_i64_values(vec![2, 1, 3]);
12506        assert!(ordered_identity_int64_keys_match(
12507            &unsorted_left,
12508            &unsorted_right
12509        ));
12510    }
12511
12512    #[test]
12513    fn merge_identical_duplicate_keys_cross_join_values_jdupk() {
12514        // Identical left/right key columns that contain duplicates must NOT take
12515        // the identity 1:1 fast path: pandas cross-joins each duplicate, so a=10
12516        // and a=20 each pair with b=100 and b=200. (br-frankenpandas-jdupk)
12517        let left = DataFrame::from_dict(
12518            &["id", "a"],
12519            vec![
12520                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
12521                ("a", vec![Scalar::Int64(10), Scalar::Int64(20)]),
12522            ],
12523        )
12524        .unwrap();
12525        let right = DataFrame::from_dict(
12526            &["id", "b"],
12527            vec![
12528                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
12529                ("b", vec![Scalar::Int64(100), Scalar::Int64(200)]),
12530            ],
12531        )
12532        .unwrap();
12533
12534        let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
12535        assert_eq!(
12536            merged.columns.get("a").unwrap().values(),
12537            &[
12538                Scalar::Int64(10),
12539                Scalar::Int64(10),
12540                Scalar::Int64(20),
12541                Scalar::Int64(20)
12542            ]
12543        );
12544        assert_eq!(
12545            merged.columns.get("b").unwrap().values(),
12546            &[
12547                Scalar::Int64(100),
12548                Scalar::Int64(200),
12549                Scalar::Int64(100),
12550                Scalar::Int64(200)
12551            ]
12552        );
12553    }
12554
12555    #[test]
12556    fn ordered_unique_utf8_inner_positions_match_left_major_hash_order_53lat() {
12557        let left = contiguous_utf8_column(&["a", "b", "d", "f"]);
12558        let right = contiguous_utf8_column(&["b", "c", "f"]);
12559        let (left_positions, right_positions) =
12560            ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
12561
12562        assert_eq!(left_positions, vec![1, 3]);
12563        assert_eq!(right_positions, vec![0, 2]);
12564
12565        let merged = merge_dataframes(
12566            &utf8_key_merge_frame(&["a", "b", "d", "f"], "lv", 10),
12567            &utf8_key_merge_frame(&["b", "c", "f"], "rv", 20),
12568            "id",
12569            JoinType::Inner,
12570        )
12571        .unwrap();
12572        assert_eq!(
12573            merged.columns.get("lv").unwrap().values(),
12574            &[Scalar::Int64(11), Scalar::Int64(13)]
12575        );
12576        assert_eq!(
12577            merged.columns.get("rv").unwrap().values(),
12578            &[Scalar::Int64(20), Scalar::Int64(22)]
12579        );
12580    }
12581
12582    #[test]
12583    fn ordered_unique_utf8_seek_bound_preserves_late_overlap_lr52z() {
12584        let left = contiguous_utf8_column(&["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]);
12585        let right = contiguous_utf8_column(&["h", "i", "j", "k"]);
12586        let (left_bytes, left_offsets) =
12587            strictly_increasing_utf8_key_spans(&left).expect("sorted left");
12588
12589        assert_eq!(utf8_span_lower_bound(left_bytes, left_offsets, b"h"), 7);
12590
12591        let (left_positions, right_positions) =
12592            ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
12593        assert_eq!(left_positions, vec![7, 8, 9]);
12594        assert_eq!(right_positions, vec![0, 1, 2]);
12595
12596        let disjoint_left = contiguous_utf8_column(&["a", "b"]);
12597        let disjoint_right = contiguous_utf8_column(&["c", "d"]);
12598        let (left_positions, right_positions) =
12599            ordered_unique_utf8_inner_positions(&disjoint_left, &disjoint_right)
12600                .expect("ordered disjoint utf8 positions");
12601        assert!(left_positions.is_empty());
12602        assert!(right_positions.is_empty());
12603    }
12604
12605    #[test]
12606    fn ordered_unique_utf8_bulk_fixed_width_window_jbyuc11() {
12607        let left = contiguous_utf8_column(&["k000", "k001", "k002", "k003", "k004"]);
12608        let right = contiguous_utf8_column(&["k002", "k003", "k004", "k005"]);
12609
12610        let (left_positions, right_positions) =
12611            ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
12612        assert_eq!(left_positions, vec![2, 3, 4]);
12613        assert_eq!(right_positions, vec![0, 1, 2]);
12614    }
12615
12616    #[test]
12617    fn ordered_unique_utf8_bulk_window_returns_range_plan_jbyuc11111() {
12618        let left = contiguous_utf8_column(&["k000", "k001", "k002", "k003", "k004"]);
12619        let right = contiguous_utf8_column(&["k002", "k003", "k004", "k005"]);
12620
12621        let plan =
12622            ordered_unique_utf8_inner_position_plan(&left, &right).expect("ordered utf8 plan");
12623
12624        assert_eq!(
12625            plan,
12626            InnerPositionPlan::ContiguousRanges {
12627                left_start: 2,
12628                right_start: 0,
12629                len: 3
12630            }
12631        );
12632    }
12633
12634    #[test]
12635    fn ordered_unique_utf8_lower_hex_certificate_returns_range_plan_jbyuc111111() {
12636        let left =
12637            contiguous_utf8_column(&["id_0000000a", "id_0000000b", "id_0000000c", "id_0000000d"]);
12638        let right = contiguous_utf8_column(&["id_0000000c", "id_0000000d", "id_0000000e"]);
12639        let (_, _, left_cert) = left
12640            .as_lower_hex_sequence_utf8_contiguous()
12641            .expect("left sequence certificate");
12642        let (_, _, right_cert) = right
12643            .as_lower_hex_sequence_utf8_contiguous()
12644            .expect("right sequence certificate");
12645
12646        assert_eq!(
12647            ordered_utf8_lower_hex_overlap_len(left_cert, right_cert, 2, 4, 0, 3),
12648            Some(2)
12649        );
12650        assert_eq!(
12651            lower_hex_overlap_plan_from_certificates(&left, &right),
12652            Some(InnerPositionPlan::ContiguousRanges {
12653                left_start: 2,
12654                right_start: 0,
12655                len: 2
12656            })
12657        );
12658        let plan =
12659            ordered_unique_utf8_inner_position_plan(&left, &right).expect("ordered utf8 plan");
12660        assert_eq!(
12661            plan,
12662            InnerPositionPlan::ContiguousRanges {
12663                left_start: 2,
12664                right_start: 0,
12665                len: 2
12666            }
12667        );
12668    }
12669
12670    #[test]
12671    fn ordered_unique_utf8_lower_hex_arithmetic_empty_overlap_jbyuc1111111111() {
12672        let left = contiguous_utf8_column(&["id_00000001", "id_00000002", "id_00000003"]);
12673        let right = contiguous_utf8_column(&["id_00000008", "id_00000009"]);
12674
12675        assert_eq!(
12676            lower_hex_overlap_plan_from_certificates(&left, &right),
12677            Some(InnerPositionPlan::Gather {
12678                left_positions: Vec::new(),
12679                right_positions: Vec::new(),
12680            })
12681        );
12682        let (left_positions, right_positions) =
12683            ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
12684        assert!(left_positions.is_empty());
12685        assert!(right_positions.is_empty());
12686    }
12687
12688    #[test]
12689    fn ordered_unique_utf8_lower_hex_prefix_mismatch_falls_back_jbyuc1111111111() {
12690        let left = contiguous_utf8_column(&["aa_00000001", "aa_00000002", "aa_00000003"]);
12691        let right = contiguous_utf8_column(&["bb_00000001", "bb_00000002", "bb_00000003"]);
12692
12693        assert!(
12694            lower_hex_overlap_plan_from_certificates(&left, &right).is_none(),
12695            "matching lower-hex counters with different prefixes must not use arithmetic overlap"
12696        );
12697        let (left_positions, right_positions) =
12698            ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
12699        assert!(left_positions.is_empty());
12700        assert!(right_positions.is_empty());
12701    }
12702
12703    #[test]
12704    fn ordered_utf8_contiguous_no_overlap_output_fast_path_jbyuc111111111() -> Result<(), String> {
12705        let left = utf8_key_merge_frame(
12706            &["id_00000000", "id_00000001", "id_00000002", "id_00000003"],
12707            "lv",
12708            10,
12709        );
12710        let right = utf8_key_merge_frame(&["id_00000002", "id_00000003", "id_00000004"], "rv", 100);
12711        let plan = ordered_unique_utf8_inner_position_plan(
12712            left.columns()
12713                .get("id")
12714                .ok_or_else(|| "left key column missing".to_owned())?,
12715            right
12716                .columns()
12717                .get("id")
12718                .ok_or_else(|| "right key column missing".to_owned())?,
12719        )
12720        .ok_or_else(|| "ordered utf8 plan unavailable".to_owned())?;
12721        let InnerPositionPlan::ContiguousRanges {
12722            left_start,
12723            right_start,
12724            len,
12725        } = plan
12726        else {
12727            return Err("expected contiguous range plan".to_owned());
12728        };
12729
12730        let merged = build_single_key_inner_contiguous_no_overlap_output(
12731            &left,
12732            &right,
12733            &["id"],
12734            &["id"],
12735            PositionSelection::ContiguousRange {
12736                start: left_start,
12737                len,
12738            },
12739            PositionSelection::ContiguousRange {
12740                start: right_start,
12741                len,
12742            },
12743        )
12744        .ok_or_else(|| "no-overlap contiguous output fast path missed".to_owned())?;
12745
12746        assert_eq!(merged.column_order, ["id", "lv", "rv"]);
12747        let id_output = merged
12748            .columns
12749            .get("id")
12750            .ok_or_else(|| "id output missing".to_owned())?;
12751        let (prefix, certificate, certificate_len) = id_output
12752            .as_lower_hex_sequence_utf8()
12753            .ok_or_else(|| "id output lost lower-hex sequence witness".to_owned())?;
12754        assert_eq!(prefix, b"id_");
12755        assert_eq!(certificate.start(), 2);
12756        assert_eq!(certificate.hex_width(), 8);
12757        assert_eq!(certificate_len, 2);
12758        assert_eq!(
12759            id_output.values(),
12760            &[
12761                Scalar::Utf8("id_00000002".to_owned()),
12762                Scalar::Utf8("id_00000003".to_owned())
12763            ]
12764        );
12765        assert_eq!(
12766            merged
12767                .columns
12768                .get("lv")
12769                .ok_or_else(|| "lv output missing".to_owned())?
12770                .values(),
12771            &[Scalar::Int64(12), Scalar::Int64(13)]
12772        );
12773        assert_eq!(
12774            merged
12775                .columns
12776                .get("rv")
12777                .ok_or_else(|| "rv output missing".to_owned())?
12778                .values(),
12779            &[Scalar::Int64(100), Scalar::Int64(101)]
12780        );
12781
12782        let overlapping_right =
12783            utf8_key_merge_frame(&["id_00000002", "id_00000003", "id_00000004"], "lv", 100);
12784        assert!(
12785            build_single_key_inner_contiguous_no_overlap_output(
12786                &left,
12787                &overlapping_right,
12788                &["id"],
12789                &["id"],
12790                PositionSelection::ContiguousRange {
12791                    start: left_start,
12792                    len,
12793                },
12794                PositionSelection::ContiguousRange {
12795                    start: right_start,
12796                    len,
12797                },
12798            )
12799            .is_none(),
12800            "overlapping non-key columns must keep the suffix/error generic path"
12801        );
12802        Ok(())
12803    }
12804
12805    #[test]
12806    fn ordered_unique_utf8_uncertified_fixed_width_still_matches_jbyuc111111() {
12807        let left = contiguous_utf8_column(&["k00A", "k00B", "k00C", "k00D"]);
12808        let right = contiguous_utf8_column(&["k00B", "k00D"]);
12809
12810        assert!(left.as_lower_hex_sequence_utf8_contiguous().is_none());
12811        assert!(right.as_lower_hex_sequence_utf8_contiguous().is_none());
12812        let (left_positions, right_positions) =
12813            ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
12814        assert_eq!(left_positions, vec![1, 3]);
12815        assert_eq!(right_positions, vec![0, 1]);
12816    }
12817
12818    #[test]
12819    fn ordered_unique_utf8_fixed_width_gap_falls_back_jbyuc11() {
12820        let left = contiguous_utf8_column(&["k000", "k001", "k003", "k004"]);
12821        let right = contiguous_utf8_column(&["k001", "k002", "k004"]);
12822
12823        let (left_positions, right_positions) =
12824            ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
12825        assert_eq!(left_positions, vec![1, 3]);
12826        assert_eq!(right_positions, vec![0, 2]);
12827    }
12828
12829    #[test]
12830    fn ordered_unique_utf8_rejects_unsorted_or_duplicate_keys_53lat() {
12831        let unsorted_left = contiguous_utf8_column(&["b", "a", "b"]);
12832        let duplicate_right = contiguous_utf8_column(&["b", "b", "a"]);
12833        assert!(ordered_unique_utf8_inner_positions(&unsorted_left, &duplicate_right).is_none());
12834
12835        let left = utf8_key_merge_frame(&["b", "a", "b"], "lv", 10);
12836        let right = utf8_key_merge_frame(&["b", "b", "a"], "rv", 20);
12837        let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
12838
12839        assert_eq!(
12840            merged.columns.get("lv").unwrap().values(),
12841            &[
12842                Scalar::Int64(10),
12843                Scalar::Int64(10),
12844                Scalar::Int64(11),
12845                Scalar::Int64(12),
12846                Scalar::Int64(12)
12847            ]
12848        );
12849        assert_eq!(
12850            merged.columns.get("rv").unwrap().values(),
12851            &[
12852                Scalar::Int64(20),
12853                Scalar::Int64(21),
12854                Scalar::Int64(22),
12855                Scalar::Int64(20),
12856                Scalar::Int64(21)
12857            ]
12858        );
12859    }
12860
12861    #[test]
12862    fn merge_inner_int64_fast_paths_match_naive_reference_fuzz_jdupk() {
12863        // Differential guard: merge_dataframes dispatches int64 single-key inner
12864        // merges to ordered/identity/dense fast paths. Each MUST equal a naive
12865        // left-major nested-loop join for arbitrary int64 keys (sorted/unsorted,
12866        // unique/duplicate, overlapping/disjoint, negative). This is the
12867        // isomorphism proof those perf paths owe; it caught the identity-path
12868        // row-loss bug. (br-frankenpandas-rw0r5)
12869        let mut state: u64 = 0x9E37_79B9_7F4A_7C15;
12870        let mut next = || {
12871            state = state
12872                .wrapping_mul(6_364_136_223_846_793_005)
12873                .wrapping_add(1_442_695_040_888_963_407);
12874            state >> 33
12875        };
12876        for _ in 0..400 {
12877            let nl = (next() % 6 + 1) as usize;
12878            let nr = (next() % 6 + 1) as usize;
12879            // small key range forces collisions; offset gives negatives too
12880            let lk: Vec<i64> = (0..nl).map(|_| (next() % 5) as i64 - 2).collect();
12881            let rk: Vec<i64> = (0..nr).map(|_| (next() % 5) as i64 - 2).collect();
12882
12883            let left = DataFrame::from_dict(
12884                &["id", "a"],
12885                vec![
12886                    ("id", lk.iter().map(|&k| Scalar::Int64(k)).collect()),
12887                    (
12888                        "a",
12889                        (0..nl).map(|i| Scalar::Int64(i as i64 + 1000)).collect(),
12890                    ),
12891                ],
12892            )
12893            .unwrap();
12894            let right = DataFrame::from_dict(
12895                &["id", "b"],
12896                vec![
12897                    ("id", rk.iter().map(|&k| Scalar::Int64(k)).collect()),
12898                    (
12899                        "b",
12900                        (0..nr).map(|j| Scalar::Int64(j as i64 + 2000)).collect(),
12901                    ),
12902                ],
12903            )
12904            .unwrap();
12905
12906            let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
12907
12908            // Naive reference: pandas inner merge is left-major, right-minor.
12909            let mut exp_a = Vec::new();
12910            let mut exp_b = Vec::new();
12911            for (i, &left_value) in lk.iter().enumerate() {
12912                for (j, &right_value) in rk.iter().enumerate() {
12913                    if left_value == right_value {
12914                        exp_a.push(Scalar::Int64(i as i64 + 1000));
12915                        exp_b.push(Scalar::Int64(j as i64 + 2000));
12916                    }
12917                }
12918            }
12919            assert_eq!(
12920                merged.columns.get("a").unwrap().values(),
12921                exp_a.as_slice(),
12922                "left payload mismatch for lk={lk:?} rk={rk:?}"
12923            );
12924            assert_eq!(
12925                merged.columns.get("b").unwrap().values(),
12926                exp_b.as_slice(),
12927                "right payload mismatch for lk={lk:?} rk={rk:?}"
12928            );
12929
12930            // Cardinality guard for left/right/outer (dtype/order independent —
12931            // catches the row-loss class regardless of int->float promotion).
12932            let inner_pairs = exp_a.len();
12933            let left_only = lk.iter().filter(|&key| !rk.contains(key)).count();
12934            let right_only = rk.iter().filter(|&key| !lk.contains(key)).count();
12935            for (how, expected_rows) in [
12936                (JoinType::Left, inner_pairs + left_only),
12937                (JoinType::Right, inner_pairs + right_only),
12938                (JoinType::Outer, inner_pairs + left_only + right_only),
12939            ] {
12940                let m = merge_dataframes(&left, &right, "id", how).unwrap();
12941                assert_eq!(
12942                    m.columns.get("id").unwrap().len(),
12943                    expected_rows,
12944                    "{how:?} cardinality mismatch for lk={lk:?} rk={rk:?}"
12945                );
12946            }
12947        }
12948    }
12949
12950    #[test]
12951    fn merge_null_nan_keys_metamorphic_unmatched_rows_do_not_disturb_inner_tn6qb8()
12952    -> Result<(), JoinError> {
12953        let left = DataFrame::from_dict(
12954            &["id", "left_v"],
12955            vec![
12956                (
12957                    "id",
12958                    vec![
12959                        Scalar::Float64(1.0),
12960                        Scalar::Null(NullKind::NaN),
12961                        Scalar::Null(NullKind::Null),
12962                        Scalar::Float64(2.0),
12963                    ],
12964                ),
12965                (
12966                    "left_v",
12967                    vec![
12968                        Scalar::Int64(10),
12969                        Scalar::Int64(20),
12970                        Scalar::Int64(21),
12971                        Scalar::Int64(30),
12972                    ],
12973                ),
12974            ],
12975        )?;
12976        let right = DataFrame::from_dict(
12977            &["id", "right_v"],
12978            vec![
12979                (
12980                    "id",
12981                    vec![
12982                        Scalar::Null(NullKind::Null),
12983                        Scalar::Float64(2.0),
12984                        Scalar::Float64(f64::NAN),
12985                    ],
12986                ),
12987                (
12988                    "right_v",
12989                    vec![Scalar::Int64(200), Scalar::Int64(300), Scalar::Int64(201)],
12990                ),
12991            ],
12992        )?;
12993
12994        let baseline = merge_dataframes(&left, &right, "id", JoinType::Inner)?;
12995
12996        let left_with_unmatched = DataFrame::from_dict(
12997            &["id", "left_v"],
12998            vec![
12999                (
13000                    "id",
13001                    vec![
13002                        Scalar::Float64(1.0),
13003                        Scalar::Null(NullKind::NaN),
13004                        Scalar::Null(NullKind::Null),
13005                        Scalar::Float64(2.0),
13006                        Scalar::Float64(99.0),
13007                    ],
13008                ),
13009                (
13010                    "left_v",
13011                    vec![
13012                        Scalar::Int64(10),
13013                        Scalar::Int64(20),
13014                        Scalar::Int64(21),
13015                        Scalar::Int64(30),
13016                        Scalar::Int64(990),
13017                    ],
13018                ),
13019            ],
13020        )?;
13021        let right_with_unmatched = DataFrame::from_dict(
13022            &["id", "right_v"],
13023            vec![
13024                (
13025                    "id",
13026                    vec![
13027                        Scalar::Null(NullKind::Null),
13028                        Scalar::Float64(2.0),
13029                        Scalar::Float64(f64::NAN),
13030                        Scalar::Float64(100.0),
13031                    ],
13032                ),
13033                (
13034                    "right_v",
13035                    vec![
13036                        Scalar::Int64(200),
13037                        Scalar::Int64(300),
13038                        Scalar::Int64(201),
13039                        Scalar::Int64(1000),
13040                    ],
13041                ),
13042            ],
13043        )?;
13044
13045        let transformed = merge_dataframes(
13046            &left_with_unmatched,
13047            &right_with_unmatched,
13048            "id",
13049            JoinType::Inner,
13050        )?;
13051
13052        assert_eq!(
13053            merged_values(&baseline, "left_v")?,
13054            merged_values(&transformed, "left_v")?
13055        );
13056        assert_eq!(
13057            merged_values(&baseline, "right_v")?,
13058            merged_values(&transformed, "right_v")?
13059        );
13060        assert_eq!(
13061            merged_values(&baseline, "left_v")?,
13062            &[
13063                Scalar::Int64(20),
13064                Scalar::Int64(20),
13065                Scalar::Int64(21),
13066                Scalar::Int64(21),
13067                Scalar::Int64(30),
13068            ]
13069        );
13070        assert_eq!(
13071            merged_values(&baseline, "right_v")?,
13072            &[
13073                Scalar::Int64(200),
13074                Scalar::Int64(201),
13075                Scalar::Int64(200),
13076                Scalar::Int64(201),
13077                Scalar::Int64(300),
13078            ]
13079        );
13080
13081        Ok(())
13082    }
13083
13084    #[test]
13085    fn merge_mixed_dtype_missing_keys_metamorphic_outer_both_equals_inner_tn6qb8()
13086    -> Result<(), JoinError> {
13087        let left = DataFrame::from_dict(
13088            &["id", "left_v"],
13089            vec![
13090                (
13091                    "id",
13092                    vec![
13093                        Scalar::Int64(1),
13094                        Scalar::Int64(2),
13095                        Scalar::Null(NullKind::NaN),
13096                        Scalar::Int64(3),
13097                    ],
13098                ),
13099                (
13100                    "left_v",
13101                    vec![
13102                        Scalar::Float64(10.0),
13103                        Scalar::Float64(20.0),
13104                        Scalar::Float64(30.0),
13105                        Scalar::Float64(40.0),
13106                    ],
13107                ),
13108            ],
13109        )?;
13110        let right = DataFrame::from_dict(
13111            &["id", "right_v"],
13112            vec![
13113                (
13114                    "id",
13115                    vec![
13116                        Scalar::Float64(1.0),
13117                        Scalar::Float64(2.5),
13118                        Scalar::Null(NullKind::Null),
13119                        Scalar::Float64(3.0),
13120                    ],
13121                ),
13122                (
13123                    "right_v",
13124                    vec![
13125                        Scalar::Float64(100.0),
13126                        Scalar::Float64(250.0),
13127                        Scalar::Float64(300.0),
13128                        Scalar::Float64(400.0),
13129                    ],
13130                ),
13131            ],
13132        )?;
13133        let options = MergeExecutionOptions {
13134            indicator_name: Some("_merge".to_owned()),
13135            sort: true,
13136            ..MergeExecutionOptions::default()
13137        };
13138
13139        let inner = merge_dataframes_on_with_options(
13140            &left,
13141            &right,
13142            &["id"],
13143            &["id"],
13144            JoinType::Inner,
13145            options.clone(),
13146        )?;
13147        let outer = merge_dataframes_on_with_options(
13148            &left,
13149            &right,
13150            &["id"],
13151            &["id"],
13152            JoinType::Outer,
13153            options,
13154        )?;
13155
13156        assert_eq!(
13157            merged_values(&inner, "left_v")?,
13158            merged_values_where_indicator(&outer, "left_v", "_merge", "both")?
13159        );
13160        assert_eq!(
13161            merged_values(&inner, "right_v")?,
13162            merged_values_where_indicator(&outer, "right_v", "_merge", "both")?
13163        );
13164        assert_eq!(
13165            merged_values(&inner, "left_v")?,
13166            &[
13167                Scalar::Float64(10.0),
13168                Scalar::Float64(40.0),
13169                Scalar::Float64(30.0)
13170            ]
13171        );
13172        assert_eq!(
13173            merged_values(&inner, "right_v")?,
13174            &[
13175                Scalar::Float64(100.0),
13176                Scalar::Float64(400.0),
13177                Scalar::Float64(300.0)
13178            ]
13179        );
13180        assert_eq!(
13181            merged_values(&outer, "_merge")?,
13182            &[
13183                Scalar::Utf8("both".to_owned()),
13184                Scalar::Utf8("left_only".to_owned()),
13185                Scalar::Utf8("right_only".to_owned()),
13186                Scalar::Utf8("both".to_owned()),
13187                Scalar::Utf8("both".to_owned()),
13188            ]
13189        );
13190
13191        Ok(())
13192    }
13193
13194    #[test]
13195    fn merge_cross_cartesian_product() {
13196        let left = make_left_df();
13197        let right = make_right_df();
13198
13199        let merged = merge_dataframes(&left, &right, "unused_key", JoinType::Cross).unwrap();
13200
13201        assert_eq!(merged.columns.get("id_x").unwrap().len(), 9);
13202        assert_eq!(
13203            &merged.columns.get("id_x").unwrap().values()[0..3],
13204            &[Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(1)]
13205        );
13206        assert_eq!(
13207            &merged.columns.get("id_y").unwrap().values()[0..3],
13208            &[Scalar::Int64(2), Scalar::Int64(3), Scalar::Int64(4)]
13209        );
13210        assert_eq!(
13211            &merged.columns.get("val_a").unwrap().values()[0..3],
13212            &[Scalar::Int64(10), Scalar::Int64(10), Scalar::Int64(10)]
13213        );
13214        assert_eq!(
13215            &merged.columns.get("val_b").unwrap().values()[0..3],
13216            &[Scalar::Int64(200), Scalar::Int64(300), Scalar::Int64(400)]
13217        );
13218    }
13219
13220    #[test]
13221    fn merge_cross_does_not_require_on_column() {
13222        let left = make_left_df();
13223        let right = make_right_df();
13224
13225        let merged =
13226            merge_dataframes(&left, &right, "definitely_missing", JoinType::Cross).unwrap();
13227        assert_eq!(merged.columns.get("id_x").unwrap().len(), 9);
13228    }
13229
13230    #[test]
13231    fn merge_cross_with_empty_side_yields_empty_rows() {
13232        let left = DataFrame::from_dict(
13233            &["l"],
13234            vec![("l", vec![Scalar::Int64(1), Scalar::Int64(2)])],
13235        )
13236        .unwrap();
13237        let right = DataFrame::from_dict(&["r"], vec![("r", vec![])]).unwrap();
13238
13239        let merged = merge_dataframes(&left, &right, "ignored", JoinType::Cross).unwrap();
13240        assert_eq!(merged.index.labels().len(), 0);
13241        assert!(merged.columns.get("l").unwrap().values().is_empty());
13242        assert!(merged.columns.get("r").unwrap().values().is_empty());
13243    }
13244
13245    #[test]
13246    fn merge_composite_inner_multiplies_cardinality_for_duplicates() {
13247        let left = DataFrame::from_dict(
13248            &["k1", "k2", "left_v"],
13249            vec![
13250                (
13251                    "k1",
13252                    vec![Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(1)],
13253                ),
13254                (
13255                    "k2",
13256                    vec![
13257                        Scalar::Utf8("a".to_owned()),
13258                        Scalar::Utf8("a".to_owned()),
13259                        Scalar::Utf8("b".to_owned()),
13260                    ],
13261                ),
13262                (
13263                    "left_v",
13264                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
13265                ),
13266            ],
13267        )
13268        .unwrap();
13269        let right = DataFrame::from_dict(
13270            &["k1", "k2", "right_v"],
13271            vec![
13272                (
13273                    "k1",
13274                    vec![Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(1)],
13275                ),
13276                (
13277                    "k2",
13278                    vec![
13279                        Scalar::Utf8("a".to_owned()),
13280                        Scalar::Utf8("a".to_owned()),
13281                        Scalar::Utf8("c".to_owned()),
13282                    ],
13283                ),
13284                (
13285                    "right_v",
13286                    vec![Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(300)],
13287                ),
13288            ],
13289        )
13290        .unwrap();
13291
13292        let merged = merge_dataframes_on(&left, &right, &["k1", "k2"], JoinType::Inner).unwrap();
13293        assert_eq!(merged.columns.get("k1").unwrap().len(), 4);
13294        assert_eq!(
13295            merged.columns.get("k1").unwrap().values(),
13296            &[
13297                Scalar::Int64(1),
13298                Scalar::Int64(1),
13299                Scalar::Int64(1),
13300                Scalar::Int64(1)
13301            ]
13302        );
13303        assert_eq!(
13304            merged.columns.get("k2").unwrap().values(),
13305            &[
13306                Scalar::Utf8("a".to_owned()),
13307                Scalar::Utf8("a".to_owned()),
13308                Scalar::Utf8("a".to_owned()),
13309                Scalar::Utf8("a".to_owned())
13310            ]
13311        );
13312        assert_eq!(
13313            merged.columns.get("left_v").unwrap().values(),
13314            &[
13315                Scalar::Int64(10),
13316                Scalar::Int64(10),
13317                Scalar::Int64(20),
13318                Scalar::Int64(20)
13319            ]
13320        );
13321        assert_eq!(
13322            merged.columns.get("right_v").unwrap().values(),
13323            &[
13324                Scalar::Int64(100),
13325                Scalar::Int64(200),
13326                Scalar::Int64(100),
13327                Scalar::Int64(200)
13328            ]
13329        );
13330    }
13331
13332    #[test]
13333    fn merge_composite_outer_sorts_join_keys_lexicographically() {
13334        let left = DataFrame::from_dict(
13335            &["k1", "k2", "left_v"],
13336            vec![
13337                ("k1", vec![Scalar::Int64(2), Scalar::Int64(1)]),
13338                (
13339                    "k2",
13340                    vec![Scalar::Utf8("y".to_owned()), Scalar::Utf8("x".to_owned())],
13341                ),
13342                ("left_v", vec![Scalar::Int64(20), Scalar::Int64(10)]),
13343            ],
13344        )
13345        .unwrap();
13346        let right = DataFrame::from_dict(
13347            &["k1", "k2", "right_v"],
13348            vec![
13349                ("k1", vec![Scalar::Int64(2), Scalar::Int64(3)]),
13350                (
13351                    "k2",
13352                    vec![Scalar::Utf8("y".to_owned()), Scalar::Utf8("z".to_owned())],
13353                ),
13354                ("right_v", vec![Scalar::Int64(200), Scalar::Int64(300)]),
13355            ],
13356        )
13357        .unwrap();
13358
13359        let merged = merge_dataframes_on(&left, &right, &["k1", "k2"], JoinType::Outer).unwrap();
13360        assert_eq!(
13361            merged.columns.get("k1").unwrap().values(),
13362            &[Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)]
13363        );
13364        assert_eq!(
13365            merged.columns.get("k2").unwrap().values(),
13366            &[
13367                Scalar::Utf8("x".to_owned()),
13368                Scalar::Utf8("y".to_owned()),
13369                Scalar::Utf8("z".to_owned())
13370            ]
13371        );
13372        assert_eq!(
13373            merged.columns.get("left_v").unwrap().values(),
13374            &[
13375                Scalar::Float64(10.0),
13376                Scalar::Float64(20.0),
13377                Scalar::Null(NullKind::NaN)
13378            ]
13379        );
13380        assert_eq!(
13381            merged.columns.get("right_v").unwrap().values(),
13382            &[
13383                Scalar::Null(NullKind::NaN),
13384                Scalar::Float64(200.0),
13385                Scalar::Float64(300.0)
13386            ]
13387        );
13388    }
13389
13390    #[test]
13391    fn merge_composite_inner_matches_missing_key_components() {
13392        let left = DataFrame::from_dict(
13393            &["k1", "k2", "left_v"],
13394            vec![
13395                ("k1", vec![Scalar::Int64(1), Scalar::Int64(1)]),
13396                (
13397                    "k2",
13398                    vec![Scalar::Null(NullKind::Null), Scalar::Utf8("a".to_owned())],
13399                ),
13400                ("left_v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
13401            ],
13402        )
13403        .unwrap();
13404        let right = DataFrame::from_dict(
13405            &["k1", "k2", "right_v"],
13406            vec![
13407                (
13408                    "k1",
13409                    vec![Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(2)],
13410                ),
13411                (
13412                    "k2",
13413                    vec![
13414                        Scalar::Null(NullKind::Null),
13415                        Scalar::Utf8("a".to_owned()),
13416                        Scalar::Null(NullKind::Null),
13417                    ],
13418                ),
13419                (
13420                    "right_v",
13421                    vec![Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(300)],
13422                ),
13423            ],
13424        )
13425        .unwrap();
13426
13427        let merged = merge_dataframes_on(&left, &right, &["k1", "k2"], JoinType::Inner).unwrap();
13428        assert_eq!(
13429            merged.columns.get("k1").unwrap().values(),
13430            &[Scalar::Int64(1), Scalar::Int64(1)]
13431        );
13432        assert_eq!(
13433            merged.columns.get("k2").unwrap().values(),
13434            &[Scalar::Null(NullKind::Null), Scalar::Utf8("a".to_owned())]
13435        );
13436        assert_eq!(
13437            merged.columns.get("left_v").unwrap().values(),
13438            &[Scalar::Int64(10), Scalar::Int64(20)]
13439        );
13440        assert_eq!(
13441            merged.columns.get("right_v").unwrap().values(),
13442            &[Scalar::Int64(100), Scalar::Int64(200)]
13443        );
13444    }
13445
13446    #[test]
13447    fn merge_composite_outer_keeps_right_only_rows_with_missing_keys() {
13448        let left = DataFrame::from_dict(
13449            &["k1", "k2", "left_v"],
13450            vec![
13451                ("k1", vec![Scalar::Int64(1)]),
13452                ("k2", vec![Scalar::Null(NullKind::Null)]),
13453                ("left_v", vec![Scalar::Int64(10)]),
13454            ],
13455        )
13456        .unwrap();
13457        let right = DataFrame::from_dict(
13458            &["k1", "k2", "right_v"],
13459            vec![
13460                ("k1", vec![Scalar::Int64(1), Scalar::Int64(2)]),
13461                (
13462                    "k2",
13463                    vec![Scalar::Null(NullKind::Null), Scalar::Null(NullKind::Null)],
13464                ),
13465                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
13466            ],
13467        )
13468        .unwrap();
13469
13470        let merged = merge_dataframes_on(&left, &right, &["k1", "k2"], JoinType::Outer).unwrap();
13471        assert_eq!(
13472            merged.columns.get("k1").unwrap().values(),
13473            &[Scalar::Int64(1), Scalar::Int64(2)]
13474        );
13475        assert_eq!(
13476            merged.columns.get("k2").unwrap().values(),
13477            &[Scalar::Null(NullKind::Null), Scalar::Null(NullKind::Null)]
13478        );
13479        assert_eq!(
13480            merged.columns.get("left_v").unwrap().values(),
13481            &[Scalar::Float64(10.0), Scalar::Null(NullKind::NaN)]
13482        );
13483        assert_eq!(
13484            merged.columns.get("right_v").unwrap().values(),
13485            &[Scalar::Int64(100), Scalar::Int64(200)]
13486        );
13487    }
13488
13489    #[test]
13490    fn merge_composite_missing_key_column_errors() {
13491        let left = DataFrame::from_dict(
13492            &["k1", "k2", "left_v"],
13493            vec![
13494                ("k1", vec![Scalar::Int64(1)]),
13495                ("k2", vec![Scalar::Utf8("x".to_owned())]),
13496                ("left_v", vec![Scalar::Int64(10)]),
13497            ],
13498        )
13499        .unwrap();
13500        let right = DataFrame::from_dict(
13501            &["k1", "right_v"],
13502            vec![
13503                ("k1", vec![Scalar::Int64(1)]),
13504                ("right_v", vec![Scalar::Int64(100)]),
13505            ],
13506        )
13507        .unwrap();
13508
13509        let err = merge_dataframes_on(&left, &right, &["k1", "k2"], JoinType::Inner)
13510            .expect_err("should fail");
13511        assert!(format!("{err}").contains("right DataFrame missing key column 'k2'"));
13512    }
13513
13514    #[test]
13515    fn merge_composite_key_alias_inner_keeps_both_key_sets() {
13516        let left = DataFrame::from_dict(
13517            &["lk1", "lk2", "left_v"],
13518            vec![
13519                (
13520                    "lk1",
13521                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
13522                ),
13523                (
13524                    "lk2",
13525                    vec![
13526                        Scalar::Utf8("a".to_owned()),
13527                        Scalar::Utf8("b".to_owned()),
13528                        Scalar::Utf8("c".to_owned()),
13529                    ],
13530                ),
13531                (
13532                    "left_v",
13533                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
13534                ),
13535            ],
13536        )
13537        .unwrap();
13538        let right = DataFrame::from_dict(
13539            &["rk1", "rk2", "right_v"],
13540            vec![
13541                (
13542                    "rk1",
13543                    vec![Scalar::Int64(2), Scalar::Int64(3), Scalar::Int64(4)],
13544                ),
13545                (
13546                    "rk2",
13547                    vec![
13548                        Scalar::Utf8("b".to_owned()),
13549                        Scalar::Utf8("c".to_owned()),
13550                        Scalar::Utf8("d".to_owned()),
13551                    ],
13552                ),
13553                (
13554                    "right_v",
13555                    vec![Scalar::Int64(200), Scalar::Int64(300), Scalar::Int64(400)],
13556                ),
13557            ],
13558        )
13559        .unwrap();
13560
13561        let merged = merge_dataframes_on_with(
13562            &left,
13563            &right,
13564            &["lk1", "lk2"],
13565            &["rk1", "rk2"],
13566            JoinType::Inner,
13567        )
13568        .unwrap();
13569        assert_eq!(
13570            merged.columns.get("lk1").unwrap().values(),
13571            &[Scalar::Int64(2), Scalar::Int64(3)]
13572        );
13573        assert_eq!(
13574            merged.columns.get("lk2").unwrap().values(),
13575            &[Scalar::Utf8("b".to_owned()), Scalar::Utf8("c".to_owned())]
13576        );
13577        assert_eq!(
13578            merged.columns.get("left_v").unwrap().values(),
13579            &[Scalar::Int64(20), Scalar::Int64(30)]
13580        );
13581        assert_eq!(
13582            merged.columns.get("rk1").unwrap().values(),
13583            &[Scalar::Int64(2), Scalar::Int64(3)]
13584        );
13585        assert_eq!(
13586            merged.columns.get("rk2").unwrap().values(),
13587            &[Scalar::Utf8("b".to_owned()), Scalar::Utf8("c".to_owned())]
13588        );
13589        assert_eq!(
13590            merged.columns.get("right_v").unwrap().values(),
13591            &[Scalar::Int64(200), Scalar::Int64(300)]
13592        );
13593    }
13594
13595    #[test]
13596    fn merge_composite_key_alias_outer_propagates_missing_per_side() {
13597        let left = DataFrame::from_dict(
13598            &["lk1", "lk2", "left_v"],
13599            vec![
13600                (
13601                    "lk1",
13602                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
13603                ),
13604                (
13605                    "lk2",
13606                    vec![
13607                        Scalar::Utf8("a".to_owned()),
13608                        Scalar::Null(NullKind::Null),
13609                        Scalar::Utf8("c".to_owned()),
13610                    ],
13611                ),
13612                (
13613                    "left_v",
13614                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
13615                ),
13616            ],
13617        )
13618        .unwrap();
13619        let right = DataFrame::from_dict(
13620            &["rk1", "rk2", "right_v"],
13621            vec![
13622                (
13623                    "rk1",
13624                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(4)],
13625                ),
13626                (
13627                    "rk2",
13628                    vec![
13629                        Scalar::Utf8("a".to_owned()),
13630                        Scalar::Null(NullKind::Null),
13631                        Scalar::Utf8("d".to_owned()),
13632                    ],
13633                ),
13634                (
13635                    "right_v",
13636                    vec![Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(400)],
13637                ),
13638            ],
13639        )
13640        .unwrap();
13641
13642        let merged = merge_dataframes_on_with(
13643            &left,
13644            &right,
13645            &["lk1", "lk2"],
13646            &["rk1", "rk2"],
13647            JoinType::Outer,
13648        )
13649        .unwrap();
13650
13651        assert_eq!(
13652            merged.columns.get("lk1").unwrap().values(),
13653            &[
13654                Scalar::Float64(1.0),
13655                Scalar::Float64(2.0),
13656                Scalar::Float64(3.0),
13657                Scalar::Null(NullKind::NaN)
13658            ]
13659        );
13660        assert_eq!(
13661            merged.columns.get("rk1").unwrap().values(),
13662            &[
13663                Scalar::Float64(1.0),
13664                Scalar::Float64(2.0),
13665                Scalar::Null(NullKind::NaN),
13666                Scalar::Float64(4.0)
13667            ]
13668        );
13669        assert_eq!(
13670            merged.columns.get("left_v").unwrap().values(),
13671            &[
13672                Scalar::Float64(10.0),
13673                Scalar::Float64(20.0),
13674                Scalar::Float64(30.0),
13675                Scalar::Null(NullKind::NaN)
13676            ]
13677        );
13678        assert_eq!(
13679            merged.columns.get("right_v").unwrap().values(),
13680            &[
13681                Scalar::Float64(100.0),
13682                Scalar::Float64(200.0),
13683                Scalar::Null(NullKind::NaN),
13684                Scalar::Float64(400.0)
13685            ]
13686        );
13687    }
13688
13689    #[test]
13690    fn merge_key_alias_lists_must_have_equal_lengths() {
13691        let left = make_left_df();
13692        let right = make_right_df();
13693        let err = merge_dataframes_on_with(&left, &right, &["id", "id"], &["id"], JoinType::Inner)
13694            .expect_err("should fail");
13695        assert!(format!("{err}").contains("equal length"));
13696    }
13697
13698    #[test]
13699    fn merge_indicator_default_name_tracks_row_provenance() {
13700        let left = make_left_df();
13701        let right = make_right_df();
13702
13703        let merged = merge_dataframes_on_with_options(
13704            &left,
13705            &right,
13706            &["id"],
13707            &["id"],
13708            JoinType::Outer,
13709            MergeExecutionOptions {
13710                indicator_name: Some("_merge".to_owned()),
13711                ..MergeExecutionOptions::default()
13712            },
13713        )
13714        .expect("merge");
13715
13716        assert_eq!(
13717            merged.columns.get("_merge").expect("indicator").values(),
13718            &[
13719                Scalar::Utf8("left_only".to_owned()),
13720                Scalar::Utf8("both".to_owned()),
13721                Scalar::Utf8("both".to_owned()),
13722                Scalar::Utf8("right_only".to_owned())
13723            ]
13724        );
13725    }
13726
13727    #[test]
13728    fn merge_indicator_custom_name_preserves_suffix_behavior() {
13729        let left = DataFrame::from_dict(
13730            &["id", "val"],
13731            vec![
13732                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
13733                ("val", vec![Scalar::Int64(10), Scalar::Int64(20)]),
13734            ],
13735        )
13736        .unwrap();
13737        let right = DataFrame::from_dict(
13738            &["id", "val"],
13739            vec![
13740                ("id", vec![Scalar::Int64(2), Scalar::Int64(3)]),
13741                ("val", vec![Scalar::Int64(200), Scalar::Int64(300)]),
13742            ],
13743        )
13744        .unwrap();
13745
13746        let merged = merge_dataframes_on_with_options(
13747            &left,
13748            &right,
13749            &["id"],
13750            &["id"],
13751            JoinType::Outer,
13752            MergeExecutionOptions {
13753                indicator_name: Some("origin".to_owned()),
13754                ..MergeExecutionOptions::default()
13755            },
13756        )
13757        .expect("merge");
13758
13759        assert!(merged.columns.contains_key("val_x"));
13760        assert!(merged.columns.contains_key("val_y"));
13761        assert_eq!(
13762            merged.columns.get("origin").expect("indicator").values(),
13763            &[
13764                Scalar::Utf8("left_only".to_owned()),
13765                Scalar::Utf8("both".to_owned()),
13766                Scalar::Utf8("right_only".to_owned())
13767            ]
13768        );
13769    }
13770
13771    #[test]
13772    fn merge_indicator_rejects_conflicting_column_name() {
13773        let left = make_left_df();
13774        let right = make_right_df();
13775
13776        let err = merge_dataframes_on_with_options(
13777            &left,
13778            &right,
13779            &["id"],
13780            &["id"],
13781            JoinType::Inner,
13782            MergeExecutionOptions {
13783                indicator_name: Some("id".to_owned()),
13784                ..MergeExecutionOptions::default()
13785            },
13786        )
13787        .expect_err("expected indicator name conflict");
13788        assert!(format!("{err}").contains("conflicts with an existing column"));
13789    }
13790
13791    #[test]
13792    fn merge_cross_indicator_marks_all_rows_both() {
13793        // Restored after br-frankenpandas-glsam revert: pandas 2.2.3
13794        // supports `how='cross', indicator=...` and emits "both" for every
13795        // cross-product row (verified against FP-P2D-039 fixture provenance
13796        // pandas_version=2.2.3). The Explore-agent claim that pandas raises
13797        // was incorrect; this test locks in the actual pandas behavior.
13798        let left = DataFrame::from_dict(
13799            &["l"],
13800            vec![("l", vec![Scalar::Int64(1), Scalar::Int64(2)])],
13801        )
13802        .unwrap();
13803        let right = DataFrame::from_dict(&["r"], vec![("r", vec![Scalar::Int64(9)])]).unwrap();
13804
13805        let merged = merge_dataframes_on_with_options(
13806            &left,
13807            &right,
13808            &["ignored"],
13809            &["ignored"],
13810            JoinType::Cross,
13811            MergeExecutionOptions {
13812                indicator_name: Some("_merge".to_owned()),
13813                ..MergeExecutionOptions::default()
13814            },
13815        )
13816        .expect("cross merge");
13817        assert_eq!(
13818            merged.columns.get("_merge").expect("indicator").values(),
13819            &[
13820                Scalar::Utf8("both".to_owned()),
13821                Scalar::Utf8("both".to_owned())
13822            ]
13823        );
13824    }
13825
13826    #[test]
13827    fn merge_cross_validate_mode_contract_ohb5f() {
13828        let left = DataFrame::from_dict(
13829            &["l"],
13830            vec![("l", vec![Scalar::Int64(1), Scalar::Int64(2)])],
13831        )
13832        .expect("left");
13833        let right = DataFrame::from_dict(
13834            &["r"],
13835            vec![("r", vec![Scalar::Int64(10), Scalar::Int64(20)])],
13836        )
13837        .expect("right");
13838
13839        let many_to_many = merge_dataframes_on_with_options(
13840            &left,
13841            &right,
13842            &["missing_left_key"],
13843            &["missing_right_key"],
13844            JoinType::Cross,
13845            MergeExecutionOptions {
13846                validate_mode: Some(MergeValidateMode::ManyToMany),
13847                ..MergeExecutionOptions::default()
13848            },
13849        )
13850        .expect("cross merge validate=many_to_many");
13851        assert_eq!(many_to_many.index.len(), 4);
13852
13853        for validate_mode in [
13854            MergeValidateMode::OneToOne,
13855            MergeValidateMode::OneToMany,
13856            MergeValidateMode::ManyToOne,
13857        ] {
13858            let err = merge_dataframes_on_with_options(
13859                &left,
13860                &right,
13861                &["missing_left_key"],
13862                &["missing_right_key"],
13863                JoinType::Cross,
13864                MergeExecutionOptions {
13865                    validate_mode: Some(validate_mode),
13866                    ..MergeExecutionOptions::default()
13867                },
13868            )
13869            .expect_err("enforcing validate modes are not meaningful for cross joins");
13870            let message = format!("{err}");
13871            assert!(message.contains(validate_mode.as_str()));
13872            assert!(message.contains("not supported for cross join"));
13873        }
13874    }
13875
13876    #[test]
13877    fn merge_validate_one_to_one_rejects_duplicate_left_keys() {
13878        let left = DataFrame::from_dict(
13879            &["id", "left_v"],
13880            vec![
13881                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
13882                ("left_v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
13883            ],
13884        )
13885        .expect("left frame");
13886        let right = DataFrame::from_dict(
13887            &["id", "right_v"],
13888            vec![
13889                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
13890                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
13891            ],
13892        )
13893        .expect("right frame");
13894
13895        let err = merge_dataframes_on_with_options(
13896            &left,
13897            &right,
13898            &["id"],
13899            &["id"],
13900            JoinType::Inner,
13901            MergeExecutionOptions {
13902                validate_mode: Some(MergeValidateMode::OneToOne),
13903                ..MergeExecutionOptions::default()
13904            },
13905        )
13906        .expect_err("one_to_one must reject duplicate left keys");
13907        assert!(format!("{err}").contains("left keys are not unique"));
13908    }
13909
13910    #[test]
13911    fn merge_validate_one_to_many_allows_duplicate_right_keys() {
13912        let left = DataFrame::from_dict(
13913            &["id", "left_v"],
13914            vec![
13915                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
13916                ("left_v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
13917            ],
13918        )
13919        .expect("left frame");
13920        let right = DataFrame::from_dict(
13921            &["id", "right_v"],
13922            vec![
13923                (
13924                    "id",
13925                    vec![Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(2)],
13926                ),
13927                (
13928                    "right_v",
13929                    vec![Scalar::Int64(100), Scalar::Int64(101), Scalar::Int64(200)],
13930                ),
13931            ],
13932        )
13933        .expect("right frame");
13934
13935        let merged = merge_dataframes_on_with_options(
13936            &left,
13937            &right,
13938            &["id"],
13939            &["id"],
13940            JoinType::Inner,
13941            MergeExecutionOptions {
13942                validate_mode: Some(MergeValidateMode::OneToMany),
13943                ..MergeExecutionOptions::default()
13944            },
13945        )
13946        .expect("one_to_many should allow duplicate right keys");
13947        assert_eq!(merged.columns.get("id").expect("id").values().len(), 3);
13948    }
13949
13950    #[test]
13951    fn merge_validate_one_to_many_rejects_duplicate_left_keys_9hsb3() {
13952        let left = DataFrame::from_dict(
13953            &["id", "left_v"],
13954            vec![
13955                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
13956                ("left_v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
13957            ],
13958        )
13959        .expect("left frame");
13960        let right = DataFrame::from_dict(
13961            &["id", "right_v"],
13962            vec![
13963                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
13964                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
13965            ],
13966        )
13967        .expect("right frame");
13968
13969        let err = merge_dataframes_on_with_options(
13970            &left,
13971            &right,
13972            &["id"],
13973            &["id"],
13974            JoinType::Inner,
13975            MergeExecutionOptions {
13976                validate_mode: Some(MergeValidateMode::OneToMany),
13977                ..MergeExecutionOptions::default()
13978            },
13979        )
13980        .expect_err("one_to_many must reject duplicate left keys");
13981        assert!(format!("{err}").contains("left keys are not unique"));
13982    }
13983
13984    #[test]
13985    fn merge_validate_many_to_one_rejects_duplicate_right_keys() {
13986        let left = DataFrame::from_dict(
13987            &["id", "left_v"],
13988            vec![
13989                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
13990                ("left_v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
13991            ],
13992        )
13993        .expect("left frame");
13994        let right = DataFrame::from_dict(
13995            &["id", "right_v"],
13996            vec![
13997                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
13998                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(101)]),
13999            ],
14000        )
14001        .expect("right frame");
14002
14003        let err = merge_dataframes_on_with_options(
14004            &left,
14005            &right,
14006            &["id"],
14007            &["id"],
14008            JoinType::Inner,
14009            MergeExecutionOptions {
14010                validate_mode: Some(MergeValidateMode::ManyToOne),
14011                ..MergeExecutionOptions::default()
14012            },
14013        )
14014        .expect_err("many_to_one must reject duplicate right keys");
14015        assert!(format!("{err}").contains("right keys are not unique"));
14016    }
14017
14018    #[test]
14019    fn merge_validate_many_to_one_allows_duplicate_left_keys_9hsb3() {
14020        let left = DataFrame::from_dict(
14021            &["id", "left_v"],
14022            vec![
14023                (
14024                    "id",
14025                    vec![Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(2)],
14026                ),
14027                (
14028                    "left_v",
14029                    vec![Scalar::Int64(10), Scalar::Int64(11), Scalar::Int64(20)],
14030                ),
14031            ],
14032        )
14033        .expect("left frame");
14034        let right = DataFrame::from_dict(
14035            &["id", "right_v"],
14036            vec![
14037                ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
14038                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
14039            ],
14040        )
14041        .expect("right frame");
14042
14043        let merged = merge_dataframes_on_with_options(
14044            &left,
14045            &right,
14046            &["id"],
14047            &["id"],
14048            JoinType::Inner,
14049            MergeExecutionOptions {
14050                validate_mode: Some(MergeValidateMode::ManyToOne),
14051                ..MergeExecutionOptions::default()
14052            },
14053        )
14054        .expect("many_to_one should allow duplicate left keys");
14055        assert_eq!(merged.columns.get("id").expect("id").values().len(), 3);
14056    }
14057
14058    #[test]
14059    fn merge_validate_many_to_many_allows_duplicates_on_both_sides() {
14060        let left = DataFrame::from_dict(
14061            &["id", "left_v"],
14062            vec![
14063                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
14064                ("left_v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
14065            ],
14066        )
14067        .expect("left frame");
14068        let right = DataFrame::from_dict(
14069            &["id", "right_v"],
14070            vec![
14071                ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
14072                ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
14073            ],
14074        )
14075        .expect("right frame");
14076
14077        let merged = merge_dataframes_on_with_options(
14078            &left,
14079            &right,
14080            &["id"],
14081            &["id"],
14082            JoinType::Inner,
14083            MergeExecutionOptions {
14084                validate_mode: Some(MergeValidateMode::ManyToMany),
14085                ..MergeExecutionOptions::default()
14086            },
14087        )
14088        .expect("many_to_many should allow duplicate keys on both sides");
14089        assert_eq!(merged.columns.get("id").expect("id").values().len(), 4);
14090    }
14091
14092    #[test]
14093    fn join_series_cross_cartesian_product() {
14094        let left = Series::from_values(
14095            "left",
14096            vec!["a".into(), "b".into()],
14097            vec![Scalar::Int64(1), Scalar::Int64(2)],
14098        )
14099        .unwrap();
14100        let right = Series::from_values(
14101            "right",
14102            vec!["x".into(), "y".into()],
14103            vec![Scalar::Int64(10), Scalar::Int64(20)],
14104        )
14105        .unwrap();
14106
14107        let out = join_series(&left, &right, JoinType::Cross).unwrap();
14108        assert_eq!(out.index.labels().len(), 4);
14109        assert_eq!(
14110            out.left_values.values(),
14111            &[
14112                Scalar::Int64(1),
14113                Scalar::Int64(1),
14114                Scalar::Int64(2),
14115                Scalar::Int64(2)
14116            ]
14117        );
14118        assert_eq!(
14119            out.right_values.values(),
14120            &[
14121                Scalar::Int64(10),
14122                Scalar::Int64(20),
14123                Scalar::Int64(10),
14124                Scalar::Int64(20)
14125            ]
14126        );
14127    }
14128
14129    // ── DataFrameMergeExt trait tests ──
14130
14131    #[test]
14132    fn dataframe_merge_via_trait() {
14133        use fp_frame::DataFrame;
14134
14135        use super::{DataFrameMergeExt, merge_dataframes_on};
14136
14137        let left = DataFrame::from_series(vec![
14138            Series::from_values(
14139                "key",
14140                vec![0_i64.into(), 1_i64.into()],
14141                vec![Scalar::Int64(1), Scalar::Int64(2)],
14142            )
14143            .unwrap(),
14144            Series::from_values(
14145                "val_l",
14146                vec![0_i64.into(), 1_i64.into()],
14147                vec![Scalar::Int64(10), Scalar::Int64(20)],
14148            )
14149            .unwrap(),
14150        ])
14151        .unwrap();
14152
14153        let right = DataFrame::from_series(vec![
14154            Series::from_values(
14155                "key",
14156                vec![0_i64.into(), 1_i64.into()],
14157                vec![Scalar::Int64(1), Scalar::Int64(3)],
14158            )
14159            .unwrap(),
14160            Series::from_values(
14161                "val_r",
14162                vec![0_i64.into(), 1_i64.into()],
14163                vec![Scalar::Int64(100), Scalar::Int64(300)],
14164            )
14165            .unwrap(),
14166        ])
14167        .unwrap();
14168
14169        // Instance method
14170        let result = left.merge(&right, &["key"], JoinType::Inner).unwrap();
14171        assert_eq!(result.index.len(), 1); // only key=1 matches
14172
14173        // Standalone function should give same result
14174        let result2 = merge_dataframes_on(&left, &right, &["key"], JoinType::Inner).unwrap();
14175        assert_eq!(result.index.len(), result2.index.len());
14176    }
14177
14178    // ── merge_asof tests ──
14179
14180    #[test]
14181    fn merge_asof_backward() {
14182        use super::DataFrameMergeExt;
14183
14184        // Left: trades at times 1, 3, 5, 7
14185        let left = fp_frame::DataFrame::from_dict(
14186            &["time", "price"],
14187            vec![
14188                (
14189                    "time",
14190                    vec![
14191                        Scalar::Int64(1),
14192                        Scalar::Int64(3),
14193                        Scalar::Int64(5),
14194                        Scalar::Int64(7),
14195                    ],
14196                ),
14197                (
14198                    "price",
14199                    vec![
14200                        Scalar::Float64(100.0),
14201                        Scalar::Float64(101.0),
14202                        Scalar::Float64(102.0),
14203                        Scalar::Float64(103.0),
14204                    ],
14205                ),
14206            ],
14207        )
14208        .unwrap();
14209
14210        // Right: quotes at times 2, 4, 6
14211        let right = fp_frame::DataFrame::from_dict(
14212            &["time", "bid"],
14213            vec![
14214                (
14215                    "time",
14216                    vec![Scalar::Int64(2), Scalar::Int64(4), Scalar::Int64(6)],
14217                ),
14218                (
14219                    "bid",
14220                    vec![
14221                        Scalar::Float64(99.5),
14222                        Scalar::Float64(100.5),
14223                        Scalar::Float64(101.5),
14224                    ],
14225                ),
14226            ],
14227        )
14228        .unwrap();
14229
14230        let result = left.merge_asof(&right, "time", "backward").unwrap();
14231        // For time=1: no right row <= 1, so bid=NaN
14232        // For time=3: last right row <= 3 is time=2 → bid=99.5
14233        // For time=5: last right row <= 5 is time=4 → bid=100.5
14234        // For time=7: last right row <= 7 is time=6 → bid=101.5
14235        let bid_col = result.columns.get("bid").unwrap();
14236        assert!(bid_col.values()[0].is_missing());
14237        assert_eq!(bid_col.values()[1], Scalar::Float64(99.5));
14238        assert_eq!(bid_col.values()[2], Scalar::Float64(100.5));
14239        assert_eq!(bid_col.values()[3], Scalar::Float64(101.5));
14240    }
14241
14242    #[test]
14243    fn merge_asof_forward() {
14244        use super::AsofDirection;
14245
14246        let left = fp_frame::DataFrame::from_dict(
14247            &["time", "val"],
14248            vec![
14249                ("time", vec![Scalar::Int64(1), Scalar::Int64(3)]),
14250                ("val", vec![Scalar::Float64(10.0), Scalar::Float64(30.0)]),
14251            ],
14252        )
14253        .unwrap();
14254
14255        let right = fp_frame::DataFrame::from_dict(
14256            &["time", "quote"],
14257            vec![
14258                ("time", vec![Scalar::Int64(2), Scalar::Int64(5)]),
14259                ("quote", vec![Scalar::Float64(20.0), Scalar::Float64(50.0)]),
14260            ],
14261        )
14262        .unwrap();
14263
14264        let result = super::merge_asof(&left, &right, "time", AsofDirection::Forward).unwrap();
14265        // time=1: first right >= 1 is time=2 → quote=20
14266        // time=3: first right >= 3 is time=5 → quote=50
14267        let quote_col = result.columns.get("quote").unwrap();
14268        assert_eq!(quote_col.values()[0], Scalar::Float64(20.0));
14269        assert_eq!(quote_col.values()[1], Scalar::Float64(50.0));
14270    }
14271
14272    #[test]
14273    fn merge_asof_nearest() {
14274        use super::AsofDirection;
14275
14276        let left = fp_frame::DataFrame::from_dict(
14277            &["time", "val"],
14278            vec![
14279                ("time", vec![Scalar::Int64(3), Scalar::Int64(7)]),
14280                ("val", vec![Scalar::Float64(1.0), Scalar::Float64(2.0)]),
14281            ],
14282        )
14283        .unwrap();
14284
14285        let right = fp_frame::DataFrame::from_dict(
14286            &["time", "ref_val"],
14287            vec![
14288                (
14289                    "time",
14290                    vec![Scalar::Int64(1), Scalar::Int64(5), Scalar::Int64(10)],
14291                ),
14292                (
14293                    "ref_val",
14294                    vec![
14295                        Scalar::Float64(100.0),
14296                        Scalar::Float64(500.0),
14297                        Scalar::Float64(1000.0),
14298                    ],
14299                ),
14300            ],
14301        )
14302        .unwrap();
14303
14304        let result = super::merge_asof(&left, &right, "time", AsofDirection::Nearest).unwrap();
14305        // time=3: nearest is 1(dist=2) or 5(dist=2), first found = 1 → ref_val=100
14306        // Actually: for nearest, it finds the one with smallest dist. dist(3,1)=2, dist(3,5)=2
14307        // ties go to first found, so ref_val = 100
14308        // time=7: nearest is 5(dist=2) or 10(dist=3) → ref_val=500
14309        let ref_col = result.columns.get("ref_val").unwrap();
14310        assert_eq!(ref_col.values()[1], Scalar::Float64(500.0)); // time=7 → 5 is nearest
14311    }
14312
14313    #[test]
14314    fn merge_asof_nearest_excludes_exact_finds_neighbor() {
14315        // Regression: with direction=nearest and allow_exact_matches=false,
14316        // an exact-equal key must be skipped over to reach the nearest
14317        // non-equal key, rather than yielding no match. Verified against
14318        // pandas 2.2.3: merge_asof(left=5, right=[3,5,5], nearest,
14319        // allow_exact_matches=False) -> matches value 3.
14320        use super::{AsofDirection, MergeAsofOptions};
14321
14322        let left = fp_frame::DataFrame::from_dict(
14323            &["time", "val"],
14324            vec![
14325                ("time", vec![Scalar::Int64(5)]),
14326                ("val", vec![Scalar::Int64(1)]),
14327            ],
14328        )
14329        .unwrap();
14330        let right = fp_frame::DataFrame::from_dict(
14331            &["time", "ref_val"],
14332            vec![
14333                (
14334                    "time",
14335                    vec![Scalar::Int64(3), Scalar::Int64(5), Scalar::Int64(5)],
14336                ),
14337                (
14338                    "ref_val",
14339                    vec![
14340                        Scalar::Float64(10.0),
14341                        Scalar::Float64(20.0),
14342                        Scalar::Float64(30.0),
14343                    ],
14344                ),
14345            ],
14346        )
14347        .unwrap();
14348
14349        let opts = MergeAsofOptions::new().allow_exact_matches(false);
14350        let result =
14351            super::merge_asof_with_options(&left, &right, "time", AsofDirection::Nearest, opts)
14352                .unwrap();
14353        let ref_col = result.columns.get("ref_val").unwrap();
14354        assert_eq!(ref_col.values()[0], Scalar::Float64(10.0)); // value 3 is nearest non-exact
14355    }
14356
14357    #[test]
14358    fn merge_asof_exact_match() {
14359        use super::AsofDirection;
14360
14361        let left = fp_frame::DataFrame::from_dict(
14362            &["time", "val"],
14363            vec![
14364                ("time", vec![Scalar::Int64(2), Scalar::Int64(4)]),
14365                ("val", vec![Scalar::Float64(1.0), Scalar::Float64(2.0)]),
14366            ],
14367        )
14368        .unwrap();
14369
14370        let right = fp_frame::DataFrame::from_dict(
14371            &["time", "quote"],
14372            vec![
14373                ("time", vec![Scalar::Int64(2), Scalar::Int64(4)]),
14374                ("quote", vec![Scalar::Float64(20.0), Scalar::Float64(40.0)]),
14375            ],
14376        )
14377        .unwrap();
14378
14379        // Backward: exact match should work (right_val <= left_val includes ==).
14380        let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
14381        assert_eq!(
14382            result.columns.get("quote").unwrap().values()[0],
14383            Scalar::Float64(20.0)
14384        );
14385        assert_eq!(
14386            result.columns.get("quote").unwrap().values()[1],
14387            Scalar::Float64(40.0)
14388        );
14389
14390        // Forward: exact match should work (right_val >= left_val includes ==).
14391        let result = super::merge_asof(&left, &right, "time", AsofDirection::Forward).unwrap();
14392        assert_eq!(
14393            result.columns.get("quote").unwrap().values()[0],
14394            Scalar::Float64(20.0)
14395        );
14396    }
14397
14398    #[test]
14399    fn merge_asof_no_matches_backward() {
14400        use super::AsofDirection;
14401
14402        let left = fp_frame::DataFrame::from_dict(
14403            &["time", "val"],
14404            vec![
14405                ("time", vec![Scalar::Int64(1)]),
14406                ("val", vec![Scalar::Float64(10.0)]),
14407            ],
14408        )
14409        .unwrap();
14410
14411        // Right starts at time=5, so backward from time=1 finds nothing.
14412        let right = fp_frame::DataFrame::from_dict(
14413            &["time", "quote"],
14414            vec![
14415                ("time", vec![Scalar::Int64(5)]),
14416                ("quote", vec![Scalar::Float64(50.0)]),
14417            ],
14418        )
14419        .unwrap();
14420
14421        let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
14422        assert!(result.columns.get("quote").unwrap().values()[0].is_missing());
14423    }
14424
14425    #[test]
14426    fn merge_asof_no_matches_forward() {
14427        use super::AsofDirection;
14428
14429        let left = fp_frame::DataFrame::from_dict(
14430            &["time", "val"],
14431            vec![
14432                ("time", vec![Scalar::Int64(10)]),
14433                ("val", vec![Scalar::Float64(10.0)]),
14434            ],
14435        )
14436        .unwrap();
14437
14438        // Right ends at time=5, so forward from time=10 finds nothing.
14439        let right = fp_frame::DataFrame::from_dict(
14440            &["time", "quote"],
14441            vec![
14442                ("time", vec![Scalar::Int64(5)]),
14443                ("quote", vec![Scalar::Float64(50.0)]),
14444            ],
14445        )
14446        .unwrap();
14447
14448        let result = super::merge_asof(&left, &right, "time", AsofDirection::Forward).unwrap();
14449        assert!(result.columns.get("quote").unwrap().values()[0].is_missing());
14450    }
14451
14452    #[test]
14453    fn merge_asof_nan_in_key() {
14454        use super::AsofDirection;
14455
14456        let left = fp_frame::DataFrame::from_dict(
14457            &["time", "val"],
14458            vec![
14459                (
14460                    "time",
14461                    vec![
14462                        Scalar::Int64(1),
14463                        Scalar::Null(NullKind::NaN),
14464                        Scalar::Int64(5),
14465                    ],
14466                ),
14467                (
14468                    "val",
14469                    vec![
14470                        Scalar::Float64(10.0),
14471                        Scalar::Float64(20.0),
14472                        Scalar::Float64(30.0),
14473                    ],
14474                ),
14475            ],
14476        )
14477        .unwrap();
14478
14479        let right = fp_frame::DataFrame::from_dict(
14480            &["time", "quote"],
14481            vec![
14482                ("time", vec![Scalar::Int64(2), Scalar::Int64(4)]),
14483                (
14484                    "quote",
14485                    vec![Scalar::Float64(200.0), Scalar::Float64(400.0)],
14486                ),
14487            ],
14488        )
14489        .unwrap();
14490
14491        // pandas merge_asof accepts NaN keys: the NaN row gets no match
14492        // (null in joined columns) — verified against FP-P2D-056
14493        // backward_nan_left_key_strict (pandas 2.2.3 oracle).
14494        let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
14495        assert!(result.columns.get("quote").unwrap().values()[1].is_missing());
14496        // time=5 → backward match to time=4 → quote=400
14497        assert_eq!(
14498            result.columns.get("quote").unwrap().values()[2],
14499            Scalar::Float64(400.0)
14500        );
14501    }
14502
14503    #[test]
14504    fn merge_asof_nan_in_right_key() {
14505        use super::AsofDirection;
14506
14507        // Symmetric to merge_asof_nan_in_key: NaN keys on the right side
14508        // also get treated as no-candidate (pandas does NOT raise). Other
14509        // left rows still match to non-NaN right rows.
14510        let left = fp_frame::DataFrame::from_dict(
14511            &["time", "val"],
14512            vec![
14513                (
14514                    "time",
14515                    vec![Scalar::Int64(1), Scalar::Int64(3), Scalar::Int64(5)],
14516                ),
14517                (
14518                    "val",
14519                    vec![
14520                        Scalar::Float64(10.0),
14521                        Scalar::Float64(20.0),
14522                        Scalar::Float64(30.0),
14523                    ],
14524                ),
14525            ],
14526        )
14527        .unwrap();
14528
14529        let right = fp_frame::DataFrame::from_dict(
14530            &["time", "quote"],
14531            vec![
14532                (
14533                    "time",
14534                    vec![
14535                        Scalar::Int64(2),
14536                        Scalar::Null(NullKind::NaN),
14537                        Scalar::Int64(4),
14538                    ],
14539                ),
14540                (
14541                    "quote",
14542                    vec![
14543                        Scalar::Float64(200.0),
14544                        Scalar::Float64(999.0),
14545                        Scalar::Float64(400.0),
14546                    ],
14547                ),
14548            ],
14549        )
14550        .unwrap();
14551
14552        let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
14553        // left time=1 → no right ≤ 1 → null
14554        assert!(result.columns.get("quote").unwrap().values()[0].is_missing());
14555        // left time=3 → right time=2 → 200.0 (NaN right row never matches)
14556        assert_eq!(
14557            result.columns.get("quote").unwrap().values()[1],
14558            Scalar::Float64(200.0)
14559        );
14560        // left time=5 → right time=4 → 400.0
14561        assert_eq!(
14562            result.columns.get("quote").unwrap().values()[2],
14563            Scalar::Float64(400.0)
14564        );
14565    }
14566
14567    #[test]
14568    fn merge_asof_overlapping_columns_apply_suffixes() {
14569        use super::AsofDirection;
14570
14571        let left = fp_frame::DataFrame::from_dict(
14572            &["time", "shared", "left_only"],
14573            vec![
14574                ("time", vec![Scalar::Int64(1), Scalar::Int64(2)]),
14575                ("shared", vec![Scalar::Int64(10), Scalar::Int64(20)]),
14576                ("left_only", vec![Scalar::Int64(1), Scalar::Int64(2)]),
14577            ],
14578        )
14579        .unwrap();
14580
14581        let right = fp_frame::DataFrame::from_dict(
14582            &["time", "shared", "right_only"],
14583            vec![
14584                ("time", vec![Scalar::Int64(1), Scalar::Int64(2)]),
14585                ("shared", vec![Scalar::Int64(100), Scalar::Int64(200)]),
14586                ("right_only", vec![Scalar::Int64(9), Scalar::Int64(8)]),
14587            ],
14588        )
14589        .unwrap();
14590
14591        let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
14592        let shared_left = result.columns.get("shared_x").unwrap().values();
14593        let shared_right = result.columns.get("shared_y").unwrap().values();
14594
14595        assert_eq!(shared_left[0], Scalar::Int64(10));
14596        assert_eq!(shared_left[1], Scalar::Int64(20));
14597        assert_eq!(shared_right[0], Scalar::Int64(100));
14598        assert_eq!(shared_right[1], Scalar::Int64(200));
14599    }
14600
14601    #[test]
14602    fn merge_asof_duplicate_column_gets_suffix() {
14603        use super::AsofDirection;
14604
14605        // Both left and right have a "val" column besides the key.
14606        let left = fp_frame::DataFrame::from_dict(
14607            &["time", "val"],
14608            vec![
14609                ("time", vec![Scalar::Int64(1)]),
14610                ("val", vec![Scalar::Float64(10.0)]),
14611            ],
14612        )
14613        .unwrap();
14614
14615        let right = fp_frame::DataFrame::from_dict(
14616            &["time", "val"],
14617            vec![
14618                ("time", vec![Scalar::Int64(1)]),
14619                ("val", vec![Scalar::Float64(99.0)]),
14620            ],
14621        )
14622        .unwrap();
14623
14624        let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
14625        // Overlapping columns should receive default merge suffixes.
14626        assert!(result.columns.contains_key("val_x"));
14627        assert!(result.columns.contains_key("val_y"));
14628        assert_eq!(
14629            result.columns.get("val_x").unwrap().values()[0],
14630            Scalar::Float64(10.0)
14631        );
14632        assert_eq!(
14633            result.columns.get("val_y").unwrap().values()[0],
14634            Scalar::Float64(99.0)
14635        );
14636    }
14637
14638    #[test]
14639    fn merge_asof_missing_column_errors() {
14640        use super::AsofDirection;
14641
14642        let left =
14643            fp_frame::DataFrame::from_dict(&["a"], vec![("a", vec![Scalar::Int64(1)])]).unwrap();
14644
14645        let right =
14646            fp_frame::DataFrame::from_dict(&["b"], vec![("b", vec![Scalar::Int64(1)])]).unwrap();
14647
14648        let err = super::merge_asof(&left, &right, "time", AsofDirection::Backward);
14649        assert!(err.is_err());
14650    }
14651
14652    #[test]
14653    fn merge_asof_invalid_direction_errors() {
14654        let left =
14655            fp_frame::DataFrame::from_dict(&["time"], vec![("time", vec![Scalar::Int64(1)])])
14656                .unwrap();
14657        let right =
14658            fp_frame::DataFrame::from_dict(&["time"], vec![("time", vec![Scalar::Int64(1)])])
14659                .unwrap();
14660
14661        let err = left.merge_asof(&right, "time", "sideways");
14662        assert!(matches!(
14663            err,
14664            Err(super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(msg)))
14665                if msg.contains("invalid direction")
14666        ));
14667    }
14668
14669    #[test]
14670    fn merge_asof_unsorted_left_errors() {
14671        use super::AsofDirection;
14672
14673        let left = fp_frame::DataFrame::from_dict(
14674            &["time", "val"],
14675            vec![
14676                ("time", vec![Scalar::Int64(2), Scalar::Int64(1)]),
14677                ("val", vec![Scalar::Float64(10.0), Scalar::Float64(20.0)]),
14678            ],
14679        )
14680        .unwrap();
14681
14682        let right = fp_frame::DataFrame::from_dict(
14683            &["time", "quote"],
14684            vec![
14685                ("time", vec![Scalar::Int64(1), Scalar::Int64(2)]),
14686                (
14687                    "quote",
14688                    vec![Scalar::Float64(100.0), Scalar::Float64(200.0)],
14689                ),
14690            ],
14691        )
14692        .unwrap();
14693
14694        let err = super::merge_asof(&left, &right, "time", AsofDirection::Backward)
14695            .expect_err("unsorted left should error");
14696        assert!(matches!(
14697            err,
14698            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(msg))
14699                if msg.contains("sorted")
14700        ));
14701    }
14702
14703    #[test]
14704    fn merge_asof_unsorted_right_errors() {
14705        use super::AsofDirection;
14706
14707        let left = fp_frame::DataFrame::from_dict(
14708            &["time", "val"],
14709            vec![
14710                ("time", vec![Scalar::Int64(1), Scalar::Int64(2)]),
14711                ("val", vec![Scalar::Float64(10.0), Scalar::Float64(20.0)]),
14712            ],
14713        )
14714        .unwrap();
14715
14716        let right = fp_frame::DataFrame::from_dict(
14717            &["time", "quote"],
14718            vec![
14719                ("time", vec![Scalar::Int64(2), Scalar::Int64(1)]),
14720                (
14721                    "quote",
14722                    vec![Scalar::Float64(200.0), Scalar::Float64(100.0)],
14723                ),
14724            ],
14725        )
14726        .unwrap();
14727
14728        let err = super::merge_asof(&left, &right, "time", AsofDirection::Backward)
14729            .expect_err("unsorted right should error");
14730        assert!(matches!(
14731            err,
14732            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(msg))
14733                if msg.contains("sorted")
14734        ));
14735    }
14736
14737    #[test]
14738    fn merge_asof_non_numeric_key_errors() {
14739        use super::AsofDirection;
14740
14741        let left = fp_frame::DataFrame::from_dict(
14742            &["time", "val"],
14743            vec![
14744                ("time", vec![Scalar::Utf8("a".into())]),
14745                ("val", vec![Scalar::Float64(10.0)]),
14746            ],
14747        )
14748        .unwrap();
14749
14750        let right = fp_frame::DataFrame::from_dict(
14751            &["time", "quote"],
14752            vec![
14753                ("time", vec![Scalar::Utf8("b".into())]),
14754                ("quote", vec![Scalar::Float64(20.0)]),
14755            ],
14756        )
14757        .unwrap();
14758
14759        let err = super::merge_asof(&left, &right, "time", AsofDirection::Backward)
14760            .expect_err("non-numeric key should error");
14761        assert!(matches!(
14762            err,
14763            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(msg))
14764                if msg.contains("numeric")
14765        ));
14766    }
14767
14768    #[test]
14769    fn merge_asof_preserves_all_left_rows() {
14770        use super::AsofDirection;
14771
14772        let left = fp_frame::DataFrame::from_dict(
14773            &["time", "val"],
14774            vec![
14775                (
14776                    "time",
14777                    vec![
14778                        Scalar::Int64(1),
14779                        Scalar::Int64(2),
14780                        Scalar::Int64(3),
14781                        Scalar::Int64(4),
14782                        Scalar::Int64(5),
14783                    ],
14784                ),
14785                (
14786                    "val",
14787                    vec![
14788                        Scalar::Float64(10.0),
14789                        Scalar::Float64(20.0),
14790                        Scalar::Float64(30.0),
14791                        Scalar::Float64(40.0),
14792                        Scalar::Float64(50.0),
14793                    ],
14794                ),
14795            ],
14796        )
14797        .unwrap();
14798
14799        let right = fp_frame::DataFrame::from_dict(
14800            &["time", "quote"],
14801            vec![
14802                ("time", vec![Scalar::Int64(3)]),
14803                ("quote", vec![Scalar::Float64(300.0)]),
14804            ],
14805        )
14806        .unwrap();
14807
14808        let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
14809        // All 5 left rows should be present.
14810        assert_eq!(result.index.len(), 5);
14811    }
14812
14813    // ── merge_asof options tests ──
14814
14815    #[test]
14816    fn merge_asof_allow_exact_matches_false_backward() {
14817        use super::{AsofDirection, MergeAsofOptions, merge_asof_with_options};
14818
14819        // Left: keys 1, 2, 3
14820        let left = fp_frame::DataFrame::from_dict(
14821            &["time", "val"],
14822            vec![
14823                (
14824                    "time",
14825                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
14826                ),
14827                (
14828                    "val",
14829                    vec![
14830                        Scalar::Float64(10.0),
14831                        Scalar::Float64(20.0),
14832                        Scalar::Float64(30.0),
14833                    ],
14834                ),
14835            ],
14836        )
14837        .unwrap();
14838
14839        // Right: keys 1, 2, 3 (exact matches exist)
14840        let right = fp_frame::DataFrame::from_dict(
14841            &["time", "quote"],
14842            vec![
14843                (
14844                    "time",
14845                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
14846                ),
14847                (
14848                    "quote",
14849                    vec![
14850                        Scalar::Float64(100.0),
14851                        Scalar::Float64(200.0),
14852                        Scalar::Float64(300.0),
14853                    ],
14854                ),
14855            ],
14856        )
14857        .unwrap();
14858
14859        // With allow_exact_matches=true (default), all should match
14860        let result_with_exact = merge_asof_with_options(
14861            &left,
14862            &right,
14863            "time",
14864            AsofDirection::Backward,
14865            MergeAsofOptions::new(),
14866        )
14867        .unwrap();
14868
14869        let quote_col = result_with_exact.columns.get("quote").unwrap();
14870        assert_eq!(quote_col.values()[0], Scalar::Float64(100.0)); // 1 matches 1
14871        assert_eq!(quote_col.values()[1], Scalar::Float64(200.0)); // 2 matches 2
14872        assert_eq!(quote_col.values()[2], Scalar::Float64(300.0)); // 3 matches 3
14873
14874        // With allow_exact_matches=false, exact matches should be excluded
14875        let result_no_exact = merge_asof_with_options(
14876            &left,
14877            &right,
14878            "time",
14879            AsofDirection::Backward,
14880            MergeAsofOptions::new().allow_exact_matches(false),
14881        )
14882        .unwrap();
14883
14884        let quote_col_no_exact = result_no_exact.columns.get("quote").unwrap();
14885        // 1 has no previous right key, should be null
14886        assert!(matches!(quote_col_no_exact.values()[0], Scalar::Null(_)));
14887        // 2 should match previous (1)
14888        assert_eq!(quote_col_no_exact.values()[1], Scalar::Float64(100.0));
14889        // 3 should match previous (2)
14890        assert_eq!(quote_col_no_exact.values()[2], Scalar::Float64(200.0));
14891    }
14892
14893    #[test]
14894    fn merge_asof_tolerance() {
14895        use super::{AsofDirection, MergeAsofOptions, merge_asof_with_options};
14896
14897        // Left: keys 1, 5, 10
14898        let left = fp_frame::DataFrame::from_dict(
14899            &["time", "val"],
14900            vec![
14901                (
14902                    "time",
14903                    vec![Scalar::Int64(1), Scalar::Int64(5), Scalar::Int64(10)],
14904                ),
14905                (
14906                    "val",
14907                    vec![
14908                        Scalar::Float64(10.0),
14909                        Scalar::Float64(50.0),
14910                        Scalar::Float64(100.0),
14911                    ],
14912                ),
14913            ],
14914        )
14915        .unwrap();
14916
14917        // Right: keys 2, 6
14918        let right = fp_frame::DataFrame::from_dict(
14919            &["time", "quote"],
14920            vec![
14921                ("time", vec![Scalar::Int64(2), Scalar::Int64(6)]),
14922                (
14923                    "quote",
14924                    vec![Scalar::Float64(200.0), Scalar::Float64(600.0)],
14925                ),
14926            ],
14927        )
14928        .unwrap();
14929
14930        // With tolerance=2, matches within 2 units are valid
14931        let result = merge_asof_with_options(
14932            &left,
14933            &right,
14934            "time",
14935            AsofDirection::Backward,
14936            MergeAsofOptions::new().tolerance(2.0),
14937        )
14938        .unwrap();
14939
14940        let quote_col = result.columns.get("quote").unwrap();
14941        // 1 < 2, no previous match, null
14942        assert!(matches!(quote_col.values()[0], Scalar::Null(_)));
14943        // 5 finds 2 (diff = 3), but tolerance is 2, so null
14944        assert!(matches!(quote_col.values()[1], Scalar::Null(_)));
14945        // 10 finds 6 (diff = 4), but tolerance is 2, so null
14946        assert!(matches!(quote_col.values()[2], Scalar::Null(_)));
14947
14948        // With tolerance=5, all should match
14949        let result_wider = merge_asof_with_options(
14950            &left,
14951            &right,
14952            "time",
14953            AsofDirection::Backward,
14954            MergeAsofOptions::new().tolerance(5.0),
14955        )
14956        .unwrap();
14957
14958        let quote_col_wider = result_wider.columns.get("quote").unwrap();
14959        // 1 < 2, still no previous
14960        assert!(matches!(quote_col_wider.values()[0], Scalar::Null(_)));
14961        // 5 finds 2 (diff = 3 <= 5)
14962        assert_eq!(quote_col_wider.values()[1], Scalar::Float64(200.0));
14963        // 10 finds 6 (diff = 4 <= 5)
14964        assert_eq!(quote_col_wider.values()[2], Scalar::Float64(600.0));
14965    }
14966
14967    #[test]
14968    fn merge_asof_by_column() {
14969        use super::{AsofDirection, MergeAsofOptions, merge_asof_with_options};
14970
14971        // Left: two groups (A and B), each with times
14972        let left = fp_frame::DataFrame::from_dict(
14973            &["group", "time", "val"],
14974            vec![
14975                (
14976                    "group",
14977                    vec![
14978                        Scalar::Utf8("A".into()),
14979                        Scalar::Utf8("A".into()),
14980                        Scalar::Utf8("B".into()),
14981                        Scalar::Utf8("B".into()),
14982                    ],
14983                ),
14984                (
14985                    "time",
14986                    vec![
14987                        Scalar::Int64(1),
14988                        Scalar::Int64(2),
14989                        Scalar::Int64(3),
14990                        Scalar::Int64(4),
14991                    ],
14992                ),
14993                (
14994                    "val",
14995                    vec![
14996                        Scalar::Float64(10.0),
14997                        Scalar::Float64(30.0),
14998                        Scalar::Float64(20.0),
14999                        Scalar::Float64(40.0),
15000                    ],
15001                ),
15002            ],
15003        )
15004        .unwrap();
15005
15006        // Right: same groups with quotes
15007        let right = fp_frame::DataFrame::from_dict(
15008            &["group", "time", "quote"],
15009            vec![
15010                (
15011                    "group",
15012                    vec![
15013                        Scalar::Utf8("A".into()),
15014                        Scalar::Utf8("B".into()),
15015                        Scalar::Utf8("A".into()),
15016                    ],
15017                ),
15018                (
15019                    "time",
15020                    vec![Scalar::Int64(2), Scalar::Int64(3), Scalar::Int64(4)],
15021                ),
15022                (
15023                    "quote",
15024                    vec![
15025                        Scalar::Float64(200.0),
15026                        Scalar::Float64(400.0),
15027                        Scalar::Float64(300.0),
15028                    ],
15029                ),
15030            ],
15031        )
15032        .unwrap();
15033
15034        // Merge with 'by' column
15035        let result = merge_asof_with_options(
15036            &left,
15037            &right,
15038            "time",
15039            AsofDirection::Backward,
15040            MergeAsofOptions::new().by(vec!["group".to_string()]),
15041        )
15042        .unwrap();
15043
15044        let quote_col = result.columns.get("quote").unwrap();
15045        // Left after 2d3338b1's reorder is (A,1), (A,2), (B,3), (B,4) — globally
15046        // sorted by time. Right is (A,2), (B,3), (A,4). Backward grouped asof:
15047        // Row 0: (A,1) → no right A with time <= 1 → null
15048        assert!(matches!(quote_col.values()[0], Scalar::Null(_)));
15049        // Row 1: (A,2) → right A time=2 → 200.0
15050        assert_eq!(quote_col.values()[1], Scalar::Float64(200.0));
15051        // Row 2: (B,3) → right B time=3 → 400.0
15052        assert_eq!(quote_col.values()[2], Scalar::Float64(400.0));
15053        // Row 3: (B,4) → right B time=3 (latest <= 4) → 400.0
15054        assert_eq!(quote_col.values()[3], Scalar::Float64(400.0));
15055    }
15056
15057    #[test]
15058    fn merge_asof_by_column_requires_globally_sorted_left_keys() {
15059        use super::{AsofDirection, MergeAsofOptions, merge_asof_with_options};
15060
15061        let left = fp_frame::DataFrame::from_dict(
15062            &["group", "time"],
15063            vec![
15064                (
15065                    "group",
15066                    vec![
15067                        Scalar::Utf8("A".into()),
15068                        Scalar::Utf8("A".into()),
15069                        Scalar::Utf8("B".into()),
15070                        Scalar::Utf8("B".into()),
15071                    ],
15072                ),
15073                (
15074                    "time",
15075                    vec![
15076                        Scalar::Int64(1),
15077                        Scalar::Int64(3),
15078                        Scalar::Int64(1),
15079                        Scalar::Int64(2),
15080                    ],
15081                ),
15082            ],
15083        )
15084        .unwrap();
15085        let right = fp_frame::DataFrame::from_dict(
15086            &["group", "time", "quote"],
15087            vec![
15088                (
15089                    "group",
15090                    vec![
15091                        Scalar::Utf8("A".into()),
15092                        Scalar::Utf8("B".into()),
15093                        Scalar::Utf8("A".into()),
15094                    ],
15095                ),
15096                (
15097                    "time",
15098                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
15099                ),
15100                (
15101                    "quote",
15102                    vec![
15103                        Scalar::Float64(10.0),
15104                        Scalar::Float64(20.0),
15105                        Scalar::Float64(30.0),
15106                    ],
15107                ),
15108            ],
15109        )
15110        .unwrap();
15111
15112        let err = merge_asof_with_options(
15113            &left,
15114            &right,
15115            "time",
15116            AsofDirection::Backward,
15117            MergeAsofOptions::new().by(vec!["group".to_string()]),
15118        )
15119        .expect_err("pandas requires globally sorted left keys even with by=");
15120        assert!(matches!(
15121            err,
15122            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(message))
15123                if message.contains("left") && message.contains("sorted")
15124        ));
15125    }
15126
15127    #[test]
15128    fn merge_asof_by_column_requires_globally_sorted_right_keys() {
15129        use super::{AsofDirection, MergeAsofOptions, merge_asof_with_options};
15130
15131        let left = fp_frame::DataFrame::from_dict(
15132            &["group", "time"],
15133            vec![
15134                (
15135                    "group",
15136                    vec![
15137                        Scalar::Utf8("A".into()),
15138                        Scalar::Utf8("B".into()),
15139                        Scalar::Utf8("A".into()),
15140                    ],
15141                ),
15142                (
15143                    "time",
15144                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
15145                ),
15146            ],
15147        )
15148        .unwrap();
15149        let right = fp_frame::DataFrame::from_dict(
15150            &["group", "time", "quote"],
15151            vec![
15152                (
15153                    "group",
15154                    vec![
15155                        Scalar::Utf8("A".into()),
15156                        Scalar::Utf8("A".into()),
15157                        Scalar::Utf8("B".into()),
15158                    ],
15159                ),
15160                (
15161                    "time",
15162                    vec![Scalar::Int64(1), Scalar::Int64(3), Scalar::Int64(2)],
15163                ),
15164                (
15165                    "quote",
15166                    vec![
15167                        Scalar::Float64(10.0),
15168                        Scalar::Float64(30.0),
15169                        Scalar::Float64(20.0),
15170                    ],
15171                ),
15172            ],
15173        )
15174        .unwrap();
15175
15176        let err = merge_asof_with_options(
15177            &left,
15178            &right,
15179            "time",
15180            AsofDirection::Backward,
15181            MergeAsofOptions::new().by(vec!["group".to_string()]),
15182        )
15183        .expect_err("pandas requires globally sorted right keys even with by=");
15184        assert!(matches!(
15185            err,
15186            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(message))
15187                if message.contains("right") && message.contains("sorted")
15188        ));
15189    }
15190
15191    #[test]
15192    fn merge_ordered_sorts_and_ffills_values() {
15193        let left = fp_frame::DataFrame::from_dict(
15194            &["date", "left_val"],
15195            vec![
15196                ("date", vec![Scalar::Int64(1), Scalar::Int64(3)]),
15197                ("left_val", vec![Scalar::Int64(10), Scalar::Int64(30)]),
15198            ],
15199        )
15200        .unwrap();
15201
15202        let right = fp_frame::DataFrame::from_dict(
15203            &["date", "right_val"],
15204            vec![
15205                ("date", vec![Scalar::Int64(2), Scalar::Int64(3)]),
15206                ("right_val", vec![Scalar::Int64(200), Scalar::Int64(300)]),
15207            ],
15208        )
15209        .unwrap();
15210
15211        let result = super::merge_ordered(&left, &right, &["date"], Some("ffill")).unwrap();
15212        let frame = fp_frame::DataFrame::new(result.index, result.columns).unwrap();
15213
15214        assert_eq!(
15215            frame.column("date").unwrap().values(),
15216            &[Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)]
15217        );
15218        assert_eq!(
15219            frame.column("left_val").unwrap().values(),
15220            &[
15221                Scalar::Float64(10.0),
15222                Scalar::Float64(10.0),
15223                Scalar::Float64(30.0),
15224            ]
15225        );
15226        assert_eq!(
15227            frame.column("right_val").unwrap().values(),
15228            &[
15229                Scalar::Null(NullKind::NaN),
15230                Scalar::Float64(200.0),
15231                Scalar::Float64(300.0),
15232            ]
15233        );
15234    }
15235
15236    #[test]
15237    fn merge_ordered_invalid_fill_method_errors() {
15238        let left = fp_frame::DataFrame::from_dict(
15239            &["date", "left_val"],
15240            vec![
15241                ("date", vec![Scalar::Int64(1)]),
15242                ("left_val", vec![Scalar::Int64(10)]),
15243            ],
15244        )
15245        .unwrap();
15246
15247        let right = fp_frame::DataFrame::from_dict(
15248            &["date", "right_val"],
15249            vec![
15250                ("date", vec![Scalar::Int64(2)]),
15251                ("right_val", vec![Scalar::Int64(200)]),
15252            ],
15253        )
15254        .unwrap();
15255
15256        let err = super::merge_ordered(&left, &right, &["date"], Some("sideways"))
15257            .expect_err("invalid fill method should error");
15258        assert!(matches!(
15259            err,
15260            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(message))
15261                if message.contains("fill_method must be 'ffill' or None")
15262        ));
15263    }
15264
15265    #[test]
15266    fn merge_ordered_rejects_bfill_like_pandas() {
15267        let left = fp_frame::DataFrame::from_dict(
15268            &["date", "left_val"],
15269            vec![
15270                ("date", vec![Scalar::Int64(1), Scalar::Int64(3)]),
15271                ("left_val", vec![Scalar::Int64(10), Scalar::Int64(30)]),
15272            ],
15273        )
15274        .unwrap();
15275
15276        let right = fp_frame::DataFrame::from_dict(
15277            &["date", "right_val"],
15278            vec![
15279                ("date", vec![Scalar::Int64(2), Scalar::Int64(3)]),
15280                ("right_val", vec![Scalar::Int64(200), Scalar::Int64(300)]),
15281            ],
15282        )
15283        .unwrap();
15284
15285        let err = super::merge_ordered(&left, &right, &["date"], Some("bfill"))
15286            .expect_err("pandas only accepts fill_method='ffill' or None");
15287        assert!(matches!(
15288            err,
15289            super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(message))
15290                if message.contains("fill_method must be 'ffill' or None")
15291        ));
15292    }
15293
15294    // ── join() pandas-named alias (br-frankenpandas-nk54a) ──────────────
15295
15296    #[test]
15297    fn dataframe_join_aliases_join_on_index() {
15298        use std::collections::BTreeMap;
15299
15300        use fp_columnar::Column;
15301        use fp_frame::DataFrame;
15302        use fp_index::Index;
15303        use fp_types::{DType, Scalar};
15304
15305        use super::DataFrameMergeExt;
15306
15307        fn build(name1: &str, name2: &str, vals1: &[i64], vals2: &[i64]) -> DataFrame {
15308            let mut cols = BTreeMap::new();
15309            cols.insert(
15310                name1.to_owned(),
15311                Column::new(
15312                    DType::Int64,
15313                    vals1.iter().map(|v| Scalar::Int64(*v)).collect(),
15314                )
15315                .unwrap(),
15316            );
15317            cols.insert(
15318                name2.to_owned(),
15319                Column::new(
15320                    DType::Int64,
15321                    vals2.iter().map(|v| Scalar::Int64(*v)).collect(),
15322                )
15323                .unwrap(),
15324            );
15325            DataFrame::new_with_column_order(
15326                Index::new(
15327                    (0..vals1.len() as i64)
15328                        .map(fp_index::IndexLabel::Int64)
15329                        .collect(),
15330                ),
15331                cols,
15332                vec![name1.to_owned(), name2.to_owned()],
15333            )
15334            .unwrap()
15335        }
15336
15337        let left = build("a", "b", &[10, 20, 30], &[1, 2, 3]);
15338        let right = build("c", "d", &[100, 200, 300], &[7, 8, 9]);
15339
15340        let via_join = left.join(&right, super::JoinType::Inner).unwrap();
15341        let via_join_on_index = left.join_on_index(&right, super::JoinType::Inner).unwrap();
15342
15343        // Both produce the same MergedDataFrame shape & values.
15344        let join_keys: Vec<&String> = via_join.columns.keys().collect();
15345        let idx_keys: Vec<&String> = via_join_on_index.columns.keys().collect();
15346        assert_eq!(join_keys, idx_keys);
15347        assert_eq!(via_join.index, via_join_on_index.index);
15348        for k in via_join.columns.keys() {
15349            assert_eq!(
15350                via_join.columns.get(k).unwrap().values(),
15351                via_join_on_index.columns.get(k).unwrap().values(),
15352                "column {k} differs"
15353            );
15354        }
15355    }
15356}