From 94b1360257d81efbd60910cf8d7f15820a85f311 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E5=93=A5=E4=B8=8D=E5=A4=AA=E9=80=8D=E9=81=A5?= <115146404+xgbtxy@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:11:15 +0800 Subject: [PATCH] fix(rust): prevent panics and NaN bypass in dataloader split and shuffle validation (#5219) ## Summary Fixes multiple panics and a `NaN` validation bypass in the dataloader permutation split and shuffle configuration validation (`rust/lancedb/src/dataloader/permutation/split.rs` and `rust/lancedb/src/dataloader/permutation/shuffle.rs`), returning `Error::InvalidInput` cleanly instead of crashing. ## Root Cause Invalid configurations passed through Rust, Python, or Node.js bindings could bypass validation or panic during validation/execution: 1. **`SplitSizes::Fixed(0)` divide-by-zero panic**: `SplitSizes::validate()` evaluated `(num_rows / num_splits) == 0` without first checking `*num_splits == 0`, panicking with integer division by zero inside `validate()`. 2. **Empty `SplitSizes::Percentages` / `SplitSizes::Counts` out-of-bounds panic**: Both passed `validate()` with `Ok(())` and later panicked with index out of bounds (`split_sizes[split_id]`) in `Splitter::sequential_split_id()`. 3. **`SplitSizes::Percentages` `NaN` bypass**: Because IEEE 754 comparisons with `NaN` return `false`, `SplitSizes::Percentages(vec![f64::NAN])` bypassed `< 0.0 || > 1.0`, `< 1.0`, and `sum > 1.0` checks in `validate()`. 4. **Unchecked `u64` summation overflow**: `SplitSizes::Counts` and `SplitStrategy::Hash` summed weights/counts with `.sum::()` / `+`, panicking on overflow in debug builds or wrapping in release builds. 5. **`Shuffler::shuffle()` divide-by-zero panics**: The `clump_size == 0` check lived only inside `do_shuffle()`, so inputs routed through `in_memory_shuffle()` (when `num_rows < max_rows_per_file`, the default path for datasets under 1M/10M rows) panicked in `shuffle_batch()` at `.div_ceil(0)`. Similarly, `max_rows_per_file == 0` panicked in `do_shuffle()` at `num_rows.div_ceil(0)`. ## Changes - `rust/lancedb/src/dataloader/permutation/split.rs`: - Reject `*num_splits == 0`, empty `Percentages`/`Counts`, non-finite/`NaN` percentages via `!(0.0..=1.0).contains(percentage)`, and overflowing `Counts` sums in `SplitSizes::validate()`. - Reject `clump_size == Some(0)` in `SplitStrategy::Random` and overflowing weight sums in `SplitStrategy::Hash` inside `SplitStrategy::validate()`. - `rust/lancedb/src/dataloader/permutation/shuffle.rs`: - Validate `max_rows_per_file == 0` and `clump_size == Some(0)` upfront at the entry of `Shuffler::shuffle()` so both in-memory and external shuffle paths return `Error::InvalidInput` cleanly before creating temporary directories or dividing. - Add unit tests in `split.rs` and `shuffle.rs` covering all invalid configurations end-to-end. ## Verification - Confirmed all 5 new tests fail on `main` prior to the fix (including division-by-zero panics at `split.rs:670`, `shuffle.rs:92`, and `shuffle.rs:131`). - Verified the full `dataloader::permutation::` unit test suite passes after the fix: - `cargo test --profile ci --locked -p lancedb --lib dataloader::permutation::` (`54 passed; 0 failed`) - `cargo fmt --all -- --check` - `cargo clippy --profile ci --locked -p lancedb --lib --tests` --- .../src/dataloader/permutation/builder.rs | 98 +++- .../src/dataloader/permutation/shuffle.rs | 43 +- .../src/dataloader/permutation/split.rs | 523 ++++++++++++++++-- 3 files changed, 597 insertions(+), 67 deletions(-) diff --git a/rust/lancedb/src/dataloader/permutation/builder.rs b/rust/lancedb/src/dataloader/permutation/builder.rs index 93efb130f..357a98f13 100644 --- a/rust/lancedb/src/dataloader/permutation/builder.rs +++ b/rust/lancedb/src/dataloader/permutation/builder.rs @@ -355,6 +355,14 @@ impl PermutationBuilder { .count_rows(self.config.filter.clone()) .await? as u64; + self.config.split_strategy.validate(num_rows)?; + // Bootstrap's output row count (num_samples) differs from its input row count + // (num_rows); every other strategy's output matches its input. The shuffler + // must be told the former, not assume it always equals the latter. + // Plan the output row count before scanning so invalid or unrepresentable + // dimensions fail fast before materialization. + let output_rows = splitter.try_output_row_count(num_rows)?; + // Apply splits let rows = rows.execute().await?; // Splits are assigned by position, so the scan has to arrive in a fixed order. @@ -363,10 +371,6 @@ impl PermutationBuilder { } else { self.sort_by_column(rows, ROW_ID).await? }; - // Bootstrap's output row count (num_samples) differs from its input row count - // (num_rows); every other strategy's output matches its input. The shuffler - // must be told the former, not assume it always equals the latter. - let output_rows = splitter.output_row_count(num_rows); let split_data = splitter.apply(rows, num_rows).await?; // Shuffle data if requested @@ -1180,4 +1184,90 @@ mod tests { assert_eq!(first_plan.count_rows(None).await.unwrap(), 100); assert_eq!(first_plan.version().await.unwrap(), first_version); } + + #[tokio::test] + async fn test_permutation_builder_rejects_invalid_bootstrap_config() { + let temp_dir = tempfile::tempdir().unwrap(); + let db = connect(temp_dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let initial_data = lance_datagen::gen_batch() + .col("col_a", lance_datagen::array::step::()) + .into_ldb_stream(RowCount::from(10), BatchCount::from(1)); + let data_table = db + .create_table("base_tbl", initial_data) + .execute() + .await + .unwrap(); + + let invalid_strategies = vec![ + SplitStrategy::Bootstrap { + num_samples: 10, + sizes: SplitSizes::Fixed(0), + seed: Some(42), + }, + SplitStrategy::Bootstrap { + num_samples: 10, + sizes: SplitSizes::Counts(vec![20]), + seed: Some(42), + }, + SplitStrategy::Bootstrap { + num_samples: 10, + sizes: SplitSizes::Counts(vec![u64::MAX, 1]), + seed: Some(42), + }, + SplitStrategy::Bootstrap { + num_samples: 0, + sizes: SplitSizes::Fixed(0), + seed: Some(42), + }, + SplitStrategy::Bootstrap { + num_samples: 10, + sizes: SplitSizes::Percentages(vec![f64::NAN]), + seed: Some(42), + }, + SplitStrategy::Bootstrap { + num_samples: u64::MAX, + sizes: SplitSizes::Fixed(u64::MAX), + seed: Some(42), + }, + SplitStrategy::Bootstrap { + num_samples: u64::MAX, + sizes: SplitSizes::Percentages(vec![0.5, 0.5]), + seed: Some(42), + }, + ]; + + for strategy in invalid_strategies { + let err = PermutationBuilder::new(data_table.clone()) + .with_split_strategy(strategy, None) + .build() + .await + .unwrap_err(); + assert!( + matches!(err, Error::InvalidInput { .. }), + "expected InvalidInput, got: {err:?}" + ); + } + + // Also validate against the filtered eligible row count (0 eligible rows). + let err = PermutationBuilder::new(data_table) + .with_filter("col_a > 1000".to_string()) + .with_split_strategy( + SplitStrategy::Bootstrap { + num_samples: 10, + sizes: SplitSizes::Fixed(2), + seed: Some(42), + }, + None, + ) + .build() + .await + .unwrap_err(); + assert!( + matches!(err, Error::InvalidInput { .. }), + "expected InvalidInput for empty filtered bootstrap table, got: {err:?}" + ); + } } diff --git a/rust/lancedb/src/dataloader/permutation/shuffle.rs b/rust/lancedb/src/dataloader/permutation/shuffle.rs index 2bc06452c..adacdb881 100644 --- a/rust/lancedb/src/dataloader/permutation/shuffle.rs +++ b/rust/lancedb/src/dataloader/permutation/shuffle.rs @@ -134,11 +134,6 @@ impl Shuffler { let tmp_dir = temp_dir.path().to_path_buf(); let clump_size = self.config.clump_size.unwrap_or(1); - if clump_size == 0 { - return Err(Error::InvalidInput { - message: "clump size must be greater than 0".to_string(), - }); - } let object_store = ObjectStore::local(); let arrow_schema = data.schema(); @@ -275,6 +270,16 @@ impl Shuffler { data: SendableRecordBatchStream, num_rows: u64, ) -> Result { + if self.config.max_rows_per_file == 0 { + return Err(Error::InvalidInput { + message: "max_rows_per_file must be greater than 0".to_string(), + }); + } + if self.config.clump_size == Some(0) { + return Err(Error::InvalidInput { + message: "clump size must be greater than 0".to_string(), + }); + } log::debug!( "Shuffle job {}: shuffling {} rows and {} columns", self.id, @@ -490,4 +495,32 @@ mod tests { } } } + + #[tokio::test] + async fn test_in_memory_shuffle_rejects_zero_clump_size() { + let config = ShufflerConfig { + temp_dir: TemporaryDirectory::None, + clump_size: Some(0), + ..Default::default() + }; + let shuffler = Shuffler::new(config); + let stream = create_test_stream(BatchCount::from(2), RowCount::from(10)); + + let result = shuffler.shuffle(stream, 20).await; + assert!(matches!(result, Err(Error::InvalidInput { .. }))); + } + + #[tokio::test] + async fn test_shuffle_rejects_zero_max_rows_per_file() { + let config = ShufflerConfig { + temp_dir: TemporaryDirectory::None, + max_rows_per_file: 0, + ..Default::default() + }; + let shuffler = Shuffler::new(config); + let stream = create_test_stream(BatchCount::from(2), RowCount::from(10)); + + let result = shuffler.shuffle(stream, 20).await; + assert!(matches!(result, Err(Error::InvalidInput { .. }))); + } } diff --git a/rust/lancedb/src/dataloader/permutation/split.rs b/rust/lancedb/src/dataloader/permutation/split.rs index 0fb7f669b..4bc7aee0f 100644 --- a/rust/lancedb/src/dataloader/permutation/split.rs +++ b/rust/lancedb/src/dataloader/permutation/split.rs @@ -27,6 +27,9 @@ use crate::{ pub const SPLIT_ID_COLUMN: &str = "split_id"; +/// Maximum number of `u64` elements a `Vec` can represent (`isize::MAX / size_of::()`). +const MAX_U64_VEC_LEN: u64 = (isize::MAX as u64) / (std::mem::size_of::() as u64); + /// Strategy for assigning rows to splits #[derive(Debug, Clone, Default)] pub enum SplitStrategy { @@ -136,11 +139,20 @@ impl SplitStrategy { pub fn validate(&self, num_rows: u64) -> Result<()> { match self { Self::NoSplit => Ok(()), - Self::Random { sizes, .. } => sizes.validate(num_rows), + Self::Random { + sizes, clump_size, .. + } => { + if *clump_size == Some(0) { + return Err(Error::InvalidInput { + message: "clump size must be greater than 0".to_string(), + }); + } + sizes.validate(num_rows) + } Self::Hash { split_weights, + discard_weight, columns, - .. } => { if columns.is_empty() { return Err(Error::InvalidInput { @@ -157,6 +169,13 @@ impl SplitStrategy { message: "Split weights must be greater than 0".to_string(), }); } + split_weights + .iter() + .try_fold(0u64, |acc, &w| acc.checked_add(w)) + .and_then(|sum| sum.checked_add(*discard_weight)) + .ok_or_else(|| Error::InvalidInput { + message: "Hash split weights and discard weight overflowed u64".to_string(), + })?; Ok(()) } Self::Sequential { sizes } => sizes.validate(num_rows), @@ -176,6 +195,14 @@ impl SplitStrategy { message: "Bootstrap strategy requires num_samples > 0".to_string(), }); } + if *num_samples > MAX_U64_VEC_LEN { + return Err(Error::InvalidInput { + message: format!( + "Bootstrap strategy's num_samples ({num_samples}) exceeds the maximum \ + representable vector length ({MAX_U64_VEC_LEN})" + ), + }); + } // Validated against num_samples, not num_rows: sampling is with replacement, // so num_samples may exceed the number of eligible rows. sizes.validate(*num_samples) @@ -242,7 +269,7 @@ impl Splitter { num_rows: u64, sizes: &SplitSizes, ) -> Result { - let split_sizes = sizes.to_counts(num_rows); + let split_sizes = sizes.try_to_counts(num_rows)?; let split_index = AtomicUsize::new(0); let counter_in_split = AtomicU64::new(0); @@ -420,7 +447,13 @@ impl Splitter { }); } - let split_sample_counts = sizes.to_counts(num_samples); + let split_sample_counts = sizes.try_to_counts(num_samples)?; + let total_samples = split_sample_counts + .iter() + .try_fold(0u64, |acc, &c| acc.checked_add(c)) + .ok_or_else(|| Error::InvalidInput { + message: "Bootstrap split sample counts overflowed u64".to_string(), + })?; // `try_reserve_exact` (fallible) rather than `with_capacity` (infallible -- // aborts the whole process via `handle_alloc_error` on failure, which no @@ -434,13 +467,14 @@ impl Splitter { allocate in memory" ), }; + let total_samples_usize = usize::try_from(total_samples).map_err(|_| too_large())?; let mut position_indices = Vec::::new(); position_indices - .try_reserve_exact(num_samples as usize) + .try_reserve_exact(total_samples_usize) .map_err(|_| too_large())?; let mut split_ids = Vec::::new(); split_ids - .try_reserve_exact(num_samples as usize) + .try_reserve_exact(total_samples_usize) .map_err(|_| too_large())?; for (split_idx, &count) in split_sample_counts.iter().enumerate() { // Derive an independent seed per split (rather than one RNG shared across all @@ -573,11 +607,35 @@ impl Splitter { /// `Fixed(n)` when `n` does not divide `num_samples` evenly, or explicit /// `counts`/`ratios` that do not use every sample) and `apply_bootstrap` only /// ever emits exactly what `to_counts` returns. + pub(crate) fn try_output_row_count(&self, num_rows: u64) -> Result { + match &self.strategy { + SplitStrategy::Bootstrap { + num_samples, sizes, .. + } => sizes.checked_total_rows(*num_samples), + _ => Ok(num_rows), + } + } + pub fn output_row_count(&self, num_rows: u64) -> u64 { match &self.strategy { SplitStrategy::Bootstrap { num_samples, sizes, .. - } => sizes.to_counts(*num_samples).iter().sum(), + } => match sizes { + SplitSizes::Fixed(num_splits) => { + debug_assert!(*num_splits > 0, "Fixed split count must be > 0"); + num_samples + .checked_div(*num_splits) + .map_or(0, |rows_per_split| rows_per_split * *num_splits) + } + SplitSizes::Counts(counts) => { + counts.iter().copied().fold(0u64, u64::saturating_add) + } + SplitSizes::Percentages(_) => sizes + .to_counts(*num_samples) + .iter() + .copied() + .fold(0u64, u64::saturating_add), + }, _ => num_rows, } } @@ -620,8 +678,13 @@ impl SplitSizes { pub fn validate(&self, num_rows: u64) -> Result<()> { match self { Self::Percentages(percentages) => { + if percentages.is_empty() { + return Err(Error::InvalidInput { + message: "Split percentages must not be empty".to_string(), + }); + } for percentage in percentages { - if *percentage < 0.0 || *percentage > 1.0 { + if !(0.0..=1.0).contains(percentage) { return Err(Error::InvalidInput { message: "Split percentages must be between 0.0 and 1.0".to_string(), }); @@ -643,12 +706,22 @@ impl SplitSizes { } } Self::Counts(counts) => { - if counts.iter().sum::() > num_rows { + if counts.is_empty() { + return Err(Error::InvalidInput { + message: "Split counts must not be empty".to_string(), + }); + } + let total_rows = counts + .iter() + .try_fold(0u64, |acc, &c| acc.checked_add(c)) + .ok_or_else(|| Error::InvalidInput { + message: "Split counts overflowed u64".to_string(), + })?; + if total_rows > num_rows { return Err(Error::InvalidInput { message: format!( "Split counts specified {} rows but only {} are available", - counts.iter().sum::(), - num_rows + total_rows, num_rows ), }); } @@ -659,6 +732,19 @@ impl SplitSizes { } } Self::Fixed(num_splits) => { + if *num_splits == 0 { + return Err(Error::InvalidInput { + message: "Split fixed config must specify at least 1 split".to_string(), + }); + } + if *num_splits > MAX_U64_VEC_LEN { + return Err(Error::InvalidInput { + message: format!( + "Split fixed config specified {} splits which exceeds the maximum representable split count ({})", + *num_splits, MAX_U64_VEC_LEN + ), + }); + } if *num_splits > num_rows { return Err(Error::InvalidInput { message: format!( @@ -680,54 +766,190 @@ impl SplitSizes { Ok(()) } + fn percentages_to_counts(percentages: &[f64], num_rows: u64) -> Result> { + let mut counts = Vec::::new(); + counts + .try_reserve_exact(percentages.len()) + .map_err(|_| Error::InvalidInput { + message: format!( + "Split percentages count ({}) is too large to allocate in memory", + percentages.len() + ), + })?; + + let mut percentage_sum = 0.0_f64; + let mut sum: u128 = 0; + for &p in percentages { + let count = (p * (num_rows as f64)).round() as u64; + percentage_sum += p; + sum += count as u128; + counts.push(count); + } + + let num_rows_u128 = num_rows as u128; + let is_basically_one = (num_rows as f64 - percentage_sum * num_rows as f64).abs() < 0.5; + + // If the sum of percentages is close to 1.0 then rounding errors can add up + // to more or less than num_rows. + // + // Drop items from buckets in round-robin order until we have at most num_rows, + // using bulk passes so large rounding discrepancies cannot spin. + if sum > num_rows_u128 { + let mut excess = sum - num_rows_u128; + while excess > 0 { + let mut nonzero_count: u128 = 0; + let mut min_nonzero: u64 = u64::MAX; + for &c in &counts { + if c > 0 { + nonzero_count += 1; + if c < min_nonzero { + min_nonzero = c; + } + } + } + if nonzero_count == 0 { + break; + } + let full_rounds = (excess / nonzero_count).min(min_nonzero as u128); + if full_rounds > 0 { + let decrement = full_rounds as u64; + for c in &mut counts { + if *c > 0 { + *c -= decrement; + } + } + excess -= full_rounds * nonzero_count; + } else { + for c in &mut counts { + if excess == 0 { + break; + } + if *c > 0 { + *c -= 1; + excess -= 1; + } + } + } + } + } else if is_basically_one && sum < num_rows_u128 && !counts.is_empty() { + // On the other hand, if the percentages sum to ~1.0 then we also shouldn't _lose_ + // rows due to rounding errors. + let deficit = num_rows_u128 - sum; + let len = counts.len() as u128; + let base_add = (deficit / len) as u64; + let rem = (deficit % len) as usize; + for (idx, count) in counts.iter_mut().enumerate() { + *count += base_add + u64::from(idx < rem); + } + } + + Ok(counts) + } + + pub(crate) fn checked_total_rows(&self, num_rows: u64) -> Result { + match self { + Self::Percentages(percentages) => { + let counts = Self::percentages_to_counts(percentages, num_rows)?; + counts + .iter() + .try_fold(0u64, |acc, &c| acc.checked_add(c)) + .ok_or_else(|| Error::InvalidInput { + message: "Split percentage counts overflowed u64".to_string(), + }) + } + Self::Counts(counts) => { + let total = counts + .iter() + .try_fold(0u64, |acc, &c| acc.checked_add(c)) + .ok_or_else(|| Error::InvalidInput { + message: "Split counts overflowed u64".to_string(), + })?; + if total > num_rows { + return Err(Error::InvalidInput { + message: format!( + "Split counts specified {} rows but only {} are available", + total, num_rows + ), + }); + } + Ok(total) + } + Self::Fixed(num_splits) => { + if *num_splits == 0 { + return Err(Error::InvalidInput { + message: "Split fixed config must specify at least 1 split".to_string(), + }); + } + Ok((num_rows / *num_splits) * *num_splits) + } + } + } + + pub(crate) fn try_to_counts(&self, num_rows: u64) -> Result> { + let sizes = match self { + Self::Percentages(percentages) => Self::percentages_to_counts(percentages, num_rows)?, + Self::Counts(counts) => { + let total = counts + .iter() + .try_fold(0u64, |acc, &c| acc.checked_add(c)) + .ok_or_else(|| Error::InvalidInput { + message: "Split counts overflowed u64".to_string(), + })?; + if total > num_rows { + return Err(Error::InvalidInput { + message: format!( + "Split counts specified {} rows but only {} are available", + total, num_rows + ), + }); + } + let mut out = Vec::::new(); + out.try_reserve_exact(counts.len()) + .map_err(|_| Error::InvalidInput { + message: format!( + "Split counts length ({}) is too large to allocate in memory", + counts.len() + ), + })?; + out.extend_from_slice(counts); + out + } + Self::Fixed(num_splits) => { + if *num_splits == 0 { + return Err(Error::InvalidInput { + message: "Split fixed config must specify at least 1 split".to_string(), + }); + } + let num_splits_usize = + usize::try_from(*num_splits).map_err(|_| Error::InvalidInput { + message: format!( + "Split fixed config specified {} splits which is too large to allocate in memory", + *num_splits + ), + })?; + let rows_per_split = num_rows / *num_splits; + let mut out = Vec::::new(); + out.try_reserve_exact(num_splits_usize) + .map_err(|_| Error::InvalidInput { + message: format!( + "Split fixed config specified {} splits which is too large to allocate in memory", + *num_splits + ), + })?; + out.resize(num_splits_usize, rows_per_split); + out + } + }; + + assert!(sizes.iter().map(|&c| c as u128).sum::() <= num_rows as u128); + + Ok(sizes) + } + pub fn to_counts(&self, num_rows: u64) -> Vec { let sizes = match self { - Self::Percentages(percentages) => { - let mut percentage_sum = 0.0_f64; - let mut counts = percentages - .iter() - .map(|p| { - let count = (p * (num_rows as f64)).round() as u64; - percentage_sum += p; - count - }) - .collect::>(); - let sum = counts.iter().sum::(); - - let is_basically_one = - (num_rows as f64 - percentage_sum * num_rows as f64).abs() < 0.5; - - // If the sum of percentages is close to 1.0 then rounding errors can add up - // to more or less than num_rows - // - // Drop items from buckets until we have the correct number of rows - let mut excess = sum as i64 - num_rows as i64; - let mut drop_idx = 0; - while excess > 0 { - if counts[drop_idx] > 0 { - counts[drop_idx] -= 1; - excess -= 1; - } - drop_idx += 1; - if drop_idx == counts.len() { - drop_idx = 0; - } - } - - // On the other hand, if the percentages sum to ~1.0 then the we also shouldn't _lose_ - // rows due to rounding errors - let mut add_idx = 0; - while is_basically_one && excess < 0 { - counts[add_idx] += 1; - add_idx += 1; - excess += 1; - if add_idx == counts.len() { - add_idx = 0; - } - } - - counts - } + Self::Percentages(percentages) => Self::percentages_to_counts(percentages, num_rows) + .expect("Split percentages allocation failed"), Self::Counts(counts) => counts.clone(), Self::Fixed(num_splits) => { let rows_per_split = num_rows / *num_splits; @@ -735,7 +957,7 @@ impl SplitSizes { } }; - assert!(sizes.iter().sum::() <= num_rows); + assert!(sizes.iter().map(|&c| c as u128).sum::() <= num_rows as u128); sizes } @@ -1168,4 +1390,189 @@ mod tests { }; assert!(err.to_string().contains("no eligible rows")); } + + #[test] + fn test_split_sizes_rejects_zero_empty_nan_and_overflow() { + assert!(matches!( + SplitSizes::Fixed(0).validate(100), + Err(Error::InvalidInput { .. }) + )); + assert!(matches!( + SplitSizes::Fixed(0).validate(0), + Err(Error::InvalidInput { .. }) + )); + assert!(matches!( + SplitSizes::Percentages(vec![]).validate(100), + Err(Error::InvalidInput { .. }) + )); + assert!(matches!( + SplitSizes::Counts(vec![]).validate(100), + Err(Error::InvalidInput { .. }) + )); + assert!(matches!( + SplitSizes::Percentages(vec![f64::NAN]).validate(100), + Err(Error::InvalidInput { .. }) + )); + assert!(matches!( + SplitSizes::Percentages(vec![0.5, f64::NAN]).validate(100), + Err(Error::InvalidInput { .. }) + )); + assert!(matches!( + SplitSizes::Percentages(vec![f64::INFINITY]).validate(100), + Err(Error::InvalidInput { .. }) + )); + assert!(matches!( + SplitSizes::Percentages(vec![f64::NEG_INFINITY]).validate(100), + Err(Error::InvalidInput { .. }) + )); + assert!(matches!( + SplitSizes::Counts(vec![u64::MAX, 1]).validate(100), + Err(Error::InvalidInput { .. }) + )); + } + + #[test] + fn test_split_strategy_rejects_zero_clump_size_and_weight_overflow() { + let random_zero_clump = SplitStrategy::Random { + seed: None, + sizes: SplitSizes::Fixed(2), + clump_size: Some(0), + }; + assert!(matches!( + random_zero_clump.validate(100), + Err(Error::InvalidInput { .. }) + )); + + let hash_weights_overflow = SplitStrategy::Hash { + columns: vec![ID_COLUMN.to_string()], + split_weights: vec![u64::MAX, 1], + discard_weight: 0, + }; + assert!(matches!( + hash_weights_overflow.validate(100), + Err(Error::InvalidInput { .. }) + )); + + let hash_discard_overflow = SplitStrategy::Hash { + columns: vec![ID_COLUMN.to_string()], + split_weights: vec![u64::MAX], + discard_weight: 1, + }; + assert!(matches!( + hash_discard_overflow.validate(100), + Err(Error::InvalidInput { .. }) + )); + } + + #[tokio::test] + async fn test_splitter_apply_rejects_invalid_configs_cleanly() { + let invalid_strategies = vec![ + SplitStrategy::Sequential { + sizes: SplitSizes::Fixed(0), + }, + SplitStrategy::Sequential { + sizes: SplitSizes::Percentages(vec![]), + }, + SplitStrategy::Sequential { + sizes: SplitSizes::Counts(vec![]), + }, + SplitStrategy::Sequential { + sizes: SplitSizes::Percentages(vec![f64::NAN]), + }, + SplitStrategy::Random { + seed: Some(42), + sizes: SplitSizes::Fixed(2), + clump_size: Some(0), + }, + ]; + + for strategy in invalid_strategies { + let splitter = Splitter::new(TemporaryDirectory::None, strategy); + let result = splitter.apply(test_data(), 50).await; + assert!(matches!(result, Err(Error::InvalidInput { .. }))); + } + } + + #[test] + fn test_split_sizes_large_boundary_counts_and_validation() { + // Rounding two 50% splits of u64::MAX produces 2^63 + 2^63 = 2^64 before + // excess adjustment, which must not overflow u64 summation or signed diff. + let half_max = SplitSizes::Percentages(vec![0.5, 0.5]).to_counts(u64::MAX); + assert_eq!(half_max.len(), 2); + assert_eq!( + half_max.iter().map(|&c| c as u128).sum::(), + u64::MAX as u128 + ); + + let above_i64_max = (i64::MAX as u64) + 10; + let large_pct = SplitSizes::Percentages(vec![0.6, 0.4]).to_counts(above_i64_max); + assert_eq!(large_pct.len(), 2); + assert!(large_pct.iter().map(|&c| c as u128).sum::() <= above_i64_max as u128); + + // Unrepresentable fixed split counts and bootstrap sample counts must be + // rejected with InvalidInput without attempting large allocations. + assert!(matches!( + SplitSizes::Fixed(u64::MAX).validate(u64::MAX), + Err(Error::InvalidInput { .. }) + )); + assert!(matches!( + SplitStrategy::Bootstrap { + num_samples: u64::MAX, + sizes: SplitSizes::Fixed(u64::MAX), + seed: Some(42), + } + .validate(10), + Err(Error::InvalidInput { .. }) + )); + assert!(matches!( + SplitStrategy::Bootstrap { + num_samples: u64::MAX, + sizes: SplitSizes::Percentages(vec![0.5, 0.5]), + seed: Some(42), + } + .validate(10), + Err(Error::InvalidInput { .. }) + )); + + // output_row_count and checked_total_rows must not allocate a Fixed split vector + // or overflow on large percentage totals. + let large_fixed_splitter = Splitter::new( + TemporaryDirectory::None, + SplitStrategy::Bootstrap { + num_samples: u64::MAX, + sizes: SplitSizes::Fixed(u64::MAX), + seed: Some(42), + }, + ); + assert_eq!(large_fixed_splitter.output_row_count(10), u64::MAX); + assert_eq!( + large_fixed_splitter.try_output_row_count(10).unwrap(), + u64::MAX + ); + + let large_pct_splitter = Splitter::new( + TemporaryDirectory::None, + SplitStrategy::Bootstrap { + num_samples: u64::MAX, + sizes: SplitSizes::Percentages(vec![0.5, 0.5]), + seed: Some(42), + }, + ); + assert_eq!(large_pct_splitter.output_row_count(10), u64::MAX); + assert_eq!( + large_pct_splitter.try_output_row_count(10).unwrap(), + u64::MAX + ); + + // Fallible count planning must return InvalidInput without attempting a large + // allocation when the split count exceeds the maximum representable Vec. + assert!(matches!( + SplitSizes::Fixed(u64::MAX).try_to_counts(u64::MAX), + Err(Error::InvalidInput { .. }) + )); + assert!(matches!( + SplitSizes::Fixed(MAX_U64_VEC_LEN + 1).try_to_counts(MAX_U64_VEC_LEN + 1), + Err(Error::InvalidInput { .. }) + )); + } }