fix(dataloader): skip oversized grouped split sorts (#5373)

A random split assigns split IDs in ascending order after shuffling.
When that produces a single large batch, DataFusion can reject the batch
before it has anything to spill. On main, a 4M-row split requests 122.1
MiB and a 6M-row split requests 183.1 MiB. The default 100 MiB pool has
90 MiB available after the merge reservation.

Write the already-grouped batch directly when that final sort cannot
admit it. Keep the existing sort when the batch fits, for multiple
shuffle runs and for an explicit shuffle after split assignment.
Document the client-side memory override and include it in
resource-exhausted sort errors.

The 11M-row multi-run case and the 4M-row explicit post-split shuffle
still need a larger budget. Both keep their exact order with the same
override. The multi-run path can interleave equal split IDs across runs,
so this patch keeps that merge behavior.

## Validation

On isolated Linux x86-64, baseline `614f8c32` and this head used
`release-with-debug`, the same Embedded fixture, seed 42, and four
alternating AB/BA repetitions per case. Each run used a fresh 4 GiB
cgroup on the same 8-vCPU EC2 instance. EOF includes permutation build
and reading all output rows. Every successful pair produced the same
ordered `(row_id, split_id)` digest and split counts. The 4M and 6M
single-run cases had zero temporary spill bytes. The 11M case used
46,046,296 temporary bytes in both arms and cleaned up after success and
failure.

| Scenario / metric (lower is better) | Baseline | This PR | Benefit |
| --- | ---: | ---: | ---: |
| 2M random splits, default / default, median EOF | 169.5 ms | 163.0 ms
| 1.04× faster |
| 2M random splits, default / default, median peak RSS | 214.7 MiB |
209.6 MiB | 1.02× lower |
| 4M random splits, override / default, median EOF | 337.5 ms | 265.0 ms
| 1.27× faster |
| 4M random splits, override / default, median peak RSS | 290.2 MiB |
243.0 MiB | 1.19× lower |
| 6M random splits, override / default, median EOF | 504.5 ms | 424.5 ms
| 1.19× faster |
| 6M random splits, override / default, median peak RSS | 357.4 MiB |
283.1 MiB | 1.26× lower |

The override is 2 GiB. The 4M and 6M baseline cases failed at the
default limit. The 6M override / override control measured 511.5 ms
versus 507.5 ms median EOF and 357.5 MiB versus 357.1 MiB median peak
RSS.

Adds a small regression that compares exact filtered split order at two
sort budgets and checks that an explicit shuffle still uses the sorter.


[OSS-3341](https://linear.app/lancedb/issue/OSS-3341/streamingdataset-permutationbuilder-fails-on-tables-over-3m-rows)
This commit is contained in:
Yang Cen
2026-12-03 10:21:28 +08:00
committed by GitHub
parent 3031e7c2c7
commit 00ead8d0b6
4 changed files with 157 additions and 22 deletions
+6
View File
@@ -80,6 +80,12 @@ To include newly appended rows, build a new `Permutation` (and any `StreamingDat
against the updated table. Permutations written before this behavior shipped continue to
read as they did before.
## Sort memory for permutation builds
The permutation sort runs on the SDK client for both Embedded and Enterprise tables. Its memory pool defaults to
100 MiB. If a permutation sort runs out of memory, set `LANCEDB_PERM_BUILDER_MEMORY_LIMIT` to a byte count in the
client environment. Shuffle buffers and the materialized permutation can use additional client memory.
## Output formats {#output-formats}
By default, a `Table` data loader emits Arrow data. `collate_fn` is PyTorch's batching hook: PyTorch calls it to
@@ -4,10 +4,12 @@
use std::{collections::HashMap, sync::Arc};
use arrow_array::RecordBatch;
use datafusion::error::DataFusionError;
use datafusion::prelude::{SessionConfig, SessionContext};
use datafusion_common::utils::memory::get_record_batch_memory_size;
use datafusion_execution::{disk_manager::DiskManagerBuilder, runtime_env::RuntimeEnvBuilder};
use datafusion_expr::col;
use futures::TryStreamExt;
use futures::{StreamExt, TryStreamExt, stream};
use lance_core::ROW_ID;
use lance_datafusion::exec::SessionContextExt;
@@ -17,7 +19,7 @@ use crate::{
connect,
database::{CreateTableMode, CreateTableRequest, Database},
dataloader::permutation::{
shuffle::{Shuffler, ShufflerConfig},
shuffle::{PERMUTATION_SHUFFLE_RUN_ROWS, Shuffler, ShufflerConfig},
split::{SPLIT_ID_COLUMN, SplitStrategy, Splitter},
util::{TemporaryDirectory, rename_column},
},
@@ -216,21 +218,48 @@ impl PermutationBuilder {
async fn sort_by_column(
&self,
data: SendableRecordBatchStream,
mut data: SendableRecordBatchStream,
column: &str,
memory_limit: usize,
ordered_single_batch: bool,
) -> Result<SendableRecordBatchStream> {
let memory_limit = std::env::var("LANCEDB_PERM_BUILDER_MEMORY_LIMIT")
.unwrap_or_else(|_| DEFAULT_MEMORY_LIMIT.to_string())
.parse::<usize>()
.unwrap_or_else(|_| {
log::error!(
"Failed to parse LANCEDB_PERM_BUILDER_MEMORY_LIMIT, using default: {}",
DEFAULT_MEMORY_LIMIT
);
DEFAULT_MEMORY_LIMIT
let config = SessionConfig::default();
if ordered_single_batch && let Some(batch) = data.try_next().await? {
let merge_reservation = match self.config.temp_dir {
TemporaryDirectory::None => 0,
_ => config.options().execution.sort_spill_reservation_bytes,
};
// This path only receives the two primitive columns from a single
// random-split run. DataFusion charges both the retained buffers and
// the size of the rows, even if a split count truncated the batch.
let logical_size = batch.columns().iter().try_fold(0usize, |size, column| {
Ok::<_, Error>(size.saturating_add(column.to_data().get_slice_memory_size()?))
});
let charge = get_record_batch_memory_size(&batch).saturating_add(logical_size?);
let schema = data.schema();
if charge > memory_limit.saturating_sub(merge_reservation) {
// Split IDs were assigned in ascending order after the shuffle.
// Write that order directly when an empty sorter cannot admit
// the batch. The writer can consume zero-copy slices.
let batch_size = config.batch_size();
let batches = (0..batch.num_rows())
.step_by(batch_size)
.map(move |offset| {
Ok(batch.slice(offset, batch_size.min(batch.num_rows() - offset)))
});
return Ok(Box::pin(SimpleRecordBatchStream::new(
stream::iter(batches).chain(data),
schema,
)));
}
data = Box::pin(SimpleRecordBatchStream::new(
stream::once(async move { Ok(batch) }).chain(data),
schema,
));
}
let ctx = SessionContext::new_with_config_rt(
SessionConfig::default(),
config,
RuntimeEnvBuilder::new()
.with_memory_limit(memory_limit, 1.0)
.with_disk_manager_builder(
@@ -261,9 +290,17 @@ impl PermutationBuilder {
let column = column.to_string();
let schema = df_stream.schema();
let stream = df_stream.map_err(move |e| Error::Other {
message: format!("Failed to execute sort by {}: {}", column, e),
source: Some(e.into()),
let stream = df_stream.map_err(move |e| {
let mut message = format!("Failed to execute sort by {}: {}", column, e);
if matches!(e.find_root(), DataFusionError::ResourcesExhausted(_)) {
message.push_str(
" Set LANCEDB_PERM_BUILDER_MEMORY_LIMIT on the client to change the sort budget in bytes.",
);
}
Error::Other {
message,
source: Some(e.into()),
}
});
Ok(Box::pin(SimpleRecordBatchStream { schema, stream }))
}
@@ -295,7 +332,21 @@ impl PermutationBuilder {
}
/// Builds the permutation table and stores it in the given database.
pub async fn build(mut self) -> Result<Table> {
pub async fn build(self) -> Result<Table> {
let memory_limit = std::env::var("LANCEDB_PERM_BUILDER_MEMORY_LIMIT")
.unwrap_or_else(|_| DEFAULT_MEMORY_LIMIT.to_string())
.parse::<usize>()
.unwrap_or_else(|_| {
log::error!(
"Failed to parse LANCEDB_PERM_BUILDER_MEMORY_LIMIT, using default: {}",
DEFAULT_MEMORY_LIMIT
);
DEFAULT_MEMORY_LIMIT
});
self.build_with_sort_memory_limit(memory_limit).await
}
async fn build_with_sort_memory_limit(mut self, memory_limit: usize) -> Result<Table> {
// Remote tables resolve latest independently for each request, and a
// native handle can refresh or answer a query from a namespace server.
// Use a separate pinned handle so count, projection, and scan all refer
@@ -369,7 +420,8 @@ impl PermutationBuilder {
let rows = if self.base_table.base_table().scan_order_is_deterministic() {
rows
} else {
self.sort_by_column(rows, ROW_ID).await?
self.sort_by_column(rows, ROW_ID, memory_limit, false)
.await?
};
let split_data = splitter.apply(rows, num_rows).await?;
@@ -381,7 +433,7 @@ impl PermutationBuilder {
seed,
clump_size,
temp_dir: self.config.temp_dir.clone(),
max_rows_per_file: 10 * 1024 * 1024,
max_rows_per_file: PERMUTATION_SHUFFLE_RUN_ROWS,
});
shuffler.shuffle(split_data, output_rows).await?
}
@@ -392,7 +444,17 @@ impl PermutationBuilder {
needs_sort |= !matches!(self.config.shuffle_strategy, ShuffleStrategy::None);
let sorted = if needs_sort {
self.sort_by_column(shuffled, SPLIT_ID_COLUMN).await?
let ordered_single_batch =
matches!(self.config.split_strategy, SplitStrategy::Random { .. })
&& matches!(self.config.shuffle_strategy, ShuffleStrategy::None)
&& num_rows < PERMUTATION_SHUFFLE_RUN_ROWS;
self.sort_by_column(
shuffled,
SPLIT_ID_COLUMN,
memory_limit,
ordered_single_batch,
)
.await?
} else {
shuffled
};
@@ -994,6 +1056,71 @@ mod tests {
);
}
#[tokio::test]
async fn test_oversized_random_split_keeps_seeded_order() {
let temp_dir = tempfile::tempdir().unwrap();
let db = connect(temp_dir.path().to_str().unwrap())
.execute()
.await
.unwrap();
let data = lance_datagen::gen_batch()
.col("value", lance_datagen::array::step::<Int32Type>())
.into_ldb_stream(RowCount::from(4096), BatchCount::from(1));
let base = db.create_table("base", data).execute().await.unwrap();
let builder = || {
PermutationBuilder::new(base.clone())
.with_split_strategy(
SplitStrategy::Random {
seed: Some(42),
sizes: SplitSizes::Counts(vec![1000, 1000, 1000]),
clump_size: None,
},
None,
)
.with_filter("value >= 8".to_string())
.with_temp_dir(TemporaryDirectory::None)
};
let read = |table: Table| async move {
let stream = table.query().execute().await.unwrap();
let schema = stream.schema();
let batches: Vec<_> = stream.try_collect().await.unwrap();
arrow::compute::concat_batches(&schema, &batches).unwrap()
};
let reference = read(
builder()
.build_with_sort_memory_limit(DEFAULT_MEMORY_LIMIT)
.await
.unwrap(),
)
.await;
let memory_limit = 64 * 1024;
let bounded = read(
builder()
.build_with_sort_memory_limit(memory_limit)
.await
.unwrap(),
)
.await;
assert_eq!(bounded.num_rows(), 3000);
assert_eq!(bounded, reference);
let error = builder()
.with_shuffle_strategy(ShuffleStrategy::Random {
seed: Some(13),
clump_size: None,
})
.build_with_sort_memory_limit(memory_limit)
.await
.unwrap_err();
assert!(
error
.to_string()
.contains("LANCEDB_PERM_BUILDER_MEMORY_LIMIT")
);
}
/// Rows that have not been flushed to the base table have no row id, so a
/// permutation cannot reference them. Reading the base table alone would drop
/// them from training without saying so, so the table is refused instead.
@@ -28,6 +28,8 @@ use crate::{
dataloader::permutation::util::{TemporaryDirectory, non_crypto_rng},
};
pub(super) const PERMUTATION_SHUFFLE_RUN_ROWS: u64 = 10 * 1024 * 1024;
#[derive(Debug, Clone)]
pub struct ShufflerConfig {
/// An optional seed to make the shuffle deterministic
@@ -19,7 +19,7 @@ use crate::{
Error, Result,
arrow::{SendableRecordBatchStream, SimpleRecordBatchStream},
dataloader::{
permutation::shuffle::{Shuffler, ShufflerConfig},
permutation::shuffle::{PERMUTATION_SHUFFLE_RUN_ROWS, Shuffler, ShufflerConfig},
permutation::util::{TemporaryDirectory, non_crypto_rng},
},
query::{Query, QueryBase, Select},
@@ -531,7 +531,7 @@ impl Splitter {
let shuffler = Shuffler::new(ShufflerConfig {
seed: *seed,
// In this case we are only shuffling row ids so we can use a large max_rows_per_file
max_rows_per_file: 10 * 1024 * 1024,
max_rows_per_file: PERMUTATION_SHUFFLE_RUN_ROWS,
temp_dir: self.temp_dir.clone(),
clump_size: *clump_size,
});