1#![forbid(unsafe_code)]
2#![warn(rustdoc::broken_intra_doc_links)]
3
4use 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};
79use 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 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 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 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 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
351fn coalesce_utf8_contiguous_key_column(
352 left_key_col: &Column,
353 right_key_col: &Column,
354 left_positions: &[Option<usize>],
355 right_positions: &[Option<usize>],
356) -> Option<Column> {
357 let (left_bytes, left_offsets) = left_key_col.as_utf8_contiguous()?;
358 let (right_bytes, right_offsets) = right_key_col.as_utf8_contiguous()?;
359 if left_positions.len() != right_positions.len() {
360 return None;
361 }
362
363 let mut byte_len = 0usize;
364 for (left_pos, right_pos) in left_positions.iter().zip(right_positions.iter()) {
365 let (bytes, offsets, pos) = match (left_pos, right_pos) {
366 (Some(pos), _) => (left_bytes, left_offsets, *pos),
367 (None, Some(pos)) => (right_bytes, right_offsets, *pos),
368 (None, None) => return None,
369 };
370 let end = pos.checked_add(1)?;
371 let start_offset = *offsets.get(pos)?;
372 let end_offset = *offsets.get(end)?;
373 if end_offset < start_offset || end_offset > bytes.len() {
374 return None;
375 }
376 byte_len = byte_len.checked_add(end_offset - start_offset)?;
377 }
378
379 let mut bytes = Vec::with_capacity(byte_len);
380 let mut offsets = Vec::with_capacity(left_positions.len() + 1);
381 offsets.push(0);
382 for (left_pos, right_pos) in left_positions.iter().zip(right_positions.iter()) {
383 let (source_bytes, source_offsets, pos) = match (left_pos, right_pos) {
384 (Some(pos), _) => (left_bytes, left_offsets, *pos),
385 (None, Some(pos)) => (right_bytes, right_offsets, *pos),
386 (None, None) => return None,
387 };
388 let start = *source_offsets.get(pos)?;
389 let end = *source_offsets.get(pos.checked_add(1)?)?;
390 bytes.extend_from_slice(source_bytes.get(start..end)?);
391 offsets.push(bytes.len());
392 }
393 Some(Column::from_utf8_contiguous(bytes, offsets))
394}
395
396fn coalesce_temporal_i64_key_column(
402 left_key_col: &Column,
403 right_key_col: &Column,
404 left_positions: &[Option<usize>],
405 right_positions: &[Option<usize>],
406) -> Option<Column> {
407 if left_positions.len() != right_positions.len()
408 || !left_key_col.validity().all()
409 || !right_key_col.validity().all()
410 {
411 return None;
412 }
413
414 let (left_keys, right_keys, nat, is_datetime) =
415 match (left_key_col.dtype(), right_key_col.dtype()) {
416 (DType::Datetime64, DType::Datetime64) => (
417 left_key_col.as_datetime64_slice()?,
418 right_key_col.as_datetime64_slice()?,
419 fp_types::Timestamp::NAT,
420 true,
421 ),
422 (DType::Timedelta64, DType::Timedelta64) => (
423 left_key_col.as_timedelta64_slice()?,
424 right_key_col.as_timedelta64_slice()?,
425 fp_types::Timedelta::NAT,
426 false,
427 ),
428 _ => return None,
429 };
430
431 let mut data = Vec::with_capacity(left_positions.len());
432 for (left_pos, right_pos) in left_positions.iter().zip(right_positions.iter()) {
433 let value = match (*left_pos, *right_pos) {
434 (Some(pos), _) => *left_keys.get(pos)?,
435 (None, Some(pos)) => *right_keys.get(pos)?,
436 (None, None) => return None,
437 };
438 if value == nat {
439 return None;
440 }
441 data.push(value);
442 }
443
444 let validity = ValidityMask::all_valid(data.len());
445 Some(if is_datetime {
446 Column::from_datetime64_values_with_validity(data, validity)
447 } else {
448 Column::from_timedelta64_values_with_validity(data, validity)
449 })
450}
451
452enum SharedOptionalUtf8GatherPlan {
453 NullableRange {
454 null_prefix: usize,
455 source_start: usize,
456 source_len: usize,
457 null_suffix: usize,
458 },
459 Positions {
460 positions: Arc<[usize]>,
461 validity: ValidityMask,
462 },
463}
464
465fn shared_optional_utf8_gather_plan(
466 positions: &[Option<usize>],
467 source_len: usize,
468) -> Option<SharedOptionalUtf8GatherPlan> {
469 let mut first_valid = None;
470 let mut last_valid_exclusive = 0usize;
471 let mut has_missing = false;
472 for (out_idx, slot) in positions.iter().enumerate() {
473 match slot {
474 Some(idx) if *idx < source_len => {
475 first_valid.get_or_insert(out_idx);
476 last_valid_exclusive = out_idx + 1;
477 }
478 _ => has_missing = true,
479 }
480 }
481 if !has_missing {
482 return None;
483 }
484 if let Some(first_valid) = first_valid {
485 let source_start = positions.get(first_valid).copied().flatten()?;
486 let valid_len = last_valid_exclusive - first_valid;
487 let valid_window = positions.get(first_valid..last_valid_exclusive)?;
488 let contiguous = valid_window
489 .iter()
490 .enumerate()
491 .all(|(offset, slot)| *slot == Some(source_start + offset));
492 if contiguous
493 && source_start
494 .checked_add(valid_len)
495 .is_some_and(|end| end <= source_len)
496 {
497 return Some(SharedOptionalUtf8GatherPlan::NullableRange {
498 null_prefix: first_valid,
499 source_start,
500 source_len: valid_len,
501 null_suffix: positions.len() - last_valid_exclusive,
502 });
503 }
504 } else {
505 return Some(SharedOptionalUtf8GatherPlan::NullableRange {
506 null_prefix: positions.len(),
507 source_start: 0,
508 source_len: 0,
509 null_suffix: 0,
510 });
511 }
512
513 let mut plan = Vec::with_capacity(positions.len());
514 let mut words = vec![0_u64; positions.len().div_ceil(64)];
515 for (out_idx, slot) in positions.iter().enumerate() {
516 match slot {
517 Some(idx) if *idx < source_len => {
518 plan.push(*idx);
519 words[out_idx / 64] |= 1_u64 << (out_idx % 64);
520 }
521 _ => plan.push(usize::MAX),
522 }
523 }
524 Some(SharedOptionalUtf8GatherPlan::Positions {
525 positions: Arc::from(plan),
526 validity: ValidityMask::from_words(words, positions.len()),
527 })
528}
529
530fn reindex_with_shared_utf8_plan(
531 column: &Column,
532 positions: &[Option<usize>],
533 plan: Option<&SharedOptionalUtf8GatherPlan>,
534) -> Result<Column, JoinError> {
535 if let Some(column) = plan.and_then(|plan| reindex_eager_utf8_with_plan(column, plan)) {
536 return Ok(column);
537 }
538 Ok(column.reindex_by_positions(positions)?)
539}
540
541fn reindex_outer_with_shared_utf8_plan(
542 column: &Column,
543 positions: &[Option<usize>],
544 plan: Option<&SharedOptionalUtf8GatherPlan>,
545) -> Result<Column, JoinError> {
546 if let Some(column) = plan.and_then(|plan| reindex_eager_utf8_with_plan(column, plan)) {
547 return Ok(column);
548 }
549 reindex_outer_join_column(column, positions)
550}
551
552fn reindex_eager_utf8_with_plan(
553 column: &Column,
554 plan: &SharedOptionalUtf8GatherPlan,
555) -> Option<Column> {
556 match plan {
557 SharedOptionalUtf8GatherPlan::NullableRange {
558 null_prefix,
559 source_start,
560 source_len,
561 null_suffix,
562 } => column.reindex_eager_utf8_with_nullable_range(
563 *null_prefix,
564 *source_start,
565 *source_len,
566 *null_suffix,
567 ),
568 SharedOptionalUtf8GatherPlan::Positions {
569 positions,
570 validity,
571 } => column.reindex_eager_utf8_with_shared_plan(Arc::clone(positions), validity.clone()),
572 }
573}
574
575fn sort_outer_join_rows(
576 out_labels: &mut Vec<IndexLabel>,
577 left_positions: &mut [Option<usize>],
578 right_positions: &mut [Option<usize>],
579) {
580 if out_labels.len() <= 1 {
581 return;
582 }
583
584 let mut rows = out_labels
585 .drain(..)
586 .zip(left_positions.iter().copied())
587 .zip(right_positions.iter().copied())
588 .map(|((label, left_pos), right_pos)| (label, left_pos, right_pos))
589 .collect::<Vec<_>>();
590 rows.sort_by(|left, right| left.0.cmp(&right.0));
591
592 for (idx, (label, left_pos, right_pos)) in rows.into_iter().enumerate() {
593 out_labels.push(label);
594 left_positions[idx] = left_pos;
595 right_positions[idx] = right_pos;
596 }
597}
598
599fn join_series_with_global_allocator(
600 left: &Series,
601 right: &Series,
602 join_type: JoinType,
603 right_map: &FxHashMap<&IndexLabel, Vec<usize>>,
604 left_map: Option<&FxHashMap<&IndexLabel, Vec<usize>>>,
605 output_rows: usize,
606) -> Result<JoinedSeries, JoinError> {
607 let mut out_labels = Vec::with_capacity(output_rows);
608 let mut left_positions = Vec::<Option<usize>>::with_capacity(output_rows);
609 let mut right_positions = Vec::<Option<usize>>::with_capacity(output_rows);
610
611 match join_type {
612 JoinType::Inner | JoinType::Left | JoinType::Outer => {
613 for (left_pos, label) in left.index().labels().iter().enumerate() {
615 if let Some(matches) = right_map.get(label) {
616 for right_pos in matches {
617 out_labels.push(label.clone());
618 left_positions.push(Some(left_pos));
619 right_positions.push(Some(*right_pos));
620 }
621 continue;
622 }
623
624 if matches!(join_type, JoinType::Left | JoinType::Outer) {
625 out_labels.push(label.clone());
626 left_positions.push(Some(left_pos));
627 right_positions.push(None);
628 }
629 }
630
631 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");
646 for (right_pos, label) in right.index().labels().iter().enumerate() {
647 if let Some(matches) = left_map.get(label) {
648 for left_pos in matches {
649 out_labels.push(label.clone());
650 left_positions.push(Some(*left_pos));
651 right_positions.push(Some(right_pos));
652 }
653 continue;
654 }
655
656 out_labels.push(label.clone());
657 left_positions.push(None);
658 right_positions.push(Some(right_pos));
659 }
660 }
661 JoinType::Cross => {
662 for (left_pos, left_label) in left.index().labels().iter().enumerate() {
663 for (right_pos, _) in right.index().labels().iter().enumerate() {
664 out_labels.push(left_label.clone());
665 left_positions.push(Some(left_pos));
666 right_positions.push(Some(right_pos));
667 }
668 }
669 }
670 }
671
672 if matches!(join_type, JoinType::Outer) {
673 sort_outer_join_rows(&mut out_labels, &mut left_positions, &mut right_positions);
674 }
675
676 let left_values = if matches!(join_type, JoinType::Outer) {
677 reindex_outer_join_column(left.column(), &left_positions)?
678 } else {
679 left.column().reindex_by_positions(&left_positions)?
680 };
681 let right_values = if matches!(join_type, JoinType::Outer) {
682 reindex_outer_join_column(right.column(), &right_positions)?
683 } else {
684 right.column().reindex_by_positions(&right_positions)?
685 };
686
687 let shared_name = if left.index().name().eq(&right.index().name()) {
690 left.index().name().map(str::to_owned)
691 } else {
692 None
693 };
694 Ok(JoinedSeries {
695 index: Index::new(out_labels).rename_index(shared_name.as_deref()),
696 left_values,
697 right_values,
698 })
699}
700
701fn join_series_with_arena(
702 left: &Series,
703 right: &Series,
704 join_type: JoinType,
705 right_map: &FxHashMap<&IndexLabel, Vec<usize>>,
706 left_map: Option<&FxHashMap<&IndexLabel, Vec<usize>>>,
707 output_rows: usize,
708) -> Result<JoinedSeries, JoinError> {
709 let arena = Bump::new();
710 let mut out_labels = Vec::with_capacity(output_rows);
711 let mut left_positions = BumpVec::<Option<usize>>::with_capacity_in(output_rows, &arena);
712 let mut right_positions = BumpVec::<Option<usize>>::with_capacity_in(output_rows, &arena);
713
714 match join_type {
715 JoinType::Inner | JoinType::Left | JoinType::Outer => {
716 for (left_pos, label) in left.index().labels().iter().enumerate() {
717 if let Some(matches) = right_map.get(label) {
718 for right_pos in matches {
719 out_labels.push(label.clone());
720 left_positions.push(Some(left_pos));
721 right_positions.push(Some(*right_pos));
722 }
723 continue;
724 }
725
726 if matches!(join_type, JoinType::Left | JoinType::Outer) {
727 out_labels.push(label.clone());
728 left_positions.push(Some(left_pos));
729 right_positions.push(None);
730 }
731 }
732
733 if matches!(join_type, JoinType::Outer) {
734 let left_map = left_map.as_ref().expect("left_map required for Outer join");
735 for (right_pos, label) in right.index().labels().iter().enumerate() {
736 if !left_map.contains_key(label) {
737 out_labels.push(label.clone());
738 left_positions.push(None);
739 right_positions.push(Some(right_pos));
740 }
741 }
742 }
743 }
744 JoinType::Right => {
745 let left_map = left_map.expect("left_map required for Right join");
746 for (right_pos, label) in right.index().labels().iter().enumerate() {
747 if let Some(matches) = left_map.get(label) {
748 for left_pos in matches {
749 out_labels.push(label.clone());
750 left_positions.push(Some(*left_pos));
751 right_positions.push(Some(right_pos));
752 }
753 continue;
754 }
755
756 out_labels.push(label.clone());
757 left_positions.push(None);
758 right_positions.push(Some(right_pos));
759 }
760 }
761 JoinType::Cross => {
762 for (left_pos, left_label) in left.index().labels().iter().enumerate() {
763 for (right_pos, _) in right.index().labels().iter().enumerate() {
764 out_labels.push(left_label.clone());
765 left_positions.push(Some(left_pos));
766 right_positions.push(Some(right_pos));
767 }
768 }
769 }
770 }
771
772 if matches!(join_type, JoinType::Outer) {
773 sort_outer_join_rows(
774 &mut out_labels,
775 left_positions.as_mut_slice(),
776 right_positions.as_mut_slice(),
777 );
778 }
779
780 let left_values = if matches!(join_type, JoinType::Outer) {
781 reindex_outer_join_column(left.column(), left_positions.as_slice())?
782 } else {
783 left.column()
784 .reindex_by_positions(left_positions.as_slice())?
785 };
786 let right_values = if matches!(join_type, JoinType::Outer) {
787 reindex_outer_join_column(right.column(), right_positions.as_slice())?
788 } else {
789 right
790 .column()
791 .reindex_by_positions(right_positions.as_slice())?
792 };
793
794 let shared_name = if left.index().name().eq(&right.index().name()) {
797 left.index().name().map(str::to_owned)
798 } else {
799 None
800 };
801 Ok(JoinedSeries {
802 index: Index::new(out_labels).rename_index(shared_name.as_deref()),
803 left_values,
804 right_values,
805 })
806}
807
808#[derive(Debug, Clone, PartialEq)]
810pub struct MergedDataFrame {
811 pub index: Index,
812 pub columns: std::collections::BTreeMap<String, Column>,
813 pub column_order: Vec<String>,
817}
818
819#[derive(Debug, Clone, PartialEq, Eq, Hash)]
820enum JoinKeyComponent {
821 Present(IndexLabel),
822 FloatBits(u64),
823 Missing,
824}
825
826impl Ord for JoinKeyComponent {
827 fn cmp(&self, other: &Self) -> Ordering {
828 use JoinKeyComponent::{FloatBits, Missing, Present};
829 match (self, other) {
830 (Missing, Missing) => Ordering::Equal,
831 (Missing, _) => Ordering::Greater,
832 (_, Missing) => Ordering::Less,
833 (Present(IndexLabel::Int64(a)), Present(IndexLabel::Int64(b))) => a.cmp(b),
834 (Present(IndexLabel::Utf8(a)), Present(IndexLabel::Utf8(b))) => a.cmp(b),
835 (Present(IndexLabel::Timedelta64(a)), Present(IndexLabel::Timedelta64(b))) => a.cmp(b),
836 (Present(IndexLabel::Datetime64(a)), Present(IndexLabel::Datetime64(b))) => a.cmp(b),
837 (Present(IndexLabel::Null(a)), Present(IndexLabel::Null(b))) => a.cmp(b),
842 (Present(IndexLabel::Null(_)), Present(_)) => Ordering::Greater,
843 (Present(_), Present(IndexLabel::Null(_))) => Ordering::Less,
844 (Present(IndexLabel::Null(_)), FloatBits(_)) => Ordering::Greater,
845 (FloatBits(_), Present(IndexLabel::Null(_))) => Ordering::Less,
846 (Present(IndexLabel::Int64(_)), Present(IndexLabel::Utf8(_))) => Ordering::Less,
847 (Present(IndexLabel::Utf8(_)), Present(IndexLabel::Int64(_))) => Ordering::Greater,
848 (Present(IndexLabel::Timedelta64(_)), Present(IndexLabel::Int64(_))) => {
849 Ordering::Greater
850 }
851 (Present(IndexLabel::Timedelta64(_)), Present(IndexLabel::Utf8(_))) => {
852 Ordering::Greater
853 }
854 (Present(IndexLabel::Int64(_)), Present(IndexLabel::Timedelta64(_))) => Ordering::Less,
855 (Present(IndexLabel::Utf8(_)), Present(IndexLabel::Timedelta64(_))) => Ordering::Less,
856 (Present(IndexLabel::Datetime64(_)), Present(IndexLabel::Int64(_))) => {
857 Ordering::Greater
858 }
859 (Present(IndexLabel::Datetime64(_)), Present(IndexLabel::Utf8(_))) => Ordering::Greater,
860 (Present(IndexLabel::Datetime64(_)), Present(IndexLabel::Timedelta64(_))) => {
861 Ordering::Greater
862 }
863 (Present(IndexLabel::Int64(_)), Present(IndexLabel::Datetime64(_))) => Ordering::Less,
864 (Present(IndexLabel::Utf8(_)), Present(IndexLabel::Datetime64(_))) => Ordering::Less,
865 (Present(IndexLabel::Timedelta64(_)), Present(IndexLabel::Datetime64(_))) => {
866 Ordering::Less
867 }
868 (Present(IndexLabel::Int64(a)), FloatBits(bits)) => {
869 let ord = (*a as f64).total_cmp(&f64::from_bits(*bits));
870 if ord == Ordering::Equal {
871 Ordering::Less
872 } else {
873 ord
874 }
875 }
876 (FloatBits(bits), Present(IndexLabel::Int64(a))) => {
877 let ord = f64::from_bits(*bits).total_cmp(&(*a as f64));
878 if ord == Ordering::Equal {
879 Ordering::Greater
880 } else {
881 ord
882 }
883 }
884 (Present(IndexLabel::Timedelta64(a)), FloatBits(bits)) => {
885 let ord = (*a as f64).total_cmp(&f64::from_bits(*bits));
886 if ord == Ordering::Equal {
887 Ordering::Less
888 } else {
889 ord
890 }
891 }
892 (FloatBits(bits), Present(IndexLabel::Timedelta64(a))) => {
893 let ord = f64::from_bits(*bits).total_cmp(&(*a as f64));
894 if ord == Ordering::Equal {
895 Ordering::Greater
896 } else {
897 ord
898 }
899 }
900 (Present(IndexLabel::Datetime64(a)), FloatBits(bits)) => {
901 let ord = (*a as f64).total_cmp(&f64::from_bits(*bits));
902 if ord == Ordering::Equal {
903 Ordering::Less
904 } else {
905 ord
906 }
907 }
908 (FloatBits(bits), Present(IndexLabel::Datetime64(a))) => {
909 let ord = f64::from_bits(*bits).total_cmp(&(*a as f64));
910 if ord == Ordering::Equal {
911 Ordering::Greater
912 } else {
913 ord
914 }
915 }
916 (FloatBits(a_bits), FloatBits(b_bits)) => {
917 f64::from_bits(*a_bits).total_cmp(&f64::from_bits(*b_bits))
918 }
919 (FloatBits(_), Present(IndexLabel::Utf8(_))) => Ordering::Less,
920 (Present(IndexLabel::Utf8(_)), FloatBits(_)) => Ordering::Greater,
921 (Present(IndexLabel::Float64(a)), Present(IndexLabel::Float64(b))) => a.cmp(b),
927 (Present(IndexLabel::Bool(a)), Present(IndexLabel::Bool(b))) => a.cmp(b),
928 (a, b) => join_component_rank(a).cmp(&join_component_rank(b)),
929 }
930 }
931}
932
933fn join_component_rank(c: &JoinKeyComponent) -> u8 {
936 use JoinKeyComponent::{FloatBits, Missing, Present};
937 match c {
938 Present(IndexLabel::Int64(_)) => 0,
939 Present(IndexLabel::Float64(_)) => 1,
940 Present(IndexLabel::Bool(_)) => 2,
941 Present(IndexLabel::Utf8(_)) => 3,
942 Present(IndexLabel::Timedelta64(_)) => 4,
943 Present(IndexLabel::Datetime64(_)) => 5,
944 Present(IndexLabel::Null(_)) => 6,
945 FloatBits(_) => 7,
946 Missing => 8,
947 }
948}
949
950impl PartialOrd for JoinKeyComponent {
951 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
952 Some(self.cmp(other))
953 }
954}
955
956fn scalar_to_key_component(s: &fp_types::Scalar) -> JoinKeyComponent {
957 match s {
958 fp_types::Scalar::Int64(v) => JoinKeyComponent::Present(IndexLabel::Int64(*v)),
959 fp_types::Scalar::Float64(v) if !v.is_nan() => {
960 if *v == v.trunc() && *v >= i64::MIN as f64 && *v < 9223372036854775808.0 {
961 JoinKeyComponent::Present(IndexLabel::Int64(*v as i64))
962 } else {
963 JoinKeyComponent::FloatBits(v.to_bits())
964 }
965 }
966 fp_types::Scalar::Utf8(v) => JoinKeyComponent::Present(IndexLabel::Utf8(v.clone())),
967 fp_types::Scalar::Bool(b) => JoinKeyComponent::Present(IndexLabel::Int64(i64::from(*b))),
968 fp_types::Scalar::Timedelta64(v) if *v != fp_types::Timedelta::NAT => {
969 JoinKeyComponent::Present(IndexLabel::Timedelta64(*v))
970 }
971 fp_types::Scalar::Datetime64(v) if *v != fp_types::Timestamp::NAT => {
972 JoinKeyComponent::Present(IndexLabel::Datetime64(*v))
973 }
974 _ => JoinKeyComponent::Missing, }
976}
977
978type CompositeJoinKey = smallvec::SmallVec<[JoinKeyComponent; 1]>;
984
985type MergeRowPositions = (
989 Vec<Option<usize>>,
990 Vec<Option<usize>>,
991 Option<Vec<CompositeJoinKey>>,
992);
993type JoinPositionBucket = smallvec::SmallVec<[usize; 1]>;
994
995fn collect_join_key_columns<'a>(
996 frame: &'a fp_frame::DataFrame,
997 on: &[&str],
998 side: &str,
999) -> Result<Vec<&'a Column>, JoinError> {
1000 let mut key_columns = Vec::with_capacity(on.len());
1001 for key_name in on {
1002 let key_column = frame.column(key_name).ok_or_else(|| {
1003 JoinError::Frame(FrameError::CompatibilityRejected(format!(
1004 "{side} DataFrame missing key column '{key_name}'"
1005 )))
1006 })?;
1007 key_columns.push(key_column);
1008 }
1009 Ok(key_columns)
1010}
1011
1012fn collect_composite_keys(key_columns: &[&Column]) -> Vec<CompositeJoinKey> {
1013 let row_count = key_columns.first().map_or(0, |column| column.len());
1014 let mut out = Vec::with_capacity(row_count);
1015
1016 for row in 0..row_count {
1017 let mut parts: CompositeJoinKey = smallvec::SmallVec::with_capacity(key_columns.len());
1018 for column in key_columns {
1019 parts.push(scalar_to_key_component(&column.values()[row]));
1020 }
1021 out.push(parts);
1022 }
1023
1024 out
1025}
1026
1027fn collect_single_join_keys(column: &Column) -> Vec<JoinKeyComponent> {
1028 column
1029 .values()
1030 .iter()
1031 .map(scalar_to_key_component)
1032 .collect()
1033}
1034
1035fn has_duplicate_composite_keys(keys: &[CompositeJoinKey]) -> bool {
1036 let mut seen = FxHashSet::with_capacity_and_hasher(keys.len(), Default::default());
1037 for key in keys {
1038 if !seen.insert(key) {
1039 return true;
1040 }
1041 }
1042 false
1043}
1044
1045fn validate_merge_cardinality(
1046 validate_mode: MergeValidateMode,
1047 left_keys: &[CompositeJoinKey],
1048 right_keys: &[CompositeJoinKey],
1049) -> Result<(), JoinError> {
1050 let left_has_duplicates = has_duplicate_composite_keys(left_keys);
1051 let right_has_duplicates = has_duplicate_composite_keys(right_keys);
1052
1053 let fail = |message: &str| {
1054 Err(JoinError::Frame(FrameError::CompatibilityRejected(
1055 message.to_owned(),
1056 )))
1057 };
1058
1059 match validate_mode {
1060 MergeValidateMode::OneToOne => {
1061 if left_has_duplicates {
1062 return fail("merge validate='one_to_one' failed: left keys are not unique");
1063 }
1064 if right_has_duplicates {
1065 return fail("merge validate='one_to_one' failed: right keys are not unique");
1066 }
1067 }
1068 MergeValidateMode::OneToMany => {
1069 if left_has_duplicates {
1070 return fail("merge validate='one_to_many' failed: left keys are not unique");
1071 }
1072 }
1073 MergeValidateMode::ManyToOne => {
1074 if right_has_duplicates {
1075 return fail("merge validate='many_to_one' failed: right keys are not unique");
1076 }
1077 }
1078 MergeValidateMode::ManyToMany => {}
1079 }
1080
1081 Ok(())
1082}
1083
1084fn validate_mode_allows_fast_positions(validate_mode: Option<MergeValidateMode>) -> bool {
1085 matches!(validate_mode, None | Some(MergeValidateMode::ManyToMany))
1086}
1087
1088fn reorder_vec_by_index<T: Clone>(values: &mut Vec<T>, order: &[usize]) {
1089 let existing = values.clone();
1090 values.clear();
1091 values.reserve(order.len());
1092 for &idx in order {
1093 values.push(existing[idx].clone());
1094 }
1095}
1096
1097fn sort_merge_rows_by_join_keys(
1098 left_keys: &[CompositeJoinKey],
1099 right_keys: &[CompositeJoinKey],
1100 left_positions: &mut Vec<Option<usize>>,
1101 right_positions: &mut Vec<Option<usize>>,
1102) {
1103 let n = left_positions.len();
1104 if n <= 1 {
1105 return;
1106 }
1107 let mut distinct: Vec<&CompositeJoinKey> = {
1120 let mut set = FxHashSet::default();
1121 left_keys
1122 .iter()
1123 .chain(right_keys.iter())
1124 .filter(|k| set.insert(*k))
1125 .collect()
1126 };
1127 distinct.sort_unstable();
1128 let d = distinct.len();
1129 let mut rank_of: FxHashMap<&CompositeJoinKey, u32> = FxHashMap::default();
1130 rank_of.reserve(d);
1131 for (r, k) in distinct.iter().enumerate() {
1132 rank_of.insert(*k, r as u32);
1133 }
1134 let left_rank: Vec<u32> = left_keys.iter().map(|k| rank_of[k]).collect();
1135 let right_rank: Vec<u32> = right_keys.iter().map(|k| rank_of[k]).collect();
1136 let ranks: Vec<u32> = left_positions
1137 .iter()
1138 .zip(right_positions.iter())
1139 .map(|(lp, rp)| match lp {
1140 Some(p) => left_rank[*p],
1141 None => right_rank[rp.expect("an unmatched merge row has a right position")],
1142 })
1143 .collect();
1144 let mut counts = vec![0usize; d + 1];
1145 for &r in &ranks {
1146 counts[r as usize + 1] += 1;
1147 }
1148 for i in 0..d {
1149 counts[i + 1] += counts[i];
1150 }
1151 let mut cursor = counts;
1154 let mut order = vec![0usize; n];
1155 for (i, &r) in ranks.iter().enumerate() {
1156 let slot = cursor[r as usize];
1157 order[slot] = i;
1158 cursor[r as usize] = slot + 1;
1159 }
1160 reorder_vec_by_index(left_positions, &order);
1161 reorder_vec_by_index(right_positions, &order);
1162}
1163
1164fn push_merge_row_key(out_row_keys: &mut Option<Vec<CompositeJoinKey>>, key: &CompositeJoinKey) {
1165 if let Some(out_row_keys) = out_row_keys {
1166 out_row_keys.push(key.clone());
1167 }
1168}
1169
1170#[derive(Debug, Clone, PartialEq, Eq)]
1171struct ResolvedMergeSuffixes {
1172 left: Option<String>,
1173 right: Option<String>,
1174}
1175
1176impl Default for ResolvedMergeSuffixes {
1177 fn default() -> Self {
1178 Self {
1179 left: Some("_x".to_owned()),
1180 right: Some("_y".to_owned()),
1181 }
1182 }
1183}
1184
1185fn resolve_merge_suffixes(suffixes: Option<[Option<String>; 2]>) -> ResolvedMergeSuffixes {
1186 match suffixes {
1187 Some([left, right]) => ResolvedMergeSuffixes { left, right },
1188 None => ResolvedMergeSuffixes::default(),
1189 }
1190}
1191
1192fn suffix_is_present(suffix: Option<&str>) -> bool {
1193 suffix.is_some_and(|value| !value.is_empty())
1194}
1195
1196fn apply_merge_suffix(name: &str, suffix: Option<&str>) -> String {
1197 match suffix {
1198 Some(value) if !value.is_empty() => format!("{name}{value}"),
1199 _ => name.to_owned(),
1200 }
1201}
1202
1203fn collect_overlapping_column_names(
1204 left_col_names: &HashSet<&String>,
1205 right_col_names: &HashSet<&String>,
1206 excluded_names: &HashSet<&str>,
1207) -> Vec<String> {
1208 let mut overlaps = left_col_names
1209 .iter()
1210 .filter(|name| right_col_names.contains(*name) && !excluded_names.contains(name.as_str()))
1211 .map(|name| (*name).clone())
1212 .collect::<Vec<_>>();
1213 overlaps.sort();
1214 overlaps
1215}
1216
1217const SMALL_SCHEMA_LINEAR_COLUMN_LOOKUP_LIMIT: usize = 8;
1218
1219fn column_name_lookup_contains(
1220 names: &[&String],
1221 hashed_names: Option<&HashSet<&str>>,
1222 target: &str,
1223) -> bool {
1224 if let Some(hashed_names) = hashed_names {
1225 hashed_names.contains(target)
1226 } else {
1227 names.iter().any(|name| name.as_str() == target)
1228 }
1229}
1230
1231fn ensure_merge_suffixes_for_overlaps(
1232 overlap_names: &[String],
1233 suffixes: &ResolvedMergeSuffixes,
1234) -> Result<(), JoinError> {
1235 if overlap_names.is_empty() {
1236 return Ok(());
1237 }
1238 if !suffix_is_present(suffixes.left.as_deref()) && !suffix_is_present(suffixes.right.as_deref())
1239 {
1240 return Err(JoinError::Frame(FrameError::CompatibilityRejected(
1241 format!(
1242 "columns overlap but no suffix specified: {}",
1243 overlap_names.join(", ")
1244 ),
1245 )));
1246 }
1247 Ok(())
1248}
1249
1250fn insert_merged_output_column(
1251 output_columns: &mut std::collections::BTreeMap<String, Column>,
1252 order: &mut Vec<String>,
1253 name: String,
1254 column: Column,
1255) -> Result<(), JoinError> {
1256 if output_columns.contains_key(&name) {
1257 return Err(JoinError::Frame(FrameError::CompatibilityRejected(
1258 format!("merge suffixes cause duplicate output column '{name}'"),
1259 )));
1260 }
1261 order.push(name.clone());
1262 output_columns.insert(name, column);
1263 Ok(())
1264}
1265
1266fn ordered_identity_int64_keys_match(left_key: &Column, right_key: &Column) -> bool {
1267 if left_key.len() != right_key.len()
1268 || !matches!(left_key.dtype(), DType::Int64)
1269 || !matches!(right_key.dtype(), DType::Int64)
1270 || !left_key.validity().all()
1271 || !right_key.validity().all()
1272 {
1273 return false;
1274 }
1275
1276 if let (Some(left), Some(right)) = (left_key.as_i64_slice(), right_key.as_i64_slice()) {
1277 let mut previous = None;
1278 let mut strictly_increasing = true;
1279 for (&left_value, &right_value) in left.iter().zip(right) {
1280 if left_value != right_value {
1281 return false;
1282 }
1283 if previous.is_some_and(|previous| left_value <= previous) {
1284 strictly_increasing = false;
1285 break;
1286 }
1287 previous = Some(left_value);
1288 }
1289 if strictly_increasing {
1290 return true;
1291 }
1292 }
1293
1294 let mut seen = FxHashSet::<i64>::with_capacity_and_hasher(left_key.len(), Default::default());
1300 for (left, right) in left_key.values().iter().zip(right_key.values()) {
1301 match (left, right) {
1302 (Scalar::Int64(left), Scalar::Int64(right))
1303 if matches!(left.cmp(right), Ordering::Equal) =>
1304 {
1305 if !seen.insert(*left) {
1306 return false;
1307 }
1308 }
1309 _ => return false,
1310 }
1311 }
1312 true
1313}
1314
1315fn strictly_increasing_int64_key_values(column: &Column) -> Option<&[Scalar]> {
1316 if column.dtype() != DType::Int64 || !column.validity().all() {
1317 return None;
1318 }
1319
1320 let values = column.values();
1321 let mut previous = None;
1322 for value in values {
1323 let current = match value {
1324 Scalar::Int64(value) => *value,
1325 _ => return None,
1326 };
1327 if previous.is_some_and(|previous| current <= previous) {
1328 return None;
1329 }
1330 previous = Some(current);
1331 }
1332 Some(values)
1333}
1334
1335fn all_valid_int64_key_values(column: &Column) -> Option<&[Scalar]> {
1336 if column.dtype() != DType::Int64 || !column.validity().all() {
1337 return None;
1338 }
1339
1340 let values = column.values();
1341 if values.iter().all(|value| matches!(value, Scalar::Int64(_))) {
1342 Some(values)
1343 } else {
1344 None
1345 }
1346}
1347
1348fn ordered_unique_int64_inner_positions(
1349 left_key: &Column,
1350 right_key: &Column,
1351) -> Option<(Vec<usize>, Vec<usize>)> {
1352 if let (Some(left_values), Some(right_values)) = (
1358 strictly_increasing_i64_slice(left_key),
1359 strictly_increasing_i64_slice(right_key),
1360 ) {
1361 let mut left_positions =
1362 Vec::<usize>::with_capacity(left_values.len().min(right_values.len()));
1363 let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
1364 let (mut left_idx, mut right_idx) = (0usize, 0usize);
1365 while left_idx < left_values.len() && right_idx < right_values.len() {
1366 match left_values[left_idx].cmp(&right_values[right_idx]) {
1367 Ordering::Equal => {
1368 left_positions.push(left_idx);
1369 right_positions.push(right_idx);
1370 left_idx += 1;
1371 right_idx += 1;
1372 }
1373 Ordering::Less => left_idx += 1,
1374 Ordering::Greater => right_idx += 1,
1375 }
1376 }
1377 return Some((left_positions, right_positions));
1378 }
1379
1380 let left_values = strictly_increasing_int64_key_values(left_key)?;
1381 let right_values = strictly_increasing_int64_key_values(right_key)?;
1382
1383 let mut left_positions = Vec::<usize>::with_capacity(left_values.len().min(right_values.len()));
1384 let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
1385 let mut left_idx = 0usize;
1386 let mut right_idx = 0usize;
1387
1388 while left_idx < left_values.len() && right_idx < right_values.len() {
1389 let left_value = match &left_values[left_idx] {
1390 Scalar::Int64(value) => *value,
1391 _ => return None,
1392 };
1393 let right_value = match &right_values[right_idx] {
1394 Scalar::Int64(value) => *value,
1395 _ => return None,
1396 };
1397
1398 match left_value.cmp(&right_value) {
1399 Ordering::Equal => {
1400 left_positions.push(left_idx);
1401 right_positions.push(right_idx);
1402 left_idx += 1;
1403 right_idx += 1;
1404 }
1405 Ordering::Less => left_idx += 1,
1406 Ordering::Greater => right_idx += 1,
1407 }
1408 }
1409
1410 Some((left_positions, right_positions))
1411}
1412
1413fn strictly_increasing_utf8_key_spans(column: &Column) -> Option<(&[u8], &[usize])> {
1414 column.as_strictly_increasing_utf8_contiguous()
1415}
1416
1417fn utf8_span<'a>(bytes: &'a [u8], offsets: &[usize], pos: usize) -> &'a [u8] {
1418 &bytes[offsets[pos]..offsets[pos + 1]]
1419}
1420
1421fn utf8_offsets_are_sorted(bytes: &[u8], offsets: &[usize]) -> bool {
1422 offsets
1423 .windows(3)
1424 .all(|window| bytes[window[0]..window[1]] <= bytes[window[1]..window[2]])
1425}
1426
1427fn sorted_contiguous_utf8_inner_positions(
1428 left_bytes: &[u8],
1429 left_offsets: &[usize],
1430 right_bytes: &[u8],
1431 right_offsets: &[usize],
1432) -> Option<(Vec<usize>, Vec<usize>)> {
1433 if !utf8_offsets_are_sorted(left_bytes, left_offsets)
1434 || !utf8_offsets_are_sorted(right_bytes, right_offsets)
1435 {
1436 return None;
1437 }
1438
1439 let left_n = left_offsets.len() - 1;
1440 let right_n = right_offsets.len() - 1;
1441 let mut left_positions = Vec::<usize>::with_capacity(left_n.min(right_n));
1442 let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
1443 let mut left_pos = 0usize;
1444 let mut right_pos = 0usize;
1445
1446 while left_pos < left_n && right_pos < right_n {
1447 let left_span = utf8_span(left_bytes, left_offsets, left_pos);
1448 let right_span = utf8_span(right_bytes, right_offsets, right_pos);
1449 match left_span.cmp(right_span) {
1450 Ordering::Less => left_pos += 1,
1451 Ordering::Greater => right_pos += 1,
1452 Ordering::Equal => {
1453 let left_start = left_pos;
1454 let right_start = right_pos;
1455 while left_pos < left_n
1456 && utf8_span(left_bytes, left_offsets, left_pos) == left_span
1457 {
1458 left_pos += 1;
1459 }
1460 while right_pos < right_n
1461 && utf8_span(right_bytes, right_offsets, right_pos) == right_span
1462 {
1463 right_pos += 1;
1464 }
1465 for matched_left in left_start..left_pos {
1466 for matched_right in right_start..right_pos {
1467 left_positions.push(matched_left);
1468 right_positions.push(matched_right);
1469 }
1470 }
1471 }
1472 }
1473 }
1474
1475 Some((left_positions, right_positions))
1476}
1477
1478fn utf8_span_lower_bound(bytes: &[u8], offsets: &[usize], needle: &[u8]) -> usize {
1479 let mut lo = 0usize;
1480 let mut hi = offsets.len() - 1;
1481 while lo < hi {
1482 let mid = lo + (hi - lo) / 2;
1483 if utf8_span(bytes, offsets, mid) < needle {
1484 lo = mid + 1;
1485 } else {
1486 hi = mid;
1487 }
1488 }
1489 lo
1490}
1491
1492fn ordered_unique_utf8_fixed_width(left_key: &Column, right_key: &Column) -> Option<usize> {
1493 let (_, _, left_width) = left_key.as_fixed_width_strictly_increasing_utf8_contiguous()?;
1494 let (_, _, right_width) = right_key.as_fixed_width_strictly_increasing_utf8_contiguous()?;
1495 (left_width == right_width && left_width > 0).then_some(left_width)
1496}
1497
1498fn ordered_utf8_lower_hex_overlap_len(
1499 left_cert: Utf8LowerHexSequence,
1500 right_cert: Utf8LowerHexSequence,
1501 left_idx: usize,
1502 left_n: usize,
1503 right_idx: usize,
1504 right_n: usize,
1505) -> Option<usize> {
1506 if !left_cert.same_shape(right_cert) {
1507 return None;
1508 }
1509 let left_value = left_cert.value_at(left_idx)?;
1510 let right_value = right_cert.value_at(right_idx)?;
1511 if left_value != right_value {
1512 return None;
1513 }
1514 Some(left_n.saturating_sub(left_idx).min(right_n - right_idx))
1515}
1516
1517fn lower_hex_overlap_plan_from_certificates(
1518 left_key: &Column,
1519 right_key: &Column,
1520) -> Option<InnerPositionPlan> {
1521 let (left_prefix, left_cert, left_n) = left_key.as_lower_hex_sequence_utf8()?;
1522 let (right_prefix, right_cert, right_n) = right_key.as_lower_hex_sequence_utf8()?;
1523 if !left_cert.same_shape(right_cert) {
1524 return None;
1525 }
1526 if left_prefix != right_prefix {
1527 return None;
1528 }
1529
1530 let left_n = u64::try_from(left_n).ok()?;
1531 let right_n = u64::try_from(right_n).ok()?;
1532 if left_n == 0 || right_n == 0 {
1533 return Some(InnerPositionPlan::Gather {
1534 left_positions: Vec::new(),
1535 right_positions: Vec::new(),
1536 });
1537 }
1538
1539 let left_start_value = left_cert.start();
1540 let right_start_value = right_cert.start();
1541 let left_end_value = left_start_value.checked_add(left_n)?;
1542 let right_end_value = right_start_value.checked_add(right_n)?;
1543 let overlap_start = left_start_value.max(right_start_value);
1544 let overlap_end = left_end_value.min(right_end_value);
1545 if overlap_start >= overlap_end {
1546 return Some(InnerPositionPlan::Gather {
1547 left_positions: Vec::new(),
1548 right_positions: Vec::new(),
1549 });
1550 }
1551
1552 let len = usize::try_from(overlap_end.checked_sub(overlap_start)?).ok()?;
1553 let left_start = usize::try_from(overlap_start.checked_sub(left_start_value)?).ok()?;
1554 let right_start = usize::try_from(overlap_start.checked_sub(right_start_value)?).ok()?;
1555 let left_len = usize::try_from(left_n).ok()?;
1556 let right_len = usize::try_from(right_n).ok()?;
1557 let left_end = left_start.checked_add(len)?;
1558 let right_end = right_start.checked_add(len)?;
1559 if left_end > left_len || right_end > right_len {
1560 return None;
1561 }
1562
1563 Some(InnerPositionPlan::ContiguousRanges {
1564 left_start,
1565 right_start,
1566 len,
1567 })
1568}
1569
1570#[derive(Debug, Clone, PartialEq, Eq)]
1571enum InnerPositionPlan {
1572 Gather {
1573 left_positions: Vec<usize>,
1574 right_positions: Vec<usize>,
1575 },
1576 ContiguousRanges {
1577 left_start: usize,
1578 right_start: usize,
1579 len: usize,
1580 },
1581}
1582
1583impl InnerPositionPlan {
1584 #[cfg(test)]
1585 fn into_positions(self) -> (Vec<usize>, Vec<usize>) {
1586 match self {
1587 Self::Gather {
1588 left_positions,
1589 right_positions,
1590 } => (left_positions, right_positions),
1591 Self::ContiguousRanges {
1592 left_start,
1593 right_start,
1594 len,
1595 } => (
1596 (left_start..left_start + len).collect(),
1597 (right_start..right_start + len).collect(),
1598 ),
1599 }
1600 }
1601}
1602
1603fn ordered_unique_utf8_inner_position_plan(
1611 left_key: &Column,
1612 right_key: &Column,
1613) -> Option<InnerPositionPlan> {
1614 if let Some(plan) = lower_hex_overlap_plan_from_certificates(left_key, right_key) {
1615 return Some(plan);
1616 }
1617
1618 let (left_bytes, left_offsets) = strictly_increasing_utf8_key_spans(left_key)?;
1619 let (right_bytes, right_offsets) = strictly_increasing_utf8_key_spans(right_key)?;
1620 let left_n = left_offsets.len() - 1;
1621 let right_n = right_offsets.len() - 1;
1622 let fixed_width = ordered_unique_utf8_fixed_width(left_key, right_key);
1623
1624 if left_n == 0 || right_n == 0 {
1625 return Some(InnerPositionPlan::Gather {
1626 left_positions: Vec::new(),
1627 right_positions: Vec::new(),
1628 });
1629 }
1630
1631 let mut left_positions = Vec::<usize>::with_capacity(left_n.min(right_n));
1632 let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
1633
1634 let first_left = utf8_span(left_bytes, left_offsets, 0);
1635 let last_left = utf8_span(left_bytes, left_offsets, left_n - 1);
1636 let first_right = utf8_span(right_bytes, right_offsets, 0);
1637 let last_right = utf8_span(right_bytes, right_offsets, right_n - 1);
1638 if last_left < first_right || last_right < first_left {
1639 return Some(InnerPositionPlan::Gather {
1640 left_positions,
1641 right_positions,
1642 });
1643 }
1644
1645 let mut left_idx = utf8_span_lower_bound(left_bytes, left_offsets, first_right);
1646 let mut right_idx = if left_idx < left_n {
1647 utf8_span_lower_bound(
1648 right_bytes,
1649 right_offsets,
1650 utf8_span(left_bytes, left_offsets, left_idx),
1651 )
1652 } else {
1653 right_n
1654 };
1655 let mut fixed_width_bulk_attempted = false;
1656
1657 while left_idx < left_n && right_idx < right_n {
1658 let left_span = utf8_span(left_bytes, left_offsets, left_idx);
1659 let right_span = utf8_span(right_bytes, right_offsets, right_idx);
1660
1661 match left_span.cmp(right_span) {
1662 Ordering::Equal => {
1663 if let Some(width) = fixed_width
1664 && !fixed_width_bulk_attempted
1665 {
1666 fixed_width_bulk_attempted = true;
1667 let lower_hex_sequences = match (
1672 left_key.as_lower_hex_sequence_utf8_contiguous(),
1673 right_key.as_lower_hex_sequence_utf8_contiguous(),
1674 ) {
1675 (Some((_, _, left_cert)), Some((_, _, right_cert))) => {
1676 Some((left_cert, right_cert))
1677 }
1678 _ => None,
1679 };
1680 if let Some((left_cert, right_cert)) = lower_hex_sequences
1681 && let Some(run_len) = ordered_utf8_lower_hex_overlap_len(
1682 left_cert, right_cert, left_idx, left_n, right_idx, right_n,
1683 )
1684 && run_len > 1
1685 {
1686 if left_positions.is_empty() {
1687 return Some(InnerPositionPlan::ContiguousRanges {
1688 left_start: left_idx,
1689 right_start: right_idx,
1690 len: run_len,
1691 });
1692 }
1693 left_positions.extend(left_idx..left_idx + run_len);
1694 right_positions.extend(right_idx..right_idx + run_len);
1695 left_idx += run_len;
1696 right_idx += run_len;
1697 continue;
1698 }
1699 let run_len = left_n.saturating_sub(left_idx).min(right_n - right_idx);
1700 if run_len > 1
1701 && let Some(byte_len) = run_len.checked_mul(width)
1702 {
1703 let left_start = left_offsets[left_idx];
1704 let right_start = right_offsets[right_idx];
1705 let left_end = left_start + byte_len;
1706 let right_end = right_start + byte_len;
1707 if left_end <= left_bytes.len()
1708 && right_end <= right_bytes.len()
1709 && left_bytes[left_start..left_end]
1710 == right_bytes[right_start..right_end]
1711 {
1712 if left_positions.is_empty() {
1713 return Some(InnerPositionPlan::ContiguousRanges {
1714 left_start: left_idx,
1715 right_start: right_idx,
1716 len: run_len,
1717 });
1718 }
1719 left_positions.extend(left_idx..left_idx + run_len);
1720 right_positions.extend(right_idx..right_idx + run_len);
1721 left_idx += run_len;
1722 right_idx += run_len;
1723 continue;
1724 }
1725 }
1726 }
1727 left_positions.push(left_idx);
1728 right_positions.push(right_idx);
1729 left_idx += 1;
1730 right_idx += 1;
1731 }
1732 Ordering::Less => left_idx += 1,
1733 Ordering::Greater => right_idx += 1,
1734 }
1735 }
1736
1737 Some(InnerPositionPlan::Gather {
1738 left_positions,
1739 right_positions,
1740 })
1741}
1742
1743#[cfg(test)]
1744fn ordered_unique_utf8_inner_positions(
1745 left_key: &Column,
1746 right_key: &Column,
1747) -> Option<(Vec<usize>, Vec<usize>)> {
1748 ordered_unique_utf8_inner_position_plan(left_key, right_key)
1749 .map(InnerPositionPlan::into_positions)
1750}
1751
1752fn strictly_increasing_i64_slice(column: &Column) -> Option<&[i64]> {
1759 let data = column.as_i64_slice()?;
1760 if data.windows(2).any(|pair| pair[1] <= pair[0]) {
1761 return None;
1762 }
1763 Some(data)
1764}
1765
1766fn ordered_unique_int64_left_match_positions(
1767 left_key: &Column,
1768 right_key: &Column,
1769) -> Option<Vec<Option<usize>>> {
1770 if let (Some(left_values), Some(right_values)) = (
1777 strictly_increasing_i64_slice(left_key),
1778 strictly_increasing_i64_slice(right_key),
1779 ) {
1780 let mut right_positions = Vec::<Option<usize>>::with_capacity(left_values.len());
1781 let mut right_idx = 0usize;
1782 for &left_value in left_values {
1783 while right_idx < right_values.len() && right_values[right_idx] < left_value {
1784 right_idx += 1;
1785 }
1786 let matched = match right_values.get(right_idx) {
1787 Some(&right_value) if right_value == left_value => Some(right_idx),
1788 _ => None,
1789 };
1790 right_positions.push(matched);
1791 }
1792 return Some(right_positions);
1793 }
1794
1795 let left_values = strictly_increasing_int64_key_values(left_key)?;
1796 let right_values = strictly_increasing_int64_key_values(right_key)?;
1797
1798 let mut right_positions = Vec::<Option<usize>>::with_capacity(left_values.len());
1799 let mut right_idx = 0usize;
1800
1801 for left_value in left_values {
1802 let Scalar::Int64(left_value) = left_value else {
1803 return None;
1804 };
1805 while let Some(Scalar::Int64(right_value)) = right_values.get(right_idx)
1806 && right_value < left_value
1807 {
1808 right_idx += 1;
1809 }
1810
1811 let matched = match right_values.get(right_idx) {
1812 Some(Scalar::Int64(right_value)) if right_value == left_value => Some(right_idx),
1813 Some(Scalar::Int64(_)) | None => None,
1814 Some(_) => return None,
1815 };
1816 right_positions.push(matched);
1817 }
1818
1819 Some(right_positions)
1820}
1821
1822fn ordered_unique_int64_right_match_positions(
1823 left_key: &Column,
1824 right_key: &Column,
1825) -> Option<Vec<Option<usize>>> {
1826 if let (Some(left_values), Some(right_values)) = (
1832 strictly_increasing_i64_slice(left_key),
1833 strictly_increasing_i64_slice(right_key),
1834 ) {
1835 let mut left_positions = Vec::<Option<usize>>::with_capacity(right_values.len());
1836 let mut left_idx = 0usize;
1837 for &right_value in right_values {
1838 while left_idx < left_values.len() && left_values[left_idx] < right_value {
1839 left_idx += 1;
1840 }
1841 let matched = match left_values.get(left_idx) {
1842 Some(&left_value) if left_value == right_value => Some(left_idx),
1843 _ => None,
1844 };
1845 left_positions.push(matched);
1846 }
1847 return Some(left_positions);
1848 }
1849
1850 let left_values = strictly_increasing_int64_key_values(left_key)?;
1851 let right_values = strictly_increasing_int64_key_values(right_key)?;
1852
1853 let mut left_positions = Vec::<Option<usize>>::with_capacity(right_values.len());
1854 let mut left_idx = 0usize;
1855
1856 for right_value in right_values {
1857 let Scalar::Int64(right_value) = right_value else {
1858 return None;
1859 };
1860 while let Some(Scalar::Int64(left_value)) = left_values.get(left_idx)
1861 && left_value < right_value
1862 {
1863 left_idx += 1;
1864 }
1865
1866 let matched = match left_values.get(left_idx) {
1867 Some(Scalar::Int64(left_value)) if left_value == right_value => Some(left_idx),
1868 Some(Scalar::Int64(_)) | None => None,
1869 Some(_) => return None,
1870 };
1871 left_positions.push(matched);
1872 }
1873
1874 Some(left_positions)
1875}
1876
1877type OptionalJoinPositions = (Vec<Option<usize>>, Vec<Option<usize>>);
1878
1879fn dense_int64_unique_right_left_positions(
1894 left_key: &Column,
1895 right_key: &Column,
1896) -> Option<OptionalJoinPositions> {
1897 let left_values = left_key.as_i64_slice()?;
1898 let right_values = right_key.as_i64_slice()?;
1899 if right_values.is_empty() || left_values.len() > u32::MAX as usize {
1900 return None;
1901 }
1902
1903 let mut min_key = i64::MAX;
1904 let mut max_key = i64::MIN;
1905 for &key in right_values {
1906 min_key = min_key.min(key);
1907 max_key = max_key.max(key);
1908 }
1909
1910 let span = i128::from(max_key)
1911 .checked_sub(i128::from(min_key))?
1912 .checked_add(1)?;
1913 let row_count = left_values.len().saturating_add(right_values.len());
1914 let max_dense_span = row_count.saturating_mul(4).max(1024);
1915 if span > max_dense_span as i128 {
1916 return None;
1917 }
1918 let span = usize::try_from(span).ok()?;
1919 let span_i128 = i128::try_from(span).ok()?;
1920
1921 let mut table = vec![0u32; span];
1924 for (pos, &key) in right_values.iter().enumerate() {
1925 let bucket = usize::try_from(i128::from(key) - i128::from(min_key)).ok()?;
1926 if table[bucket] != 0 {
1927 return None;
1928 }
1929 table[bucket] = (pos as u32).checked_add(1)?;
1930 }
1931
1932 let mut left_positions = Vec::<Option<usize>>::with_capacity(left_values.len());
1933 let mut right_positions = Vec::<Option<usize>>::with_capacity(left_values.len());
1934 for (left_pos, &key) in left_values.iter().enumerate() {
1935 let offset = i128::from(key) - i128::from(min_key);
1936 let matched = if (0..span_i128).contains(&offset) {
1937 match table[offset as usize] {
1938 0 => None,
1939 slot => Some(slot as usize - 1),
1940 }
1941 } else {
1942 None
1943 };
1944 left_positions.push(Some(left_pos));
1945 right_positions.push(matched);
1946 }
1947
1948 Some((left_positions, right_positions))
1949}
1950
1951fn dense_int64_left_positions(
1952 left_key: &Column,
1953 right_key: &Column,
1954) -> Option<OptionalJoinPositions> {
1955 if let Some(direct) = dense_int64_unique_right_left_positions(left_key, right_key) {
1956 return Some(direct);
1957 }
1958 let left_values = all_valid_int64_key_values(left_key)?;
1959 let right_values = all_valid_int64_key_values(right_key)?;
1960
1961 if right_values.is_empty() {
1962 let left_positions = (0..left_values.len()).map(Some).collect::<Vec<_>>();
1963 let right_positions = vec![None; left_values.len()];
1964 return Some((left_positions, right_positions));
1965 }
1966
1967 let mut min_key = i64::MAX;
1968 let mut max_key = i64::MIN;
1969 for value in right_values {
1970 let Scalar::Int64(key) = value else {
1971 return None;
1972 };
1973 min_key = min_key.min(*key);
1974 max_key = max_key.max(*key);
1975 }
1976
1977 let span = i128::from(max_key)
1978 .checked_sub(i128::from(min_key))?
1979 .checked_add(1)?;
1980 let row_count = left_values.len().saturating_add(right_values.len());
1981 let max_dense_span = row_count.saturating_mul(4).max(1024);
1982 if span > max_dense_span as i128 {
1983 return None;
1984 }
1985 let span = usize::try_from(span).ok()?;
1986 let span_i128 = i128::try_from(span).ok()?;
1987
1988 let mut right_counts = vec![0usize; span];
1989 for value in right_values {
1990 let Scalar::Int64(key) = value else {
1991 return None;
1992 };
1993 let bucket = usize::try_from(i128::from(*key) - i128::from(min_key)).ok()?;
1994 right_counts[bucket] = right_counts[bucket].checked_add(1)?;
1995 }
1996
1997 let mut right_offsets = Vec::<usize>::with_capacity(span + 1);
1998 right_offsets.push(0);
1999 let mut running = 0usize;
2000 for count in &right_counts {
2001 running = running.checked_add(*count)?;
2002 right_offsets.push(running);
2003 }
2004
2005 let mut write_offsets = right_offsets[..span].to_vec();
2006 let mut right_positions_by_bucket = vec![0usize; right_values.len()];
2007 for (pos, value) in right_values.iter().enumerate() {
2008 let Scalar::Int64(key) = value else {
2009 return None;
2010 };
2011 let bucket = usize::try_from(i128::from(*key) - i128::from(min_key)).ok()?;
2012 let write_idx = write_offsets[bucket];
2013 right_positions_by_bucket[write_idx] = pos;
2014 write_offsets[bucket] = write_offsets[bucket].checked_add(1)?;
2015 }
2016
2017 let mut output_len = 0usize;
2018 for value in left_values {
2019 let Scalar::Int64(key) = value else {
2020 return None;
2021 };
2022 let offset = i128::from(*key) - i128::from(min_key);
2023 let bucket_rows = if (0..span_i128).contains(&offset) {
2024 let bucket = usize::try_from(offset).ok()?;
2025 right_counts[bucket].max(1)
2026 } else {
2027 1
2028 };
2029 output_len = output_len.checked_add(bucket_rows)?;
2030 }
2031
2032 let mut left_positions = Vec::<Option<usize>>::with_capacity(output_len);
2033 let mut right_positions = Vec::<Option<usize>>::with_capacity(output_len);
2034 for (left_pos, value) in left_values.iter().enumerate() {
2035 let Scalar::Int64(key) = value else {
2036 return None;
2037 };
2038 let offset = i128::from(*key) - i128::from(min_key);
2039 if (0..span_i128).contains(&offset) {
2040 let bucket = usize::try_from(offset).ok()?;
2041 let start = right_offsets[bucket];
2042 let end = right_offsets[bucket + 1];
2043 if start != end {
2044 for &right_pos in &right_positions_by_bucket[start..end] {
2045 left_positions.push(Some(left_pos));
2046 right_positions.push(Some(right_pos));
2047 }
2048 continue;
2049 }
2050 }
2051 left_positions.push(Some(left_pos));
2052 right_positions.push(None);
2053 }
2054
2055 Some((left_positions, right_positions))
2056}
2057
2058fn dense_int64_unique_left_right_positions(
2065 left_key: &Column,
2066 right_key: &Column,
2067) -> Option<OptionalJoinPositions> {
2068 let left_values = left_key.as_i64_slice()?;
2069 let right_values = right_key.as_i64_slice()?;
2070 if left_values.is_empty() || left_values.len() > u32::MAX as usize {
2071 return None;
2072 }
2073
2074 let mut min_key = i64::MAX;
2075 let mut max_key = i64::MIN;
2076 for &key in left_values {
2077 min_key = min_key.min(key);
2078 max_key = max_key.max(key);
2079 }
2080
2081 let span = i128::from(max_key)
2082 .checked_sub(i128::from(min_key))?
2083 .checked_add(1)?;
2084 let row_count = left_values.len().saturating_add(right_values.len());
2085 let max_dense_span = row_count.saturating_mul(4).max(1024);
2086 if span > max_dense_span as i128 {
2087 return None;
2088 }
2089 let span = usize::try_from(span).ok()?;
2090 let span_i128 = i128::try_from(span).ok()?;
2091
2092 let mut table = vec![0u32; span];
2093 for (pos, &key) in left_values.iter().enumerate() {
2094 let bucket = usize::try_from(i128::from(key) - i128::from(min_key)).ok()?;
2095 if table[bucket] != 0 {
2096 return None;
2097 }
2098 table[bucket] = (pos as u32).checked_add(1)?;
2099 }
2100
2101 let mut left_positions = Vec::<Option<usize>>::with_capacity(right_values.len());
2102 let mut right_positions = Vec::<Option<usize>>::with_capacity(right_values.len());
2103 for (right_pos, &key) in right_values.iter().enumerate() {
2104 let offset = i128::from(key) - i128::from(min_key);
2105 let matched = if (0..span_i128).contains(&offset) {
2106 match table[offset as usize] {
2107 0 => None,
2108 slot => Some(slot as usize - 1),
2109 }
2110 } else {
2111 None
2112 };
2113 left_positions.push(matched);
2114 right_positions.push(Some(right_pos));
2115 }
2116
2117 Some((left_positions, right_positions))
2118}
2119
2120fn dense_int64_right_positions(
2121 left_key: &Column,
2122 right_key: &Column,
2123) -> Option<OptionalJoinPositions> {
2124 if let Some(direct) = dense_int64_unique_left_right_positions(left_key, right_key) {
2125 return Some(direct);
2126 }
2127 let left_values = all_valid_int64_key_values(left_key)?;
2128 let right_values = all_valid_int64_key_values(right_key)?;
2129
2130 if left_values.is_empty() {
2131 let left_positions = vec![None; right_values.len()];
2132 let right_positions = (0..right_values.len()).map(Some).collect::<Vec<_>>();
2133 return Some((left_positions, right_positions));
2134 }
2135
2136 let mut min_key = i64::MAX;
2137 let mut max_key = i64::MIN;
2138 for value in left_values {
2139 let Scalar::Int64(key) = value else {
2140 return None;
2141 };
2142 min_key = min_key.min(*key);
2143 max_key = max_key.max(*key);
2144 }
2145
2146 let span = i128::from(max_key)
2147 .checked_sub(i128::from(min_key))?
2148 .checked_add(1)?;
2149 let row_count = left_values.len().saturating_add(right_values.len());
2150 let max_dense_span = row_count.saturating_mul(4).max(1024);
2151 if span > max_dense_span as i128 {
2152 return None;
2153 }
2154 let span = usize::try_from(span).ok()?;
2155 let span_i128 = i128::try_from(span).ok()?;
2156
2157 let mut left_counts = vec![0usize; span];
2158 for value in left_values {
2159 let Scalar::Int64(key) = value else {
2160 return None;
2161 };
2162 let bucket = usize::try_from(i128::from(*key) - i128::from(min_key)).ok()?;
2163 left_counts[bucket] = left_counts[bucket].checked_add(1)?;
2164 }
2165
2166 let mut left_offsets = Vec::<usize>::with_capacity(span + 1);
2167 left_offsets.push(0);
2168 let mut running = 0usize;
2169 for count in &left_counts {
2170 running = running.checked_add(*count)?;
2171 left_offsets.push(running);
2172 }
2173
2174 let mut write_offsets = left_offsets[..span].to_vec();
2175 let mut left_positions_by_bucket = vec![0usize; left_values.len()];
2176 for (pos, value) in left_values.iter().enumerate() {
2177 let Scalar::Int64(key) = value else {
2178 return None;
2179 };
2180 let bucket = usize::try_from(i128::from(*key) - i128::from(min_key)).ok()?;
2181 let write_idx = write_offsets[bucket];
2182 left_positions_by_bucket[write_idx] = pos;
2183 write_offsets[bucket] = write_offsets[bucket].checked_add(1)?;
2184 }
2185
2186 let mut output_len = 0usize;
2187 for value in right_values {
2188 let Scalar::Int64(key) = value else {
2189 return None;
2190 };
2191 let offset = i128::from(*key) - i128::from(min_key);
2192 let bucket_rows = if (0..span_i128).contains(&offset) {
2193 let bucket = usize::try_from(offset).ok()?;
2194 left_counts[bucket].max(1)
2195 } else {
2196 1
2197 };
2198 output_len = output_len.checked_add(bucket_rows)?;
2199 }
2200
2201 let mut left_positions = Vec::<Option<usize>>::with_capacity(output_len);
2202 let mut right_positions = Vec::<Option<usize>>::with_capacity(output_len);
2203 for (right_pos, value) in right_values.iter().enumerate() {
2204 let Scalar::Int64(key) = value else {
2205 return None;
2206 };
2207 let offset = i128::from(*key) - i128::from(min_key);
2208 if (0..span_i128).contains(&offset) {
2209 let bucket = usize::try_from(offset).ok()?;
2210 let start = left_offsets[bucket];
2211 let end = left_offsets[bucket + 1];
2212 if start != end {
2213 for &left_pos in &left_positions_by_bucket[start..end] {
2214 left_positions.push(Some(left_pos));
2215 right_positions.push(Some(right_pos));
2216 }
2217 continue;
2218 }
2219 }
2220 left_positions.push(None);
2221 right_positions.push(Some(right_pos));
2222 }
2223
2224 Some((left_positions, right_positions))
2225}
2226
2227fn dense_int64_unique_outer_positions(
2239 left_key: &Column,
2240 right_key: &Column,
2241) -> Option<OptionalJoinPositions> {
2242 let left_values = left_key.as_i64_slice()?;
2243 let right_values = right_key.as_i64_slice()?;
2244 if left_values.len() > u32::MAX as usize || right_values.len() > u32::MAX as usize {
2245 return None;
2246 }
2247
2248 let mut min_key = i64::MAX;
2249 let mut max_key = i64::MIN;
2250 let mut any = false;
2251 for &key in left_values.iter().chain(right_values.iter()) {
2252 min_key = min_key.min(key);
2253 max_key = max_key.max(key);
2254 any = true;
2255 }
2256 if !any {
2257 return Some((Vec::new(), Vec::new()));
2258 }
2259
2260 let span = i128::from(max_key)
2261 .checked_sub(i128::from(min_key))?
2262 .checked_add(1)?;
2263 let row_count = left_values.len().saturating_add(right_values.len());
2264 let max_dense_span = row_count.saturating_mul(4).max(1024);
2265 if span > max_dense_span as i128 {
2266 return None;
2267 }
2268 let span = usize::try_from(span).ok()?;
2269
2270 let mut left_table = vec![0u32; span];
2271 let mut right_table = vec![0u32; span];
2272 for (pos, &key) in left_values.iter().enumerate() {
2273 let bucket = usize::try_from(i128::from(key) - i128::from(min_key)).ok()?;
2274 if left_table[bucket] != 0 {
2275 return None;
2276 }
2277 left_table[bucket] = (pos as u32).checked_add(1)?;
2278 }
2279 for (pos, &key) in right_values.iter().enumerate() {
2280 let bucket = usize::try_from(i128::from(key) - i128::from(min_key)).ok()?;
2281 if right_table[bucket] != 0 {
2282 return None;
2283 }
2284 right_table[bucket] = (pos as u32).checked_add(1)?;
2285 }
2286
2287 let mut left_positions = Vec::<Option<usize>>::new();
2288 let mut right_positions = Vec::<Option<usize>>::new();
2289 for bucket in 0..span {
2290 match (left_table[bucket], right_table[bucket]) {
2291 (0, 0) => {}
2292 (l, 0) => {
2293 left_positions.push(Some(l as usize - 1));
2294 right_positions.push(None);
2295 }
2296 (0, r) => {
2297 left_positions.push(None);
2298 right_positions.push(Some(r as usize - 1));
2299 }
2300 (l, r) => {
2301 left_positions.push(Some(l as usize - 1));
2302 right_positions.push(Some(r as usize - 1));
2303 }
2304 }
2305 }
2306
2307 Some((left_positions, right_positions))
2308}
2309
2310fn dense_int64_outer_positions(
2311 left_key: &Column,
2312 right_key: &Column,
2313) -> Option<OptionalJoinPositions> {
2314 if let Some(direct) = dense_int64_unique_outer_positions(left_key, right_key) {
2315 return Some(direct);
2316 }
2317 let left_values = all_valid_int64_key_values(left_key)?;
2318 let right_values = all_valid_int64_key_values(right_key)?;
2319
2320 let mut min_key = None::<i64>;
2321 let mut max_key = None::<i64>;
2322 for value in left_values.iter().chain(right_values.iter()) {
2323 let Scalar::Int64(key) = value else {
2324 return None;
2325 };
2326 min_key = Some(min_key.map_or(*key, |current| current.min(*key)));
2327 max_key = Some(max_key.map_or(*key, |current| current.max(*key)));
2328 }
2329
2330 let Some(min_key) = min_key else {
2331 return Some((Vec::new(), Vec::new()));
2332 };
2333 let max_key = max_key.expect("max key exists when min key exists");
2334 let span = i128::from(max_key)
2335 .checked_sub(i128::from(min_key))?
2336 .checked_add(1)?;
2337 let row_count = left_values.len().saturating_add(right_values.len());
2338 let max_dense_span = row_count.saturating_mul(4).max(1024);
2339 if span > max_dense_span as i128 {
2340 return None;
2341 }
2342 let span = usize::try_from(span).ok()?;
2343
2344 let mut left_buckets = (0..span).map(|_| Vec::<usize>::new()).collect::<Vec<_>>();
2345 let mut right_buckets = (0..span).map(|_| Vec::<usize>::new()).collect::<Vec<_>>();
2346
2347 for (pos, value) in left_values.iter().enumerate() {
2348 let Scalar::Int64(key) = value else {
2349 return None;
2350 };
2351 let bucket = usize::try_from(i128::from(*key) - i128::from(min_key)).ok()?;
2352 left_buckets[bucket].push(pos);
2353 }
2354 for (pos, value) in right_values.iter().enumerate() {
2355 let Scalar::Int64(key) = value else {
2356 return None;
2357 };
2358 let bucket = usize::try_from(i128::from(*key) - i128::from(min_key)).ok()?;
2359 right_buckets[bucket].push(pos);
2360 }
2361
2362 let mut output_len = 0usize;
2363 for (left_bucket, right_bucket) in left_buckets.iter().zip(right_buckets.iter()) {
2364 let bucket_rows = match (left_bucket.is_empty(), right_bucket.is_empty()) {
2365 (false, false) => left_bucket.len().checked_mul(right_bucket.len())?,
2366 (false, true) => left_bucket.len(),
2367 (true, false) => right_bucket.len(),
2368 (true, true) => 0,
2369 };
2370 output_len = output_len.checked_add(bucket_rows)?;
2371 }
2372
2373 let mut left_positions = Vec::<Option<usize>>::with_capacity(output_len);
2374 let mut right_positions = Vec::<Option<usize>>::with_capacity(output_len);
2375 for (left_bucket, right_bucket) in left_buckets.into_iter().zip(right_buckets) {
2376 match (left_bucket.is_empty(), right_bucket.is_empty()) {
2377 (false, false) => {
2378 for left_pos in left_bucket {
2379 for &right_pos in &right_bucket {
2380 left_positions.push(Some(left_pos));
2381 right_positions.push(Some(right_pos));
2382 }
2383 }
2384 }
2385 (false, true) => {
2386 for left_pos in left_bucket {
2387 left_positions.push(Some(left_pos));
2388 right_positions.push(None);
2389 }
2390 }
2391 (true, false) => {
2392 for right_pos in right_bucket {
2393 left_positions.push(None);
2394 right_positions.push(Some(right_pos));
2395 }
2396 }
2397 (true, true) => {}
2398 }
2399 }
2400
2401 Some((left_positions, right_positions))
2402}
2403
2404fn ordered_unique_int64_outer_positions(
2405 left_key: &Column,
2406 right_key: &Column,
2407) -> Option<OptionalJoinPositions> {
2408 if let (Some(left_values), Some(right_values)) = (
2415 strictly_increasing_i64_slice(left_key),
2416 strictly_increasing_i64_slice(right_key),
2417 ) {
2418 let cap = left_values.len().saturating_add(right_values.len());
2419 let mut left_positions = Vec::<Option<usize>>::with_capacity(cap);
2420 let mut right_positions = Vec::<Option<usize>>::with_capacity(cap);
2421 let (mut left_idx, mut right_idx) = (0usize, 0usize);
2422 while left_idx < left_values.len() && right_idx < right_values.len() {
2423 match left_values[left_idx].cmp(&right_values[right_idx]) {
2424 Ordering::Equal => {
2425 left_positions.push(Some(left_idx));
2426 right_positions.push(Some(right_idx));
2427 left_idx += 1;
2428 right_idx += 1;
2429 }
2430 Ordering::Less => {
2431 left_positions.push(Some(left_idx));
2432 right_positions.push(None);
2433 left_idx += 1;
2434 }
2435 Ordering::Greater => {
2436 left_positions.push(None);
2437 right_positions.push(Some(right_idx));
2438 right_idx += 1;
2439 }
2440 }
2441 }
2442 while left_idx < left_values.len() {
2443 left_positions.push(Some(left_idx));
2444 right_positions.push(None);
2445 left_idx += 1;
2446 }
2447 while right_idx < right_values.len() {
2448 left_positions.push(None);
2449 right_positions.push(Some(right_idx));
2450 right_idx += 1;
2451 }
2452 return Some((left_positions, right_positions));
2453 }
2454
2455 let left_values = strictly_increasing_int64_key_values(left_key)?;
2456 let right_values = strictly_increasing_int64_key_values(right_key)?;
2457
2458 let mut left_positions =
2459 Vec::<Option<usize>>::with_capacity(left_values.len().saturating_add(right_values.len()));
2460 let mut right_positions = Vec::<Option<usize>>::with_capacity(left_positions.capacity());
2461 let mut left_idx = 0usize;
2462 let mut right_idx = 0usize;
2463
2464 while left_idx < left_values.len() && right_idx < right_values.len() {
2465 let left_value = match &left_values[left_idx] {
2466 Scalar::Int64(value) => *value,
2467 _ => return None,
2468 };
2469 let right_value = match &right_values[right_idx] {
2470 Scalar::Int64(value) => *value,
2471 _ => return None,
2472 };
2473
2474 match left_value.cmp(&right_value) {
2475 Ordering::Equal => {
2476 left_positions.push(Some(left_idx));
2477 right_positions.push(Some(right_idx));
2478 left_idx += 1;
2479 right_idx += 1;
2480 }
2481 Ordering::Less => {
2482 left_positions.push(Some(left_idx));
2483 right_positions.push(None);
2484 left_idx += 1;
2485 }
2486 Ordering::Greater => {
2487 left_positions.push(None);
2488 right_positions.push(Some(right_idx));
2489 right_idx += 1;
2490 }
2491 }
2492 }
2493
2494 while left_idx < left_values.len() {
2495 left_positions.push(Some(left_idx));
2496 right_positions.push(None);
2497 left_idx += 1;
2498 }
2499 while right_idx < right_values.len() {
2500 left_positions.push(None);
2501 right_positions.push(Some(right_idx));
2502 right_idx += 1;
2503 }
2504
2505 Some((left_positions, right_positions))
2506}
2507
2508fn identity_merge_column(
2509 column: &Column,
2510 row_count: usize,
2511 identity_positions: &mut Option<Vec<usize>>,
2512) -> Column {
2513 if column.validity().all() {
2514 return column.clone();
2515 }
2516
2517 let positions = identity_positions.get_or_insert_with(|| (0..row_count).collect());
2518 column.take_positions(positions)
2519}
2520
2521fn resolve_merge_indicator_name(indicator_name: Option<&str>) -> Result<Option<String>, JoinError> {
2522 let Some(name) = indicator_name else {
2523 return Ok(None);
2524 };
2525 if name.trim().is_empty() {
2526 return Err(JoinError::Frame(FrameError::CompatibilityRejected(
2527 "merge indicator column name must be non-empty".to_owned(),
2528 )));
2529 }
2530 Ok(Some(name.to_owned()))
2531}
2532
2533fn build_merge_indicator_column(
2534 left_positions: &[Option<usize>],
2535 right_positions: &[Option<usize>],
2536) -> Result<Column, JoinError> {
2537 let values = left_positions
2538 .iter()
2539 .zip(right_positions.iter())
2540 .map(|(left_pos, right_pos)| match (left_pos, right_pos) {
2541 (Some(_), Some(_)) => fp_types::Scalar::Utf8("both".to_owned()),
2542 (Some(_), None) => fp_types::Scalar::Utf8("left_only".to_owned()),
2543 (None, Some(_)) => fp_types::Scalar::Utf8("right_only".to_owned()),
2544 (None, None) => fp_types::Scalar::Null(fp_types::NullKind::Null),
2545 })
2546 .collect::<Vec<_>>();
2547 Column::from_values(values).map_err(JoinError::from)
2548}
2549
2550fn ensure_indicator_name_available(
2551 indicator_name: &str,
2552 left_col_names: &HashSet<&String>,
2553 right_col_names: &HashSet<&String>,
2554 output_columns: &std::collections::BTreeMap<String, Column>,
2555) -> Result<(), JoinError> {
2556 if left_col_names
2557 .iter()
2558 .any(|name| name.as_str() == indicator_name)
2559 || right_col_names
2560 .iter()
2561 .any(|name| name.as_str() == indicator_name)
2562 || output_columns.contains_key(indicator_name)
2563 {
2564 return Err(JoinError::Frame(FrameError::CompatibilityRejected(
2565 format!("merge indicator column '{indicator_name}' conflicts with an existing column"),
2566 )));
2567 }
2568 Ok(())
2569}
2570
2571fn take_positions_typed(column: &Column, positions: &[usize]) -> Column {
2589 if let Some(slice) = column.as_i64_slice() {
2590 let mut data = Vec::with_capacity(positions.len());
2591 for &pos in positions {
2592 data.push(slice[pos]);
2593 }
2594 return Column::from_i64_values(data);
2595 }
2596 column.take_positions(positions)
2597}
2598
2599#[derive(Clone, Copy)]
2600enum PositionSelection<'a> {
2601 Positions(&'a [usize]),
2602 ContiguousRange { start: usize, len: usize },
2603}
2604
2605impl PositionSelection<'_> {
2606 fn len(self) -> usize {
2607 match self {
2608 Self::Positions(positions) => positions.len(),
2609 Self::ContiguousRange { len, .. } => len,
2610 }
2611 }
2612}
2613
2614fn take_position_selection_typed(column: &Column, selection: PositionSelection<'_>) -> Column {
2615 match selection {
2616 PositionSelection::Positions(positions) => take_positions_typed(column, positions),
2617 PositionSelection::ContiguousRange { start, len } => {
2618 column.take_contiguous_range(start, len)
2619 }
2620 }
2621}
2622
2623fn take_lower_hex_sequence_range(column: &Column, start: usize, len: usize) -> Option<Column> {
2624 let (prefix, certificate, source_len) = column.as_lower_hex_sequence_utf8()?;
2625 let end = start.checked_add(len)?;
2626 if end > source_len {
2627 return None;
2628 }
2629 let start_value = certificate.value_at(start)?;
2630 Column::from_lower_hex_sequence_utf8(prefix, start_value, len, certificate.hex_width())
2631}
2632
2633#[derive(Clone, Copy)]
2634enum FusedInt64Side {
2635 Left,
2636 Right,
2637}
2638
2639struct FusedInt64OutputColumn<'a> {
2640 name: String,
2641 side: FusedInt64Side,
2642 values: &'a [i64],
2643}
2644
2645struct FusedInt64MergeOptions<'a> {
2646 suffixes: &'a ResolvedMergeSuffixes,
2647 require_all_left_keys_matched: bool,
2648}
2649
2650#[cfg(not(test))]
2651const DENSE_I64_INNER_PARALLEL_MIN_VALUES: usize = 1 << 18;
2652#[cfg(test)]
2653const DENSE_I64_INNER_PARALLEL_MIN_VALUES: usize = 1;
2654const DENSE_I64_INNER_PARALLEL_MAX_CHUNKS: usize = 16;
2655
2656fn join_parallel_thread_count() -> usize {
2657 static THREAD_COUNT: OnceLock<usize> = OnceLock::new();
2658 *THREAD_COUNT.get_or_init(|| {
2659 std::thread::available_parallelism()
2660 .map_or(1, usize::from)
2661 .min(DENSE_I64_INNER_PARALLEL_MAX_CHUNKS)
2662 })
2663}
2664
2665struct DenseI64InnerOutputPlan<'a> {
2666 left_keys: &'a [i64],
2667 min: i64,
2668 max: i64,
2669 offsets: &'a [usize],
2670 positions: &'a [usize],
2671 output_len: usize,
2672}
2673
2674enum DenseI64LaneData {
2676 RepeatRunLengths {
2680 values: Vec<i64>,
2681 run_lens: Arc<[usize]>,
2682 },
2683 RepeatedSlices {
2686 data: Vec<i64>,
2687 segments: Arc<[(usize, usize)]>,
2688 },
2689 Full(Vec<i64>),
2691}
2692
2693fn build_dense_i64_inner_output_data(
2714 specs: &[FusedInt64OutputColumn<'_>],
2715 plan: &DenseI64InnerOutputPlan<'_>,
2716) -> Vec<DenseI64LaneData> {
2717 let mut matched: Vec<(usize, usize, usize)> = Vec::new();
2720 for (left_pos, &v) in plan.left_keys.iter().enumerate() {
2721 if v < plan.min || v > plan.max {
2722 continue;
2723 }
2724 let bucket = (v - plan.min) as usize;
2725 if bucket + 1 >= plan.offsets.len() {
2726 continue;
2727 }
2728 let start = plan.offsets[bucket];
2729 let run_len = plan.offsets[bucket + 1] - start;
2730 if run_len == 0 {
2731 continue;
2732 }
2733 matched.push((left_pos, start, run_len));
2734 }
2735 debug_assert_eq!(
2736 matched
2737 .iter()
2738 .map(|&(_, _, run_len)| run_len)
2739 .sum::<usize>(),
2740 plan.output_len
2741 );
2742
2743 let use_repeat_runs = plan.output_len >= matched.len().saturating_mul(2);
2746
2747 let use_repeated_slices = use_repeat_runs;
2748 let repeat_run_lens: Option<Arc<[usize]>> = if use_repeat_runs {
2749 Some(
2750 matched
2751 .iter()
2752 .map(|&(_, _, run_len)| run_len)
2753 .collect::<Vec<_>>()
2754 .into(),
2755 )
2756 } else {
2757 None
2758 };
2759 let repeated_segments: Option<Arc<[(usize, usize)]>> = if use_repeated_slices {
2760 Some(
2761 matched
2762 .iter()
2763 .map(|&(_, start, run_len)| (start, run_len))
2764 .collect::<Vec<_>>()
2765 .into(),
2766 )
2767 } else {
2768 None
2769 };
2770
2771 let full_specs: Vec<usize> = specs
2772 .iter()
2773 .enumerate()
2774 .filter(|(_, spec)| {
2775 !(use_repeat_runs && matches!(spec.side, FusedInt64Side::Left))
2776 && !(use_repeated_slices && matches!(spec.side, FusedInt64Side::Right))
2777 })
2778 .map(|(idx, _)| idx)
2779 .collect();
2780
2781 let mut full_data: Vec<Vec<i64>> = Vec::new();
2784 let thread_count = join_parallel_thread_count();
2785 if !full_specs.is_empty()
2786 && plan.output_len >= DENSE_I64_INNER_PARALLEL_MIN_VALUES
2787 && thread_count > 1
2788 {
2789 let tapes: Vec<Option<Vec<i64>>> = full_specs
2793 .iter()
2794 .map(|&spec_idx| match specs[spec_idx].side {
2795 FusedInt64Side::Left => None,
2796 FusedInt64Side::Right => Some(
2797 plan.positions
2798 .iter()
2799 .map(|&right_pos| specs[spec_idx].values[right_pos])
2800 .collect(),
2801 ),
2802 })
2803 .collect();
2804
2805 let target = plan.output_len.div_ceil(thread_count).max(1);
2808 let mut boundaries = vec![(0usize, 0usize)];
2809 let mut cumulative = 0usize;
2810 let mut next_target = target;
2811 for (matched_idx, &(_, _, run_len)) in matched.iter().enumerate() {
2812 cumulative += run_len;
2813 if cumulative >= next_target && matched_idx + 1 < matched.len() {
2814 boundaries.push((matched_idx + 1, cumulative));
2815 next_target = cumulative.saturating_add(target);
2816 }
2817 }
2818 boundaries.push((matched.len(), plan.output_len));
2819 let chunk_count = boundaries.len() - 1;
2820
2821 let mut column_bufs: Vec<Vec<i64>> = full_specs
2824 .iter()
2825 .map(|_| vec![0i64; plan.output_len])
2826 .collect();
2827 let mut bundles: Vec<Vec<&mut [i64]>> = (0..chunk_count)
2828 .map(|_| Vec::with_capacity(full_specs.len()))
2829 .collect();
2830 for buf in &mut column_bufs {
2831 let mut rest: &mut [i64] = buf.as_mut_slice();
2832 let mut prev = 0usize;
2833 for (chunk_idx, window) in boundaries.windows(2).enumerate() {
2834 let (chunk_slice, tail) = rest.split_at_mut(window[1].1 - prev);
2835 prev = window[1].1;
2836 rest = tail;
2837 bundles[chunk_idx].push(chunk_slice);
2838 }
2839 }
2840
2841 let matched = &matched;
2842 let full_specs = &full_specs;
2843 std::thread::scope(|scope| {
2844 let mut handles = Vec::with_capacity(chunk_count);
2845 for (chunk_idx, mut bundle) in bundles.into_iter().enumerate() {
2846 let (matched_start, out_start) = boundaries[chunk_idx];
2847 let (matched_end, out_end) = boundaries[chunk_idx + 1];
2848 let tapes = &tapes;
2849 handles.push(scope.spawn(move || {
2850 let mut cursor = 0usize;
2851 for &(left_pos, start, run_len) in &matched[matched_start..matched_end] {
2852 for (slice, (&spec_idx, tape)) in
2853 bundle.iter_mut().zip(full_specs.iter().zip(tapes.iter()))
2854 {
2855 match specs[spec_idx].side {
2856 FusedInt64Side::Left => {
2857 slice[cursor..cursor + run_len]
2858 .fill(specs[spec_idx].values[left_pos]);
2859 }
2860 FusedInt64Side::Right => {
2861 slice[cursor..cursor + run_len].copy_from_slice(
2862 &tape.as_ref().expect("right spec must have a bucket tape")
2863 [start..start + run_len],
2864 );
2865 }
2866 }
2867 }
2868 cursor += run_len;
2869 }
2870 debug_assert_eq!(cursor, out_end - out_start);
2871 }));
2872 }
2873 for handle in handles {
2874 handle
2875 .join()
2876 .expect("dense i64 output worker must not panic");
2877 }
2878 });
2879 full_data = column_bufs;
2880 } else if !full_specs.is_empty() {
2881 full_data = full_specs
2882 .iter()
2883 .map(|_| Vec::<i64>::with_capacity(plan.output_len))
2884 .collect();
2885 for &(left_pos, start, run_len) in &matched {
2886 for (out, &spec_idx) in full_data.iter_mut().zip(full_specs.iter()) {
2887 match specs[spec_idx].side {
2888 FusedInt64Side::Left => {
2889 out.resize(out.len() + run_len, specs[spec_idx].values[left_pos]);
2890 }
2891 FusedInt64Side::Right => {
2892 for &right_pos in &plan.positions[start..start + run_len] {
2893 out.push(specs[spec_idx].values[right_pos]);
2894 }
2895 }
2896 }
2897 }
2898 }
2899 debug_assert!(full_data.iter().all(|data| data.len() == plan.output_len));
2900 }
2901
2902 let mut full_iter = full_data.into_iter();
2905 specs
2906 .iter()
2907 .map(|spec| {
2908 if use_repeat_runs && matches!(spec.side, FusedInt64Side::Left) {
2909 DenseI64LaneData::RepeatRunLengths {
2910 values: matched
2911 .iter()
2912 .map(|&(left_pos, _, _)| spec.values[left_pos])
2913 .collect(),
2914 run_lens: Arc::clone(
2915 repeat_run_lens
2916 .as_ref()
2917 .expect("repeat run lengths must exist"),
2918 ),
2919 }
2920 } else if use_repeated_slices && matches!(spec.side, FusedInt64Side::Right) {
2921 DenseI64LaneData::RepeatedSlices {
2922 data: plan
2923 .positions
2924 .iter()
2925 .map(|&right_pos| spec.values[right_pos])
2926 .collect(),
2927 segments: Arc::clone(
2928 repeated_segments
2929 .as_ref()
2930 .expect("repeated slice segments must exist"),
2931 ),
2932 }
2933 } else {
2934 DenseI64LaneData::Full(
2935 full_iter
2936 .next()
2937 .expect("full lane buffer must exist for every non-run spec"),
2938 )
2939 }
2940 })
2941 .collect()
2942}
2943
2944enum DenseInnerSpecKind {
2948 I64,
2949 F64,
2950}
2951
2952struct FusedF64OutputColumn<'a> {
2954 name: String,
2955 side: FusedInt64Side,
2956 values: &'a [f64],
2957}
2958
2959fn dense_inner_matched_runs(plan: &DenseI64InnerOutputPlan<'_>) -> Vec<(usize, usize, usize)> {
2964 let mut matched = Vec::new();
2965 for (left_pos, &v) in plan.left_keys.iter().enumerate() {
2966 if v < plan.min || v > plan.max {
2967 continue;
2968 }
2969 let bucket = (v - plan.min) as usize;
2970 if bucket + 1 >= plan.offsets.len() {
2971 continue;
2972 }
2973 let start = plan.offsets[bucket];
2974 let run_len = plan.offsets[bucket + 1] - start;
2975 if run_len == 0 {
2976 continue;
2977 }
2978 matched.push((left_pos, start, run_len));
2979 }
2980 matched
2981}
2982
2983fn build_dense_inner_f64_column(
2999 side: FusedInt64Side,
3000 values: &[f64],
3001 matched: &[(usize, usize, usize)],
3002 positions: &[usize],
3003 run_lens: &Arc<[usize]>,
3004 segments: &Arc<[(usize, usize)]>,
3005 output_len: usize,
3006) -> Column {
3007 match side {
3008 FusedInt64Side::Left => {
3009 let run_values: Vec<f64> = matched
3010 .iter()
3011 .map(|&(left_pos, _, _)| values[left_pos])
3012 .collect();
3013 Column::from_f64_repeat_values_run_lengths(run_values, Arc::clone(run_lens))
3014 }
3015 FusedInt64Side::Right => {
3016 let tape: Vec<f64> = positions.iter().map(|&p| values[p]).collect();
3017 Column::from_f64_repeated_slices_shared(tape, Arc::clone(segments), output_len)
3018 }
3019 }
3020}
3021
3022fn build_dense_inner_f64_columns(
3027 specs: Vec<FusedF64OutputColumn<'_>>,
3028 matched: &[(usize, usize, usize)],
3029 positions: &[usize],
3030 output_len: usize,
3031) -> Vec<(String, Column)> {
3032 if specs.is_empty() {
3033 return Vec::new();
3034 }
3035 let run_lens: Arc<[usize]> = matched.iter().map(|&(_, _, run_len)| run_len).collect();
3036 let segments: Arc<[(usize, usize)]> = matched
3037 .iter()
3038 .map(|&(_, bucket_start, run_len)| (bucket_start, run_len))
3039 .collect();
3040
3041 let worker_count = join_parallel_thread_count().min(specs.len());
3042 if worker_count < 2 {
3043 return specs
3044 .into_iter()
3045 .map(|s| {
3046 (
3047 s.name,
3048 build_dense_inner_f64_column(
3049 s.side, s.values, matched, positions, &run_lens, &segments, output_len,
3050 ),
3051 )
3052 })
3053 .collect();
3054 }
3055
3056 let next = std::sync::atomic::AtomicUsize::new(0);
3057 let specs_ref = &specs;
3058 let run_lens_ref = &run_lens;
3059 let segments_ref = &segments;
3060 let built_by_worker = std::thread::scope(|scope| {
3061 let mut handles = Vec::with_capacity(worker_count);
3062 for _ in 0..worker_count {
3063 let next = &next;
3064 handles.push(scope.spawn(move || {
3065 let mut local: Vec<(usize, Column)> = Vec::new();
3066 loop {
3067 let idx = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3068 if idx >= specs_ref.len() {
3069 break;
3070 }
3071 let s = &specs_ref[idx];
3072 local.push((
3073 idx,
3074 build_dense_inner_f64_column(
3075 s.side,
3076 s.values,
3077 matched,
3078 positions,
3079 run_lens_ref,
3080 segments_ref,
3081 output_len,
3082 ),
3083 ));
3084 }
3085 local
3086 }));
3087 }
3088 let mut all: Vec<(usize, Column)> = Vec::new();
3089 for handle in handles {
3090 all.extend(
3091 handle
3092 .join()
3093 .expect("f64 inner-merge column worker panicked"),
3094 );
3095 }
3096 all
3097 });
3098
3099 let mut built: Vec<Option<Column>> = (0..specs.len()).map(|_| None).collect();
3100 for (idx, column) in built_by_worker {
3101 built[idx] = Some(column);
3102 }
3103 specs
3104 .into_iter()
3105 .zip(built)
3106 .map(|(s, column)| {
3107 (
3108 s.name,
3109 column.expect("every f64 column index is built once"),
3110 )
3111 })
3112 .collect()
3113}
3114
3115fn build_single_key_dense_i64_inner_merge_output(
3116 left: &fp_frame::DataFrame,
3117 right: &fp_frame::DataFrame,
3118 left_on: &[&str],
3119 right_on: &[&str],
3120 left_key: &Column,
3121 right_key: &Column,
3122 options: FusedInt64MergeOptions<'_>,
3123) -> Result<Option<MergedDataFrame>, JoinError> {
3124 debug_assert_eq!(left_on.len(), 1);
3125 debug_assert_eq!(right_on.len(), 1);
3126
3127 let Some(left_keys) = left_key.as_i64_slice() else {
3128 return Ok(None);
3129 };
3130 let Some(right_keys) = right_key.as_i64_slice() else {
3131 return Ok(None);
3132 };
3133
3134 let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
3135 let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
3136 let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
3137 let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
3138 let shared_key_names = if left_on[0] == right_on[0] {
3139 [left_on[0]].into_iter().collect::<HashSet<&str>>()
3140 } else {
3141 HashSet::new()
3142 };
3143 let overlapping_names =
3144 collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
3145
3146 let mut i64_specs = Vec::<FusedInt64OutputColumn<'_>>::new();
3154 let mut f64_specs = Vec::<FusedF64OutputColumn<'_>>::new();
3155 let mut order_kinds = Vec::<DenseInnerSpecKind>::new();
3156
3157 for name in left.column_names() {
3158 let col = left
3159 .columns()
3160 .get(name)
3161 .expect("left column listed in column_names must exist");
3162 let out_name = if left_key_name_set.contains(name.as_str()) {
3163 name.clone()
3164 } else if right_col_names.contains(name) {
3165 apply_merge_suffix(name, options.suffixes.left.as_deref())
3166 } else {
3167 name.clone()
3168 };
3169 if let Some(values) = col.as_i64_slice() {
3170 i64_specs.push(FusedInt64OutputColumn {
3171 name: out_name,
3172 side: FusedInt64Side::Left,
3173 values,
3174 });
3175 order_kinds.push(DenseInnerSpecKind::I64);
3176 } else if let Some(values) = col.as_f64_slice() {
3177 f64_specs.push(FusedF64OutputColumn {
3178 name: out_name,
3179 side: FusedInt64Side::Left,
3180 values,
3181 });
3182 order_kinds.push(DenseInnerSpecKind::F64);
3183 } else {
3184 return Ok(None);
3185 }
3186 }
3187
3188 for name in right.column_names() {
3189 let col = right
3190 .columns()
3191 .get(name)
3192 .expect("right column listed in column_names must exist");
3193 if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
3194 continue;
3195 }
3196 let out_name = if left_col_names.contains(name) {
3197 apply_merge_suffix(name, options.suffixes.right.as_deref())
3198 } else {
3199 name.clone()
3200 };
3201 if let Some(values) = col.as_i64_slice() {
3202 i64_specs.push(FusedInt64OutputColumn {
3203 name: out_name,
3204 side: FusedInt64Side::Right,
3205 values,
3206 });
3207 order_kinds.push(DenseInnerSpecKind::I64);
3208 } else if let Some(values) = col.as_f64_slice() {
3209 f64_specs.push(FusedF64OutputColumn {
3210 name: out_name,
3211 side: FusedInt64Side::Right,
3212 values,
3213 });
3214 order_kinds.push(DenseInnerSpecKind::F64);
3215 } else {
3216 return Ok(None);
3217 }
3218 }
3219
3220 ensure_merge_suffixes_for_overlaps(&overlapping_names, options.suffixes)?;
3221
3222 if left_keys.is_empty() || right_keys.is_empty() {
3223 if options.require_all_left_keys_matched && !left_keys.is_empty() {
3224 return Ok(None);
3225 }
3226 let mut columns = std::collections::BTreeMap::new();
3227 let mut column_order = Vec::with_capacity(order_kinds.len());
3228 let mut i64_it = i64_specs.into_iter();
3229 let mut f64_it = f64_specs.into_iter();
3230 for kind in &order_kinds {
3231 match kind {
3232 DenseInnerSpecKind::I64 => {
3233 let spec = i64_it.next().expect("i64 spec for each I64 kind");
3234 insert_merged_output_column(
3235 &mut columns,
3236 &mut column_order,
3237 spec.name,
3238 Column::from_i64_values(Vec::new()),
3239 )?;
3240 }
3241 DenseInnerSpecKind::F64 => {
3242 let spec = f64_it.next().expect("f64 spec for each F64 kind");
3243 insert_merged_output_column(
3244 &mut columns,
3245 &mut column_order,
3246 spec.name,
3247 Column::from_f64_values(Vec::new()),
3248 )?;
3249 }
3250 }
3251 }
3252 return Ok(Some(MergedDataFrame {
3253 index: Index::new(Vec::new()),
3254 columns,
3255 column_order,
3256 }));
3257 }
3258
3259 let mut min = right_keys[0];
3260 let mut max = right_keys[0];
3261 for &v in right_keys {
3262 if v < min {
3263 min = v;
3264 }
3265 if v > max {
3266 max = v;
3267 }
3268 }
3269 let span = (max as i128) - (min as i128) + 1;
3270 if span > (1i128 << 24) || span > 16 * (right_keys.len() as i128) {
3271 return Ok(None);
3272 }
3273 let range = span as usize;
3274
3275 let mut offsets = vec![0usize; range + 1];
3276 for &v in right_keys {
3277 offsets[(v - min) as usize + 1] += 1;
3278 }
3279 for i in 0..range {
3280 offsets[i + 1] += offsets[i];
3281 }
3282 let mut positions = vec![0usize; right_keys.len()];
3283 let mut cursor = offsets.clone();
3284 for (pos, &v) in right_keys.iter().enumerate() {
3285 let bucket = (v - min) as usize;
3286 positions[cursor[bucket]] = pos;
3287 cursor[bucket] += 1;
3288 }
3289
3290 let mut output_len = 0usize;
3291 for &v in left_keys {
3292 if v < min || v > max {
3293 if options.require_all_left_keys_matched {
3294 return Ok(None);
3295 }
3296 continue;
3297 }
3298 let bucket = (v - min) as usize;
3299 let bucket_len = offsets[bucket + 1] - offsets[bucket];
3300 if bucket_len == 0 {
3301 if options.require_all_left_keys_matched {
3302 return Ok(None);
3303 }
3304 continue;
3305 }
3306 let Some(new_output_len) = output_len.checked_add(bucket_len) else {
3307 return Ok(None);
3308 };
3309 output_len = new_output_len;
3310 }
3311
3312 let output_plan = DenseI64InnerOutputPlan {
3313 left_keys,
3314 min,
3315 max,
3316 offsets: &offsets,
3317 positions: &positions,
3318 output_len,
3319 };
3320 let i64_lanes = build_dense_i64_inner_output_data(&i64_specs, &output_plan);
3321 let matched = if f64_specs.is_empty() {
3325 Vec::new()
3326 } else {
3327 dense_inner_matched_runs(&output_plan)
3328 };
3329 let f64_columns = build_dense_inner_f64_columns(f64_specs, &matched, &positions, output_len);
3330
3331 let index = Index::new_known_unique_int64_unit_range(0, output_len);
3335 let mut columns = std::collections::BTreeMap::new();
3336 let mut column_order = Vec::with_capacity(order_kinds.len());
3337 let mut i64_it = i64_specs.into_iter().zip(i64_lanes);
3338 let mut f64_it = f64_columns.into_iter();
3339 for kind in &order_kinds {
3340 match kind {
3341 DenseInnerSpecKind::I64 => {
3342 let (spec, lane) = i64_it.next().expect("i64 lane for each I64 kind");
3343 let column = match lane {
3344 DenseI64LaneData::RepeatRunLengths { values, run_lens } => {
3345 Column::from_i64_repeat_values_run_lengths(values, run_lens)
3346 }
3347 DenseI64LaneData::RepeatedSlices { data, segments } => {
3348 Column::from_i64_repeated_slices_shared(data, segments, output_len)
3349 }
3350 DenseI64LaneData::Full(data) => Column::from_i64_values(data),
3351 };
3352 debug_assert_eq!(column.len(), output_len);
3353 insert_merged_output_column(&mut columns, &mut column_order, spec.name, column)?;
3354 }
3355 DenseInnerSpecKind::F64 => {
3356 let (name, column) = f64_it.next().expect("f64 column for each F64 kind");
3357 debug_assert_eq!(column.len(), output_len);
3358 insert_merged_output_column(&mut columns, &mut column_order, name, column)?;
3359 }
3360 }
3361 }
3362
3363 Ok(Some(MergedDataFrame {
3364 index,
3365 columns,
3366 column_order,
3367 }))
3368}
3369
3370fn push_join_invalid_range(ranges: &mut Vec<(usize, usize)>, start: usize, len: usize) {
3371 if len == 0 {
3372 return;
3373 }
3374 if let Some((last_start, last_len)) = ranges.last_mut()
3375 && last_start.checked_add(*last_len) == Some(start)
3376 {
3377 *last_len += len;
3378 return;
3379 }
3380 ranges.push((start, len));
3381}
3382
3383fn dense_cycle_key_at(witness: Int64DenseCycleWitness, row: usize) -> Option<i64> {
3384 let offset = i64::try_from(row % witness.period).ok()?;
3385 witness.start.checked_add(offset)
3386}
3387
3388fn dense_cycle_left_join_shape(
3389 left_witness: Int64DenseCycleWitness,
3390 right_witness: Int64DenseCycleWitness,
3391) -> Option<(usize, ValidityMask)> {
3392 let mut output_len = 0usize;
3393 let mut invalid_ranges = Vec::<(usize, usize)>::new();
3394 for left_pos in 0..left_witness.len {
3395 let key = dense_cycle_key_at(left_witness, left_pos)?;
3396 if let Some((_, right_count)) = right_witness.offset_count_for_key(key) {
3397 output_len = output_len.checked_add(right_count)?;
3398 } else {
3399 push_join_invalid_range(&mut invalid_ranges, output_len, 1);
3400 output_len = output_len.checked_add(1)?;
3401 }
3402 }
3403 let right_validity = ValidityMask::from_invalid_ranges(Arc::from(invalid_ranges), output_len);
3404 Some((output_len, right_validity))
3405}
3406
3407fn build_single_key_dense_cycle_i64_left_merge_output(
3422 left: &fp_frame::DataFrame,
3423 right: &fp_frame::DataFrame,
3424 left_on: &[&str],
3425 right_on: &[&str],
3426 left_key: &Column,
3427 right_key: &Column,
3428 suffixes: &ResolvedMergeSuffixes,
3429) -> Result<Option<MergedDataFrame>, JoinError> {
3430 debug_assert_eq!(left_on.len(), 1);
3431 debug_assert_eq!(right_on.len(), 1);
3432
3433 let Some(left_witness) = left_key
3434 .int64_dense_cycle_witness()
3435 .filter(|witness| witness.len == left_key.len())
3436 else {
3437 return Ok(None);
3438 };
3439 let Some(right_witness) = right_key
3440 .int64_dense_cycle_witness()
3441 .filter(|witness| witness.len == right_key.len())
3442 else {
3443 return Ok(None);
3444 };
3445 let Some((output_len, right_validity)) =
3446 dense_cycle_left_join_shape(left_witness, right_witness)
3447 else {
3448 return Ok(None);
3449 };
3450
3451 let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
3452 let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
3453 let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
3454 let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
3455 let shared_key_names = if left_on[0] == right_on[0] {
3456 [left_on[0]].into_iter().collect::<HashSet<&str>>()
3457 } else {
3458 HashSet::new()
3459 };
3460 let overlapping_names =
3461 collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
3462
3463 enum DenseCycleLeftLane {
3464 Left,
3465 Right,
3466 }
3467 let mut spec_names = Vec::<String>::new();
3468 let mut spec_kinds = Vec::<DenseCycleLeftLane>::new();
3469 let mut spec_sources = Vec::<Arc<[i64]>>::new();
3470
3471 for name in left.column_names() {
3472 let col = left
3473 .columns()
3474 .get(name)
3475 .expect("left column listed in column_names must exist");
3476 let Some(source) = col.as_i64_arc() else {
3477 return Ok(None);
3478 };
3479 let out_name = if left_key_name_set.contains(name.as_str()) {
3480 name.clone()
3481 } else if right_col_names.contains(name) {
3482 apply_merge_suffix(name, suffixes.left.as_deref())
3483 } else {
3484 name.clone()
3485 };
3486 spec_names.push(out_name);
3487 spec_kinds.push(DenseCycleLeftLane::Left);
3488 spec_sources.push(source);
3489 }
3490
3491 for name in right.column_names() {
3492 let col = right
3493 .columns()
3494 .get(name)
3495 .expect("right column listed in column_names must exist");
3496 if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
3497 continue;
3498 }
3499 let Some(source) = col.as_i64_arc() else {
3500 return Ok(None);
3501 };
3502 let out_name = if left_col_names.contains(name) {
3503 apply_merge_suffix(name, suffixes.right.as_deref())
3504 } else {
3505 name.clone()
3506 };
3507 spec_names.push(out_name);
3508 spec_kinds.push(DenseCycleLeftLane::Right);
3509 spec_sources.push(source);
3510 }
3511 ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
3512
3513 let index = Index::new_known_unique_int64_unit_range(0, output_len);
3514 let mut columns = std::collections::BTreeMap::new();
3515 let mut column_order = Vec::with_capacity(spec_names.len());
3516 for ((name, kind), source) in spec_names.into_iter().zip(spec_kinds).zip(spec_sources) {
3517 let column = match kind {
3518 DenseCycleLeftLane::Left => Column::from_i64_left_join_dense_cycle_left(
3519 source,
3520 left_witness,
3521 right_witness,
3522 output_len,
3523 ),
3524 DenseCycleLeftLane::Right => Column::from_i64_left_join_dense_cycle_right_nullable(
3525 source,
3526 left_witness,
3527 right_witness,
3528 right_validity.clone(),
3529 output_len,
3530 ),
3531 };
3532 debug_assert_eq!(column.len(), output_len);
3533 insert_merged_output_column(&mut columns, &mut column_order, name, column)?;
3534 }
3535
3536 Ok(Some(MergedDataFrame {
3537 index,
3538 columns,
3539 column_order,
3540 }))
3541}
3542
3543fn build_single_key_dense_i64_left_merge_output(
3563 left: &fp_frame::DataFrame,
3564 right: &fp_frame::DataFrame,
3565 left_on: &[&str],
3566 right_on: &[&str],
3567 left_key: &Column,
3568 right_key: &Column,
3569 suffixes: &ResolvedMergeSuffixes,
3570) -> Result<Option<MergedDataFrame>, JoinError> {
3571 debug_assert_eq!(left_on.len(), 1);
3572 debug_assert_eq!(right_on.len(), 1);
3573
3574 let Some(left_keys) = left_key.as_i64_slice() else {
3575 return Ok(None);
3576 };
3577 let Some(right_keys) = right_key.as_i64_slice() else {
3578 return Ok(None);
3579 };
3580 if left_keys.is_empty() || right_keys.is_empty() {
3583 return Ok(None);
3584 }
3585
3586 let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
3587 let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
3588 let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
3589 let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
3590 let shared_key_names = if left_on[0] == right_on[0] {
3591 [left_on[0]].into_iter().collect::<HashSet<&str>>()
3592 } else {
3593 HashSet::new()
3594 };
3595 let overlapping_names =
3596 collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
3597
3598 let mut specs = Vec::<FusedInt64OutputColumn<'_>>::new();
3599 let mut sources = Vec::<Arc<[i64]>>::new();
3600 for name in left.column_names() {
3601 let col = left
3602 .columns()
3603 .get(name)
3604 .expect("left column listed in column_names must exist");
3605 let Some(values) = col.as_i64_slice() else {
3606 return Ok(None);
3607 };
3608 let source = col.as_i64_arc().unwrap_or_else(|| Arc::from(values));
3609 let out_name = if left_key_name_set.contains(name.as_str()) {
3610 name.clone()
3611 } else if right_col_names.contains(name) {
3612 apply_merge_suffix(name, suffixes.left.as_deref())
3613 } else {
3614 name.clone()
3615 };
3616 specs.push(FusedInt64OutputColumn {
3617 name: out_name,
3618 side: FusedInt64Side::Left,
3619 values,
3620 });
3621 sources.push(source);
3622 }
3623 for name in right.column_names() {
3624 let col = right
3625 .columns()
3626 .get(name)
3627 .expect("right column listed in column_names must exist");
3628 if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
3629 continue;
3630 }
3631 let Some(values) = col.as_i64_slice() else {
3632 return Ok(None);
3633 };
3634 let source = col.as_i64_arc().unwrap_or_else(|| Arc::from(values));
3635 let out_name = if left_col_names.contains(name) {
3636 apply_merge_suffix(name, suffixes.right.as_deref())
3637 } else {
3638 name.clone()
3639 };
3640 specs.push(FusedInt64OutputColumn {
3641 name: out_name,
3642 side: FusedInt64Side::Right,
3643 values,
3644 });
3645 sources.push(source);
3646 }
3647 ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
3648
3649 let row_count = left_keys.len().saturating_add(right_keys.len());
3650 let max_dense_span = row_count.saturating_mul(4).max(1024);
3651 let left_witness = left_key
3652 .int64_dense_cycle_witness()
3653 .filter(|witness| witness.len == left_keys.len());
3654 let right_witness = right_key
3655 .int64_dense_cycle_witness()
3656 .filter(|witness| witness.len == right_keys.len());
3657 if let (Some(left_witness), Some(right_witness), Some((right_min, right_max))) = (
3658 left_witness,
3659 right_witness,
3660 right_witness.and_then(dense_cycle_domain),
3661 ) {
3662 let right_span = i128::from(right_max) - i128::from(right_min) + 1;
3663 if right_span <= max_dense_span as i128
3664 && let Some((output_len, right_validity)) =
3665 dense_cycle_probe_output_len_and_validity(left_witness, right_witness)
3666 {
3667 let index = Index::new_known_unique_int64_unit_range(0, output_len);
3668 let mut columns = std::collections::BTreeMap::new();
3669 let mut column_order = Vec::with_capacity(specs.len());
3670 for (spec, source) in specs.into_iter().zip(sources) {
3671 let column = match spec.side {
3672 FusedInt64Side::Left => Column::from_i64_dense_cycle_probe_repeat(
3673 source,
3674 left_witness,
3675 right_witness,
3676 output_len,
3677 ),
3678 FusedInt64Side::Right => {
3679 Column::from_i64_nullable_dense_cycle_probe_build_with_sparse_validity(
3680 source,
3681 left_witness,
3682 right_witness,
3683 right_validity.clone(),
3684 output_len,
3685 )
3686 }
3687 };
3688 debug_assert_eq!(column.len(), output_len);
3689 insert_merged_output_column(&mut columns, &mut column_order, spec.name, column)?;
3690 }
3691 return Ok(Some(MergedDataFrame {
3692 index,
3693 columns,
3694 column_order,
3695 }));
3696 }
3697 }
3698
3699 let mut min_key = right_keys[0];
3703 let mut max_key = right_keys[0];
3704 for &key in right_keys {
3705 min_key = min_key.min(key);
3706 max_key = max_key.max(key);
3707 }
3708 let span = (i128::from(max_key)) - (i128::from(min_key)) + 1;
3709 if span > max_dense_span as i128 {
3710 return Ok(None);
3711 }
3712 let span = usize::try_from(span).expect("span bounded by max_dense_span");
3713
3714 let mut offsets = vec![0usize; span + 1];
3715 for &key in right_keys {
3716 offsets[(key - min_key) as usize + 1] += 1;
3717 }
3718 for i in 0..span {
3719 offsets[i + 1] += offsets[i];
3720 }
3721 let mut positions = vec![0usize; right_keys.len()];
3722 let mut cursor = offsets[..span].to_vec();
3723 for (pos, &key) in right_keys.iter().enumerate() {
3724 let bucket = (key - min_key) as usize;
3725 positions[cursor[bucket]] = pos;
3726 cursor[bucket] += 1;
3727 }
3728
3729 const UNMATCHED: usize = usize::MAX;
3732 let mut plan = Vec::<(usize, usize, usize)>::with_capacity(left_keys.len());
3733 let mut output_len = 0usize;
3734 for (left_pos, &key) in left_keys.iter().enumerate() {
3735 let offset = i128::from(key) - i128::from(min_key);
3736 let run = if offset >= 0 && offset < span as i128 {
3737 let bucket = offset as usize;
3738 let start = offsets[bucket];
3739 let len = offsets[bucket + 1] - start;
3740 if len == 0 {
3741 (left_pos, UNMATCHED, 1)
3742 } else {
3743 (left_pos, start, len)
3744 }
3745 } else {
3746 (left_pos, UNMATCHED, 1)
3747 };
3748 let Some(new_len) = output_len.checked_add(run.2) else {
3749 return Ok(None);
3750 };
3751 output_len = new_len;
3752 plan.push(run);
3753 }
3754
3755 let right_segments: Arc<[(usize, usize)]> = plan
3764 .iter()
3765 .map(|&(_, start, run_len)| (start, run_len))
3766 .collect();
3767
3768 let use_repeat_runs = output_len >= plan.len().saturating_mul(2);
3772
3773 let full_specs: Vec<usize> = specs
3777 .iter()
3778 .enumerate()
3779 .filter(|(_, spec)| matches!(spec.side, FusedInt64Side::Left) && !use_repeat_runs)
3780 .map(|(idx, _)| idx)
3781 .collect();
3782
3783 let mut full_data: Vec<Vec<i64>> = Vec::new();
3784 let thread_count = join_parallel_thread_count();
3785 if !full_specs.is_empty() {
3786 let tapes: Vec<Option<Vec<i64>>> = full_specs
3788 .iter()
3789 .map(|&spec_idx| match specs[spec_idx].side {
3790 FusedInt64Side::Left => None,
3791 FusedInt64Side::Right => Some(
3792 positions
3793 .iter()
3794 .map(|&right_pos| specs[spec_idx].values[right_pos])
3795 .collect(),
3796 ),
3797 })
3798 .collect();
3799
3800 if output_len >= DENSE_I64_INNER_PARALLEL_MIN_VALUES && thread_count > 1 {
3801 let target = output_len.div_ceil(thread_count).max(1);
3803 let mut boundaries = vec![(0usize, 0usize)];
3804 let mut cumulative = 0usize;
3805 let mut next_target = target;
3806 for (plan_idx, &(_, _, run_len)) in plan.iter().enumerate() {
3807 cumulative += run_len;
3808 if cumulative >= next_target && plan_idx + 1 < plan.len() {
3809 boundaries.push((plan_idx + 1, cumulative));
3810 next_target = cumulative.saturating_add(target);
3811 }
3812 }
3813 boundaries.push((plan.len(), output_len));
3814 let chunk_count = boundaries.len() - 1;
3815
3816 let mut column_bufs: Vec<Vec<i64>> =
3817 full_specs.iter().map(|_| vec![0i64; output_len]).collect();
3818 let mut bundles: Vec<Vec<&mut [i64]>> = (0..chunk_count)
3819 .map(|_| Vec::with_capacity(full_specs.len()))
3820 .collect();
3821 for buf in &mut column_bufs {
3822 let mut rest: &mut [i64] = buf.as_mut_slice();
3823 let mut prev = 0usize;
3824 for (chunk_idx, window) in boundaries.windows(2).enumerate() {
3825 let (chunk_slice, tail) = rest.split_at_mut(window[1].1 - prev);
3826 prev = window[1].1;
3827 rest = tail;
3828 bundles[chunk_idx].push(chunk_slice);
3829 }
3830 }
3831
3832 let plan = &plan;
3833 let specs_ref = &specs;
3834 let full_specs_ref = &full_specs;
3835 std::thread::scope(|scope| {
3836 let mut handles = Vec::with_capacity(chunk_count);
3837 for (chunk_idx, mut bundle) in bundles.into_iter().enumerate() {
3838 let (plan_start, out_start) = boundaries[chunk_idx];
3839 let (plan_end, out_end) = boundaries[chunk_idx + 1];
3840 let tapes = &tapes;
3841 handles.push(scope.spawn(move || {
3842 let mut cursor = 0usize;
3843 for &(left_pos, start, run_len) in &plan[plan_start..plan_end] {
3844 for (slice, (&spec_idx, tape)) in bundle
3845 .iter_mut()
3846 .zip(full_specs_ref.iter().zip(tapes.iter()))
3847 {
3848 match specs_ref[spec_idx].side {
3849 FusedInt64Side::Left => {
3850 slice[cursor..cursor + run_len]
3851 .fill(specs_ref[spec_idx].values[left_pos]);
3852 }
3853 FusedInt64Side::Right => {
3854 if start != UNMATCHED {
3855 slice[cursor..cursor + run_len].copy_from_slice(
3856 &tape
3857 .as_ref()
3858 .expect("right spec must have a bucket tape")
3859 [start..start + run_len],
3860 );
3861 }
3862 }
3866 }
3867 }
3868 cursor += run_len;
3869 }
3870 debug_assert_eq!(cursor, out_end - out_start);
3871 }));
3872 }
3873 for handle in handles {
3874 handle
3875 .join()
3876 .expect("dense i64 left output worker must not panic");
3877 }
3878 });
3879 full_data = column_bufs;
3880 } else {
3881 full_data = full_specs.iter().map(|_| vec![0i64; output_len]).collect();
3882 let mut cursor = 0usize;
3883 for &(left_pos, start, run_len) in &plan {
3884 for (buf, (&spec_idx, tape)) in full_data
3885 .iter_mut()
3886 .zip(full_specs.iter().zip(tapes.iter()))
3887 {
3888 match specs[spec_idx].side {
3889 FusedInt64Side::Left => {
3890 buf[cursor..cursor + run_len].fill(specs[spec_idx].values[left_pos]);
3891 }
3892 FusedInt64Side::Right => {
3893 if start != UNMATCHED {
3894 buf[cursor..cursor + run_len].copy_from_slice(
3895 &tape.as_ref().expect("right spec must have a bucket tape")
3896 [start..start + run_len],
3897 );
3898 }
3899 }
3900 }
3901 }
3902 cursor += run_len;
3903 }
3904 debug_assert_eq!(cursor, output_len);
3905 }
3906 }
3907
3908 let index = Index::new_known_unique_int64_unit_range(0, output_len);
3910 let mut columns = std::collections::BTreeMap::new();
3911 let mut column_order = Vec::with_capacity(specs.len());
3912 let mut full_iter = full_data.into_iter();
3913 for spec in specs {
3914 let column = match spec.side {
3915 FusedInt64Side::Right => {
3916 let tape: Vec<i64> = positions
3920 .iter()
3921 .map(|&right_pos| spec.values[right_pos])
3922 .collect();
3923 Column::from_i64_nullable_repeated_slices_shared(
3924 tape,
3925 Arc::clone(&right_segments),
3926 output_len,
3927 )
3928 }
3929 FusedInt64Side::Left if use_repeat_runs => Column::from_i64_repeat_runs(
3930 plan.iter()
3931 .map(|&(left_pos, _, run_len)| (spec.values[left_pos], run_len))
3932 .collect(),
3933 ),
3934 FusedInt64Side::Left => {
3935 let data = full_iter
3936 .next()
3937 .expect("full lane buffer must exist for every non-run left spec");
3938 Column::from_i64_values(data)
3939 }
3940 };
3941 debug_assert_eq!(column.len(), output_len);
3942 insert_merged_output_column(&mut columns, &mut column_order, spec.name, column)?;
3943 }
3944
3945 Ok(Some(MergedDataFrame {
3946 index,
3947 columns,
3948 column_order,
3949 }))
3950}
3951
3952fn build_single_key_dense_i64_right_merge_output(
3963 left: &fp_frame::DataFrame,
3964 right: &fp_frame::DataFrame,
3965 left_on: &[&str],
3966 right_on: &[&str],
3967 left_key: &Column,
3968 right_key: &Column,
3969 suffixes: &ResolvedMergeSuffixes,
3970) -> Result<Option<MergedDataFrame>, JoinError> {
3971 debug_assert_eq!(left_on.len(), 1);
3972 debug_assert_eq!(right_on.len(), 1);
3973
3974 let Some(left_keys) = left_key.as_i64_slice() else {
3975 return Ok(None);
3976 };
3977 let Some(right_keys) = right_key.as_i64_slice() else {
3978 return Ok(None);
3979 };
3980 if left_keys.is_empty() || right_keys.is_empty() {
3981 return Ok(None);
3982 }
3983
3984 let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
3985 let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
3986 let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
3987 let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
3988 let shared_key_names = if left_on[0] == right_on[0] {
3989 [left_on[0]].into_iter().collect::<HashSet<&str>>()
3990 } else {
3991 HashSet::new()
3992 };
3993 let overlapping_names =
3994 collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
3995
3996 let mut specs = Vec::<FusedInt64OutputColumn<'_>>::new();
4000 let mut sources = Vec::<Arc<[i64]>>::new();
4001 for name in left.column_names() {
4002 let col = left
4003 .columns()
4004 .get(name)
4005 .expect("left column listed in column_names must exist");
4006 let Some(values) = col.as_i64_slice() else {
4007 return Ok(None);
4008 };
4009 if left_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
4010 let right_key_col = right
4011 .columns()
4012 .get(right_on[0])
4013 .expect("right key column must exist");
4014 let source = right_key_col
4015 .as_i64_arc()
4016 .unwrap_or_else(|| Arc::from(right_keys));
4017 specs.push(FusedInt64OutputColumn {
4018 name: name.clone(),
4019 side: FusedInt64Side::Right,
4020 values: right_keys,
4021 });
4022 sources.push(source);
4023 continue;
4024 }
4025 let source = col.as_i64_arc().unwrap_or_else(|| Arc::from(values));
4026 let out_name = if left_key_name_set.contains(name.as_str()) {
4027 name.clone()
4028 } else if right_col_names.contains(name) {
4029 apply_merge_suffix(name, suffixes.left.as_deref())
4030 } else {
4031 name.clone()
4032 };
4033 specs.push(FusedInt64OutputColumn {
4034 name: out_name,
4035 side: FusedInt64Side::Left,
4036 values,
4037 });
4038 sources.push(source);
4039 }
4040 for name in right.column_names() {
4041 let col = right
4042 .columns()
4043 .get(name)
4044 .expect("right column listed in column_names must exist");
4045 if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
4046 continue;
4047 }
4048 let Some(values) = col.as_i64_slice() else {
4049 return Ok(None);
4050 };
4051 let source = col.as_i64_arc().unwrap_or_else(|| Arc::from(values));
4052 let out_name = if left_col_names.contains(name) {
4053 apply_merge_suffix(name, suffixes.right.as_deref())
4054 } else {
4055 name.clone()
4056 };
4057 specs.push(FusedInt64OutputColumn {
4058 name: out_name,
4059 side: FusedInt64Side::Right,
4060 values,
4061 });
4062 sources.push(source);
4063 }
4064 ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
4065
4066 let row_count = left_keys.len().saturating_add(right_keys.len());
4067 let max_dense_span = row_count.saturating_mul(4).max(1024);
4068 let left_witness = left_key
4069 .int64_dense_cycle_witness()
4070 .filter(|witness| witness.len == left_keys.len());
4071 let right_witness = right_key
4072 .int64_dense_cycle_witness()
4073 .filter(|witness| witness.len == right_keys.len());
4074 if let (Some(left_witness), Some(right_witness), Some((left_min, left_max))) = (
4075 left_witness,
4076 right_witness,
4077 left_witness.and_then(dense_cycle_domain),
4078 ) {
4079 let left_span = i128::from(left_max) - i128::from(left_min) + 1;
4080 if left_span <= max_dense_span as i128
4081 && let Some((output_len, left_validity)) =
4082 dense_cycle_probe_output_len_and_validity(right_witness, left_witness)
4083 {
4084 let index = Index::new_known_unique_int64_unit_range(0, output_len);
4085 let mut columns = std::collections::BTreeMap::new();
4086 let mut column_order = Vec::with_capacity(specs.len());
4087 for (spec, source) in specs.into_iter().zip(sources) {
4088 let column = match spec.side {
4089 FusedInt64Side::Left => {
4090 Column::from_i64_nullable_dense_cycle_probe_build_with_sparse_validity(
4091 source,
4092 right_witness,
4093 left_witness,
4094 left_validity.clone(),
4095 output_len,
4096 )
4097 }
4098 FusedInt64Side::Right => Column::from_i64_dense_cycle_probe_repeat(
4099 source,
4100 right_witness,
4101 left_witness,
4102 output_len,
4103 ),
4104 };
4105 debug_assert_eq!(column.len(), output_len);
4106 insert_merged_output_column(&mut columns, &mut column_order, spec.name, column)?;
4107 }
4108 return Ok(Some(MergedDataFrame {
4109 index,
4110 columns,
4111 column_order,
4112 }));
4113 }
4114 }
4115
4116 let mut min_key = left_keys[0];
4119 let mut max_key = left_keys[0];
4120 for &key in left_keys {
4121 min_key = min_key.min(key);
4122 max_key = max_key.max(key);
4123 }
4124 let span = (i128::from(max_key)) - (i128::from(min_key)) + 1;
4125 if span > max_dense_span as i128 {
4126 return Ok(None);
4127 }
4128 let span = usize::try_from(span).expect("span bounded by max_dense_span");
4129
4130 let mut offsets = vec![0usize; span + 1];
4131 for &key in left_keys {
4132 offsets[(key - min_key) as usize + 1] += 1;
4133 }
4134 for i in 0..span {
4135 offsets[i + 1] += offsets[i];
4136 }
4137 let mut positions = vec![0usize; left_keys.len()];
4138 let mut cursor = offsets[..span].to_vec();
4139 for (pos, &key) in left_keys.iter().enumerate() {
4140 let bucket = (key - min_key) as usize;
4141 positions[cursor[bucket]] = pos;
4142 cursor[bucket] += 1;
4143 }
4144
4145 const UNMATCHED: usize = usize::MAX;
4148 let mut plan = Vec::<(usize, usize, usize)>::with_capacity(right_keys.len());
4149 let mut output_len = 0usize;
4150 for (right_pos, &key) in right_keys.iter().enumerate() {
4151 let offset = i128::from(key) - i128::from(min_key);
4152 let run = if offset >= 0 && offset < span as i128 {
4153 let bucket = offset as usize;
4154 let start = offsets[bucket];
4155 let len = offsets[bucket + 1] - start;
4156 if len == 0 {
4157 (right_pos, UNMATCHED, 1)
4158 } else {
4159 (right_pos, start, len)
4160 }
4161 } else {
4162 (right_pos, UNMATCHED, 1)
4163 };
4164 let Some(new_len) = output_len.checked_add(run.2) else {
4165 return Ok(None);
4166 };
4167 output_len = new_len;
4168 plan.push(run);
4169 }
4170
4171 let left_segments: Arc<[(usize, usize)]> = plan
4178 .iter()
4179 .map(|&(_, start, run_len)| (start, run_len))
4180 .collect();
4181
4182 let use_repeat_runs = output_len >= plan.len().saturating_mul(2);
4184
4185 let full_specs: Vec<usize> = specs
4188 .iter()
4189 .enumerate()
4190 .filter(|(_, spec)| matches!(spec.side, FusedInt64Side::Right) && !use_repeat_runs)
4191 .map(|(idx, _)| idx)
4192 .collect();
4193
4194 let mut full_data: Vec<Vec<i64>> = Vec::new();
4195 let thread_count = join_parallel_thread_count();
4196 if !full_specs.is_empty() {
4197 let tapes: Vec<Option<Vec<i64>>> = full_specs
4199 .iter()
4200 .map(|&spec_idx| match specs[spec_idx].side {
4201 FusedInt64Side::Right => None,
4202 FusedInt64Side::Left => Some(
4203 positions
4204 .iter()
4205 .map(|&left_pos| specs[spec_idx].values[left_pos])
4206 .collect(),
4207 ),
4208 })
4209 .collect();
4210
4211 if output_len >= DENSE_I64_INNER_PARALLEL_MIN_VALUES && thread_count > 1 {
4212 let target = output_len.div_ceil(thread_count).max(1);
4213 let mut boundaries = vec![(0usize, 0usize)];
4214 let mut cumulative = 0usize;
4215 let mut next_target = target;
4216 for (plan_idx, &(_, _, run_len)) in plan.iter().enumerate() {
4217 cumulative += run_len;
4218 if cumulative >= next_target && plan_idx + 1 < plan.len() {
4219 boundaries.push((plan_idx + 1, cumulative));
4220 next_target = cumulative.saturating_add(target);
4221 }
4222 }
4223 boundaries.push((plan.len(), output_len));
4224 let chunk_count = boundaries.len() - 1;
4225
4226 let mut column_bufs: Vec<Vec<i64>> =
4227 full_specs.iter().map(|_| vec![0i64; output_len]).collect();
4228 let mut bundles: Vec<Vec<&mut [i64]>> = (0..chunk_count)
4229 .map(|_| Vec::with_capacity(full_specs.len()))
4230 .collect();
4231 for buf in &mut column_bufs {
4232 let mut rest: &mut [i64] = buf.as_mut_slice();
4233 let mut prev = 0usize;
4234 for (chunk_idx, window) in boundaries.windows(2).enumerate() {
4235 let (chunk_slice, tail) = rest.split_at_mut(window[1].1 - prev);
4236 prev = window[1].1;
4237 rest = tail;
4238 bundles[chunk_idx].push(chunk_slice);
4239 }
4240 }
4241
4242 let plan = &plan;
4243 let specs_ref = &specs;
4244 let full_specs_ref = &full_specs;
4245 std::thread::scope(|scope| {
4246 let mut handles = Vec::with_capacity(chunk_count);
4247 for (chunk_idx, mut bundle) in bundles.into_iter().enumerate() {
4248 let (plan_start, out_start) = boundaries[chunk_idx];
4249 let (plan_end, out_end) = boundaries[chunk_idx + 1];
4250 let tapes = &tapes;
4251 handles.push(scope.spawn(move || {
4252 let mut cursor = 0usize;
4253 for &(right_pos, start, run_len) in &plan[plan_start..plan_end] {
4254 for (slice, (&spec_idx, tape)) in bundle
4255 .iter_mut()
4256 .zip(full_specs_ref.iter().zip(tapes.iter()))
4257 {
4258 match specs_ref[spec_idx].side {
4259 FusedInt64Side::Right => {
4260 slice[cursor..cursor + run_len]
4261 .fill(specs_ref[spec_idx].values[right_pos]);
4262 }
4263 FusedInt64Side::Left => {
4264 if start != UNMATCHED {
4265 slice[cursor..cursor + run_len].copy_from_slice(
4266 &tape
4267 .as_ref()
4268 .expect("left spec must have a bucket tape")
4269 [start..start + run_len],
4270 );
4271 }
4272 }
4273 }
4274 }
4275 cursor += run_len;
4276 }
4277 debug_assert_eq!(cursor, out_end - out_start);
4278 }));
4279 }
4280 for handle in handles {
4281 handle
4282 .join()
4283 .expect("dense i64 right output worker must not panic");
4284 }
4285 });
4286 full_data = column_bufs;
4287 } else {
4288 full_data = full_specs.iter().map(|_| vec![0i64; output_len]).collect();
4289 let mut cursor = 0usize;
4290 for &(right_pos, start, run_len) in &plan {
4291 for (buf, (&spec_idx, tape)) in full_data
4292 .iter_mut()
4293 .zip(full_specs.iter().zip(tapes.iter()))
4294 {
4295 match specs[spec_idx].side {
4296 FusedInt64Side::Right => {
4297 buf[cursor..cursor + run_len].fill(specs[spec_idx].values[right_pos]);
4298 }
4299 FusedInt64Side::Left => {
4300 if start != UNMATCHED {
4301 buf[cursor..cursor + run_len].copy_from_slice(
4302 &tape.as_ref().expect("left spec must have a bucket tape")
4303 [start..start + run_len],
4304 );
4305 }
4306 }
4307 }
4308 }
4309 cursor += run_len;
4310 }
4311 debug_assert_eq!(cursor, output_len);
4312 }
4313 }
4314
4315 let index = Index::new_known_unique_int64_unit_range(0, output_len);
4317 let mut columns = std::collections::BTreeMap::new();
4318 let mut column_order = Vec::with_capacity(specs.len());
4319 let mut full_iter = full_data.into_iter();
4320 for spec in specs {
4321 let column = match spec.side {
4322 FusedInt64Side::Left => {
4323 let tape: Vec<i64> = positions
4328 .iter()
4329 .map(|&left_pos| spec.values[left_pos])
4330 .collect();
4331 Column::from_i64_nullable_repeated_slices_shared(
4332 tape,
4333 Arc::clone(&left_segments),
4334 output_len,
4335 )
4336 }
4337 FusedInt64Side::Right if use_repeat_runs => Column::from_i64_repeat_runs(
4338 plan.iter()
4339 .map(|&(right_pos, _, run_len)| (spec.values[right_pos], run_len))
4340 .collect(),
4341 ),
4342 FusedInt64Side::Right => {
4343 let data = full_iter
4344 .next()
4345 .expect("full lane buffer must exist for every non-run right spec");
4346 Column::from_i64_values(data)
4347 }
4348 };
4349 debug_assert_eq!(column.len(), output_len);
4350 insert_merged_output_column(&mut columns, &mut column_order, spec.name, column)?;
4351 }
4352
4353 Ok(Some(MergedDataFrame {
4354 index,
4355 columns,
4356 column_order,
4357 }))
4358}
4359
4360fn dense_cycle_domain(witness: Int64DenseCycleWitness) -> Option<(i64, i64)> {
4361 let last_offset = i64::try_from(witness.period.checked_sub(1)?).ok()?;
4362 Some((witness.start, witness.start.checked_add(last_offset)?))
4363}
4364
4365fn dense_cycle_probe_output_len_and_validity(
4366 probe_witness: Int64DenseCycleWitness,
4367 build_witness: Int64DenseCycleWitness,
4368) -> Option<(usize, ValidityMask)> {
4369 let mut output_len = 0usize;
4370 let mut invalid_ranges = Vec::<(usize, usize)>::new();
4371 for probe_pos in 0..probe_witness.len {
4372 let offset = i64::try_from(probe_pos % probe_witness.period).ok()?;
4373 let key = probe_witness.start.checked_add(offset)?;
4374 let run_len = build_witness
4375 .offset_count_for_key(key)
4376 .map_or(1, |(_, count)| count);
4377 if build_witness.offset_count_for_key(key).is_none() {
4378 push_dense_outer_invalid_range(&mut invalid_ranges, output_len, 1);
4379 }
4380 output_len = output_len.checked_add(run_len)?;
4381 }
4382 Some((
4383 output_len,
4384 ValidityMask::from_invalid_ranges(Arc::from(invalid_ranges), output_len),
4385 ))
4386}
4387
4388struct DenseOuterRunTape {
4389 run_lens: Option<Arc<[usize]>>,
4390 left_run_valid: Option<Arc<[bool]>>,
4391 left_run_positions: Option<Arc<[usize]>>,
4392 right_positions_csr: Option<Arc<[usize]>>,
4393 right_segments: Option<Arc<[(usize, usize)]>>,
4394 key_runs: Vec<(i64, usize)>,
4395 left_sparse_validity: ValidityMask,
4396 right_sparse_validity: ValidityMask,
4397 output_len: usize,
4398 has_left_missing: bool,
4399 has_right_missing: bool,
4400}
4401
4402fn push_dense_outer_invalid_range(ranges: &mut Vec<(usize, usize)>, start: usize, len: usize) {
4403 if len == 0 {
4404 return;
4405 }
4406 if let Some((last_start, last_len)) = ranges.last_mut()
4407 && last_start.checked_add(*last_len) == Some(start)
4408 {
4409 *last_len += len;
4410 return;
4411 }
4412 ranges.push((start, len));
4413}
4414
4415fn append_dense_cycle_positions(
4416 positions: &mut Vec<usize>,
4417 witness: Int64DenseCycleWitness,
4418 key: i64,
4419) -> Option<usize> {
4420 let (mut pos, count) = witness.offset_count_for_key(key)?;
4421 for _ in 0..count {
4422 positions.push(pos);
4423 pos = pos.checked_add(witness.period)?;
4424 }
4425 Some(count)
4426}
4427
4428fn build_dense_cycle_outer_run_tape(
4429 left_witness: Int64DenseCycleWitness,
4430 right_witness: Int64DenseCycleWitness,
4431 min_key: i64,
4432 span: usize,
4433) -> Option<DenseOuterRunTape> {
4434 let mut run_count = 0usize;
4435 let mut active_key_count = 0usize;
4436 let mut output_len = 0usize;
4437 let mut has_left_missing = false;
4438 let mut has_right_missing = false;
4439 for bucket in 0..span {
4440 let key = min_key.checked_add(i64::try_from(bucket).ok()?)?;
4441 let ll = left_witness
4442 .offset_count_for_key(key)
4443 .map_or(0, |(_, count)| count);
4444 let rl = right_witness
4445 .offset_count_for_key(key)
4446 .map_or(0, |(_, count)| count);
4447 let rows = match (ll > 0, rl > 0) {
4448 (true, true) => {
4449 run_count = run_count.checked_add(ll)?;
4450 ll.checked_mul(rl)?
4451 }
4452 (true, false) => {
4453 has_right_missing = true;
4454 run_count = run_count.checked_add(ll)?;
4455 ll
4456 }
4457 (false, true) => {
4458 has_left_missing = true;
4459 run_count = run_count.checked_add(1)?;
4460 rl
4461 }
4462 (false, false) => continue,
4463 };
4464 active_key_count = active_key_count.checked_add(1)?;
4465 output_len = output_len.checked_add(rows)?;
4466 }
4467
4468 let build_left_tape = !has_left_missing;
4469 let mut run_lens = Vec::with_capacity(if build_left_tape { run_count } else { 0 });
4470 let mut left_run_valid = Vec::with_capacity(if build_left_tape { run_count } else { 0 });
4471 let mut left_run_positions = Vec::with_capacity(if build_left_tape { run_count } else { 0 });
4472 let mut right_positions_csr = Vec::with_capacity(right_witness.len);
4473 let mut right_segments = Vec::with_capacity(run_count);
4474 let mut key_runs = Vec::with_capacity(active_key_count);
4475 let mut left_invalid_ranges = Vec::<(usize, usize)>::new();
4476 let mut right_invalid_ranges = Vec::<(usize, usize)>::new();
4477 let mut out_pos = 0usize;
4478 let build_right_tape = !has_right_missing;
4479 for bucket in 0..span {
4480 let key = min_key.checked_add(i64::try_from(bucket).ok()?)?;
4481 let left_span = left_witness.offset_count_for_key(key);
4482 let right_span = right_witness.offset_count_for_key(key);
4483 let ll = left_span.map_or(0, |(_, count)| count);
4484 let rl = right_span.map_or(0, |(_, count)| count);
4485 if ll == 0 && rl == 0 {
4486 continue;
4487 }
4488
4489 let right_start = if rl > 0 {
4490 if build_right_tape {
4491 let start = right_positions_csr.len();
4492 let appended =
4493 append_dense_cycle_positions(&mut right_positions_csr, right_witness, key)?;
4494 debug_assert_eq!(appended, rl);
4495 start
4496 } else {
4497 0
4498 }
4499 } else {
4500 usize::MAX
4501 };
4502
4503 let rows = match (left_span, right_span) {
4504 (Some((mut left_pos, left_count)), Some((_, right_count))) => {
4505 let rows = left_count.checked_mul(right_count)?;
4506 if build_left_tape {
4507 run_lens.extend(std::iter::repeat_n(right_count, left_count));
4508 left_run_valid.extend(std::iter::repeat_n(true, left_count));
4509 }
4510 if build_right_tape {
4511 right_segments
4512 .extend(std::iter::repeat_n((right_start, right_count), left_count));
4513 }
4514 if build_left_tape {
4515 for _ in 0..left_count {
4516 left_run_positions.push(left_pos);
4517 left_pos = left_pos.checked_add(left_witness.period)?;
4518 }
4519 }
4520 rows
4521 }
4522 (Some((mut left_pos, left_count)), None) => {
4523 push_dense_outer_invalid_range(&mut right_invalid_ranges, out_pos, left_count);
4524 if build_left_tape {
4525 run_lens.extend(std::iter::repeat_n(1, left_count));
4526 left_run_valid.extend(std::iter::repeat_n(true, left_count));
4527 }
4528 if build_right_tape {
4529 right_segments.extend(std::iter::repeat_n((usize::MAX, 1), left_count));
4530 }
4531 if build_left_tape {
4532 for _ in 0..left_count {
4533 left_run_positions.push(left_pos);
4534 left_pos = left_pos.checked_add(left_witness.period)?;
4535 }
4536 }
4537 left_count
4538 }
4539 (None, Some((_, right_count))) => {
4540 push_dense_outer_invalid_range(&mut left_invalid_ranges, out_pos, right_count);
4541 if build_left_tape {
4542 run_lens.push(right_count);
4543 left_run_valid.push(false);
4544 left_run_positions.push(0);
4545 }
4546 if build_right_tape {
4547 right_segments.push((right_start, right_count));
4548 }
4549 right_count
4550 }
4551 (None, None) => unreachable!("empty buckets are skipped above"),
4552 };
4553 key_runs.push((key, rows));
4554 out_pos = out_pos.checked_add(rows)?;
4555 }
4556 if out_pos != output_len
4557 || (build_left_tape
4558 && (run_lens.len() != run_count
4559 || left_run_valid.len() != run_count
4560 || left_run_positions.len() != run_count))
4561 || (!build_left_tape
4562 && (!run_lens.is_empty()
4563 || !left_run_valid.is_empty()
4564 || !left_run_positions.is_empty()))
4565 || (build_right_tape
4566 && (right_segments.len() != run_count
4567 || right_positions_csr.len() != right_witness.len))
4568 || (!build_right_tape && (!right_segments.is_empty() || !right_positions_csr.is_empty()))
4569 {
4570 return None;
4571 }
4572
4573 Some(DenseOuterRunTape {
4574 run_lens: build_left_tape.then(|| Arc::from(run_lens)),
4575 left_run_valid: build_left_tape.then(|| Arc::from(left_run_valid)),
4576 left_run_positions: build_left_tape.then(|| Arc::from(left_run_positions)),
4577 right_positions_csr: build_right_tape.then(|| Arc::from(right_positions_csr)),
4578 right_segments: build_right_tape.then(|| Arc::from(right_segments)),
4579 key_runs,
4580 left_sparse_validity: ValidityMask::from_invalid_ranges(
4581 Arc::from(left_invalid_ranges),
4582 output_len,
4583 ),
4584 right_sparse_validity: ValidityMask::from_invalid_ranges(
4585 Arc::from(right_invalid_ranges),
4586 output_len,
4587 ),
4588 output_len,
4589 has_left_missing,
4590 has_right_missing,
4591 })
4592}
4593
4594fn build_single_key_dense_i64_outer_merge_output(
4623 left: &fp_frame::DataFrame,
4624 right: &fp_frame::DataFrame,
4625 left_on: &[&str],
4626 right_on: &[&str],
4627 left_key: &Column,
4628 right_key: &Column,
4629 suffixes: &ResolvedMergeSuffixes,
4630) -> Result<Option<MergedDataFrame>, JoinError> {
4631 debug_assert_eq!(left_on.len(), 1);
4632 debug_assert_eq!(right_on.len(), 1);
4633
4634 if left_on[0] != right_on[0] {
4637 return Ok(None);
4638 }
4639 let Some(left_keys) = left_key.as_i64_slice() else {
4640 return Ok(None);
4641 };
4642 let Some(right_keys) = right_key.as_i64_slice() else {
4643 return Ok(None);
4644 };
4645 if left_keys.is_empty() || right_keys.is_empty() {
4646 return Ok(None);
4647 }
4648
4649 let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
4650 let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
4651 let key_name = left_on[0];
4652 let shared_key_names = [key_name].into_iter().collect::<HashSet<&str>>();
4653 let overlapping_names =
4654 collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
4655
4656 enum OuterLaneKind {
4659 SharedKey,
4660 Lane(FusedInt64Side),
4661 }
4662 let mut spec_names = Vec::<String>::new();
4663 let mut spec_kinds = Vec::<OuterLaneKind>::new();
4664 let mut spec_values = Vec::<&[i64]>::new();
4665 let mut spec_sources = Vec::<Arc<[i64]>>::new();
4666 for name in left.column_names() {
4667 let col = left
4668 .columns()
4669 .get(name)
4670 .expect("left column listed in column_names must exist");
4671 let Some(values) = col.as_i64_slice() else {
4672 return Ok(None);
4673 };
4674 let source = col.as_i64_arc().unwrap_or_else(|| Arc::from(values));
4675 if name.as_str() == key_name {
4676 spec_names.push(name.clone());
4677 spec_kinds.push(OuterLaneKind::SharedKey);
4678 spec_values.push(values);
4679 spec_sources.push(Arc::clone(&source));
4680 continue;
4681 }
4682 let out_name = if right_col_names.contains(name) {
4683 apply_merge_suffix(name, suffixes.left.as_deref())
4684 } else {
4685 name.clone()
4686 };
4687 spec_names.push(out_name);
4688 spec_kinds.push(OuterLaneKind::Lane(FusedInt64Side::Left));
4689 spec_values.push(values);
4690 spec_sources.push(source);
4691 }
4692 for name in right.column_names() {
4693 let col = right
4694 .columns()
4695 .get(name)
4696 .expect("right column listed in column_names must exist");
4697 let Some(values) = col.as_i64_slice() else {
4698 return Ok(None);
4699 };
4700 let source = col.as_i64_arc().unwrap_or_else(|| Arc::from(values));
4701 if name.as_str() == key_name {
4702 continue;
4703 }
4704 let out_name = if left_col_names.contains(name) {
4705 apply_merge_suffix(name, suffixes.right.as_deref())
4706 } else {
4707 name.clone()
4708 };
4709 spec_names.push(out_name);
4710 spec_kinds.push(OuterLaneKind::Lane(FusedInt64Side::Right));
4711 spec_values.push(values);
4712 spec_sources.push(source);
4713 }
4714 ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
4715
4716 let left_witness = left_key
4719 .int64_dense_cycle_witness()
4720 .filter(|witness| witness.len == left_keys.len());
4721 let right_witness = right_key
4722 .int64_dense_cycle_witness()
4723 .filter(|witness| witness.len == right_keys.len());
4724 let (min_key, max_key) = match (
4725 left_witness.and_then(dense_cycle_domain),
4726 right_witness.and_then(dense_cycle_domain),
4727 ) {
4728 (Some((left_min, left_max)), Some((right_min, right_max))) => {
4729 (left_min.min(right_min), left_max.max(right_max))
4730 }
4731 _ => {
4732 let mut min_key = left_keys[0];
4733 let mut max_key = left_keys[0];
4734 for &key in left_keys.iter().chain(right_keys.iter()) {
4735 min_key = min_key.min(key);
4736 max_key = max_key.max(key);
4737 }
4738 (min_key, max_key)
4739 }
4740 };
4741 let span = (i128::from(max_key)) - (i128::from(min_key)) + 1;
4742 let row_count = left_keys.len().saturating_add(right_keys.len());
4743 let max_dense_span = row_count.saturating_mul(4).max(1024);
4744 if span > max_dense_span as i128 {
4745 return Ok(None);
4746 }
4747 let span = usize::try_from(span).expect("span bounded by max_dense_span");
4748
4749 const NONE_POS: usize = usize::MAX;
4750 let Some(DenseOuterRunTape {
4751 run_lens,
4752 left_run_valid,
4753 left_run_positions,
4754 right_positions_csr,
4755 right_segments,
4756 key_runs,
4757 left_sparse_validity,
4758 right_sparse_validity,
4759 output_len,
4760 has_left_missing,
4761 has_right_missing,
4762 }) = (match (left_witness, right_witness) {
4763 (Some(left_witness), Some(right_witness)) => {
4764 build_dense_cycle_outer_run_tape(left_witness, right_witness, min_key, span)
4765 }
4766 _ => None,
4767 })
4768 .or_else(|| {
4769 let build_dense_cycle_csr =
4771 |witness: Int64DenseCycleWitness| -> Option<(Vec<usize>, Vec<usize>)> {
4772 let mut offsets = Vec::with_capacity(span + 1);
4773 offsets.push(0);
4774 let mut total = 0usize;
4775 for bucket in 0..span {
4776 let key = min_key.checked_add(i64::try_from(bucket).ok()?)?;
4777 let count = witness
4778 .offset_count_for_key(key)
4779 .map_or(0, |(_, count)| count);
4780 total = total.checked_add(count)?;
4781 offsets.push(total);
4782 }
4783 if total != witness.len {
4784 return None;
4785 }
4786 let mut positions = Vec::with_capacity(witness.len);
4787 for bucket in 0..span {
4788 let key = min_key.checked_add(i64::try_from(bucket).ok()?)?;
4789 let appended =
4790 append_dense_cycle_positions(&mut positions, witness, key).unwrap_or(0);
4791 debug_assert_eq!(
4792 appended,
4793 witness
4794 .offset_count_for_key(key)
4795 .map_or(0, |(_, count)| count)
4796 );
4797 }
4798 (positions.len() == witness.len).then_some((offsets, positions))
4799 };
4800 let build_csr = |keys: &[i64], witness: Option<Int64DenseCycleWitness>| {
4801 if let Some(csr) = witness
4802 .filter(|witness| witness.len == keys.len())
4803 .and_then(&build_dense_cycle_csr)
4804 {
4805 return csr;
4806 }
4807 let mut offsets = vec![0usize; span + 1];
4808 for &key in keys {
4809 offsets[(key - min_key) as usize + 1] += 1;
4810 }
4811 for i in 0..span {
4812 offsets[i + 1] += offsets[i];
4813 }
4814 let mut positions = vec![0usize; keys.len()];
4815 let mut cursor = offsets[..span].to_vec();
4816 for (pos, &key) in keys.iter().enumerate() {
4817 let bucket = (key - min_key) as usize;
4818 positions[cursor[bucket]] = pos;
4819 cursor[bucket] += 1;
4820 }
4821 (offsets, positions)
4822 };
4823 let (left_offsets, left_positions_csr) = build_csr(left_keys, left_witness);
4824 let (right_offsets, right_positions_csr) = build_csr(right_keys, right_witness);
4825
4826 let mut plan = Vec::<(usize, usize, usize)>::new();
4828 let mut key_runs = Vec::<(i64, usize)>::new();
4829 let mut left_invalid_ranges = Vec::<(usize, usize)>::new();
4830 let mut right_invalid_ranges = Vec::<(usize, usize)>::new();
4831 let mut output_len = 0usize;
4832 let mut has_left_missing = false; let mut has_right_missing = false; for bucket in 0..span {
4835 let ll = left_offsets[bucket + 1] - left_offsets[bucket];
4836 let rl = right_offsets[bucket + 1] - right_offsets[bucket];
4837 let bucket_rows = match (ll > 0, rl > 0) {
4838 (true, true) => {
4839 let rows = ll.checked_mul(rl)?;
4840 let rs = right_offsets[bucket];
4841 for &lp in &left_positions_csr[left_offsets[bucket]..left_offsets[bucket + 1]] {
4842 plan.push((lp, rs, rl));
4843 }
4844 rows
4845 }
4846 (true, false) => {
4847 has_right_missing = true;
4848 push_dense_outer_invalid_range(&mut right_invalid_ranges, output_len, ll);
4849 for &lp in &left_positions_csr[left_offsets[bucket]..left_offsets[bucket + 1]] {
4850 plan.push((lp, NONE_POS, 1));
4851 }
4852 ll
4853 }
4854 (false, true) => {
4855 has_left_missing = true;
4856 push_dense_outer_invalid_range(&mut left_invalid_ranges, output_len, rl);
4857 plan.push((NONE_POS, right_offsets[bucket], rl));
4858 rl
4859 }
4860 (false, false) => continue,
4861 };
4862 output_len = output_len.checked_add(bucket_rows)?;
4863 key_runs.push((min_key + bucket as i64, bucket_rows));
4864 }
4865
4866 let run_lens: Arc<[usize]> = plan.iter().map(|&(_, _, run_len)| run_len).collect();
4871 let left_run_valid: Arc<[bool]> = plan.iter().map(|&(lp, _, _)| lp < NONE_POS).collect();
4872 let left_run_positions: Arc<[usize]> = plan
4873 .iter()
4874 .map(|&(lp, _, _)| if lp == NONE_POS { 0 } else { lp })
4875 .collect();
4876 let right_segments: Arc<[(usize, usize)]> =
4877 plan.iter().map(|&(_, rs, run_len)| (rs, run_len)).collect();
4878 Some(DenseOuterRunTape {
4879 run_lens: Some(run_lens),
4880 left_run_valid: Some(left_run_valid),
4881 left_run_positions: Some(left_run_positions),
4882 right_positions_csr: Some(Arc::from(right_positions_csr)),
4883 right_segments: Some(right_segments),
4884 key_runs,
4885 left_sparse_validity: ValidityMask::from_invalid_ranges(
4886 Arc::from(left_invalid_ranges),
4887 output_len,
4888 ),
4889 right_sparse_validity: ValidityMask::from_invalid_ranges(
4890 Arc::from(right_invalid_ranges),
4891 output_len,
4892 ),
4893 output_len,
4894 has_left_missing,
4895 has_right_missing,
4896 })
4897 })
4898 else {
4899 return Ok(None);
4900 };
4901
4902 let promoted = |side: FusedInt64Side| match side {
4905 FusedInt64Side::Left => has_left_missing,
4906 FusedInt64Side::Right => has_right_missing,
4907 };
4908
4909 let left_run_values_i64 = |idx: usize| -> Option<Vec<i64>> {
4911 Some(
4912 left_run_positions
4913 .as_ref()?
4914 .iter()
4915 .zip(left_run_valid.as_ref()?.iter())
4916 .map(|(&lp, &valid)| if valid { spec_values[idx][lp] } else { 0 })
4917 .collect(),
4918 )
4919 };
4920 let index = Index::new_known_unique_int64_unit_range(0, output_len);
4922 let mut columns = std::collections::BTreeMap::new();
4923 let mut column_order = Vec::with_capacity(spec_names.len());
4924 for (idx, (name, kind)) in spec_names.into_iter().zip(spec_kinds.iter()).enumerate() {
4925 let column = match kind {
4926 OuterLaneKind::SharedKey => {
4927 if output_len >= key_runs.len().saturating_mul(2) {
4930 Column::from_i64_repeat_runs(key_runs.clone())
4931 } else {
4932 let mut data = Vec::with_capacity(output_len);
4933 for &(key, run_len) in &key_runs {
4934 data.resize(data.len() + run_len, key);
4935 }
4936 Column::from_i64_values(data)
4937 }
4938 }
4939 OuterLaneKind::Lane(side) => match (side, promoted(*side)) {
4940 (FusedInt64Side::Left, false) => {
4941 let Some(run_lens) = run_lens.as_ref() else {
4942 return Ok(None);
4943 };
4944 let Some(run_values) = left_run_values_i64(idx) else {
4945 return Ok(None);
4946 };
4947 Column::from_i64_repeat_values_run_lengths(run_values, Arc::clone(run_lens))
4948 }
4949 (FusedInt64Side::Left, true) => {
4950 if left_run_positions.is_none()
4951 && let (Some(left_witness), Some(right_witness)) =
4952 (left_witness, right_witness)
4953 {
4954 Column::from_i64_nullable_dense_cycle_left_as_f64_with_sparse_validity(
4955 Arc::clone(&spec_sources[idx]),
4956 left_witness,
4957 right_witness,
4958 min_key,
4959 span,
4960 left_sparse_validity.clone(),
4961 output_len,
4962 )
4963 } else {
4964 let Some(run_lens) = run_lens.as_ref() else {
4965 return Ok(None);
4966 };
4967 let Some(left_run_positions) = left_run_positions.as_ref() else {
4968 return Ok(None);
4969 };
4970 let Some(left_run_valid) = left_run_valid.as_ref() else {
4971 return Ok(None);
4972 };
4973 Column::from_i64_nullable_repeat_positions_as_f64_with_sparse_validity(
4974 Arc::clone(&spec_sources[idx]),
4975 Arc::clone(left_run_positions),
4976 Arc::clone(left_run_valid),
4977 Arc::clone(run_lens),
4978 left_sparse_validity.clone(),
4979 output_len,
4980 )
4981 }
4982 }
4983 (FusedInt64Side::Right, false) => {
4984 let Some(right_positions_csr) = right_positions_csr.as_ref() else {
4985 return Ok(None);
4986 };
4987 let Some(right_segments) = right_segments.as_ref() else {
4988 return Ok(None);
4989 };
4990 let tape_i64 = right_positions_csr
4991 .iter()
4992 .map(|&pos| spec_values[idx][pos])
4993 .collect();
4994 Column::from_i64_repeated_slices_shared(
4995 tape_i64,
4996 Arc::clone(right_segments),
4997 output_len,
4998 )
4999 }
5000 (FusedInt64Side::Right, true) => {
5001 if right_positions_csr.is_none()
5002 && let (Some(left_witness), Some(right_witness)) =
5003 (left_witness, right_witness)
5004 {
5005 Column::from_i64_nullable_dense_cycle_right_as_f64_with_sparse_validity(
5006 Arc::clone(&spec_sources[idx]),
5007 left_witness,
5008 right_witness,
5009 min_key,
5010 span,
5011 right_sparse_validity.clone(),
5012 output_len,
5013 )
5014 } else {
5015 let Some(right_positions_csr) = right_positions_csr.as_ref() else {
5016 return Ok(None);
5017 };
5018 let Some(right_segments) = right_segments.as_ref() else {
5019 return Ok(None);
5020 };
5021 Column::from_i64_nullable_repeated_positions_as_f64_with_sparse_validity(
5022 Arc::clone(&spec_sources[idx]),
5023 Arc::clone(right_positions_csr),
5024 Arc::clone(right_segments),
5025 right_sparse_validity.clone(),
5026 output_len,
5027 )
5028 }
5029 }
5030 },
5031 };
5032 debug_assert_eq!(column.len(), output_len);
5033 insert_merged_output_column(&mut columns, &mut column_order, name, column)?;
5034 }
5035
5036 Ok(Some(MergedDataFrame {
5037 index,
5038 columns,
5039 column_order,
5040 }))
5041}
5042
5043fn build_single_key_dense_i64_right_all_matched_merge_output(
5044 left: &fp_frame::DataFrame,
5045 right: &fp_frame::DataFrame,
5046 left_on: &[&str],
5047 right_on: &[&str],
5048 left_key: &Column,
5049 right_key: &Column,
5050 suffixes: &ResolvedMergeSuffixes,
5051) -> Result<Option<MergedDataFrame>, JoinError> {
5052 debug_assert_eq!(left_on.len(), 1);
5053 debug_assert_eq!(right_on.len(), 1);
5054
5055 let Some(left_keys) = left_key.as_i64_slice() else {
5056 return Ok(None);
5057 };
5058 let Some(right_keys) = right_key.as_i64_slice() else {
5059 return Ok(None);
5060 };
5061
5062 let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
5063 let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
5064 let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
5065 let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
5066 let shared_key_names = if left_on[0] == right_on[0] {
5067 [left_on[0]].into_iter().collect::<HashSet<&str>>()
5068 } else {
5069 HashSet::new()
5070 };
5071 let overlapping_names =
5072 collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
5073
5074 let mut specs = Vec::<FusedInt64OutputColumn<'_>>::new();
5075 for name in left.column_names() {
5076 let col = left
5077 .columns()
5078 .get(name)
5079 .expect("left column listed in column_names must exist");
5080 let (values, side) = if left_key_name_set.contains(name.as_str())
5081 && shared_key_names.contains(name.as_str())
5082 {
5083 let right_key_col = right
5084 .columns()
5085 .get(right_on[0])
5086 .expect("right key column must exist");
5087 let Some(values) = right_key_col.as_i64_slice() else {
5088 return Ok(None);
5089 };
5090 (values, FusedInt64Side::Right)
5091 } else {
5092 let Some(values) = col.as_i64_slice() else {
5093 return Ok(None);
5094 };
5095 (values, FusedInt64Side::Left)
5096 };
5097 let out_name = if left_key_name_set.contains(name.as_str()) {
5098 name.clone()
5099 } else if right_col_names.contains(name) {
5100 apply_merge_suffix(name, suffixes.left.as_deref())
5101 } else {
5102 name.clone()
5103 };
5104 specs.push(FusedInt64OutputColumn {
5105 name: out_name,
5106 side,
5107 values,
5108 });
5109 }
5110
5111 for name in right.column_names() {
5112 let col = right
5113 .columns()
5114 .get(name)
5115 .expect("right column listed in column_names must exist");
5116 if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
5117 continue;
5118 }
5119 let Some(values) = col.as_i64_slice() else {
5120 return Ok(None);
5121 };
5122 let out_name = if left_col_names.contains(name) {
5123 apply_merge_suffix(name, suffixes.right.as_deref())
5124 } else {
5125 name.clone()
5126 };
5127 specs.push(FusedInt64OutputColumn {
5128 name: out_name,
5129 side: FusedInt64Side::Right,
5130 values,
5131 });
5132 }
5133
5134 ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
5135
5136 if right_keys.is_empty() {
5137 let mut columns = std::collections::BTreeMap::new();
5138 let mut column_order = Vec::with_capacity(specs.len());
5139 for spec in specs {
5140 insert_merged_output_column(
5141 &mut columns,
5142 &mut column_order,
5143 spec.name,
5144 Column::from_i64_values(Vec::new()),
5145 )?;
5146 }
5147 return Ok(Some(MergedDataFrame {
5148 index: Index::new(Vec::new()),
5149 columns,
5150 column_order,
5151 }));
5152 }
5153 if left_keys.is_empty() {
5154 return Ok(None);
5155 }
5156
5157 let mut min = left_keys[0];
5158 let mut max = left_keys[0];
5159 for &v in left_keys {
5160 if v < min {
5161 min = v;
5162 }
5163 if v > max {
5164 max = v;
5165 }
5166 }
5167 let span = (max as i128) - (min as i128) + 1;
5168 if span > (1i128 << 24) || span > 16 * (left_keys.len() as i128) {
5169 return Ok(None);
5170 }
5171 let range = span as usize;
5172
5173 let mut offsets = vec![0usize; range + 1];
5174 for &v in left_keys {
5175 offsets[(v - min) as usize + 1] += 1;
5176 }
5177 for i in 0..range {
5178 offsets[i + 1] += offsets[i];
5179 }
5180 let mut positions = vec![0usize; left_keys.len()];
5181 let mut cursor = offsets.clone();
5182 for (pos, &v) in left_keys.iter().enumerate() {
5183 let bucket = (v - min) as usize;
5184 positions[cursor[bucket]] = pos;
5185 cursor[bucket] += 1;
5186 }
5187
5188 let mut output_len = 0usize;
5189 for &v in right_keys {
5190 if v < min || v > max {
5191 return Ok(None);
5192 }
5193 let bucket = (v - min) as usize;
5194 let bucket_len = offsets[bucket + 1] - offsets[bucket];
5195 if bucket_len == 0 {
5196 return Ok(None);
5197 }
5198 let Some(new_output_len) = output_len.checked_add(bucket_len) else {
5199 return Ok(None);
5200 };
5201 output_len = new_output_len;
5202 }
5203
5204 let mut output_data = specs
5205 .iter()
5206 .map(|_| Vec::<i64>::with_capacity(output_len))
5207 .collect::<Vec<_>>();
5208 for (right_pos, &v) in right_keys.iter().enumerate() {
5209 let bucket = (v - min) as usize;
5210 for &left_pos in &positions[offsets[bucket]..offsets[bucket + 1]] {
5211 for (out, spec) in output_data.iter_mut().zip(specs.iter()) {
5212 match spec.side {
5213 FusedInt64Side::Left => out.push(spec.values[left_pos]),
5214 FusedInt64Side::Right => out.push(spec.values[right_pos]),
5215 }
5216 }
5217 }
5218 }
5219
5220 let index = Index::new_known_unique_int64_unit_range(0, output_len);
5224 let mut columns = std::collections::BTreeMap::new();
5225 let mut column_order = Vec::with_capacity(specs.len());
5226 for (spec, data) in specs.into_iter().zip(output_data) {
5227 debug_assert_eq!(data.len(), output_len);
5228 insert_merged_output_column(
5229 &mut columns,
5230 &mut column_order,
5231 spec.name,
5232 Column::from_i64_values(data),
5233 )?;
5234 }
5235
5236 Ok(Some(MergedDataFrame {
5237 index,
5238 columns,
5239 column_order,
5240 }))
5241}
5242
5243fn build_single_key_dense_i64_outer_all_matched_merge_output(
5244 left: &fp_frame::DataFrame,
5245 right: &fp_frame::DataFrame,
5246 left_on: &[&str],
5247 right_on: &[&str],
5248 left_key: &Column,
5249 right_key: &Column,
5250 suffixes: &ResolvedMergeSuffixes,
5251) -> Result<Option<MergedDataFrame>, JoinError> {
5252 debug_assert_eq!(left_on.len(), 1);
5253 debug_assert_eq!(right_on.len(), 1);
5254
5255 let Some(left_keys) = left_key.as_i64_slice() else {
5256 return Ok(None);
5257 };
5258 let Some(right_keys) = right_key.as_i64_slice() else {
5259 return Ok(None);
5260 };
5261
5262 if left_keys.is_empty() != right_keys.is_empty() {
5263 return Ok(None);
5264 }
5265 let dense_domain = if left_keys.is_empty() {
5266 None
5267 } else {
5268 let left_witness = left_key
5269 .int64_dense_cycle_witness()
5270 .filter(|witness| witness.len == left_keys.len());
5271 let right_witness = right_key
5272 .int64_dense_cycle_witness()
5273 .filter(|witness| witness.len == right_keys.len());
5274 match (
5275 left_witness.and_then(dense_cycle_domain),
5276 right_witness.and_then(dense_cycle_domain),
5277 ) {
5278 (Some(left_domain), Some(right_domain)) => {
5279 if left_domain != right_domain {
5280 return Ok(None);
5281 }
5282 Some(left_domain)
5283 }
5284 _ => {
5285 let min_max = |keys: &[i64]| {
5286 let mut min_key = keys[0];
5287 let mut max_key = keys[0];
5288 for &key in &keys[1..] {
5289 min_key = min_key.min(key);
5290 max_key = max_key.max(key);
5291 }
5292 (min_key, max_key)
5293 };
5294 let (left_min_key, left_max_key) = min_max(left_keys);
5295 let (right_min_key, right_max_key) = min_max(right_keys);
5296 if left_min_key != right_min_key || left_max_key != right_max_key {
5297 return Ok(None);
5298 }
5299 Some((left_min_key, left_max_key))
5300 }
5301 }
5302 };
5303
5304 let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
5305 let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
5306 let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
5307 let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
5308 let shared_key_names = if left_on[0] == right_on[0] {
5309 [left_on[0]].into_iter().collect::<HashSet<&str>>()
5310 } else {
5311 HashSet::new()
5312 };
5313 let overlapping_names =
5314 collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
5315
5316 let mut specs = Vec::<FusedInt64OutputColumn<'_>>::new();
5317 for name in left.column_names() {
5318 let col = left
5319 .columns()
5320 .get(name)
5321 .expect("left column listed in column_names must exist");
5322 let Some(values) = col.as_i64_slice() else {
5323 return Ok(None);
5324 };
5325 let out_name = if left_key_name_set.contains(name.as_str()) {
5326 name.clone()
5327 } else if right_col_names.contains(name) {
5328 apply_merge_suffix(name, suffixes.left.as_deref())
5329 } else {
5330 name.clone()
5331 };
5332 specs.push(FusedInt64OutputColumn {
5333 name: out_name,
5334 side: FusedInt64Side::Left,
5335 values,
5336 });
5337 }
5338
5339 for name in right.column_names() {
5340 let col = right
5341 .columns()
5342 .get(name)
5343 .expect("right column listed in column_names must exist");
5344 if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
5345 continue;
5346 }
5347 let Some(values) = col.as_i64_slice() else {
5348 return Ok(None);
5349 };
5350 let out_name = if left_col_names.contains(name) {
5351 apply_merge_suffix(name, suffixes.right.as_deref())
5352 } else {
5353 name.clone()
5354 };
5355 specs.push(FusedInt64OutputColumn {
5356 name: out_name,
5357 side: FusedInt64Side::Right,
5358 values,
5359 });
5360 }
5361
5362 ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
5363
5364 if left_keys.is_empty() || right_keys.is_empty() {
5365 if !left_keys.is_empty() || !right_keys.is_empty() {
5366 return Ok(None);
5367 }
5368 let mut columns = std::collections::BTreeMap::new();
5369 let mut column_order = Vec::with_capacity(specs.len());
5370 for spec in specs {
5371 insert_merged_output_column(
5372 &mut columns,
5373 &mut column_order,
5374 spec.name,
5375 Column::from_i64_values(Vec::new()),
5376 )?;
5377 }
5378 return Ok(Some(MergedDataFrame {
5379 index: Index::new(Vec::new()),
5380 columns,
5381 column_order,
5382 }));
5383 }
5384
5385 let (min_key, max_key) = dense_domain.expect("empty dense outer case returned above");
5386
5387 let span = i128::from(max_key)
5388 .checked_sub(i128::from(min_key))
5389 .and_then(|span| span.checked_add(1));
5390 let Some(span) = span else {
5391 return Ok(None);
5392 };
5393 let row_count = left_keys.len().saturating_add(right_keys.len());
5394 let max_dense_span = row_count.saturating_mul(4).max(1024);
5395 if span > max_dense_span as i128 {
5396 return Ok(None);
5397 }
5398 let Ok(span) = usize::try_from(span) else {
5399 return Ok(None);
5400 };
5401
5402 let mut left_buckets = (0..span).map(|_| Vec::<usize>::new()).collect::<Vec<_>>();
5403 let mut right_buckets = (0..span).map(|_| Vec::<usize>::new()).collect::<Vec<_>>();
5404 for (pos, &key) in left_keys.iter().enumerate() {
5405 let Ok(bucket) = usize::try_from(i128::from(key) - i128::from(min_key)) else {
5406 return Ok(None);
5407 };
5408 left_buckets[bucket].push(pos);
5409 }
5410 for (pos, &key) in right_keys.iter().enumerate() {
5411 let Ok(bucket) = usize::try_from(i128::from(key) - i128::from(min_key)) else {
5412 return Ok(None);
5413 };
5414 right_buckets[bucket].push(pos);
5415 }
5416
5417 let mut output_len = 0usize;
5418 for (left_bucket, right_bucket) in left_buckets.iter().zip(right_buckets.iter()) {
5419 match (left_bucket.is_empty(), right_bucket.is_empty()) {
5420 (false, false) => {
5421 let Some(bucket_rows) = left_bucket.len().checked_mul(right_bucket.len()) else {
5422 return Ok(None);
5423 };
5424 let Some(new_output_len) = output_len.checked_add(bucket_rows) else {
5425 return Ok(None);
5426 };
5427 output_len = new_output_len;
5428 }
5429 (false, true) | (true, false) => return Ok(None),
5430 (true, true) => {}
5431 }
5432 }
5433
5434 let index = Index::new_known_unique_int64_unit_range(0, output_len);
5438 let mut columns = std::collections::BTreeMap::new();
5439 let mut column_order = Vec::with_capacity(specs.len());
5440 for spec in specs {
5441 let FusedInt64OutputColumn { name, side, values } = spec;
5442 let mut data = Vec::<i64>::with_capacity(output_len);
5443 match side {
5444 FusedInt64Side::Left => {
5445 for (left_bucket, right_bucket) in left_buckets.iter().zip(right_buckets.iter()) {
5446 if left_bucket.is_empty() {
5447 continue;
5448 }
5449 let repeat_count = right_bucket.len();
5450 for &left_pos in left_bucket {
5451 let value = values[left_pos];
5452 for _ in 0..repeat_count {
5453 data.push(value);
5454 }
5455 }
5456 }
5457 }
5458 FusedInt64Side::Right => {
5459 for (left_bucket, right_bucket) in left_buckets.iter().zip(right_buckets.iter()) {
5460 if left_bucket.is_empty() {
5461 continue;
5462 }
5463 for _ in left_bucket {
5464 for &right_pos in right_bucket {
5465 data.push(values[right_pos]);
5466 }
5467 }
5468 }
5469 }
5470 }
5471 debug_assert_eq!(data.len(), output_len);
5472 insert_merged_output_column(
5473 &mut columns,
5474 &mut column_order,
5475 name,
5476 Column::from_i64_values(data),
5477 )?;
5478 }
5479
5480 Ok(Some(MergedDataFrame {
5481 index,
5482 columns,
5483 column_order,
5484 }))
5485}
5486
5487struct FixedDecimalUtf8Domain {
5488 prefix: Vec<u8>,
5489 decimal_width: usize,
5490 start: u64,
5491 len: usize,
5492}
5493
5494impl FixedDecimalUtf8Domain {
5495 fn row_width(&self) -> usize {
5496 self.prefix.len() + self.decimal_width
5497 }
5498}
5499
5500fn trailing_decimal_width(bytes: &[u8]) -> Option<usize> {
5501 let width = bytes
5502 .iter()
5503 .rev()
5504 .take_while(|byte| byte.is_ascii_digit())
5505 .count();
5506 (width > 0).then_some(width)
5507}
5508
5509fn parse_decimal_u64(bytes: &[u8]) -> Option<u64> {
5510 let mut out = 0u64;
5511 for &byte in bytes {
5512 if !byte.is_ascii_digit() {
5513 return None;
5514 }
5515 out = out.checked_mul(10)?.checked_add(u64::from(byte - b'0'))?;
5516 }
5517 Some(out)
5518}
5519
5520fn fixed_decimal_utf8_domain(bytes: &[u8], offsets: &[usize]) -> Option<FixedDecimalUtf8Domain> {
5521 let len = offsets.len().checked_sub(1)?;
5522 if len == 0 {
5523 return None;
5524 }
5525
5526 let first = utf8_span(bytes, offsets, 0);
5527 let decimal_width = trailing_decimal_width(first)?;
5528 let prefix_len = first.len().checked_sub(decimal_width)?;
5529 let prefix = first[..prefix_len].to_vec();
5530 let start = parse_decimal_u64(&first[prefix_len..])?;
5531 let row_width = first.len();
5532
5533 for row in 0..len {
5534 let span = utf8_span(bytes, offsets, row);
5535 if span.len() != row_width || !span.starts_with(&prefix) {
5536 return None;
5537 }
5538 let value = parse_decimal_u64(&span[prefix_len..])?;
5539 if value != start.checked_add(row as u64)? {
5540 return None;
5541 }
5542 }
5543
5544 Some(FixedDecimalUtf8Domain {
5545 prefix,
5546 decimal_width,
5547 start,
5548 len,
5549 })
5550}
5551
5552fn fixed_decimal_utf8_bucket(span: &[u8], domain: &FixedDecimalUtf8Domain) -> Option<usize> {
5553 if span.len() != domain.row_width() || !span.starts_with(&domain.prefix) {
5554 return None;
5555 }
5556 let value = parse_decimal_u64(&span[domain.prefix.len()..])?;
5557 let relative = value.checked_sub(domain.start)?;
5558 let bucket = usize::try_from(relative).ok()?;
5559 (bucket < domain.len).then_some(bucket)
5560}
5561
5562enum FixedDecimalUtf8OuterLane<'a> {
5563 SharedKey,
5564 LeftF64(&'a [f64]),
5565 RightF64(&'a [f64]),
5566 LeftI64(&'a [i64]),
5567 RightI64(&'a [i64]),
5568}
5569
5570fn build_single_key_fixed_decimal_utf8_outer_all_matched_merge_output(
5571 left: &fp_frame::DataFrame,
5572 right: &fp_frame::DataFrame,
5573 left_on: &[&str],
5574 right_on: &[&str],
5575 left_key: &Column,
5576 right_key: &Column,
5577 suffixes: &ResolvedMergeSuffixes,
5578) -> Result<Option<MergedDataFrame>, JoinError> {
5579 debug_assert_eq!(left_on.len(), 1);
5580 debug_assert_eq!(right_on.len(), 1);
5581
5582 if left_on[0] != right_on[0] {
5583 return Ok(None);
5584 }
5585
5586 let Some((left_bytes, left_offsets)) = left_key.as_utf8_contiguous() else {
5587 return Ok(None);
5588 };
5589 let Some((right_bytes, right_offsets)) = right_key.as_utf8_contiguous() else {
5590 return Ok(None);
5591 };
5592 let left_len = left_offsets.len().saturating_sub(1);
5593 let right_len = right_offsets.len().saturating_sub(1);
5594 if left_len == 0 || right_len == 0 {
5595 return Ok(None);
5596 }
5597
5598 let Some(domain) = fixed_decimal_utf8_domain(right_bytes, right_offsets) else {
5599 return Ok(None);
5600 };
5601
5602 let mut counts = vec![0usize; right_len];
5603 let mut left_buckets = Vec::<usize>::with_capacity(left_len);
5604 for left_pos in 0..left_len {
5605 let span = utf8_span(left_bytes, left_offsets, left_pos);
5606 let Some(bucket) = fixed_decimal_utf8_bucket(span, &domain) else {
5607 return Ok(None);
5608 };
5609 counts[bucket] = counts[bucket].checked_add(1).ok_or_else(|| {
5610 JoinError::Frame(FrameError::CompatibilityRejected(
5611 "merge output row count overflowed".to_owned(),
5612 ))
5613 })?;
5614 left_buckets.push(bucket);
5615 }
5616 if counts.contains(&0) {
5617 return Ok(None);
5618 }
5619
5620 let mut offsets = Vec::with_capacity(right_len + 1);
5621 offsets.push(0usize);
5622 for &count in &counts {
5623 offsets.push(offsets.last().copied().unwrap_or(0) + count);
5624 }
5625 let output_len = offsets[right_len];
5626 let mut left_positions = vec![0usize; output_len];
5627 let mut cursor = offsets[..right_len].to_vec();
5628 for (left_pos, &bucket) in left_buckets.iter().enumerate() {
5629 let out = cursor[bucket];
5630 left_positions[out] = left_pos;
5631 cursor[bucket] += 1;
5632 }
5633
5634 let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
5635 let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
5636 let shared_key_names = [left_on[0]].into_iter().collect::<HashSet<&str>>();
5637 let overlapping_names =
5638 collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
5639 ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
5640
5641 let mut specs = Vec::<(String, FixedDecimalUtf8OuterLane<'_>)>::new();
5642 for name in left.column_names() {
5643 let col = left
5644 .columns()
5645 .get(name)
5646 .expect("left column listed in column_names must exist");
5647 let lane = if name.as_str() == left_on[0] {
5648 FixedDecimalUtf8OuterLane::SharedKey
5649 } else if let Some(values) = col.as_f64_slice() {
5650 FixedDecimalUtf8OuterLane::LeftF64(values)
5651 } else if let Some(values) = col.as_i64_slice() {
5652 FixedDecimalUtf8OuterLane::LeftI64(values)
5653 } else {
5654 return Ok(None);
5655 };
5656 let out_name = if name.as_str() == left_on[0] {
5657 name.clone()
5658 } else if right_col_names.contains(name) {
5659 apply_merge_suffix(name, suffixes.left.as_deref())
5660 } else {
5661 name.clone()
5662 };
5663 specs.push((out_name, lane));
5664 }
5665 for name in right.column_names() {
5666 if name.as_str() == right_on[0] {
5667 continue;
5668 }
5669 let col = right
5670 .columns()
5671 .get(name)
5672 .expect("right column listed in column_names must exist");
5673 let lane = if let Some(values) = col.as_f64_slice() {
5674 FixedDecimalUtf8OuterLane::RightF64(values)
5675 } else if let Some(values) = col.as_i64_slice() {
5676 FixedDecimalUtf8OuterLane::RightI64(values)
5677 } else {
5678 return Ok(None);
5679 };
5680 let out_name = if left_col_names.contains(name) {
5681 apply_merge_suffix(name, suffixes.right.as_deref())
5682 } else {
5683 name.clone()
5684 };
5685 specs.push((out_name, lane));
5686 }
5687
5688 let run_lens: Arc<[usize]> = Arc::from(counts.clone());
5689 let index = Index::new_known_unique_int64_unit_range(0, output_len);
5690 let mut columns = std::collections::BTreeMap::new();
5691 let mut column_order = Vec::with_capacity(specs.len());
5692 for (name, lane) in specs {
5693 let column = match lane {
5694 FixedDecimalUtf8OuterLane::SharedKey => {
5695 let row_width = domain.row_width();
5696 let mut bytes = Vec::with_capacity(output_len.saturating_mul(row_width));
5697 let mut out_offsets = Vec::with_capacity(output_len + 1);
5698 out_offsets.push(0);
5699 for (bucket, &count) in counts.iter().enumerate() {
5700 let span = utf8_span(right_bytes, right_offsets, bucket);
5701 for _ in 0..count {
5702 bytes.extend_from_slice(span);
5703 out_offsets.push(bytes.len());
5704 }
5705 }
5706 Column::from_utf8_contiguous(bytes, out_offsets)
5707 }
5708 FixedDecimalUtf8OuterLane::LeftF64(values) => {
5709 let data = left_positions.iter().map(|&pos| values[pos]).collect();
5710 Column::from_f64_values_all_valid_unchecked(data)
5711 }
5712 FixedDecimalUtf8OuterLane::RightF64(values) => {
5713 let run_values = (0..right_len).map(|bucket| values[bucket]).collect();
5714 Column::from_f64_repeat_values_run_lengths(run_values, Arc::clone(&run_lens))
5715 }
5716 FixedDecimalUtf8OuterLane::LeftI64(values) => {
5717 let data = left_positions.iter().map(|&pos| values[pos]).collect();
5718 Column::from_i64_values(data)
5719 }
5720 FixedDecimalUtf8OuterLane::RightI64(values) => {
5721 let run_values = (0..right_len).map(|bucket| values[bucket]).collect();
5722 Column::from_i64_repeat_values_run_lengths(run_values, Arc::clone(&run_lens))
5723 }
5724 };
5725 debug_assert_eq!(column.len(), output_len);
5726 insert_merged_output_column(&mut columns, &mut column_order, name, column)?;
5727 }
5728
5729 Ok(Some(MergedDataFrame {
5730 index,
5731 columns,
5732 column_order,
5733 }))
5734}
5735
5736fn build_single_key_inner_merge_output(
5737 left: &fp_frame::DataFrame,
5738 right: &fp_frame::DataFrame,
5739 left_on: &[&str],
5740 right_on: &[&str],
5741 left_positions: &[usize],
5742 right_positions: &[usize],
5743 suffixes: &ResolvedMergeSuffixes,
5744) -> Result<MergedDataFrame, JoinError> {
5745 build_single_key_inner_merge_output_with_selections(
5746 left,
5747 right,
5748 left_on,
5749 right_on,
5750 PositionSelection::Positions(left_positions),
5751 PositionSelection::Positions(right_positions),
5752 suffixes,
5753 )
5754}
5755
5756fn build_single_key_inner_contiguous_no_overlap_output(
5757 left: &fp_frame::DataFrame,
5758 right: &fp_frame::DataFrame,
5759 left_on: &[&str],
5760 right_on: &[&str],
5761 left_positions: PositionSelection<'_>,
5762 right_positions: PositionSelection<'_>,
5763) -> Option<MergedDataFrame> {
5764 let (
5765 PositionSelection::ContiguousRange {
5766 start: left_start,
5767 len,
5768 },
5769 PositionSelection::ContiguousRange {
5770 start: right_start,
5771 len: right_len,
5772 },
5773 ) = (left_positions, right_positions)
5774 else {
5775 return None;
5776 };
5777 if left_on[0] != right_on[0] || len != right_len {
5778 return None;
5779 }
5780
5781 let left_col_names = left.column_names();
5782 let right_col_names = right.column_names();
5783 if left_col_names.iter().any(|left_name| {
5784 left_name.as_str() != left_on[0]
5785 && right_col_names
5786 .iter()
5787 .any(|right_name| right_name.as_str() == left_name.as_str())
5788 }) {
5789 return None;
5790 }
5791
5792 let mut columns = std::collections::BTreeMap::new();
5793 let mut column_order =
5794 Vec::with_capacity(left_col_names.len() + right_col_names.len().saturating_sub(1));
5795 let left_selection = PositionSelection::ContiguousRange {
5796 start: left_start,
5797 len,
5798 };
5799 let right_selection = PositionSelection::ContiguousRange {
5800 start: right_start,
5801 len,
5802 };
5803
5804 for name in left_col_names.iter().copied() {
5805 let column = left
5806 .columns()
5807 .get(name)
5808 .expect("left column listed in column_names must exist");
5809 let output_column = if name.as_str() == left_on[0] {
5810 take_lower_hex_sequence_range(column, left_start, len)
5811 .unwrap_or_else(|| take_position_selection_typed(column, left_selection))
5812 } else {
5813 take_position_selection_typed(column, left_selection)
5814 };
5815 column_order.push(name.clone());
5816 let previous = columns.insert(name.clone(), output_column);
5817 debug_assert!(previous.is_none());
5818 }
5819 for name in right_col_names.iter().copied() {
5820 if name.as_str() == right_on[0] {
5821 continue;
5822 }
5823 let column = right
5824 .columns()
5825 .get(name)
5826 .expect("right column listed in column_names must exist");
5827 column_order.push(name.clone());
5828 let previous = columns.insert(
5829 name.clone(),
5830 take_position_selection_typed(column, right_selection),
5831 );
5832 debug_assert!(previous.is_none());
5833 }
5834
5835 Some(MergedDataFrame {
5836 index: Index::new_known_unique_int64_unit_range(0, len),
5837 columns,
5838 column_order,
5839 })
5840}
5841
5842fn build_single_key_inner_merge_output_with_selections(
5843 left: &fp_frame::DataFrame,
5844 right: &fp_frame::DataFrame,
5845 left_on: &[&str],
5846 right_on: &[&str],
5847 left_positions: PositionSelection<'_>,
5848 right_positions: PositionSelection<'_>,
5849 suffixes: &ResolvedMergeSuffixes,
5850) -> Result<MergedDataFrame, JoinError> {
5851 debug_assert_eq!(left_on.len(), 1);
5852 debug_assert_eq!(right_on.len(), 1);
5853 debug_assert_eq!(left_positions.len(), right_positions.len());
5854
5855 if let Some(merged) = build_single_key_inner_contiguous_no_overlap_output(
5856 left,
5857 right,
5858 left_on,
5859 right_on,
5860 left_positions,
5861 right_positions,
5862 ) {
5863 return Ok(merged);
5864 }
5865
5866 let n = left_positions.len();
5867 let index = Index::new_known_unique_int64_unit_range(0, n);
5869
5870 let left_col_names = left.column_names();
5871 let right_col_names = right.column_names();
5872 let use_linear_name_lookup =
5873 left_col_names.len() + right_col_names.len() <= SMALL_SCHEMA_LINEAR_COLUMN_LOOKUP_LIMIT;
5874 let left_hashed_col_names = (!use_linear_name_lookup).then(|| {
5875 left_col_names
5876 .iter()
5877 .map(|name| name.as_str())
5878 .collect::<HashSet<_>>()
5879 });
5880 let right_hashed_col_names = (!use_linear_name_lookup).then(|| {
5881 right_col_names
5882 .iter()
5883 .map(|name| name.as_str())
5884 .collect::<HashSet<_>>()
5885 });
5886 let shared_key_name = (left_on[0] == right_on[0]).then_some(left_on[0]);
5887 let mut overlapping_names = left_col_names
5888 .iter()
5889 .filter_map(|name| {
5890 let name = name.as_str();
5891 (Some(name) != shared_key_name
5892 && column_name_lookup_contains(
5893 &right_col_names,
5894 right_hashed_col_names.as_ref(),
5895 name,
5896 ))
5897 .then(|| name.to_owned())
5898 })
5899 .collect::<Vec<_>>();
5900 overlapping_names.sort();
5901 ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
5902
5903 let mut specs: Vec<(String, &Column, PositionSelection<'_>)> = Vec::new();
5910 for name in left_col_names.iter().copied() {
5911 let col = left
5912 .columns()
5913 .get(name)
5914 .expect("left column listed in column_names must exist");
5915 let out_name = if name.as_str() == left_on[0] {
5916 name.clone()
5917 } else if column_name_lookup_contains(
5918 &right_col_names,
5919 right_hashed_col_names.as_ref(),
5920 name.as_str(),
5921 ) {
5922 apply_merge_suffix(name, suffixes.left.as_deref())
5923 } else {
5924 name.clone()
5925 };
5926 specs.push((out_name, col, left_positions));
5927 }
5928 for name in right_col_names.iter().copied() {
5929 if name.as_str() == right_on[0] && shared_key_name == Some(name.as_str()) {
5930 continue;
5931 }
5932 let col = right
5933 .columns()
5934 .get(name)
5935 .expect("right column listed in column_names must exist");
5936 let out_name = if column_name_lookup_contains(
5937 &left_col_names,
5938 left_hashed_col_names.as_ref(),
5939 name.as_str(),
5940 ) {
5941 apply_merge_suffix(name, suffixes.right.as_deref())
5942 } else {
5943 name.clone()
5944 };
5945 specs.push((out_name, col, right_positions));
5946 }
5947
5948 let built: Vec<Column> = {
5949 let thread_count = join_parallel_thread_count();
5950 if specs.len() > 1 && n >= DENSE_I64_INNER_PARALLEL_MIN_VALUES && thread_count > 1 {
5951 let mut slots: Vec<Option<Column>> = (0..specs.len()).map(|_| None).collect();
5952 let chunk = specs.len().div_ceil(thread_count).max(1);
5953 std::thread::scope(|scope| {
5954 for (spec_chunk, slot_chunk) in specs.chunks(chunk).zip(slots.chunks_mut(chunk)) {
5955 scope.spawn(move || {
5956 for ((_, col, positions), slot) in spec_chunk.iter().zip(slot_chunk) {
5957 *slot = Some(take_position_selection_typed(col, *positions));
5958 }
5959 });
5960 }
5961 });
5962 slots
5963 .into_iter()
5964 .map(|c| c.expect("every spec column must be built"))
5965 .collect()
5966 } else {
5967 specs
5968 .iter()
5969 .map(|(_, col, positions)| take_position_selection_typed(col, *positions))
5970 .collect()
5971 }
5972 };
5973
5974 let mut columns = std::collections::BTreeMap::new();
5975 let mut column_order: Vec<String> = Vec::with_capacity(specs.len());
5976 for ((out_name, _, _), column) in specs.into_iter().zip(built) {
5977 insert_merged_output_column(&mut columns, &mut column_order, out_name, column)?;
5978 }
5979
5980 Ok(MergedDataFrame {
5981 index,
5982 columns,
5983 column_order,
5984 })
5985}
5986
5987fn build_single_key_dense_left_merge_output(
5988 left: &fp_frame::DataFrame,
5989 right: &fp_frame::DataFrame,
5990 left_on: &[&str],
5991 right_on: &[&str],
5992 left_positions: &[Option<usize>],
5993 right_positions: &[Option<usize>],
5994 suffixes: &ResolvedMergeSuffixes,
5995) -> Result<MergedDataFrame, JoinError> {
5996 debug_assert_eq!(left_on.len(), 1);
5997 debug_assert_eq!(right_on.len(), 1);
5998 debug_assert_eq!(left_positions.len(), right_positions.len());
5999
6000 let n = left_positions.len();
6001 let index = Index::new_known_unique_int64_unit_range(0, n);
6003 let mut columns = std::collections::BTreeMap::new();
6004 let mut column_order: Vec<String> = Vec::new();
6005
6006 let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
6007 let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
6008 let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
6009 let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
6010 let shared_key_names = if left_on[0] == right_on[0] {
6011 [left_on[0]].into_iter().collect::<HashSet<&str>>()
6012 } else {
6013 HashSet::new()
6014 };
6015 let overlapping_names =
6016 collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
6017 ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
6018 for name in left.column_names() {
6019 let col = left
6020 .columns()
6021 .get(name)
6022 .expect("left column listed in column_names must exist");
6023 let out_name = if left_key_name_set.contains(name.as_str()) {
6024 name.clone()
6025 } else if right_col_names.contains(name) {
6026 apply_merge_suffix(name, suffixes.left.as_deref())
6027 } else {
6028 name.clone()
6029 };
6030 let output = col.reindex_by_positions(left_positions)?;
6031 insert_merged_output_column(&mut columns, &mut column_order, out_name, output)?;
6032 }
6033
6034 for name in right.column_names() {
6035 let col = right
6036 .columns()
6037 .get(name)
6038 .expect("right column listed in column_names must exist");
6039 if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
6040 continue;
6041 }
6042
6043 let reindexed = col.reindex_by_positions(right_positions)?;
6044 let out_name = if left_col_names.contains(name) {
6045 apply_merge_suffix(name, suffixes.right.as_deref())
6046 } else {
6047 name.clone()
6048 };
6049 insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
6050 }
6051
6052 Ok(MergedDataFrame {
6053 index,
6054 columns,
6055 column_order,
6056 })
6057}
6058
6059fn build_single_key_ordered_unique_left_merge_output(
6060 left: &fp_frame::DataFrame,
6061 right: &fp_frame::DataFrame,
6062 left_on: &[&str],
6063 right_on: &[&str],
6064 right_positions: &[Option<usize>],
6065 suffixes: &ResolvedMergeSuffixes,
6066) -> Result<MergedDataFrame, JoinError> {
6067 debug_assert_eq!(left_on.len(), 1);
6068 debug_assert_eq!(right_on.len(), 1);
6069 debug_assert_eq!(left.len(), right_positions.len());
6070
6071 let n = left.len();
6072 let index = Index::new_known_unique_int64_unit_range(0, n);
6074 let mut columns = std::collections::BTreeMap::new();
6075 let mut column_order: Vec<String> = Vec::new();
6076 let mut identity_positions = None;
6077
6078 let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
6079 let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
6080 let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
6081 let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
6082 let shared_key_names = if left_on[0] == right_on[0] {
6083 [left_on[0]].into_iter().collect::<HashSet<&str>>()
6084 } else {
6085 HashSet::new()
6086 };
6087 let overlapping_names =
6088 collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
6089 ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
6090 let right_utf8_plan = shared_optional_utf8_gather_plan(right_positions, right.len());
6091
6092 for name in left.column_names() {
6093 let col = left
6094 .columns()
6095 .get(name)
6096 .expect("left column listed in column_names must exist");
6097 let out_name = if left_key_name_set.contains(name.as_str()) {
6098 name.clone()
6099 } else if right_col_names.contains(name) {
6100 apply_merge_suffix(name, suffixes.left.as_deref())
6101 } else {
6102 name.clone()
6103 };
6104 let output = identity_merge_column(col, n, &mut identity_positions);
6105 insert_merged_output_column(&mut columns, &mut column_order, out_name, output)?;
6106 }
6107
6108 for name in right.column_names() {
6109 let col = right
6110 .columns()
6111 .get(name)
6112 .expect("right column listed in column_names must exist");
6113 if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
6114 continue;
6115 }
6116
6117 let reindexed =
6118 reindex_with_shared_utf8_plan(col, right_positions, right_utf8_plan.as_ref())?;
6119 let out_name = if left_col_names.contains(name) {
6120 apply_merge_suffix(name, suffixes.right.as_deref())
6121 } else {
6122 name.clone()
6123 };
6124 insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
6125 }
6126
6127 Ok(MergedDataFrame {
6128 index,
6129 columns,
6130 column_order,
6131 })
6132}
6133
6134fn build_single_key_ordered_unique_right_merge_output(
6135 left: &fp_frame::DataFrame,
6136 right: &fp_frame::DataFrame,
6137 left_on: &[&str],
6138 right_on: &[&str],
6139 left_positions: &[Option<usize>],
6140 suffixes: &ResolvedMergeSuffixes,
6141) -> Result<MergedDataFrame, JoinError> {
6142 debug_assert_eq!(left_on.len(), 1);
6143 debug_assert_eq!(right_on.len(), 1);
6144 debug_assert_eq!(right.len(), left_positions.len());
6145
6146 let n = right.len();
6147 let index = Index::new_known_unique_int64_unit_range(0, n);
6149 let mut columns = std::collections::BTreeMap::new();
6150 let mut column_order: Vec<String> = Vec::new();
6151 let mut identity_positions = None;
6152
6153 let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
6154 let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
6155 let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
6156 let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
6157 let shared_key_names = if left_on[0] == right_on[0] {
6158 [left_on[0]].into_iter().collect::<HashSet<&str>>()
6159 } else {
6160 HashSet::new()
6161 };
6162 let overlapping_names =
6163 collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
6164 ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
6165
6166 for name in left.column_names() {
6167 let col = left
6168 .columns()
6169 .get(name)
6170 .expect("left column listed in column_names must exist");
6171 let out_name = if left_key_name_set.contains(name.as_str()) {
6172 name.clone()
6173 } else if right_col_names.contains(name) {
6174 apply_merge_suffix(name, suffixes.left.as_deref())
6175 } else {
6176 name.clone()
6177 };
6178 let output = if left_key_name_set.contains(name.as_str())
6179 && shared_key_names.contains(name.as_str())
6180 {
6181 let right_key_col = right
6182 .columns()
6183 .get(right_on[0])
6184 .expect("right key column must exist");
6185 identity_merge_column(right_key_col, n, &mut identity_positions)
6186 } else {
6187 col.reindex_by_positions(left_positions)?
6188 };
6189 insert_merged_output_column(&mut columns, &mut column_order, out_name, output)?;
6190 }
6191
6192 for name in right.column_names() {
6193 let col = right
6194 .columns()
6195 .get(name)
6196 .expect("right column listed in column_names must exist");
6197 if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
6198 continue;
6199 }
6200
6201 let reindexed = identity_merge_column(col, n, &mut identity_positions);
6202 let out_name = if left_col_names.contains(name) {
6203 apply_merge_suffix(name, suffixes.right.as_deref())
6204 } else {
6205 name.clone()
6206 };
6207 insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
6208 }
6209
6210 Ok(MergedDataFrame {
6211 index,
6212 columns,
6213 column_order,
6214 })
6215}
6216
6217fn build_single_key_dense_right_merge_output(
6218 left: &fp_frame::DataFrame,
6219 right: &fp_frame::DataFrame,
6220 left_on: &[&str],
6221 right_on: &[&str],
6222 left_positions: &[Option<usize>],
6223 right_positions: &[Option<usize>],
6224 suffixes: &ResolvedMergeSuffixes,
6225) -> Result<MergedDataFrame, JoinError> {
6226 debug_assert_eq!(left_on.len(), 1);
6227 debug_assert_eq!(right_on.len(), 1);
6228 debug_assert_eq!(left_positions.len(), right_positions.len());
6229
6230 let n = left_positions.len();
6231 let index = Index::new_known_unique_int64_unit_range(0, n);
6233 let mut columns = std::collections::BTreeMap::new();
6234 let mut column_order: Vec<String> = Vec::new();
6235
6236 let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
6237 let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
6238 let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
6239 let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
6240 let shared_key_names = if left_on[0] == right_on[0] {
6241 [left_on[0]].into_iter().collect::<HashSet<&str>>()
6242 } else {
6243 HashSet::new()
6244 };
6245 let overlapping_names =
6246 collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
6247 ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
6248
6249 for name in left.column_names() {
6250 let col = left
6251 .columns()
6252 .get(name)
6253 .expect("left column listed in column_names must exist");
6254 let out_name = if left_key_name_set.contains(name.as_str()) {
6255 name.clone()
6256 } else if right_col_names.contains(name) {
6257 apply_merge_suffix(name, suffixes.left.as_deref())
6258 } else {
6259 name.clone()
6260 };
6261 let output = if left_key_name_set.contains(name.as_str())
6262 && shared_key_names.contains(name.as_str())
6263 {
6264 let right_key_col = right
6265 .columns()
6266 .get(right_on[0])
6267 .expect("right key column must exist");
6268 right_key_col.reindex_by_positions(right_positions)?
6269 } else {
6270 col.reindex_by_positions(left_positions)?
6271 };
6272 insert_merged_output_column(&mut columns, &mut column_order, out_name, output)?;
6273 }
6274
6275 for name in right.column_names() {
6276 let col = right
6277 .columns()
6278 .get(name)
6279 .expect("right column listed in column_names must exist");
6280 if right_key_name_set.contains(name.as_str()) && shared_key_names.contains(name.as_str()) {
6281 continue;
6282 }
6283
6284 let reindexed = col.reindex_by_positions(right_positions)?;
6285 let out_name = if left_col_names.contains(name) {
6286 apply_merge_suffix(name, suffixes.right.as_deref())
6287 } else {
6288 name.clone()
6289 };
6290 insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
6291 }
6292
6293 Ok(MergedDataFrame {
6294 index,
6295 columns,
6296 column_order,
6297 })
6298}
6299
6300fn build_single_key_ordered_unique_outer_merge_output(
6301 left: &fp_frame::DataFrame,
6302 right: &fp_frame::DataFrame,
6303 left_on: &[&str],
6304 right_on: &[&str],
6305 left_positions: &[Option<usize>],
6306 right_positions: &[Option<usize>],
6307 suffixes: &ResolvedMergeSuffixes,
6308) -> Result<MergedDataFrame, JoinError> {
6309 debug_assert_eq!(left_on.len(), 1);
6310 debug_assert_eq!(right_on.len(), 1);
6311 debug_assert_eq!(left_positions.len(), right_positions.len());
6312
6313 let n = left_positions.len();
6314 let index = Index::new_known_unique_int64_unit_range(0, n);
6316 let mut columns = std::collections::BTreeMap::new();
6317 let mut column_order: Vec<String> = Vec::new();
6318
6319 let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
6320 let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
6321 let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
6322 let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
6323
6324 let mut shared_name_positions = HashMap::<&str, (usize, usize)>::new();
6325 if left_on[0] == right_on[0] {
6326 shared_name_positions.insert(left_on[0], (0, 0));
6327 }
6328 let shared_key_names = shared_name_positions
6329 .keys()
6330 .copied()
6331 .collect::<HashSet<&str>>();
6332 let overlapping_names =
6333 collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
6334 ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
6335
6336 let mut left_take_positions = Vec::with_capacity(n);
6337 let mut right_take_positions = Vec::with_capacity(n);
6338 let mut all_positions_present = true;
6339 for (left_pos, right_pos) in left_positions.iter().zip(right_positions.iter()) {
6340 let (Some(left_pos), Some(right_pos)) = (*left_pos, *right_pos) else {
6341 all_positions_present = false;
6342 break;
6343 };
6344 left_take_positions.push(left_pos);
6345 right_take_positions.push(right_pos);
6346 }
6347 let all_present_take_positions =
6348 all_positions_present.then_some((left_take_positions, right_take_positions));
6349 let all_present_left_positions = all_present_take_positions
6350 .as_ref()
6351 .map(|(positions, _)| positions.as_slice());
6352 let all_present_right_positions = all_present_take_positions
6353 .as_ref()
6354 .map(|(_, positions)| positions.as_slice());
6355 let left_has_utf8 = left
6356 .columns()
6357 .values()
6358 .any(|column| column.dtype() == DType::Utf8);
6359 let right_has_utf8 = right
6360 .columns()
6361 .values()
6362 .any(|column| column.dtype() == DType::Utf8);
6363 let left_utf8_plan = (left_has_utf8 && all_present_left_positions.is_none())
6364 .then(|| shared_optional_utf8_gather_plan(left_positions, left.len()))
6365 .flatten();
6366 let right_utf8_plan = (right_has_utf8 && all_present_right_positions.is_none())
6367 .then(|| shared_optional_utf8_gather_plan(right_positions, right.len()))
6368 .flatten();
6369
6370 enum ColBuild<'a> {
6379 KeyCoalesce {
6380 left_key_col: &'a Column,
6381 right_key_col: &'a Column,
6382 },
6383 Reindex {
6384 col: &'a Column,
6385 positions: &'a [Option<usize>],
6386 utf8_plan: Option<&'a SharedOptionalUtf8GatherPlan>,
6387 },
6388 Take {
6389 col: &'a Column,
6390 present: &'a [usize],
6391 },
6392 }
6393 let mut jobs: Vec<(String, ColBuild<'_>)> = Vec::new();
6394 for name in left.column_names() {
6395 let col = left
6396 .columns()
6397 .get(name)
6398 .expect("left column listed in column_names must exist");
6399 if left_key_name_set.contains(name.as_str()) {
6400 if let Some((left_key_idx, right_key_idx)) = shared_name_positions.get(name.as_str()) {
6401 let left_key_col = left
6402 .columns()
6403 .get(left_on[*left_key_idx])
6404 .expect("left key column must exist");
6405 let spec = if let Some(positions) = all_present_left_positions {
6406 ColBuild::Take {
6407 col: left_key_col,
6408 present: positions,
6409 }
6410 } else {
6411 let right_key_col = right
6412 .columns()
6413 .get(right_on[*right_key_idx])
6414 .expect("right key column must exist");
6415 ColBuild::KeyCoalesce {
6416 left_key_col,
6417 right_key_col,
6418 }
6419 };
6420 jobs.push((name.clone(), spec));
6421 } else {
6422 let spec = if let Some(positions) = all_present_left_positions {
6423 ColBuild::Take {
6424 col,
6425 present: positions,
6426 }
6427 } else {
6428 ColBuild::Reindex {
6429 col,
6430 positions: left_positions,
6431 utf8_plan: left_utf8_plan.as_ref(),
6432 }
6433 };
6434 jobs.push((name.clone(), spec));
6435 }
6436 continue;
6437 }
6438 let spec = if let Some(positions) = all_present_left_positions {
6439 ColBuild::Take {
6440 col,
6441 present: positions,
6442 }
6443 } else {
6444 ColBuild::Reindex {
6445 col,
6446 positions: left_positions,
6447 utf8_plan: left_utf8_plan.as_ref(),
6448 }
6449 };
6450 let out_name = if right_col_names.contains(name) {
6451 apply_merge_suffix(name, suffixes.left.as_deref())
6452 } else {
6453 name.clone()
6454 };
6455 jobs.push((out_name, spec));
6456 }
6457 for name in right.column_names() {
6458 let col = right
6459 .columns()
6460 .get(name)
6461 .expect("right column listed in column_names must exist");
6462 if right_key_name_set.contains(name.as_str())
6463 && shared_name_positions.contains_key(name.as_str())
6464 {
6465 continue;
6466 }
6467 let spec = if let Some(positions) = all_present_right_positions {
6468 ColBuild::Take {
6469 col,
6470 present: positions,
6471 }
6472 } else {
6473 ColBuild::Reindex {
6474 col,
6475 positions: right_positions,
6476 utf8_plan: right_utf8_plan.as_ref(),
6477 }
6478 };
6479 let out_name = if left_col_names.contains(name) {
6480 apply_merge_suffix(name, suffixes.right.as_deref())
6481 } else {
6482 name.clone()
6483 };
6484 jobs.push((out_name, spec));
6485 }
6486
6487 let compute = |spec: &ColBuild<'_>| -> Result<Column, JoinError> {
6488 match spec {
6489 ColBuild::KeyCoalesce {
6490 left_key_col,
6491 right_key_col,
6492 } => {
6493 if let Some(column) = coalesce_temporal_i64_key_column(
6494 left_key_col,
6495 right_key_col,
6496 left_positions,
6497 right_positions,
6498 ) {
6499 return Ok(column);
6500 }
6501 if let (Some(left_keys), Some(right_keys)) =
6502 (left_key_col.as_i64_slice(), right_key_col.as_i64_slice())
6503 {
6504 let mut data = Vec::with_capacity(left_positions.len());
6505 let mut all_positions_valid = true;
6506 for (left_pos, right_pos) in left_positions.iter().zip(right_positions.iter()) {
6507 match (*left_pos, *right_pos) {
6508 (Some(pos), _) if pos < left_keys.len() => data.push(left_keys[pos]),
6509 (None, Some(pos)) if pos < right_keys.len() => {
6510 data.push(right_keys[pos])
6511 }
6512 _ => {
6513 all_positions_valid = false;
6514 break;
6515 }
6516 }
6517 }
6518 if all_positions_valid {
6519 return Ok(Column::from_i64_values(data));
6520 }
6521 }
6522
6523 let values = left_positions
6524 .iter()
6525 .zip(right_positions.iter())
6526 .map(|(left_pos, right_pos)| match (left_pos, right_pos) {
6527 (Some(pos), _) => left_key_col.values()[*pos].clone(),
6528 (None, Some(pos)) => right_key_col.values()[*pos].clone(),
6529 (None, None) => fp_types::Scalar::Null(fp_types::NullKind::Null),
6530 })
6531 .collect::<Vec<_>>();
6532 Ok(Column::from_values(values)?)
6533 }
6534 ColBuild::Reindex {
6535 col,
6536 positions,
6537 utf8_plan,
6538 } => reindex_outer_with_shared_utf8_plan(col, positions, *utf8_plan),
6539 ColBuild::Take { col, present } => Ok(take_positions_typed(col, present)),
6540 }
6541 };
6542
6543 let worker_count = std::thread::available_parallelism()
6544 .map_or(1, std::num::NonZeroUsize::get)
6545 .min(64)
6546 .min(jobs.len().max(1));
6547 let computed: Vec<Result<Column, JoinError>> = if worker_count >= 2 && jobs.len() >= 2 {
6548 let next = std::sync::atomic::AtomicUsize::new(0);
6549 let jobs_ref = &jobs;
6550 let compute_ref = &compute;
6551 let mut slots: Vec<Option<Result<Column, JoinError>>> =
6552 (0..jobs.len()).map(|_| None).collect();
6553 let parts = std::thread::scope(|scope| {
6554 let mut handles = Vec::with_capacity(worker_count);
6555 for _ in 0..worker_count {
6556 let next = &next;
6557 handles.push(scope.spawn(move || {
6558 let mut out: Vec<(usize, Result<Column, JoinError>)> = Vec::new();
6559 loop {
6560 let i = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
6561 if i >= jobs_ref.len() {
6562 break;
6563 }
6564 out.push((i, compute_ref(&jobs_ref[i].1)));
6565 }
6566 out
6567 }));
6568 }
6569 handles
6570 .into_iter()
6571 .map(|h| h.join().expect("join assembly worker panicked"))
6572 .collect::<Vec<_>>()
6573 });
6574 for part in parts {
6575 for (i, r) in part {
6576 slots[i] = Some(r);
6577 }
6578 }
6579 slots
6580 .into_iter()
6581 .map(|s| s.expect("every output column computed"))
6582 .collect()
6583 } else {
6584 jobs.iter().map(|(_, spec)| compute(spec)).collect()
6585 };
6586
6587 for ((out_name, _), col_res) in jobs.into_iter().zip(computed) {
6588 insert_merged_output_column(&mut columns, &mut column_order, out_name, col_res?)?;
6589 }
6590
6591 Ok(MergedDataFrame {
6592 index,
6593 columns,
6594 column_order,
6595 })
6596}
6597
6598fn build_single_key_ordered_identity_inner_merge_output(
6599 left: &fp_frame::DataFrame,
6600 right: &fp_frame::DataFrame,
6601 left_on: &[&str],
6602 right_on: &[&str],
6603 suffixes: &ResolvedMergeSuffixes,
6604) -> Result<MergedDataFrame, JoinError> {
6605 debug_assert_eq!(left_on.len(), 1);
6606 debug_assert_eq!(right_on.len(), 1);
6607 debug_assert_eq!(left_on[0], right_on[0]);
6608
6609 let n = left.len();
6610 debug_assert_eq!(n, right.len());
6611 let index = Index::new_known_unique_int64_unit_range(0, n);
6613 let mut columns = std::collections::BTreeMap::new();
6614 let mut column_order: Vec<String> = Vec::new();
6615 let mut identity_positions = None;
6616
6617 let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
6618 let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
6619 let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
6620 let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
6621 let shared_key_names = left_on.iter().copied().collect::<HashSet<&str>>();
6622 let overlapping_names =
6623 collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
6624 ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
6625
6626 for name in left.column_names() {
6627 let col = left
6628 .columns()
6629 .get(name)
6630 .expect("left column listed in column_names must exist");
6631 let out_name = if left_key_name_set.contains(name.as_str()) {
6632 name.clone()
6633 } else if right_col_names.contains(name) {
6634 apply_merge_suffix(name, suffixes.left.as_deref())
6635 } else {
6636 name.clone()
6637 };
6638 let output = identity_merge_column(col, n, &mut identity_positions);
6639 insert_merged_output_column(&mut columns, &mut column_order, out_name, output)?;
6640 }
6641
6642 for name in right.column_names() {
6643 if right_key_name_set.contains(name.as_str()) {
6644 continue;
6645 }
6646
6647 let col = right
6648 .columns()
6649 .get(name)
6650 .expect("right column listed in column_names must exist");
6651 let out_name = if left_col_names.contains(name) {
6652 apply_merge_suffix(name, suffixes.right.as_deref())
6653 } else {
6654 name.clone()
6655 };
6656 let output = identity_merge_column(col, n, &mut identity_positions);
6657 insert_merged_output_column(&mut columns, &mut column_order, out_name, output)?;
6658 }
6659
6660 Ok(MergedDataFrame {
6661 index,
6662 columns,
6663 column_order,
6664 })
6665}
6666
6667fn dense_int64_inner_positions(
6681 left_key: &Column,
6682 right_key: &Column,
6683) -> Option<(Vec<usize>, Vec<usize>)> {
6684 let left = left_key.as_i64_slice()?;
6685 let right = right_key.as_i64_slice()?;
6686 dense_i64_inner_positions_slices(left, right)
6687}
6688
6689fn temporal_i64_inner_positions(
6700 left_key: &Column,
6701 right_key: &Column,
6702) -> Option<(Vec<usize>, Vec<usize>)> {
6703 if !left_key.validity().all() || !right_key.validity().all() {
6704 return None;
6705 }
6706
6707 let (left, right, nat) = match (left_key.dtype(), right_key.dtype()) {
6708 (DType::Datetime64, DType::Datetime64) => (
6709 left_key.as_datetime64_slice()?,
6710 right_key.as_datetime64_slice()?,
6711 fp_types::Timestamp::NAT,
6712 ),
6713 (DType::Timedelta64, DType::Timedelta64) => (
6714 left_key.as_timedelta64_slice()?,
6715 right_key.as_timedelta64_slice()?,
6716 fp_types::Timedelta::NAT,
6717 ),
6718 _ => return None,
6719 };
6720 let mut left_positions = Vec::with_capacity(left.len().min(right.len()));
6721 let mut right_positions = Vec::with_capacity(left_positions.capacity());
6722 let (mut left_idx, mut right_idx) = (0usize, 0usize);
6723 let mut ordered = newly_reached_temporal_i64_value_is_strict(left, 0, nat)
6724 && newly_reached_temporal_i64_value_is_strict(right, 0, nat);
6725 while ordered && left_idx < left.len() && right_idx < right.len() {
6726 match left[left_idx].cmp(&right[right_idx]) {
6727 Ordering::Equal => {
6728 left_positions.push(left_idx);
6729 right_positions.push(right_idx);
6730 left_idx += 1;
6731 right_idx += 1;
6732 ordered = newly_reached_temporal_i64_value_is_strict(left, left_idx, nat)
6733 && newly_reached_temporal_i64_value_is_strict(right, right_idx, nat);
6734 }
6735 Ordering::Less => {
6736 left_idx += 1;
6737 ordered = newly_reached_temporal_i64_value_is_strict(left, left_idx, nat);
6738 }
6739 Ordering::Greater => {
6740 right_idx += 1;
6741 ordered = newly_reached_temporal_i64_value_is_strict(right, right_idx, nat);
6742 }
6743 }
6744 }
6745 while ordered && left_idx < left.len() {
6746 left_idx += 1;
6747 ordered = newly_reached_temporal_i64_value_is_strict(left, left_idx, nat);
6748 }
6749 while ordered && right_idx < right.len() {
6750 right_idx += 1;
6751 ordered = newly_reached_temporal_i64_value_is_strict(right, right_idx, nat);
6752 }
6753 if ordered {
6754 return Some((left_positions, right_positions));
6755 }
6756
6757 if left.contains(&nat) || right.contains(&nat) {
6758 return None;
6759 }
6760
6761 dense_i64_inner_positions_slices(left, right)
6762 .or_else(|| Some(hash_i64_inner_positions_slices(left, right)))
6763}
6764
6765fn temporal_i64_left_positions(
6771 left_key: &Column,
6772 right_key: &Column,
6773) -> Option<OptionalJoinPositions> {
6774 if !left_key.validity().all() || !right_key.validity().all() {
6775 return None;
6776 }
6777
6778 let (left, right, nat) = match (left_key.dtype(), right_key.dtype()) {
6779 (DType::Datetime64, DType::Datetime64) => (
6780 left_key.as_datetime64_slice()?,
6781 right_key.as_datetime64_slice()?,
6782 fp_types::Timestamp::NAT,
6783 ),
6784 (DType::Timedelta64, DType::Timedelta64) => (
6785 left_key.as_timedelta64_slice()?,
6786 right_key.as_timedelta64_slice()?,
6787 fp_types::Timedelta::NAT,
6788 ),
6789 _ => return None,
6790 };
6791 if left.contains(&nat) || right.contains(&nat) {
6792 return None;
6793 }
6794
6795 if left.windows(2).all(|pair| pair[0] < pair[1])
6796 && right.windows(2).all(|pair| pair[0] < pair[1])
6797 {
6798 let left_positions = (0..left.len()).map(Some).collect::<Vec<_>>();
6799 let mut right_positions = Vec::with_capacity(left.len());
6800 let mut right_idx = 0usize;
6801 for &left_value in left {
6802 while right_idx < right.len() && right[right_idx] < left_value {
6803 right_idx += 1;
6804 }
6805 right_positions.push(
6806 (right_idx < right.len()
6807 && matches!(right[right_idx].cmp(&left_value), Ordering::Equal))
6808 .then_some(right_idx),
6809 );
6810 }
6811 return Some((left_positions, right_positions));
6812 }
6813
6814 if right.is_empty() {
6815 return Some((
6816 (0..left.len()).map(Some).collect(),
6817 vec![None; left.len()],
6818 ));
6819 }
6820 let mut right_map = FxHashMap::<i64, JoinPositionBucket>::with_capacity_and_hasher(
6821 right.len(),
6822 Default::default(),
6823 );
6824 for (pos, &key) in right.iter().enumerate() {
6825 right_map.entry(key).or_default().push(pos);
6826 }
6827 let mut left_positions = Vec::<Option<usize>>::with_capacity(left.len());
6828 let mut right_positions = Vec::<Option<usize>>::with_capacity(left.len());
6829 for (left_pos, &key) in left.iter().enumerate() {
6830 if let Some(matches) = right_map.get(&key) {
6831 for &right_pos in matches {
6832 left_positions.push(Some(left_pos));
6833 right_positions.push(Some(right_pos));
6834 }
6835 } else {
6836 left_positions.push(Some(left_pos));
6837 right_positions.push(None);
6838 }
6839 }
6840 Some((left_positions, right_positions))
6841}
6842
6843#[inline]
6844fn newly_reached_temporal_i64_value_is_strict(values: &[i64], idx: usize, nat: i64) -> bool {
6845 let Some(&value) = values.get(idx) else {
6846 return true;
6847 };
6848 value != nat && (idx == 0 || values[idx - 1] < value)
6849}
6850
6851fn ordered_unique_temporal_i64_right_match_positions(
6859 left_key: &Column,
6860 right_key: &Column,
6861) -> Option<Vec<Option<usize>>> {
6862 if !left_key.validity().all() || !right_key.validity().all() {
6863 return None;
6864 }
6865
6866 let (left, right, nat) = match (left_key.dtype(), right_key.dtype()) {
6867 (DType::Datetime64, DType::Datetime64) => (
6868 left_key.as_datetime64_slice()?,
6869 right_key.as_datetime64_slice()?,
6870 fp_types::Timestamp::NAT,
6871 ),
6872 (DType::Timedelta64, DType::Timedelta64) => (
6873 left_key.as_timedelta64_slice()?,
6874 right_key.as_timedelta64_slice()?,
6875 fp_types::Timedelta::NAT,
6876 ),
6877 _ => return None,
6878 };
6879 if !newly_reached_temporal_i64_value_is_strict(left, 0, nat) {
6880 return None;
6881 }
6882
6883 let mut left_positions = Vec::with_capacity(right.len());
6884 let mut left_idx = 0usize;
6885 for (right_idx, &right_value) in right.iter().enumerate() {
6886 if !newly_reached_temporal_i64_value_is_strict(right, right_idx, nat) {
6887 return None;
6888 }
6889 while left_idx < left.len() && left[left_idx] < right_value {
6890 left_idx += 1;
6891 if !newly_reached_temporal_i64_value_is_strict(left, left_idx, nat) {
6892 return None;
6893 }
6894 }
6895 left_positions.push(
6896 (left_idx < left.len()
6897 && matches!(left[left_idx].cmp(&right_value), Ordering::Equal))
6898 .then_some(left_idx),
6899 );
6900 }
6901 while left_idx < left.len() {
6902 left_idx += 1;
6903 if !newly_reached_temporal_i64_value_is_strict(left, left_idx, nat) {
6904 return None;
6905 }
6906 }
6907 Some(left_positions)
6908}
6909
6910fn ordered_unique_temporal_i64_outer_positions(
6918 left_key: &Column,
6919 right_key: &Column,
6920) -> Option<OptionalJoinPositions> {
6921 if !left_key.validity().all() || !right_key.validity().all() {
6922 return None;
6923 }
6924
6925 let (left, right, nat) = match (left_key.dtype(), right_key.dtype()) {
6926 (DType::Datetime64, DType::Datetime64) => (
6927 left_key.as_datetime64_slice()?,
6928 right_key.as_datetime64_slice()?,
6929 fp_types::Timestamp::NAT,
6930 ),
6931 (DType::Timedelta64, DType::Timedelta64) => (
6932 left_key.as_timedelta64_slice()?,
6933 right_key.as_timedelta64_slice()?,
6934 fp_types::Timedelta::NAT,
6935 ),
6936 _ => return None,
6937 };
6938 if !newly_reached_temporal_i64_value_is_strict(left, 0, nat)
6939 || !newly_reached_temporal_i64_value_is_strict(right, 0, nat)
6940 {
6941 return None;
6942 }
6943
6944 let capacity = left.len().saturating_add(right.len());
6945 let mut left_positions = Vec::<Option<usize>>::with_capacity(capacity);
6946 let mut right_positions = Vec::<Option<usize>>::with_capacity(capacity);
6947 let (mut left_idx, mut right_idx) = (0usize, 0usize);
6948 while left_idx < left.len() && right_idx < right.len() {
6949 match left[left_idx].cmp(&right[right_idx]) {
6950 Ordering::Equal => {
6951 left_positions.push(Some(left_idx));
6952 right_positions.push(Some(right_idx));
6953 left_idx += 1;
6954 right_idx += 1;
6955 if !newly_reached_temporal_i64_value_is_strict(left, left_idx, nat)
6956 || !newly_reached_temporal_i64_value_is_strict(right, right_idx, nat)
6957 {
6958 return None;
6959 }
6960 }
6961 Ordering::Less => {
6962 left_positions.push(Some(left_idx));
6963 right_positions.push(None);
6964 left_idx += 1;
6965 if !newly_reached_temporal_i64_value_is_strict(left, left_idx, nat) {
6966 return None;
6967 }
6968 }
6969 Ordering::Greater => {
6970 left_positions.push(None);
6971 right_positions.push(Some(right_idx));
6972 right_idx += 1;
6973 if !newly_reached_temporal_i64_value_is_strict(right, right_idx, nat) {
6974 return None;
6975 }
6976 }
6977 }
6978 }
6979 while left_idx < left.len() {
6980 left_positions.push(Some(left_idx));
6981 right_positions.push(None);
6982 left_idx += 1;
6983 if !newly_reached_temporal_i64_value_is_strict(left, left_idx, nat) {
6984 return None;
6985 }
6986 }
6987 while right_idx < right.len() {
6988 left_positions.push(None);
6989 right_positions.push(Some(right_idx));
6990 right_idx += 1;
6991 if !newly_reached_temporal_i64_value_is_strict(right, right_idx, nat) {
6992 return None;
6993 }
6994 }
6995 Some((left_positions, right_positions))
6996}
6997
6998fn dense_i64_inner_positions_slices(
7004 left: &[i64],
7005 right: &[i64],
7006) -> Option<(Vec<usize>, Vec<usize>)> {
7007 if right.is_empty() || left.is_empty() {
7008 return Some((Vec::new(), Vec::new()));
7009 }
7010
7011 let mut min = right[0];
7012 let mut max = right[0];
7013 for &v in right {
7014 if v < min {
7015 min = v;
7016 }
7017 if v > max {
7018 max = v;
7019 }
7020 }
7021 let span = (max as i128) - (min as i128) + 1;
7025 if span > (1i128 << 24) || span > 16 * (right.len() as i128) {
7026 return None;
7027 }
7028 let range = span as usize;
7029
7030 let mut offsets = vec![0usize; range + 1];
7033 for &v in right {
7034 offsets[(v - min) as usize + 1] += 1;
7035 }
7036 for i in 0..range {
7037 offsets[i + 1] += offsets[i];
7038 }
7039 let mut positions = vec![0usize; right.len()];
7040 let mut cursor = offsets.clone();
7041 for (pos, &v) in right.iter().enumerate() {
7042 let bucket = (v - min) as usize;
7043 positions[cursor[bucket]] = pos;
7044 cursor[bucket] += 1;
7045 }
7046
7047 let mut left_positions = Vec::<usize>::with_capacity(left.len().min(right.len()));
7048 let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
7049 for (left_pos, &v) in left.iter().enumerate() {
7050 if v < min || v > max {
7051 continue;
7052 }
7053 let bucket = (v - min) as usize;
7054 for &right_pos in &positions[offsets[bucket]..offsets[bucket + 1]] {
7055 left_positions.push(left_pos);
7056 right_positions.push(right_pos);
7057 }
7058 }
7059 Some((left_positions, right_positions))
7060}
7061
7062fn hash_int64_inner_positions(
7067 left_key: &Column,
7068 right_key: &Column,
7069) -> Option<(Vec<usize>, Vec<usize>)> {
7070 let left = left_key.as_i64_slice()?;
7071 let right = right_key.as_i64_slice()?;
7072 Some(hash_i64_inner_positions_slices(left, right))
7073}
7074
7075fn hash_int64_left_positions(
7086 left_key: &Column,
7087 right_key: &Column,
7088) -> Option<OptionalJoinPositions> {
7089 let left = left_key.as_i64_slice()?;
7090 let right = right_key.as_i64_slice()?;
7091 if right.is_empty() {
7092 let left_positions = (0..left.len()).map(Some).collect::<Vec<_>>();
7093 let right_positions = vec![None; left.len()];
7094 return Some((left_positions, right_positions));
7095 }
7096 let mut right_map = FxHashMap::<i64, JoinPositionBucket>::with_capacity_and_hasher(
7097 right.len(),
7098 Default::default(),
7099 );
7100 for (pos, &key) in right.iter().enumerate() {
7101 right_map.entry(key).or_default().push(pos);
7102 }
7103 let mut left_positions = Vec::<Option<usize>>::with_capacity(left.len());
7104 let mut right_positions = Vec::<Option<usize>>::with_capacity(left.len());
7105 for (left_pos, &key) in left.iter().enumerate() {
7106 if let Some(matches) = right_map.get(&key) {
7107 for &right_pos in matches {
7108 left_positions.push(Some(left_pos));
7109 right_positions.push(Some(right_pos));
7110 }
7111 } else {
7112 left_positions.push(Some(left_pos));
7113 right_positions.push(None);
7114 }
7115 }
7116 Some((left_positions, right_positions))
7117}
7118
7119fn hash_int64_outer_positions(
7128 left_key: &Column,
7129 right_key: &Column,
7130) -> Option<OptionalJoinPositions> {
7131 let left = left_key.as_i64_slice()?;
7132 let right = right_key.as_i64_slice()?;
7133 let mut gid_of: FxHashMap<i64, u32> = FxHashMap::with_capacity_and_hasher(
7134 left.len().saturating_add(right.len()),
7135 Default::default(),
7136 );
7137 let mut gid_keys: Vec<i64> = Vec::new();
7138 let mut left_gid: Vec<u32> = Vec::with_capacity(left.len());
7139 for &key in left {
7140 let g = *gid_of.entry(key).or_insert_with(|| {
7141 let x = gid_keys.len() as u32;
7142 gid_keys.push(key);
7143 x
7144 });
7145 left_gid.push(g);
7146 }
7147 let mut right_gid: Vec<u32> = Vec::with_capacity(right.len());
7148 for &key in right {
7149 let g = *gid_of.entry(key).or_insert_with(|| {
7150 let x = gid_keys.len() as u32;
7151 gid_keys.push(key);
7152 x
7153 });
7154 right_gid.push(g);
7155 }
7156 let ng = gid_keys.len();
7157 let mut loff = vec![0u32; ng + 1];
7159 for &g in &left_gid {
7160 loff[g as usize + 1] += 1;
7161 }
7162 let mut roff = vec![0u32; ng + 1];
7163 for &g in &right_gid {
7164 roff[g as usize + 1] += 1;
7165 }
7166 for g in 0..ng {
7167 loff[g + 1] += loff[g];
7168 roff[g + 1] += roff[g];
7169 }
7170 let mut lpos = vec![0u32; left.len()];
7171 let mut lw = loff[..ng].to_vec();
7172 for (i, &g) in left_gid.iter().enumerate() {
7173 let g = g as usize;
7174 lpos[lw[g] as usize] = i as u32;
7175 lw[g] += 1;
7176 }
7177 let mut rpos = vec![0u32; right.len()];
7178 let mut rw = roff[..ng].to_vec();
7179 for (i, &g) in right_gid.iter().enumerate() {
7180 let g = g as usize;
7181 rpos[rw[g] as usize] = i as u32;
7182 rw[g] += 1;
7183 }
7184 let mut order: Vec<u32> = (0..ng as u32).collect();
7185 order.sort_unstable_by_key(|&g| gid_keys[g as usize]);
7186 let mut left_positions = Vec::<Option<usize>>::new();
7187 let mut right_positions = Vec::<Option<usize>>::new();
7188 for &g in &order {
7189 let g = g as usize;
7190 let ls = &lpos[loff[g] as usize..loff[g + 1] as usize];
7191 let rs = &rpos[roff[g] as usize..roff[g + 1] as usize];
7192 match (ls.is_empty(), rs.is_empty()) {
7193 (false, false) => {
7194 for &l in ls {
7195 for &r in rs {
7196 left_positions.push(Some(l as usize));
7197 right_positions.push(Some(r as usize));
7198 }
7199 }
7200 }
7201 (false, true) => {
7202 for &l in ls {
7203 left_positions.push(Some(l as usize));
7204 right_positions.push(None);
7205 }
7206 }
7207 (true, false) => {
7208 for &r in rs {
7209 left_positions.push(None);
7210 right_positions.push(Some(r as usize));
7211 }
7212 }
7213 (true, true) => {}
7214 }
7215 }
7216 Some((left_positions, right_positions))
7217}
7218
7219fn contiguous_utf8_inner_positions(
7228 left_key: &Column,
7229 right_key: &Column,
7230) -> Option<(Vec<usize>, Vec<usize>)> {
7231 let (left_bytes, left_offsets) = left_key.as_utf8_contiguous()?;
7232 let (right_bytes, right_offsets) = right_key.as_utf8_contiguous()?;
7233 let left_n = left_offsets.len() - 1;
7234 let right_n = right_offsets.len() - 1;
7235 if left_n == 0 || right_n == 0 {
7236 return Some((Vec::new(), Vec::new()));
7237 }
7238
7239 if let Some(positions) =
7240 sorted_contiguous_utf8_inner_positions(left_bytes, left_offsets, right_bytes, right_offsets)
7241 {
7242 return Some(positions);
7243 }
7244
7245 let mut right_map = FxHashMap::<&[u8], JoinPositionBucket>::with_capacity_and_hasher(
7246 right_n,
7247 Default::default(),
7248 );
7249 for pos in 0..right_n {
7250 let span = &right_bytes[right_offsets[pos]..right_offsets[pos + 1]];
7251 right_map.entry(span).or_default().push(pos);
7252 }
7253
7254 let mut left_positions = Vec::<usize>::with_capacity(left_n.min(right_n));
7255 let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
7256 for left_pos in 0..left_n {
7257 let span = &left_bytes[left_offsets[left_pos]..left_offsets[left_pos + 1]];
7258 if let Some(matches) = right_map.get(span) {
7259 for &right_pos in matches {
7260 left_positions.push(left_pos);
7261 right_positions.push(right_pos);
7262 }
7263 }
7264 }
7265 Some((left_positions, right_positions))
7266}
7267
7268fn collect_contiguous_utf8_position_map<'a>(
7269 bytes: &'a [u8],
7270 offsets: &[usize],
7271) -> FxHashMap<&'a [u8], JoinPositionBucket> {
7272 let n = offsets.len() - 1;
7273 let mut map =
7274 FxHashMap::<&[u8], JoinPositionBucket>::with_capacity_and_hasher(n, Default::default());
7275 for pos in 0..n {
7276 let span = &bytes[offsets[pos]..offsets[pos + 1]];
7277 map.entry(span).or_default().push(pos);
7278 }
7279 map
7280}
7281
7282fn contiguous_utf8_left_positions(
7283 left_key: &Column,
7284 right_key: &Column,
7285) -> Option<OptionalJoinPositions> {
7286 let (left_bytes, left_offsets) = left_key.as_utf8_contiguous()?;
7287 let (right_bytes, right_offsets) = right_key.as_utf8_contiguous()?;
7288 let left_n = left_offsets.len() - 1;
7289 let right_map = collect_contiguous_utf8_position_map(right_bytes, right_offsets);
7290
7291 let mut out_len = 0usize;
7292 for left_pos in 0..left_n {
7293 let span = &left_bytes[left_offsets[left_pos]..left_offsets[left_pos + 1]];
7294 out_len += right_map.get(span).map_or(1, JoinPositionBucket::len);
7295 }
7296
7297 let mut left_positions = Vec::<Option<usize>>::with_capacity(out_len);
7298 let mut right_positions = Vec::<Option<usize>>::with_capacity(out_len);
7299 for left_pos in 0..left_n {
7300 let span = &left_bytes[left_offsets[left_pos]..left_offsets[left_pos + 1]];
7301 if let Some(matches) = right_map.get(span) {
7302 for &right_pos in matches {
7303 left_positions.push(Some(left_pos));
7304 right_positions.push(Some(right_pos));
7305 }
7306 } else {
7307 left_positions.push(Some(left_pos));
7308 right_positions.push(None);
7309 }
7310 }
7311 Some((left_positions, right_positions))
7312}
7313
7314fn contiguous_utf8_outer_positions(
7315 left_key: &Column,
7316 right_key: &Column,
7317) -> Option<OptionalJoinPositions> {
7318 let (left_bytes, left_offsets) = left_key.as_utf8_contiguous()?;
7319 let (right_bytes, right_offsets) = right_key.as_utf8_contiguous()?;
7320 let left_n = left_offsets.len() - 1;
7321 let right_n = right_offsets.len() - 1;
7322
7323 let left_map = collect_contiguous_utf8_position_map(left_bytes, left_offsets);
7324 let right_map = collect_contiguous_utf8_position_map(right_bytes, right_offsets);
7325 let mut seen = FxHashSet::<&[u8]>::with_capacity_and_hasher(
7326 left_map.len() + right_map.len(),
7327 Default::default(),
7328 );
7329 let mut keys = Vec::<&[u8]>::with_capacity(left_map.len() + right_map.len());
7330 for pos in 0..left_n {
7331 let span = &left_bytes[left_offsets[pos]..left_offsets[pos + 1]];
7332 if seen.insert(span) {
7333 keys.push(span);
7334 }
7335 }
7336 for pos in 0..right_n {
7337 let span = &right_bytes[right_offsets[pos]..right_offsets[pos + 1]];
7338 if seen.insert(span) {
7339 keys.push(span);
7340 }
7341 }
7342 keys.sort_unstable();
7343
7344 let mut out_len = 0usize;
7345 for &key in &keys {
7346 out_len += match (left_map.get(key), right_map.get(key)) {
7347 (Some(lefts), Some(rights)) => lefts.len() * rights.len(),
7348 (Some(lefts), None) => lefts.len(),
7349 (None, Some(rights)) => rights.len(),
7350 (None, None) => 0,
7351 };
7352 }
7353
7354 let mut left_positions = Vec::<Option<usize>>::with_capacity(out_len);
7355 let mut right_positions = Vec::<Option<usize>>::with_capacity(out_len);
7356 for key in keys {
7357 match (left_map.get(key), right_map.get(key)) {
7358 (Some(lefts), Some(rights)) => {
7359 for &left_pos in lefts {
7360 for &right_pos in rights {
7361 left_positions.push(Some(left_pos));
7362 right_positions.push(Some(right_pos));
7363 }
7364 }
7365 }
7366 (Some(lefts), None) => {
7367 for &left_pos in lefts {
7368 left_positions.push(Some(left_pos));
7369 right_positions.push(None);
7370 }
7371 }
7372 (None, Some(rights)) => {
7373 for &right_pos in rights {
7374 left_positions.push(None);
7375 right_positions.push(Some(right_pos));
7376 }
7377 }
7378 (None, None) => {}
7379 }
7380 }
7381 Some((left_positions, right_positions))
7382}
7383
7384fn scalar_utf8_values(column: &Column) -> Option<&[Scalar]> {
7385 if column.dtype() != DType::Utf8 || !column.validity().all() {
7386 return None;
7387 }
7388 let values = column.values();
7389 values
7390 .iter()
7391 .all(|value| matches!(value, Scalar::Utf8(_)))
7392 .then_some(values)
7393}
7394
7395fn scalar_utf8_span(value: &Scalar) -> Option<&[u8]> {
7396 match value {
7397 Scalar::Utf8(value) => Some(value.as_bytes()),
7398 _ => None,
7399 }
7400}
7401
7402fn collect_scalar_utf8_position_map(
7403 values: &[Scalar],
7404) -> Option<FxHashMap<&[u8], JoinPositionBucket>> {
7405 let mut map = FxHashMap::<&[u8], JoinPositionBucket>::with_capacity_and_hasher(
7406 values.len(),
7407 Default::default(),
7408 );
7409 for (pos, value) in values.iter().enumerate() {
7410 map.entry(scalar_utf8_span(value)?).or_default().push(pos);
7411 }
7412 Some(map)
7413}
7414
7415fn scalar_utf8_inner_positions(
7416 left_key: &Column,
7417 right_key: &Column,
7418) -> Option<(Vec<usize>, Vec<usize>)> {
7419 let left = scalar_utf8_values(left_key)?;
7420 let right = scalar_utf8_values(right_key)?;
7421 if left.is_empty() || right.is_empty() {
7422 return Some((Vec::new(), Vec::new()));
7423 }
7424
7425 let right_map = collect_scalar_utf8_position_map(right)?;
7426 let mut left_positions = Vec::<usize>::with_capacity(left.len().min(right.len()));
7427 let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
7428 for (left_pos, value) in left.iter().enumerate() {
7429 if let Some(matches) = right_map.get(scalar_utf8_span(value)?) {
7430 for &right_pos in matches {
7431 left_positions.push(left_pos);
7432 right_positions.push(right_pos);
7433 }
7434 }
7435 }
7436 Some((left_positions, right_positions))
7437}
7438
7439fn scalar_utf8_left_positions(
7440 left_key: &Column,
7441 right_key: &Column,
7442) -> Option<OptionalJoinPositions> {
7443 let left = scalar_utf8_values(left_key)?;
7444 let right = scalar_utf8_values(right_key)?;
7445 let right_map = collect_scalar_utf8_position_map(right)?;
7446
7447 let mut out_len = 0usize;
7448 for value in left {
7449 out_len += right_map
7450 .get(scalar_utf8_span(value)?)
7451 .map_or(1, JoinPositionBucket::len);
7452 }
7453
7454 let mut left_positions = Vec::<Option<usize>>::with_capacity(out_len);
7455 let mut right_positions = Vec::<Option<usize>>::with_capacity(out_len);
7456 for (left_pos, value) in left.iter().enumerate() {
7457 if let Some(matches) = right_map.get(scalar_utf8_span(value)?) {
7458 for &right_pos in matches {
7459 left_positions.push(Some(left_pos));
7460 right_positions.push(Some(right_pos));
7461 }
7462 } else {
7463 left_positions.push(Some(left_pos));
7464 right_positions.push(None);
7465 }
7466 }
7467 Some((left_positions, right_positions))
7468}
7469
7470fn scalar_utf8_outer_positions(
7471 left_key: &Column,
7472 right_key: &Column,
7473) -> Option<OptionalJoinPositions> {
7474 let left = scalar_utf8_values(left_key)?;
7475 let right = scalar_utf8_values(right_key)?;
7476 let left_map = collect_scalar_utf8_position_map(left)?;
7477 let right_map = collect_scalar_utf8_position_map(right)?;
7478
7479 let mut seen = FxHashSet::<&[u8]>::with_capacity_and_hasher(
7480 left_map.len() + right_map.len(),
7481 Default::default(),
7482 );
7483 let mut keys = Vec::<&[u8]>::with_capacity(left_map.len() + right_map.len());
7484 for value in left {
7485 let span = scalar_utf8_span(value)?;
7486 if seen.insert(span) {
7487 keys.push(span);
7488 }
7489 }
7490 for value in right {
7491 let span = scalar_utf8_span(value)?;
7492 if seen.insert(span) {
7493 keys.push(span);
7494 }
7495 }
7496 keys.sort_unstable();
7497
7498 let mut out_len = 0usize;
7499 for &key in &keys {
7500 out_len += match (left_map.get(key), right_map.get(key)) {
7501 (Some(lefts), Some(rights)) => lefts.len() * rights.len(),
7502 (Some(lefts), None) => lefts.len(),
7503 (None, Some(rights)) => rights.len(),
7504 (None, None) => 0,
7505 };
7506 }
7507
7508 let mut left_positions = Vec::<Option<usize>>::with_capacity(out_len);
7509 let mut right_positions = Vec::<Option<usize>>::with_capacity(out_len);
7510 for key in keys {
7511 match (left_map.get(key), right_map.get(key)) {
7512 (Some(lefts), Some(rights)) => {
7513 for &left_pos in lefts {
7514 for &right_pos in rights {
7515 left_positions.push(Some(left_pos));
7516 right_positions.push(Some(right_pos));
7517 }
7518 }
7519 }
7520 (Some(lefts), None) => {
7521 for &left_pos in lefts {
7522 left_positions.push(Some(left_pos));
7523 right_positions.push(None);
7524 }
7525 }
7526 (None, Some(rights)) => {
7527 for &right_pos in rights {
7528 left_positions.push(None);
7529 right_positions.push(Some(right_pos));
7530 }
7531 }
7532 (None, None) => {}
7533 }
7534 }
7535 Some((left_positions, right_positions))
7536}
7537
7538fn hash_i64_inner_positions_slices(left: &[i64], right: &[i64]) -> (Vec<usize>, Vec<usize>) {
7539 if right.is_empty() || left.is_empty() {
7540 return (Vec::new(), Vec::new());
7541 }
7542
7543 let mut right_map = FxHashMap::<i64, JoinPositionBucket>::with_capacity_and_hasher(
7544 right.len(),
7545 Default::default(),
7546 );
7547 for (pos, &key) in right.iter().enumerate() {
7548 right_map.entry(key).or_default().push(pos);
7549 }
7550
7551 let mut left_positions = Vec::<usize>::with_capacity(left.len().min(right.len()));
7552 let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
7553 for (left_pos, &key) in left.iter().enumerate() {
7554 if let Some(matches) = right_map.get(&key) {
7555 for &right_pos in matches {
7556 left_positions.push(left_pos);
7557 right_positions.push(right_pos);
7558 }
7559 }
7560 }
7561 (left_positions, right_positions)
7562}
7563
7564fn typed_wide_two_i64_key_positions(
7589 join_type: JoinType,
7590 left_cols: &[&Column],
7591 right_cols: &[&Column],
7592) -> Option<MergeRowPositions> {
7593 if !matches!(
7594 join_type,
7595 JoinType::Inner | JoinType::Left | JoinType::Outer
7596 ) {
7597 return None;
7598 }
7599 if left_cols.len() != 2 || right_cols.len() != 2 {
7600 return None;
7601 }
7602 let l0 = left_cols[0].as_i64_slice()?;
7603 let l1 = left_cols[1].as_i64_slice()?;
7604 let r0 = right_cols[0].as_i64_slice()?;
7605 let r1 = right_cols[1].as_i64_slice()?;
7606 let pack = |a: i64, b: i64| -> u128 { (u128::from(a as u64) << 64) | u128::from(b as u64) };
7607
7608 if matches!(join_type, JoinType::Outer) {
7609 let mut gid_of: FxHashMap<u128, u32> = FxHashMap::with_capacity_and_hasher(
7615 l0.len().saturating_add(r0.len()),
7616 Default::default(),
7617 );
7618 let mut gid_keys: Vec<u128> = Vec::new();
7619 let mut left_gid: Vec<u32> = Vec::with_capacity(l0.len());
7620 for pos in 0..l0.len() {
7621 let key = pack(l0[pos], l1[pos]);
7622 let g = *gid_of.entry(key).or_insert_with(|| {
7623 let x = gid_keys.len() as u32;
7624 gid_keys.push(key);
7625 x
7626 });
7627 left_gid.push(g);
7628 }
7629 let mut right_gid: Vec<u32> = Vec::with_capacity(r0.len());
7630 for pos in 0..r0.len() {
7631 let key = pack(r0[pos], r1[pos]);
7632 let g = *gid_of.entry(key).or_insert_with(|| {
7633 let x = gid_keys.len() as u32;
7634 gid_keys.push(key);
7635 x
7636 });
7637 right_gid.push(g);
7638 }
7639 let ng = gid_keys.len();
7640 let mut loff = vec![0u32; ng + 1];
7641 for &g in &left_gid {
7642 loff[g as usize + 1] += 1;
7643 }
7644 let mut roff = vec![0u32; ng + 1];
7645 for &g in &right_gid {
7646 roff[g as usize + 1] += 1;
7647 }
7648 for g in 0..ng {
7649 loff[g + 1] += loff[g];
7650 roff[g + 1] += roff[g];
7651 }
7652 let mut lpos = vec![0u32; l0.len()];
7653 let mut lw = loff[..ng].to_vec();
7654 for (i, &g) in left_gid.iter().enumerate() {
7655 let g = g as usize;
7656 lpos[lw[g] as usize] = i as u32;
7657 lw[g] += 1;
7658 }
7659 let mut rpos = vec![0u32; r0.len()];
7660 let mut rw = roff[..ng].to_vec();
7661 for (i, &g) in right_gid.iter().enumerate() {
7662 let g = g as usize;
7663 rpos[rw[g] as usize] = i as u32;
7664 rw[g] += 1;
7665 }
7666 let decode = |packed: u128| -> (i64, i64) {
7668 (((packed >> 64) as u64) as i64, (packed as u64) as i64)
7669 };
7670 let mut order: Vec<u32> = (0..ng as u32).collect();
7671 order.sort_unstable_by_key(|&g| decode(gid_keys[g as usize]));
7672 let mut left_positions = Vec::<Option<usize>>::new();
7673 let mut right_positions = Vec::<Option<usize>>::new();
7674 for &g in &order {
7675 let g = g as usize;
7676 let ls = &lpos[loff[g] as usize..loff[g + 1] as usize];
7677 let rs = &rpos[roff[g] as usize..roff[g + 1] as usize];
7678 match (ls.is_empty(), rs.is_empty()) {
7679 (false, false) => {
7680 for &l in ls {
7681 for &r in rs {
7682 left_positions.push(Some(l as usize));
7683 right_positions.push(Some(r as usize));
7684 }
7685 }
7686 }
7687 (false, true) => {
7688 for &l in ls {
7689 left_positions.push(Some(l as usize));
7690 right_positions.push(None);
7691 }
7692 }
7693 (true, false) => {
7694 for &r in rs {
7695 left_positions.push(None);
7696 right_positions.push(Some(r as usize));
7697 }
7698 }
7699 (true, true) => {}
7700 }
7701 }
7702 return Some((left_positions, right_positions, None));
7703 }
7704
7705 let mut right_map = FxHashMap::<u128, JoinPositionBucket>::with_capacity_and_hasher(
7707 r0.len(),
7708 Default::default(),
7709 );
7710 for pos in 0..r0.len() {
7711 right_map
7712 .entry(pack(r0[pos], r1[pos]))
7713 .or_default()
7714 .push(pos);
7715 }
7716 let is_left = matches!(join_type, JoinType::Left);
7717 let mut left_positions = Vec::<Option<usize>>::new();
7718 let mut right_positions = Vec::<Option<usize>>::new();
7719 for left_pos in 0..l0.len() {
7720 let key = pack(l0[left_pos], l1[left_pos]);
7721 if let Some(matches) = right_map.get(&key) {
7722 for &right_pos in matches {
7723 left_positions.push(Some(left_pos));
7724 right_positions.push(Some(right_pos));
7725 }
7726 } else if is_left {
7727 left_positions.push(Some(left_pos));
7728 right_positions.push(None);
7729 }
7730 }
7731 Some((left_positions, right_positions, None))
7732}
7733
7734fn typed_wide_multi_i64_key_positions(
7748 join_type: JoinType,
7749 left_cols: &[&Column],
7750 right_cols: &[&Column],
7751) -> Option<MergeRowPositions> {
7752 if !matches!(
7753 join_type,
7754 JoinType::Inner | JoinType::Left | JoinType::Outer
7755 ) {
7756 return None;
7757 }
7758 let k = left_cols.len();
7759 if k < 3 || right_cols.len() != k {
7760 return None;
7761 }
7762 let mut ls: Vec<&[i64]> = Vec::with_capacity(k);
7763 let mut rs: Vec<&[i64]> = Vec::with_capacity(k);
7764 for c in 0..k {
7765 ls.push(left_cols[c].as_i64_slice()?);
7766 rs.push(right_cols[c].as_i64_slice()?);
7767 }
7768 let nl = ls[0].len();
7769 let nr = rs[0].len();
7770 if ls.iter().any(|s| s.len() != nl) || rs.iter().any(|s| s.len() != nr) {
7771 return None;
7772 }
7773
7774 let mut lgid: Vec<Vec<u32>> = Vec::with_capacity(k);
7776 let mut rgid: Vec<Vec<u32>> = Vec::with_capacity(k);
7777 let mut cards: Vec<u64> = Vec::with_capacity(k);
7778 for c in 0..k {
7779 let mut m: FxHashMap<i64, u32> =
7780 FxHashMap::with_capacity_and_hasher(nl + nr, Default::default());
7781 let mut next: u32 = 0;
7782 let mut lg = Vec::with_capacity(nl);
7783 for &v in ls[c] {
7784 let g = *m.entry(v).or_insert_with(|| {
7785 let x = next;
7786 next += 1;
7787 x
7788 });
7789 lg.push(g);
7790 }
7791 let mut rg = Vec::with_capacity(nr);
7792 for &v in rs[c] {
7793 let g = *m.entry(v).or_insert_with(|| {
7794 let x = next;
7795 next += 1;
7796 x
7797 });
7798 rg.push(g);
7799 }
7800 cards.push(next as u64);
7801 lgid.push(lg);
7802 rgid.push(rg);
7803 }
7804
7805 let mut bits: Vec<u32> = Vec::with_capacity(k);
7807 let mut total: u32 = 0;
7808 for &card in &cards {
7809 let b = if card <= 1 {
7810 0
7811 } else {
7812 64 - (card - 1).leading_zeros()
7813 };
7814 bits.push(b);
7815 total += b;
7816 }
7817 if total > 127 {
7818 return None;
7819 }
7820
7821 let pack = |gids: &[Vec<u32>], row: usize| -> u128 {
7822 let mut p: u128 = 0;
7823 for c in 0..k {
7824 p = (p << bits[c]) | u128::from(gids[c][row]);
7825 }
7826 p
7827 };
7828
7829 if matches!(join_type, JoinType::Outer) {
7830 let mut gid_of: FxHashMap<u128, u32> =
7831 FxHashMap::with_capacity_and_hasher(nl.saturating_add(nr), Default::default());
7832 let mut gid_tuple: Vec<Vec<i64>> = Vec::new();
7834 let mut left_g: Vec<u32> = Vec::with_capacity(nl);
7835 for (row, _) in ls[0].iter().enumerate().take(nl) {
7836 let key = pack(&lgid, row);
7837 let g = *gid_of.entry(key).or_insert_with(|| {
7838 let x = gid_tuple.len() as u32;
7839 gid_tuple.push((0..k).map(|c| ls[c][row]).collect());
7840 x
7841 });
7842 left_g.push(g);
7843 }
7844 let mut right_g: Vec<u32> = Vec::with_capacity(nr);
7845 for (row, _) in rs[0].iter().enumerate().take(nr) {
7846 let key = pack(&rgid, row);
7847 let g = *gid_of.entry(key).or_insert_with(|| {
7848 let x = gid_tuple.len() as u32;
7849 gid_tuple.push((0..k).map(|c| rs[c][row]).collect());
7850 x
7851 });
7852 right_g.push(g);
7853 }
7854 let ng = gid_tuple.len();
7855 let mut loff = vec![0u32; ng + 1];
7856 for &g in &left_g {
7857 loff[g as usize + 1] += 1;
7858 }
7859 let mut roff = vec![0u32; ng + 1];
7860 for &g in &right_g {
7861 roff[g as usize + 1] += 1;
7862 }
7863 for g in 0..ng {
7864 loff[g + 1] += loff[g];
7865 roff[g + 1] += roff[g];
7866 }
7867 let mut lpos = vec![0u32; nl];
7868 let mut lw = loff[..ng].to_vec();
7869 for (i, &g) in left_g.iter().enumerate() {
7870 let g = g as usize;
7871 lpos[lw[g] as usize] = i as u32;
7872 lw[g] += 1;
7873 }
7874 let mut rpos = vec![0u32; nr];
7875 let mut rw = roff[..ng].to_vec();
7876 for (i, &g) in right_g.iter().enumerate() {
7877 let g = g as usize;
7878 rpos[rw[g] as usize] = i as u32;
7879 rw[g] += 1;
7880 }
7881 let mut order: Vec<u32> = (0..ng as u32).collect();
7882 order.sort_unstable_by(|&a, &b| gid_tuple[a as usize].cmp(&gid_tuple[b as usize]));
7883 let mut left_positions = Vec::<Option<usize>>::new();
7884 let mut right_positions = Vec::<Option<usize>>::new();
7885 for &g in &order {
7886 let g = g as usize;
7887 let lsl = &lpos[loff[g] as usize..loff[g + 1] as usize];
7888 let rsl = &rpos[roff[g] as usize..roff[g + 1] as usize];
7889 match (lsl.is_empty(), rsl.is_empty()) {
7890 (false, false) => {
7891 for &l in lsl {
7892 for &r in rsl {
7893 left_positions.push(Some(l as usize));
7894 right_positions.push(Some(r as usize));
7895 }
7896 }
7897 }
7898 (false, true) => {
7899 for &l in lsl {
7900 left_positions.push(Some(l as usize));
7901 right_positions.push(None);
7902 }
7903 }
7904 (true, false) => {
7905 for &r in rsl {
7906 left_positions.push(None);
7907 right_positions.push(Some(r as usize));
7908 }
7909 }
7910 (true, true) => {}
7911 }
7912 }
7913 return Some((left_positions, right_positions, None));
7914 }
7915
7916 let mut right_map =
7918 FxHashMap::<u128, JoinPositionBucket>::with_capacity_and_hasher(nr, Default::default());
7919 for pos in 0..nr {
7920 right_map.entry(pack(&rgid, pos)).or_default().push(pos);
7921 }
7922 let is_left = matches!(join_type, JoinType::Left);
7923 let mut left_positions = Vec::<Option<usize>>::new();
7924 let mut right_positions = Vec::<Option<usize>>::new();
7925 for left_pos in 0..nl {
7926 let key = pack(&lgid, left_pos);
7927 if let Some(matches) = right_map.get(&key) {
7928 for &right_pos in matches {
7929 left_positions.push(Some(left_pos));
7930 right_positions.push(Some(right_pos));
7931 }
7932 } else if is_left {
7933 left_positions.push(Some(left_pos));
7934 right_positions.push(None);
7935 }
7936 }
7937 Some((left_positions, right_positions, None))
7938}
7939
7940fn bounded_composite_multi_i64_key_positions(
7955 join_type: JoinType,
7956 left_cols: &[&Column],
7957 right_cols: &[&Column],
7958) -> Option<MergeRowPositions> {
7959 if !matches!(join_type, JoinType::Inner | JoinType::Left) {
7960 return None;
7961 }
7962 let k = left_cols.len();
7963 if k < 3 || right_cols.len() != k {
7964 return None;
7965 }
7966 let mut ls: Vec<&[i64]> = Vec::with_capacity(k);
7967 let mut rs: Vec<&[i64]> = Vec::with_capacity(k);
7968 for c in 0..k {
7969 ls.push(left_cols[c].as_i64_slice()?);
7970 rs.push(right_cols[c].as_i64_slice()?);
7971 }
7972 let nl = ls[0].len();
7973 let nr = rs[0].len();
7974 if ls.iter().any(|s| s.len() != nl) || rs.iter().any(|s| s.len() != nr) {
7975 return None;
7976 }
7977 if nl == 0 || nr == 0 {
7978 return None;
7981 }
7982
7983 let mut mins = vec![0i64; k];
7986 let mut ranges = vec![0u128; k];
7987 for c in 0..k {
7988 let mut mn = i64::MAX;
7989 let mut mx = i64::MIN;
7990 for &v in ls[c] {
7991 if v < mn {
7992 mn = v;
7993 }
7994 if v > mx {
7995 mx = v;
7996 }
7997 }
7998 for &v in rs[c] {
7999 if v < mn {
8000 mn = v;
8001 }
8002 if v > mx {
8003 mx = v;
8004 }
8005 }
8006 mins[c] = mn;
8007 ranges[c] = (mx as i128 - mn as i128 + 1) as u128;
8008 }
8009 let mut strides = vec![1i64; k];
8011 let mut acc: u128 = 1;
8012 for c in 0..k {
8013 strides[c] = acc as i64;
8014 acc = acc.checked_mul(ranges[c])?;
8015 if acc > i64::MAX as u128 {
8016 return None;
8017 }
8018 }
8019 let comp = |s: &[&[i64]], row: usize| -> i64 {
8020 let mut p: i64 = 0;
8021 for c in 0..k {
8022 p += (s[c][row] - mins[c]) * strides[c];
8024 }
8025 p
8026 };
8027 let lcomp: Vec<i64> = (0..nl).map(|r| comp(&ls, r)).collect();
8028 let rcomp: Vec<i64> = (0..nr).map(|r| comp(&rs, r)).collect();
8029
8030 if matches!(join_type, JoinType::Inner) {
8031 let (lp, rp) = hash_i64_inner_positions_slices(&lcomp, &rcomp);
8032 return Some((
8033 lp.into_iter().map(Some).collect(),
8034 rp.into_iter().map(Some).collect(),
8035 None,
8036 ));
8037 }
8038
8039 let mut right_map =
8042 FxHashMap::<i64, JoinPositionBucket>::with_capacity_and_hasher(nr, Default::default());
8043 for (pos, &key) in rcomp.iter().enumerate() {
8044 right_map.entry(key).or_default().push(pos);
8045 }
8046 let mut left_positions = Vec::<Option<usize>>::with_capacity(nl);
8047 let mut right_positions = Vec::<Option<usize>>::with_capacity(nl);
8048 for (left_pos, &key) in lcomp.iter().enumerate() {
8049 if let Some(matches) = right_map.get(&key) {
8050 for &right_pos in matches {
8051 left_positions.push(Some(left_pos));
8052 right_positions.push(Some(right_pos));
8053 }
8054 } else {
8055 left_positions.push(Some(left_pos));
8056 right_positions.push(None);
8057 }
8058 }
8059 Some((left_positions, right_positions, None))
8060}
8061
8062fn dense_packed_int64_inner_positions(
8063 left_cols: &[&Column],
8064 right_cols: &[&Column],
8065) -> Option<(Vec<usize>, Vec<usize>)> {
8066 let k = left_cols.len();
8067 if k == 0 || k != right_cols.len() {
8068 return None;
8069 }
8070
8071 let left_slices: Vec<&[i64]> = left_cols
8072 .iter()
8073 .map(|c| c.as_i64_slice())
8074 .collect::<Option<Vec<_>>>()?;
8075 let right_slices: Vec<&[i64]> = right_cols
8076 .iter()
8077 .map(|c| c.as_i64_slice())
8078 .collect::<Option<Vec<_>>>()?;
8079
8080 let n_left = left_slices[0].len();
8081 let n_right = right_slices[0].len();
8082 if n_left == 0 || n_right == 0 {
8083 return Some((Vec::new(), Vec::new()));
8084 }
8085
8086 let mut mins = vec![0i64; k];
8088 let mut strides = vec![1i128; k];
8089 let mut total: i128 = 1;
8090 for c in 0..k {
8091 let mut mn = right_slices[c][0];
8092 let mut mx = right_slices[c][0];
8093 for &v in left_slices[c].iter().chain(right_slices[c].iter()) {
8094 if v < mn {
8095 mn = v;
8096 }
8097 if v > mx {
8098 mx = v;
8099 }
8100 }
8101 mins[c] = mn;
8102 let range = (mx as i128) - (mn as i128) + 1;
8103 strides[c] = total;
8104 total = total.checked_mul(range)?;
8105 if total > (1i128 << 24) {
8108 return None;
8109 }
8110 }
8111 if total > 16 * ((n_left + n_right) as i128) {
8112 return None;
8113 }
8114
8115 let pack = |slices: &[&[i64]], n: usize| -> Vec<i64> {
8116 (0..n)
8117 .map(|row| {
8118 let mut acc: i128 = 0;
8119 for c in 0..k {
8120 acc += ((slices[c][row] as i128) - (mins[c] as i128)) * strides[c];
8121 }
8122 acc as i64
8123 })
8124 .collect()
8125 };
8126 let packed_left = pack(&left_slices, n_left);
8127 let packed_right = pack(&right_slices, n_right);
8128
8129 dense_i64_inner_positions_slices(&packed_left, &packed_right)
8130}
8131
8132fn merge_single_key_inner_unsorted(
8133 left: &fp_frame::DataFrame,
8134 right: &fp_frame::DataFrame,
8135 left_on: &[&str],
8136 right_on: &[&str],
8137 left_key_columns: &[&Column],
8138 right_key_columns: &[&Column],
8139 suffixes: &ResolvedMergeSuffixes,
8140) -> Result<MergedDataFrame, JoinError> {
8141 debug_assert_eq!(left_key_columns.len(), 1);
8142 debug_assert_eq!(right_key_columns.len(), 1);
8143
8144 if left_on[0] == right_on[0]
8145 && ordered_identity_int64_keys_match(left_key_columns[0], right_key_columns[0])
8146 {
8147 return build_single_key_ordered_identity_inner_merge_output(
8148 left, right, left_on, right_on, suffixes,
8149 );
8150 }
8151 if let Some((left_positions, right_positions)) =
8152 ordered_unique_int64_inner_positions(left_key_columns[0], right_key_columns[0])
8153 {
8154 return build_single_key_inner_merge_output(
8155 left,
8156 right,
8157 left_on,
8158 right_on,
8159 &left_positions,
8160 &right_positions,
8161 suffixes,
8162 );
8163 }
8164
8165 if let Some(merged) = build_single_key_dense_i64_inner_merge_output(
8166 left,
8167 right,
8168 left_on,
8169 right_on,
8170 left_key_columns[0],
8171 right_key_columns[0],
8172 FusedInt64MergeOptions {
8173 suffixes,
8174 require_all_left_keys_matched: false,
8175 },
8176 )? {
8177 return Ok(merged);
8178 }
8179
8180 if let Some((left_positions, right_positions)) =
8186 temporal_i64_inner_positions(left_key_columns[0], right_key_columns[0])
8187 {
8188 return build_single_key_inner_merge_output(
8189 left,
8190 right,
8191 left_on,
8192 right_on,
8193 &left_positions,
8194 &right_positions,
8195 suffixes,
8196 );
8197 }
8198
8199 if let Some((left_positions, right_positions)) =
8202 dense_int64_inner_positions(left_key_columns[0], right_key_columns[0])
8203 {
8204 return build_single_key_inner_merge_output(
8205 left,
8206 right,
8207 left_on,
8208 right_on,
8209 &left_positions,
8210 &right_positions,
8211 suffixes,
8212 );
8213 }
8214 if let Some((left_positions, right_positions)) =
8215 hash_int64_inner_positions(left_key_columns[0], right_key_columns[0])
8216 {
8217 return build_single_key_inner_merge_output(
8218 left,
8219 right,
8220 left_on,
8221 right_on,
8222 &left_positions,
8223 &right_positions,
8224 suffixes,
8225 );
8226 }
8227
8228 if let Some(position_plan) =
8229 ordered_unique_utf8_inner_position_plan(left_key_columns[0], right_key_columns[0])
8230 {
8231 return match position_plan {
8232 InnerPositionPlan::Gather {
8233 left_positions,
8234 right_positions,
8235 } => build_single_key_inner_merge_output(
8236 left,
8237 right,
8238 left_on,
8239 right_on,
8240 &left_positions,
8241 &right_positions,
8242 suffixes,
8243 ),
8244 InnerPositionPlan::ContiguousRanges {
8245 left_start,
8246 right_start,
8247 len,
8248 } => build_single_key_inner_merge_output_with_selections(
8249 left,
8250 right,
8251 left_on,
8252 right_on,
8253 PositionSelection::ContiguousRange {
8254 start: left_start,
8255 len,
8256 },
8257 PositionSelection::ContiguousRange {
8258 start: right_start,
8259 len,
8260 },
8261 suffixes,
8262 ),
8263 };
8264 }
8265
8266 if let Some((left_positions, right_positions)) =
8270 contiguous_utf8_inner_positions(left_key_columns[0], right_key_columns[0])
8271 {
8272 return build_single_key_inner_merge_output(
8273 left,
8274 right,
8275 left_on,
8276 right_on,
8277 &left_positions,
8278 &right_positions,
8279 suffixes,
8280 );
8281 }
8282 if let Some((left_positions, right_positions)) =
8283 scalar_utf8_inner_positions(left_key_columns[0], right_key_columns[0])
8284 {
8285 return build_single_key_inner_merge_output(
8286 left,
8287 right,
8288 left_on,
8289 right_on,
8290 &left_positions,
8291 &right_positions,
8292 suffixes,
8293 );
8294 }
8295
8296 let left_keys = collect_single_join_keys(left_key_columns[0]);
8297 let right_keys = collect_single_join_keys(right_key_columns[0]);
8298 let mut right_map =
8299 FxHashMap::<&JoinKeyComponent, JoinPositionBucket>::with_capacity_and_hasher(
8300 right_keys.len(),
8301 Default::default(),
8302 );
8303 for (pos, key) in right_keys.iter().enumerate() {
8304 right_map.entry(key).or_default().push(pos);
8305 }
8306
8307 let mut left_positions = Vec::<usize>::with_capacity(left_keys.len().min(right_keys.len()));
8308 let mut right_positions = Vec::<usize>::with_capacity(left_positions.capacity());
8309 for (left_pos, key) in left_keys.iter().enumerate() {
8310 if let Some(matches) = right_map.get(key) {
8311 for &right_pos in matches {
8312 left_positions.push(left_pos);
8313 right_positions.push(right_pos);
8314 }
8315 }
8316 }
8317
8318 build_single_key_inner_merge_output(
8319 left,
8320 right,
8321 left_on,
8322 right_on,
8323 &left_positions,
8324 &right_positions,
8325 suffixes,
8326 )
8327}
8328
8329pub fn merge_dataframes_on_with(
8337 left: &fp_frame::DataFrame,
8338 right: &fp_frame::DataFrame,
8339 left_on: &[&str],
8340 right_on: &[&str],
8341 join_type: JoinType,
8342) -> Result<MergedDataFrame, JoinError> {
8343 merge_dataframes_on_with_options(
8344 left,
8345 right,
8346 left_on,
8347 right_on,
8348 join_type,
8349 MergeExecutionOptions::default(),
8350 )
8351}
8352
8353pub fn merge_dataframes_on_with_options(
8355 left: &fp_frame::DataFrame,
8356 right: &fp_frame::DataFrame,
8357 left_on: &[&str],
8358 right_on: &[&str],
8359 join_type: JoinType,
8360 options: MergeExecutionOptions,
8361) -> Result<MergedDataFrame, JoinError> {
8362 let MergeExecutionOptions {
8363 indicator_name,
8364 validate_mode,
8365 suffixes,
8366 sort,
8367 } = options;
8368 let indicator_name = resolve_merge_indicator_name(indicator_name.as_deref())?;
8369 let suffixes = resolve_merge_suffixes(suffixes);
8370
8371 if matches!(join_type, JoinType::Cross) {
8372 if let Some(validate_mode) = validate_mode
8373 && !matches!(validate_mode, MergeValidateMode::ManyToMany)
8374 {
8375 return Err(JoinError::Frame(FrameError::CompatibilityRejected(
8376 format!(
8377 "merge validate='{}' is not supported for cross join",
8378 validate_mode.as_str()
8379 ),
8380 )));
8381 }
8382 return merge_dataframes_cross(left, right, indicator_name.as_deref(), &suffixes);
8383 }
8384
8385 if left_on.is_empty() || right_on.is_empty() {
8386 return Err(JoinError::Frame(FrameError::CompatibilityRejected(
8387 "merge requires at least one key column".to_owned(),
8388 )));
8389 }
8390 if left_on.len() != right_on.len() {
8391 return Err(JoinError::Frame(FrameError::CompatibilityRejected(
8392 "merge requires left_on and right_on key lists with equal length".to_owned(),
8393 )));
8394 }
8395
8396 let mut seen_left_keys = HashSet::new();
8397 for key_name in left_on {
8398 if !seen_left_keys.insert(*key_name) {
8399 return Err(JoinError::Frame(FrameError::CompatibilityRejected(
8400 format!("merge left key column '{key_name}' is duplicated"),
8401 )));
8402 }
8403 }
8404 let mut seen_right_keys = HashSet::new();
8405 for key_name in right_on {
8406 if !seen_right_keys.insert(*key_name) {
8407 return Err(JoinError::Frame(FrameError::CompatibilityRejected(
8408 format!("merge right key column '{key_name}' is duplicated"),
8409 )));
8410 }
8411 }
8412
8413 let left_key_columns = collect_join_key_columns(left, left_on, "left")?;
8414 let right_key_columns = collect_join_key_columns(right, right_on, "right")?;
8415 let validate_allows_fast_positions = validate_mode_allows_fast_positions(validate_mode);
8416
8417 if matches!(join_type, JoinType::Inner)
8418 && left_on.len() == 1
8419 && right_on.len() == 1
8420 && !sort
8421 && indicator_name.is_none()
8422 && validate_allows_fast_positions
8423 {
8424 return merge_single_key_inner_unsorted(
8425 left,
8426 right,
8427 left_on,
8428 right_on,
8429 &left_key_columns,
8430 &right_key_columns,
8431 &suffixes,
8432 );
8433 }
8434 if matches!(join_type, JoinType::Left)
8435 && left_on.len() == 1
8436 && right_on.len() == 1
8437 && !sort
8438 && indicator_name.is_none()
8439 && validate_allows_fast_positions
8440 && let Some(right_positions) =
8441 ordered_unique_int64_left_match_positions(left_key_columns[0], right_key_columns[0])
8442 {
8443 return build_single_key_ordered_unique_left_merge_output(
8444 left,
8445 right,
8446 left_on,
8447 right_on,
8448 &right_positions,
8449 &suffixes,
8450 );
8451 }
8452 if matches!(join_type, JoinType::Left)
8453 && left_on.len() == 1
8454 && right_on.len() == 1
8455 && !sort
8456 && indicator_name.is_none()
8457 && validate_allows_fast_positions
8458 && let Some((left_positions, right_positions)) =
8459 temporal_i64_left_positions(left_key_columns[0], right_key_columns[0])
8460 {
8461 return build_single_key_dense_left_merge_output(
8462 left,
8463 right,
8464 left_on,
8465 right_on,
8466 &left_positions,
8467 &right_positions,
8468 &suffixes,
8469 );
8470 }
8471 if matches!(join_type, JoinType::Left)
8472 && left_on.len() == 1
8473 && right_on.len() == 1
8474 && !sort
8475 && indicator_name.is_none()
8476 && validate_allows_fast_positions
8477 && let Some(merged) = build_single_key_dense_cycle_i64_left_merge_output(
8478 left,
8479 right,
8480 left_on,
8481 right_on,
8482 left_key_columns[0],
8483 right_key_columns[0],
8484 &suffixes,
8485 )?
8486 {
8487 return Ok(merged);
8488 }
8489 if matches!(join_type, JoinType::Left)
8490 && left_on.len() == 1
8491 && right_on.len() == 1
8492 && !sort
8493 && indicator_name.is_none()
8494 && validate_allows_fast_positions
8495 && let Some(merged) = build_single_key_dense_i64_inner_merge_output(
8496 left,
8497 right,
8498 left_on,
8499 right_on,
8500 left_key_columns[0],
8501 right_key_columns[0],
8502 FusedInt64MergeOptions {
8503 suffixes: &suffixes,
8504 require_all_left_keys_matched: true,
8505 },
8506 )?
8507 {
8508 return Ok(merged);
8509 }
8510 if matches!(join_type, JoinType::Left)
8511 && left_on.len() == 1
8512 && right_on.len() == 1
8513 && !sort
8514 && indicator_name.is_none()
8515 && validate_allows_fast_positions
8516 && let Some(merged) = build_single_key_dense_i64_left_merge_output(
8517 left,
8518 right,
8519 left_on,
8520 right_on,
8521 left_key_columns[0],
8522 right_key_columns[0],
8523 &suffixes,
8524 )?
8525 {
8526 return Ok(merged);
8527 }
8528 if matches!(join_type, JoinType::Left)
8529 && left_on.len() == 1
8530 && right_on.len() == 1
8531 && !sort
8532 && indicator_name.is_none()
8533 && validate_allows_fast_positions
8534 && let Some((left_positions, right_positions)) =
8535 dense_int64_left_positions(left_key_columns[0], right_key_columns[0])
8536 {
8537 return build_single_key_dense_left_merge_output(
8538 left,
8539 right,
8540 left_on,
8541 right_on,
8542 &left_positions,
8543 &right_positions,
8544 &suffixes,
8545 );
8546 }
8547 if matches!(join_type, JoinType::Left)
8548 && left_on.len() == 1
8549 && right_on.len() == 1
8550 && !sort
8551 && indicator_name.is_none()
8552 && validate_allows_fast_positions
8553 && let Some((left_positions, right_positions)) =
8554 hash_int64_left_positions(left_key_columns[0], right_key_columns[0])
8555 {
8556 return build_single_key_dense_left_merge_output(
8557 left,
8558 right,
8559 left_on,
8560 right_on,
8561 &left_positions,
8562 &right_positions,
8563 &suffixes,
8564 );
8565 }
8566 if matches!(join_type, JoinType::Left)
8567 && left_on.len() == 1
8568 && right_on.len() == 1
8569 && !sort
8570 && indicator_name.is_none()
8571 && validate_allows_fast_positions
8572 && let Some((left_positions, right_positions)) =
8573 contiguous_utf8_left_positions(left_key_columns[0], right_key_columns[0])
8574 {
8575 return build_single_key_dense_left_merge_output(
8576 left,
8577 right,
8578 left_on,
8579 right_on,
8580 &left_positions,
8581 &right_positions,
8582 &suffixes,
8583 );
8584 }
8585 if matches!(join_type, JoinType::Left)
8586 && left_on.len() == 1
8587 && right_on.len() == 1
8588 && !sort
8589 && indicator_name.is_none()
8590 && validate_allows_fast_positions
8591 && let Some((left_positions, right_positions)) =
8592 scalar_utf8_left_positions(left_key_columns[0], right_key_columns[0])
8593 {
8594 return build_single_key_dense_left_merge_output(
8595 left,
8596 right,
8597 left_on,
8598 right_on,
8599 &left_positions,
8600 &right_positions,
8601 &suffixes,
8602 );
8603 }
8604 if matches!(join_type, JoinType::Right)
8605 && left_on.len() == 1
8606 && right_on.len() == 1
8607 && !sort
8608 && indicator_name.is_none()
8609 && validate_allows_fast_positions
8610 && let Some(left_positions) =
8611 ordered_unique_int64_right_match_positions(left_key_columns[0], right_key_columns[0])
8612 {
8613 return build_single_key_ordered_unique_right_merge_output(
8614 left,
8615 right,
8616 left_on,
8617 right_on,
8618 &left_positions,
8619 &suffixes,
8620 );
8621 }
8622 if matches!(join_type, JoinType::Right)
8623 && left_on.len() == 1
8624 && right_on.len() == 1
8625 && !sort
8626 && indicator_name.is_none()
8627 && validate_allows_fast_positions
8628 && let Some(left_positions) = ordered_unique_temporal_i64_right_match_positions(
8629 left_key_columns[0],
8630 right_key_columns[0],
8631 )
8632 {
8633 return build_single_key_ordered_unique_right_merge_output(
8634 left,
8635 right,
8636 left_on,
8637 right_on,
8638 &left_positions,
8639 &suffixes,
8640 );
8641 }
8642 if matches!(join_type, JoinType::Right)
8643 && left_on.len() == 1
8644 && right_on.len() == 1
8645 && !sort
8646 && indicator_name.is_none()
8647 && validate_allows_fast_positions
8648 && let Some(merged) = build_single_key_dense_i64_right_all_matched_merge_output(
8649 left,
8650 right,
8651 left_on,
8652 right_on,
8653 left_key_columns[0],
8654 right_key_columns[0],
8655 &suffixes,
8656 )?
8657 {
8658 return Ok(merged);
8659 }
8660 if matches!(join_type, JoinType::Right)
8661 && left_on.len() == 1
8662 && right_on.len() == 1
8663 && !sort
8664 && indicator_name.is_none()
8665 && validate_allows_fast_positions
8666 && let Some(merged) = build_single_key_dense_i64_right_merge_output(
8667 left,
8668 right,
8669 left_on,
8670 right_on,
8671 left_key_columns[0],
8672 right_key_columns[0],
8673 &suffixes,
8674 )?
8675 {
8676 return Ok(merged);
8677 }
8678 if matches!(join_type, JoinType::Right)
8679 && left_on.len() == 1
8680 && right_on.len() == 1
8681 && !sort
8682 && indicator_name.is_none()
8683 && validate_allows_fast_positions
8684 && let Some((left_positions, right_positions)) =
8685 dense_int64_right_positions(left_key_columns[0], right_key_columns[0])
8686 {
8687 return build_single_key_dense_right_merge_output(
8688 left,
8689 right,
8690 left_on,
8691 right_on,
8692 &left_positions,
8693 &right_positions,
8694 &suffixes,
8695 );
8696 }
8697 if matches!(join_type, JoinType::Outer)
8698 && left_on.len() == 1
8699 && right_on.len() == 1
8700 && !sort
8701 && indicator_name.is_none()
8702 && validate_allows_fast_positions
8703 && let Some((left_positions, right_positions)) =
8704 ordered_unique_temporal_i64_outer_positions(
8705 left_key_columns[0],
8706 right_key_columns[0],
8707 )
8708 {
8709 return build_single_key_ordered_unique_outer_merge_output(
8710 left,
8711 right,
8712 left_on,
8713 right_on,
8714 &left_positions,
8715 &right_positions,
8716 &suffixes,
8717 );
8718 }
8719 if matches!(join_type, JoinType::Outer)
8720 && left_on.len() == 1
8721 && right_on.len() == 1
8722 && !sort
8723 && indicator_name.is_none()
8724 && validate_allows_fast_positions
8725 && let Some((left_positions, right_positions)) =
8726 ordered_unique_int64_outer_positions(left_key_columns[0], right_key_columns[0])
8727 {
8728 return build_single_key_ordered_unique_outer_merge_output(
8729 left,
8730 right,
8731 left_on,
8732 right_on,
8733 &left_positions,
8734 &right_positions,
8735 &suffixes,
8736 );
8737 }
8738 if matches!(join_type, JoinType::Outer)
8739 && left_on.len() == 1
8740 && right_on.len() == 1
8741 && !sort
8742 && indicator_name.is_none()
8743 && validate_allows_fast_positions
8744 && let Some(merged) = build_single_key_dense_i64_outer_all_matched_merge_output(
8745 left,
8746 right,
8747 left_on,
8748 right_on,
8749 left_key_columns[0],
8750 right_key_columns[0],
8751 &suffixes,
8752 )?
8753 {
8754 return Ok(merged);
8755 }
8756 if matches!(join_type, JoinType::Outer)
8757 && left_on.len() == 1
8758 && right_on.len() == 1
8759 && !sort
8760 && indicator_name.is_none()
8761 && validate_allows_fast_positions
8762 && let Some(merged) = build_single_key_dense_i64_outer_merge_output(
8763 left,
8764 right,
8765 left_on,
8766 right_on,
8767 left_key_columns[0],
8768 right_key_columns[0],
8769 &suffixes,
8770 )?
8771 {
8772 return Ok(merged);
8773 }
8774 if matches!(join_type, JoinType::Outer)
8775 && left_on.len() == 1
8776 && right_on.len() == 1
8777 && !sort
8778 && indicator_name.is_none()
8779 && validate_allows_fast_positions
8780 && let Some((left_positions, right_positions)) =
8781 dense_int64_outer_positions(left_key_columns[0], right_key_columns[0])
8782 {
8783 return build_single_key_ordered_unique_outer_merge_output(
8784 left,
8785 right,
8786 left_on,
8787 right_on,
8788 &left_positions,
8789 &right_positions,
8790 &suffixes,
8791 );
8792 }
8793 if matches!(join_type, JoinType::Outer)
8794 && left_on.len() == 1
8795 && right_on.len() == 1
8796 && !sort
8797 && indicator_name.is_none()
8798 && validate_allows_fast_positions
8799 && let Some((left_positions, right_positions)) =
8800 hash_int64_outer_positions(left_key_columns[0], right_key_columns[0])
8801 {
8802 return build_single_key_ordered_unique_outer_merge_output(
8803 left,
8804 right,
8805 left_on,
8806 right_on,
8807 &left_positions,
8808 &right_positions,
8809 &suffixes,
8810 );
8811 }
8812 if matches!(join_type, JoinType::Outer)
8813 && left_on.len() == 1
8814 && right_on.len() == 1
8815 && !sort
8816 && indicator_name.is_none()
8817 && validate_allows_fast_positions
8818 && let Some(merged) = build_single_key_fixed_decimal_utf8_outer_all_matched_merge_output(
8819 left,
8820 right,
8821 left_on,
8822 right_on,
8823 left_key_columns[0],
8824 right_key_columns[0],
8825 &suffixes,
8826 )?
8827 {
8828 return Ok(merged);
8829 }
8830 if matches!(join_type, JoinType::Outer)
8831 && left_on.len() == 1
8832 && right_on.len() == 1
8833 && !sort
8834 && indicator_name.is_none()
8835 && validate_allows_fast_positions
8836 && let Some((left_positions, right_positions)) =
8837 contiguous_utf8_outer_positions(left_key_columns[0], right_key_columns[0])
8838 {
8839 return build_single_key_ordered_unique_outer_merge_output(
8840 left,
8841 right,
8842 left_on,
8843 right_on,
8844 &left_positions,
8845 &right_positions,
8846 &suffixes,
8847 );
8848 }
8849 if matches!(join_type, JoinType::Outer)
8850 && left_on.len() == 1
8851 && right_on.len() == 1
8852 && !sort
8853 && indicator_name.is_none()
8854 && validate_allows_fast_positions
8855 && let Some((left_positions, right_positions)) =
8856 scalar_utf8_outer_positions(left_key_columns[0], right_key_columns[0])
8857 {
8858 return build_single_key_ordered_unique_outer_merge_output(
8859 left,
8860 right,
8861 left_on,
8862 right_on,
8863 &left_positions,
8864 &right_positions,
8865 &suffixes,
8866 );
8867 }
8868
8869 let needs_key_order = sort || matches!(join_type, JoinType::Outer);
8870
8871 let packed_inner = if matches!(join_type, JoinType::Inner)
8877 && !sort
8878 && validate_allows_fast_positions
8879 && indicator_name.is_none()
8880 {
8881 dense_packed_int64_inner_positions(&left_key_columns, &right_key_columns)
8882 } else {
8883 None
8884 };
8885
8886 let typed_two_key = if !sort
8890 && indicator_name.is_none()
8891 && validate_allows_fast_positions
8892 && packed_inner.is_none()
8893 {
8894 typed_wide_two_i64_key_positions(join_type, &left_key_columns, &right_key_columns)
8895 } else {
8896 None
8897 };
8898
8899 let composite_multi_key = if !sort
8904 && indicator_name.is_none()
8905 && validate_allows_fast_positions
8906 && packed_inner.is_none()
8907 && typed_two_key.is_none()
8908 {
8909 bounded_composite_multi_i64_key_positions(join_type, &left_key_columns, &right_key_columns)
8910 } else {
8911 None
8912 };
8913
8914 let typed_multi_key = if !sort
8917 && indicator_name.is_none()
8918 && validate_allows_fast_positions
8919 && packed_inner.is_none()
8920 && typed_two_key.is_none()
8921 && composite_multi_key.is_none()
8922 {
8923 typed_wide_multi_i64_key_positions(join_type, &left_key_columns, &right_key_columns)
8924 } else {
8925 None
8926 };
8927
8928 let (left_positions, right_positions, _out_row_keys): MergeRowPositions =
8929 if let Some((lp, rp)) = packed_inner {
8930 (
8931 lp.into_iter().map(Some).collect(),
8932 rp.into_iter().map(Some).collect(),
8933 None,
8934 )
8935 } else if let Some(typed) = typed_two_key {
8936 typed
8937 } else if let Some(typed) = composite_multi_key {
8938 typed
8939 } else if let Some(typed) = typed_multi_key {
8940 typed
8941 } else {
8942 let left_keys = collect_composite_keys(&left_key_columns);
8944 let right_keys = collect_composite_keys(&right_key_columns);
8945 if let Some(validate_mode) = validate_mode {
8946 validate_merge_cardinality(validate_mode, &left_keys, &right_keys)?;
8947 }
8948
8949 let right_map = if matches!(
8951 join_type,
8952 JoinType::Inner | JoinType::Left | JoinType::Outer | JoinType::Right
8953 ) {
8954 let mut m =
8955 FxHashMap::<&CompositeJoinKey, JoinPositionBucket>::with_capacity_and_hasher(
8956 right_keys.len(),
8957 Default::default(),
8958 );
8959 for (pos, key) in right_keys.iter().enumerate() {
8960 m.entry(key).or_default().push(pos);
8961 }
8962 Some(m)
8963 } else {
8964 None
8965 };
8966
8967 let left_map = if matches!(join_type, JoinType::Outer) {
8970 let mut m =
8971 FxHashMap::<&CompositeJoinKey, JoinPositionBucket>::with_capacity_and_hasher(
8972 left_keys.len(),
8973 Default::default(),
8974 );
8975 for (pos, key) in left_keys.iter().enumerate() {
8976 m.entry(key).or_default().push(pos);
8977 }
8978 Some(m)
8979 } else {
8980 None
8981 };
8982
8983 let row_capacity = match join_type {
8985 JoinType::Inner => left_keys.len().min(right_keys.len()),
8986 JoinType::Left => left_keys.len(),
8987 JoinType::Right => right_keys.len(),
8988 JoinType::Outer => left_keys.len().saturating_add(right_keys.len()),
8989 JoinType::Cross => left_keys.len().saturating_mul(right_keys.len()),
8990 };
8991 let mut left_positions = Vec::<Option<usize>>::with_capacity(row_capacity);
8992 let mut right_positions = Vec::<Option<usize>>::with_capacity(row_capacity);
8993 let mut out_row_keys: Option<Vec<CompositeJoinKey>> = None;
8997
8998 match join_type {
8999 JoinType::Inner | JoinType::Left | JoinType::Outer => {
9000 let right_map = right_map
9001 .as_ref()
9002 .expect("right_map required for Inner, Left, and Outer joins");
9003 for (left_pos, key) in left_keys.iter().enumerate() {
9004 if let Some(matches) = right_map.get(key) {
9005 for &right_pos in matches {
9006 push_merge_row_key(&mut out_row_keys, key);
9007 left_positions.push(Some(left_pos));
9008 right_positions.push(Some(right_pos));
9009 }
9010 continue;
9011 }
9012
9013 if matches!(join_type, JoinType::Left | JoinType::Outer) {
9014 push_merge_row_key(&mut out_row_keys, key);
9015 left_positions.push(Some(left_pos));
9016 right_positions.push(None);
9017 }
9018 }
9019
9020 if matches!(join_type, JoinType::Outer) {
9021 let left_map = left_map.as_ref().expect("left_map required for Outer join");
9022 for (right_pos, key) in right_keys.iter().enumerate() {
9023 if !left_map.contains_key(key) {
9024 push_merge_row_key(&mut out_row_keys, key);
9025 left_positions.push(None);
9026 right_positions.push(Some(right_pos));
9027 }
9028 }
9029 }
9030 }
9031 JoinType::Right => {
9032 let right_map = right_map
9042 .as_ref()
9043 .expect("right_map required for Right join");
9044 let mut left_by_right: Vec<Vec<usize>> = vec![Vec::new(); right_keys.len()];
9045 for (left_pos, key) in left_keys.iter().enumerate() {
9046 if let Some(right_rows) = right_map.get(key) {
9047 for &right_pos in right_rows {
9048 left_by_right[right_pos].push(left_pos);
9049 }
9050 }
9051 }
9052 for (right_pos, key) in right_keys.iter().enumerate() {
9053 let lefts = &left_by_right[right_pos];
9054 if lefts.is_empty() {
9055 push_merge_row_key(&mut out_row_keys, key);
9056 left_positions.push(None);
9057 right_positions.push(Some(right_pos));
9058 } else {
9059 for &left_pos in lefts {
9060 push_merge_row_key(&mut out_row_keys, key);
9061 left_positions.push(Some(left_pos));
9062 right_positions.push(Some(right_pos));
9063 }
9064 }
9065 }
9066 }
9067 JoinType::Cross => {
9068 return Err(JoinError::Frame(FrameError::CompatibilityRejected(
9069 "cross join must be handled by merge_dataframes_cross".to_owned(),
9070 )));
9071 }
9072 }
9073
9074 if needs_key_order {
9077 sort_merge_rows_by_join_keys(
9078 &left_keys,
9079 &right_keys,
9080 &mut left_positions,
9081 &mut right_positions,
9082 );
9083 }
9084 (left_positions, right_positions, out_row_keys)
9085 };
9086
9087 let all_positions_present = matches!(join_type, JoinType::Inner)
9088 || (matches!(
9089 join_type,
9090 JoinType::Left | JoinType::Right | JoinType::Outer
9091 ) && left_positions.iter().all(Option::is_some)
9092 && right_positions.iter().all(Option::is_some));
9093 let all_present_take_positions = all_positions_present.then(|| {
9094 let left = left_positions
9095 .iter()
9096 .map(|position| position.expect("all-present join emits left positions for every row"))
9097 .collect::<Vec<_>>();
9098 let right = right_positions
9099 .iter()
9100 .map(|position| position.expect("all-present join emits right positions for every row"))
9101 .collect::<Vec<_>>();
9102 (left, right)
9103 });
9104 let all_present_left_positions = all_present_take_positions
9105 .as_ref()
9106 .map(|(positions, _)| positions.as_slice());
9107 let all_present_right_positions = all_present_take_positions
9108 .as_ref()
9109 .map(|(_, positions)| positions.as_slice());
9110
9111 let n = left_positions.len();
9113 let index = Index::new_known_unique_int64_unit_range(0, n);
9115 let mut columns = std::collections::BTreeMap::new();
9116 let mut column_order: Vec<String> = Vec::new();
9117
9118 let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
9120 let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
9121 let left_key_name_set: HashSet<&str> = left_on.iter().copied().collect();
9122 let right_key_name_set: HashSet<&str> = right_on.iter().copied().collect();
9123
9124 let mut shared_name_positions = HashMap::<&str, (usize, usize)>::new();
9126 for (idx, (left_key_name, right_key_name)) in left_on.iter().zip(right_on.iter()).enumerate() {
9127 if left_key_name == right_key_name {
9128 shared_name_positions.insert(*left_key_name, (idx, idx));
9129 }
9130 }
9131 let shared_key_names = shared_name_positions
9132 .keys()
9133 .copied()
9134 .collect::<HashSet<&str>>();
9135 let overlapping_names =
9136 collect_overlapping_column_names(&left_col_names, &right_col_names, &shared_key_names);
9137 ensure_merge_suffixes_for_overlaps(&overlapping_names, &suffixes)?;
9138
9139 for name in left.column_names() {
9142 let col = left
9143 .columns()
9144 .get(name)
9145 .expect("left column listed in column_names must exist");
9146 if left_key_name_set.contains(name.as_str()) {
9147 if let Some((left_key_idx, right_key_idx)) = shared_name_positions.get(name.as_str()) {
9148 let left_key_col = left_key_columns[*left_key_idx];
9151 let key_column = if let Some(positions) = all_present_left_positions {
9152 take_positions_typed(left_key_col, positions)
9153 } else {
9154 let right_key_col = right_key_columns[*right_key_idx];
9155 coalesce_utf8_contiguous_key_column(
9156 left_key_col,
9157 right_key_col,
9158 &left_positions,
9159 &right_positions,
9160 )
9161 .map(Ok)
9162 .unwrap_or_else(|| {
9163 let values = left_positions
9164 .iter()
9165 .zip(right_positions.iter())
9166 .map(|(left_pos, right_pos)| match (left_pos, right_pos) {
9167 (Some(pos), _) => left_key_col.values()[*pos].clone(),
9168 (None, Some(pos)) => right_key_col.values()[*pos].clone(),
9169 (None, None) => fp_types::Scalar::Null(fp_types::NullKind::Null),
9170 })
9171 .collect::<Vec<_>>();
9172 Column::from_values(values)
9173 })?
9174 };
9175 insert_merged_output_column(
9176 &mut columns,
9177 &mut column_order,
9178 name.clone(),
9179 key_column,
9180 )?;
9181 } else {
9182 let key_column = if let Some(positions) = all_present_left_positions {
9183 take_positions_typed(col, positions)
9184 } else if matches!(join_type, JoinType::Outer) {
9185 reindex_outer_join_column(col, &left_positions)?
9186 } else {
9187 col.reindex_by_positions(&left_positions)?
9188 };
9189 insert_merged_output_column(
9190 &mut columns,
9191 &mut column_order,
9192 name.clone(),
9193 key_column,
9194 )?;
9195 }
9196 continue;
9197 }
9198 let reindexed = if let Some(positions) = all_present_left_positions {
9199 take_positions_typed(col, positions)
9200 } else if matches!(join_type, JoinType::Outer) {
9201 reindex_outer_join_column(col, &left_positions)?
9202 } else {
9203 col.reindex_by_positions(&left_positions)?
9204 };
9205 let out_name = if right_col_names.contains(name) {
9206 apply_merge_suffix(name, suffixes.left.as_deref())
9207 } else {
9208 name.clone()
9209 };
9210 insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
9211 }
9212
9213 for name in right.column_names() {
9215 let col = right
9216 .columns()
9217 .get(name)
9218 .expect("right column listed in column_names must exist");
9219 if right_key_name_set.contains(name.as_str())
9220 && shared_name_positions.contains_key(name.as_str())
9221 {
9222 continue;
9224 }
9225 let reindexed = if let Some(positions) = all_present_right_positions {
9226 take_positions_typed(col, positions)
9227 } else if matches!(join_type, JoinType::Outer) {
9228 reindex_outer_join_column(col, &right_positions)?
9229 } else {
9230 col.reindex_by_positions(&right_positions)?
9231 };
9232 let out_name = if left_col_names.contains(name) {
9233 apply_merge_suffix(name, suffixes.right.as_deref())
9234 } else {
9235 name.clone()
9236 };
9237 insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
9238 }
9239
9240 if let Some(indicator_name) = indicator_name.as_deref() {
9241 ensure_indicator_name_available(
9242 indicator_name,
9243 &left_col_names,
9244 &right_col_names,
9245 &columns,
9246 )?;
9247 let indicator_col = build_merge_indicator_column(&left_positions, &right_positions)?;
9248 insert_merged_output_column(
9249 &mut columns,
9250 &mut column_order,
9251 indicator_name.to_owned(),
9252 indicator_col,
9253 )?;
9254 }
9255
9256 Ok(MergedDataFrame {
9257 index,
9258 columns,
9259 column_order,
9260 })
9261}
9262
9263pub fn merge_dataframes_on(
9267 left: &fp_frame::DataFrame,
9268 right: &fp_frame::DataFrame,
9269 on: &[&str],
9270 join_type: JoinType,
9271) -> Result<MergedDataFrame, JoinError> {
9272 merge_dataframes_on_with(left, right, on, on, join_type)
9273}
9274
9275pub fn merge_dataframes(
9277 left: &fp_frame::DataFrame,
9278 right: &fp_frame::DataFrame,
9279 on: &str,
9280 join_type: JoinType,
9281) -> Result<MergedDataFrame, JoinError> {
9282 if matches!(join_type, JoinType::Inner) {
9283 let left_key = left.column(on).ok_or_else(|| {
9284 JoinError::Frame(FrameError::CompatibilityRejected(format!(
9285 "left DataFrame missing key column '{on}'"
9286 )))
9287 })?;
9288 let right_key = right.column(on).ok_or_else(|| {
9289 JoinError::Frame(FrameError::CompatibilityRejected(format!(
9290 "right DataFrame missing key column '{on}'"
9291 )))
9292 })?;
9293 let suffixes = ResolvedMergeSuffixes::default();
9294 return merge_single_key_inner_unsorted(
9295 left,
9296 right,
9297 &[on],
9298 &[on],
9299 &[left_key],
9300 &[right_key],
9301 &suffixes,
9302 );
9303 }
9304 merge_dataframes_on(left, right, &[on], join_type)
9305}
9306
9307fn merge_dataframes_cross(
9308 left: &fp_frame::DataFrame,
9309 right: &fp_frame::DataFrame,
9310 indicator_name: Option<&str>,
9311 suffixes: &ResolvedMergeSuffixes,
9312) -> Result<MergedDataFrame, JoinError> {
9313 let left_rows = left.index().len();
9314 let right_rows = right.index().len();
9315 let out_rows = left_rows.saturating_mul(right_rows);
9316
9317 let mut left_positions = Vec::<Option<usize>>::with_capacity(out_rows);
9318 let mut right_positions = Vec::<Option<usize>>::with_capacity(out_rows);
9319 for left_pos in 0..left_rows {
9320 for right_pos in 0..right_rows {
9321 left_positions.push(Some(left_pos));
9322 right_positions.push(Some(right_pos));
9323 }
9324 }
9325
9326 let index = Index::new((0..out_rows as i64).map(IndexLabel::from).collect());
9327 let mut columns = std::collections::BTreeMap::new();
9328 let mut column_order: Vec<String> = Vec::new();
9329
9330 let left_col_names: std::collections::HashSet<&String> = left.columns().keys().collect();
9331 let right_col_names: std::collections::HashSet<&String> = right.columns().keys().collect();
9332 let overlapping_names =
9333 collect_overlapping_column_names(&left_col_names, &right_col_names, &HashSet::new());
9334 ensure_merge_suffixes_for_overlaps(&overlapping_names, suffixes)?;
9335
9336 for (name, col) in left.columns() {
9337 let reindexed = col.reindex_by_positions(&left_positions)?;
9338 let out_name = if right_col_names.contains(name) {
9339 apply_merge_suffix(name, suffixes.left.as_deref())
9340 } else {
9341 name.clone()
9342 };
9343 insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
9344 }
9345
9346 for (name, col) in right.columns() {
9347 let reindexed = col.reindex_by_positions(&right_positions)?;
9348 let out_name = if left_col_names.contains(name) {
9349 apply_merge_suffix(name, suffixes.right.as_deref())
9350 } else {
9351 name.clone()
9352 };
9353 insert_merged_output_column(&mut columns, &mut column_order, out_name, reindexed)?;
9354 }
9355
9356 if let Some(indicator_name) = indicator_name {
9357 ensure_indicator_name_available(
9358 indicator_name,
9359 &left_col_names,
9360 &right_col_names,
9361 &columns,
9362 )?;
9363 let indicator_col = build_merge_indicator_column(&left_positions, &right_positions)?;
9364 insert_merged_output_column(
9365 &mut columns,
9366 &mut column_order,
9367 indicator_name.to_owned(),
9368 indicator_col,
9369 )?;
9370 }
9371
9372 Ok(MergedDataFrame {
9373 index,
9374 columns,
9375 column_order,
9376 })
9377}
9378
9379pub trait DataFrameMergeExt {
9384 fn merge(
9388 &self,
9389 other: &fp_frame::DataFrame,
9390 on: &[&str],
9391 how: JoinType,
9392 ) -> Result<MergedDataFrame, JoinError>;
9393
9394 fn merge_with_options(
9398 &self,
9399 other: &fp_frame::DataFrame,
9400 left_on: &[&str],
9401 right_on: &[&str],
9402 how: JoinType,
9403 options: MergeExecutionOptions,
9404 ) -> Result<MergedDataFrame, JoinError>;
9405
9406 fn join_on_index(
9410 &self,
9411 other: &fp_frame::DataFrame,
9412 how: JoinType,
9413 ) -> Result<MergedDataFrame, JoinError>;
9414
9415 fn join(
9421 &self,
9422 other: &fp_frame::DataFrame,
9423 how: JoinType,
9424 ) -> Result<MergedDataFrame, JoinError> {
9425 self.join_on_index(other, how)
9426 }
9427
9428 fn merge_asof(
9437 &self,
9438 other: &fp_frame::DataFrame,
9439 on: &str,
9440 direction: &str,
9441 ) -> Result<MergedDataFrame, JoinError>;
9442
9443 fn merge_asof_with_options(
9454 &self,
9455 other: &fp_frame::DataFrame,
9456 on: &str,
9457 direction: &str,
9458 options: MergeAsofOptions,
9459 ) -> Result<MergedDataFrame, JoinError>;
9460
9461 fn merge_ordered(
9465 &self,
9466 other: &fp_frame::DataFrame,
9467 on: &[&str],
9468 fill_method: Option<&str>,
9469 ) -> Result<MergedDataFrame, JoinError>;
9470}
9471
9472pub fn merge_ordered(
9477 left: &fp_frame::DataFrame,
9478 right: &fp_frame::DataFrame,
9479 on: &[&str],
9480 fill_method: Option<&str>,
9481) -> Result<MergedDataFrame, JoinError> {
9482 let options = MergeExecutionOptions {
9483 sort: true,
9484 ..MergeExecutionOptions::default()
9485 };
9486 let merged = merge_dataframes_on_with_options(left, right, on, on, JoinType::Outer, options)?;
9487
9488 if let Some(method) = fill_method {
9489 let mut df = fp_frame::DataFrame::new_with_column_order(
9491 merged.index.clone(),
9492 merged.columns.clone(),
9493 merged.column_order.clone(),
9494 )
9495 .map_err(JoinError::Frame)?;
9496
9497 df = match method {
9498 "ffill" => df.ffill(None).map_err(JoinError::Frame)?,
9499 _ => {
9500 return Err(JoinError::Frame(FrameError::CompatibilityRejected(
9501 format!("merge_ordered: fill_method must be 'ffill' or None, got '{method}'"),
9502 )));
9503 }
9504 };
9505
9506 let column_order = df.column_names().into_iter().cloned().collect();
9507 Ok(MergedDataFrame {
9508 index: df.index().clone(),
9509 columns: df.columns().clone(),
9510 column_order,
9511 })
9512 } else {
9513 Ok(merged)
9514 }
9515}
9516
9517#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9519pub enum AsofDirection {
9520 Backward,
9521 Forward,
9522 Nearest,
9523}
9524
9525#[derive(Debug, Clone, Default)]
9532pub struct MergeAsofOptions {
9533 pub allow_exact_matches: bool,
9536 pub tolerance: Option<f64>,
9539 pub by: Option<Vec<String>>,
9542}
9543
9544impl MergeAsofOptions {
9545 pub fn new() -> Self {
9547 Self {
9548 allow_exact_matches: true,
9549 tolerance: None,
9550 by: None,
9551 }
9552 }
9553
9554 pub fn allow_exact_matches(mut self, allow: bool) -> Self {
9556 self.allow_exact_matches = allow;
9557 self
9558 }
9559
9560 pub fn tolerance(mut self, tol: f64) -> Self {
9562 self.tolerance = Some(tol);
9563 self
9564 }
9565
9566 pub fn by(mut self, cols: Vec<String>) -> Self {
9568 self.by = Some(cols);
9569 self
9570 }
9571}
9572
9573type ShiftedDatetimeAsofKeys = (Vec<f64>, Vec<f64>);
9585
9586fn try_asof_datetime_shift(
9587 left_key: &Column,
9588 right_key: &Column,
9589 on: &str,
9590) -> Option<Result<ShiftedDatetimeAsofKeys, JoinError>> {
9591 if left_key.dtype() != DType::Datetime64 || right_key.dtype() != DType::Datetime64 {
9592 return None;
9593 }
9594 let ld = left_key.as_datetime64_slice()?;
9595 let rd = right_key.as_datetime64_slice()?;
9596 let lv = left_key.validity();
9597 let rv = right_key.validity();
9598 let l_all = lv.all();
9603 let r_all = rv.all();
9604 let is_valid = |data: &[i64], v: &fp_columnar::ValidityMask, all: bool, i: usize| -> bool {
9605 (all || v.get(i)) && data[i] != fp_types::Timestamp::NAT
9606 };
9607 let mut lo = i64::MAX;
9609 let mut hi = i64::MIN;
9610 let mut any = false;
9611 for i in 0..ld.len() {
9612 if is_valid(ld, lv, l_all, i) {
9613 lo = lo.min(ld[i]);
9614 hi = hi.max(ld[i]);
9615 any = true;
9616 }
9617 }
9618 for i in 0..rd.len() {
9619 if is_valid(rd, rv, r_all, i) {
9620 lo = lo.min(rd[i]);
9621 hi = hi.max(rd[i]);
9622 any = true;
9623 }
9624 }
9625 if !any {
9626 return Some(Ok((vec![f64::NAN; ld.len()], vec![f64::NAN; rd.len()])));
9628 }
9629 if (hi as i128 - lo as i128) >= (1i128 << 53) {
9630 return Some(Err(JoinError::Frame(FrameError::CompatibilityRejected(
9631 format!(
9632 "merge_asof: Datetime64 key '{on}' spans more than ~104 days of nanoseconds, \
9633 which exceeds f64 asof precision; not yet supported"
9634 ),
9635 ))));
9636 }
9637 let shift = |data: &[i64], v: &fp_columnar::ValidityMask, all: bool| -> Vec<f64> {
9638 (0..data.len())
9639 .map(|i| {
9640 if is_valid(data, v, all, i) {
9641 (data[i] - lo) as f64
9642 } else {
9643 f64::NAN
9644 }
9645 })
9646 .collect()
9647 };
9648 Some(Ok((shift(ld, lv, l_all), shift(rd, rv, r_all))))
9649}
9650
9651#[derive(Clone, Copy)]
9652struct Datetime64AsofKey<'a> {
9653 data: &'a [i64],
9654 validity: &'a ValidityMask,
9655 all_valid: bool,
9656}
9657
9658impl Datetime64AsofKey<'_> {
9659 #[inline]
9660 fn is_valid(self, i: usize) -> bool {
9661 (self.all_valid || self.validity.get(i)) && self.data[i] != fp_types::Timestamp::NAT
9662 }
9663}
9664
9665fn datetime64_key_parts(column: &Column) -> Option<Datetime64AsofKey<'_>> {
9666 let data = column.as_datetime64_slice()?;
9667 let validity = column.validity();
9668 Some(Datetime64AsofKey {
9669 data,
9670 validity,
9671 all_valid: validity.all(),
9672 })
9673}
9674
9675fn ensure_sorted_non_decreasing_datetime64(
9676 key: Datetime64AsofKey<'_>,
9677 side: &str,
9678 on: &str,
9679) -> Result<(), JoinError> {
9680 let mut prev: Option<i64> = None;
9681 for i in 0..key.data.len() {
9682 if !key.is_valid(i) {
9683 continue;
9684 }
9685 let value = key.data[i];
9686 if let Some(prev_value) = prev
9687 && value < prev_value
9688 {
9689 return Err(JoinError::Frame(FrameError::CompatibilityRejected(
9690 format!("merge_asof: {side} column '{on}' must be sorted"),
9691 )));
9692 }
9693 prev = Some(value);
9694 }
9695 Ok(())
9696}
9697
9698fn within_datetime64_tolerance(left: i64, right: i64, tolerance: Option<f64>) -> bool {
9699 match tolerance {
9700 Some(tol) => ((left as i128 - right as i128).abs() as f64) <= tol,
9701 None => true,
9702 }
9703}
9704
9705fn compute_asof_matches_datetime64(
9706 left: Datetime64AsofKey<'_>,
9707 right: Datetime64AsofKey<'_>,
9708 direction: AsofDirection,
9709 allow_exact_matches: bool,
9710 tolerance: Option<f64>,
9711) -> Vec<Option<usize>> {
9712 let mut filtered_values = Vec::new();
9713 let mut filtered_positions = Vec::new();
9714 let (right_valid_values, right_valid_positions) =
9715 if right.all_valid && !right.data.contains(&fp_types::Timestamp::NAT) {
9716 (right.data, None)
9717 } else {
9718 for i in 0..right.data.len() {
9719 if right.is_valid(i) {
9720 filtered_values.push(right.data[i]);
9721 filtered_positions.push(i);
9722 }
9723 }
9724 (
9725 filtered_values.as_slice(),
9726 Some(filtered_positions.as_slice()),
9727 )
9728 };
9729
9730 compute_asof_matches_datetime64_prepared(
9731 left,
9732 right_valid_values,
9733 right_valid_positions,
9734 direction,
9735 allow_exact_matches,
9736 tolerance,
9737 )
9738}
9739
9740fn compute_asof_matches_datetime64_prepared(
9741 left: Datetime64AsofKey<'_>,
9742 right_valid_values: &[i64],
9743 right_valid_positions: Option<&[usize]>,
9744 direction: AsofDirection,
9745 allow_exact_matches: bool,
9746 tolerance: Option<f64>,
9747) -> Vec<Option<usize>> {
9748 let right_source_position =
9749 |position: usize| right_valid_positions.map_or(position, |positions| positions[position]);
9750
9751 let mut right_matches = Vec::with_capacity(left.data.len());
9752
9753 match direction {
9754 AsofDirection::Backward => {
9755 let mut best: Option<usize> = None;
9756 let mut best_val: Option<i64> = None;
9757 let mut j = 0usize;
9758 for i in 0..left.data.len() {
9759 if !left.is_valid(i) {
9760 right_matches.push(None);
9761 continue;
9762 }
9763 let lv = left.data[i];
9764 while j < right_valid_values.len() {
9765 let rv = right_valid_values[j];
9766 let should_include = if allow_exact_matches {
9767 rv <= lv
9768 } else {
9769 rv < lv
9770 };
9771 if !should_include {
9772 break;
9773 }
9774 best = Some(right_source_position(j));
9775 best_val = Some(rv);
9776 j += 1;
9777 }
9778
9779 let matched = match (best, best_val) {
9780 (Some(idx), Some(rv)) if within_datetime64_tolerance(lv, rv, tolerance) => {
9781 Some(idx)
9782 }
9783 _ => None,
9784 };
9785 right_matches.push(matched);
9786 }
9787 }
9788 AsofDirection::Forward => {
9789 let mut j = 0usize;
9790 for i in 0..left.data.len() {
9791 if !left.is_valid(i) {
9792 right_matches.push(None);
9793 continue;
9794 }
9795 let lv = left.data[i];
9796 while j < right_valid_values.len() {
9797 let rv = right_valid_values[j];
9798 let should_skip = if allow_exact_matches {
9799 rv < lv
9800 } else {
9801 rv <= lv
9802 };
9803 if !should_skip {
9804 break;
9805 }
9806 j += 1;
9807 }
9808
9809 if j < right_valid_values.len() {
9810 let rv = right_valid_values[j];
9811 if within_datetime64_tolerance(lv, rv, tolerance) {
9812 right_matches.push(Some(right_source_position(j)));
9813 } else {
9814 right_matches.push(None);
9815 }
9816 } else {
9817 right_matches.push(None);
9818 }
9819 }
9820 }
9821 AsofDirection::Nearest => {
9822 for i in 0..left.data.len() {
9823 if !left.is_valid(i) {
9824 right_matches.push(None);
9825 continue;
9826 }
9827 if right_valid_values.is_empty() {
9828 right_matches.push(None);
9829 continue;
9830 }
9831
9832 let lv = left.data[i];
9833 let (lower, upper) = if allow_exact_matches {
9834 let lo = right_valid_values.partition_point(|rv| *rv <= lv);
9835 let up = right_valid_values.partition_point(|rv| *rv < lv);
9836 (
9837 if lo > 0 { Some(lo - 1) } else { None },
9838 if up < right_valid_values.len() {
9839 Some(up)
9840 } else {
9841 None
9842 },
9843 )
9844 } else {
9845 let lo = right_valid_values.partition_point(|rv| *rv < lv);
9846 let up = right_valid_values.partition_point(|rv| *rv <= lv);
9847 (
9848 if lo > 0 { Some(lo - 1) } else { None },
9849 if up < right_valid_values.len() {
9850 Some(up)
9851 } else {
9852 None
9853 },
9854 )
9855 };
9856
9857 let chosen = match (lower, upper) {
9858 (Some(l), Some(u)) => {
9859 let lower_dist = (right_valid_values[l] as i128 - lv as i128).abs();
9860 let upper_dist = (right_valid_values[u] as i128 - lv as i128).abs();
9861 if upper_dist < lower_dist {
9862 Some(u)
9863 } else {
9864 Some(l)
9865 }
9866 }
9867 (Some(l), None) => Some(l),
9868 (None, Some(u)) => Some(u),
9869 (None, None) => None,
9870 };
9871
9872 let matched = match chosen {
9873 Some(idx)
9874 if within_datetime64_tolerance(lv, right_valid_values[idx], tolerance) =>
9875 {
9876 Some(right_source_position(idx))
9877 }
9878 _ => None,
9879 };
9880 right_matches.push(matched);
9881 }
9882 }
9883 }
9884
9885 right_matches
9886}
9887
9888fn try_asof_datetime_matches(
9889 left_key: &Column,
9890 right_key: &Column,
9891 on: &str,
9892 direction: AsofDirection,
9893 allow_exact_matches: bool,
9894 tolerance: Option<f64>,
9895) -> Option<Result<Vec<Option<usize>>, JoinError>> {
9896 if left_key.dtype() != DType::Datetime64 || right_key.dtype() != DType::Datetime64 {
9897 return None;
9898 }
9899 let left = datetime64_key_parts(left_key)?;
9900 let right = datetime64_key_parts(right_key)?;
9901
9902 Some((|| {
9903 ensure_sorted_non_decreasing_datetime64(left, "left", on)?;
9904 ensure_sorted_non_decreasing_datetime64(right, "right", on)?;
9905
9906 Ok(compute_asof_matches_datetime64(
9907 left,
9908 right,
9909 direction,
9910 allow_exact_matches,
9911 tolerance,
9912 ))
9913 })())
9914}
9915
9916fn asof_numeric_values(column: &Column, side: &str, on: &str) -> Result<Vec<f64>, JoinError> {
9917 if let Some(data) = column.as_i64_slice() {
9924 return Ok(data.iter().map(|&v| v as f64).collect());
9925 }
9926 if let Some(data) = column.as_f64_slice() {
9927 return Ok(data.to_vec());
9928 }
9929 let mut out = Vec::with_capacity(column.len());
9930 for value in column.values() {
9931 if let Scalar::Timedelta64(ns) = value {
9937 if *ns == fp_types::Timedelta::NAT {
9938 out.push(f64::NAN);
9939 } else {
9940 out.push(*ns as f64);
9941 }
9942 continue;
9943 }
9944 match value.to_f64() {
9945 Ok(v) => out.push(v),
9946 Err(TypeError::ValueIsMissing { .. }) => out.push(f64::NAN),
9947 Err(_) => {
9948 return Err(JoinError::Frame(FrameError::CompatibilityRejected(
9949 format!("merge_asof: {side} column '{on}' must be numeric"),
9950 )));
9951 }
9952 }
9953 }
9954 Ok(out)
9955}
9956
9957fn ensure_sorted_non_decreasing(values: &[f64], side: &str, on: &str) -> Result<(), JoinError> {
9958 let mut prev: Option<f64> = None;
9959 for &value in values {
9960 if value.is_nan() {
9961 continue;
9962 }
9963 if let Some(prev_value) = prev
9964 && value < prev_value
9965 {
9966 return Err(JoinError::Frame(FrameError::CompatibilityRejected(
9967 format!("merge_asof: {side} column '{on}' must be sorted"),
9968 )));
9969 }
9970 prev = Some(value);
9971 }
9972 Ok(())
9973}
9974
9975pub fn merge_asof(
9977 left: &fp_frame::DataFrame,
9978 right: &fp_frame::DataFrame,
9979 on: &str,
9980 direction: AsofDirection,
9981) -> Result<MergedDataFrame, JoinError> {
9982 merge_asof_with_options(left, right, on, direction, MergeAsofOptions::new())
9983}
9984
9985pub fn merge_asof_with_options(
9994 left: &fp_frame::DataFrame,
9995 right: &fp_frame::DataFrame,
9996 on: &str,
9997 direction: AsofDirection,
9998 options: MergeAsofOptions,
9999) -> Result<MergedDataFrame, JoinError> {
10000 if let Some(ref by_cols) = options.by {
10002 return merge_asof_grouped(left, right, on, direction, &options, by_cols);
10003 }
10004
10005 merge_asof_simple(left, right, on, direction, &options)
10006}
10007
10008fn merge_asof_simple(
10010 left: &fp_frame::DataFrame,
10011 right: &fp_frame::DataFrame,
10012 on: &str,
10013 direction: AsofDirection,
10014 options: &MergeAsofOptions,
10015) -> Result<MergedDataFrame, JoinError> {
10016 let left_key = left.columns().get(on).ok_or_else(|| {
10017 JoinError::Frame(FrameError::CompatibilityRejected(format!(
10018 "merge_asof: column '{on}' not found in left"
10019 )))
10020 })?;
10021 let right_key = right.columns().get(on).ok_or_else(|| {
10022 JoinError::Frame(FrameError::CompatibilityRejected(format!(
10023 "merge_asof: column '{on}' not found in right"
10024 )))
10025 })?;
10026
10027 if let Some(datetime_matches) = try_asof_datetime_matches(
10028 left_key,
10029 right_key,
10030 on,
10031 direction,
10032 options.allow_exact_matches,
10033 options.tolerance,
10034 ) {
10035 let right_matches = datetime_matches?;
10036 return build_asof_output(left, right, on, &right_matches, None);
10037 }
10038
10039 let (left_vals, right_vals) = match try_asof_datetime_shift(left_key, right_key, on) {
10043 Some(shifted) => shifted?,
10044 None => (
10045 asof_numeric_values(left_key, "left", on)?,
10046 asof_numeric_values(right_key, "right", on)?,
10047 ),
10048 };
10049
10050 ensure_sorted_non_decreasing(&left_vals, "left", on)?;
10054 ensure_sorted_non_decreasing(&right_vals, "right", on)?;
10055
10056 let right_matches = compute_asof_matches(
10057 &left_vals,
10058 &right_vals,
10059 direction,
10060 options.allow_exact_matches,
10061 options.tolerance,
10062 );
10063
10064 build_asof_output(left, right, on, &right_matches, None)
10065}
10066
10067fn merge_asof_grouped(
10069 left: &fp_frame::DataFrame,
10070 right: &fp_frame::DataFrame,
10071 on: &str,
10072 direction: AsofDirection,
10073 options: &MergeAsofOptions,
10074 by_cols: &[String],
10075) -> Result<MergedDataFrame, JoinError> {
10076 for col in by_cols {
10078 if left.columns().get(col).is_none() {
10079 return Err(JoinError::Frame(FrameError::CompatibilityRejected(
10080 format!("merge_asof: 'by' column '{col}' not found in left"),
10081 )));
10082 }
10083 if right.columns().get(col).is_none() {
10084 return Err(JoinError::Frame(FrameError::CompatibilityRejected(
10085 format!("merge_asof: 'by' column '{col}' not found in right"),
10086 )));
10087 }
10088 }
10089
10090 let left_key = left.columns().get(on).ok_or_else(|| {
10091 JoinError::Frame(FrameError::CompatibilityRejected(format!(
10092 "merge_asof: column '{on}' not found in left"
10093 )))
10094 })?;
10095 let right_key = right.columns().get(on).ok_or_else(|| {
10096 JoinError::Frame(FrameError::CompatibilityRejected(format!(
10097 "merge_asof: column '{on}' not found in right"
10098 )))
10099 })?;
10100
10101 let (left_vals, right_vals) = match try_asof_datetime_shift(left_key, right_key, on) {
10104 Some(shifted) => shifted?,
10105 None => (
10106 asof_numeric_values(left_key, "left", on)?,
10107 asof_numeric_values(right_key, "right", on)?,
10108 ),
10109 };
10110
10111 ensure_sorted_non_decreasing(&left_vals, "left", on)?;
10115 ensure_sorted_non_decreasing(&right_vals, "right", on)?;
10116
10117 let (left_ids, right_ids) = build_group_ids(left, right, by_cols)?;
10123
10124 let mut right_groups: FxHashMap<u32, Vec<usize>> = FxHashMap::default();
10132 for (idx, &id) in right_ids.iter().enumerate() {
10133 right_groups.entry(id).or_default().push(idx);
10134 }
10135
10136 let mut left_groups: FxHashMap<u32, Vec<usize>> = FxHashMap::default();
10148 for (left_idx, &id) in left_ids.iter().enumerate() {
10149 left_groups.entry(id).or_default().push(left_idx);
10150 }
10151
10152 let mut right_matches: Vec<Option<usize>> = vec![None; left_vals.len()];
10153 for (group_id, left_positions) in &left_groups {
10154 let Some(group_indices) = right_groups.get(group_id) else {
10155 continue; };
10157 let group_right_vals: Vec<f64> = group_indices.iter().map(|&i| right_vals[i]).collect();
10158 let group_left_vals: Vec<f64> = left_positions.iter().map(|&i| left_vals[i]).collect();
10159
10160 let group_matches = compute_asof_matches(
10161 &group_left_vals,
10162 &group_right_vals,
10163 direction,
10164 options.allow_exact_matches,
10165 options.tolerance,
10166 );
10167
10168 for (k, &left_idx) in left_positions.iter().enumerate() {
10169 if let Some(Some(group_idx)) = group_matches.get(k) {
10170 right_matches[left_idx] = Some(group_indices[*group_idx]);
10171 }
10172 }
10173 }
10174
10175 build_asof_output(left, right, on, &right_matches, Some(by_cols))
10176}
10177
10178#[derive(PartialEq, Eq, Hash)]
10186enum ByKey<'a> {
10187 Null(u8),
10188 Bool(bool),
10189 Int(i64),
10190 Str(&'a str),
10191 Timedelta(i64),
10192 Datetime(i64),
10193 Period(i64),
10194}
10195
10196impl<'a> ByKey<'a> {
10197 fn from_scalar(s: &'a Scalar) -> Option<Self> {
10198 Some(match s {
10199 Scalar::Null(NullKind::Null) => ByKey::Null(0),
10200 Scalar::Null(NullKind::NaN) => ByKey::Null(1),
10201 Scalar::Null(NullKind::NaT) => ByKey::Null(2),
10202 Scalar::Bool(b) => ByKey::Bool(*b),
10203 Scalar::Int64(v) => ByKey::Int(*v),
10204 Scalar::Utf8(s) => ByKey::Str(s.as_str()),
10205 Scalar::Timedelta64(v) => ByKey::Timedelta(*v),
10206 Scalar::Datetime64(v) => ByKey::Datetime(*v),
10207 Scalar::Period(v) => ByKey::Period(v.ordinal),
10208 Scalar::Float64(_) | Scalar::Interval(_) => return None,
10209 })
10210 }
10211}
10212
10213fn try_factorize_typed<'a>(
10217 left: &'a [Scalar],
10218 right: &'a [Scalar],
10219) -> Option<(Vec<u32>, Vec<u32>)> {
10220 let mut codes: FxHashMap<ByKey<'a>, u32> = FxHashMap::default();
10221 let mut next = 0u32;
10222 let mut left_ids = Vec::with_capacity(left.len());
10223 for v in left {
10224 let id = *codes.entry(ByKey::from_scalar(v)?).or_insert_with(|| {
10225 let i = next;
10226 next += 1;
10227 i
10228 });
10229 left_ids.push(id);
10230 }
10231 let mut right_ids = Vec::with_capacity(right.len());
10232 for v in right {
10233 let id = *codes.entry(ByKey::from_scalar(v)?).or_insert_with(|| {
10234 let i = next;
10235 next += 1;
10236 i
10237 });
10238 right_ids.push(id);
10239 }
10240 Some((left_ids, right_ids))
10241}
10242
10243fn build_group_ids(
10254 left: &fp_frame::DataFrame,
10255 right: &fp_frame::DataFrame,
10256 by_cols: &[String],
10257) -> Result<(Vec<u32>, Vec<u32>), JoinError> {
10258 if by_cols.len() == 1
10259 && let (Some(lcol), Some(rcol)) = (
10260 left.columns().get(&by_cols[0]),
10261 right.columns().get(&by_cols[0]),
10262 )
10263 && let Some(ids) = try_factorize_typed(lcol.values(), rcol.values())
10264 {
10265 return Ok(ids);
10266 }
10267
10268 let left_keys = build_group_keys(left, by_cols)?;
10269 let right_keys = build_group_keys(right, by_cols)?;
10270 let mut codes: FxHashMap<Vec<String>, u32> = FxHashMap::default();
10271 let mut next = 0u32;
10272 let mut intern = |k: &Vec<String>, codes: &mut FxHashMap<Vec<String>, u32>| -> u32 {
10273 if let Some(&id) = codes.get(k) {
10274 id
10275 } else {
10276 let id = next;
10277 next += 1;
10278 codes.insert(k.clone(), id);
10279 id
10280 }
10281 };
10282 let left_ids = left_keys.iter().map(|k| intern(k, &mut codes)).collect();
10283 let right_ids = right_keys.iter().map(|k| intern(k, &mut codes)).collect();
10284 Ok((left_ids, right_ids))
10285}
10286
10287fn build_group_keys(
10289 df: &fp_frame::DataFrame,
10290 by_cols: &[String],
10291) -> Result<Vec<Vec<String>>, JoinError> {
10292 let n = df.len();
10293 let mut keys = vec![Vec::with_capacity(by_cols.len()); n];
10294
10295 for col_name in by_cols {
10296 let col = df.columns().get(col_name).ok_or_else(|| {
10297 JoinError::Frame(FrameError::CompatibilityRejected(format!(
10298 "merge_asof: column '{col_name}' not found"
10299 )))
10300 })?;
10301 for (i, val) in col.values().iter().enumerate() {
10302 keys[i].push(format!("{val:?}"));
10303 }
10304 }
10305
10306 Ok(keys)
10307}
10308
10309fn compute_asof_matches(
10311 left_vals: &[f64],
10312 right_vals: &[f64],
10313 direction: AsofDirection,
10314 allow_exact_matches: bool,
10315 tolerance: Option<f64>,
10316) -> Vec<Option<usize>> {
10317 let mut right_non_nan_values = Vec::new();
10318 let mut right_non_nan_positions = Vec::new();
10319 for (pos, &rv) in right_vals.iter().enumerate() {
10320 if !rv.is_nan() {
10321 right_non_nan_values.push(rv);
10322 right_non_nan_positions.push(pos);
10323 }
10324 }
10325
10326 let mut right_matches: Vec<Option<usize>> = Vec::with_capacity(left_vals.len());
10327
10328 match direction {
10329 AsofDirection::Backward => {
10330 let mut best: Option<usize> = None;
10331 let mut best_val: Option<f64> = None;
10332 let mut j = 0usize;
10333 for &lv in left_vals {
10334 if lv.is_nan() {
10335 right_matches.push(None);
10336 continue;
10337 }
10338 while j < right_non_nan_values.len() {
10340 let rv = right_non_nan_values[j];
10341 let should_include = if allow_exact_matches {
10342 rv <= lv
10343 } else {
10344 rv < lv
10345 };
10346 if !should_include {
10347 break;
10348 }
10349 best = Some(right_non_nan_positions[j]);
10350 best_val = Some(rv);
10351 j += 1;
10352 }
10353
10354 let matched = match (best, best_val, tolerance) {
10356 (Some(idx), Some(rv), Some(tol)) if (lv - rv).abs() <= tol => Some(idx),
10357 (Some(idx), _, None) => Some(idx),
10358 _ => None,
10359 };
10360 right_matches.push(matched);
10361 }
10362 }
10363 AsofDirection::Forward => {
10364 let mut j = 0usize;
10365 for &lv in left_vals {
10366 if lv.is_nan() {
10367 right_matches.push(None);
10368 continue;
10369 }
10370 while j < right_non_nan_values.len() {
10372 let rv = right_non_nan_values[j];
10373 let should_skip = if allow_exact_matches {
10374 rv < lv
10375 } else {
10376 rv <= lv
10377 };
10378 if !should_skip {
10379 break;
10380 }
10381 j += 1;
10382 }
10383
10384 if j < right_non_nan_values.len() {
10385 let rv = right_non_nan_values[j];
10386 let matched = match tolerance {
10388 Some(tol) if (rv - lv).abs() <= tol => Some(right_non_nan_positions[j]),
10389 None => Some(right_non_nan_positions[j]),
10390 _ => None,
10391 };
10392 right_matches.push(matched);
10393 } else {
10394 right_matches.push(None);
10395 }
10396 }
10397 }
10398 AsofDirection::Nearest => {
10399 for &lv in left_vals {
10400 if lv.is_nan() {
10401 right_matches.push(None);
10402 continue;
10403 }
10404 if right_non_nan_values.is_empty() {
10405 right_matches.push(None);
10406 continue;
10407 }
10408
10409 let (lower, upper) = if allow_exact_matches {
10419 let lo = right_non_nan_values.partition_point(|rv| *rv <= lv);
10420 let up = right_non_nan_values.partition_point(|rv| *rv < lv);
10421 (
10422 if lo > 0 { Some(lo - 1) } else { None },
10423 if up < right_non_nan_values.len() {
10424 Some(up)
10425 } else {
10426 None
10427 },
10428 )
10429 } else {
10430 let lo = right_non_nan_values.partition_point(|rv| *rv < lv);
10431 let up = right_non_nan_values.partition_point(|rv| *rv <= lv);
10432 (
10433 if lo > 0 { Some(lo - 1) } else { None },
10434 if up < right_non_nan_values.len() {
10435 Some(up)
10436 } else {
10437 None
10438 },
10439 )
10440 };
10441
10442 let chosen = match (lower, upper) {
10443 (Some(l), Some(u)) => {
10444 let lower_dist = (right_non_nan_values[l] - lv).abs();
10445 let upper_dist = (right_non_nan_values[u] - lv).abs();
10446 if upper_dist < lower_dist {
10448 Some(u)
10449 } else {
10450 Some(l)
10451 }
10452 }
10453 (Some(l), None) => Some(l),
10454 (None, Some(u)) => Some(u),
10455 (None, None) => None,
10456 };
10457
10458 let matched = match chosen {
10460 Some(idx) => {
10461 let rv = right_non_nan_values[idx];
10462 match tolerance {
10463 Some(tol) if (lv - rv).abs() <= tol => {
10464 Some(right_non_nan_positions[idx])
10465 }
10466 None => Some(right_non_nan_positions[idx]),
10467 _ => None,
10468 }
10469 }
10470 None => None,
10471 };
10472 right_matches.push(matched);
10473 }
10474 }
10475 }
10476
10477 right_matches
10478}
10479
10480enum AsofOutputTask<'a> {
10484 LeftClone(&'a Column),
10485 RightGather(&'a Column),
10486}
10487
10488fn build_asof_output(
10489 left: &fp_frame::DataFrame,
10490 right: &fp_frame::DataFrame,
10491 on: &str,
10492 right_matches: &[Option<usize>],
10493 by_cols: Option<&[String]>,
10494) -> Result<MergedDataFrame, JoinError> {
10495 let right_n = right.len();
10496
10497 let left_col_names: Vec<String> = left.column_names().iter().map(|s| s.to_string()).collect();
10498 let right_col_names_all: Vec<String> =
10499 right.column_names().iter().map(|s| s.to_string()).collect();
10500
10501 let excluded_cols: HashSet<&str> = {
10503 let mut s = HashSet::new();
10504 s.insert(on);
10505 if let Some(by) = by_cols {
10506 for c in by {
10507 s.insert(c.as_str());
10508 }
10509 }
10510 s
10511 };
10512
10513 let right_col_names: Vec<String> = right_col_names_all
10514 .iter()
10515 .filter(|c| !excluded_cols.contains(c.as_str()))
10516 .cloned()
10517 .collect();
10518
10519 let left_name_set: HashSet<&String> = left_col_names.iter().collect();
10520 let right_name_set: HashSet<&String> = right_col_names_all.iter().collect();
10521 let mut excluded_names = HashSet::new();
10522 excluded_names.insert(on);
10523 let overlap_names =
10524 collect_overlapping_column_names(&left_name_set, &right_name_set, &excluded_names);
10525 let overlap_set: HashSet<String> = overlap_names.iter().cloned().collect();
10526 let suffixes = ResolvedMergeSuffixes::default();
10527 ensure_merge_suffixes_for_overlaps(&overlap_names, &suffixes)?;
10528
10529 let n_out = left.len();
10530 let mut out_columns = std::collections::BTreeMap::new();
10531 let mut column_order: Vec<String> = Vec::new();
10532
10533 let mut specs: Vec<(String, AsofOutputTask<'_>)> = Vec::new();
10542 for col_name in &left_col_names {
10543 let col = left.columns().get(col_name).ok_or_else(|| {
10544 JoinError::Frame(FrameError::CompatibilityRejected(format!(
10545 "merge_asof: left column '{col_name}' not found"
10546 )))
10547 })?;
10548 let output_name = if overlap_set.contains(col_name) {
10549 apply_merge_suffix(col_name, suffixes.left.as_deref())
10550 } else {
10551 col_name.clone()
10552 };
10553 specs.push((output_name, AsofOutputTask::LeftClone(col)));
10554 }
10555 for col_name in &right_col_names {
10556 let right_col = right.columns().get(col_name).ok_or_else(|| {
10557 JoinError::Frame(FrameError::CompatibilityRejected(format!(
10558 "merge_asof: right column '{col_name}' not found"
10559 )))
10560 })?;
10561 let output_name = if overlap_set.contains(col_name) {
10562 apply_merge_suffix(col_name, suffixes.right.as_deref())
10563 } else {
10564 col_name.clone()
10565 };
10566 specs.push((output_name, AsofOutputTask::RightGather(right_col)));
10567 }
10568
10569 let build_one = |task: &AsofOutputTask<'_>| -> Result<Column, ColumnError> {
10570 match task {
10571 AsofOutputTask::LeftClone(col) => Ok((*col).clone()),
10572 AsofOutputTask::RightGather(right_col) => {
10573 if let Some(src) = right_col.as_f64_slice() {
10585 let mut data = Vec::with_capacity(n_out);
10586 let mut validity = fp_columnar::ValidityMask::all_valid(n_out);
10587 for (i, m) in right_matches.iter().enumerate() {
10588 match m {
10589 Some(j) if *j < right_n => data.push(src[*j]),
10590 _ => {
10591 data.push(0.0);
10597 validity.set(i, false);
10598 }
10599 }
10600 }
10601 return Ok(Column::from_f64_values_with_validity(data, validity));
10602 }
10603 let src = right_col.values();
10604 let mut vals = Vec::with_capacity(n_out);
10605 for m in right_matches {
10606 match m {
10607 Some(j) if *j < right_n => vals.push(src[*j].clone()),
10608 _ => vals.push(fp_types::Scalar::Null(fp_types::NullKind::NaN)),
10609 }
10610 }
10611 Column::new(right_col.dtype(), vals)
10612 }
10613 }
10614 };
10615
10616 let built: Vec<Result<Column, ColumnError>> = {
10617 let thread_count = join_parallel_thread_count();
10618 if specs.len() > 1 && n_out >= DENSE_I64_INNER_PARALLEL_MIN_VALUES && thread_count > 1 {
10619 let mut slots: Vec<Option<Result<Column, ColumnError>>> =
10620 (0..specs.len()).map(|_| None).collect();
10621 let chunk = specs.len().div_ceil(thread_count).max(1);
10622 let build_one = &build_one;
10623 std::thread::scope(|scope| {
10624 for (spec_chunk, slot_chunk) in specs.chunks(chunk).zip(slots.chunks_mut(chunk)) {
10625 scope.spawn(move || {
10626 for ((_, task), slot) in spec_chunk.iter().zip(slot_chunk) {
10627 *slot = Some(build_one(task));
10628 }
10629 });
10630 }
10631 });
10632 slots
10633 .into_iter()
10634 .map(|c| c.expect("every asof output column must be built"))
10635 .collect()
10636 } else {
10637 specs.iter().map(|(_, task)| build_one(task)).collect()
10638 }
10639 };
10640
10641 for ((output_name, _), column) in specs.into_iter().zip(built) {
10642 insert_merged_output_column(&mut out_columns, &mut column_order, output_name, column?)?;
10643 }
10644
10645 Ok(MergedDataFrame {
10646 index: left.index().clone(),
10647 columns: out_columns,
10648 column_order,
10649 })
10650}
10651
10652impl DataFrameMergeExt for fp_frame::DataFrame {
10653 fn merge(
10654 &self,
10655 other: &fp_frame::DataFrame,
10656 on: &[&str],
10657 how: JoinType,
10658 ) -> Result<MergedDataFrame, JoinError> {
10659 merge_dataframes_on(self, other, on, how)
10660 }
10661
10662 fn merge_with_options(
10663 &self,
10664 other: &fp_frame::DataFrame,
10665 left_on: &[&str],
10666 right_on: &[&str],
10667 how: JoinType,
10668 options: MergeExecutionOptions,
10669 ) -> Result<MergedDataFrame, JoinError> {
10670 merge_dataframes_on_with_options(self, other, left_on, right_on, how, options)
10671 }
10672
10673 fn join_on_index(
10674 &self,
10675 other: &fp_frame::DataFrame,
10676 how: JoinType,
10677 ) -> Result<MergedDataFrame, JoinError> {
10678 let left = self.reset_index(false)?;
10679 let right = other.reset_index(false)?;
10680 merge_dataframes_on(&left, &right, &["index"], how)
10681 }
10682
10683 fn merge_asof(
10684 &self,
10685 other: &fp_frame::DataFrame,
10686 on: &str,
10687 direction: &str,
10688 ) -> Result<MergedDataFrame, JoinError> {
10689 self.merge_asof_with_options(other, on, direction, MergeAsofOptions::new())
10690 }
10691
10692 fn merge_asof_with_options(
10693 &self,
10694 other: &fp_frame::DataFrame,
10695 on: &str,
10696 direction: &str,
10697 options: MergeAsofOptions,
10698 ) -> Result<MergedDataFrame, JoinError> {
10699 let dir = match direction {
10700 "backward" => AsofDirection::Backward,
10701 "forward" => AsofDirection::Forward,
10702 "nearest" => AsofDirection::Nearest,
10703 _ => {
10704 return Err(JoinError::Frame(FrameError::CompatibilityRejected(
10705 format!("merge_asof: invalid direction '{direction}'"),
10706 )));
10707 }
10708 };
10709 crate::merge_asof_with_options(self, other, on, dir, options)
10710 }
10711
10712 fn merge_ordered(
10713 &self,
10714 other: &fp_frame::DataFrame,
10715 on: &[&str],
10716 fill_method: Option<&str>,
10717 ) -> Result<MergedDataFrame, JoinError> {
10718 crate::merge_ordered(self, other, on, fill_method)
10719 }
10720}
10721
10722#[cfg(test)]
10723mod tests {
10724 use fp_columnar::{Column, ValidityMask};
10725 use fp_frame::Series;
10726 use fp_index::{Index, IndexLabel};
10727 use fp_types::{DType, NullKind, Scalar};
10728
10729 use super::{
10730 DataFrameMergeExt, DenseI64InnerOutputPlan, DenseI64LaneData, FusedInt64OutputColumn,
10731 FusedInt64Side, InnerPositionPlan, JoinExecutionOptions, JoinType, PositionSelection,
10732 ResolvedMergeSuffixes, build_dense_i64_inner_output_data,
10733 build_single_key_dense_cycle_i64_left_merge_output,
10734 build_single_key_dense_i64_left_merge_output,
10735 build_single_key_dense_i64_right_merge_output, build_single_key_dense_left_merge_output,
10736 build_single_key_inner_contiguous_no_overlap_output, dense_int64_left_positions,
10737 join_series, join_series_with_options, join_series_with_trace,
10738 lower_hex_overlap_plan_from_certificates, ordered_unique_utf8_inner_position_plan,
10739 ordered_unique_utf8_inner_positions, ordered_utf8_lower_hex_overlap_len,
10740 scalar_utf8_left_positions, scalar_utf8_outer_positions,
10741 sorted_contiguous_utf8_inner_positions, strictly_increasing_utf8_key_spans,
10742 utf8_span_lower_bound,
10743 };
10744
10745 fn contiguous_utf8_column(values: &[&str]) -> Column {
10746 let mut bytes = Vec::new();
10747 let mut offsets = Vec::with_capacity(values.len() + 1);
10748 offsets.push(0);
10749 for value in values {
10750 bytes.extend_from_slice(value.as_bytes());
10751 offsets.push(bytes.len());
10752 }
10753 Column::from_utf8_contiguous(bytes, offsets)
10754 }
10755
10756 fn utf8_key_merge_frame(keys: &[&str], value_name: &str, base: i64) -> DataFrame {
10757 let index = Index::new(
10758 (0..keys.len())
10759 .map(|row| IndexLabel::Int64(row as i64))
10760 .collect(),
10761 );
10762 let mut columns = std::collections::BTreeMap::new();
10763 columns.insert("id".to_owned(), contiguous_utf8_column(keys));
10764 columns.insert(
10765 value_name.to_owned(),
10766 Column::from_i64_values((0..keys.len()).map(|row| base + row as i64).collect()),
10767 );
10768 DataFrame::new_with_column_order(
10769 index,
10770 columns,
10771 vec!["id".to_owned(), value_name.to_owned()],
10772 )
10773 .expect("utf8 key frame")
10774 }
10775
10776 fn scalar_utf8_column(values: &[&str]) -> Column {
10777 Column::from_values(
10778 values
10779 .iter()
10780 .map(|value| Scalar::Utf8((*value).to_owned()))
10781 .collect(),
10782 )
10783 .expect("scalar utf8 column")
10784 }
10785
10786 #[test]
10787 fn scalar_utf8_left_positions_preserve_duplicate_order_blackthrush() {
10788 let left = scalar_utf8_column(&["b", "a", "b", "x"]);
10789 let right = scalar_utf8_column(&["a", "b", "b"]);
10790
10791 let (left_positions, right_positions) =
10792 scalar_utf8_left_positions(&left, &right).expect("scalar utf8 left positions");
10793
10794 assert_eq!(
10795 left_positions,
10796 vec![Some(0), Some(0), Some(1), Some(2), Some(2), Some(3)]
10797 );
10798 assert_eq!(
10799 right_positions,
10800 vec![Some(1), Some(2), Some(0), Some(1), Some(2), None]
10801 );
10802 }
10803
10804 #[test]
10805 fn scalar_utf8_outer_positions_sort_keys_and_keep_unmatched_blackthrush() {
10806 let left = scalar_utf8_column(&["b", "a", "b", "x"]);
10807 let right = scalar_utf8_column(&["a", "b", "b", "z"]);
10808
10809 let (left_positions, right_positions) =
10810 scalar_utf8_outer_positions(&left, &right).expect("scalar utf8 outer positions");
10811
10812 assert_eq!(
10813 left_positions,
10814 vec![Some(1), Some(0), Some(0), Some(2), Some(2), Some(3), None,]
10815 );
10816 assert_eq!(
10817 right_positions,
10818 vec![Some(0), Some(1), Some(2), Some(1), Some(2), None, Some(3),]
10819 );
10820 }
10821
10822 #[test]
10823 fn inner_join_multiplies_cardinality_for_duplicates() {
10824 let left = Series::from_values(
10825 "left",
10826 vec!["k".into(), "k".into(), "x".into()],
10827 vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
10828 )
10829 .expect("left");
10830
10831 let right = Series::from_values(
10832 "right",
10833 vec!["k".into(), "k".into()],
10834 vec![Scalar::Int64(10), Scalar::Int64(20)],
10835 )
10836 .expect("right");
10837
10838 let out = join_series(&left, &right, JoinType::Inner).expect("join");
10839 assert_eq!(out.index.labels().len(), 4);
10840 assert_eq!(
10841 out.left_values.values(),
10842 &[
10843 Scalar::Int64(1),
10844 Scalar::Int64(1),
10845 Scalar::Int64(2),
10846 Scalar::Int64(2)
10847 ]
10848 );
10849 }
10850
10851 #[test]
10852 fn left_join_injects_missing_for_unmatched_right_rows() {
10853 let left = Series::from_values(
10854 "left",
10855 vec!["a".into(), "b".into()],
10856 vec![Scalar::Int64(1), Scalar::Int64(2)],
10857 )
10858 .expect("left");
10859 let right =
10860 Series::from_values("right", vec!["a".into()], vec![Scalar::Int64(10)]).expect("right");
10861
10862 let out = join_series(&left, &right, JoinType::Left).expect("join");
10863 assert_eq!(
10864 out.right_values.values(),
10865 &[Scalar::Int64(10), Scalar::Null(NullKind::Null)]
10866 );
10867 }
10868
10869 #[test]
10870 fn arena_join_matches_global_allocator_behavior() {
10871 let left = Series::from_values(
10872 "left",
10873 vec!["k".into(), "k".into(), "x".into()],
10874 vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
10875 )
10876 .expect("left");
10877
10878 let right = Series::from_values(
10879 "right",
10880 vec!["k".into(), "k".into()],
10881 vec![Scalar::Int64(10), Scalar::Int64(20)],
10882 )
10883 .expect("right");
10884
10885 let global = join_series_with_options(
10886 &left,
10887 &right,
10888 JoinType::Inner,
10889 JoinExecutionOptions {
10890 use_arena: false,
10891 arena_budget_bytes: 0,
10892 },
10893 )
10894 .expect("global join");
10895
10896 let arena = join_series_with_options(
10897 &left,
10898 &right,
10899 JoinType::Inner,
10900 JoinExecutionOptions::default(),
10901 )
10902 .expect("arena join");
10903
10904 assert_eq!(arena, global);
10905 }
10906
10907 #[test]
10908 fn arena_join_falls_back_when_budget_is_too_small() {
10909 let left = Series::from_values(
10910 "left",
10911 vec!["a".into(), "a".into(), "a".into()],
10912 vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
10913 )
10914 .expect("left");
10915 let right = Series::from_values(
10916 "right",
10917 vec!["a".into(), "a".into()],
10918 vec![Scalar::Int64(10), Scalar::Int64(20)],
10919 )
10920 .expect("right");
10921
10922 let options = JoinExecutionOptions {
10923 use_arena: true,
10924 arena_budget_bytes: 1,
10925 };
10926 let (fallback_out, trace) =
10927 join_series_with_trace(&left, &right, JoinType::Inner, options).expect("fallback join");
10928 let global_out = join_series_with_options(
10929 &left,
10930 &right,
10931 JoinType::Inner,
10932 JoinExecutionOptions {
10933 use_arena: false,
10934 arena_budget_bytes: 0,
10935 },
10936 )
10937 .expect("global join");
10938
10939 assert_eq!(fallback_out, global_out);
10940 assert!(!trace.used_arena);
10941 assert!(trace.estimated_bytes > options.arena_budget_bytes);
10942 }
10943
10944 #[test]
10945 fn arena_join_is_stable_across_many_small_operations() {
10946 let left = Series::from_values(
10947 "left",
10948 vec!["a".into(), "b".into()],
10949 vec![Scalar::Int64(1), Scalar::Int64(2)],
10950 )
10951 .expect("left");
10952 let right = Series::from_values(
10953 "right",
10954 vec!["a".into(), "b".into()],
10955 vec![Scalar::Int64(10), Scalar::Int64(20)],
10956 )
10957 .expect("right");
10958
10959 let options = JoinExecutionOptions::default();
10960 for _ in 0..1_000 {
10961 let out = join_series_with_options(&left, &right, JoinType::Inner, options)
10962 .expect("arena join");
10963 assert_eq!(out.index.labels().len(), 2);
10964 assert_eq!(
10965 out.right_values.values(),
10966 &[Scalar::Int64(10), Scalar::Int64(20)]
10967 );
10968 }
10969 }
10970
10971 #[test]
10973 fn arena_large_join_100k_rows() {
10974 let n = 100_000;
10975 let labels: Vec<IndexLabel> = (0..n).map(|i| IndexLabel::Int64(i as i64 % 1000)).collect();
10976 let values: Vec<Scalar> = (0..n).map(|i| Scalar::Int64(i as i64)).collect();
10977
10978 let left = Series::from_values("left", labels.clone(), values.clone()).expect("left");
10979 let right = Series::from_values("right", labels, values).expect("right");
10980
10981 let out = join_series_with_options(
10982 &left,
10983 &right,
10984 JoinType::Inner,
10985 JoinExecutionOptions::default(),
10986 )
10987 .expect("100K arena join");
10988
10989 let out_fallback = join_series_with_options(
10993 &left,
10994 &right,
10995 JoinType::Inner,
10996 JoinExecutionOptions {
10997 use_arena: true,
10998 arena_budget_bytes: 1,
10999 },
11000 )
11001 .expect("100K fallback join");
11002
11003 assert_eq!(out.index.labels().len(), out_fallback.index.labels().len());
11004 }
11005
11006 #[test]
11007 fn right_join_contains_all_right_labels() {
11008 let left = Series::from_values(
11009 "left",
11010 vec!["a".into(), "b".into()],
11011 vec![Scalar::Int64(1), Scalar::Int64(2)],
11012 )
11013 .expect("left");
11014 let right = Series::from_values(
11015 "right",
11016 vec!["b".into(), "c".into()],
11017 vec![Scalar::Int64(20), Scalar::Int64(30)],
11018 )
11019 .expect("right");
11020
11021 let out = join_series(&left, &right, JoinType::Right).expect("join");
11022 assert_eq!(out.index.labels().len(), 2);
11024 assert_eq!(
11025 out.index.labels(),
11026 &[IndexLabel::Utf8("b".into()), IndexLabel::Utf8("c".into())]
11027 );
11028 assert_eq!(
11030 out.left_values.values(),
11031 &[Scalar::Int64(2), Scalar::Null(NullKind::Null)]
11032 );
11033 assert_eq!(
11034 out.right_values.values(),
11035 &[Scalar::Int64(20), Scalar::Int64(30)]
11036 );
11037 }
11038
11039 #[test]
11040 fn right_join_multiplies_cardinality_for_duplicates() {
11041 let left = Series::from_values(
11042 "left",
11043 vec!["k".into(), "k".into()],
11044 vec![Scalar::Int64(1), Scalar::Int64(2)],
11045 )
11046 .expect("left");
11047 let right = Series::from_values(
11048 "right",
11049 vec!["k".into(), "x".into()],
11050 vec![Scalar::Int64(10), Scalar::Int64(30)],
11051 )
11052 .expect("right");
11053
11054 let out = join_series(&left, &right, JoinType::Right).expect("join");
11055 assert_eq!(out.index.labels().len(), 3);
11057 assert_eq!(
11058 out.right_values.values(),
11059 &[Scalar::Int64(10), Scalar::Int64(10), Scalar::Int64(30)]
11060 );
11061 }
11062
11063 #[test]
11064 fn outer_join_contains_all_labels_from_both_sides() {
11065 let left = Series::from_values(
11066 "left",
11067 vec!["a".into(), "b".into()],
11068 vec![Scalar::Int64(1), Scalar::Int64(2)],
11069 )
11070 .expect("left");
11071 let right = Series::from_values(
11072 "right",
11073 vec!["b".into(), "c".into()],
11074 vec![Scalar::Int64(20), Scalar::Int64(30)],
11075 )
11076 .expect("right");
11077
11078 let out = join_series(&left, &right, JoinType::Outer).expect("join");
11079 assert_eq!(out.index.labels().len(), 3);
11081 assert_eq!(
11082 out.left_values.values(),
11083 &[
11084 Scalar::Float64(1.0),
11085 Scalar::Float64(2.0),
11086 Scalar::Null(NullKind::NaN)
11087 ]
11088 );
11089 assert_eq!(
11090 out.right_values.values(),
11091 &[
11092 Scalar::Null(NullKind::NaN),
11093 Scalar::Float64(20.0),
11094 Scalar::Float64(30.0)
11095 ]
11096 );
11097 }
11098
11099 #[test]
11100 fn outer_join_sorts_union_labels_like_pandas() {
11101 let left = Series::from_values(
11102 "left",
11103 vec!["a".into(), "c".into()],
11104 vec![Scalar::Int64(1), Scalar::Int64(3)],
11105 )
11106 .expect("left");
11107 let right = Series::from_values(
11108 "right",
11109 vec!["b".into(), "c".into()],
11110 vec![Scalar::Int64(20), Scalar::Int64(30)],
11111 )
11112 .expect("right");
11113
11114 let out = join_series(&left, &right, JoinType::Outer).expect("join");
11115 assert_eq!(
11116 out.index.labels(),
11117 &[
11118 IndexLabel::Utf8("a".into()),
11119 IndexLabel::Utf8("b".into()),
11120 IndexLabel::Utf8("c".into())
11121 ]
11122 );
11123 assert_eq!(
11124 out.left_values.values(),
11125 &[
11126 Scalar::Float64(1.0),
11127 Scalar::Null(NullKind::NaN),
11128 Scalar::Float64(3.0)
11129 ]
11130 );
11131 assert_eq!(
11132 out.right_values.values(),
11133 &[
11134 Scalar::Null(NullKind::NaN),
11135 Scalar::Float64(20.0),
11136 Scalar::Float64(30.0)
11137 ]
11138 );
11139 }
11140
11141 #[test]
11142 fn outer_join_with_duplicates() {
11143 let left = Series::from_values(
11144 "left",
11145 vec!["k".into(), "k".into(), "a".into()],
11146 vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
11147 )
11148 .expect("left");
11149 let right = Series::from_values(
11150 "right",
11151 vec!["k".into(), "z".into()],
11152 vec![Scalar::Int64(10), Scalar::Int64(99)],
11153 )
11154 .expect("right");
11155
11156 let out = join_series(&left, &right, JoinType::Outer).expect("join");
11157 assert_eq!(out.index.labels().len(), 4);
11159 }
11160
11161 #[test]
11162 fn arena_right_join_matches_global() {
11163 let left = Series::from_values(
11164 "left",
11165 vec!["a".into(), "b".into()],
11166 vec![Scalar::Int64(1), Scalar::Int64(2)],
11167 )
11168 .expect("left");
11169 let right = Series::from_values(
11170 "right",
11171 vec!["b".into(), "c".into()],
11172 vec![Scalar::Int64(20), Scalar::Int64(30)],
11173 )
11174 .expect("right");
11175
11176 let global = join_series_with_options(
11177 &left,
11178 &right,
11179 JoinType::Right,
11180 JoinExecutionOptions {
11181 use_arena: false,
11182 arena_budget_bytes: 0,
11183 },
11184 )
11185 .expect("global");
11186 let arena = join_series_with_options(
11187 &left,
11188 &right,
11189 JoinType::Right,
11190 JoinExecutionOptions::default(),
11191 )
11192 .expect("arena");
11193 assert_eq!(arena, global);
11194 }
11195
11196 #[test]
11197 fn arena_outer_join_matches_global() {
11198 let left = Series::from_values(
11199 "left",
11200 vec!["a".into(), "b".into()],
11201 vec![Scalar::Int64(1), Scalar::Int64(2)],
11202 )
11203 .expect("left");
11204 let right = Series::from_values(
11205 "right",
11206 vec!["b".into(), "c".into()],
11207 vec![Scalar::Int64(20), Scalar::Int64(30)],
11208 )
11209 .expect("right");
11210
11211 let global = join_series_with_options(
11212 &left,
11213 &right,
11214 JoinType::Outer,
11215 JoinExecutionOptions {
11216 use_arena: false,
11217 arena_budget_bytes: 0,
11218 },
11219 )
11220 .expect("global");
11221 let arena = join_series_with_options(
11222 &left,
11223 &right,
11224 JoinType::Outer,
11225 JoinExecutionOptions::default(),
11226 )
11227 .expect("arena");
11228 assert_eq!(arena, global);
11229 }
11230
11231 #[test]
11234 fn arena_reset_between_operations() {
11235 let left = Series::from_values(
11236 "left",
11237 vec!["a".into(), "b".into()],
11238 vec![Scalar::Int64(1), Scalar::Int64(2)],
11239 )
11240 .expect("left");
11241 let right = Series::from_values(
11242 "right",
11243 vec!["a".into(), "c".into()],
11244 vec![Scalar::Int64(10), Scalar::Int64(30)],
11245 )
11246 .expect("right");
11247
11248 let out1 = join_series_with_options(
11250 &left,
11251 &right,
11252 JoinType::Inner,
11253 JoinExecutionOptions::default(),
11254 )
11255 .expect("op1");
11256 assert_eq!(out1.index.labels().len(), 1);
11257
11258 let out2 = join_series_with_options(
11260 &left,
11261 &right,
11262 JoinType::Left,
11263 JoinExecutionOptions::default(),
11264 )
11265 .expect("op2");
11266 assert_eq!(out2.index.labels().len(), 2);
11267 }
11268
11269 use fp_frame::{DataFrame, FrameError};
11272
11273 use super::{
11274 JoinError, MergeExecutionOptions, MergeValidateMode, MergedDataFrame,
11275 build_single_key_dense_right_merge_output, dense_int64_right_positions, merge_dataframes,
11276 merge_dataframes_on, merge_dataframes_on_with, merge_dataframes_on_with_options,
11277 ordered_identity_int64_keys_match, resolve_merge_suffixes,
11278 };
11279
11280 fn make_left_df() -> DataFrame {
11281 DataFrame::from_dict(
11282 &["id", "val_a"],
11283 vec![
11284 (
11285 "id",
11286 vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
11287 ),
11288 (
11289 "val_a",
11290 vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
11291 ),
11292 ],
11293 )
11294 .unwrap()
11295 }
11296
11297 fn make_right_df() -> DataFrame {
11298 DataFrame::from_dict(
11299 &["id", "val_b"],
11300 vec![
11301 (
11302 "id",
11303 vec![Scalar::Int64(2), Scalar::Int64(3), Scalar::Int64(4)],
11304 ),
11305 (
11306 "val_b",
11307 vec![Scalar::Int64(200), Scalar::Int64(300), Scalar::Int64(400)],
11308 ),
11309 ],
11310 )
11311 .unwrap()
11312 }
11313
11314 #[test]
11315 fn merge_preserves_pandas_column_order_for_nonalphabetical_names() {
11316 let left = DataFrame::from_dict(
11322 &["k", "zebra", "apple"],
11323 vec![
11324 ("k", vec![Scalar::Int64(1), Scalar::Int64(2)]),
11325 ("zebra", vec![Scalar::Int64(10), Scalar::Int64(20)]),
11326 ("apple", vec![Scalar::Int64(30), Scalar::Int64(40)]),
11327 ],
11328 )
11329 .unwrap();
11330 let right = DataFrame::from_dict(
11331 &["k", "mango"],
11332 vec![
11333 ("k", vec![Scalar::Int64(1), Scalar::Int64(2)]),
11334 ("mango", vec![Scalar::Int64(50), Scalar::Int64(60)]),
11335 ],
11336 )
11337 .unwrap();
11338 let merged = merge_dataframes(&left, &right, "k", JoinType::Inner).unwrap();
11339 let order: Vec<&str> = merged.column_order.iter().map(String::as_str).collect();
11340 assert_eq!(order, ["k", "zebra", "apple", "mango"]);
11341 }
11342
11343 #[test]
11344 fn join_row_count_lattice_n8npw() {
11345 let mut s: u64 = 0x4e57_0b1c_2d3e_4f55;
11348 let mut next = || {
11349 s = s
11350 .wrapping_mul(6_364_136_223_846_793_005)
11351 .wrapping_add(1_442_695_040_888_963_407);
11352 (s >> 33) as u32
11353 };
11354 for iter in 0..300u32 {
11355 let ln = (next() % 6) as usize + 1;
11356 let rn = (next() % 6) as usize + 1;
11357 let lk: Vec<Scalar> = (0..ln)
11358 .map(|_| Scalar::Int64((next() % 4) as i64))
11359 .collect();
11360 let rk: Vec<Scalar> = (0..rn)
11361 .map(|_| Scalar::Int64((next() % 4) as i64))
11362 .collect();
11363 let left = DataFrame::from_dict(
11364 &["k", "lv"],
11365 vec![
11366 ("k", lk),
11367 ("lv", (0..ln).map(|i| Scalar::Int64(i as i64)).collect()),
11368 ],
11369 )
11370 .unwrap();
11371 let right = DataFrame::from_dict(
11372 &["k", "rv"],
11373 vec![
11374 ("k", rk),
11375 ("rv", (0..rn).map(|i| Scalar::Int64(i as i64)).collect()),
11376 ],
11377 )
11378 .unwrap();
11379 let rows = |jt| {
11380 let m = merge_dataframes(&left, &right, "k", jt).unwrap();
11381 merged_values(&m, "k").unwrap().len()
11382 };
11383 let inner = rows(JoinType::Inner);
11384 let lj = rows(JoinType::Left);
11385 let rj = rows(JoinType::Right);
11386 let outer = rows(JoinType::Outer);
11387 assert!(
11388 inner <= lj && lj <= outer,
11389 "inner<=left<=outer iter={iter}: {inner} {lj} {outer}"
11390 );
11391 assert!(
11392 inner <= rj && rj <= outer,
11393 "inner<=right<=outer iter={iter}: {inner} {rj} {outer}"
11394 );
11395 }
11396 }
11397
11398 #[test]
11399 fn right_join_null_fill_multiset_7je8m() {
11400 use std::collections::HashMap;
11401 let mut s: u64 = 0x4e57_0b1c_2d3e_4f54;
11405 let mut next = || {
11406 s = s
11407 .wrapping_mul(6_364_136_223_846_793_005)
11408 .wrapping_add(1_442_695_040_888_963_407);
11409 (s >> 33) as u32
11410 };
11411 for iter in 0..300u32 {
11412 let ln = (next() % 6) as usize + 1;
11413 let rn = (next() % 6) as usize + 1;
11414 let lk: Vec<i64> = (0..ln).map(|_| (next() % 4) as i64).collect();
11415 let lv: Vec<i64> = (0..ln).map(|i| i as i64).collect();
11416 let rk: Vec<i64> = (0..rn).map(|_| (next() % 4) as i64).collect();
11417 let rv: Vec<i64> = (0..rn).map(|i| 100 + i as i64).collect();
11418 let left = DataFrame::from_dict(
11419 &["k", "lv"],
11420 vec![
11421 ("k", lk.iter().map(|&x| Scalar::Int64(x)).collect()),
11422 ("lv", lv.iter().map(|&x| Scalar::Int64(x)).collect()),
11423 ],
11424 )
11425 .unwrap();
11426 let right = DataFrame::from_dict(
11427 &["k", "rv"],
11428 vec![
11429 ("k", rk.iter().map(|&x| Scalar::Int64(x)).collect()),
11430 ("rv", rv.iter().map(|&x| Scalar::Int64(x)).collect()),
11431 ],
11432 )
11433 .unwrap();
11434 let merged = merge_dataframes(&left, &right, "k", JoinType::Right).unwrap();
11435
11436 let ks = merged_values(&merged, "k").unwrap();
11437 let lvs = merged_values(&merged, "lv").unwrap();
11438 let rvs = merged_values(&merged, "rv").unwrap();
11439 let ki = |v: &Scalar| -> i64 {
11440 match v {
11441 Scalar::Int64(x) => *x,
11442 Scalar::Float64(x) => *x as i64,
11443 _ => i64::MIN,
11444 }
11445 };
11446 let kopt =
11447 |v: &Scalar| -> Option<i64> { if v.is_missing() { None } else { Some(ki(v)) } };
11448 let mut got: Vec<(i64, Option<i64>, i64)> = (0..ks.len())
11449 .map(|i| (ki(&ks[i]), kopt(&lvs[i]), ki(&rvs[i])))
11450 .collect();
11451 let mut lby: HashMap<i64, Vec<i64>> = HashMap::new();
11453 for i in 0..ln {
11454 lby.entry(lk[i]).or_default().push(lv[i]);
11455 }
11456 let mut exp: Vec<(i64, Option<i64>, i64)> = Vec::new();
11457 for i in 0..rn {
11458 match lby.get(&rk[i]) {
11459 Some(lvals) => {
11460 for &a in lvals {
11461 exp.push((rk[i], Some(a), rv[i]));
11462 }
11463 }
11464 None => exp.push((rk[i], None, rv[i])),
11465 }
11466 }
11467 got.sort();
11468 exp.sort();
11469 assert_eq!(got, exp, "right join multiset iter={iter}");
11470 }
11471 }
11472
11473 #[test]
11474 fn inner_join_utf8_value_multiset_fr4ns() {
11475 use std::collections::HashMap;
11476 let mut s: u64 = 0x4e57_0b1c_2d3e_4f51;
11480 let mut next = || {
11481 s = s
11482 .wrapping_mul(6_364_136_223_846_793_005)
11483 .wrapping_add(1_442_695_040_888_963_407);
11484 (s >> 33) as u32
11485 };
11486 let key = |n: u32| Scalar::Utf8(format!("{}", (b'a' + (n % 4) as u8) as char));
11487 for iter in 0..300u32 {
11488 let ln = (next() % 6) as usize + 1;
11489 let rn = (next() % 6) as usize + 1;
11490 let lk: Vec<Scalar> = (0..ln).map(|_| key(next())).collect();
11491 let lv: Vec<i64> = (0..ln).map(|i| i as i64).collect();
11492 let rk: Vec<Scalar> = (0..rn).map(|_| key(next())).collect();
11493 let rv: Vec<i64> = (0..rn).map(|i| 100 + i as i64).collect();
11494 let left = DataFrame::from_dict(
11495 &["k", "lv"],
11496 vec![
11497 ("k", lk.clone()),
11498 ("lv", lv.iter().map(|&x| Scalar::Int64(x)).collect()),
11499 ],
11500 )
11501 .unwrap();
11502 let right = DataFrame::from_dict(
11503 &["k", "rv"],
11504 vec![
11505 ("k", rk.clone()),
11506 ("rv", rv.iter().map(|&x| Scalar::Int64(x)).collect()),
11507 ],
11508 )
11509 .unwrap();
11510 let merged = merge_dataframes(&left, &right, "k", JoinType::Inner).unwrap();
11511
11512 let ks = merged_values(&merged, "k").unwrap();
11513 let lvs = merged_values(&merged, "lv").unwrap();
11514 let rvs = merged_values(&merged, "rv").unwrap();
11515 let kstr = |v: &Scalar| -> String {
11516 match v {
11517 Scalar::Utf8(x) => x.clone(),
11518 _ => String::new(),
11519 }
11520 };
11521 let ki = |v: &Scalar| -> i64 {
11522 match v {
11523 Scalar::Int64(x) => *x,
11524 _ => i64::MIN,
11525 }
11526 };
11527 let mut got: Vec<(String, i64, i64)> = (0..ks.len())
11528 .map(|i| (kstr(&ks[i]), ki(&lvs[i]), ki(&rvs[i])))
11529 .collect();
11530 let mut lby: HashMap<String, Vec<i64>> = HashMap::new();
11532 for i in 0..ln {
11533 lby.entry(kstr(&lk[i])).or_default().push(lv[i]);
11534 }
11535 let mut rby: HashMap<String, Vec<i64>> = HashMap::new();
11536 for i in 0..rn {
11537 rby.entry(kstr(&rk[i])).or_default().push(rv[i]);
11538 }
11539 let mut exp: Vec<(String, i64, i64)> = Vec::new();
11540 for (k, lvals) in &lby {
11541 if let Some(rvals) = rby.get(k) {
11542 for &a in lvals {
11543 for &b in rvals {
11544 exp.push((k.clone(), a, b));
11545 }
11546 }
11547 }
11548 }
11549 got.sort();
11550 exp.sort();
11551 assert_eq!(got, exp, "inner Utf8 multiset iter={iter}");
11552 }
11553 }
11554
11555 #[test]
11556 fn inner_join_utf8_keys_jlf8d() {
11557 use std::collections::HashMap;
11558 let s = |v: &str| Scalar::Utf8(v.to_owned());
11560 let left = DataFrame::from_dict(
11561 &["k", "lv"],
11562 vec![
11563 ("k", vec![s("a"), s("b"), s("c")]),
11564 (
11565 "lv",
11566 vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
11567 ),
11568 ],
11569 )
11570 .expect("left");
11571 let right = DataFrame::from_dict(
11572 &["k", "rv"],
11573 vec![
11574 ("k", vec![s("b"), s("c"), s("d")]),
11575 (
11576 "rv",
11577 vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
11578 ),
11579 ],
11580 )
11581 .expect("right");
11582 let merged = merge_dataframes(&left, &right, "k", JoinType::Inner).expect("merge");
11583
11584 let keys = merged_values(&merged, "k").expect("k");
11585 let lv = merged_values(&merged, "lv").expect("lv");
11586 let rv = merged_values(&merged, "rv").expect("rv");
11587 let exp_lv: HashMap<&str, i64> = [("b", 2), ("c", 3)].into_iter().collect();
11588 let exp_rv: HashMap<&str, i64> = [("b", 10), ("c", 20)].into_iter().collect();
11589 assert_eq!(keys.len(), 2, "inner keys = {{b,c}}");
11590 for i in 0..keys.len() {
11591 let k = match &keys[i] {
11592 Scalar::Utf8(x) => x.as_str(),
11593 _ => "?",
11594 };
11595 let geti = |s: &Scalar| match s {
11596 Scalar::Int64(v) => *v,
11597 _ => i64::MIN,
11598 };
11599 assert_eq!(geti(&lv[i]), exp_lv[k], "lv at {k}");
11600 assert_eq!(geti(&rv[i]), exp_rv[k], "rv at {k}");
11601 }
11602 }
11603
11604 #[test]
11605 fn merge_indicator_column_d3ec6() {
11606 use std::collections::BTreeSet;
11607 let left = DataFrame::from_dict(
11609 &["k"],
11610 vec![(
11611 "k",
11612 vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
11613 )],
11614 )
11615 .expect("left");
11616 let right = DataFrame::from_dict(
11617 &["k"],
11618 vec![(
11619 "k",
11620 vec![Scalar::Int64(2), Scalar::Int64(3), Scalar::Int64(4)],
11621 )],
11622 )
11623 .expect("right");
11624 let opts = super::MergeExecutionOptions {
11625 indicator_name: Some("_merge".to_owned()),
11626 ..Default::default()
11627 };
11628 let m = super::merge_dataframes_on_with_options(
11629 &left,
11630 &right,
11631 &["k"],
11632 &["k"],
11633 JoinType::Outer,
11634 opts,
11635 )
11636 .expect("merge");
11637
11638 let keys = merged_values(&m, "k").expect("k");
11639 let ind = merged_values(&m, "_merge").expect("_merge present");
11640 let lset: BTreeSet<i64> = [1, 2, 3].into_iter().collect();
11641 let rset: BTreeSet<i64> = [2, 3, 4].into_iter().collect();
11642 assert_eq!(keys.len(), 4, "outer keys = union");
11643 for i in 0..keys.len() {
11644 let k = match &keys[i] {
11645 Scalar::Int64(v) => *v,
11646 _ => i64::MIN,
11647 };
11648 let exp = match (lset.contains(&k), rset.contains(&k)) {
11649 (true, true) => "both",
11650 (true, false) => "left_only",
11651 (false, true) => "right_only",
11652 (false, false) => "??",
11653 };
11654 assert_eq!(ind[i], Scalar::Utf8(exp.to_owned()), "indicator at key {k}");
11655 }
11656 }
11657
11658 #[test]
11659 fn merge_overlapping_columns_suffixed_vb10q() {
11660 let mk = |vfactor: i64| {
11663 DataFrame::from_dict(
11664 &["k", "v"],
11665 vec![
11666 (
11667 "k",
11668 vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
11669 ),
11670 (
11671 "v",
11672 vec![
11673 Scalar::Int64(vfactor),
11674 Scalar::Int64(2 * vfactor),
11675 Scalar::Int64(3 * vfactor),
11676 ],
11677 ),
11678 ],
11679 )
11680 .expect("frame")
11681 };
11682 let left = mk(10); let right = mk(100); let merged = merge_dataframes(&left, &right, "k", JoinType::Inner).expect("merge");
11685
11686 let keys = merged_values(&merged, "k").expect("k");
11687 let vx = merged_values(&merged, "v_x").expect("v_x present");
11688 let vy = merged_values(&merged, "v_y").expect("v_y present");
11689 assert_eq!(keys.len(), 3);
11690 for i in 0..keys.len() {
11691 let k = match &keys[i] {
11692 Scalar::Int64(x) => *x,
11693 _ => i64::MIN,
11694 };
11695 assert_eq!(vx[i], Scalar::Int64(k * 10), "v_x at key {k}");
11696 assert_eq!(vy[i], Scalar::Int64(k * 100), "v_y at key {k}");
11697 }
11698 }
11699
11700 #[test]
11701 fn int64_join_row_count_matches_cardinality_invariant_ya1po() {
11702 use std::collections::BTreeMap;
11703
11704 let mut state: u64 = 0xa5a5_5a5a_dead_beef;
11709 let mut next = || {
11710 state = state
11711 .wrapping_mul(6_364_136_223_846_793_005)
11712 .wrapping_add(1_442_695_040_888_963_407);
11713 (state >> 33) as u32
11714 };
11715
11716 let build = |keys: &[i64], payload_name: &str| {
11717 let n = keys.len();
11718 DataFrame::from_dict(
11719 &["k", payload_name],
11720 vec![
11721 (
11722 "k",
11723 keys.iter().copied().map(Scalar::Int64).collect::<Vec<_>>(),
11724 ),
11725 (
11726 payload_name,
11727 (0..n as i64).map(Scalar::Int64).collect::<Vec<_>>(),
11728 ),
11729 ],
11730 )
11731 .expect("frame")
11732 };
11733
11734 for iter in 0..1500u32 {
11735 let nl = (next() % 9) as usize + 1;
11736 let nr = (next() % 9) as usize + 1;
11737 let lk: Vec<i64> = (0..nl).map(|_| (next() % 4) as i64).collect();
11739 let rk: Vec<i64> = (0..nr).map(|_| (next() % 4) as i64).collect();
11740 let left = build(&lk, "lv");
11741 let right = build(&rk, "rv");
11742
11743 let mut lc: BTreeMap<i64, i64> = BTreeMap::new();
11744 let mut rc: BTreeMap<i64, i64> = BTreeMap::new();
11745 for &k in &lk {
11746 *lc.entry(k).or_default() += 1;
11747 }
11748 for &k in &rk {
11749 *rc.entry(k).or_default() += 1;
11750 }
11751 let mut all_keys: Vec<i64> = lc.keys().chain(rc.keys()).copied().collect();
11752 all_keys.sort_unstable();
11753 all_keys.dedup();
11754
11755 let g = |k: i64, m: &BTreeMap<i64, i64>| m.get(&k).copied().unwrap_or(0);
11756 let inner: i64 = all_keys.iter().map(|&k| g(k, &lc) * g(k, &rc)).sum();
11757 let left_exp: i64 = lc.iter().map(|(&k, &l)| l * g(k, &rc).max(1)).sum();
11758 let right_exp: i64 = rc.iter().map(|(&k, &r)| r * g(k, &lc).max(1)).sum();
11759 let outer: i64 = all_keys
11760 .iter()
11761 .map(|&k| {
11762 let (l, r) = (g(k, &lc), g(k, &rc));
11763 if l > 0 && r > 0 { l * r } else { l + r }
11764 })
11765 .sum();
11766
11767 let ctx = format!("iter={iter} lk={lk:?} rk={rk:?}");
11768 for (jt, exp) in [
11769 (JoinType::Inner, inner),
11770 (JoinType::Left, left_exp),
11771 (JoinType::Right, right_exp),
11772 (JoinType::Outer, outer),
11773 ] {
11774 let merged = merge_dataframes(&left, &right, "k", jt).expect("merge");
11775 let rows = merged_values(&merged, "k").expect("key col").len() as i64;
11776 assert_eq!(rows, exp, "{jt:?} row count {ctx}");
11777 }
11778 }
11779 }
11780
11781 #[test]
11782 fn inner_join_value_multiset_matches_crossproduct_oracle_5foyp() {
11783 use std::collections::BTreeMap;
11784
11785 let mut state: u64 = 0x0ddc_0ffe_e0dd_f00d;
11791 let mut next = || {
11792 state = state
11793 .wrapping_mul(6_364_136_223_846_793_005)
11794 .wrapping_add(1_442_695_040_888_963_407);
11795 (state >> 33) as u32
11796 };
11797
11798 let build = |keys: &[i64], pname: &str| {
11799 let n = keys.len();
11800 DataFrame::from_dict(
11801 &["k", pname],
11802 vec![
11803 (
11804 "k",
11805 keys.iter().copied().map(Scalar::Int64).collect::<Vec<_>>(),
11806 ),
11807 (pname, (0..n as i64).map(Scalar::Int64).collect::<Vec<_>>()),
11809 ],
11810 )
11811 .expect("frame")
11812 };
11813 let geti = |s: &Scalar| match s {
11817 Scalar::Int64(v) => *v,
11818 _ => i64::MIN,
11819 };
11820
11821 for iter in 0..1500u32 {
11822 let nl = (next() % 9) as usize + 1;
11823 let nr = (next() % 9) as usize + 1;
11824 let lk: Vec<i64> = (0..nl).map(|_| (next() % 4) as i64).collect();
11825 let rk: Vec<i64> = (0..nr).map(|_| (next() % 4) as i64).collect();
11826 let left = build(&lk, "lv");
11827 let right = build(&rk, "rv");
11828
11829 let merged = merge_dataframes(&left, &right, "k", JoinType::Inner).expect("merge");
11830 let ks = merged_values(&merged, "k").expect("k");
11831 let lvs = merged_values(&merged, "lv").expect("lv");
11832 let rvs = merged_values(&merged, "rv").expect("rv");
11833 let mut got: Vec<(i64, i64, i64)> = (0..ks.len())
11834 .map(|i| (geti(&ks[i]), geti(&lvs[i]), geti(&rvs[i])))
11835 .collect();
11836 got.sort_unstable();
11837
11838 let mut lg: BTreeMap<i64, Vec<i64>> = BTreeMap::new();
11840 let mut rg: BTreeMap<i64, Vec<i64>> = BTreeMap::new();
11841 for (i, &k) in lk.iter().enumerate() {
11842 lg.entry(k).or_default().push(i as i64);
11843 }
11844 for (i, &k) in rk.iter().enumerate() {
11845 rg.entry(k).or_default().push(i as i64);
11846 }
11847 let mut exp: Vec<(i64, i64, i64)> = Vec::new();
11848 for (&k, lps) in &lg {
11849 if let Some(rps) = rg.get(&k) {
11850 for &a in lps {
11851 for &b in rps {
11852 exp.push((k, a, b));
11853 }
11854 }
11855 }
11856 }
11857 exp.sort_unstable();
11858
11859 assert_eq!(
11860 got, exp,
11861 "inner join value multiset iter={iter} lk={lk:?} rk={rk:?}"
11862 );
11863 }
11864 }
11865
11866 #[test]
11867 fn left_outer_join_nullfill_value_oracle_kaj3t() {
11868 use std::collections::BTreeMap;
11869
11870 const NUL: i64 = i64::MIN;
11876 let mut state: u64 = 0xfeed_face_cafe_b0ba;
11877 let mut next = || {
11878 state = state
11879 .wrapping_mul(6_364_136_223_846_793_005)
11880 .wrapping_add(1_442_695_040_888_963_407);
11881 (state >> 33) as u32
11882 };
11883
11884 let build = |keys: &[i64], pname: &str| {
11885 let n = keys.len();
11886 DataFrame::from_dict(
11887 &["k", pname],
11888 vec![
11889 (
11890 "k",
11891 keys.iter().copied().map(Scalar::Int64).collect::<Vec<_>>(),
11892 ),
11893 (pname, (0..n as i64).map(Scalar::Int64).collect::<Vec<_>>()),
11894 ],
11895 )
11896 .expect("frame")
11897 };
11898 let geti = |s: &Scalar| match s {
11903 Scalar::Int64(v) => *v,
11904 Scalar::Float64(v) if v.is_finite() => *v as i64,
11905 _ => NUL,
11906 };
11907
11908 for iter in 0..1500u32 {
11909 let nl = (next() % 9) as usize + 1;
11910 let nr = (next() % 9) as usize + 1;
11911 let lk: Vec<i64> = (0..nl).map(|_| (next() % 4) as i64).collect();
11912 let rk: Vec<i64> = (0..nr).map(|_| (next() % 4) as i64).collect();
11913 let left = build(&lk, "lv");
11914 let right = build(&rk, "rv");
11915
11916 let mut rg: BTreeMap<i64, Vec<i64>> = BTreeMap::new();
11918 for (j, &k) in rk.iter().enumerate() {
11919 rg.entry(k).or_default().push(j as i64);
11920 }
11921 let lkeys: std::collections::BTreeSet<i64> = lk.iter().copied().collect();
11922
11923 let read = |jt: JoinType| -> Vec<(i64, i64, i64)> {
11924 let merged = merge_dataframes(&left, &right, "k", jt).expect("merge");
11925 let ks = merged_values(&merged, "k").expect("k");
11926 let lvs = merged_values(&merged, "lv").expect("lv");
11927 let rvs = merged_values(&merged, "rv").expect("rv");
11928 let mut got: Vec<(i64, i64, i64)> = (0..ks.len())
11929 .map(|i| (geti(&ks[i]), geti(&lvs[i]), geti(&rvs[i])))
11930 .collect();
11931 got.sort_unstable();
11932 got
11933 };
11934
11935 let mut exp_left: Vec<(i64, i64, i64)> = Vec::new();
11938 for (i, &k) in lk.iter().enumerate() {
11939 match rg.get(&k) {
11940 Some(rps) => {
11941 for &j in rps {
11942 exp_left.push((k, i as i64, j));
11943 }
11944 }
11945 None => exp_left.push((k, i as i64, NUL)),
11946 }
11947 }
11948 exp_left.sort_unstable();
11949 assert_eq!(
11950 read(JoinType::Left),
11951 exp_left,
11952 "left join value oracle iter={iter} lk={lk:?} rk={rk:?}"
11953 );
11954
11955 let mut exp_outer = exp_left.clone();
11958 for (j, &k) in rk.iter().enumerate() {
11959 if !lkeys.contains(&k) {
11960 exp_outer.push((k, NUL, j as i64));
11961 }
11962 }
11963 exp_outer.sort_unstable();
11964 assert_eq!(
11965 read(JoinType::Outer),
11966 exp_outer,
11967 "outer join value oracle iter={iter} lk={lk:?} rk={rk:?}"
11968 );
11969 }
11970 }
11971
11972 #[test]
11973 fn left_join_value_multiset_matches_unmatched_oracle_gp0ik() {
11974 use std::collections::BTreeMap;
11975
11976 let mut state: u64 = 0x51de_cafe_2026_0618;
11980 let mut next = || {
11981 state = state
11982 .wrapping_mul(6_364_136_223_846_793_005)
11983 .wrapping_add(1_442_695_040_888_963_407);
11984 (state >> 33) as u32
11985 };
11986
11987 let build = |keys: &[i64], pname: &str| {
11988 let n = keys.len();
11989 DataFrame::from_dict(
11990 &["k", pname],
11991 vec![
11992 (
11993 "k",
11994 keys.iter().copied().map(Scalar::Int64).collect::<Vec<_>>(),
11995 ),
11996 (pname, (0..n as i64).map(Scalar::Int64).collect::<Vec<_>>()),
11997 ],
11998 )
11999 .expect("frame")
12000 };
12001 let geti = |s: &Scalar| match s {
12002 Scalar::Int64(v) => *v,
12003 _ => i64::MIN,
12004 };
12005 let get_optional_i64 = |s: &Scalar| match s {
12006 Scalar::Int64(v) => Some(*v),
12007 value if value.is_missing() => None,
12008 _ => Some(i64::MIN),
12009 };
12010
12011 for iter in 0..1500u32 {
12012 let nl = (next() % 9) as usize + 1;
12013 let nr = (next() % 9) as usize + 1;
12014 let lk: Vec<i64> = (0..nl).map(|_| (next() % 5) as i64).collect();
12015 let rk: Vec<i64> = (0..nr).map(|_| (next() % 3) as i64).collect();
12016 let left = build(&lk, "lv");
12017 let right = build(&rk, "rv");
12018
12019 let merged = merge_dataframes(&left, &right, "k", JoinType::Left).expect("merge");
12020 let ks = merged_values(&merged, "k").expect("k");
12021 let lvs = merged_values(&merged, "lv").expect("lv");
12022 let rvs = merged_values(&merged, "rv").expect("rv");
12023 let mut got: Vec<(i64, i64, Option<i64>)> = (0..ks.len())
12024 .map(|i| (geti(&ks[i]), geti(&lvs[i]), get_optional_i64(&rvs[i])))
12025 .collect();
12026 got.sort_unstable();
12027
12028 let mut rg: BTreeMap<i64, Vec<i64>> = BTreeMap::new();
12029 for (i, &k) in rk.iter().enumerate() {
12030 rg.entry(k).or_default().push(i as i64);
12031 }
12032 let mut exp: Vec<(i64, i64, Option<i64>)> = Vec::new();
12033 for (left_pos, &k) in lk.iter().enumerate() {
12034 if let Some(right_positions) = rg.get(&k) {
12035 for &right_pos in right_positions {
12036 exp.push((k, left_pos as i64, Some(right_pos)));
12037 }
12038 } else {
12039 exp.push((k, left_pos as i64, None));
12040 }
12041 }
12042 exp.sort_unstable();
12043
12044 assert_eq!(
12045 got, exp,
12046 "left join value multiset iter={iter} lk={lk:?} rk={rk:?}"
12047 );
12048 }
12049 }
12050
12051 #[test]
12052 fn right_join_value_multiset_matches_unmatched_oracle_pd1h5() {
12053 use std::collections::BTreeMap;
12054
12055 let mut state: u64 = 0x7191_2026_0618_a015;
12059 let mut next = || {
12060 state = state
12061 .wrapping_mul(6_364_136_223_846_793_005)
12062 .wrapping_add(1_442_695_040_888_963_407);
12063 (state >> 33) as u32
12064 };
12065
12066 let build = |keys: &[i64], pname: &str| {
12067 let n = keys.len();
12068 DataFrame::from_dict(
12069 &["k", pname],
12070 vec![
12071 (
12072 "k",
12073 keys.iter().copied().map(Scalar::Int64).collect::<Vec<_>>(),
12074 ),
12075 (pname, (0..n as i64).map(Scalar::Int64).collect::<Vec<_>>()),
12076 ],
12077 )
12078 .expect("frame")
12079 };
12080 let geti = |s: &Scalar| match s {
12081 Scalar::Int64(v) => *v,
12082 Scalar::Float64(v) if v.is_finite() => *v as i64,
12083 _ => i64::MIN,
12084 };
12085 let get_optional_i64 = |s: &Scalar| match s {
12086 Scalar::Int64(v) => Some(*v),
12087 Scalar::Float64(v) if v.is_finite() => Some(*v as i64),
12088 value if value.is_missing() => None,
12089 _ => Some(i64::MIN),
12090 };
12091
12092 for iter in 0..1500u32 {
12093 let nl = (next() % 9) as usize + 1;
12094 let nr = (next() % 9) as usize + 1;
12095 let lk: Vec<i64> = (0..nl).map(|_| (next() % 4) as i64).collect();
12096 let rk: Vec<i64> = (0..nr).map(|_| (next() % 5) as i64).collect();
12097 let left = build(&lk, "lv");
12098 let right = build(&rk, "rv");
12099
12100 let merged = merge_dataframes(&left, &right, "k", JoinType::Right).expect("merge");
12101 let ks = merged_values(&merged, "k").expect("k");
12102 let lvs = merged_values(&merged, "lv").expect("lv");
12103 let rvs = merged_values(&merged, "rv").expect("rv");
12104 let mut got: Vec<(i64, Option<i64>, i64)> = (0..ks.len())
12105 .map(|i| (geti(&ks[i]), get_optional_i64(&lvs[i]), geti(&rvs[i])))
12106 .collect();
12107 got.sort_unstable();
12108
12109 let mut lg: BTreeMap<i64, Vec<i64>> = BTreeMap::new();
12110 for (i, &k) in lk.iter().enumerate() {
12111 lg.entry(k).or_default().push(i as i64);
12112 }
12113 let mut exp: Vec<(i64, Option<i64>, i64)> = Vec::new();
12114 for (right_pos, &k) in rk.iter().enumerate() {
12115 if let Some(left_positions) = lg.get(&k) {
12116 for &left_pos in left_positions {
12117 exp.push((k, Some(left_pos), right_pos as i64));
12118 }
12119 } else {
12120 exp.push((k, None, right_pos as i64));
12121 }
12122 }
12123 exp.sort_unstable();
12124
12125 assert_eq!(
12126 got, exp,
12127 "right join value multiset iter={iter} lk={lk:?} rk={rk:?}"
12128 );
12129 }
12130 }
12131
12132 fn merged_values<'a>(
12133 merged: &'a MergedDataFrame,
12134 name: &str,
12135 ) -> Result<&'a [Scalar], JoinError> {
12136 Ok(merged
12137 .columns
12138 .get(name)
12139 .ok_or_else(|| {
12140 JoinError::Frame(FrameError::CompatibilityRejected(format!(
12141 "missing merged column '{name}'"
12142 )))
12143 })?
12144 .values())
12145 }
12146
12147 #[test]
12148 fn temporal_i64_inner_positions_match_scalar_oracle_with_duplicates_b2hwb() {
12149 let build_positions_from_scalar_oracle = |left: &Column, right: &Column| {
12150 let left_keys = super::collect_single_join_keys(left);
12151 let right_keys = super::collect_single_join_keys(right);
12152 let mut left_positions = Vec::new();
12153 let mut right_positions = Vec::new();
12154 for (left_pos, left_key) in left_keys.iter().enumerate() {
12155 for (right_pos, right_key) in right_keys.iter().enumerate() {
12156 if left_key == right_key {
12157 left_positions.push(left_pos);
12158 right_positions.push(right_pos);
12159 }
12160 }
12161 }
12162 (left_positions, right_positions)
12163 };
12164
12165 let left_ns = [30, 10, 20, 10];
12166 let right_ns = [10, 30, 10, 40];
12167 for temporal in [DType::Datetime64, DType::Timedelta64] {
12168 let scalar = |ns| match temporal {
12169 DType::Datetime64 => Scalar::Datetime64(ns),
12170 DType::Timedelta64 => Scalar::Timedelta64(ns),
12171 _ => unreachable!("test iterates only temporal dtypes"),
12172 };
12173 let left = Column::from_values(left_ns.into_iter().map(scalar).collect())
12174 .expect("left temporal key");
12175 let right = Column::from_values(right_ns.into_iter().map(scalar).collect())
12176 .expect("right temporal key");
12177
12178 assert_eq!(
12179 super::temporal_i64_inner_positions(&left, &right),
12180 Some(build_positions_from_scalar_oracle(&left, &right)),
12181 "raw-nanosecond planner must preserve scalar-oracle pair order for {temporal:?}"
12182 );
12183 }
12184
12185 let nat = fp_types::Timestamp::NAT;
12186 let ordered = Column::from_datetime64_values(vec![1, 2, 3, 4]);
12187 let nat_middle = Column::from_datetime64_values(vec![1, 2, nat, 4]);
12188 let nat_tail = Column::from_datetime64_values(vec![1, 2, 3, nat]);
12189 let single_nat = Column::from_datetime64_values(vec![nat]);
12190 for (left, right) in [
12191 (&nat_middle, &ordered),
12192 (&ordered, &nat_tail),
12193 (&single_nat, &ordered),
12194 ] {
12195 assert!(
12196 super::temporal_i64_inner_positions(left, right).is_none(),
12197 "NaT anywhere must retain the scalar INNER fallback",
12198 );
12199 }
12200 }
12201
12202 #[test]
12203 #[ignore = "foreground performance probe"]
12204 fn bench_temporal_i64_inner_validation_fusion_71kgc() {
12205 let n = 400_000_i64;
12206 let input_len = usize::try_from(n).expect("positive benchmark length");
12207 let left = Column::from_datetime64_values_with_validity(
12208 (0..n).collect(),
12209 ValidityMask::all_valid(input_len),
12210 );
12211 let right = Column::from_datetime64_values_with_validity(
12212 (0..n).map(|value| value * 2).collect(),
12213 ValidityMask::all_valid(input_len),
12214 );
12215
12216 let former = || {
12219 if !left.validity().all() || !right.validity().all() {
12220 return None;
12221 }
12222 let left_raw = left.as_datetime64_slice()?;
12223 let right_raw = right.as_datetime64_slice()?;
12224 let nat = fp_types::Timestamp::NAT;
12225 if left_raw.contains(&nat) || right_raw.contains(&nat) {
12226 return None;
12227 }
12228 if left_raw.windows(2).any(|pair| pair[0] >= pair[1])
12229 || right_raw.windows(2).any(|pair| pair[0] >= pair[1])
12230 {
12231 return None;
12232 }
12233
12234 let mut left_positions = Vec::with_capacity(left_raw.len().min(right_raw.len()));
12235 let mut right_positions = Vec::with_capacity(left_positions.capacity());
12236 let (mut left_idx, mut right_idx) = (0usize, 0usize);
12237 while left_idx < left_raw.len() && right_idx < right_raw.len() {
12238 match left_raw[left_idx].cmp(&right_raw[right_idx]) {
12239 std::cmp::Ordering::Equal => {
12240 left_positions.push(left_idx);
12241 right_positions.push(right_idx);
12242 left_idx += 1;
12243 right_idx += 1;
12244 }
12245 std::cmp::Ordering::Less => left_idx += 1,
12246 std::cmp::Ordering::Greater => right_idx += 1,
12247 }
12248 }
12249 Some((left_positions, right_positions))
12250 };
12251 let candidate = || super::temporal_i64_inner_positions(&left, &right);
12252
12253 let former_output = former().expect("former temporal INNER positions");
12254 let candidate_output = candidate().expect("temporal INNER positions");
12255 assert_eq!(candidate_output, former_output);
12256 assert_eq!(candidate_output.0.len(), input_len.div_ceil(2));
12257 drop((former_output, candidate_output));
12258 for _ in 0..2 {
12259 std::hint::black_box(former());
12260 std::hint::black_box(candidate());
12261 }
12262
12263 type InnerPositions = Option<(Vec<usize>, Vec<usize>)>;
12264 let sample = |plan: &dyn Fn() -> InnerPositions| {
12265 let start = std::time::Instant::now();
12266 let output = std::hint::black_box(plan()).expect("supported temporal INNER plan");
12267 assert_eq!(std::hint::black_box(output.0.len()), input_len.div_ceil(2));
12268 drop(output);
12269 start.elapsed().as_secs_f64() * 1_000.0
12270 };
12271 let mut former_a = Vec::with_capacity(15);
12272 let mut former_b = Vec::with_capacity(15);
12273 let mut candidate_a = Vec::with_capacity(15);
12274 let mut candidate_b = Vec::with_capacity(15);
12275 for round in 0..15 {
12276 if round % 2 == 0 {
12277 former_a.push(sample(&former));
12278 candidate_a.push(sample(&candidate));
12279 candidate_b.push(sample(&candidate));
12280 former_b.push(sample(&former));
12281 } else {
12282 former_b.push(sample(&former));
12283 candidate_b.push(sample(&candidate));
12284 candidate_a.push(sample(&candidate));
12285 former_a.push(sample(&former));
12286 }
12287 }
12288
12289 let report = |label: &str, mut samples: Vec<f64>| {
12290 samples.sort_by(f64::total_cmp);
12291 let p50 = samples[samples.len() / 2];
12292 let p95_idx = samples
12293 .len()
12294 .saturating_mul(95)
12295 .div_ceil(100)
12296 .saturating_sub(1);
12297 println!(
12298 "{label}: p50={p50:.3} ms p95={:.3} ms max={:.3} ms",
12299 samples[p95_idx],
12300 samples[samples.len() - 1],
12301 );
12302 };
12303 report("inner_plan_three_pass_former_a", former_a);
12304 report("inner_plan_three_pass_former_b", former_b);
12305 report("inner_plan_fused_candidate_a", candidate_a);
12306 report("inner_plan_fused_candidate_b", candidate_b);
12307 }
12308
12309 #[test]
12310 fn merge_datetime_inner_preserves_dtype_order_and_nat_fallback_b2hwb()
12311 -> Result<(), JoinError> {
12312 let left = DataFrame::from_dict(
12313 &["key", "lv"],
12314 vec![
12315 (
12316 "key",
12317 vec![
12318 Scalar::Datetime64(30),
12319 Scalar::Datetime64(10),
12320 Scalar::Datetime64(20),
12321 Scalar::Datetime64(10),
12322 ],
12323 ),
12324 (
12325 "lv",
12326 vec![
12327 Scalar::Int64(0),
12328 Scalar::Int64(1),
12329 Scalar::Int64(2),
12330 Scalar::Int64(3),
12331 ],
12332 ),
12333 ],
12334 )?;
12335 let right = DataFrame::from_dict(
12336 &["key", "rv"],
12337 vec![
12338 (
12339 "key",
12340 vec![
12341 Scalar::Datetime64(10),
12342 Scalar::Datetime64(30),
12343 Scalar::Datetime64(10),
12344 Scalar::Datetime64(40),
12345 ],
12346 ),
12347 (
12348 "rv",
12349 vec![
12350 Scalar::Int64(100),
12351 Scalar::Int64(101),
12352 Scalar::Int64(102),
12353 Scalar::Int64(103),
12354 ],
12355 ),
12356 ],
12357 )?;
12358 let merged = merge_dataframes_on(&left, &right, &["key"], JoinType::Inner)?;
12359 assert_eq!(merged.columns["key"].dtype(), DType::Datetime64);
12360 assert_eq!(
12361 merged_values(&merged, "key")?,
12362 &[
12363 Scalar::Datetime64(30),
12364 Scalar::Datetime64(10),
12365 Scalar::Datetime64(10),
12366 Scalar::Datetime64(10),
12367 Scalar::Datetime64(10),
12368 ]
12369 );
12370 assert_eq!(
12371 merged_values(&merged, "lv")?,
12372 &[
12373 Scalar::Int64(0),
12374 Scalar::Int64(1),
12375 Scalar::Int64(1),
12376 Scalar::Int64(3),
12377 Scalar::Int64(3),
12378 ]
12379 );
12380 assert_eq!(
12381 merged_values(&merged, "rv")?,
12382 &[
12383 Scalar::Int64(101),
12384 Scalar::Int64(100),
12385 Scalar::Int64(102),
12386 Scalar::Int64(100),
12387 Scalar::Int64(102),
12388 ]
12389 );
12390
12391 let nat = fp_types::Timestamp::NAT;
12392 let nat_left = DataFrame::from_dict(
12393 &["key", "lv"],
12394 vec![
12395 (
12396 "key",
12397 vec![Scalar::Datetime64(nat), Scalar::Datetime64(5)],
12398 ),
12399 ("lv", vec![Scalar::Int64(0), Scalar::Int64(1)]),
12400 ],
12401 )?;
12402 let nat_right = DataFrame::from_dict(
12403 &["key", "rv"],
12404 vec![
12405 (
12406 "key",
12407 vec![Scalar::Datetime64(nat), Scalar::Datetime64(5)],
12408 ),
12409 ("rv", vec![Scalar::Int64(10), Scalar::Int64(11)]),
12410 ],
12411 )?;
12412 assert!(
12413 super::temporal_i64_inner_positions(
12414 nat_left.column("key").expect("left NaT key"),
12415 nat_right.column("key").expect("right NaT key")
12416 )
12417 .is_none(),
12418 "NaT must retain the scalar Missing-key fallback"
12419 );
12420 let nat_merged =
12421 merge_dataframes_on(&nat_left, &nat_right, &["key"], JoinType::Inner)?;
12422 assert_eq!(nat_merged.columns["key"].dtype(), DType::Datetime64);
12423 assert_eq!(nat_merged.index.len(), 2);
12424 assert!(merged_values(&nat_merged, "key")?[0].is_missing());
12425 assert_eq!(
12426 &merged_values(&nat_merged, "key")?[1..],
12427 &[Scalar::Datetime64(5)]
12428 );
12429
12430 Ok(())
12431 }
12432
12433 #[test]
12434 fn temporal_i64_left_positions_match_scalar_oracle_with_duplicates_lw0qg() {
12435 let build_positions_from_scalar_oracle = |left: &Column, right: &Column| {
12436 let left_keys = super::collect_single_join_keys(left);
12437 let right_keys = super::collect_single_join_keys(right);
12438 let mut left_positions = Vec::new();
12439 let mut right_positions = Vec::new();
12440 for (left_pos, left_key) in left_keys.iter().enumerate() {
12441 let mut matched = false;
12442 for (right_pos, right_key) in right_keys.iter().enumerate() {
12443 if left_key == right_key {
12444 left_positions.push(Some(left_pos));
12445 right_positions.push(Some(right_pos));
12446 matched = true;
12447 }
12448 }
12449 if !matched {
12450 left_positions.push(Some(left_pos));
12451 right_positions.push(None);
12452 }
12453 }
12454 (left_positions, right_positions)
12455 };
12456
12457 let left_ns = [30, 10, 20, 10, 50];
12458 let right_ns = [10, 30, 10, 40];
12459 for temporal in [DType::Datetime64, DType::Timedelta64] {
12460 let scalar = |ns| match temporal {
12461 DType::Datetime64 => Scalar::Datetime64(ns),
12462 DType::Timedelta64 => Scalar::Timedelta64(ns),
12463 _ => unreachable!("test iterates only temporal dtypes"),
12464 };
12465 let left = Column::from_values(left_ns.into_iter().map(scalar).collect())
12466 .expect("left temporal key");
12467 let right = Column::from_values(right_ns.into_iter().map(scalar).collect())
12468 .expect("right temporal key");
12469
12470 assert_eq!(
12471 super::temporal_i64_left_positions(&left, &right),
12472 Some(build_positions_from_scalar_oracle(&left, &right)),
12473 "raw-nanosecond LEFT planner must preserve scalar-oracle row order for {temporal:?}"
12474 );
12475 }
12476 }
12477
12478 #[test]
12479 fn merge_datetime_left_preserves_dtype_order_and_nat_fallback_lw0qg()
12480 -> Result<(), JoinError> {
12481 let left = DataFrame::from_dict(
12482 &["key", "lv"],
12483 vec![
12484 (
12485 "key",
12486 vec![
12487 Scalar::Datetime64(30),
12488 Scalar::Datetime64(10),
12489 Scalar::Datetime64(20),
12490 Scalar::Datetime64(10),
12491 Scalar::Datetime64(50),
12492 ],
12493 ),
12494 (
12495 "lv",
12496 vec![
12497 Scalar::Int64(0),
12498 Scalar::Int64(1),
12499 Scalar::Int64(2),
12500 Scalar::Int64(3),
12501 Scalar::Int64(4),
12502 ],
12503 ),
12504 ],
12505 )?;
12506 let right = DataFrame::from_dict(
12507 &["key", "rv"],
12508 vec![
12509 (
12510 "key",
12511 vec![
12512 Scalar::Datetime64(10),
12513 Scalar::Datetime64(30),
12514 Scalar::Datetime64(10),
12515 Scalar::Datetime64(40),
12516 ],
12517 ),
12518 (
12519 "rv",
12520 vec![
12521 Scalar::Int64(100),
12522 Scalar::Int64(101),
12523 Scalar::Int64(102),
12524 Scalar::Int64(103),
12525 ],
12526 ),
12527 ],
12528 )?;
12529 let merged = merge_dataframes_on(&left, &right, &["key"], JoinType::Left)?;
12530 assert_eq!(merged.columns["key"].dtype(), DType::Datetime64);
12531 assert_eq!(
12532 merged_values(&merged, "key")?,
12533 &[
12534 Scalar::Datetime64(30),
12535 Scalar::Datetime64(10),
12536 Scalar::Datetime64(10),
12537 Scalar::Datetime64(20),
12538 Scalar::Datetime64(10),
12539 Scalar::Datetime64(10),
12540 Scalar::Datetime64(50),
12541 ]
12542 );
12543 assert_eq!(
12544 merged_values(&merged, "lv")?,
12545 &[
12546 Scalar::Int64(0),
12547 Scalar::Int64(1),
12548 Scalar::Int64(1),
12549 Scalar::Int64(2),
12550 Scalar::Int64(3),
12551 Scalar::Int64(3),
12552 Scalar::Int64(4),
12553 ]
12554 );
12555 let right_values = merged_values(&merged, "rv")?;
12556 assert_eq!(right_values.len(), 7);
12557 assert_eq!(right_values[0], Scalar::Int64(101));
12558 assert_eq!(&right_values[1..3], &[Scalar::Int64(100), Scalar::Int64(102)]);
12559 assert!(right_values[3].is_missing());
12560 assert_eq!(&right_values[4..6], &[Scalar::Int64(100), Scalar::Int64(102)]);
12561 assert!(right_values[6].is_missing());
12562
12563 let nat = fp_types::Timestamp::NAT;
12564 let nat_left = DataFrame::from_dict(
12565 &["key", "lv"],
12566 vec![
12567 (
12568 "key",
12569 vec![
12570 Scalar::Datetime64(nat),
12571 Scalar::Datetime64(5),
12572 Scalar::Datetime64(7),
12573 ],
12574 ),
12575 (
12576 "lv",
12577 vec![Scalar::Int64(0), Scalar::Int64(1), Scalar::Int64(2)],
12578 ),
12579 ],
12580 )?;
12581 let nat_right = DataFrame::from_dict(
12582 &["key", "rv"],
12583 vec![
12584 (
12585 "key",
12586 vec![Scalar::Datetime64(nat), Scalar::Datetime64(5)],
12587 ),
12588 ("rv", vec![Scalar::Int64(10), Scalar::Int64(11)]),
12589 ],
12590 )?;
12591 assert!(
12592 super::temporal_i64_left_positions(
12593 nat_left.column("key").expect("left NaT key"),
12594 nat_right.column("key").expect("right NaT key")
12595 )
12596 .is_none(),
12597 "NaT must retain the scalar Missing-key fallback"
12598 );
12599 let nat_merged =
12600 merge_dataframes_on(&nat_left, &nat_right, &["key"], JoinType::Left)?;
12601 assert_eq!(nat_merged.columns["key"].dtype(), DType::Datetime64);
12602 assert_eq!(nat_merged.index.len(), 3);
12603 assert!(merged_values(&nat_merged, "key")?[0].is_missing());
12604 assert_eq!(
12605 &merged_values(&nat_merged, "key")?[1..],
12606 &[Scalar::Datetime64(5), Scalar::Datetime64(7)]
12607 );
12608 let nat_right_values = merged_values(&nat_merged, "rv")?;
12609 assert_eq!(&nat_right_values[..2], &[Scalar::Int64(10), Scalar::Int64(11)]);
12610 assert!(nat_right_values[2].is_missing());
12611
12612 Ok(())
12613 }
12614
12615 #[test]
12616 fn temporal_i64_right_positions_match_scalar_oracle_and_reject_unsupported_8tf5c() {
12617 let scalar_oracle = |left: &Column, right: &Column| {
12618 let left_keys = super::collect_single_join_keys(left);
12619 let right_keys = super::collect_single_join_keys(right);
12620 right_keys
12621 .iter()
12622 .map(|right_key| left_keys.iter().position(|left_key| left_key == right_key))
12623 .collect::<Vec<_>>()
12624 };
12625
12626 let left_ns = [-20, 10, 30, 50];
12627 let right_ns = [-30, -20, 20, 30, 60];
12628 for temporal in [DType::Datetime64, DType::Timedelta64] {
12629 let scalar = |ns| match temporal {
12630 DType::Datetime64 => Scalar::Datetime64(ns),
12631 DType::Timedelta64 => Scalar::Timedelta64(ns),
12632 _ => unreachable!("test iterates only temporal dtypes"),
12633 };
12634 let left = Column::from_values(left_ns.into_iter().map(scalar).collect())
12635 .expect("left temporal key");
12636 let right = Column::from_values(right_ns.into_iter().map(scalar).collect())
12637 .expect("right temporal key");
12638 assert_eq!(
12639 super::ordered_unique_temporal_i64_right_match_positions(&left, &right),
12640 Some(scalar_oracle(&left, &right)),
12641 "raw-nanosecond RIGHT planner must preserve right-major scalar matches for {temporal:?}",
12642 );
12643 }
12644
12645 let empty_left = Column::from_datetime64_values(Vec::new());
12646 let ordered_right = Column::from_datetime64_values(vec![1, 2, 3]);
12647 assert_eq!(
12648 super::ordered_unique_temporal_i64_right_match_positions(
12649 &empty_left,
12650 &ordered_right,
12651 ),
12652 Some(vec![None; 3]),
12653 );
12654
12655 let nat = fp_types::Timestamp::NAT;
12656 let nat_left = Column::from_datetime64_values(vec![nat, 1, 2]);
12657 let nat_middle_left = Column::from_datetime64_values(vec![1, nat, 3]);
12658 let nat_tail_right = Column::from_datetime64_values(vec![1, 2, nat]);
12659 let single_nat = Column::from_datetime64_values(vec![nat]);
12660 let duplicate_left = Column::from_datetime64_values(vec![1, 1, 2]);
12661 let late_duplicate_left = Column::from_datetime64_values(vec![1, 2, 3, 3]);
12662 let unsorted_right = Column::from_datetime64_values(vec![2, 1, 3]);
12663 let late_unsorted_right = Column::from_datetime64_values(vec![1, 2, 4, 3]);
12664 let mixed_right = Column::from_values(
12665 [1, 2, 3]
12666 .into_iter()
12667 .map(Scalar::Timedelta64)
12668 .collect(),
12669 )
12670 .expect("mixed timedelta key");
12671 let mut validity = ValidityMask::all_valid(3);
12672 validity.set(1, false);
12673 let nullable_left =
12674 Column::from_datetime64_values_with_validity(vec![1, 2, 3], validity);
12675 for (left, right) in [
12676 (&nat_left, &ordered_right),
12677 (&nat_middle_left, &ordered_right),
12678 (&ordered_right, &nat_tail_right),
12679 (&single_nat, &ordered_right),
12680 (&duplicate_left, &ordered_right),
12681 (&late_duplicate_left, &ordered_right),
12682 (&ordered_right, &unsorted_right),
12683 (&ordered_right, &late_unsorted_right),
12684 (&ordered_right, &mixed_right),
12685 (&nullable_left, &ordered_right),
12686 ] {
12687 assert!(
12688 super::ordered_unique_temporal_i64_right_match_positions(left, right).is_none(),
12689 "unsupported temporal RIGHT shape must retain the scalar fallback",
12690 );
12691 }
12692 }
12693
12694 #[test]
12695 #[ignore = "foreground performance probe"]
12696 fn bench_temporal_i64_right_validation_fusion_69e0m() {
12697 let n = 400_000_i64;
12698 let input_len = usize::try_from(n).expect("positive benchmark length");
12699 let left = Column::from_datetime64_values_with_validity(
12700 (0..n).collect(),
12701 ValidityMask::all_valid(input_len),
12702 );
12703 let right = Column::from_datetime64_values_with_validity(
12704 (0..n).map(|value| value * 2).collect(),
12705 ValidityMask::all_valid(input_len),
12706 );
12707
12708 let former = || {
12711 if !left.validity().all() || !right.validity().all() {
12712 return None;
12713 }
12714 let left_raw = left.as_datetime64_slice()?;
12715 let right_raw = right.as_datetime64_slice()?;
12716 let nat = fp_types::Timestamp::NAT;
12717 if left_raw.contains(&nat) || right_raw.contains(&nat) {
12718 return None;
12719 }
12720 if left_raw.windows(2).any(|pair| pair[0] >= pair[1])
12721 || right_raw.windows(2).any(|pair| pair[0] >= pair[1])
12722 {
12723 return None;
12724 }
12725
12726 let mut left_positions = Vec::with_capacity(right_raw.len());
12727 let mut left_idx = 0usize;
12728 for &right_value in right_raw {
12729 while left_idx < left_raw.len() && left_raw[left_idx] < right_value {
12730 left_idx += 1;
12731 }
12732 left_positions.push(
12733 (left_idx < left_raw.len()
12734 && matches!(
12735 left_raw[left_idx].cmp(&right_value),
12736 std::cmp::Ordering::Equal
12737 ))
12738 .then_some(left_idx),
12739 );
12740 }
12741 Some(left_positions)
12742 };
12743 let candidate = || {
12744 super::ordered_unique_temporal_i64_right_match_positions(&left, &right)
12745 };
12746
12747 let former_output = former().expect("former temporal RIGHT positions");
12748 let candidate_output = candidate().expect("fused temporal RIGHT positions");
12749 assert_eq!(candidate_output, former_output);
12750 assert_eq!(candidate_output.len(), input_len);
12751 drop((former_output, candidate_output));
12752 for _ in 0..2 {
12753 std::hint::black_box(former());
12754 std::hint::black_box(candidate());
12755 }
12756
12757 let sample = |plan: &dyn Fn() -> Option<Vec<Option<usize>>>| {
12758 let start = std::time::Instant::now();
12759 let output = std::hint::black_box(plan()).expect("supported temporal RIGHT plan");
12760 assert_eq!(std::hint::black_box(output.len()), input_len);
12761 drop(output);
12762 start.elapsed().as_secs_f64() * 1_000.0
12763 };
12764 let mut former_a = Vec::with_capacity(15);
12765 let mut former_b = Vec::with_capacity(15);
12766 let mut candidate_a = Vec::with_capacity(15);
12767 let mut candidate_b = Vec::with_capacity(15);
12768 for round in 0..15 {
12769 if round % 2 == 0 {
12770 former_a.push(sample(&former));
12771 candidate_a.push(sample(&candidate));
12772 candidate_b.push(sample(&candidate));
12773 former_b.push(sample(&former));
12774 } else {
12775 former_b.push(sample(&former));
12776 candidate_b.push(sample(&candidate));
12777 candidate_a.push(sample(&candidate));
12778 former_a.push(sample(&former));
12779 }
12780 }
12781
12782 let report = |label: &str, mut samples: Vec<f64>| {
12783 samples.sort_by(f64::total_cmp);
12784 let p50 = samples[samples.len() / 2];
12785 let p95_idx = samples
12786 .len()
12787 .saturating_mul(95)
12788 .div_ceil(100)
12789 .saturating_sub(1);
12790 println!(
12791 "{label}: p50={p50:.3} ms p95={:.3} ms max={:.3} ms",
12792 samples[p95_idx],
12793 samples[samples.len() - 1],
12794 );
12795 };
12796 report("right_plan_three_pass_former_a", former_a);
12797 report("right_plan_three_pass_former_b", former_b);
12798 report("right_plan_fused_candidate_a", candidate_a);
12799 report("right_plan_fused_candidate_b", candidate_b);
12800 }
12801
12802 #[test]
12803 fn merge_datetime_right_preserves_dtype_order_and_nat_fallback_8tf5c()
12804 -> Result<(), JoinError> {
12805 let left = DataFrame::from_dict(
12806 &["key", "lv"],
12807 vec![
12808 (
12809 "key",
12810 vec![
12811 Scalar::Datetime64(10),
12812 Scalar::Datetime64(30),
12813 Scalar::Datetime64(50),
12814 ],
12815 ),
12816 (
12817 "lv",
12818 vec![Scalar::Int64(0), Scalar::Int64(1), Scalar::Int64(2)],
12819 ),
12820 ],
12821 )?;
12822 let right = DataFrame::from_dict(
12823 &["key", "rv"],
12824 vec![
12825 (
12826 "key",
12827 vec![
12828 Scalar::Datetime64(0),
12829 Scalar::Datetime64(10),
12830 Scalar::Datetime64(40),
12831 Scalar::Datetime64(50),
12832 Scalar::Datetime64(60),
12833 ],
12834 ),
12835 (
12836 "rv",
12837 vec![
12838 Scalar::Int64(100),
12839 Scalar::Int64(101),
12840 Scalar::Int64(102),
12841 Scalar::Int64(103),
12842 Scalar::Int64(104),
12843 ],
12844 ),
12845 ],
12846 )?;
12847 let merged = merge_dataframes_on(&left, &right, &["key"], JoinType::Right)?;
12848 assert_eq!(merged.columns["key"].dtype(), DType::Datetime64);
12849 assert_eq!(
12850 merged_values(&merged, "key")?,
12851 &[
12852 Scalar::Datetime64(0),
12853 Scalar::Datetime64(10),
12854 Scalar::Datetime64(40),
12855 Scalar::Datetime64(50),
12856 Scalar::Datetime64(60),
12857 ],
12858 );
12859 assert_eq!(
12860 merged_values(&merged, "rv")?,
12861 &[
12862 Scalar::Int64(100),
12863 Scalar::Int64(101),
12864 Scalar::Int64(102),
12865 Scalar::Int64(103),
12866 Scalar::Int64(104),
12867 ],
12868 );
12869 let left_values = merged_values(&merged, "lv")?;
12870 assert_eq!(left_values.len(), 5);
12871 assert!(left_values[0].is_missing());
12872 assert_eq!(left_values[1], Scalar::Int64(0));
12873 assert!(left_values[2].is_missing());
12874 assert_eq!(left_values[3], Scalar::Int64(2));
12875 assert!(left_values[4].is_missing());
12876
12877 let nat = fp_types::Timestamp::NAT;
12878 let nat_left = DataFrame::from_dict(
12879 &["key", "lv"],
12880 vec![
12881 (
12882 "key",
12883 vec![Scalar::Datetime64(nat), Scalar::Datetime64(5)],
12884 ),
12885 ("lv", vec![Scalar::Int64(0), Scalar::Int64(1)]),
12886 ],
12887 )?;
12888 let nat_right = DataFrame::from_dict(
12889 &["key", "rv"],
12890 vec![
12891 (
12892 "key",
12893 vec![
12894 Scalar::Datetime64(nat),
12895 Scalar::Datetime64(5),
12896 Scalar::Datetime64(7),
12897 ],
12898 ),
12899 (
12900 "rv",
12901 vec![Scalar::Int64(10), Scalar::Int64(11), Scalar::Int64(12)],
12902 ),
12903 ],
12904 )?;
12905 assert!(
12906 super::ordered_unique_temporal_i64_right_match_positions(
12907 nat_left.column("key").expect("left NaT key"),
12908 nat_right.column("key").expect("right NaT key"),
12909 )
12910 .is_none(),
12911 "NaT must retain the scalar Missing-key fallback",
12912 );
12913 let nat_merged =
12914 merge_dataframes_on(&nat_left, &nat_right, &["key"], JoinType::Right)?;
12915 assert_eq!(nat_merged.columns["key"].dtype(), DType::Datetime64);
12916 assert_eq!(nat_merged.index.len(), 3);
12917 assert!(merged_values(&nat_merged, "key")?[0].is_missing());
12918 assert_eq!(
12919 &merged_values(&nat_merged, "key")?[1..],
12920 &[Scalar::Datetime64(5), Scalar::Datetime64(7)],
12921 );
12922 let nat_left_values = merged_values(&nat_merged, "lv")?;
12923 assert_eq!(&nat_left_values[..2], &[Scalar::Int64(0), Scalar::Int64(1)]);
12924 assert!(nat_left_values[2].is_missing());
12925
12926 Ok(())
12927 }
12928
12929 #[test]
12930 fn temporal_i64_outer_key_coalesce_matches_scalar_and_declines_unsupported_i4gzc() {
12931 let left_positions = [None, Some(0), Some(1), None, Some(2), Some(3), None];
12932 let right_positions = [Some(0), Some(1), None, Some(2), Some(3), None, Some(4)];
12933 let left_ns = vec![-20, 10, 30, 50];
12934 let right_ns = vec![-30, -20, 20, 30, 60];
12935 let union_ns = [-30, -20, 10, 20, 30, 50, 60];
12936 let temporal_column = |dtype, values: Vec<i64>| {
12937 let len = values.len();
12938 match dtype {
12939 DType::Datetime64 => Column::from_datetime64_values_with_validity(
12940 values,
12941 ValidityMask::all_valid(len),
12942 ),
12943 DType::Timedelta64 => Column::from_timedelta64_values_with_validity(
12944 values,
12945 ValidityMask::all_valid(len),
12946 ),
12947 _ => unreachable!("test iterates only temporal dtypes"),
12948 }
12949 };
12950
12951 for temporal in [DType::Datetime64, DType::Timedelta64] {
12952 let left = temporal_column(temporal, left_ns.clone());
12953 let right = temporal_column(temporal, right_ns.clone());
12954 let candidate = super::coalesce_temporal_i64_key_column(
12955 &left,
12956 &right,
12957 &left_positions,
12958 &right_positions,
12959 )
12960 .expect("supported temporal key coalesce");
12961 assert_eq!(candidate.dtype(), temporal);
12962 assert!(candidate.validity().all());
12963 let candidate_ns = match temporal {
12964 DType::Datetime64 => candidate.as_datetime64_slice(),
12965 DType::Timedelta64 => candidate.as_timedelta64_slice(),
12966 _ => unreachable!("test iterates only temporal dtypes"),
12967 };
12968 assert_eq!(candidate_ns, Some(union_ns.as_slice()));
12969
12970 let reference_values = left_positions
12971 .iter()
12972 .zip(right_positions.iter())
12973 .map(|(left_pos, right_pos)| match (left_pos, right_pos) {
12974 (Some(pos), _) => left.values()[*pos].clone(),
12975 (None, Some(pos)) => right.values()[*pos].clone(),
12976 (None, None) => Scalar::Null(NullKind::Null),
12977 })
12978 .collect::<Vec<_>>();
12979 let reference = Column::from_values(reference_values).expect("scalar reference");
12980 assert_eq!(candidate, reference);
12981 }
12982
12983 let datetime_left = temporal_column(DType::Datetime64, left_ns);
12984 let datetime_right = temporal_column(DType::Datetime64, right_ns);
12985 let timedelta_right = temporal_column(DType::Timedelta64, vec![-30, -20, 20, 30, 60]);
12986 let mut nullable_validity = ValidityMask::all_valid(datetime_left.len());
12987 nullable_validity.set(1, false);
12988 let nullable_left = Column::from_datetime64_values_with_validity(
12989 vec![-20, 10, 30, 50],
12990 nullable_validity,
12991 );
12992 let nat_left = Column::from_datetime64_values_with_validity(
12993 vec![fp_types::Timestamp::NAT, 10, 30, 50],
12994 ValidityMask::all_valid(4),
12995 );
12996 for (left, right, left_tape, right_tape) in [
12997 (
12998 &nullable_left,
12999 &datetime_right,
13000 left_positions.as_slice(),
13001 right_positions.as_slice(),
13002 ),
13003 (
13004 &datetime_left,
13005 &timedelta_right,
13006 left_positions.as_slice(),
13007 right_positions.as_slice(),
13008 ),
13009 (&nat_left, &datetime_right, &[Some(0)], &[Some(0)]),
13010 (&datetime_left, &datetime_right, &[Some(0)], &[]),
13011 (&datetime_left, &datetime_right, &[Some(99)], &[None]),
13012 (&datetime_left, &datetime_right, &[None], &[None]),
13013 ] {
13014 assert!(
13015 super::coalesce_temporal_i64_key_column(
13016 left,
13017 right,
13018 left_tape,
13019 right_tape,
13020 )
13021 .is_none(),
13022 "unsupported temporal key coalesce must retain Scalar fallback",
13023 );
13024 }
13025 }
13026
13027 #[test]
13028 #[ignore = "foreground performance probe"]
13029 fn bench_temporal_i64_outer_key_coalesce_i4gzc() {
13030 let n = 200_000_i64;
13031 let input_len = usize::try_from(n).expect("positive benchmark length");
13032 let left = Column::from_datetime64_values_with_validity(
13033 (0..n).collect(),
13034 ValidityMask::all_valid(input_len),
13035 );
13036 let right = Column::from_datetime64_values_with_validity(
13037 (0..n).map(|value| value * 2).collect(),
13038 ValidityMask::all_valid(input_len),
13039 );
13040 let (left_positions, right_positions) =
13041 super::ordered_unique_temporal_i64_outer_positions(&left, &right)
13042 .expect("ordered temporal position tapes");
13043 let expected_rows = 300_000usize;
13044 assert_eq!(left_positions.len(), expected_rows);
13045
13046 let former = || {
13047 let values = left_positions
13048 .iter()
13049 .zip(right_positions.iter())
13050 .map(|(left_pos, right_pos)| match (left_pos, right_pos) {
13051 (Some(pos), _) => left.values()[*pos].clone(),
13052 (None, Some(pos)) => right.values()[*pos].clone(),
13053 (None, None) => Scalar::Null(NullKind::Null),
13054 })
13055 .collect::<Vec<_>>();
13056 Column::from_values(values).expect("former Scalar key coalesce")
13057 };
13058 let candidate = || {
13059 super::coalesce_temporal_i64_key_column(
13060 &left,
13061 &right,
13062 &left_positions,
13063 &right_positions,
13064 )
13065 .expect("typed temporal key coalesce")
13066 };
13067
13068 let former_output = former();
13069 let candidate_output = candidate();
13070 assert_eq!(candidate_output, former_output);
13071 drop((former_output, candidate_output));
13072 for _ in 0..2 {
13073 std::hint::black_box(former());
13074 std::hint::black_box(candidate());
13075 }
13076
13077 let sample = |build: &dyn Fn() -> Column| {
13078 let start = std::time::Instant::now();
13079 let output = std::hint::black_box(build());
13080 assert_eq!(std::hint::black_box(output.len()), expected_rows);
13081 drop(output);
13082 start.elapsed().as_secs_f64() * 1_000.0
13083 };
13084 let mut former_a = Vec::with_capacity(15);
13085 let mut former_b = Vec::with_capacity(15);
13086 let mut candidate_a = Vec::with_capacity(15);
13087 let mut candidate_b = Vec::with_capacity(15);
13088 for round in 0..15 {
13089 if round % 2 == 0 {
13090 former_a.push(sample(&former));
13091 candidate_a.push(sample(&candidate));
13092 candidate_b.push(sample(&candidate));
13093 former_b.push(sample(&former));
13094 } else {
13095 former_b.push(sample(&former));
13096 candidate_b.push(sample(&candidate));
13097 candidate_a.push(sample(&candidate));
13098 former_a.push(sample(&former));
13099 }
13100 }
13101
13102 let report = |label: &str, mut samples: Vec<f64>| {
13103 samples.sort_by(f64::total_cmp);
13104 let p50 = samples[samples.len() / 2];
13105 let p95_idx = samples
13106 .len()
13107 .saturating_mul(95)
13108 .div_ceil(100)
13109 .saturating_sub(1);
13110 println!(
13111 "{label}: p50={p50:.3} ms p95={:.3} ms max={:.3} ms",
13112 samples[p95_idx],
13113 samples[samples.len() - 1],
13114 );
13115 };
13116 report("outer_key_scalar_former_a", former_a);
13117 report("outer_key_scalar_former_b", former_b);
13118 report("outer_key_typed_candidate_a", candidate_a);
13119 report("outer_key_typed_candidate_b", candidate_b);
13120 }
13121
13122 #[test]
13123 fn temporal_i64_outer_positions_match_ordered_union_and_reject_unsupported_rvb6u() {
13124 let left_ns = [-20, 10, 30, 50];
13125 let right_ns = [-30, -20, 20, 30, 60];
13126 let expected = (
13127 vec![None, Some(0), Some(1), None, Some(2), Some(3), None],
13128 vec![Some(0), Some(1), None, Some(2), Some(3), None, Some(4)],
13129 );
13130 for temporal in [DType::Datetime64, DType::Timedelta64] {
13131 let scalar = |ns| match temporal {
13132 DType::Datetime64 => Scalar::Datetime64(ns),
13133 DType::Timedelta64 => Scalar::Timedelta64(ns),
13134 _ => unreachable!("test iterates only temporal dtypes"),
13135 };
13136 let left = Column::from_values(left_ns.into_iter().map(scalar).collect())
13137 .expect("left temporal key");
13138 let right = Column::from_values(right_ns.into_iter().map(scalar).collect())
13139 .expect("right temporal key");
13140 assert_eq!(
13141 super::ordered_unique_temporal_i64_outer_positions(&left, &right),
13142 Some(expected.clone()),
13143 "raw-nanosecond OUTER planner must preserve key-sorted optional positions for {temporal:?}",
13144 );
13145 }
13146
13147 let empty_left = Column::from_datetime64_values(Vec::new());
13148 let ordered_right = Column::from_datetime64_values(vec![1, 2, 3]);
13149 assert_eq!(
13150 super::ordered_unique_temporal_i64_outer_positions(&empty_left, &ordered_right),
13151 Some((vec![None; 3], vec![Some(0), Some(1), Some(2)])),
13152 );
13153
13154 let nat = fp_types::Timestamp::NAT;
13155 let nat_left = Column::from_datetime64_values(vec![nat, 1, 2]);
13156 let duplicate_left = Column::from_datetime64_values(vec![1, 1, 2]);
13157 let unsorted_right = Column::from_datetime64_values(vec![2, 1, 3]);
13158 let mixed_right = Column::from_values(
13159 [1, 2, 3]
13160 .into_iter()
13161 .map(Scalar::Timedelta64)
13162 .collect(),
13163 )
13164 .expect("mixed timedelta key");
13165 let mut validity = ValidityMask::all_valid(3);
13166 validity.set(1, false);
13167 let nullable_left =
13168 Column::from_datetime64_values_with_validity(vec![1, 2, 3], validity);
13169 for (left, right) in [
13170 (&nat_left, &ordered_right),
13171 (&duplicate_left, &ordered_right),
13172 (&ordered_right, &unsorted_right),
13173 (&ordered_right, &mixed_right),
13174 (&nullable_left, &ordered_right),
13175 ] {
13176 assert!(
13177 super::ordered_unique_temporal_i64_outer_positions(left, right).is_none(),
13178 "unsupported temporal OUTER shape must retain the scalar fallback",
13179 );
13180 }
13181 }
13182
13183 #[test]
13184 #[ignore = "foreground performance probe"]
13185 fn bench_temporal_i64_outer_validation_fusion_pizud() {
13186 let n = 400_000_i64;
13187 let input_len = usize::try_from(n).expect("positive benchmark length");
13188 let left = Column::from_datetime64_values_with_validity(
13189 (0..n).collect(),
13190 ValidityMask::all_valid(input_len),
13191 );
13192 let right = Column::from_datetime64_values_with_validity(
13193 (0..n).map(|value| value * 2).collect(),
13194 ValidityMask::all_valid(input_len),
13195 );
13196 let expected_rows = 600_000usize;
13197
13198 let former = || {
13201 if !left.validity().all() || !right.validity().all() {
13202 return None;
13203 }
13204 let left_raw = left.as_datetime64_slice()?;
13205 let right_raw = right.as_datetime64_slice()?;
13206 let nat = fp_types::Timestamp::NAT;
13207 if left_raw.contains(&nat) || right_raw.contains(&nat) {
13208 return None;
13209 }
13210 if left_raw.windows(2).any(|pair| pair[0] >= pair[1])
13211 || right_raw.windows(2).any(|pair| pair[0] >= pair[1])
13212 {
13213 return None;
13214 }
13215
13216 let capacity = left_raw.len().saturating_add(right_raw.len());
13217 let mut left_positions = Vec::<Option<usize>>::with_capacity(capacity);
13218 let mut right_positions = Vec::<Option<usize>>::with_capacity(capacity);
13219 let (mut left_idx, mut right_idx) = (0usize, 0usize);
13220 while left_idx < left_raw.len() && right_idx < right_raw.len() {
13221 match left_raw[left_idx].cmp(&right_raw[right_idx]) {
13222 std::cmp::Ordering::Equal => {
13223 left_positions.push(Some(left_idx));
13224 right_positions.push(Some(right_idx));
13225 left_idx += 1;
13226 right_idx += 1;
13227 }
13228 std::cmp::Ordering::Less => {
13229 left_positions.push(Some(left_idx));
13230 right_positions.push(None);
13231 left_idx += 1;
13232 }
13233 std::cmp::Ordering::Greater => {
13234 left_positions.push(None);
13235 right_positions.push(Some(right_idx));
13236 right_idx += 1;
13237 }
13238 }
13239 }
13240 while left_idx < left_raw.len() {
13241 left_positions.push(Some(left_idx));
13242 right_positions.push(None);
13243 left_idx += 1;
13244 }
13245 while right_idx < right_raw.len() {
13246 left_positions.push(None);
13247 right_positions.push(Some(right_idx));
13248 right_idx += 1;
13249 }
13250 Some((left_positions, right_positions))
13251 };
13252 let candidate = || super::ordered_unique_temporal_i64_outer_positions(&left, &right);
13253
13254 let former_output = former().expect("former temporal union");
13255 let candidate_output = candidate().expect("fused temporal union");
13256 assert_eq!(candidate_output, former_output);
13257 assert_eq!(candidate_output.0.len(), expected_rows);
13258 drop((former_output, candidate_output));
13259 for _ in 0..2 {
13260 std::hint::black_box(former());
13261 std::hint::black_box(candidate());
13262 }
13263
13264 let sample = |plan: &dyn Fn() -> Option<super::OptionalJoinPositions>| {
13265 let start = std::time::Instant::now();
13266 let output = std::hint::black_box(plan()).expect("supported temporal union");
13267 assert_eq!(std::hint::black_box(output.0.len()), expected_rows);
13268 drop(output);
13269 start.elapsed().as_secs_f64() * 1_000.0
13270 };
13271 let mut former_a = Vec::with_capacity(15);
13272 let mut former_b = Vec::with_capacity(15);
13273 let mut candidate_a = Vec::with_capacity(15);
13274 let mut candidate_b = Vec::with_capacity(15);
13275 for round in 0..15 {
13276 if round % 2 == 0 {
13277 former_a.push(sample(&former));
13278 candidate_a.push(sample(&candidate));
13279 candidate_b.push(sample(&candidate));
13280 former_b.push(sample(&former));
13281 } else {
13282 former_b.push(sample(&former));
13283 candidate_b.push(sample(&candidate));
13284 candidate_a.push(sample(&candidate));
13285 former_a.push(sample(&former));
13286 }
13287 }
13288
13289 let report = |label: &str, mut samples: Vec<f64>| {
13290 samples.sort_by(f64::total_cmp);
13291 let p50 = samples[samples.len() / 2];
13292 let p95_idx = samples
13293 .len()
13294 .saturating_mul(95)
13295 .div_ceil(100)
13296 .saturating_sub(1);
13297 println!(
13298 "{label}: p50={p50:.3} ms p95={:.3} ms max={:.3} ms",
13299 samples[p95_idx],
13300 samples[samples.len() - 1],
13301 );
13302 };
13303 report("outer_plan_three_pass_former_a", former_a);
13304 report("outer_plan_three_pass_former_b", former_b);
13305 report("outer_plan_fused_candidate_a", candidate_a);
13306 report("outer_plan_fused_candidate_b", candidate_b);
13307 }
13308
13309 #[test]
13310 fn merge_temporal_outer_matches_generic_dtype_order_and_null_fill_rvb6u()
13311 -> Result<(), JoinError> {
13312 let left_ns = [-20, 10, 30, 50];
13313 let right_ns = [-30, -20, 20, 30, 60];
13314 let union_ns = [-30, -20, 10, 20, 30, 50, 60];
13315 for temporal in [DType::Datetime64, DType::Timedelta64] {
13316 let scalar = |ns| match temporal {
13317 DType::Datetime64 => Scalar::Datetime64(ns),
13318 DType::Timedelta64 => Scalar::Timedelta64(ns),
13319 _ => unreachable!("test iterates only temporal dtypes"),
13320 };
13321 let left = DataFrame::from_dict(
13322 &["key", "lv"],
13323 vec![
13324 ("key", left_ns.into_iter().map(scalar).collect()),
13325 (
13326 "lv",
13327 vec![
13328 Scalar::Int64(100),
13329 Scalar::Int64(101),
13330 Scalar::Int64(102),
13331 Scalar::Int64(103),
13332 ],
13333 ),
13334 ],
13335 )?;
13336 let right = DataFrame::from_dict(
13337 &["key", "rv"],
13338 vec![
13339 ("key", right_ns.into_iter().map(scalar).collect()),
13340 (
13341 "rv",
13342 vec![
13343 Scalar::Int64(200),
13344 Scalar::Int64(201),
13345 Scalar::Int64(202),
13346 Scalar::Int64(203),
13347 Scalar::Int64(204),
13348 ],
13349 ),
13350 ],
13351 )?;
13352 let candidate = merge_dataframes_on(&left, &right, &["key"], JoinType::Outer)?;
13353 let generic = merge_dataframes_on_with_options(
13354 &left,
13355 &right,
13356 &["key"],
13357 &["key"],
13358 JoinType::Outer,
13359 MergeExecutionOptions {
13360 sort: true,
13361 ..MergeExecutionOptions::default()
13362 },
13363 )?;
13364 assert_eq!(candidate, generic, "{temporal:?} OUTER output parity");
13365 assert_eq!(candidate.columns["key"].dtype(), temporal);
13366 assert_eq!(
13367 merged_values(&candidate, "key")?,
13368 union_ns.into_iter().map(scalar).collect::<Vec<_>>().as_slice(),
13369 );
13370
13371 let left_values = merged_values(&candidate, "lv")?;
13372 assert!(left_values[0].is_missing());
13373 assert_eq!(left_values[1], Scalar::Float64(100.0));
13374 assert_eq!(left_values[2], Scalar::Float64(101.0));
13375 assert!(left_values[3].is_missing());
13376 assert_eq!(left_values[4], Scalar::Float64(102.0));
13377 assert_eq!(left_values[5], Scalar::Float64(103.0));
13378 assert!(left_values[6].is_missing());
13379
13380 let right_values = merged_values(&candidate, "rv")?;
13381 assert_eq!(right_values[0], Scalar::Float64(200.0));
13382 assert_eq!(right_values[1], Scalar::Float64(201.0));
13383 assert!(right_values[2].is_missing());
13384 assert_eq!(right_values[3], Scalar::Float64(202.0));
13385 assert_eq!(right_values[4], Scalar::Float64(203.0));
13386 assert!(right_values[5].is_missing());
13387 assert_eq!(right_values[6], Scalar::Float64(204.0));
13388 }
13389
13390 let nat = fp_types::Timestamp::NAT;
13391 let nat_left = DataFrame::from_dict(
13392 &["key", "lv"],
13393 vec![
13394 ("key", vec![Scalar::Datetime64(nat), Scalar::Datetime64(5)]),
13395 ("lv", vec![Scalar::Int64(0), Scalar::Int64(1)]),
13396 ],
13397 )?;
13398 let nat_right = DataFrame::from_dict(
13399 &["key", "rv"],
13400 vec![
13401 (
13402 "key",
13403 vec![
13404 Scalar::Datetime64(nat),
13405 Scalar::Datetime64(5),
13406 Scalar::Datetime64(7),
13407 ],
13408 ),
13409 ("rv", vec![Scalar::Int64(10), Scalar::Int64(11), Scalar::Int64(12)]),
13410 ],
13411 )?;
13412 assert!(
13413 super::ordered_unique_temporal_i64_outer_positions(
13414 nat_left.column("key").expect("left NaT key"),
13415 nat_right.column("key").expect("right NaT key"),
13416 )
13417 .is_none(),
13418 "NaT must retain the scalar Missing-key fallback",
13419 );
13420 let nat_candidate =
13421 merge_dataframes_on(&nat_left, &nat_right, &["key"], JoinType::Outer)?;
13422 let nat_generic = merge_dataframes_on_with_options(
13423 &nat_left,
13424 &nat_right,
13425 &["key"],
13426 &["key"],
13427 JoinType::Outer,
13428 MergeExecutionOptions {
13429 sort: true,
13430 ..MergeExecutionOptions::default()
13431 },
13432 )?;
13433 assert_eq!(nat_candidate, nat_generic);
13434 assert_eq!(nat_candidate.columns["key"].dtype(), DType::Datetime64);
13435 assert!(
13436 merged_values(&nat_candidate, "key")?
13437 .iter()
13438 .any(Scalar::is_missing),
13439 );
13440
13441 Ok(())
13442 }
13443
13444 #[test]
13445 fn merge_composite_datetime_component_is_honored_not_missing_j0in7()
13446 -> Result<(), JoinError> {
13447 let left = DataFrame::from_dict(
13457 &["region", "ts", "lv"],
13458 vec![
13459 (
13460 "region",
13461 vec![
13462 Scalar::Utf8("a".to_owned()),
13463 Scalar::Utf8("a".to_owned()),
13464 Scalar::Utf8("b".to_owned()),
13465 ],
13466 ),
13467 (
13468 "ts",
13469 vec![
13470 Scalar::Datetime64(10),
13471 Scalar::Datetime64(20),
13472 Scalar::Datetime64(10),
13473 ],
13474 ),
13475 (
13476 "lv",
13477 vec![Scalar::Int64(0), Scalar::Int64(1), Scalar::Int64(2)],
13478 ),
13479 ],
13480 )?;
13481 let right = DataFrame::from_dict(
13482 &["region", "ts", "rv"],
13483 vec![
13484 (
13485 "region",
13486 vec![
13487 Scalar::Utf8("a".to_owned()),
13488 Scalar::Utf8("a".to_owned()),
13489 Scalar::Utf8("b".to_owned()),
13490 ],
13491 ),
13492 (
13493 "ts",
13494 vec![
13495 Scalar::Datetime64(10),
13496 Scalar::Datetime64(99),
13497 Scalar::Datetime64(10),
13498 ],
13499 ),
13500 (
13501 "rv",
13502 vec![Scalar::Int64(100), Scalar::Int64(101), Scalar::Int64(102)],
13503 ),
13504 ],
13505 )?;
13506 let merged =
13507 merge_dataframes_on(&left, &right, &["region", "ts"], JoinType::Inner)?;
13508 assert_eq!(
13509 merged.index.len(),
13510 2,
13511 "datetime composite component must discriminate, not collapse to Missing"
13512 );
13513 assert_eq!(merged.columns["ts"].dtype(), DType::Datetime64);
13514 let mut pairs: Vec<(i64, i64)> = merged_values(&merged, "lv")?
13516 .iter()
13517 .zip(merged_values(&merged, "rv")?)
13518 .map(|(l, r)| match (l, r) {
13519 (Scalar::Int64(a), Scalar::Int64(b)) => (*a, *b),
13520 _ => panic!("unexpected non-Int64 value column"),
13521 })
13522 .collect();
13523 pairs.sort_unstable();
13524 assert_eq!(pairs, vec![(0, 100), (2, 102)]);
13525
13526 let ltd = DataFrame::from_dict(
13528 &["region", "td", "lv"],
13529 vec![
13530 (
13531 "region",
13532 vec![Scalar::Utf8("a".to_owned()), Scalar::Utf8("a".to_owned())],
13533 ),
13534 ("td", vec![Scalar::Timedelta64(10), Scalar::Timedelta64(20)]),
13535 ("lv", vec![Scalar::Int64(0), Scalar::Int64(1)]),
13536 ],
13537 )?;
13538 let rtd = DataFrame::from_dict(
13539 &["region", "td", "rv"],
13540 vec![
13541 (
13542 "region",
13543 vec![Scalar::Utf8("a".to_owned()), Scalar::Utf8("a".to_owned())],
13544 ),
13545 ("td", vec![Scalar::Timedelta64(10), Scalar::Timedelta64(99)]),
13546 ("rv", vec![Scalar::Int64(100), Scalar::Int64(101)]),
13547 ],
13548 )?;
13549 let merged_td =
13550 merge_dataframes_on(<d, &rtd, &["region", "td"], JoinType::Inner)?;
13551 assert_eq!(
13552 merged_td.index.len(),
13553 1,
13554 "timedelta composite component must discriminate, not collapse to Missing"
13555 );
13556 assert_eq!(merged_values(&merged_td, "lv")?, &[Scalar::Int64(0)]);
13557 assert_eq!(merged_values(&merged_td, "rv")?, &[Scalar::Int64(100)]);
13558
13559 Ok(())
13560 }
13561
13562 fn merged_values_where_indicator(
13563 merged: &MergedDataFrame,
13564 column_name: &str,
13565 indicator_name: &str,
13566 indicator_value: &str,
13567 ) -> Result<Vec<Scalar>, JoinError> {
13568 let values = merged_values(merged, column_name)?;
13569 let indicators = merged_values(merged, indicator_name)?;
13570 Ok(values
13571 .iter()
13572 .zip(indicators.iter())
13573 .filter_map(|(value, indicator)| {
13574 if matches!(indicator, Scalar::Utf8(v) if v == indicator_value) {
13575 Some(value.clone())
13576 } else {
13577 None
13578 }
13579 })
13580 .collect())
13581 }
13582
13583 #[test]
13584 fn merge_inner_basic() {
13585 let left = make_left_df();
13586 let right = make_right_df();
13587 let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
13588
13589 assert_eq!(merged.columns.get("id").unwrap().len(), 2);
13590 assert_eq!(
13591 merged.columns.get("id").unwrap().values(),
13592 &[Scalar::Int64(2), Scalar::Int64(3)]
13593 );
13594 assert_eq!(
13595 merged.columns.get("val_a").unwrap().values(),
13596 &[Scalar::Int64(20), Scalar::Int64(30)]
13597 );
13598 assert_eq!(
13599 merged.columns.get("val_b").unwrap().values(),
13600 &[Scalar::Int64(200), Scalar::Int64(300)]
13601 );
13602 }
13603
13604 #[test]
13605 fn merge_inner_single_key_preserves_duplicate_probe_order() {
13606 let left = DataFrame::from_dict(
13607 &["id", "left_value"],
13608 vec![
13609 (
13610 "id",
13611 vec![Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(2)],
13612 ),
13613 (
13614 "left_value",
13615 vec![Scalar::Int64(20), Scalar::Int64(10), Scalar::Int64(21)],
13616 ),
13617 ],
13618 )
13619 .unwrap();
13620 let right = DataFrame::from_dict(
13621 &["id", "right_value"],
13622 vec![
13623 (
13624 "id",
13625 vec![Scalar::Int64(2), Scalar::Int64(2), Scalar::Int64(1)],
13626 ),
13627 (
13628 "right_value",
13629 vec![Scalar::Int64(200), Scalar::Int64(201), Scalar::Int64(100)],
13630 ),
13631 ],
13632 )
13633 .unwrap();
13634
13635 let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
13636
13637 assert_eq!(
13638 merged.columns.get("id").unwrap().values(),
13639 &[
13640 Scalar::Int64(2),
13641 Scalar::Int64(2),
13642 Scalar::Int64(1),
13643 Scalar::Int64(2),
13644 Scalar::Int64(2),
13645 ]
13646 );
13647 assert_eq!(
13648 merged.columns.get("left_value").unwrap().values(),
13649 &[
13650 Scalar::Int64(20),
13651 Scalar::Int64(20),
13652 Scalar::Int64(10),
13653 Scalar::Int64(21),
13654 Scalar::Int64(21),
13655 ]
13656 );
13657 assert_eq!(
13658 merged.columns.get("right_value").unwrap().values(),
13659 &[
13660 Scalar::Int64(200),
13661 Scalar::Int64(201),
13662 Scalar::Int64(100),
13663 Scalar::Int64(200),
13664 Scalar::Int64(201),
13665 ]
13666 );
13667 }
13668
13669 #[test]
13670 fn merge_inner_wide_sparse_int64_hash_matches_generic_validated_route() {
13671 let stride = 1_i64 << 30;
13672 let left = DataFrame::from_dict(
13673 &["id", "left_value"],
13674 vec![
13675 (
13676 "id",
13677 vec![3, 1, 3, 0, 2]
13678 .into_iter()
13679 .map(|v| Scalar::Int64(v * stride))
13680 .collect(),
13681 ),
13682 (
13683 "left_value",
13684 vec![
13685 Scalar::Int64(10),
13686 Scalar::Int64(11),
13687 Scalar::Int64(12),
13688 Scalar::Int64(13),
13689 Scalar::Int64(14),
13690 ],
13691 ),
13692 ],
13693 )
13694 .unwrap();
13695 let right = DataFrame::from_dict(
13696 &["id", "right_value"],
13697 vec![
13698 (
13699 "id",
13700 vec![3, 2, 3, 1]
13701 .into_iter()
13702 .map(|v| Scalar::Int64(v * stride))
13703 .collect(),
13704 ),
13705 (
13706 "right_value",
13707 vec![
13708 Scalar::Int64(100),
13709 Scalar::Int64(101),
13710 Scalar::Int64(102),
13711 Scalar::Int64(103),
13712 ],
13713 ),
13714 ],
13715 )
13716 .unwrap();
13717
13718 let fast = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
13719 let generic = merge_dataframes_on_with_options(
13720 &left,
13721 &right,
13722 &["id"],
13723 &["id"],
13724 JoinType::Inner,
13725 MergeExecutionOptions {
13726 validate_mode: Some(MergeValidateMode::ManyToMany),
13727 ..MergeExecutionOptions::default()
13728 },
13729 )
13730 .unwrap();
13731
13732 assert_eq!(fast.index, generic.index);
13733 assert_eq!(fast.column_order, generic.column_order);
13734 assert_eq!(fast.columns, generic.columns);
13735 assert_eq!(
13736 fast.columns.get("id").unwrap().values(),
13737 &[
13738 Scalar::Int64(3 * stride),
13739 Scalar::Int64(3 * stride),
13740 Scalar::Int64(stride),
13741 Scalar::Int64(3 * stride),
13742 Scalar::Int64(3 * stride),
13743 Scalar::Int64(2 * stride),
13744 ]
13745 );
13746 assert_eq!(
13747 fast.columns.get("left_value").unwrap().values(),
13748 &[
13749 Scalar::Int64(10),
13750 Scalar::Int64(10),
13751 Scalar::Int64(11),
13752 Scalar::Int64(12),
13753 Scalar::Int64(12),
13754 Scalar::Int64(14),
13755 ]
13756 );
13757 assert_eq!(
13758 fast.columns.get("right_value").unwrap().values(),
13759 &[
13760 Scalar::Int64(100),
13761 Scalar::Int64(102),
13762 Scalar::Int64(103),
13763 Scalar::Int64(100),
13764 Scalar::Int64(102),
13765 Scalar::Int64(101),
13766 ]
13767 );
13768 }
13769
13770 #[test]
13771 fn dense_i64_inner_parallel_output_data_preserves_row_major_order() {
13772 let left_keys = vec![-1, 2, 1, 2, 3, 9];
13773 let min = 1;
13774 let max = 3;
13775 let offsets = vec![0, 2, 3, 5];
13776 let positions = vec![1usize, 4, 0, 2, 3];
13777 let left_values = vec![10, 20, 30, 40, 50, 60];
13778 let right_values = vec![100, 101, 102, 103, 104];
13779 let specs = vec![
13780 FusedInt64OutputColumn {
13781 name: "left".to_string(),
13782 side: FusedInt64Side::Left,
13783 values: &left_values,
13784 },
13785 FusedInt64OutputColumn {
13786 name: "right".to_string(),
13787 side: FusedInt64Side::Right,
13788 values: &right_values,
13789 },
13790 ];
13791
13792 let plan = DenseI64InnerOutputPlan {
13793 left_keys: &left_keys,
13794 min,
13795 max,
13796 offsets: &offsets,
13797 positions: &positions,
13798 output_len: 6,
13799 };
13800 let actual = build_dense_i64_inner_output_data(&specs, &plan);
13801
13802 assert_eq!(lane_expanded(&actual[0]), vec![20, 30, 30, 40, 50, 50]);
13805 assert_eq!(
13806 lane_expanded(&actual[1]),
13807 vec![100, 101, 104, 100, 102, 103]
13808 );
13809 assert!(matches!(actual[0], DenseI64LaneData::Full(_)));
13810 assert!(matches!(actual[1], DenseI64LaneData::Full(_)));
13811 }
13812
13813 fn lane_expanded(lane: &DenseI64LaneData) -> Vec<i64> {
13814 match lane {
13815 DenseI64LaneData::RepeatRunLengths { values, run_lens } => {
13816 let mut out = Vec::new();
13817 for (&value, &run_len) in values.iter().zip(run_lens.iter()) {
13818 out.resize(out.len() + run_len, value);
13819 }
13820 out
13821 }
13822 DenseI64LaneData::RepeatedSlices { data, segments } => {
13823 let mut out = Vec::new();
13824 for &(start, len) in segments.iter() {
13825 out.extend_from_slice(&data[start..start + len]);
13826 }
13827 out
13828 }
13829 DenseI64LaneData::Full(data) => data.clone(),
13830 }
13831 }
13832
13833 #[test]
13834 fn dense_i64_inner_high_fanout_emits_repeat_run_left_lanes() {
13835 let left_keys = vec![1, 7, 2];
13839 let min = 1;
13840 let max = 2;
13841 let offsets = vec![0, 3, 6];
13842 let positions = vec![0usize, 2, 4, 1, 3, 5];
13843 let left_values = vec![10, 20, 30];
13844 let right_values = vec![100, 101, 102, 103, 104, 105];
13845 let specs = vec![
13846 FusedInt64OutputColumn {
13847 name: "left".to_string(),
13848 side: FusedInt64Side::Left,
13849 values: &left_values,
13850 },
13851 FusedInt64OutputColumn {
13852 name: "right".to_string(),
13853 side: FusedInt64Side::Right,
13854 values: &right_values,
13855 },
13856 ];
13857
13858 let plan = DenseI64InnerOutputPlan {
13859 left_keys: &left_keys,
13860 min,
13861 max,
13862 offsets: &offsets,
13863 positions: &positions,
13864 output_len: 6,
13865 };
13866 let actual = build_dense_i64_inner_output_data(&specs, &plan);
13867
13868 assert!(matches!(
13869 actual[0],
13870 DenseI64LaneData::RepeatRunLengths { .. }
13871 ));
13872 assert!(matches!(actual[1], DenseI64LaneData::RepeatedSlices { .. }));
13873 assert_eq!(lane_expanded(&actual[0]), vec![10, 10, 10, 30, 30, 30]);
13874 assert_eq!(
13875 lane_expanded(&actual[1]),
13876 vec![100, 102, 104, 101, 103, 105]
13877 );
13878
13879 let lazy = fp_columnar::Column::from_i64_repeat_values_run_lengths(
13883 vec![10, 30],
13884 std::sync::Arc::from([3usize, 3]),
13885 );
13886 let eager = fp_columnar::Column::from_i64_values(vec![10, 10, 10, 30, 30, 30]);
13887 assert_eq!(lazy.len(), eager.len());
13888 assert_eq!(lazy.as_i64_slice(), eager.as_i64_slice());
13889 assert_eq!(lazy.values(), eager.values());
13890 assert_eq!(lazy, eager);
13891 }
13892
13893 #[test]
13894 fn dense_cycle_left_join_output_matches_dense_left_builder() {
13895 let left = DataFrame::from_dict(
13896 &["id", "v"],
13897 vec![
13898 (
13899 "id",
13900 vec![
13901 Scalar::Int64(0),
13902 Scalar::Int64(1),
13903 Scalar::Int64(2),
13904 Scalar::Int64(0),
13905 Scalar::Int64(1),
13906 Scalar::Int64(2),
13907 Scalar::Int64(0),
13908 ],
13909 ),
13910 (
13911 "v",
13912 vec![
13913 Scalar::Int64(10),
13914 Scalar::Int64(11),
13915 Scalar::Int64(12),
13916 Scalar::Int64(13),
13917 Scalar::Int64(14),
13918 Scalar::Int64(15),
13919 Scalar::Int64(16),
13920 ],
13921 ),
13922 ],
13923 )
13924 .unwrap();
13925 let right = DataFrame::from_dict(
13926 &["id", "rv"],
13927 vec![
13928 (
13929 "id",
13930 vec![
13931 Scalar::Int64(1),
13932 Scalar::Int64(2),
13933 Scalar::Int64(1),
13934 Scalar::Int64(2),
13935 ],
13936 ),
13937 (
13938 "rv",
13939 vec![
13940 Scalar::Int64(100),
13941 Scalar::Int64(200),
13942 Scalar::Int64(101),
13943 Scalar::Int64(201),
13944 ],
13945 ),
13946 ],
13947 )
13948 .unwrap();
13949 let suffixes = ResolvedMergeSuffixes::default();
13950 let left_key = left.column("id").unwrap();
13951 let right_key = right.column("id").unwrap();
13952
13953 let fast = build_single_key_dense_cycle_i64_left_merge_output(
13954 &left,
13955 &right,
13956 &["id"],
13957 &["id"],
13958 left_key,
13959 right_key,
13960 &suffixes,
13961 )
13962 .unwrap()
13963 .expect("dense-cycle route");
13964 let old = build_single_key_dense_i64_left_merge_output(
13965 &left,
13966 &right,
13967 &["id"],
13968 &["id"],
13969 left_key,
13970 right_key,
13971 &suffixes,
13972 )
13973 .unwrap()
13974 .expect("dense left route");
13975
13976 assert_eq!(fast.index, old.index);
13977 assert_eq!(fast.column_order, old.column_order);
13978 assert_eq!(fast.columns, old.columns);
13979 assert_eq!(
13980 fast.columns.get("v").unwrap().as_i64_slice(),
13981 old.columns.get("v").unwrap().as_i64_slice()
13982 );
13983 assert_eq!(
13984 fast.columns.get("rv").unwrap().values(),
13985 &[
13986 Scalar::Null(NullKind::Null),
13987 Scalar::Int64(100),
13988 Scalar::Int64(101),
13989 Scalar::Int64(200),
13990 Scalar::Int64(201),
13991 Scalar::Null(NullKind::Null),
13992 Scalar::Int64(100),
13993 Scalar::Int64(101),
13994 Scalar::Int64(200),
13995 Scalar::Int64(201),
13996 Scalar::Null(NullKind::Null),
13997 ]
13998 );
13999 }
14000
14001 #[test]
14002 fn merge_inner_ordered_identity_matches_generic_validated_route() {
14003 let left = DataFrame::from_dict(
14004 &["id", "v"],
14005 vec![
14006 (
14007 "id",
14008 vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
14009 ),
14010 (
14011 "v",
14012 vec![
14013 Scalar::Int64(10),
14014 Scalar::Null(NullKind::Null),
14015 Scalar::Int64(30),
14016 ],
14017 ),
14018 ],
14019 )
14020 .unwrap();
14021 let right = DataFrame::from_dict(
14022 &["id", "w"],
14023 vec![
14024 (
14025 "id",
14026 vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
14027 ),
14028 (
14029 "w",
14030 vec![Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(300)],
14031 ),
14032 ],
14033 )
14034 .unwrap();
14035
14036 let fast = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
14037 let generic = merge_dataframes_on_with_options(
14038 &left,
14039 &right,
14040 &["id"],
14041 &["id"],
14042 JoinType::Inner,
14043 MergeExecutionOptions {
14044 validate_mode: Some(MergeValidateMode::OneToOne),
14045 ..MergeExecutionOptions::default()
14046 },
14047 )
14048 .unwrap();
14049
14050 assert_eq!(fast.index, generic.index);
14051 assert_eq!(fast.column_order, generic.column_order);
14052 assert_eq!(fast.columns, generic.columns);
14053 }
14054
14055 #[test]
14056 fn merge_inner_dense_int64_fused_materialization_matches_generic_route() {
14057 let left = DataFrame::from_dict(
14058 &["id", "v", "overlap"],
14059 vec![
14060 (
14061 "id",
14062 vec![
14063 Scalar::Int64(2),
14064 Scalar::Int64(1),
14065 Scalar::Int64(2),
14066 Scalar::Int64(3),
14067 ],
14068 ),
14069 (
14070 "v",
14071 vec![
14072 Scalar::Int64(20),
14073 Scalar::Int64(10),
14074 Scalar::Int64(21),
14075 Scalar::Int64(30),
14076 ],
14077 ),
14078 (
14079 "overlap",
14080 vec![
14081 Scalar::Int64(200),
14082 Scalar::Int64(100),
14083 Scalar::Int64(201),
14084 Scalar::Int64(300),
14085 ],
14086 ),
14087 ],
14088 )
14089 .unwrap();
14090 let right = DataFrame::from_dict(
14091 &["id", "w", "overlap"],
14092 vec![
14093 (
14094 "id",
14095 vec![
14096 Scalar::Int64(2),
14097 Scalar::Int64(2),
14098 Scalar::Int64(1),
14099 Scalar::Int64(4),
14100 ],
14101 ),
14102 (
14103 "w",
14104 vec![
14105 Scalar::Int64(2000),
14106 Scalar::Int64(2001),
14107 Scalar::Int64(1000),
14108 Scalar::Int64(4000),
14109 ],
14110 ),
14111 (
14112 "overlap",
14113 vec![
14114 Scalar::Int64(20_000),
14115 Scalar::Int64(20_001),
14116 Scalar::Int64(10_000),
14117 Scalar::Int64(40_000),
14118 ],
14119 ),
14120 ],
14121 )
14122 .unwrap();
14123
14124 let fast = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
14125 let generic = merge_dataframes_on_with_options(
14126 &left,
14127 &right,
14128 &["id"],
14129 &["id"],
14130 JoinType::Inner,
14131 MergeExecutionOptions {
14132 validate_mode: Some(MergeValidateMode::ManyToMany),
14133 ..MergeExecutionOptions::default()
14134 },
14135 )
14136 .unwrap();
14137
14138 assert_eq!(fast.index, generic.index);
14139 assert_eq!(fast.column_order, generic.column_order);
14140 assert_eq!(fast.columns, generic.columns);
14141 assert_eq!(
14142 fast.column_order,
14143 ["id", "v", "overlap_x", "w", "overlap_y"]
14144 );
14145 assert_eq!(
14146 fast.columns.get("id").unwrap().values(),
14147 &[
14148 Scalar::Int64(2),
14149 Scalar::Int64(2),
14150 Scalar::Int64(1),
14151 Scalar::Int64(2),
14152 Scalar::Int64(2),
14153 ]
14154 );
14155 assert_eq!(
14156 fast.columns.get("w").unwrap().values(),
14157 &[
14158 Scalar::Int64(2000),
14159 Scalar::Int64(2001),
14160 Scalar::Int64(1000),
14161 Scalar::Int64(2000),
14162 Scalar::Int64(2001),
14163 ]
14164 );
14165 assert!(
14166 fast.columns
14167 .values()
14168 .all(|column| column.as_i64_slice().is_some())
14169 );
14170 }
14171
14172 #[test]
14173 fn merge_inner_ordered_unique_int64_subset_matches_generic_validated_route() {
14174 let left = DataFrame::from_dict(
14175 &["id", "v"],
14176 vec![
14177 (
14178 "id",
14179 vec![
14180 Scalar::Int64(0),
14181 Scalar::Int64(1),
14182 Scalar::Int64(2),
14183 Scalar::Int64(3),
14184 Scalar::Int64(4),
14185 ],
14186 ),
14187 (
14188 "v",
14189 vec![
14190 Scalar::Int64(10),
14191 Scalar::Int64(11),
14192 Scalar::Int64(12),
14193 Scalar::Int64(13),
14194 Scalar::Int64(14),
14195 ],
14196 ),
14197 ],
14198 )
14199 .unwrap();
14200 let right = DataFrame::from_dict(
14201 &["id", "w"],
14202 vec![
14203 (
14204 "id",
14205 vec![
14206 Scalar::Int64(0),
14207 Scalar::Int64(2),
14208 Scalar::Int64(4),
14209 Scalar::Int64(6),
14210 ],
14211 ),
14212 (
14213 "w",
14214 vec![
14215 Scalar::Int64(100),
14216 Scalar::Int64(200),
14217 Scalar::Int64(300),
14218 Scalar::Int64(400),
14219 ],
14220 ),
14221 ],
14222 )
14223 .unwrap();
14224
14225 let fast = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
14226 let generic = merge_dataframes_on_with_options(
14227 &left,
14228 &right,
14229 &["id"],
14230 &["id"],
14231 JoinType::Inner,
14232 MergeExecutionOptions {
14233 validate_mode: Some(MergeValidateMode::OneToOne),
14234 ..MergeExecutionOptions::default()
14235 },
14236 )
14237 .unwrap();
14238
14239 assert_eq!(fast.index, generic.index);
14240 assert_eq!(fast.column_order, generic.column_order);
14241 assert_eq!(fast.columns, generic.columns);
14242 assert_eq!(
14243 fast.columns.get("id").unwrap().values(),
14244 &[Scalar::Int64(0), Scalar::Int64(2), Scalar::Int64(4)]
14245 );
14246 assert_eq!(
14247 fast.columns.get("v").unwrap().values(),
14248 &[Scalar::Int64(10), Scalar::Int64(12), Scalar::Int64(14)]
14249 );
14250 assert_eq!(
14251 fast.columns.get("w").unwrap().values(),
14252 &[Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(300)]
14253 );
14254 }
14255
14256 #[test]
14257 fn merge_inner_ordered_identity_falls_back_for_non_identity_keys() {
14258 let cases = [
14259 (
14260 vec![Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(4)],
14261 vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
14262 ),
14263 (
14264 vec![
14265 Scalar::Int64(1),
14266 Scalar::Null(NullKind::Null),
14267 Scalar::Int64(3),
14268 ],
14269 vec![
14270 Scalar::Int64(1),
14271 Scalar::Null(NullKind::Null),
14272 Scalar::Int64(3),
14273 ],
14274 ),
14275 ];
14276
14277 for (left_keys, right_keys) in cases {
14278 let left = DataFrame::from_dict(
14279 &["id", "v"],
14280 vec![
14281 ("id", left_keys),
14282 (
14283 "v",
14284 vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
14285 ),
14286 ],
14287 )
14288 .unwrap();
14289 let right = DataFrame::from_dict(
14290 &["id", "w"],
14291 vec![
14292 ("id", right_keys),
14293 (
14294 "w",
14295 vec![Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(300)],
14296 ),
14297 ],
14298 )
14299 .unwrap();
14300
14301 let maybe_fast = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
14302 let generic = merge_dataframes_on_with_options(
14303 &left,
14304 &right,
14305 &["id"],
14306 &["id"],
14307 JoinType::Inner,
14308 MergeExecutionOptions {
14309 validate_mode: Some(MergeValidateMode::OneToOne),
14310 ..MergeExecutionOptions::default()
14311 },
14312 )
14313 .unwrap();
14314
14315 assert_eq!(maybe_fast.index, generic.index);
14316 assert_eq!(maybe_fast.column_order, generic.column_order);
14317 assert_eq!(maybe_fast.columns, generic.columns);
14318 }
14319 }
14320
14321 #[test]
14322 fn merge_default_suffixes_match_pandas() {
14323 let idx: Vec<_> = (0..3).map(|i| (i as i64).into()).collect();
14328 let left = fp_frame::DataFrame::from_series(vec![
14329 fp_frame::Series::from_values(
14330 "k",
14331 idx.clone(),
14332 vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
14333 )
14334 .unwrap(),
14335 fp_frame::Series::from_values(
14336 "v",
14337 idx.clone(),
14338 vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
14339 )
14340 .unwrap(),
14341 ])
14342 .unwrap();
14343 let right = fp_frame::DataFrame::from_series(vec![
14344 fp_frame::Series::from_values(
14345 "k",
14346 idx.clone(),
14347 vec![Scalar::Int64(2), Scalar::Int64(3), Scalar::Int64(4)],
14348 )
14349 .unwrap(),
14350 fp_frame::Series::from_values(
14351 "v",
14352 idx,
14353 vec![Scalar::Int64(200), Scalar::Int64(300), Scalar::Int64(400)],
14354 )
14355 .unwrap(),
14356 ])
14357 .unwrap();
14358 let merged = merge_dataframes(&left, &right, "k", JoinType::Inner).unwrap();
14359
14360 assert_eq!(
14361 merged.columns.get("k").unwrap().values(),
14362 &[Scalar::Int64(2), Scalar::Int64(3)],
14363 "k"
14364 );
14365 assert_eq!(
14366 merged.columns.get("v_x").unwrap().values(),
14367 &[Scalar::Int64(20), Scalar::Int64(30)],
14368 "v_x"
14369 );
14370 assert_eq!(
14371 merged.columns.get("v_y").unwrap().values(),
14372 &[Scalar::Int64(200), Scalar::Int64(300)],
14373 "v_y"
14374 );
14375 assert!(
14376 !merged.columns.contains_key("v"),
14377 "bare 'v' should be suffixed away"
14378 );
14379 }
14380
14381 #[test]
14382 fn merge_left_preserves_all_left_rows() {
14383 let left = make_left_df();
14384 let right = make_right_df();
14385 let merged = merge_dataframes(&left, &right, "id", JoinType::Left).unwrap();
14386
14387 assert_eq!(merged.columns.get("id").unwrap().len(), 3);
14388 assert_eq!(
14389 merged.columns.get("val_a").unwrap().values(),
14390 &[Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)]
14391 );
14392 assert!(merged.columns.get("val_b").unwrap().values()[0].is_missing());
14394 assert_eq!(
14395 merged.columns.get("val_b").unwrap().values()[1],
14396 Scalar::Int64(200)
14397 );
14398 assert_eq!(
14399 merged.columns.get("val_b").unwrap().values()[2],
14400 Scalar::Int64(300)
14401 );
14402 }
14403
14404 #[test]
14405 fn merge_left_ordered_unique_int64_subset_matches_generic_validated_route() {
14406 let left = DataFrame::from_dict(
14407 &["id", "v"],
14408 vec![
14409 (
14410 "id",
14411 vec![
14412 Scalar::Int64(0),
14413 Scalar::Int64(1),
14414 Scalar::Int64(2),
14415 Scalar::Int64(3),
14416 Scalar::Int64(4),
14417 ],
14418 ),
14419 (
14420 "v",
14421 vec![
14422 Scalar::Int64(10),
14423 Scalar::Int64(11),
14424 Scalar::Int64(12),
14425 Scalar::Int64(13),
14426 Scalar::Int64(14),
14427 ],
14428 ),
14429 ],
14430 )
14431 .unwrap();
14432 let right = DataFrame::from_dict(
14433 &["id", "w"],
14434 vec![
14435 (
14436 "id",
14437 vec![
14438 Scalar::Int64(0),
14439 Scalar::Int64(2),
14440 Scalar::Int64(4),
14441 Scalar::Int64(6),
14442 ],
14443 ),
14444 (
14445 "w",
14446 vec![
14447 Scalar::Int64(100),
14448 Scalar::Int64(200),
14449 Scalar::Int64(300),
14450 Scalar::Int64(400),
14451 ],
14452 ),
14453 ],
14454 )
14455 .unwrap();
14456
14457 let fast = merge_dataframes(&left, &right, "id", JoinType::Left).unwrap();
14458 let generic = merge_dataframes_on_with_options(
14459 &left,
14460 &right,
14461 &["id"],
14462 &["id"],
14463 JoinType::Left,
14464 MergeExecutionOptions {
14465 validate_mode: Some(MergeValidateMode::OneToOne),
14466 ..MergeExecutionOptions::default()
14467 },
14468 )
14469 .unwrap();
14470
14471 assert_eq!(fast.index, generic.index);
14472 assert_eq!(fast.column_order, generic.column_order);
14473 assert_eq!(fast.columns, generic.columns);
14474 assert_eq!(
14475 fast.columns.get("id").unwrap().values(),
14476 &[
14477 Scalar::Int64(0),
14478 Scalar::Int64(1),
14479 Scalar::Int64(2),
14480 Scalar::Int64(3),
14481 Scalar::Int64(4)
14482 ]
14483 );
14484 let right_values = fast.columns.get("w").unwrap().values();
14485 assert_eq!(right_values[0], Scalar::Int64(100));
14486 assert!(right_values[1].is_missing());
14487 assert_eq!(right_values[2], Scalar::Int64(200));
14488 assert!(right_values[3].is_missing());
14489 assert_eq!(right_values[4], Scalar::Int64(300));
14490 }
14491
14492 #[test]
14493 fn merge_left_dense_int64_duplicates_matches_generic_validated_route() {
14494 let left = DataFrame::from_dict(
14495 &["id", "v"],
14496 vec![
14497 (
14498 "id",
14499 vec![
14500 Scalar::Int64(2),
14501 Scalar::Int64(0),
14502 Scalar::Int64(2),
14503 Scalar::Int64(1),
14504 Scalar::Int64(5),
14505 ],
14506 ),
14507 (
14508 "v",
14509 vec![
14510 Scalar::Int64(10),
14511 Scalar::Int64(11),
14512 Scalar::Int64(12),
14513 Scalar::Int64(13),
14514 Scalar::Int64(15),
14515 ],
14516 ),
14517 ],
14518 )
14519 .unwrap();
14520 let right = DataFrame::from_dict(
14521 &["id", "w"],
14522 vec![
14523 (
14524 "id",
14525 vec![
14526 Scalar::Int64(2),
14527 Scalar::Int64(2),
14528 Scalar::Int64(3),
14529 Scalar::Int64(0),
14530 ],
14531 ),
14532 (
14533 "w",
14534 vec![
14535 Scalar::Int64(200),
14536 Scalar::Int64(201),
14537 Scalar::Int64(300),
14538 Scalar::Int64(400),
14539 ],
14540 ),
14541 ],
14542 )
14543 .unwrap();
14544
14545 let fast = merge_dataframes(&left, &right, "id", JoinType::Left).unwrap();
14546 let generic = merge_dataframes_on_with_options(
14547 &left,
14548 &right,
14549 &["id"],
14550 &["id"],
14551 JoinType::Left,
14552 MergeExecutionOptions {
14553 validate_mode: Some(MergeValidateMode::ManyToMany),
14554 ..MergeExecutionOptions::default()
14555 },
14556 )
14557 .unwrap();
14558
14559 assert_eq!(fast.index, generic.index);
14560 assert_eq!(fast.column_order, generic.column_order);
14561 assert_eq!(fast.columns, generic.columns);
14562 assert_eq!(
14563 fast.columns.get("id").unwrap().values(),
14564 &[
14565 Scalar::Int64(2),
14566 Scalar::Int64(2),
14567 Scalar::Int64(0),
14568 Scalar::Int64(2),
14569 Scalar::Int64(2),
14570 Scalar::Int64(1),
14571 Scalar::Int64(5),
14572 ]
14573 );
14574 let left_values = fast.columns.get("v").unwrap().values();
14575 assert_eq!(left_values[0], Scalar::Int64(10));
14576 assert_eq!(left_values[1], Scalar::Int64(10));
14577 assert_eq!(left_values[2], Scalar::Int64(11));
14578 assert_eq!(left_values[4], Scalar::Int64(12));
14579 assert_eq!(left_values[6], Scalar::Int64(15));
14580 let right_values = fast.columns.get("w").unwrap().values();
14581 assert_eq!(right_values[0], Scalar::Int64(200));
14582 assert_eq!(right_values[1], Scalar::Int64(201));
14583 assert_eq!(right_values[2], Scalar::Int64(400));
14584 assert!(right_values[5].is_missing());
14585 assert!(right_values[6].is_missing());
14586 }
14587
14588 #[test]
14589 fn merge_left_dense_cycle_probe_output_matches_materialized_positions_yq96z() {
14590 let left = DataFrame::from_dict(
14591 &["id", "v"],
14592 vec![
14593 (
14594 "id",
14595 vec![
14596 Scalar::Int64(0),
14597 Scalar::Int64(1),
14598 Scalar::Int64(2),
14599 Scalar::Int64(0),
14600 Scalar::Int64(1),
14601 ],
14602 ),
14603 (
14604 "v",
14605 vec![
14606 Scalar::Int64(10),
14607 Scalar::Int64(11),
14608 Scalar::Int64(12),
14609 Scalar::Int64(13),
14610 Scalar::Int64(14),
14611 ],
14612 ),
14613 ],
14614 )
14615 .unwrap();
14616 let right = DataFrame::from_dict(
14617 &["id", "w"],
14618 vec![
14619 (
14620 "id",
14621 vec![
14622 Scalar::Int64(1),
14623 Scalar::Int64(2),
14624 Scalar::Int64(1),
14625 Scalar::Int64(2),
14626 ],
14627 ),
14628 (
14629 "w",
14630 vec![
14631 Scalar::Int64(100),
14632 Scalar::Int64(200),
14633 Scalar::Int64(101),
14634 Scalar::Int64(201),
14635 ],
14636 ),
14637 ],
14638 )
14639 .unwrap();
14640 let left_key = left.columns().get("id").unwrap();
14641 let right_key = right.columns().get("id").unwrap();
14642 assert!(left_key.int64_dense_cycle_witness().is_some());
14643 assert!(right_key.int64_dense_cycle_witness().is_some());
14644 let suffixes = resolve_merge_suffixes(None);
14645
14646 let fused = build_single_key_dense_i64_left_merge_output(
14647 &left,
14648 &right,
14649 &["id"],
14650 &["id"],
14651 left_key,
14652 right_key,
14653 &suffixes,
14654 )
14655 .unwrap()
14656 .expect("dense-cycle left route should accept");
14657 let (left_positions, right_positions) =
14658 dense_int64_left_positions(left_key, right_key).unwrap();
14659 let materialized = build_single_key_dense_left_merge_output(
14660 &left,
14661 &right,
14662 &["id"],
14663 &["id"],
14664 &left_positions,
14665 &right_positions,
14666 &suffixes,
14667 )
14668 .unwrap();
14669
14670 assert_eq!(fused.index, materialized.index);
14671 assert_eq!(fused.column_order, materialized.column_order);
14672 assert_eq!(fused.columns, materialized.columns);
14673 assert_eq!(
14674 fused.columns.get("w").unwrap().values(),
14675 &[
14676 Scalar::Null(NullKind::Null),
14677 Scalar::Int64(100),
14678 Scalar::Int64(101),
14679 Scalar::Int64(200),
14680 Scalar::Int64(201),
14681 Scalar::Null(NullKind::Null),
14682 Scalar::Int64(100),
14683 Scalar::Int64(101),
14684 ]
14685 );
14686 }
14687
14688 #[test]
14689 fn merge_left_all_matched_dense_int64_fused_output_matches_sorted_generic_route() {
14690 let left = DataFrame::from_dict(
14691 &["id", "v"],
14692 vec![
14693 (
14694 "id",
14695 vec![
14696 Scalar::Int64(0),
14697 Scalar::Int64(0),
14698 Scalar::Int64(1),
14699 Scalar::Int64(1),
14700 Scalar::Int64(2),
14701 ],
14702 ),
14703 (
14704 "v",
14705 vec![
14706 Scalar::Int64(10),
14707 Scalar::Int64(11),
14708 Scalar::Int64(20),
14709 Scalar::Int64(21),
14710 Scalar::Int64(30),
14711 ],
14712 ),
14713 ],
14714 )
14715 .unwrap();
14716 let right = DataFrame::from_dict(
14717 &["id", "w"],
14718 vec![
14719 (
14720 "id",
14721 vec![
14722 Scalar::Int64(0),
14723 Scalar::Int64(0),
14724 Scalar::Int64(1),
14725 Scalar::Int64(2),
14726 Scalar::Int64(2),
14727 ],
14728 ),
14729 (
14730 "w",
14731 vec![
14732 Scalar::Int64(100),
14733 Scalar::Int64(101),
14734 Scalar::Int64(200),
14735 Scalar::Int64(300),
14736 Scalar::Int64(301),
14737 ],
14738 ),
14739 ],
14740 )
14741 .unwrap();
14742
14743 let fast = merge_dataframes(&left, &right, "id", JoinType::Left).unwrap();
14744 let generic = merge_dataframes_on_with_options(
14745 &left,
14746 &right,
14747 &["id"],
14748 &["id"],
14749 JoinType::Left,
14750 MergeExecutionOptions {
14751 sort: true,
14752 ..MergeExecutionOptions::default()
14753 },
14754 )
14755 .unwrap();
14756
14757 assert_eq!(fast.index, generic.index);
14758 assert_eq!(fast.column_order, generic.column_order);
14759 assert_eq!(fast.columns, generic.columns);
14760 assert_eq!(
14761 fast.columns.get("id").unwrap().values(),
14762 &[
14763 Scalar::Int64(0),
14764 Scalar::Int64(0),
14765 Scalar::Int64(0),
14766 Scalar::Int64(0),
14767 Scalar::Int64(1),
14768 Scalar::Int64(1),
14769 Scalar::Int64(2),
14770 Scalar::Int64(2),
14771 ]
14772 );
14773 assert_eq!(
14774 fast.columns.get("v").unwrap().values(),
14775 &[
14776 Scalar::Int64(10),
14777 Scalar::Int64(10),
14778 Scalar::Int64(11),
14779 Scalar::Int64(11),
14780 Scalar::Int64(20),
14781 Scalar::Int64(21),
14782 Scalar::Int64(30),
14783 Scalar::Int64(30),
14784 ]
14785 );
14786 assert_eq!(
14787 fast.columns.get("w").unwrap().values(),
14788 &[
14789 Scalar::Int64(100),
14790 Scalar::Int64(101),
14791 Scalar::Int64(100),
14792 Scalar::Int64(101),
14793 Scalar::Int64(200),
14794 Scalar::Int64(200),
14795 Scalar::Int64(300),
14796 Scalar::Int64(301),
14797 ]
14798 );
14799 }
14800
14801 #[test]
14802 fn merge_outer_ordered_unique_int64_subset_matches_generic_validated_route() {
14803 let left = DataFrame::from_dict(
14804 &["id", "v"],
14805 vec![
14806 (
14807 "id",
14808 vec![Scalar::Int64(0), Scalar::Int64(1), Scalar::Int64(3)],
14809 ),
14810 (
14811 "v",
14812 vec![Scalar::Int64(10), Scalar::Int64(11), Scalar::Int64(13)],
14813 ),
14814 ],
14815 )
14816 .unwrap();
14817 let right = DataFrame::from_dict(
14818 &["id", "w"],
14819 vec![
14820 (
14821 "id",
14822 vec![
14823 Scalar::Int64(0),
14824 Scalar::Int64(2),
14825 Scalar::Int64(3),
14826 Scalar::Int64(5),
14827 ],
14828 ),
14829 (
14830 "w",
14831 vec![
14832 Scalar::Int64(100),
14833 Scalar::Int64(200),
14834 Scalar::Int64(300),
14835 Scalar::Int64(500),
14836 ],
14837 ),
14838 ],
14839 )
14840 .unwrap();
14841
14842 let fast = merge_dataframes(&left, &right, "id", JoinType::Outer).unwrap();
14843 let generic = merge_dataframes_on_with_options(
14844 &left,
14845 &right,
14846 &["id"],
14847 &["id"],
14848 JoinType::Outer,
14849 MergeExecutionOptions {
14850 validate_mode: Some(MergeValidateMode::OneToOne),
14851 ..MergeExecutionOptions::default()
14852 },
14853 )
14854 .unwrap();
14855
14856 assert_eq!(fast.index, generic.index);
14857 assert_eq!(fast.column_order, generic.column_order);
14858 assert_eq!(fast.columns, generic.columns);
14859 assert_eq!(
14860 fast.columns.get("id").unwrap().values(),
14861 &[
14862 Scalar::Int64(0),
14863 Scalar::Int64(1),
14864 Scalar::Int64(2),
14865 Scalar::Int64(3),
14866 Scalar::Int64(5)
14867 ]
14868 );
14869 let left_values = fast.columns.get("v").unwrap().values();
14870 assert_eq!(left_values[0], Scalar::Float64(10.0));
14871 assert_eq!(left_values[1], Scalar::Float64(11.0));
14872 assert!(left_values[2].is_missing());
14873 assert_eq!(left_values[3], Scalar::Float64(13.0));
14874 assert!(left_values[4].is_missing());
14875 let right_values = fast.columns.get("w").unwrap().values();
14876 assert_eq!(right_values[0], Scalar::Float64(100.0));
14877 assert!(right_values[1].is_missing());
14878 assert_eq!(right_values[2], Scalar::Float64(200.0));
14879 assert_eq!(right_values[3], Scalar::Float64(300.0));
14880 assert_eq!(right_values[4], Scalar::Float64(500.0));
14881 }
14882
14883 #[test]
14884 fn merge_outer_dense_int64_duplicates_matches_generic_validated_route() {
14885 let left = DataFrame::from_dict(
14886 &["id", "v"],
14887 vec![
14888 (
14889 "id",
14890 vec![
14891 Scalar::Int64(2),
14892 Scalar::Int64(0),
14893 Scalar::Int64(2),
14894 Scalar::Int64(1),
14895 Scalar::Int64(5),
14896 ],
14897 ),
14898 (
14899 "v",
14900 vec![
14901 Scalar::Int64(10),
14902 Scalar::Int64(11),
14903 Scalar::Int64(12),
14904 Scalar::Int64(13),
14905 Scalar::Int64(15),
14906 ],
14907 ),
14908 ],
14909 )
14910 .unwrap();
14911 let right = DataFrame::from_dict(
14912 &["id", "w"],
14913 vec![
14914 (
14915 "id",
14916 vec![
14917 Scalar::Int64(2),
14918 Scalar::Int64(2),
14919 Scalar::Int64(3),
14920 Scalar::Int64(0),
14921 ],
14922 ),
14923 (
14924 "w",
14925 vec![
14926 Scalar::Int64(200),
14927 Scalar::Int64(201),
14928 Scalar::Int64(300),
14929 Scalar::Int64(400),
14930 ],
14931 ),
14932 ],
14933 )
14934 .unwrap();
14935
14936 let fast = merge_dataframes(&left, &right, "id", JoinType::Outer).unwrap();
14937 let generic = merge_dataframes_on_with_options(
14938 &left,
14939 &right,
14940 &["id"],
14941 &["id"],
14942 JoinType::Outer,
14943 MergeExecutionOptions {
14944 validate_mode: Some(MergeValidateMode::ManyToMany),
14945 ..MergeExecutionOptions::default()
14946 },
14947 )
14948 .unwrap();
14949
14950 assert_eq!(fast.index, generic.index);
14951 assert_eq!(fast.column_order, generic.column_order);
14952 assert_eq!(fast.columns, generic.columns);
14953 assert_eq!(
14954 fast.columns.get("id").unwrap().values(),
14955 &[
14956 Scalar::Int64(0),
14957 Scalar::Int64(1),
14958 Scalar::Int64(2),
14959 Scalar::Int64(2),
14960 Scalar::Int64(2),
14961 Scalar::Int64(2),
14962 Scalar::Int64(3),
14963 Scalar::Int64(5),
14964 ]
14965 );
14966 let left_values = fast.columns.get("v").unwrap().values();
14967 assert_eq!(left_values[0], Scalar::Float64(11.0));
14968 assert_eq!(left_values[1], Scalar::Float64(13.0));
14969 assert_eq!(left_values[2], Scalar::Float64(10.0));
14970 assert_eq!(left_values[5], Scalar::Float64(12.0));
14971 assert!(left_values[6].is_missing());
14972 assert_eq!(left_values[7], Scalar::Float64(15.0));
14973 let right_values = fast.columns.get("w").unwrap().values();
14974 assert_eq!(right_values[0], Scalar::Float64(400.0));
14975 assert!(right_values[1].is_missing());
14976 assert_eq!(right_values[2], Scalar::Float64(200.0));
14977 assert_eq!(right_values[3], Scalar::Float64(201.0));
14978 assert!(right_values[7].is_missing());
14979 }
14980
14981 #[test]
14982 fn merge_outer_all_matched_dense_int64_duplicates_matches_generic_validated_route() {
14983 let left = DataFrame::from_dict(
14984 &["id", "v"],
14985 vec![
14986 (
14987 "id",
14988 vec![
14989 Scalar::Int64(2),
14990 Scalar::Int64(1),
14991 Scalar::Int64(2),
14992 Scalar::Int64(1),
14993 ],
14994 ),
14995 (
14996 "v",
14997 vec![
14998 Scalar::Int64(20),
14999 Scalar::Int64(10),
15000 Scalar::Int64(21),
15001 Scalar::Int64(11),
15002 ],
15003 ),
15004 ],
15005 )
15006 .unwrap();
15007 let right = DataFrame::from_dict(
15008 &["id", "w"],
15009 vec![
15010 (
15011 "id",
15012 vec![
15013 Scalar::Int64(1),
15014 Scalar::Int64(2),
15015 Scalar::Int64(1),
15016 Scalar::Int64(2),
15017 ],
15018 ),
15019 (
15020 "w",
15021 vec![
15022 Scalar::Int64(100),
15023 Scalar::Int64(200),
15024 Scalar::Int64(101),
15025 Scalar::Int64(201),
15026 ],
15027 ),
15028 ],
15029 )
15030 .unwrap();
15031
15032 let fast = merge_dataframes(&left, &right, "id", JoinType::Outer).unwrap();
15033 let generic = merge_dataframes_on_with_options(
15034 &left,
15035 &right,
15036 &["id"],
15037 &["id"],
15038 JoinType::Outer,
15039 MergeExecutionOptions {
15040 validate_mode: Some(MergeValidateMode::ManyToMany),
15041 ..MergeExecutionOptions::default()
15042 },
15043 )
15044 .unwrap();
15045
15046 assert_eq!(fast.index, generic.index);
15047 assert_eq!(fast.column_order, generic.column_order);
15048 assert_eq!(fast.columns, generic.columns);
15049 assert_eq!(
15050 generic.columns.get("id").unwrap().values(),
15051 &[
15052 Scalar::Int64(1),
15053 Scalar::Int64(1),
15054 Scalar::Int64(1),
15055 Scalar::Int64(1),
15056 Scalar::Int64(2),
15057 Scalar::Int64(2),
15058 Scalar::Int64(2),
15059 Scalar::Int64(2),
15060 ]
15061 );
15062 assert!(
15063 generic
15064 .columns
15065 .values()
15066 .all(|column| column.as_i64_slice().is_some())
15067 );
15068 }
15069
15070 #[test]
15071 fn merge_outer_all_matched_dense_int64_fused_output_matches_sorted_generic_route() {
15072 let left = DataFrame::from_dict(
15073 &["id", "v"],
15074 vec![
15075 (
15076 "id",
15077 vec![
15078 Scalar::Int64(2),
15079 Scalar::Int64(1),
15080 Scalar::Int64(2),
15081 Scalar::Int64(1),
15082 ],
15083 ),
15084 (
15085 "v",
15086 vec![
15087 Scalar::Int64(20),
15088 Scalar::Int64(10),
15089 Scalar::Int64(21),
15090 Scalar::Int64(11),
15091 ],
15092 ),
15093 ],
15094 )
15095 .unwrap();
15096 let right = DataFrame::from_dict(
15097 &["id", "w"],
15098 vec![
15099 (
15100 "id",
15101 vec![
15102 Scalar::Int64(1),
15103 Scalar::Int64(2),
15104 Scalar::Int64(1),
15105 Scalar::Int64(2),
15106 ],
15107 ),
15108 (
15109 "w",
15110 vec![
15111 Scalar::Int64(100),
15112 Scalar::Int64(200),
15113 Scalar::Int64(101),
15114 Scalar::Int64(201),
15115 ],
15116 ),
15117 ],
15118 )
15119 .unwrap();
15120
15121 let fused = merge_dataframes(&left, &right, "id", JoinType::Outer).unwrap();
15122 let generic = merge_dataframes_on_with_options(
15123 &left,
15124 &right,
15125 &["id"],
15126 &["id"],
15127 JoinType::Outer,
15128 MergeExecutionOptions {
15129 validate_mode: Some(MergeValidateMode::ManyToMany),
15130 sort: true,
15131 ..MergeExecutionOptions::default()
15132 },
15133 )
15134 .unwrap();
15135
15136 assert_eq!(fused.index, generic.index);
15137 assert_eq!(fused.column_order, generic.column_order);
15138 assert_eq!(fused.columns, generic.columns);
15139 }
15140
15141 #[test]
15142 fn merge_left_contiguous_utf8_duplicates_matches_sorted_generic_route() {
15143 let s = |v: &str| Scalar::Utf8(v.to_owned());
15144 let left = DataFrame::from_dict(
15145 &["id", "v"],
15146 vec![
15147 ("id", vec![s("a"), s("a"), s("b"), s("c")]),
15148 (
15149 "v",
15150 vec![
15151 Scalar::Int64(10),
15152 Scalar::Int64(11),
15153 Scalar::Int64(20),
15154 Scalar::Int64(30),
15155 ],
15156 ),
15157 ],
15158 )
15159 .unwrap();
15160 let right = DataFrame::from_dict(
15161 &["id", "w"],
15162 vec![
15163 ("id", vec![s("a"), s("a"), s("c")]),
15164 (
15165 "w",
15166 vec![Scalar::Int64(100), Scalar::Int64(101), Scalar::Int64(300)],
15167 ),
15168 ],
15169 )
15170 .unwrap();
15171
15172 let fast = merge_dataframes(&left, &right, "id", JoinType::Left).unwrap();
15173 let generic = merge_dataframes_on_with_options(
15174 &left,
15175 &right,
15176 &["id"],
15177 &["id"],
15178 JoinType::Left,
15179 MergeExecutionOptions {
15180 sort: true,
15181 ..MergeExecutionOptions::default()
15182 },
15183 )
15184 .unwrap();
15185
15186 assert_eq!(fast.index, generic.index);
15187 assert_eq!(fast.column_order, generic.column_order);
15188 assert_eq!(fast.columns, generic.columns);
15189 assert_eq!(
15190 fast.columns.get("id").unwrap().values(),
15191 &[s("a"), s("a"), s("a"), s("a"), s("b"), s("c")]
15192 );
15193 assert!(fast.columns.get("w").unwrap().values()[4].is_missing());
15194 }
15195
15196 #[test]
15197 fn merge_outer_contiguous_utf8_duplicates_matches_sorted_generic_route() {
15198 let s = |v: &str| Scalar::Utf8(v.to_owned());
15199 let left = DataFrame::from_dict(
15200 &["id", "v"],
15201 vec![
15202 ("id", vec![s("a"), s("a"), s("b"), s("d")]),
15203 (
15204 "v",
15205 vec![
15206 Scalar::Int64(10),
15207 Scalar::Int64(11),
15208 Scalar::Int64(20),
15209 Scalar::Int64(40),
15210 ],
15211 ),
15212 ],
15213 )
15214 .unwrap();
15215 let right = DataFrame::from_dict(
15216 &["id", "w"],
15217 vec![
15218 ("id", vec![s("a"), s("c"), s("a")]),
15219 (
15220 "w",
15221 vec![Scalar::Int64(100), Scalar::Int64(300), Scalar::Int64(101)],
15222 ),
15223 ],
15224 )
15225 .unwrap();
15226
15227 let fast = merge_dataframes(&left, &right, "id", JoinType::Outer).unwrap();
15228 let generic = merge_dataframes_on_with_options(
15229 &left,
15230 &right,
15231 &["id"],
15232 &["id"],
15233 JoinType::Outer,
15234 MergeExecutionOptions {
15235 sort: true,
15236 ..MergeExecutionOptions::default()
15237 },
15238 )
15239 .unwrap();
15240
15241 assert_eq!(fast.index, generic.index);
15242 assert_eq!(fast.column_order, generic.column_order);
15243 assert_eq!(fast.columns, generic.columns);
15244 assert_eq!(
15245 fast.columns.get("id").unwrap().values(),
15246 &[s("a"), s("a"), s("a"), s("a"), s("b"), s("c"), s("d")]
15247 );
15248 assert!(fast.columns.get("v").unwrap().values()[5].is_missing());
15249 assert!(fast.columns.get("w").unwrap().values()[4].is_missing());
15250 assert!(fast.columns.get("w").unwrap().values()[6].is_missing());
15251 }
15252
15253 #[test]
15254 fn merge_outer_fixed_decimal_utf8_all_matched_fuses_sorted_output_wikcu() {
15255 let s = |v: &str| Scalar::Utf8(v.to_owned());
15256 let left = DataFrame::from_dict(
15257 &["id", "lv"],
15258 vec![
15259 (
15260 "id",
15261 vec![
15262 s("k00000002"),
15263 s("k00000000"),
15264 s("k00000002"),
15265 s("k00000001"),
15266 ],
15267 ),
15268 (
15269 "lv",
15270 vec![
15271 Scalar::Float64(20.0),
15272 Scalar::Float64(0.0),
15273 Scalar::Float64(21.0),
15274 Scalar::Float64(10.0),
15275 ],
15276 ),
15277 ],
15278 )
15279 .unwrap();
15280 let right = DataFrame::from_dict(
15281 &["id", "rv"],
15282 vec![
15283 ("id", vec![s("k00000000"), s("k00000001"), s("k00000002")]),
15284 (
15285 "rv",
15286 vec![
15287 Scalar::Float64(100.0),
15288 Scalar::Float64(110.0),
15289 Scalar::Float64(120.0),
15290 ],
15291 ),
15292 ],
15293 )
15294 .unwrap();
15295
15296 let fast = merge_dataframes(&left, &right, "id", JoinType::Outer).unwrap();
15297 let generic = merge_dataframes_on_with_options(
15298 &left,
15299 &right,
15300 &["id"],
15301 &["id"],
15302 JoinType::Outer,
15303 MergeExecutionOptions {
15304 sort: true,
15305 ..MergeExecutionOptions::default()
15306 },
15307 )
15308 .unwrap();
15309
15310 assert_eq!(fast.index, generic.index);
15311 assert_eq!(fast.column_order, generic.column_order);
15312 assert_eq!(fast.columns, generic.columns);
15313 assert_eq!(
15314 fast.columns.get("id").unwrap().values(),
15315 &[
15316 s("k00000000"),
15317 s("k00000001"),
15318 s("k00000002"),
15319 s("k00000002")
15320 ]
15321 );
15322 assert_eq!(
15323 fast.columns.get("lv").unwrap().values(),
15324 &[
15325 Scalar::Float64(0.0),
15326 Scalar::Float64(10.0),
15327 Scalar::Float64(20.0),
15328 Scalar::Float64(21.0),
15329 ]
15330 );
15331 }
15332
15333 #[test]
15334 fn merge_right_dense_int64_duplicates_matches_generic_validated_route() {
15335 let left = DataFrame::from_dict(
15336 &["id", "v"],
15337 vec![
15338 (
15339 "id",
15340 vec![
15341 Scalar::Int64(2),
15342 Scalar::Int64(0),
15343 Scalar::Int64(2),
15344 Scalar::Int64(1),
15345 Scalar::Int64(5),
15346 ],
15347 ),
15348 (
15349 "v",
15350 vec![
15351 Scalar::Int64(10),
15352 Scalar::Int64(11),
15353 Scalar::Int64(12),
15354 Scalar::Int64(13),
15355 Scalar::Int64(15),
15356 ],
15357 ),
15358 ],
15359 )
15360 .unwrap();
15361 let right = DataFrame::from_dict(
15362 &["id", "w"],
15363 vec![
15364 (
15365 "id",
15366 vec![
15367 Scalar::Int64(2),
15368 Scalar::Int64(2),
15369 Scalar::Int64(3),
15370 Scalar::Int64(0),
15371 ],
15372 ),
15373 (
15374 "w",
15375 vec![
15376 Scalar::Int64(200),
15377 Scalar::Int64(201),
15378 Scalar::Int64(300),
15379 Scalar::Int64(400),
15380 ],
15381 ),
15382 ],
15383 )
15384 .unwrap();
15385
15386 let fast = merge_dataframes(&left, &right, "id", JoinType::Right).unwrap();
15387 let generic = merge_dataframes_on_with_options(
15388 &left,
15389 &right,
15390 &["id"],
15391 &["id"],
15392 JoinType::Right,
15393 MergeExecutionOptions {
15394 validate_mode: Some(MergeValidateMode::ManyToMany),
15395 ..MergeExecutionOptions::default()
15396 },
15397 )
15398 .unwrap();
15399
15400 assert_eq!(fast.index, generic.index);
15401 assert_eq!(fast.column_order, generic.column_order);
15402 assert_eq!(fast.columns, generic.columns);
15403 assert_eq!(
15404 fast.columns.get("id").unwrap().values(),
15405 &[
15406 Scalar::Int64(2),
15407 Scalar::Int64(2),
15408 Scalar::Int64(2),
15409 Scalar::Int64(2),
15410 Scalar::Int64(3),
15411 Scalar::Int64(0),
15412 ]
15413 );
15414 let left_values = fast.columns.get("v").unwrap().values();
15415 assert_eq!(left_values[0], Scalar::Int64(10));
15416 assert_eq!(left_values[1], Scalar::Int64(12));
15417 assert_eq!(left_values[2], Scalar::Int64(10));
15418 assert_eq!(left_values[3], Scalar::Int64(12));
15419 assert!(left_values[4].is_missing());
15420 assert_eq!(left_values[5], Scalar::Int64(11));
15421 let right_values = fast.columns.get("w").unwrap().values();
15422 assert_eq!(right_values[0], Scalar::Int64(200));
15423 assert_eq!(right_values[1], Scalar::Int64(200));
15424 assert_eq!(right_values[2], Scalar::Int64(201));
15425 assert_eq!(right_values[3], Scalar::Int64(201));
15426 assert_eq!(right_values[4], Scalar::Int64(300));
15427 assert_eq!(right_values[5], Scalar::Int64(400));
15428 }
15429
15430 #[test]
15431 fn merge_right_dense_cycle_probe_output_matches_materialized_positions_yq96z() {
15432 let left = DataFrame::from_dict(
15433 &["id", "v"],
15434 vec![
15435 (
15436 "id",
15437 vec![
15438 Scalar::Int64(1),
15439 Scalar::Int64(2),
15440 Scalar::Int64(1),
15441 Scalar::Int64(2),
15442 ],
15443 ),
15444 (
15445 "v",
15446 vec![
15447 Scalar::Int64(100),
15448 Scalar::Int64(200),
15449 Scalar::Int64(101),
15450 Scalar::Int64(201),
15451 ],
15452 ),
15453 ],
15454 )
15455 .unwrap();
15456 let right = DataFrame::from_dict(
15457 &["id", "w"],
15458 vec![
15459 (
15460 "id",
15461 vec![
15462 Scalar::Int64(0),
15463 Scalar::Int64(1),
15464 Scalar::Int64(2),
15465 Scalar::Int64(0),
15466 Scalar::Int64(1),
15467 ],
15468 ),
15469 (
15470 "w",
15471 vec![
15472 Scalar::Int64(10),
15473 Scalar::Int64(11),
15474 Scalar::Int64(12),
15475 Scalar::Int64(13),
15476 Scalar::Int64(14),
15477 ],
15478 ),
15479 ],
15480 )
15481 .unwrap();
15482 let left_key = left.columns().get("id").unwrap();
15483 let right_key = right.columns().get("id").unwrap();
15484 assert!(left_key.int64_dense_cycle_witness().is_some());
15485 assert!(right_key.int64_dense_cycle_witness().is_some());
15486 let suffixes = resolve_merge_suffixes(None);
15487
15488 let fused = build_single_key_dense_i64_right_merge_output(
15489 &left,
15490 &right,
15491 &["id"],
15492 &["id"],
15493 left_key,
15494 right_key,
15495 &suffixes,
15496 )
15497 .unwrap()
15498 .expect("dense-cycle right route should accept");
15499 let (left_positions, right_positions) =
15500 dense_int64_right_positions(left_key, right_key).unwrap();
15501 let materialized = build_single_key_dense_right_merge_output(
15502 &left,
15503 &right,
15504 &["id"],
15505 &["id"],
15506 &left_positions,
15507 &right_positions,
15508 &suffixes,
15509 )
15510 .unwrap();
15511
15512 assert_eq!(fused.index, materialized.index);
15513 assert_eq!(fused.column_order, materialized.column_order);
15514 assert_eq!(fused.columns, materialized.columns);
15515 assert_eq!(
15516 fused.columns.get("v").unwrap().values(),
15517 &[
15518 Scalar::Null(NullKind::Null),
15519 Scalar::Int64(100),
15520 Scalar::Int64(101),
15521 Scalar::Int64(200),
15522 Scalar::Int64(201),
15523 Scalar::Null(NullKind::Null),
15524 Scalar::Int64(100),
15525 Scalar::Int64(101),
15526 ]
15527 );
15528 }
15529
15530 #[test]
15531 fn merge_left_right_all_matched_dense_int64_duplicates_match_generic_validated_route() {
15532 let left = DataFrame::from_dict(
15533 &["id", "v"],
15534 vec![
15535 (
15536 "id",
15537 vec![
15538 Scalar::Int64(2),
15539 Scalar::Int64(1),
15540 Scalar::Int64(2),
15541 Scalar::Int64(1),
15542 ],
15543 ),
15544 (
15545 "v",
15546 vec![
15547 Scalar::Int64(20),
15548 Scalar::Int64(10),
15549 Scalar::Int64(21),
15550 Scalar::Int64(11),
15551 ],
15552 ),
15553 ],
15554 )
15555 .unwrap();
15556 let right = DataFrame::from_dict(
15557 &["id", "w"],
15558 vec![
15559 (
15560 "id",
15561 vec![
15562 Scalar::Int64(1),
15563 Scalar::Int64(2),
15564 Scalar::Int64(1),
15565 Scalar::Int64(2),
15566 ],
15567 ),
15568 (
15569 "w",
15570 vec![
15571 Scalar::Int64(100),
15572 Scalar::Int64(200),
15573 Scalar::Int64(101),
15574 Scalar::Int64(201),
15575 ],
15576 ),
15577 ],
15578 )
15579 .unwrap();
15580
15581 for join_type in [JoinType::Left, JoinType::Right] {
15582 let fast = merge_dataframes(&left, &right, "id", join_type).unwrap();
15583 let generic = merge_dataframes_on_with_options(
15584 &left,
15585 &right,
15586 &["id"],
15587 &["id"],
15588 join_type,
15589 MergeExecutionOptions {
15590 validate_mode: Some(MergeValidateMode::ManyToMany),
15591 ..MergeExecutionOptions::default()
15592 },
15593 )
15594 .unwrap();
15595
15596 assert_eq!(fast.index, generic.index);
15597 assert_eq!(fast.column_order, generic.column_order);
15598 assert_eq!(fast.columns, generic.columns);
15599 assert!(
15600 generic
15601 .columns
15602 .values()
15603 .all(|column| column.as_i64_slice().is_some())
15604 );
15605 }
15606 }
15607
15608 #[test]
15609 fn merge_right_all_matched_dense_int64_fused_output_matches_dense_materialization() {
15610 let left = DataFrame::from_dict(
15611 &["id", "v"],
15612 vec![
15613 (
15614 "id",
15615 vec![
15616 Scalar::Int64(2),
15617 Scalar::Int64(1),
15618 Scalar::Int64(2),
15619 Scalar::Int64(1),
15620 ],
15621 ),
15622 (
15623 "v",
15624 vec![
15625 Scalar::Int64(20),
15626 Scalar::Int64(10),
15627 Scalar::Int64(21),
15628 Scalar::Int64(11),
15629 ],
15630 ),
15631 ],
15632 )
15633 .unwrap();
15634 let right = DataFrame::from_dict(
15635 &["id", "w"],
15636 vec![
15637 (
15638 "id",
15639 vec![
15640 Scalar::Int64(1),
15641 Scalar::Int64(2),
15642 Scalar::Int64(1),
15643 Scalar::Int64(2),
15644 ],
15645 ),
15646 (
15647 "w",
15648 vec![
15649 Scalar::Int64(100),
15650 Scalar::Int64(200),
15651 Scalar::Int64(101),
15652 Scalar::Int64(201),
15653 ],
15654 ),
15655 ],
15656 )
15657 .unwrap();
15658
15659 let fused = merge_dataframes(&left, &right, "id", JoinType::Right).unwrap();
15660 let left_key = left.columns().get("id").unwrap();
15661 let right_key = right.columns().get("id").unwrap();
15662 let (left_positions, right_positions) =
15663 dense_int64_right_positions(left_key, right_key).unwrap();
15664 let suffixes = resolve_merge_suffixes(None);
15665 let materialized = build_single_key_dense_right_merge_output(
15666 &left,
15667 &right,
15668 &["id"],
15669 &["id"],
15670 &left_positions,
15671 &right_positions,
15672 &suffixes,
15673 )
15674 .unwrap();
15675
15676 assert_eq!(fused.index, materialized.index);
15677 assert_eq!(fused.column_order, materialized.column_order);
15678 assert_eq!(fused.columns, materialized.columns);
15679 assert_eq!(
15680 fused.columns.get("id").unwrap().values(),
15681 &[
15682 Scalar::Int64(1),
15683 Scalar::Int64(1),
15684 Scalar::Int64(2),
15685 Scalar::Int64(2),
15686 Scalar::Int64(1),
15687 Scalar::Int64(1),
15688 Scalar::Int64(2),
15689 Scalar::Int64(2),
15690 ]
15691 );
15692 assert!(
15693 fused
15694 .columns
15695 .values()
15696 .all(|column| column.as_i64_slice().is_some())
15697 );
15698 }
15699
15700 #[test]
15701 fn merge_right_ordered_unique_int64_subset_matches_generic_validated_route() {
15702 let left = DataFrame::from_dict(
15703 &["id", "v"],
15704 vec![
15705 (
15706 "id",
15707 vec![Scalar::Int64(0), Scalar::Int64(1), Scalar::Int64(3)],
15708 ),
15709 (
15710 "v",
15711 vec![Scalar::Int64(10), Scalar::Int64(11), Scalar::Int64(13)],
15712 ),
15713 ],
15714 )
15715 .unwrap();
15716 let right = DataFrame::from_dict(
15717 &["id", "w"],
15718 vec![
15719 (
15720 "id",
15721 vec![
15722 Scalar::Int64(0),
15723 Scalar::Int64(2),
15724 Scalar::Int64(3),
15725 Scalar::Int64(5),
15726 ],
15727 ),
15728 (
15729 "w",
15730 vec![
15731 Scalar::Int64(100),
15732 Scalar::Int64(200),
15733 Scalar::Int64(300),
15734 Scalar::Int64(500),
15735 ],
15736 ),
15737 ],
15738 )
15739 .unwrap();
15740
15741 let fast = merge_dataframes(&left, &right, "id", JoinType::Right).unwrap();
15742 let generic = merge_dataframes_on_with_options(
15743 &left,
15744 &right,
15745 &["id"],
15746 &["id"],
15747 JoinType::Right,
15748 MergeExecutionOptions {
15749 validate_mode: Some(MergeValidateMode::OneToOne),
15750 ..MergeExecutionOptions::default()
15751 },
15752 )
15753 .unwrap();
15754
15755 assert_eq!(fast.index, generic.index);
15756 assert_eq!(fast.column_order, generic.column_order);
15757 assert_eq!(fast.columns, generic.columns);
15758 assert_eq!(
15759 fast.columns.get("id").unwrap().values(),
15760 &[
15761 Scalar::Int64(0),
15762 Scalar::Int64(2),
15763 Scalar::Int64(3),
15764 Scalar::Int64(5)
15765 ]
15766 );
15767 let left_values = fast.columns.get("v").unwrap().values();
15768 assert_eq!(left_values[0], Scalar::Int64(10));
15769 assert!(left_values[1].is_missing());
15770 assert_eq!(left_values[2], Scalar::Int64(13));
15771 assert!(left_values[3].is_missing());
15772 let right_values = fast.columns.get("w").unwrap().values();
15773 assert_eq!(right_values[0], Scalar::Int64(100));
15774 assert_eq!(right_values[1], Scalar::Int64(200));
15775 assert_eq!(right_values[2], Scalar::Int64(300));
15776 assert_eq!(right_values[3], Scalar::Int64(500));
15777 }
15778
15779 #[test]
15780 fn merge_right_preserves_all_right_rows() {
15781 let left = make_left_df();
15782 let right = make_right_df();
15783 let merged = merge_dataframes(&left, &right, "id", JoinType::Right).unwrap();
15784
15785 assert_eq!(merged.columns.get("id").unwrap().len(), 3);
15786 assert_eq!(
15787 merged.columns.get("val_b").unwrap().values(),
15788 &[Scalar::Int64(200), Scalar::Int64(300), Scalar::Int64(400)]
15789 );
15790 assert_eq!(
15792 merged.columns.get("val_a").unwrap().values()[0],
15793 Scalar::Int64(20)
15794 );
15795 assert_eq!(
15796 merged.columns.get("val_a").unwrap().values()[1],
15797 Scalar::Int64(30)
15798 );
15799 assert!(merged.columns.get("val_a").unwrap().values()[2].is_missing());
15800 }
15801
15802 #[test]
15803 fn merge_outer_contains_all_rows() {
15804 let left = make_left_df();
15805 let right = make_right_df();
15806 let merged = merge_dataframes(&left, &right, "id", JoinType::Outer).unwrap();
15807
15808 assert_eq!(merged.columns.get("id").unwrap().len(), 4);
15810 }
15811
15812 #[test]
15813 fn merge_inner_sort_false_preserves_left_key_order() {
15814 let left = DataFrame::from_dict(
15815 &["id", "left_v"],
15816 vec![
15817 (
15818 "id",
15819 vec![Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(2)],
15820 ),
15821 (
15822 "left_v",
15823 vec![Scalar::Int64(20), Scalar::Int64(10), Scalar::Int64(21)],
15824 ),
15825 ],
15826 )
15827 .expect("left");
15828 let right = DataFrame::from_dict(
15829 &["id", "right_v"],
15830 vec![
15831 ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
15832 ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
15833 ],
15834 )
15835 .expect("right");
15836
15837 let merged = merge_dataframes_on_with_options(
15838 &left,
15839 &right,
15840 &["id"],
15841 &["id"],
15842 JoinType::Inner,
15843 MergeExecutionOptions::default(),
15844 )
15845 .expect("merge");
15846 assert_eq!(
15847 merged.columns.get("id").expect("id").values(),
15848 &[Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(2)]
15849 );
15850 assert_eq!(
15851 merged.columns.get("left_v").expect("left_v").values(),
15852 &[Scalar::Int64(20), Scalar::Int64(10), Scalar::Int64(21)]
15853 );
15854 assert_eq!(
15855 merged.columns.get("right_v").expect("right_v").values(),
15856 &[Scalar::Int64(200), Scalar::Int64(100), Scalar::Int64(200)]
15857 );
15858 }
15859
15860 #[test]
15861 fn merge_inner_sort_true_orders_join_keys_lexicographically() {
15862 let left = DataFrame::from_dict(
15863 &["id", "left_v"],
15864 vec![
15865 (
15866 "id",
15867 vec![Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(2)],
15868 ),
15869 (
15870 "left_v",
15871 vec![Scalar::Int64(20), Scalar::Int64(10), Scalar::Int64(21)],
15872 ),
15873 ],
15874 )
15875 .expect("left");
15876 let right = DataFrame::from_dict(
15877 &["id", "right_v"],
15878 vec![
15879 ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
15880 ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
15881 ],
15882 )
15883 .expect("right");
15884
15885 let merged = merge_dataframes_on_with_options(
15886 &left,
15887 &right,
15888 &["id"],
15889 &["id"],
15890 JoinType::Inner,
15891 MergeExecutionOptions {
15892 sort: true,
15893 ..MergeExecutionOptions::default()
15894 },
15895 )
15896 .expect("merge");
15897 assert_eq!(
15898 merged.columns.get("id").expect("id").values(),
15899 &[Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(2)]
15900 );
15901 assert_eq!(
15902 merged.columns.get("left_v").expect("left_v").values(),
15903 &[Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(21)]
15904 );
15905 assert_eq!(
15906 merged.columns.get("right_v").expect("right_v").values(),
15907 &[Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(200)]
15908 );
15909 }
15910
15911 #[test]
15912 fn merge_inner_sort_true_orders_float_keys_numerically() {
15913 let left = DataFrame::from_dict(
15914 &["id", "left_v"],
15915 vec![
15916 (
15917 "id",
15918 vec![
15919 Scalar::Float64(1.5),
15920 Scalar::Float64(-2.5),
15921 Scalar::Float64(0.25),
15922 ],
15923 ),
15924 (
15925 "left_v",
15926 vec![Scalar::Int64(15), Scalar::Int64(-25), Scalar::Int64(2)],
15927 ),
15928 ],
15929 )
15930 .expect("left");
15931 let right = DataFrame::from_dict(
15932 &["id", "right_v"],
15933 vec![
15934 (
15935 "id",
15936 vec![
15937 Scalar::Float64(-2.5),
15938 Scalar::Float64(0.25),
15939 Scalar::Float64(1.5),
15940 ],
15941 ),
15942 (
15943 "right_v",
15944 vec![Scalar::Int64(250), Scalar::Int64(25), Scalar::Int64(150)],
15945 ),
15946 ],
15947 )
15948 .expect("right");
15949
15950 let merged = merge_dataframes_on_with_options(
15951 &left,
15952 &right,
15953 &["id"],
15954 &["id"],
15955 JoinType::Inner,
15956 MergeExecutionOptions {
15957 sort: true,
15958 ..MergeExecutionOptions::default()
15959 },
15960 )
15961 .expect("merge");
15962
15963 assert_eq!(
15964 merged.columns.get("id").expect("id").values(),
15965 &[
15966 Scalar::Float64(-2.5),
15967 Scalar::Float64(0.25),
15968 Scalar::Float64(1.5)
15969 ]
15970 );
15971 assert_eq!(
15972 merged.columns.get("left_v").expect("left_v").values(),
15973 &[Scalar::Int64(-25), Scalar::Int64(2), Scalar::Int64(15)]
15974 );
15975 assert_eq!(
15976 merged.columns.get("right_v").expect("right_v").values(),
15977 &[Scalar::Int64(250), Scalar::Int64(25), Scalar::Int64(150)]
15978 );
15979 }
15980
15981 #[test]
15982 fn merge_right_sort_true_orders_join_keys_lexicographically() {
15983 let left = DataFrame::from_dict(
15984 &["id", "left_v"],
15985 vec![
15986 ("id", vec![Scalar::Int64(3), Scalar::Int64(1)]),
15987 ("left_v", vec![Scalar::Int64(30), Scalar::Int64(10)]),
15988 ],
15989 )
15990 .expect("left");
15991 let right = DataFrame::from_dict(
15992 &["id", "right_v"],
15993 vec![
15994 (
15995 "id",
15996 vec![Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(3)],
15997 ),
15998 (
15999 "right_v",
16000 vec![Scalar::Int64(200), Scalar::Int64(100), Scalar::Int64(300)],
16001 ),
16002 ],
16003 )
16004 .expect("right");
16005
16006 let merged = merge_dataframes_on_with_options(
16007 &left,
16008 &right,
16009 &["id"],
16010 &["id"],
16011 JoinType::Right,
16012 MergeExecutionOptions {
16013 sort: true,
16014 ..MergeExecutionOptions::default()
16015 },
16016 )
16017 .expect("merge");
16018 assert_eq!(
16019 merged.columns.get("id").expect("id").values(),
16020 &[Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)]
16021 );
16022 assert_eq!(
16023 merged.columns.get("left_v").expect("left_v").values(),
16024 &[
16025 Scalar::Int64(10),
16026 Scalar::Null(NullKind::Null),
16027 Scalar::Int64(30)
16028 ]
16029 );
16030 assert_eq!(
16031 merged.columns.get("right_v").expect("right_v").values(),
16032 &[Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(300)]
16033 );
16034 }
16035
16036 #[test]
16037 fn merge_column_name_conflict_adds_suffixes() {
16038 let left = DataFrame::from_dict(
16039 &["id", "val"],
16040 vec![
16041 ("id", vec![Scalar::Int64(1)]),
16042 ("val", vec![Scalar::Int64(10)]),
16043 ],
16044 )
16045 .unwrap();
16046 let right = DataFrame::from_dict(
16047 &["id", "val"],
16048 vec![
16049 ("id", vec![Scalar::Int64(1)]),
16050 ("val", vec![Scalar::Int64(99)]),
16051 ],
16052 )
16053 .unwrap();
16054
16055 let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
16056 assert!(merged.columns.contains_key("val_x"));
16057 assert!(merged.columns.contains_key("val_y"));
16058 assert_eq!(
16059 merged.columns.get("val_x").unwrap().values(),
16060 &[Scalar::Int64(10)]
16061 );
16062 assert_eq!(
16063 merged.columns.get("val_y").unwrap().values(),
16064 &[Scalar::Int64(99)]
16065 );
16066 }
16067
16068 #[test]
16069 fn merge_column_name_conflict_honors_custom_suffixes() {
16070 let left = DataFrame::from_dict(
16071 &["id", "val"],
16072 vec![
16073 ("id", vec![Scalar::Int64(1)]),
16074 ("val", vec![Scalar::Int64(10)]),
16075 ],
16076 )
16077 .expect("left");
16078 let right = DataFrame::from_dict(
16079 &["id", "val"],
16080 vec![
16081 ("id", vec![Scalar::Int64(1)]),
16082 ("val", vec![Scalar::Int64(99)]),
16083 ],
16084 )
16085 .expect("right");
16086
16087 let merged = merge_dataframes_on_with_options(
16088 &left,
16089 &right,
16090 &["id"],
16091 &["id"],
16092 JoinType::Inner,
16093 MergeExecutionOptions {
16094 suffixes: Some([Some("_L".to_owned()), Some("_R".to_owned())]),
16095 ..MergeExecutionOptions::default()
16096 },
16097 )
16098 .expect("merge");
16099 assert!(merged.columns.contains_key("val_L"));
16100 assert!(merged.columns.contains_key("val_R"));
16101 assert_eq!(
16102 merged.columns.get("val_L").expect("left suffixed").values(),
16103 &[Scalar::Int64(10)]
16104 );
16105 assert_eq!(
16106 merged
16107 .columns
16108 .get("val_R")
16109 .expect("right suffixed")
16110 .values(),
16111 &[Scalar::Int64(99)]
16112 );
16113 }
16114
16115 #[test]
16116 fn merge_column_name_conflict_allows_one_sided_suffix() {
16117 let left = DataFrame::from_dict(
16118 &["id", "val"],
16119 vec![
16120 ("id", vec![Scalar::Int64(1)]),
16121 ("val", vec![Scalar::Int64(10)]),
16122 ],
16123 )
16124 .expect("left");
16125 let right = DataFrame::from_dict(
16126 &["id", "val"],
16127 vec![
16128 ("id", vec![Scalar::Int64(1)]),
16129 ("val", vec![Scalar::Int64(99)]),
16130 ],
16131 )
16132 .expect("right");
16133
16134 let merged = merge_dataframes_on_with_options(
16135 &left,
16136 &right,
16137 &["id"],
16138 &["id"],
16139 JoinType::Inner,
16140 MergeExecutionOptions {
16141 suffixes: Some([None, Some("_r".to_owned())]),
16142 ..MergeExecutionOptions::default()
16143 },
16144 )
16145 .expect("merge");
16146 assert!(merged.columns.contains_key("val"));
16147 assert!(merged.columns.contains_key("val_r"));
16148 assert_eq!(
16149 merged.columns.get("val").expect("left unsuffixed").values(),
16150 &[Scalar::Int64(10)]
16151 );
16152 assert_eq!(
16153 merged
16154 .columns
16155 .get("val_r")
16156 .expect("right suffixed")
16157 .values(),
16158 &[Scalar::Int64(99)]
16159 );
16160 }
16161
16162 #[test]
16163 fn merge_column_name_conflict_rejects_missing_suffixes_for_overlap() {
16164 let left = DataFrame::from_dict(
16165 &["id", "val"],
16166 vec![
16167 ("id", vec![Scalar::Int64(1)]),
16168 ("val", vec![Scalar::Int64(10)]),
16169 ],
16170 )
16171 .expect("left");
16172 let right = DataFrame::from_dict(
16173 &["id", "val"],
16174 vec![
16175 ("id", vec![Scalar::Int64(1)]),
16176 ("val", vec![Scalar::Int64(99)]),
16177 ],
16178 )
16179 .expect("right");
16180
16181 let err = merge_dataframes_on_with_options(
16182 &left,
16183 &right,
16184 &["id"],
16185 &["id"],
16186 JoinType::Inner,
16187 MergeExecutionOptions {
16188 suffixes: Some([Some(String::new()), Some(String::new())]),
16189 ..MergeExecutionOptions::default()
16190 },
16191 )
16192 .expect_err("merge should reject overlapping columns without suffixes");
16193 assert!(format!("{err}").contains("columns overlap but no suffix specified"));
16194 }
16195
16196 #[test]
16197 fn merge_column_name_conflict_rejects_duplicate_output_columns_from_suffixes() {
16198 let left = DataFrame::from_dict(
16199 &["id", "val", "val_L"],
16200 vec![
16201 ("id", vec![Scalar::Int64(1)]),
16202 ("val", vec![Scalar::Int64(10)]),
16203 ("val_L", vec![Scalar::Int64(77)]),
16204 ],
16205 )
16206 .expect("left");
16207 let right = DataFrame::from_dict(
16208 &["id", "val"],
16209 vec![
16210 ("id", vec![Scalar::Int64(1)]),
16211 ("val", vec![Scalar::Int64(99)]),
16212 ],
16213 )
16214 .expect("right");
16215
16216 let err = merge_dataframes_on_with_options(
16217 &left,
16218 &right,
16219 &["id"],
16220 &["id"],
16221 JoinType::Inner,
16222 MergeExecutionOptions {
16223 suffixes: Some([Some("_L".to_owned()), Some("_R".to_owned())]),
16224 ..MergeExecutionOptions::default()
16225 },
16226 )
16227 .expect_err("merge should reject duplicate output names caused by suffixes");
16228 assert!(format!("{err}").contains("duplicate output column"));
16229 }
16230
16231 #[test]
16232 fn merge_missing_key_column_errors() {
16233 let left = make_left_df();
16234 let right = make_right_df();
16235 let err = merge_dataframes(&left, &right, "nonexistent", JoinType::Inner)
16236 .expect_err("should fail");
16237 assert!(format!("{err}").contains("nonexistent"));
16238 }
16239
16240 #[test]
16241 fn merge_duplicate_keys_multiply_cardinality() {
16242 let left = DataFrame::from_dict(
16243 &["id", "a"],
16244 vec![
16245 ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
16246 ("a", vec![Scalar::Int64(10), Scalar::Int64(20)]),
16247 ],
16248 )
16249 .unwrap();
16250 let right = DataFrame::from_dict(
16251 &["id", "b"],
16252 vec![
16253 ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
16254 ("b", vec![Scalar::Int64(100), Scalar::Int64(200)]),
16255 ],
16256 )
16257 .unwrap();
16258
16259 let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
16260 assert_eq!(merged.columns.get("id").unwrap().len(), 4);
16262 }
16263
16264 #[test]
16265 fn ordered_identity_int64_guard_uses_strict_unique_certificate() {
16266 let left = fp_columnar::Column::from_i64_values(vec![1, 2, 3, 4]);
16267 let right = fp_columnar::Column::from_i64_values(vec![1, 2, 3, 4]);
16268 assert!(ordered_identity_int64_keys_match(&left, &right));
16269
16270 let duplicate_left = fp_columnar::Column::from_i64_values(vec![1, 1, 2]);
16271 let duplicate_right = fp_columnar::Column::from_i64_values(vec![1, 1, 2]);
16272 assert!(!ordered_identity_int64_keys_match(
16273 &duplicate_left,
16274 &duplicate_right
16275 ));
16276
16277 let unsorted_left = fp_columnar::Column::from_i64_values(vec![2, 1, 3]);
16278 let unsorted_right = fp_columnar::Column::from_i64_values(vec![2, 1, 3]);
16279 assert!(ordered_identity_int64_keys_match(
16280 &unsorted_left,
16281 &unsorted_right
16282 ));
16283 }
16284
16285 #[test]
16286 fn merge_identical_duplicate_keys_cross_join_values_jdupk() {
16287 let left = DataFrame::from_dict(
16291 &["id", "a"],
16292 vec![
16293 ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
16294 ("a", vec![Scalar::Int64(10), Scalar::Int64(20)]),
16295 ],
16296 )
16297 .unwrap();
16298 let right = DataFrame::from_dict(
16299 &["id", "b"],
16300 vec![
16301 ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
16302 ("b", vec![Scalar::Int64(100), Scalar::Int64(200)]),
16303 ],
16304 )
16305 .unwrap();
16306
16307 let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
16308 assert_eq!(
16309 merged.columns.get("a").unwrap().values(),
16310 &[
16311 Scalar::Int64(10),
16312 Scalar::Int64(10),
16313 Scalar::Int64(20),
16314 Scalar::Int64(20)
16315 ]
16316 );
16317 assert_eq!(
16318 merged.columns.get("b").unwrap().values(),
16319 &[
16320 Scalar::Int64(100),
16321 Scalar::Int64(200),
16322 Scalar::Int64(100),
16323 Scalar::Int64(200)
16324 ]
16325 );
16326 }
16327
16328 #[test]
16329 fn ordered_unique_utf8_inner_positions_match_left_major_hash_order_53lat() {
16330 let left = contiguous_utf8_column(&["a", "b", "d", "f"]);
16331 let right = contiguous_utf8_column(&["b", "c", "f"]);
16332 let (left_positions, right_positions) =
16333 ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
16334
16335 assert_eq!(left_positions, vec![1, 3]);
16336 assert_eq!(right_positions, vec![0, 2]);
16337
16338 let merged = merge_dataframes(
16339 &utf8_key_merge_frame(&["a", "b", "d", "f"], "lv", 10),
16340 &utf8_key_merge_frame(&["b", "c", "f"], "rv", 20),
16341 "id",
16342 JoinType::Inner,
16343 )
16344 .unwrap();
16345 assert_eq!(
16346 merged.columns.get("lv").unwrap().values(),
16347 &[Scalar::Int64(11), Scalar::Int64(13)]
16348 );
16349 assert_eq!(
16350 merged.columns.get("rv").unwrap().values(),
16351 &[Scalar::Int64(20), Scalar::Int64(22)]
16352 );
16353 }
16354
16355 #[test]
16356 fn sorted_contiguous_utf8_inner_positions_preserves_duplicate_order_codb() {
16357 let left = contiguous_utf8_column(&["a", "a", "b", "d"]);
16358 let right = contiguous_utf8_column(&["a", "a", "c", "d"]);
16359 let (left_bytes, left_offsets) = left.as_utf8_contiguous().expect("left contiguous");
16360 let (right_bytes, right_offsets) = right.as_utf8_contiguous().expect("right contiguous");
16361
16362 let (left_positions, right_positions) = sorted_contiguous_utf8_inner_positions(
16363 left_bytes,
16364 left_offsets,
16365 right_bytes,
16366 right_offsets,
16367 )
16368 .expect("sorted spans should use two-pointer merge");
16369
16370 assert_eq!(left_positions, vec![0, 0, 1, 1, 3]);
16371 assert_eq!(right_positions, vec![0, 1, 0, 1, 3]);
16372 }
16373
16374 #[test]
16375 fn sorted_contiguous_utf8_inner_positions_rejects_unsorted_input_codb() {
16376 let left = contiguous_utf8_column(&["b", "a"]);
16377 let right = contiguous_utf8_column(&["a", "b"]);
16378 let (left_bytes, left_offsets) = left.as_utf8_contiguous().expect("left contiguous");
16379 let (right_bytes, right_offsets) = right.as_utf8_contiguous().expect("right contiguous");
16380
16381 assert!(
16382 sorted_contiguous_utf8_inner_positions(
16383 left_bytes,
16384 left_offsets,
16385 right_bytes,
16386 right_offsets,
16387 )
16388 .is_none()
16389 );
16390 }
16391
16392 #[test]
16393 fn ordered_unique_utf8_seek_bound_preserves_late_overlap_lr52z() {
16394 let left = contiguous_utf8_column(&["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]);
16395 let right = contiguous_utf8_column(&["h", "i", "j", "k"]);
16396 let (left_bytes, left_offsets) =
16397 strictly_increasing_utf8_key_spans(&left).expect("sorted left");
16398
16399 assert_eq!(utf8_span_lower_bound(left_bytes, left_offsets, b"h"), 7);
16400
16401 let (left_positions, right_positions) =
16402 ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
16403 assert_eq!(left_positions, vec![7, 8, 9]);
16404 assert_eq!(right_positions, vec![0, 1, 2]);
16405
16406 let disjoint_left = contiguous_utf8_column(&["a", "b"]);
16407 let disjoint_right = contiguous_utf8_column(&["c", "d"]);
16408 let (left_positions, right_positions) =
16409 ordered_unique_utf8_inner_positions(&disjoint_left, &disjoint_right)
16410 .expect("ordered disjoint utf8 positions");
16411 assert!(left_positions.is_empty());
16412 assert!(right_positions.is_empty());
16413 }
16414
16415 #[test]
16416 fn ordered_unique_utf8_bulk_fixed_width_window_jbyuc11() {
16417 let left = contiguous_utf8_column(&["k000", "k001", "k002", "k003", "k004"]);
16418 let right = contiguous_utf8_column(&["k002", "k003", "k004", "k005"]);
16419
16420 let (left_positions, right_positions) =
16421 ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
16422 assert_eq!(left_positions, vec![2, 3, 4]);
16423 assert_eq!(right_positions, vec![0, 1, 2]);
16424 }
16425
16426 #[test]
16427 fn ordered_unique_utf8_bulk_window_returns_range_plan_jbyuc11111() {
16428 let left = contiguous_utf8_column(&["k000", "k001", "k002", "k003", "k004"]);
16429 let right = contiguous_utf8_column(&["k002", "k003", "k004", "k005"]);
16430
16431 let plan =
16432 ordered_unique_utf8_inner_position_plan(&left, &right).expect("ordered utf8 plan");
16433
16434 assert_eq!(
16435 plan,
16436 InnerPositionPlan::ContiguousRanges {
16437 left_start: 2,
16438 right_start: 0,
16439 len: 3
16440 }
16441 );
16442 }
16443
16444 #[test]
16445 fn ordered_unique_utf8_lower_hex_certificate_returns_range_plan_jbyuc111111() {
16446 let left =
16447 contiguous_utf8_column(&["id_0000000a", "id_0000000b", "id_0000000c", "id_0000000d"]);
16448 let right = contiguous_utf8_column(&["id_0000000c", "id_0000000d", "id_0000000e"]);
16449 let (_, _, left_cert) = left
16450 .as_lower_hex_sequence_utf8_contiguous()
16451 .expect("left sequence certificate");
16452 let (_, _, right_cert) = right
16453 .as_lower_hex_sequence_utf8_contiguous()
16454 .expect("right sequence certificate");
16455
16456 assert_eq!(
16457 ordered_utf8_lower_hex_overlap_len(left_cert, right_cert, 2, 4, 0, 3),
16458 Some(2)
16459 );
16460 assert_eq!(
16461 lower_hex_overlap_plan_from_certificates(&left, &right),
16462 Some(InnerPositionPlan::ContiguousRanges {
16463 left_start: 2,
16464 right_start: 0,
16465 len: 2
16466 })
16467 );
16468 let plan =
16469 ordered_unique_utf8_inner_position_plan(&left, &right).expect("ordered utf8 plan");
16470 assert_eq!(
16471 plan,
16472 InnerPositionPlan::ContiguousRanges {
16473 left_start: 2,
16474 right_start: 0,
16475 len: 2
16476 }
16477 );
16478 }
16479
16480 #[test]
16481 fn ordered_unique_utf8_lower_hex_arithmetic_empty_overlap_jbyuc1111111111() {
16482 let left = contiguous_utf8_column(&["id_00000001", "id_00000002", "id_00000003"]);
16483 let right = contiguous_utf8_column(&["id_00000008", "id_00000009"]);
16484
16485 assert_eq!(
16486 lower_hex_overlap_plan_from_certificates(&left, &right),
16487 Some(InnerPositionPlan::Gather {
16488 left_positions: Vec::new(),
16489 right_positions: Vec::new(),
16490 })
16491 );
16492 let (left_positions, right_positions) =
16493 ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
16494 assert!(left_positions.is_empty());
16495 assert!(right_positions.is_empty());
16496 }
16497
16498 #[test]
16499 fn ordered_unique_utf8_lower_hex_prefix_mismatch_falls_back_jbyuc1111111111() {
16500 let left = contiguous_utf8_column(&["aa_00000001", "aa_00000002", "aa_00000003"]);
16501 let right = contiguous_utf8_column(&["bb_00000001", "bb_00000002", "bb_00000003"]);
16502
16503 assert!(
16504 lower_hex_overlap_plan_from_certificates(&left, &right).is_none(),
16505 "matching lower-hex counters with different prefixes must not use arithmetic overlap"
16506 );
16507 let (left_positions, right_positions) =
16508 ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
16509 assert!(left_positions.is_empty());
16510 assert!(right_positions.is_empty());
16511 }
16512
16513 #[test]
16514 fn ordered_utf8_contiguous_no_overlap_output_fast_path_jbyuc111111111() -> Result<(), String> {
16515 let left = utf8_key_merge_frame(
16516 &["id_00000000", "id_00000001", "id_00000002", "id_00000003"],
16517 "lv",
16518 10,
16519 );
16520 let right = utf8_key_merge_frame(&["id_00000002", "id_00000003", "id_00000004"], "rv", 100);
16521 let plan = ordered_unique_utf8_inner_position_plan(
16522 left.columns()
16523 .get("id")
16524 .ok_or_else(|| "left key column missing".to_owned())?,
16525 right
16526 .columns()
16527 .get("id")
16528 .ok_or_else(|| "right key column missing".to_owned())?,
16529 )
16530 .ok_or_else(|| "ordered utf8 plan unavailable".to_owned())?;
16531 let InnerPositionPlan::ContiguousRanges {
16532 left_start,
16533 right_start,
16534 len,
16535 } = plan
16536 else {
16537 return Err("expected contiguous range plan".to_owned());
16538 };
16539
16540 let merged = build_single_key_inner_contiguous_no_overlap_output(
16541 &left,
16542 &right,
16543 &["id"],
16544 &["id"],
16545 PositionSelection::ContiguousRange {
16546 start: left_start,
16547 len,
16548 },
16549 PositionSelection::ContiguousRange {
16550 start: right_start,
16551 len,
16552 },
16553 )
16554 .ok_or_else(|| "no-overlap contiguous output fast path missed".to_owned())?;
16555
16556 assert_eq!(merged.column_order, ["id", "lv", "rv"]);
16557 let id_output = merged
16558 .columns
16559 .get("id")
16560 .ok_or_else(|| "id output missing".to_owned())?;
16561 let (prefix, certificate, certificate_len) = id_output
16562 .as_lower_hex_sequence_utf8()
16563 .ok_or_else(|| "id output lost lower-hex sequence witness".to_owned())?;
16564 assert_eq!(prefix, b"id_");
16565 assert_eq!(certificate.start(), 2);
16566 assert_eq!(certificate.hex_width(), 8);
16567 assert_eq!(certificate_len, 2);
16568 assert_eq!(
16569 id_output.values(),
16570 &[
16571 Scalar::Utf8("id_00000002".to_owned()),
16572 Scalar::Utf8("id_00000003".to_owned())
16573 ]
16574 );
16575 assert_eq!(
16576 merged
16577 .columns
16578 .get("lv")
16579 .ok_or_else(|| "lv output missing".to_owned())?
16580 .values(),
16581 &[Scalar::Int64(12), Scalar::Int64(13)]
16582 );
16583 assert_eq!(
16584 merged
16585 .columns
16586 .get("rv")
16587 .ok_or_else(|| "rv output missing".to_owned())?
16588 .values(),
16589 &[Scalar::Int64(100), Scalar::Int64(101)]
16590 );
16591
16592 let overlapping_right =
16593 utf8_key_merge_frame(&["id_00000002", "id_00000003", "id_00000004"], "lv", 100);
16594 assert!(
16595 build_single_key_inner_contiguous_no_overlap_output(
16596 &left,
16597 &overlapping_right,
16598 &["id"],
16599 &["id"],
16600 PositionSelection::ContiguousRange {
16601 start: left_start,
16602 len,
16603 },
16604 PositionSelection::ContiguousRange {
16605 start: right_start,
16606 len,
16607 },
16608 )
16609 .is_none(),
16610 "overlapping non-key columns must keep the suffix/error generic path"
16611 );
16612 Ok(())
16613 }
16614
16615 #[test]
16616 fn ordered_unique_utf8_uncertified_fixed_width_still_matches_jbyuc111111() {
16617 let left = contiguous_utf8_column(&["k00A", "k00B", "k00C", "k00D"]);
16618 let right = contiguous_utf8_column(&["k00B", "k00D"]);
16619
16620 assert!(left.as_lower_hex_sequence_utf8_contiguous().is_none());
16621 assert!(right.as_lower_hex_sequence_utf8_contiguous().is_none());
16622 let (left_positions, right_positions) =
16623 ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
16624 assert_eq!(left_positions, vec![1, 3]);
16625 assert_eq!(right_positions, vec![0, 1]);
16626 }
16627
16628 #[test]
16629 fn ordered_unique_utf8_fixed_width_gap_falls_back_jbyuc11() {
16630 let left = contiguous_utf8_column(&["k000", "k001", "k003", "k004"]);
16631 let right = contiguous_utf8_column(&["k001", "k002", "k004"]);
16632
16633 let (left_positions, right_positions) =
16634 ordered_unique_utf8_inner_positions(&left, &right).expect("ordered utf8 positions");
16635 assert_eq!(left_positions, vec![1, 3]);
16636 assert_eq!(right_positions, vec![0, 2]);
16637 }
16638
16639 #[test]
16640 fn ordered_unique_utf8_rejects_unsorted_or_duplicate_keys_53lat() {
16641 let unsorted_left = contiguous_utf8_column(&["b", "a", "b"]);
16642 let duplicate_right = contiguous_utf8_column(&["b", "b", "a"]);
16643 assert!(ordered_unique_utf8_inner_positions(&unsorted_left, &duplicate_right).is_none());
16644
16645 let left = utf8_key_merge_frame(&["b", "a", "b"], "lv", 10);
16646 let right = utf8_key_merge_frame(&["b", "b", "a"], "rv", 20);
16647 let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
16648
16649 assert_eq!(
16650 merged.columns.get("lv").unwrap().values(),
16651 &[
16652 Scalar::Int64(10),
16653 Scalar::Int64(10),
16654 Scalar::Int64(11),
16655 Scalar::Int64(12),
16656 Scalar::Int64(12)
16657 ]
16658 );
16659 assert_eq!(
16660 merged.columns.get("rv").unwrap().values(),
16661 &[
16662 Scalar::Int64(20),
16663 Scalar::Int64(21),
16664 Scalar::Int64(22),
16665 Scalar::Int64(20),
16666 Scalar::Int64(21)
16667 ]
16668 );
16669 }
16670
16671 #[test]
16672 fn merge_inner_int64_fast_paths_match_naive_reference_fuzz_jdupk() {
16673 let mut state: u64 = 0x9E37_79B9_7F4A_7C15;
16680 let mut next = || {
16681 state = state
16682 .wrapping_mul(6_364_136_223_846_793_005)
16683 .wrapping_add(1_442_695_040_888_963_407);
16684 state >> 33
16685 };
16686 for _ in 0..400 {
16687 let nl = (next() % 6 + 1) as usize;
16688 let nr = (next() % 6 + 1) as usize;
16689 let lk: Vec<i64> = (0..nl).map(|_| (next() % 5) as i64 - 2).collect();
16691 let rk: Vec<i64> = (0..nr).map(|_| (next() % 5) as i64 - 2).collect();
16692
16693 let left = DataFrame::from_dict(
16694 &["id", "a"],
16695 vec![
16696 ("id", lk.iter().map(|&k| Scalar::Int64(k)).collect()),
16697 (
16698 "a",
16699 (0..nl).map(|i| Scalar::Int64(i as i64 + 1000)).collect(),
16700 ),
16701 ],
16702 )
16703 .unwrap();
16704 let right = DataFrame::from_dict(
16705 &["id", "b"],
16706 vec![
16707 ("id", rk.iter().map(|&k| Scalar::Int64(k)).collect()),
16708 (
16709 "b",
16710 (0..nr).map(|j| Scalar::Int64(j as i64 + 2000)).collect(),
16711 ),
16712 ],
16713 )
16714 .unwrap();
16715
16716 let merged = merge_dataframes(&left, &right, "id", JoinType::Inner).unwrap();
16717
16718 let mut exp_a = Vec::new();
16720 let mut exp_b = Vec::new();
16721 for (i, &left_value) in lk.iter().enumerate() {
16722 for (j, &right_value) in rk.iter().enumerate() {
16723 if left_value == right_value {
16724 exp_a.push(Scalar::Int64(i as i64 + 1000));
16725 exp_b.push(Scalar::Int64(j as i64 + 2000));
16726 }
16727 }
16728 }
16729 assert_eq!(
16730 merged.columns.get("a").unwrap().values(),
16731 exp_a.as_slice(),
16732 "left payload mismatch for lk={lk:?} rk={rk:?}"
16733 );
16734 assert_eq!(
16735 merged.columns.get("b").unwrap().values(),
16736 exp_b.as_slice(),
16737 "right payload mismatch for lk={lk:?} rk={rk:?}"
16738 );
16739
16740 let inner_pairs = exp_a.len();
16743 let left_only = lk.iter().filter(|&key| !rk.contains(key)).count();
16744 let right_only = rk.iter().filter(|&key| !lk.contains(key)).count();
16745 for (how, expected_rows) in [
16746 (JoinType::Left, inner_pairs + left_only),
16747 (JoinType::Right, inner_pairs + right_only),
16748 (JoinType::Outer, inner_pairs + left_only + right_only),
16749 ] {
16750 let m = merge_dataframes(&left, &right, "id", how).unwrap();
16751 assert_eq!(
16752 m.columns.get("id").unwrap().len(),
16753 expected_rows,
16754 "{how:?} cardinality mismatch for lk={lk:?} rk={rk:?}"
16755 );
16756 }
16757 }
16758 }
16759
16760 #[test]
16761 fn merge_null_nan_keys_metamorphic_unmatched_rows_do_not_disturb_inner_tn6qb8()
16762 -> Result<(), JoinError> {
16763 let left = DataFrame::from_dict(
16764 &["id", "left_v"],
16765 vec![
16766 (
16767 "id",
16768 vec![
16769 Scalar::Float64(1.0),
16770 Scalar::Null(NullKind::NaN),
16771 Scalar::Null(NullKind::Null),
16772 Scalar::Float64(2.0),
16773 ],
16774 ),
16775 (
16776 "left_v",
16777 vec![
16778 Scalar::Int64(10),
16779 Scalar::Int64(20),
16780 Scalar::Int64(21),
16781 Scalar::Int64(30),
16782 ],
16783 ),
16784 ],
16785 )?;
16786 let right = DataFrame::from_dict(
16787 &["id", "right_v"],
16788 vec![
16789 (
16790 "id",
16791 vec![
16792 Scalar::Null(NullKind::Null),
16793 Scalar::Float64(2.0),
16794 Scalar::Float64(f64::NAN),
16795 ],
16796 ),
16797 (
16798 "right_v",
16799 vec![Scalar::Int64(200), Scalar::Int64(300), Scalar::Int64(201)],
16800 ),
16801 ],
16802 )?;
16803
16804 let baseline = merge_dataframes(&left, &right, "id", JoinType::Inner)?;
16805
16806 let left_with_unmatched = DataFrame::from_dict(
16807 &["id", "left_v"],
16808 vec![
16809 (
16810 "id",
16811 vec![
16812 Scalar::Float64(1.0),
16813 Scalar::Null(NullKind::NaN),
16814 Scalar::Null(NullKind::Null),
16815 Scalar::Float64(2.0),
16816 Scalar::Float64(99.0),
16817 ],
16818 ),
16819 (
16820 "left_v",
16821 vec![
16822 Scalar::Int64(10),
16823 Scalar::Int64(20),
16824 Scalar::Int64(21),
16825 Scalar::Int64(30),
16826 Scalar::Int64(990),
16827 ],
16828 ),
16829 ],
16830 )?;
16831 let right_with_unmatched = DataFrame::from_dict(
16832 &["id", "right_v"],
16833 vec![
16834 (
16835 "id",
16836 vec![
16837 Scalar::Null(NullKind::Null),
16838 Scalar::Float64(2.0),
16839 Scalar::Float64(f64::NAN),
16840 Scalar::Float64(100.0),
16841 ],
16842 ),
16843 (
16844 "right_v",
16845 vec![
16846 Scalar::Int64(200),
16847 Scalar::Int64(300),
16848 Scalar::Int64(201),
16849 Scalar::Int64(1000),
16850 ],
16851 ),
16852 ],
16853 )?;
16854
16855 let transformed = merge_dataframes(
16856 &left_with_unmatched,
16857 &right_with_unmatched,
16858 "id",
16859 JoinType::Inner,
16860 )?;
16861
16862 assert_eq!(
16863 merged_values(&baseline, "left_v")?,
16864 merged_values(&transformed, "left_v")?
16865 );
16866 assert_eq!(
16867 merged_values(&baseline, "right_v")?,
16868 merged_values(&transformed, "right_v")?
16869 );
16870 assert_eq!(
16871 merged_values(&baseline, "left_v")?,
16872 &[
16873 Scalar::Int64(20),
16874 Scalar::Int64(20),
16875 Scalar::Int64(21),
16876 Scalar::Int64(21),
16877 Scalar::Int64(30),
16878 ]
16879 );
16880 assert_eq!(
16881 merged_values(&baseline, "right_v")?,
16882 &[
16883 Scalar::Int64(200),
16884 Scalar::Int64(201),
16885 Scalar::Int64(200),
16886 Scalar::Int64(201),
16887 Scalar::Int64(300),
16888 ]
16889 );
16890
16891 Ok(())
16892 }
16893
16894 #[test]
16895 fn merge_mixed_dtype_missing_keys_metamorphic_outer_both_equals_inner_tn6qb8()
16896 -> Result<(), JoinError> {
16897 let left = DataFrame::from_dict(
16898 &["id", "left_v"],
16899 vec![
16900 (
16901 "id",
16902 vec![
16903 Scalar::Int64(1),
16904 Scalar::Int64(2),
16905 Scalar::Null(NullKind::NaN),
16906 Scalar::Int64(3),
16907 ],
16908 ),
16909 (
16910 "left_v",
16911 vec![
16912 Scalar::Float64(10.0),
16913 Scalar::Float64(20.0),
16914 Scalar::Float64(30.0),
16915 Scalar::Float64(40.0),
16916 ],
16917 ),
16918 ],
16919 )?;
16920 let right = DataFrame::from_dict(
16921 &["id", "right_v"],
16922 vec![
16923 (
16924 "id",
16925 vec![
16926 Scalar::Float64(1.0),
16927 Scalar::Float64(2.5),
16928 Scalar::Null(NullKind::Null),
16929 Scalar::Float64(3.0),
16930 ],
16931 ),
16932 (
16933 "right_v",
16934 vec![
16935 Scalar::Float64(100.0),
16936 Scalar::Float64(250.0),
16937 Scalar::Float64(300.0),
16938 Scalar::Float64(400.0),
16939 ],
16940 ),
16941 ],
16942 )?;
16943 let options = MergeExecutionOptions {
16944 indicator_name: Some("_merge".to_owned()),
16945 sort: true,
16946 ..MergeExecutionOptions::default()
16947 };
16948
16949 let inner = merge_dataframes_on_with_options(
16950 &left,
16951 &right,
16952 &["id"],
16953 &["id"],
16954 JoinType::Inner,
16955 options.clone(),
16956 )?;
16957 let outer = merge_dataframes_on_with_options(
16958 &left,
16959 &right,
16960 &["id"],
16961 &["id"],
16962 JoinType::Outer,
16963 options,
16964 )?;
16965
16966 assert_eq!(
16967 merged_values(&inner, "left_v")?,
16968 merged_values_where_indicator(&outer, "left_v", "_merge", "both")?
16969 );
16970 assert_eq!(
16971 merged_values(&inner, "right_v")?,
16972 merged_values_where_indicator(&outer, "right_v", "_merge", "both")?
16973 );
16974 assert_eq!(
16975 merged_values(&inner, "left_v")?,
16976 &[
16977 Scalar::Float64(10.0),
16978 Scalar::Float64(40.0),
16979 Scalar::Float64(30.0)
16980 ]
16981 );
16982 assert_eq!(
16983 merged_values(&inner, "right_v")?,
16984 &[
16985 Scalar::Float64(100.0),
16986 Scalar::Float64(400.0),
16987 Scalar::Float64(300.0)
16988 ]
16989 );
16990 assert_eq!(
16991 merged_values(&outer, "_merge")?,
16992 &[
16993 Scalar::Utf8("both".to_owned()),
16994 Scalar::Utf8("left_only".to_owned()),
16995 Scalar::Utf8("right_only".to_owned()),
16996 Scalar::Utf8("both".to_owned()),
16997 Scalar::Utf8("both".to_owned()),
16998 ]
16999 );
17000
17001 Ok(())
17002 }
17003
17004 #[test]
17005 fn merge_cross_cartesian_product() {
17006 let left = make_left_df();
17007 let right = make_right_df();
17008
17009 let merged = merge_dataframes(&left, &right, "unused_key", JoinType::Cross).unwrap();
17010
17011 assert_eq!(merged.columns.get("id_x").unwrap().len(), 9);
17012 assert_eq!(
17013 &merged.columns.get("id_x").unwrap().values()[0..3],
17014 &[Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(1)]
17015 );
17016 assert_eq!(
17017 &merged.columns.get("id_y").unwrap().values()[0..3],
17018 &[Scalar::Int64(2), Scalar::Int64(3), Scalar::Int64(4)]
17019 );
17020 assert_eq!(
17021 &merged.columns.get("val_a").unwrap().values()[0..3],
17022 &[Scalar::Int64(10), Scalar::Int64(10), Scalar::Int64(10)]
17023 );
17024 assert_eq!(
17025 &merged.columns.get("val_b").unwrap().values()[0..3],
17026 &[Scalar::Int64(200), Scalar::Int64(300), Scalar::Int64(400)]
17027 );
17028 }
17029
17030 #[test]
17031 fn merge_cross_does_not_require_on_column() {
17032 let left = make_left_df();
17033 let right = make_right_df();
17034
17035 let merged =
17036 merge_dataframes(&left, &right, "definitely_missing", JoinType::Cross).unwrap();
17037 assert_eq!(merged.columns.get("id_x").unwrap().len(), 9);
17038 }
17039
17040 #[test]
17041 fn merge_cross_with_empty_side_yields_empty_rows() {
17042 let left = DataFrame::from_dict(
17043 &["l"],
17044 vec![("l", vec![Scalar::Int64(1), Scalar::Int64(2)])],
17045 )
17046 .unwrap();
17047 let right = DataFrame::from_dict(&["r"], vec![("r", vec![])]).unwrap();
17048
17049 let merged = merge_dataframes(&left, &right, "ignored", JoinType::Cross).unwrap();
17050 assert_eq!(merged.index.labels().len(), 0);
17051 assert!(merged.columns.get("l").unwrap().values().is_empty());
17052 assert!(merged.columns.get("r").unwrap().values().is_empty());
17053 }
17054
17055 #[test]
17056 fn merge_composite_inner_multiplies_cardinality_for_duplicates() {
17057 let left = DataFrame::from_dict(
17058 &["k1", "k2", "left_v"],
17059 vec![
17060 (
17061 "k1",
17062 vec![Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(1)],
17063 ),
17064 (
17065 "k2",
17066 vec![
17067 Scalar::Utf8("a".to_owned()),
17068 Scalar::Utf8("a".to_owned()),
17069 Scalar::Utf8("b".to_owned()),
17070 ],
17071 ),
17072 (
17073 "left_v",
17074 vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
17075 ),
17076 ],
17077 )
17078 .unwrap();
17079 let right = DataFrame::from_dict(
17080 &["k1", "k2", "right_v"],
17081 vec![
17082 (
17083 "k1",
17084 vec![Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(1)],
17085 ),
17086 (
17087 "k2",
17088 vec![
17089 Scalar::Utf8("a".to_owned()),
17090 Scalar::Utf8("a".to_owned()),
17091 Scalar::Utf8("c".to_owned()),
17092 ],
17093 ),
17094 (
17095 "right_v",
17096 vec![Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(300)],
17097 ),
17098 ],
17099 )
17100 .unwrap();
17101
17102 let merged = merge_dataframes_on(&left, &right, &["k1", "k2"], JoinType::Inner).unwrap();
17103 assert_eq!(merged.columns.get("k1").unwrap().len(), 4);
17104 assert_eq!(
17105 merged.columns.get("k1").unwrap().values(),
17106 &[
17107 Scalar::Int64(1),
17108 Scalar::Int64(1),
17109 Scalar::Int64(1),
17110 Scalar::Int64(1)
17111 ]
17112 );
17113 assert_eq!(
17114 merged.columns.get("k2").unwrap().values(),
17115 &[
17116 Scalar::Utf8("a".to_owned()),
17117 Scalar::Utf8("a".to_owned()),
17118 Scalar::Utf8("a".to_owned()),
17119 Scalar::Utf8("a".to_owned())
17120 ]
17121 );
17122 assert_eq!(
17123 merged.columns.get("left_v").unwrap().values(),
17124 &[
17125 Scalar::Int64(10),
17126 Scalar::Int64(10),
17127 Scalar::Int64(20),
17128 Scalar::Int64(20)
17129 ]
17130 );
17131 assert_eq!(
17132 merged.columns.get("right_v").unwrap().values(),
17133 &[
17134 Scalar::Int64(100),
17135 Scalar::Int64(200),
17136 Scalar::Int64(100),
17137 Scalar::Int64(200)
17138 ]
17139 );
17140 }
17141
17142 #[test]
17143 fn merge_composite_outer_sorts_join_keys_lexicographically() {
17144 let left = DataFrame::from_dict(
17145 &["k1", "k2", "left_v"],
17146 vec![
17147 ("k1", vec![Scalar::Int64(2), Scalar::Int64(1)]),
17148 (
17149 "k2",
17150 vec![Scalar::Utf8("y".to_owned()), Scalar::Utf8("x".to_owned())],
17151 ),
17152 ("left_v", vec![Scalar::Int64(20), Scalar::Int64(10)]),
17153 ],
17154 )
17155 .unwrap();
17156 let right = DataFrame::from_dict(
17157 &["k1", "k2", "right_v"],
17158 vec![
17159 ("k1", vec![Scalar::Int64(2), Scalar::Int64(3)]),
17160 (
17161 "k2",
17162 vec![Scalar::Utf8("y".to_owned()), Scalar::Utf8("z".to_owned())],
17163 ),
17164 ("right_v", vec![Scalar::Int64(200), Scalar::Int64(300)]),
17165 ],
17166 )
17167 .unwrap();
17168
17169 let merged = merge_dataframes_on(&left, &right, &["k1", "k2"], JoinType::Outer).unwrap();
17170 assert_eq!(
17171 merged.columns.get("k1").unwrap().values(),
17172 &[Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)]
17173 );
17174 assert_eq!(
17175 merged.columns.get("k2").unwrap().values(),
17176 &[
17177 Scalar::Utf8("x".to_owned()),
17178 Scalar::Utf8("y".to_owned()),
17179 Scalar::Utf8("z".to_owned())
17180 ]
17181 );
17182 assert_eq!(
17183 merged.columns.get("left_v").unwrap().values(),
17184 &[
17185 Scalar::Float64(10.0),
17186 Scalar::Float64(20.0),
17187 Scalar::Null(NullKind::NaN)
17188 ]
17189 );
17190 assert_eq!(
17191 merged.columns.get("right_v").unwrap().values(),
17192 &[
17193 Scalar::Null(NullKind::NaN),
17194 Scalar::Float64(200.0),
17195 Scalar::Float64(300.0)
17196 ]
17197 );
17198 }
17199
17200 #[test]
17201 fn merge_composite_outer_contiguous_utf8_key_coalesce_matches_scalar_route_blackthrush() {
17202 let contiguous_frame =
17203 |k1: &[&str], k2: &[&str], value_name: &str, values: &[i64]| -> DataFrame {
17204 let index = Index::new(
17205 (0..k1.len())
17206 .map(|row| IndexLabel::Int64(row as i64))
17207 .collect(),
17208 );
17209 let mut columns = std::collections::BTreeMap::new();
17210 columns.insert("k1".to_owned(), contiguous_utf8_column(k1));
17211 columns.insert("k2".to_owned(), contiguous_utf8_column(k2));
17212 columns.insert(
17213 value_name.to_owned(),
17214 Column::from_i64_values(values.to_vec()),
17215 );
17216 DataFrame::new_with_column_order(
17217 index,
17218 columns,
17219 vec!["k1".to_owned(), "k2".to_owned(), value_name.to_owned()],
17220 )
17221 .expect("contiguous frame")
17222 };
17223 let scalar_frame =
17224 |k1: &[&str], k2: &[&str], value_name: &str, values: &[i64]| -> DataFrame {
17225 DataFrame::from_dict(
17226 &["k1", "k2", value_name],
17227 vec![
17228 (
17229 "k1",
17230 k1.iter()
17231 .map(|value| Scalar::Utf8((*value).to_owned()))
17232 .collect(),
17233 ),
17234 (
17235 "k2",
17236 k2.iter()
17237 .map(|value| Scalar::Utf8((*value).to_owned()))
17238 .collect(),
17239 ),
17240 (
17241 value_name,
17242 values.iter().copied().map(Scalar::Int64).collect(),
17243 ),
17244 ],
17245 )
17246 .expect("scalar frame")
17247 };
17248
17249 let left_fast =
17250 contiguous_frame(&["b", "a", "c"], &["y", "x", "z"], "left_v", &[20, 10, 30]);
17251 let right_fast = contiguous_frame(&["b", "d"], &["y", "w"], "right_v", &[200, 400]);
17252 let left_scalar = scalar_frame(&["b", "a", "c"], &["y", "x", "z"], "left_v", &[20, 10, 30]);
17253 let right_scalar = scalar_frame(&["b", "d"], &["y", "w"], "right_v", &[200, 400]);
17254
17255 let fast =
17256 merge_dataframes_on(&left_fast, &right_fast, &["k1", "k2"], JoinType::Outer).unwrap();
17257 let scalar =
17258 merge_dataframes_on(&left_scalar, &right_scalar, &["k1", "k2"], JoinType::Outer)
17259 .unwrap();
17260
17261 for name in ["k1", "k2", "left_v", "right_v"] {
17262 assert_eq!(
17263 fast.columns.get(name).unwrap().values(),
17264 scalar.columns.get(name).unwrap().values(),
17265 "column {name}"
17266 );
17267 }
17268 assert!(
17269 fast.columns
17270 .get("k1")
17271 .unwrap()
17272 .as_utf8_contiguous()
17273 .is_some()
17274 );
17275 assert!(
17276 fast.columns
17277 .get("k2")
17278 .unwrap()
17279 .as_utf8_contiguous()
17280 .is_some()
17281 );
17282 }
17283
17284 #[test]
17285 fn merge_composite_inner_matches_missing_key_components() {
17286 let left = DataFrame::from_dict(
17287 &["k1", "k2", "left_v"],
17288 vec![
17289 ("k1", vec![Scalar::Int64(1), Scalar::Int64(1)]),
17290 (
17291 "k2",
17292 vec![Scalar::Null(NullKind::Null), Scalar::Utf8("a".to_owned())],
17293 ),
17294 ("left_v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
17295 ],
17296 )
17297 .unwrap();
17298 let right = DataFrame::from_dict(
17299 &["k1", "k2", "right_v"],
17300 vec![
17301 (
17302 "k1",
17303 vec![Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(2)],
17304 ),
17305 (
17306 "k2",
17307 vec![
17308 Scalar::Null(NullKind::Null),
17309 Scalar::Utf8("a".to_owned()),
17310 Scalar::Null(NullKind::Null),
17311 ],
17312 ),
17313 (
17314 "right_v",
17315 vec![Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(300)],
17316 ),
17317 ],
17318 )
17319 .unwrap();
17320
17321 let merged = merge_dataframes_on(&left, &right, &["k1", "k2"], JoinType::Inner).unwrap();
17322 assert_eq!(
17323 merged.columns.get("k1").unwrap().values(),
17324 &[Scalar::Int64(1), Scalar::Int64(1)]
17325 );
17326 assert_eq!(
17327 merged.columns.get("k2").unwrap().values(),
17328 &[Scalar::Null(NullKind::Null), Scalar::Utf8("a".to_owned())]
17329 );
17330 assert_eq!(
17331 merged.columns.get("left_v").unwrap().values(),
17332 &[Scalar::Int64(10), Scalar::Int64(20)]
17333 );
17334 assert_eq!(
17335 merged.columns.get("right_v").unwrap().values(),
17336 &[Scalar::Int64(100), Scalar::Int64(200)]
17337 );
17338 }
17339
17340 #[test]
17341 fn merge_composite_outer_keeps_right_only_rows_with_missing_keys() {
17342 let left = DataFrame::from_dict(
17343 &["k1", "k2", "left_v"],
17344 vec![
17345 ("k1", vec![Scalar::Int64(1)]),
17346 ("k2", vec![Scalar::Null(NullKind::Null)]),
17347 ("left_v", vec![Scalar::Int64(10)]),
17348 ],
17349 )
17350 .unwrap();
17351 let right = DataFrame::from_dict(
17352 &["k1", "k2", "right_v"],
17353 vec![
17354 ("k1", vec![Scalar::Int64(1), Scalar::Int64(2)]),
17355 (
17356 "k2",
17357 vec![Scalar::Null(NullKind::Null), Scalar::Null(NullKind::Null)],
17358 ),
17359 ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
17360 ],
17361 )
17362 .unwrap();
17363
17364 let merged = merge_dataframes_on(&left, &right, &["k1", "k2"], JoinType::Outer).unwrap();
17365 assert_eq!(
17366 merged.columns.get("k1").unwrap().values(),
17367 &[Scalar::Int64(1), Scalar::Int64(2)]
17368 );
17369 assert_eq!(
17370 merged.columns.get("k2").unwrap().values(),
17371 &[Scalar::Null(NullKind::Null), Scalar::Null(NullKind::Null)]
17372 );
17373 assert_eq!(
17374 merged.columns.get("left_v").unwrap().values(),
17375 &[Scalar::Float64(10.0), Scalar::Null(NullKind::NaN)]
17376 );
17377 assert_eq!(
17378 merged.columns.get("right_v").unwrap().values(),
17379 &[Scalar::Int64(100), Scalar::Int64(200)]
17380 );
17381 }
17382
17383 #[test]
17384 fn merge_composite_missing_key_column_errors() {
17385 let left = DataFrame::from_dict(
17386 &["k1", "k2", "left_v"],
17387 vec![
17388 ("k1", vec![Scalar::Int64(1)]),
17389 ("k2", vec![Scalar::Utf8("x".to_owned())]),
17390 ("left_v", vec![Scalar::Int64(10)]),
17391 ],
17392 )
17393 .unwrap();
17394 let right = DataFrame::from_dict(
17395 &["k1", "right_v"],
17396 vec![
17397 ("k1", vec![Scalar::Int64(1)]),
17398 ("right_v", vec![Scalar::Int64(100)]),
17399 ],
17400 )
17401 .unwrap();
17402
17403 let err = merge_dataframes_on(&left, &right, &["k1", "k2"], JoinType::Inner)
17404 .expect_err("should fail");
17405 assert!(format!("{err}").contains("right DataFrame missing key column 'k2'"));
17406 }
17407
17408 #[test]
17409 fn merge_composite_key_alias_inner_keeps_both_key_sets() {
17410 let left = DataFrame::from_dict(
17411 &["lk1", "lk2", "left_v"],
17412 vec![
17413 (
17414 "lk1",
17415 vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
17416 ),
17417 (
17418 "lk2",
17419 vec![
17420 Scalar::Utf8("a".to_owned()),
17421 Scalar::Utf8("b".to_owned()),
17422 Scalar::Utf8("c".to_owned()),
17423 ],
17424 ),
17425 (
17426 "left_v",
17427 vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
17428 ),
17429 ],
17430 )
17431 .unwrap();
17432 let right = DataFrame::from_dict(
17433 &["rk1", "rk2", "right_v"],
17434 vec![
17435 (
17436 "rk1",
17437 vec![Scalar::Int64(2), Scalar::Int64(3), Scalar::Int64(4)],
17438 ),
17439 (
17440 "rk2",
17441 vec![
17442 Scalar::Utf8("b".to_owned()),
17443 Scalar::Utf8("c".to_owned()),
17444 Scalar::Utf8("d".to_owned()),
17445 ],
17446 ),
17447 (
17448 "right_v",
17449 vec![Scalar::Int64(200), Scalar::Int64(300), Scalar::Int64(400)],
17450 ),
17451 ],
17452 )
17453 .unwrap();
17454
17455 let merged = merge_dataframes_on_with(
17456 &left,
17457 &right,
17458 &["lk1", "lk2"],
17459 &["rk1", "rk2"],
17460 JoinType::Inner,
17461 )
17462 .unwrap();
17463 assert_eq!(
17464 merged.columns.get("lk1").unwrap().values(),
17465 &[Scalar::Int64(2), Scalar::Int64(3)]
17466 );
17467 assert_eq!(
17468 merged.columns.get("lk2").unwrap().values(),
17469 &[Scalar::Utf8("b".to_owned()), Scalar::Utf8("c".to_owned())]
17470 );
17471 assert_eq!(
17472 merged.columns.get("left_v").unwrap().values(),
17473 &[Scalar::Int64(20), Scalar::Int64(30)]
17474 );
17475 assert_eq!(
17476 merged.columns.get("rk1").unwrap().values(),
17477 &[Scalar::Int64(2), Scalar::Int64(3)]
17478 );
17479 assert_eq!(
17480 merged.columns.get("rk2").unwrap().values(),
17481 &[Scalar::Utf8("b".to_owned()), Scalar::Utf8("c".to_owned())]
17482 );
17483 assert_eq!(
17484 merged.columns.get("right_v").unwrap().values(),
17485 &[Scalar::Int64(200), Scalar::Int64(300)]
17486 );
17487 }
17488
17489 #[test]
17490 fn merge_composite_key_alias_outer_propagates_missing_per_side() {
17491 let left = DataFrame::from_dict(
17492 &["lk1", "lk2", "left_v"],
17493 vec![
17494 (
17495 "lk1",
17496 vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
17497 ),
17498 (
17499 "lk2",
17500 vec![
17501 Scalar::Utf8("a".to_owned()),
17502 Scalar::Null(NullKind::Null),
17503 Scalar::Utf8("c".to_owned()),
17504 ],
17505 ),
17506 (
17507 "left_v",
17508 vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
17509 ),
17510 ],
17511 )
17512 .unwrap();
17513 let right = DataFrame::from_dict(
17514 &["rk1", "rk2", "right_v"],
17515 vec![
17516 (
17517 "rk1",
17518 vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(4)],
17519 ),
17520 (
17521 "rk2",
17522 vec![
17523 Scalar::Utf8("a".to_owned()),
17524 Scalar::Null(NullKind::Null),
17525 Scalar::Utf8("d".to_owned()),
17526 ],
17527 ),
17528 (
17529 "right_v",
17530 vec![Scalar::Int64(100), Scalar::Int64(200), Scalar::Int64(400)],
17531 ),
17532 ],
17533 )
17534 .unwrap();
17535
17536 let merged = merge_dataframes_on_with(
17537 &left,
17538 &right,
17539 &["lk1", "lk2"],
17540 &["rk1", "rk2"],
17541 JoinType::Outer,
17542 )
17543 .unwrap();
17544
17545 assert_eq!(
17546 merged.columns.get("lk1").unwrap().values(),
17547 &[
17548 Scalar::Float64(1.0),
17549 Scalar::Float64(2.0),
17550 Scalar::Float64(3.0),
17551 Scalar::Null(NullKind::NaN)
17552 ]
17553 );
17554 assert_eq!(
17555 merged.columns.get("rk1").unwrap().values(),
17556 &[
17557 Scalar::Float64(1.0),
17558 Scalar::Float64(2.0),
17559 Scalar::Null(NullKind::NaN),
17560 Scalar::Float64(4.0)
17561 ]
17562 );
17563 assert_eq!(
17564 merged.columns.get("left_v").unwrap().values(),
17565 &[
17566 Scalar::Float64(10.0),
17567 Scalar::Float64(20.0),
17568 Scalar::Float64(30.0),
17569 Scalar::Null(NullKind::NaN)
17570 ]
17571 );
17572 assert_eq!(
17573 merged.columns.get("right_v").unwrap().values(),
17574 &[
17575 Scalar::Float64(100.0),
17576 Scalar::Float64(200.0),
17577 Scalar::Null(NullKind::NaN),
17578 Scalar::Float64(400.0)
17579 ]
17580 );
17581 }
17582
17583 #[test]
17584 fn merge_key_alias_lists_must_have_equal_lengths() {
17585 let left = make_left_df();
17586 let right = make_right_df();
17587 let err = merge_dataframes_on_with(&left, &right, &["id", "id"], &["id"], JoinType::Inner)
17588 .expect_err("should fail");
17589 assert!(format!("{err}").contains("equal length"));
17590 }
17591
17592 #[test]
17593 fn merge_indicator_default_name_tracks_row_provenance() {
17594 let left = make_left_df();
17595 let right = make_right_df();
17596
17597 let merged = merge_dataframes_on_with_options(
17598 &left,
17599 &right,
17600 &["id"],
17601 &["id"],
17602 JoinType::Outer,
17603 MergeExecutionOptions {
17604 indicator_name: Some("_merge".to_owned()),
17605 ..MergeExecutionOptions::default()
17606 },
17607 )
17608 .expect("merge");
17609
17610 assert_eq!(
17611 merged.columns.get("_merge").expect("indicator").values(),
17612 &[
17613 Scalar::Utf8("left_only".to_owned()),
17614 Scalar::Utf8("both".to_owned()),
17615 Scalar::Utf8("both".to_owned()),
17616 Scalar::Utf8("right_only".to_owned())
17617 ]
17618 );
17619 }
17620
17621 #[test]
17622 fn merge_indicator_custom_name_preserves_suffix_behavior() {
17623 let left = DataFrame::from_dict(
17624 &["id", "val"],
17625 vec![
17626 ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
17627 ("val", vec![Scalar::Int64(10), Scalar::Int64(20)]),
17628 ],
17629 )
17630 .unwrap();
17631 let right = DataFrame::from_dict(
17632 &["id", "val"],
17633 vec![
17634 ("id", vec![Scalar::Int64(2), Scalar::Int64(3)]),
17635 ("val", vec![Scalar::Int64(200), Scalar::Int64(300)]),
17636 ],
17637 )
17638 .unwrap();
17639
17640 let merged = merge_dataframes_on_with_options(
17641 &left,
17642 &right,
17643 &["id"],
17644 &["id"],
17645 JoinType::Outer,
17646 MergeExecutionOptions {
17647 indicator_name: Some("origin".to_owned()),
17648 ..MergeExecutionOptions::default()
17649 },
17650 )
17651 .expect("merge");
17652
17653 assert!(merged.columns.contains_key("val_x"));
17654 assert!(merged.columns.contains_key("val_y"));
17655 assert_eq!(
17656 merged.columns.get("origin").expect("indicator").values(),
17657 &[
17658 Scalar::Utf8("left_only".to_owned()),
17659 Scalar::Utf8("both".to_owned()),
17660 Scalar::Utf8("right_only".to_owned())
17661 ]
17662 );
17663 }
17664
17665 #[test]
17666 fn merge_indicator_rejects_conflicting_column_name() {
17667 let left = make_left_df();
17668 let right = make_right_df();
17669
17670 let err = merge_dataframes_on_with_options(
17671 &left,
17672 &right,
17673 &["id"],
17674 &["id"],
17675 JoinType::Inner,
17676 MergeExecutionOptions {
17677 indicator_name: Some("id".to_owned()),
17678 ..MergeExecutionOptions::default()
17679 },
17680 )
17681 .expect_err("expected indicator name conflict");
17682 assert!(format!("{err}").contains("conflicts with an existing column"));
17683 }
17684
17685 #[test]
17686 fn merge_cross_indicator_marks_all_rows_both() {
17687 let left = DataFrame::from_dict(
17693 &["l"],
17694 vec![("l", vec![Scalar::Int64(1), Scalar::Int64(2)])],
17695 )
17696 .unwrap();
17697 let right = DataFrame::from_dict(&["r"], vec![("r", vec![Scalar::Int64(9)])]).unwrap();
17698
17699 let merged = merge_dataframes_on_with_options(
17700 &left,
17701 &right,
17702 &["ignored"],
17703 &["ignored"],
17704 JoinType::Cross,
17705 MergeExecutionOptions {
17706 indicator_name: Some("_merge".to_owned()),
17707 ..MergeExecutionOptions::default()
17708 },
17709 )
17710 .expect("cross merge");
17711 assert_eq!(
17712 merged.columns.get("_merge").expect("indicator").values(),
17713 &[
17714 Scalar::Utf8("both".to_owned()),
17715 Scalar::Utf8("both".to_owned())
17716 ]
17717 );
17718 }
17719
17720 #[test]
17721 fn merge_cross_validate_mode_contract_ohb5f() {
17722 let left = DataFrame::from_dict(
17723 &["l"],
17724 vec![("l", vec![Scalar::Int64(1), Scalar::Int64(2)])],
17725 )
17726 .expect("left");
17727 let right = DataFrame::from_dict(
17728 &["r"],
17729 vec![("r", vec![Scalar::Int64(10), Scalar::Int64(20)])],
17730 )
17731 .expect("right");
17732
17733 let many_to_many = merge_dataframes_on_with_options(
17734 &left,
17735 &right,
17736 &["missing_left_key"],
17737 &["missing_right_key"],
17738 JoinType::Cross,
17739 MergeExecutionOptions {
17740 validate_mode: Some(MergeValidateMode::ManyToMany),
17741 ..MergeExecutionOptions::default()
17742 },
17743 )
17744 .expect("cross merge validate=many_to_many");
17745 assert_eq!(many_to_many.index.len(), 4);
17746
17747 for validate_mode in [
17748 MergeValidateMode::OneToOne,
17749 MergeValidateMode::OneToMany,
17750 MergeValidateMode::ManyToOne,
17751 ] {
17752 let err = merge_dataframes_on_with_options(
17753 &left,
17754 &right,
17755 &["missing_left_key"],
17756 &["missing_right_key"],
17757 JoinType::Cross,
17758 MergeExecutionOptions {
17759 validate_mode: Some(validate_mode),
17760 ..MergeExecutionOptions::default()
17761 },
17762 )
17763 .expect_err("enforcing validate modes are not meaningful for cross joins");
17764 let message = format!("{err}");
17765 assert!(message.contains(validate_mode.as_str()));
17766 assert!(message.contains("not supported for cross join"));
17767 }
17768 }
17769
17770 #[test]
17771 fn merge_validate_one_to_one_rejects_duplicate_left_keys() {
17772 let left = DataFrame::from_dict(
17773 &["id", "left_v"],
17774 vec![
17775 ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
17776 ("left_v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
17777 ],
17778 )
17779 .expect("left frame");
17780 let right = DataFrame::from_dict(
17781 &["id", "right_v"],
17782 vec![
17783 ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
17784 ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
17785 ],
17786 )
17787 .expect("right frame");
17788
17789 let err = merge_dataframes_on_with_options(
17790 &left,
17791 &right,
17792 &["id"],
17793 &["id"],
17794 JoinType::Inner,
17795 MergeExecutionOptions {
17796 validate_mode: Some(MergeValidateMode::OneToOne),
17797 ..MergeExecutionOptions::default()
17798 },
17799 )
17800 .expect_err("one_to_one must reject duplicate left keys");
17801 assert!(format!("{err}").contains("left keys are not unique"));
17802 }
17803
17804 #[test]
17805 fn merge_validate_one_to_many_allows_duplicate_right_keys() {
17806 let left = DataFrame::from_dict(
17807 &["id", "left_v"],
17808 vec![
17809 ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
17810 ("left_v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
17811 ],
17812 )
17813 .expect("left frame");
17814 let right = DataFrame::from_dict(
17815 &["id", "right_v"],
17816 vec![
17817 (
17818 "id",
17819 vec![Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(2)],
17820 ),
17821 (
17822 "right_v",
17823 vec![Scalar::Int64(100), Scalar::Int64(101), Scalar::Int64(200)],
17824 ),
17825 ],
17826 )
17827 .expect("right frame");
17828
17829 let merged = merge_dataframes_on_with_options(
17830 &left,
17831 &right,
17832 &["id"],
17833 &["id"],
17834 JoinType::Inner,
17835 MergeExecutionOptions {
17836 validate_mode: Some(MergeValidateMode::OneToMany),
17837 ..MergeExecutionOptions::default()
17838 },
17839 )
17840 .expect("one_to_many should allow duplicate right keys");
17841 assert_eq!(merged.columns.get("id").expect("id").values().len(), 3);
17842 }
17843
17844 #[test]
17845 fn merge_validate_one_to_many_rejects_duplicate_left_keys_9hsb3() {
17846 let left = DataFrame::from_dict(
17847 &["id", "left_v"],
17848 vec![
17849 ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
17850 ("left_v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
17851 ],
17852 )
17853 .expect("left frame");
17854 let right = DataFrame::from_dict(
17855 &["id", "right_v"],
17856 vec![
17857 ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
17858 ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
17859 ],
17860 )
17861 .expect("right frame");
17862
17863 let err = merge_dataframes_on_with_options(
17864 &left,
17865 &right,
17866 &["id"],
17867 &["id"],
17868 JoinType::Inner,
17869 MergeExecutionOptions {
17870 validate_mode: Some(MergeValidateMode::OneToMany),
17871 ..MergeExecutionOptions::default()
17872 },
17873 )
17874 .expect_err("one_to_many must reject duplicate left keys");
17875 assert!(format!("{err}").contains("left keys are not unique"));
17876 }
17877
17878 #[test]
17879 fn merge_validate_many_to_one_rejects_duplicate_right_keys() {
17880 let left = DataFrame::from_dict(
17881 &["id", "left_v"],
17882 vec![
17883 ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
17884 ("left_v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
17885 ],
17886 )
17887 .expect("left frame");
17888 let right = DataFrame::from_dict(
17889 &["id", "right_v"],
17890 vec![
17891 ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
17892 ("right_v", vec![Scalar::Int64(100), Scalar::Int64(101)]),
17893 ],
17894 )
17895 .expect("right frame");
17896
17897 let err = merge_dataframes_on_with_options(
17898 &left,
17899 &right,
17900 &["id"],
17901 &["id"],
17902 JoinType::Inner,
17903 MergeExecutionOptions {
17904 validate_mode: Some(MergeValidateMode::ManyToOne),
17905 ..MergeExecutionOptions::default()
17906 },
17907 )
17908 .expect_err("many_to_one must reject duplicate right keys");
17909 assert!(format!("{err}").contains("right keys are not unique"));
17910 }
17911
17912 #[test]
17913 fn merge_validate_many_to_one_allows_duplicate_left_keys_9hsb3() {
17914 let left = DataFrame::from_dict(
17915 &["id", "left_v"],
17916 vec![
17917 (
17918 "id",
17919 vec![Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(2)],
17920 ),
17921 (
17922 "left_v",
17923 vec![Scalar::Int64(10), Scalar::Int64(11), Scalar::Int64(20)],
17924 ),
17925 ],
17926 )
17927 .expect("left frame");
17928 let right = DataFrame::from_dict(
17929 &["id", "right_v"],
17930 vec![
17931 ("id", vec![Scalar::Int64(1), Scalar::Int64(2)]),
17932 ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
17933 ],
17934 )
17935 .expect("right frame");
17936
17937 let merged = merge_dataframes_on_with_options(
17938 &left,
17939 &right,
17940 &["id"],
17941 &["id"],
17942 JoinType::Inner,
17943 MergeExecutionOptions {
17944 validate_mode: Some(MergeValidateMode::ManyToOne),
17945 ..MergeExecutionOptions::default()
17946 },
17947 )
17948 .expect("many_to_one should allow duplicate left keys");
17949 assert_eq!(merged.columns.get("id").expect("id").values().len(), 3);
17950 }
17951
17952 #[test]
17953 fn merge_validate_many_to_many_allows_duplicates_on_both_sides() {
17954 let left = DataFrame::from_dict(
17955 &["id", "left_v"],
17956 vec![
17957 ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
17958 ("left_v", vec![Scalar::Int64(10), Scalar::Int64(20)]),
17959 ],
17960 )
17961 .expect("left frame");
17962 let right = DataFrame::from_dict(
17963 &["id", "right_v"],
17964 vec![
17965 ("id", vec![Scalar::Int64(1), Scalar::Int64(1)]),
17966 ("right_v", vec![Scalar::Int64(100), Scalar::Int64(200)]),
17967 ],
17968 )
17969 .expect("right frame");
17970
17971 let merged = merge_dataframes_on_with_options(
17972 &left,
17973 &right,
17974 &["id"],
17975 &["id"],
17976 JoinType::Inner,
17977 MergeExecutionOptions {
17978 validate_mode: Some(MergeValidateMode::ManyToMany),
17979 ..MergeExecutionOptions::default()
17980 },
17981 )
17982 .expect("many_to_many should allow duplicate keys on both sides");
17983 assert_eq!(merged.columns.get("id").expect("id").values().len(), 4);
17984 }
17985
17986 #[test]
17987 fn join_series_cross_cartesian_product() {
17988 let left = Series::from_values(
17989 "left",
17990 vec!["a".into(), "b".into()],
17991 vec![Scalar::Int64(1), Scalar::Int64(2)],
17992 )
17993 .unwrap();
17994 let right = Series::from_values(
17995 "right",
17996 vec!["x".into(), "y".into()],
17997 vec![Scalar::Int64(10), Scalar::Int64(20)],
17998 )
17999 .unwrap();
18000
18001 let out = join_series(&left, &right, JoinType::Cross).unwrap();
18002 assert_eq!(out.index.labels().len(), 4);
18003 assert_eq!(
18004 out.left_values.values(),
18005 &[
18006 Scalar::Int64(1),
18007 Scalar::Int64(1),
18008 Scalar::Int64(2),
18009 Scalar::Int64(2)
18010 ]
18011 );
18012 assert_eq!(
18013 out.right_values.values(),
18014 &[
18015 Scalar::Int64(10),
18016 Scalar::Int64(20),
18017 Scalar::Int64(10),
18018 Scalar::Int64(20)
18019 ]
18020 );
18021 }
18022
18023 #[test]
18026 fn dataframe_merge_via_trait() {
18027 use fp_frame::DataFrame;
18028
18029 use super::{DataFrameMergeExt, merge_dataframes_on};
18030
18031 let left = DataFrame::from_series(vec![
18032 Series::from_values(
18033 "key",
18034 vec![0_i64.into(), 1_i64.into()],
18035 vec![Scalar::Int64(1), Scalar::Int64(2)],
18036 )
18037 .unwrap(),
18038 Series::from_values(
18039 "val_l",
18040 vec![0_i64.into(), 1_i64.into()],
18041 vec![Scalar::Int64(10), Scalar::Int64(20)],
18042 )
18043 .unwrap(),
18044 ])
18045 .unwrap();
18046
18047 let right = DataFrame::from_series(vec![
18048 Series::from_values(
18049 "key",
18050 vec![0_i64.into(), 1_i64.into()],
18051 vec![Scalar::Int64(1), Scalar::Int64(3)],
18052 )
18053 .unwrap(),
18054 Series::from_values(
18055 "val_r",
18056 vec![0_i64.into(), 1_i64.into()],
18057 vec![Scalar::Int64(100), Scalar::Int64(300)],
18058 )
18059 .unwrap(),
18060 ])
18061 .unwrap();
18062
18063 let result = left.merge(&right, &["key"], JoinType::Inner).unwrap();
18065 assert_eq!(result.index.len(), 1); let result2 = merge_dataframes_on(&left, &right, &["key"], JoinType::Inner).unwrap();
18069 assert_eq!(result.index.len(), result2.index.len());
18070 }
18071
18072 fn compute_asof_matches_datetime64_former_nsslz(
18075 left: super::Datetime64AsofKey<'_>,
18076 right: super::Datetime64AsofKey<'_>,
18077 direction: super::AsofDirection,
18078 allow_exact_matches: bool,
18079 tolerance: Option<f64>,
18080 ) -> Vec<Option<usize>> {
18081 let mut right_valid_values = Vec::new();
18082 let mut right_valid_positions = Vec::new();
18083 for i in 0..right.data.len() {
18084 if right.is_valid(i) {
18085 right_valid_values.push(right.data[i]);
18086 right_valid_positions.push(i);
18087 }
18088 }
18089 super::compute_asof_matches_datetime64_prepared(
18090 left,
18091 &right_valid_values,
18092 Some(&right_valid_positions),
18093 direction,
18094 allow_exact_matches,
18095 tolerance,
18096 )
18097 }
18098
18099 #[test]
18100 fn merge_asof_datetime64_borrowed_dense_right_matches_former_nsslz() {
18101 let dense_left = Column::from_datetime64_values_with_validity(
18102 vec![-15, -10, -5, 0, 5, 30, 35],
18103 ValidityMask::all_valid(7),
18104 );
18105 let dense_right = Column::from_datetime64_values_with_validity(
18106 vec![-10, 0, 10, 20, 30],
18107 ValidityMask::all_valid(5),
18108 );
18109
18110 let nat_right = Column::from_datetime64_values_with_validity(
18111 vec![fp_types::Timestamp::NAT, -10, 0, 20, 30],
18112 ValidityMask::all_valid(5),
18113 );
18114 let nat_left = Column::from_datetime64_values_with_validity(
18115 vec![fp_types::Timestamp::NAT, -10, -5, 0, 5, 30, 35],
18116 ValidityMask::all_valid(7),
18117 );
18118
18119 for (left, right) in [
18120 (&dense_left, &dense_right),
18121 (&dense_left, &nat_right),
18122 (&nat_left, &dense_right),
18123 ] {
18124 let left_key = super::datetime64_key_parts(left).expect("Datetime64 left key");
18125 let right_key = super::datetime64_key_parts(right).expect("Datetime64 right key");
18126 for direction in [
18127 super::AsofDirection::Backward,
18128 super::AsofDirection::Forward,
18129 super::AsofDirection::Nearest,
18130 ] {
18131 for allow_exact_matches in [false, true] {
18132 for tolerance in [None, Some(7.0)] {
18133 assert_eq!(
18134 super::compute_asof_matches_datetime64(
18135 left_key,
18136 right_key,
18137 direction,
18138 allow_exact_matches,
18139 tolerance,
18140 ),
18141 compute_asof_matches_datetime64_former_nsslz(
18142 left_key,
18143 right_key,
18144 direction,
18145 allow_exact_matches,
18146 tolerance,
18147 ),
18148 "direction={direction:?} exact={allow_exact_matches} tolerance={tolerance:?}",
18149 );
18150 }
18151 }
18152 }
18153 }
18154 }
18155
18156 #[test]
18157 #[ignore = "foreground release A/B only"]
18158 fn datetime64_asof_borrowed_dense_right_ab_nsslz() {
18159 use std::{hint::black_box, time::Instant};
18160
18161 const ITEMS: usize = 131_072;
18162 const SAMPLES: usize = 10;
18163
18164 fn elapsed(run: impl FnOnce() -> Vec<Option<usize>>) -> u128 {
18165 let started = Instant::now();
18166 let output = black_box(run());
18167 black_box(output.len());
18168 let elapsed = started.elapsed().as_nanos();
18169 drop(output);
18170 elapsed
18171 }
18172
18173 let left = Column::from_datetime64_values_with_validity(
18174 (0..ITEMS).map(|i| i as i64 * 4 + 1).collect(),
18175 ValidityMask::all_valid(ITEMS),
18176 );
18177 let right = Column::from_datetime64_values_with_validity(
18178 (0..ITEMS).map(|i| i as i64 * 4).collect(),
18179 ValidityMask::all_valid(ITEMS),
18180 );
18181 let left_key = super::datetime64_key_parts(&left).expect("Datetime64 left key");
18182 let right_key = super::datetime64_key_parts(&right).expect("Datetime64 right key");
18183 let former = || {
18184 compute_asof_matches_datetime64_former_nsslz(
18185 left_key,
18186 right_key,
18187 super::AsofDirection::Backward,
18188 true,
18189 None,
18190 )
18191 };
18192 let candidate = || {
18193 super::compute_asof_matches_datetime64(
18194 left_key,
18195 right_key,
18196 super::AsofDirection::Backward,
18197 true,
18198 None,
18199 )
18200 };
18201
18202 assert_eq!(candidate(), former());
18203 black_box(former());
18204 black_box(candidate());
18205
18206 let mut former_ns = Vec::with_capacity(SAMPLES);
18207 let mut candidate_ns = Vec::with_capacity(SAMPLES);
18208 for sample in 0..SAMPLES {
18209 if sample.is_multiple_of(2) {
18210 former_ns.push(elapsed(former));
18211 candidate_ns.push(elapsed(candidate));
18212 } else {
18213 candidate_ns.push(elapsed(candidate));
18214 former_ns.push(elapsed(former));
18215 }
18216 }
18217 former_ns.sort_unstable();
18218 candidate_ns.sort_unstable();
18219 let former_p50 = former_ns[SAMPLES / 2];
18220 let candidate_p50 = candidate_ns[SAMPLES / 2];
18221 println!(
18222 "datetime64_asof_borrowed_dense_right_ab items={ITEMS} samples={SAMPLES} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} speedup={:.6}x",
18223 former_p50 as f64 / candidate_p50 as f64,
18224 );
18225 println!("former_samples_ns={former_ns:?}");
18226 println!("candidate_samples_ns={candidate_ns:?}");
18227 }
18228
18229 #[test]
18230 fn merge_asof_backward() {
18231 use super::DataFrameMergeExt;
18232
18233 let left = fp_frame::DataFrame::from_dict(
18235 &["time", "price"],
18236 vec![
18237 (
18238 "time",
18239 vec![
18240 Scalar::Int64(1),
18241 Scalar::Int64(3),
18242 Scalar::Int64(5),
18243 Scalar::Int64(7),
18244 ],
18245 ),
18246 (
18247 "price",
18248 vec![
18249 Scalar::Float64(100.0),
18250 Scalar::Float64(101.0),
18251 Scalar::Float64(102.0),
18252 Scalar::Float64(103.0),
18253 ],
18254 ),
18255 ],
18256 )
18257 .unwrap();
18258
18259 let right = fp_frame::DataFrame::from_dict(
18261 &["time", "bid"],
18262 vec![
18263 (
18264 "time",
18265 vec![Scalar::Int64(2), Scalar::Int64(4), Scalar::Int64(6)],
18266 ),
18267 (
18268 "bid",
18269 vec![
18270 Scalar::Float64(99.5),
18271 Scalar::Float64(100.5),
18272 Scalar::Float64(101.5),
18273 ],
18274 ),
18275 ],
18276 )
18277 .unwrap();
18278
18279 let result = left.merge_asof(&right, "time", "backward").unwrap();
18280 let bid_col = result.columns.get("bid").unwrap();
18285 assert!(bid_col.values()[0].is_missing());
18286 assert_eq!(bid_col.values()[1], Scalar::Float64(99.5));
18287 assert_eq!(bid_col.values()[2], Scalar::Float64(100.5));
18288 assert_eq!(bid_col.values()[3], Scalar::Float64(101.5));
18289 }
18290
18291 #[test]
18292 fn merge_asof_forward() {
18293 use super::AsofDirection;
18294
18295 let left = fp_frame::DataFrame::from_dict(
18296 &["time", "val"],
18297 vec![
18298 ("time", vec![Scalar::Int64(1), Scalar::Int64(3)]),
18299 ("val", vec![Scalar::Float64(10.0), Scalar::Float64(30.0)]),
18300 ],
18301 )
18302 .unwrap();
18303
18304 let right = fp_frame::DataFrame::from_dict(
18305 &["time", "quote"],
18306 vec![
18307 ("time", vec![Scalar::Int64(2), Scalar::Int64(5)]),
18308 ("quote", vec![Scalar::Float64(20.0), Scalar::Float64(50.0)]),
18309 ],
18310 )
18311 .unwrap();
18312
18313 let result = super::merge_asof(&left, &right, "time", AsofDirection::Forward).unwrap();
18314 let quote_col = result.columns.get("quote").unwrap();
18317 assert_eq!(quote_col.values()[0], Scalar::Float64(20.0));
18318 assert_eq!(quote_col.values()[1], Scalar::Float64(50.0));
18319 }
18320
18321 #[test]
18322 fn merge_asof_nearest() {
18323 use super::AsofDirection;
18324
18325 let left = fp_frame::DataFrame::from_dict(
18326 &["time", "val"],
18327 vec![
18328 ("time", vec![Scalar::Int64(3), Scalar::Int64(7)]),
18329 ("val", vec![Scalar::Float64(1.0), Scalar::Float64(2.0)]),
18330 ],
18331 )
18332 .unwrap();
18333
18334 let right = fp_frame::DataFrame::from_dict(
18335 &["time", "ref_val"],
18336 vec![
18337 (
18338 "time",
18339 vec![Scalar::Int64(1), Scalar::Int64(5), Scalar::Int64(10)],
18340 ),
18341 (
18342 "ref_val",
18343 vec![
18344 Scalar::Float64(100.0),
18345 Scalar::Float64(500.0),
18346 Scalar::Float64(1000.0),
18347 ],
18348 ),
18349 ],
18350 )
18351 .unwrap();
18352
18353 let result = super::merge_asof(&left, &right, "time", AsofDirection::Nearest).unwrap();
18354 let ref_col = result.columns.get("ref_val").unwrap();
18359 assert_eq!(ref_col.values()[1], Scalar::Float64(500.0)); }
18361
18362 #[test]
18363 fn merge_asof_nearest_excludes_exact_finds_neighbor() {
18364 use super::{AsofDirection, MergeAsofOptions};
18370
18371 let left = fp_frame::DataFrame::from_dict(
18372 &["time", "val"],
18373 vec![
18374 ("time", vec![Scalar::Int64(5)]),
18375 ("val", vec![Scalar::Int64(1)]),
18376 ],
18377 )
18378 .unwrap();
18379 let right = fp_frame::DataFrame::from_dict(
18380 &["time", "ref_val"],
18381 vec![
18382 (
18383 "time",
18384 vec![Scalar::Int64(3), Scalar::Int64(5), Scalar::Int64(5)],
18385 ),
18386 (
18387 "ref_val",
18388 vec![
18389 Scalar::Float64(10.0),
18390 Scalar::Float64(20.0),
18391 Scalar::Float64(30.0),
18392 ],
18393 ),
18394 ],
18395 )
18396 .unwrap();
18397
18398 let opts = MergeAsofOptions::new().allow_exact_matches(false);
18399 let result =
18400 super::merge_asof_with_options(&left, &right, "time", AsofDirection::Nearest, opts)
18401 .unwrap();
18402 let ref_col = result.columns.get("ref_val").unwrap();
18403 assert_eq!(ref_col.values()[0], Scalar::Float64(10.0)); }
18405
18406 #[test]
18407 fn merge_asof_exact_match() {
18408 use super::AsofDirection;
18409
18410 let left = fp_frame::DataFrame::from_dict(
18411 &["time", "val"],
18412 vec![
18413 ("time", vec![Scalar::Int64(2), Scalar::Int64(4)]),
18414 ("val", vec![Scalar::Float64(1.0), Scalar::Float64(2.0)]),
18415 ],
18416 )
18417 .unwrap();
18418
18419 let right = fp_frame::DataFrame::from_dict(
18420 &["time", "quote"],
18421 vec![
18422 ("time", vec![Scalar::Int64(2), Scalar::Int64(4)]),
18423 ("quote", vec![Scalar::Float64(20.0), Scalar::Float64(40.0)]),
18424 ],
18425 )
18426 .unwrap();
18427
18428 let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
18430 assert_eq!(
18431 result.columns.get("quote").unwrap().values()[0],
18432 Scalar::Float64(20.0)
18433 );
18434 assert_eq!(
18435 result.columns.get("quote").unwrap().values()[1],
18436 Scalar::Float64(40.0)
18437 );
18438
18439 let result = super::merge_asof(&left, &right, "time", AsofDirection::Forward).unwrap();
18441 assert_eq!(
18442 result.columns.get("quote").unwrap().values()[0],
18443 Scalar::Float64(20.0)
18444 );
18445 }
18446
18447 #[test]
18448 fn merge_asof_datetime64_wide_ns_range_uses_i64_path() {
18449 use super::AsofDirection;
18450
18451 let day_ns = 86_400_000_000_000i64;
18452 let base = 1_600_000_000_000_000_000i64;
18453 let dt = |days: i64| Scalar::Datetime64(base + days * day_ns);
18454
18455 let left = fp_frame::DataFrame::from_dict(
18456 &["time", "val"],
18457 vec![
18458 ("time", vec![dt(0), dt(200), dt(400)]),
18459 (
18460 "val",
18461 vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
18462 ),
18463 ],
18464 )
18465 .unwrap();
18466
18467 let right = fp_frame::DataFrame::from_dict(
18468 &["time", "quote"],
18469 vec![
18470 ("time", vec![dt(-1), dt(199), dt(401)]),
18471 (
18472 "quote",
18473 vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
18474 ),
18475 ],
18476 )
18477 .unwrap();
18478
18479 let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
18480 let quote_col = result.columns.get("quote").unwrap();
18481 assert_eq!(quote_col.values()[0], Scalar::Int64(10));
18482 assert_eq!(quote_col.values()[1], Scalar::Int64(20));
18483 assert_eq!(quote_col.values()[2], Scalar::Int64(20));
18484 }
18485
18486 #[test]
18487 fn merge_asof_no_matches_backward() {
18488 use super::AsofDirection;
18489
18490 let left = fp_frame::DataFrame::from_dict(
18491 &["time", "val"],
18492 vec![
18493 ("time", vec![Scalar::Int64(1)]),
18494 ("val", vec![Scalar::Float64(10.0)]),
18495 ],
18496 )
18497 .unwrap();
18498
18499 let right = fp_frame::DataFrame::from_dict(
18501 &["time", "quote"],
18502 vec![
18503 ("time", vec![Scalar::Int64(5)]),
18504 ("quote", vec![Scalar::Float64(50.0)]),
18505 ],
18506 )
18507 .unwrap();
18508
18509 let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
18510 assert!(result.columns.get("quote").unwrap().values()[0].is_missing());
18511 }
18512
18513 #[test]
18514 fn merge_asof_no_matches_forward() {
18515 use super::AsofDirection;
18516
18517 let left = fp_frame::DataFrame::from_dict(
18518 &["time", "val"],
18519 vec![
18520 ("time", vec![Scalar::Int64(10)]),
18521 ("val", vec![Scalar::Float64(10.0)]),
18522 ],
18523 )
18524 .unwrap();
18525
18526 let right = fp_frame::DataFrame::from_dict(
18528 &["time", "quote"],
18529 vec![
18530 ("time", vec![Scalar::Int64(5)]),
18531 ("quote", vec![Scalar::Float64(50.0)]),
18532 ],
18533 )
18534 .unwrap();
18535
18536 let result = super::merge_asof(&left, &right, "time", AsofDirection::Forward).unwrap();
18537 assert!(result.columns.get("quote").unwrap().values()[0].is_missing());
18538 }
18539
18540 #[test]
18541 fn merge_asof_nan_in_key() {
18542 use super::AsofDirection;
18543
18544 let left = fp_frame::DataFrame::from_dict(
18545 &["time", "val"],
18546 vec![
18547 (
18548 "time",
18549 vec![
18550 Scalar::Int64(1),
18551 Scalar::Null(NullKind::NaN),
18552 Scalar::Int64(5),
18553 ],
18554 ),
18555 (
18556 "val",
18557 vec![
18558 Scalar::Float64(10.0),
18559 Scalar::Float64(20.0),
18560 Scalar::Float64(30.0),
18561 ],
18562 ),
18563 ],
18564 )
18565 .unwrap();
18566
18567 let right = fp_frame::DataFrame::from_dict(
18568 &["time", "quote"],
18569 vec![
18570 ("time", vec![Scalar::Int64(2), Scalar::Int64(4)]),
18571 (
18572 "quote",
18573 vec![Scalar::Float64(200.0), Scalar::Float64(400.0)],
18574 ),
18575 ],
18576 )
18577 .unwrap();
18578
18579 let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
18583 assert!(result.columns.get("quote").unwrap().values()[1].is_missing());
18584 assert_eq!(
18586 result.columns.get("quote").unwrap().values()[2],
18587 Scalar::Float64(400.0)
18588 );
18589 }
18590
18591 #[test]
18592 fn merge_asof_nan_in_right_key() {
18593 use super::AsofDirection;
18594
18595 let left = fp_frame::DataFrame::from_dict(
18599 &["time", "val"],
18600 vec![
18601 (
18602 "time",
18603 vec![Scalar::Int64(1), Scalar::Int64(3), Scalar::Int64(5)],
18604 ),
18605 (
18606 "val",
18607 vec![
18608 Scalar::Float64(10.0),
18609 Scalar::Float64(20.0),
18610 Scalar::Float64(30.0),
18611 ],
18612 ),
18613 ],
18614 )
18615 .unwrap();
18616
18617 let right = fp_frame::DataFrame::from_dict(
18618 &["time", "quote"],
18619 vec![
18620 (
18621 "time",
18622 vec![
18623 Scalar::Int64(2),
18624 Scalar::Null(NullKind::NaN),
18625 Scalar::Int64(4),
18626 ],
18627 ),
18628 (
18629 "quote",
18630 vec![
18631 Scalar::Float64(200.0),
18632 Scalar::Float64(999.0),
18633 Scalar::Float64(400.0),
18634 ],
18635 ),
18636 ],
18637 )
18638 .unwrap();
18639
18640 let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
18641 assert!(result.columns.get("quote").unwrap().values()[0].is_missing());
18643 assert_eq!(
18645 result.columns.get("quote").unwrap().values()[1],
18646 Scalar::Float64(200.0)
18647 );
18648 assert_eq!(
18650 result.columns.get("quote").unwrap().values()[2],
18651 Scalar::Float64(400.0)
18652 );
18653 }
18654
18655 #[test]
18656 fn merge_asof_overlapping_columns_apply_suffixes() {
18657 use super::AsofDirection;
18658
18659 let left = fp_frame::DataFrame::from_dict(
18660 &["time", "shared", "left_only"],
18661 vec![
18662 ("time", vec![Scalar::Int64(1), Scalar::Int64(2)]),
18663 ("shared", vec![Scalar::Int64(10), Scalar::Int64(20)]),
18664 ("left_only", vec![Scalar::Int64(1), Scalar::Int64(2)]),
18665 ],
18666 )
18667 .unwrap();
18668
18669 let right = fp_frame::DataFrame::from_dict(
18670 &["time", "shared", "right_only"],
18671 vec![
18672 ("time", vec![Scalar::Int64(1), Scalar::Int64(2)]),
18673 ("shared", vec![Scalar::Int64(100), Scalar::Int64(200)]),
18674 ("right_only", vec![Scalar::Int64(9), Scalar::Int64(8)]),
18675 ],
18676 )
18677 .unwrap();
18678
18679 let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
18680 let shared_left = result.columns.get("shared_x").unwrap().values();
18681 let shared_right = result.columns.get("shared_y").unwrap().values();
18682
18683 assert_eq!(shared_left[0], Scalar::Int64(10));
18684 assert_eq!(shared_left[1], Scalar::Int64(20));
18685 assert_eq!(shared_right[0], Scalar::Int64(100));
18686 assert_eq!(shared_right[1], Scalar::Int64(200));
18687 }
18688
18689 #[test]
18690 fn merge_asof_duplicate_column_gets_suffix() {
18691 use super::AsofDirection;
18692
18693 let left = fp_frame::DataFrame::from_dict(
18695 &["time", "val"],
18696 vec![
18697 ("time", vec![Scalar::Int64(1)]),
18698 ("val", vec![Scalar::Float64(10.0)]),
18699 ],
18700 )
18701 .unwrap();
18702
18703 let right = fp_frame::DataFrame::from_dict(
18704 &["time", "val"],
18705 vec![
18706 ("time", vec![Scalar::Int64(1)]),
18707 ("val", vec![Scalar::Float64(99.0)]),
18708 ],
18709 )
18710 .unwrap();
18711
18712 let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
18713 assert!(result.columns.contains_key("val_x"));
18715 assert!(result.columns.contains_key("val_y"));
18716 assert_eq!(
18717 result.columns.get("val_x").unwrap().values()[0],
18718 Scalar::Float64(10.0)
18719 );
18720 assert_eq!(
18721 result.columns.get("val_y").unwrap().values()[0],
18722 Scalar::Float64(99.0)
18723 );
18724 }
18725
18726 #[test]
18727 fn merge_asof_missing_column_errors() {
18728 use super::AsofDirection;
18729
18730 let left =
18731 fp_frame::DataFrame::from_dict(&["a"], vec![("a", vec![Scalar::Int64(1)])]).unwrap();
18732
18733 let right =
18734 fp_frame::DataFrame::from_dict(&["b"], vec![("b", vec![Scalar::Int64(1)])]).unwrap();
18735
18736 let err = super::merge_asof(&left, &right, "time", AsofDirection::Backward);
18737 assert!(err.is_err());
18738 }
18739
18740 #[test]
18741 fn merge_asof_invalid_direction_errors() {
18742 let left =
18743 fp_frame::DataFrame::from_dict(&["time"], vec![("time", vec![Scalar::Int64(1)])])
18744 .unwrap();
18745 let right =
18746 fp_frame::DataFrame::from_dict(&["time"], vec![("time", vec![Scalar::Int64(1)])])
18747 .unwrap();
18748
18749 let err = left.merge_asof(&right, "time", "sideways");
18750 assert!(matches!(
18751 err,
18752 Err(super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(msg)))
18753 if msg.contains("invalid direction")
18754 ));
18755 }
18756
18757 #[test]
18758 fn merge_asof_unsorted_left_errors() {
18759 use super::AsofDirection;
18760
18761 let left = fp_frame::DataFrame::from_dict(
18762 &["time", "val"],
18763 vec![
18764 ("time", vec![Scalar::Int64(2), Scalar::Int64(1)]),
18765 ("val", vec![Scalar::Float64(10.0), Scalar::Float64(20.0)]),
18766 ],
18767 )
18768 .unwrap();
18769
18770 let right = fp_frame::DataFrame::from_dict(
18771 &["time", "quote"],
18772 vec![
18773 ("time", vec![Scalar::Int64(1), Scalar::Int64(2)]),
18774 (
18775 "quote",
18776 vec![Scalar::Float64(100.0), Scalar::Float64(200.0)],
18777 ),
18778 ],
18779 )
18780 .unwrap();
18781
18782 let err = super::merge_asof(&left, &right, "time", AsofDirection::Backward)
18783 .expect_err("unsorted left should error");
18784 assert!(matches!(
18785 err,
18786 super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(msg))
18787 if msg.contains("sorted")
18788 ));
18789 }
18790
18791 #[test]
18792 fn merge_asof_unsorted_right_errors() {
18793 use super::AsofDirection;
18794
18795 let left = fp_frame::DataFrame::from_dict(
18796 &["time", "val"],
18797 vec![
18798 ("time", vec![Scalar::Int64(1), Scalar::Int64(2)]),
18799 ("val", vec![Scalar::Float64(10.0), Scalar::Float64(20.0)]),
18800 ],
18801 )
18802 .unwrap();
18803
18804 let right = fp_frame::DataFrame::from_dict(
18805 &["time", "quote"],
18806 vec![
18807 ("time", vec![Scalar::Int64(2), Scalar::Int64(1)]),
18808 (
18809 "quote",
18810 vec![Scalar::Float64(200.0), Scalar::Float64(100.0)],
18811 ),
18812 ],
18813 )
18814 .unwrap();
18815
18816 let err = super::merge_asof(&left, &right, "time", AsofDirection::Backward)
18817 .expect_err("unsorted right should error");
18818 assert!(matches!(
18819 err,
18820 super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(msg))
18821 if msg.contains("sorted")
18822 ));
18823 }
18824
18825 #[test]
18826 fn merge_asof_non_numeric_key_errors() {
18827 use super::AsofDirection;
18828
18829 let left = fp_frame::DataFrame::from_dict(
18830 &["time", "val"],
18831 vec![
18832 ("time", vec![Scalar::Utf8("a".into())]),
18833 ("val", vec![Scalar::Float64(10.0)]),
18834 ],
18835 )
18836 .unwrap();
18837
18838 let right = fp_frame::DataFrame::from_dict(
18839 &["time", "quote"],
18840 vec![
18841 ("time", vec![Scalar::Utf8("b".into())]),
18842 ("quote", vec![Scalar::Float64(20.0)]),
18843 ],
18844 )
18845 .unwrap();
18846
18847 let err = super::merge_asof(&left, &right, "time", AsofDirection::Backward)
18848 .expect_err("non-numeric key should error");
18849 assert!(matches!(
18850 err,
18851 super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(msg))
18852 if msg.contains("numeric")
18853 ));
18854 }
18855
18856 #[test]
18857 fn merge_asof_preserves_all_left_rows() {
18858 use super::AsofDirection;
18859
18860 let left = fp_frame::DataFrame::from_dict(
18861 &["time", "val"],
18862 vec![
18863 (
18864 "time",
18865 vec![
18866 Scalar::Int64(1),
18867 Scalar::Int64(2),
18868 Scalar::Int64(3),
18869 Scalar::Int64(4),
18870 Scalar::Int64(5),
18871 ],
18872 ),
18873 (
18874 "val",
18875 vec![
18876 Scalar::Float64(10.0),
18877 Scalar::Float64(20.0),
18878 Scalar::Float64(30.0),
18879 Scalar::Float64(40.0),
18880 Scalar::Float64(50.0),
18881 ],
18882 ),
18883 ],
18884 )
18885 .unwrap();
18886
18887 let right = fp_frame::DataFrame::from_dict(
18888 &["time", "quote"],
18889 vec![
18890 ("time", vec![Scalar::Int64(3)]),
18891 ("quote", vec![Scalar::Float64(300.0)]),
18892 ],
18893 )
18894 .unwrap();
18895
18896 let result = super::merge_asof(&left, &right, "time", AsofDirection::Backward).unwrap();
18897 assert_eq!(result.index.len(), 5);
18899 }
18900
18901 #[test]
18904 fn merge_asof_allow_exact_matches_false_backward() {
18905 use super::{AsofDirection, MergeAsofOptions, merge_asof_with_options};
18906
18907 let left = fp_frame::DataFrame::from_dict(
18909 &["time", "val"],
18910 vec![
18911 (
18912 "time",
18913 vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
18914 ),
18915 (
18916 "val",
18917 vec![
18918 Scalar::Float64(10.0),
18919 Scalar::Float64(20.0),
18920 Scalar::Float64(30.0),
18921 ],
18922 ),
18923 ],
18924 )
18925 .unwrap();
18926
18927 let right = fp_frame::DataFrame::from_dict(
18929 &["time", "quote"],
18930 vec![
18931 (
18932 "time",
18933 vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
18934 ),
18935 (
18936 "quote",
18937 vec![
18938 Scalar::Float64(100.0),
18939 Scalar::Float64(200.0),
18940 Scalar::Float64(300.0),
18941 ],
18942 ),
18943 ],
18944 )
18945 .unwrap();
18946
18947 let result_with_exact = merge_asof_with_options(
18949 &left,
18950 &right,
18951 "time",
18952 AsofDirection::Backward,
18953 MergeAsofOptions::new(),
18954 )
18955 .unwrap();
18956
18957 let quote_col = result_with_exact.columns.get("quote").unwrap();
18958 assert_eq!(quote_col.values()[0], Scalar::Float64(100.0)); assert_eq!(quote_col.values()[1], Scalar::Float64(200.0)); assert_eq!(quote_col.values()[2], Scalar::Float64(300.0)); let result_no_exact = merge_asof_with_options(
18964 &left,
18965 &right,
18966 "time",
18967 AsofDirection::Backward,
18968 MergeAsofOptions::new().allow_exact_matches(false),
18969 )
18970 .unwrap();
18971
18972 let quote_col_no_exact = result_no_exact.columns.get("quote").unwrap();
18973 assert!(matches!(quote_col_no_exact.values()[0], Scalar::Null(_)));
18975 assert_eq!(quote_col_no_exact.values()[1], Scalar::Float64(100.0));
18977 assert_eq!(quote_col_no_exact.values()[2], Scalar::Float64(200.0));
18979 }
18980
18981 #[test]
18982 fn merge_asof_tolerance() {
18983 use super::{AsofDirection, MergeAsofOptions, merge_asof_with_options};
18984
18985 let left = fp_frame::DataFrame::from_dict(
18987 &["time", "val"],
18988 vec![
18989 (
18990 "time",
18991 vec![Scalar::Int64(1), Scalar::Int64(5), Scalar::Int64(10)],
18992 ),
18993 (
18994 "val",
18995 vec![
18996 Scalar::Float64(10.0),
18997 Scalar::Float64(50.0),
18998 Scalar::Float64(100.0),
18999 ],
19000 ),
19001 ],
19002 )
19003 .unwrap();
19004
19005 let right = fp_frame::DataFrame::from_dict(
19007 &["time", "quote"],
19008 vec![
19009 ("time", vec![Scalar::Int64(2), Scalar::Int64(6)]),
19010 (
19011 "quote",
19012 vec![Scalar::Float64(200.0), Scalar::Float64(600.0)],
19013 ),
19014 ],
19015 )
19016 .unwrap();
19017
19018 let result = merge_asof_with_options(
19020 &left,
19021 &right,
19022 "time",
19023 AsofDirection::Backward,
19024 MergeAsofOptions::new().tolerance(2.0),
19025 )
19026 .unwrap();
19027
19028 let quote_col = result.columns.get("quote").unwrap();
19029 assert!(matches!(quote_col.values()[0], Scalar::Null(_)));
19031 assert!(matches!(quote_col.values()[1], Scalar::Null(_)));
19033 assert!(matches!(quote_col.values()[2], Scalar::Null(_)));
19035
19036 let result_wider = merge_asof_with_options(
19038 &left,
19039 &right,
19040 "time",
19041 AsofDirection::Backward,
19042 MergeAsofOptions::new().tolerance(5.0),
19043 )
19044 .unwrap();
19045
19046 let quote_col_wider = result_wider.columns.get("quote").unwrap();
19047 assert!(matches!(quote_col_wider.values()[0], Scalar::Null(_)));
19049 assert_eq!(quote_col_wider.values()[1], Scalar::Float64(200.0));
19051 assert_eq!(quote_col_wider.values()[2], Scalar::Float64(600.0));
19053 }
19054
19055 #[test]
19056 fn merge_asof_by_column() {
19057 use super::{AsofDirection, MergeAsofOptions, merge_asof_with_options};
19058
19059 let left = fp_frame::DataFrame::from_dict(
19061 &["group", "time", "val"],
19062 vec![
19063 (
19064 "group",
19065 vec![
19066 Scalar::Utf8("A".into()),
19067 Scalar::Utf8("A".into()),
19068 Scalar::Utf8("B".into()),
19069 Scalar::Utf8("B".into()),
19070 ],
19071 ),
19072 (
19073 "time",
19074 vec![
19075 Scalar::Int64(1),
19076 Scalar::Int64(2),
19077 Scalar::Int64(3),
19078 Scalar::Int64(4),
19079 ],
19080 ),
19081 (
19082 "val",
19083 vec![
19084 Scalar::Float64(10.0),
19085 Scalar::Float64(30.0),
19086 Scalar::Float64(20.0),
19087 Scalar::Float64(40.0),
19088 ],
19089 ),
19090 ],
19091 )
19092 .unwrap();
19093
19094 let right = fp_frame::DataFrame::from_dict(
19096 &["group", "time", "quote"],
19097 vec![
19098 (
19099 "group",
19100 vec![
19101 Scalar::Utf8("A".into()),
19102 Scalar::Utf8("B".into()),
19103 Scalar::Utf8("A".into()),
19104 ],
19105 ),
19106 (
19107 "time",
19108 vec![Scalar::Int64(2), Scalar::Int64(3), Scalar::Int64(4)],
19109 ),
19110 (
19111 "quote",
19112 vec![
19113 Scalar::Float64(200.0),
19114 Scalar::Float64(400.0),
19115 Scalar::Float64(300.0),
19116 ],
19117 ),
19118 ],
19119 )
19120 .unwrap();
19121
19122 let result = merge_asof_with_options(
19124 &left,
19125 &right,
19126 "time",
19127 AsofDirection::Backward,
19128 MergeAsofOptions::new().by(vec!["group".to_string()]),
19129 )
19130 .unwrap();
19131
19132 let quote_col = result.columns.get("quote").unwrap();
19133 assert!(matches!(quote_col.values()[0], Scalar::Null(_)));
19137 assert_eq!(quote_col.values()[1], Scalar::Float64(200.0));
19139 assert_eq!(quote_col.values()[2], Scalar::Float64(400.0));
19141 assert_eq!(quote_col.values()[3], Scalar::Float64(400.0));
19143 }
19144
19145 #[test]
19146 fn merge_asof_by_column_requires_globally_sorted_left_keys() {
19147 use super::{AsofDirection, MergeAsofOptions, merge_asof_with_options};
19148
19149 let left = fp_frame::DataFrame::from_dict(
19150 &["group", "time"],
19151 vec![
19152 (
19153 "group",
19154 vec![
19155 Scalar::Utf8("A".into()),
19156 Scalar::Utf8("A".into()),
19157 Scalar::Utf8("B".into()),
19158 Scalar::Utf8("B".into()),
19159 ],
19160 ),
19161 (
19162 "time",
19163 vec![
19164 Scalar::Int64(1),
19165 Scalar::Int64(3),
19166 Scalar::Int64(1),
19167 Scalar::Int64(2),
19168 ],
19169 ),
19170 ],
19171 )
19172 .unwrap();
19173 let right = fp_frame::DataFrame::from_dict(
19174 &["group", "time", "quote"],
19175 vec![
19176 (
19177 "group",
19178 vec![
19179 Scalar::Utf8("A".into()),
19180 Scalar::Utf8("B".into()),
19181 Scalar::Utf8("A".into()),
19182 ],
19183 ),
19184 (
19185 "time",
19186 vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
19187 ),
19188 (
19189 "quote",
19190 vec![
19191 Scalar::Float64(10.0),
19192 Scalar::Float64(20.0),
19193 Scalar::Float64(30.0),
19194 ],
19195 ),
19196 ],
19197 )
19198 .unwrap();
19199
19200 let err = merge_asof_with_options(
19201 &left,
19202 &right,
19203 "time",
19204 AsofDirection::Backward,
19205 MergeAsofOptions::new().by(vec!["group".to_string()]),
19206 )
19207 .expect_err("pandas requires globally sorted left keys even with by=");
19208 assert!(matches!(
19209 err,
19210 super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(message))
19211 if message.contains("left") && message.contains("sorted")
19212 ));
19213 }
19214
19215 #[test]
19216 fn merge_asof_by_column_requires_globally_sorted_right_keys() {
19217 use super::{AsofDirection, MergeAsofOptions, merge_asof_with_options};
19218
19219 let left = fp_frame::DataFrame::from_dict(
19220 &["group", "time"],
19221 vec![
19222 (
19223 "group",
19224 vec![
19225 Scalar::Utf8("A".into()),
19226 Scalar::Utf8("B".into()),
19227 Scalar::Utf8("A".into()),
19228 ],
19229 ),
19230 (
19231 "time",
19232 vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
19233 ),
19234 ],
19235 )
19236 .unwrap();
19237 let right = fp_frame::DataFrame::from_dict(
19238 &["group", "time", "quote"],
19239 vec![
19240 (
19241 "group",
19242 vec![
19243 Scalar::Utf8("A".into()),
19244 Scalar::Utf8("A".into()),
19245 Scalar::Utf8("B".into()),
19246 ],
19247 ),
19248 (
19249 "time",
19250 vec![Scalar::Int64(1), Scalar::Int64(3), Scalar::Int64(2)],
19251 ),
19252 (
19253 "quote",
19254 vec![
19255 Scalar::Float64(10.0),
19256 Scalar::Float64(30.0),
19257 Scalar::Float64(20.0),
19258 ],
19259 ),
19260 ],
19261 )
19262 .unwrap();
19263
19264 let err = merge_asof_with_options(
19265 &left,
19266 &right,
19267 "time",
19268 AsofDirection::Backward,
19269 MergeAsofOptions::new().by(vec!["group".to_string()]),
19270 )
19271 .expect_err("pandas requires globally sorted right keys even with by=");
19272 assert!(matches!(
19273 err,
19274 super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(message))
19275 if message.contains("right") && message.contains("sorted")
19276 ));
19277 }
19278
19279 #[test]
19280 fn merge_ordered_sorts_and_ffills_values() {
19281 let left = fp_frame::DataFrame::from_dict(
19282 &["date", "left_val"],
19283 vec![
19284 ("date", vec![Scalar::Int64(1), Scalar::Int64(3)]),
19285 ("left_val", vec![Scalar::Int64(10), Scalar::Int64(30)]),
19286 ],
19287 )
19288 .unwrap();
19289
19290 let right = fp_frame::DataFrame::from_dict(
19291 &["date", "right_val"],
19292 vec![
19293 ("date", vec![Scalar::Int64(2), Scalar::Int64(3)]),
19294 ("right_val", vec![Scalar::Int64(200), Scalar::Int64(300)]),
19295 ],
19296 )
19297 .unwrap();
19298
19299 let result = super::merge_ordered(&left, &right, &["date"], Some("ffill")).unwrap();
19300 let frame = fp_frame::DataFrame::new(result.index, result.columns).unwrap();
19301
19302 assert_eq!(
19303 frame.column("date").unwrap().values(),
19304 &[Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)]
19305 );
19306 assert_eq!(
19307 frame.column("left_val").unwrap().values(),
19308 &[
19309 Scalar::Float64(10.0),
19310 Scalar::Float64(10.0),
19311 Scalar::Float64(30.0),
19312 ]
19313 );
19314 assert_eq!(
19315 frame.column("right_val").unwrap().values(),
19316 &[
19317 Scalar::Null(NullKind::NaN),
19318 Scalar::Float64(200.0),
19319 Scalar::Float64(300.0),
19320 ]
19321 );
19322 }
19323
19324 #[test]
19325 fn merge_ordered_invalid_fill_method_errors() {
19326 let left = fp_frame::DataFrame::from_dict(
19327 &["date", "left_val"],
19328 vec![
19329 ("date", vec![Scalar::Int64(1)]),
19330 ("left_val", vec![Scalar::Int64(10)]),
19331 ],
19332 )
19333 .unwrap();
19334
19335 let right = fp_frame::DataFrame::from_dict(
19336 &["date", "right_val"],
19337 vec![
19338 ("date", vec![Scalar::Int64(2)]),
19339 ("right_val", vec![Scalar::Int64(200)]),
19340 ],
19341 )
19342 .unwrap();
19343
19344 let err = super::merge_ordered(&left, &right, &["date"], Some("sideways"))
19345 .expect_err("invalid fill method should error");
19346 assert!(matches!(
19347 err,
19348 super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(message))
19349 if message.contains("fill_method must be 'ffill' or None")
19350 ));
19351 }
19352
19353 #[test]
19354 fn merge_ordered_rejects_bfill_like_pandas() {
19355 let left = fp_frame::DataFrame::from_dict(
19356 &["date", "left_val"],
19357 vec![
19358 ("date", vec![Scalar::Int64(1), Scalar::Int64(3)]),
19359 ("left_val", vec![Scalar::Int64(10), Scalar::Int64(30)]),
19360 ],
19361 )
19362 .unwrap();
19363
19364 let right = fp_frame::DataFrame::from_dict(
19365 &["date", "right_val"],
19366 vec![
19367 ("date", vec![Scalar::Int64(2), Scalar::Int64(3)]),
19368 ("right_val", vec![Scalar::Int64(200), Scalar::Int64(300)]),
19369 ],
19370 )
19371 .unwrap();
19372
19373 let err = super::merge_ordered(&left, &right, &["date"], Some("bfill"))
19374 .expect_err("pandas only accepts fill_method='ffill' or None");
19375 assert!(matches!(
19376 err,
19377 super::JoinError::Frame(fp_frame::FrameError::CompatibilityRejected(message))
19378 if message.contains("fill_method must be 'ffill' or None")
19379 ));
19380 }
19381
19382 #[test]
19385 fn dataframe_join_aliases_join_on_index() {
19386 use std::collections::BTreeMap;
19387
19388 use fp_columnar::Column;
19389 use fp_frame::DataFrame;
19390 use fp_index::Index;
19391 use fp_types::{DType, Scalar};
19392
19393 use super::DataFrameMergeExt;
19394
19395 fn build(name1: &str, name2: &str, vals1: &[i64], vals2: &[i64]) -> DataFrame {
19396 let mut cols = BTreeMap::new();
19397 cols.insert(
19398 name1.to_owned(),
19399 Column::new(
19400 DType::Int64,
19401 vals1.iter().map(|v| Scalar::Int64(*v)).collect(),
19402 )
19403 .unwrap(),
19404 );
19405 cols.insert(
19406 name2.to_owned(),
19407 Column::new(
19408 DType::Int64,
19409 vals2.iter().map(|v| Scalar::Int64(*v)).collect(),
19410 )
19411 .unwrap(),
19412 );
19413 DataFrame::new_with_column_order(
19414 Index::new(
19415 (0..vals1.len() as i64)
19416 .map(fp_index::IndexLabel::Int64)
19417 .collect(),
19418 ),
19419 cols,
19420 vec![name1.to_owned(), name2.to_owned()],
19421 )
19422 .unwrap()
19423 }
19424
19425 let left = build("a", "b", &[10, 20, 30], &[1, 2, 3]);
19426 let right = build("c", "d", &[100, 200, 300], &[7, 8, 9]);
19427
19428 let via_join = left.join(&right, super::JoinType::Inner).unwrap();
19429 let via_join_on_index = left.join_on_index(&right, super::JoinType::Inner).unwrap();
19430
19431 let join_keys: Vec<&String> = via_join.columns.keys().collect();
19433 let idx_keys: Vec<&String> = via_join_on_index.columns.keys().collect();
19434 assert_eq!(join_keys, idx_keys);
19435 assert_eq!(via_join.index, via_join_on_index.index);
19436 for k in via_join.columns.keys() {
19437 assert_eq!(
19438 via_join.columns.get(k).unwrap().values(),
19439 via_join_on_index.columns.get(k).unwrap().values(),
19440 "column {k} differs"
19441 );
19442 }
19443 }
19444}