Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 101 additions & 6 deletions rust/lance-encoding/src/decoder.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The Lance Authors

Expand Down Expand Up @@ -2364,6 +2364,40 @@
Ok(scheduled_need.min(self.rows_scheduled))
}

/// A page already loaded for the first speculative batch can hold the rest of
/// a small fragment. Reuse it only when the decoder can size the UTF-8 data.
fn initial_utf8_batch_rows(&self, original_rows: u64, byte_target: u64) -> u64 {
if !matches!(
self.root_decoder.data_type(),
DataType::Struct(fields) if fields.len() == 1 && fields[0].data_type() == &DataType::Utf8
) {
return original_rows;
}
let available_rows = (self.rows_scheduled - self.rows_drained)
.min(self.rows_remaining)
.min(self.rows_per_batch as u64);
if available_rows <= original_rows {
return original_rows;
}
let Ok(sizes) = self.root_decoder.plan_decoded_bytes(available_rows) else {
return original_rows;
};
CANDIDATE_BATCH_SIZES
.into_iter()
.zip(sizes)
.rev()
.find_map(|(candidate, bytes)| {
let rows = u64::from(candidate).min(available_rows);
// Skip all-null pages. Leave room for offset and validity buffers
// and for the allocation used to combine decoded page slices.
let fits = bytes > rows.div_ceil(8)
&& bytes <= I32_OFFSET_BYTE_BUDGET
&& bytes.saturating_mul(2).saturating_add(5 * (rows + 1)) <= byte_target;
(rows > original_rows && fits).then_some(rows)
})
.unwrap_or(original_rows)
}

#[instrument(level = "debug", skip_all)]
async fn next_batch_task(&mut self) -> Result<Option<NextDecodeTask>> {
trace!(
Expand Down Expand Up @@ -2414,6 +2448,12 @@
return Ok(None);
}

if self.has_variable_width
&& self.bytes_per_row_feedback.load(Ordering::Relaxed) == 0
&& let Some(byte_target) = self.batch_size_bytes
{
to_take = self.initial_utf8_batch_rows(to_take, byte_target);
}
let limit = StructuralFieldDecoder::max_rows_to_drain(
&self.root_decoder,
to_take,
Expand Down Expand Up @@ -4975,12 +5015,11 @@

/// Helper: encode a batch, then decode it as a stream with optional
/// `batch_size_bytes`, collecting all output batches.
async fn decode_batches_with_byte_limit(
async fn byte_limited_decode_tasks(
batch: &RecordBatch,
batch_size: u32,
batch_size_bytes: Option<u64>,
readahead: usize,
) -> Vec<RecordBatch> {
) -> BoxStream<'static, ReadBatchTask> {
use crate::{
encoder::{EncodingOptions, encode_batch},
testing::{TestEncoding, test_encoding_strategy},
Expand Down Expand Up @@ -5024,7 +5063,7 @@
io_scheduler,
);

let decode_stream = create_decode_stream(
create_decode_stream(
&encoded.schema,
encoded.num_rows,
batch_size,
Expand All @@ -5034,9 +5073,17 @@
rx,
batch_size_bytes,
)
.unwrap();
.unwrap()
}

decode_stream
async fn decode_batches_with_byte_limit(
batch: &RecordBatch,
batch_size: u32,
batch_size_bytes: Option<u64>,
readahead: usize,
) -> Vec<RecordBatch> {
byte_limited_decode_tasks(batch, batch_size, batch_size_bytes)
.await
.map(|task| task.task)
.buffered(readahead)
.try_collect()
Expand Down Expand Up @@ -5153,6 +5200,54 @@
assert!(batches.iter().all(|batch| batch.num_rows() == 100));
}

#[tokio::test]
async fn test_byte_sized_batches_reuses_loaded_narrow_utf8_page() {
let values = arrow_array::StringArray::from_iter_values(
(0..397).map(|row| format!("company-{row:035}")),
);
let input =
RecordBatch::try_from_iter([("company_id", Arc::new(values) as ArrayRef)]).unwrap();
let target_bytes = 64 * 1024;
let batches = decode_batches_with_byte_limit(&input, 8192, Some(target_bytes), 4).await;

assert_eq!(batches.len(), 1);
assert!(batches[0].column(0).get_buffer_memory_size() <= target_bytes as usize);
assert_eq!(batches[0], input);
}

#[tokio::test]
async fn test_byte_sized_batches_preserves_utf8_fallback_before_feedback() {
let long_value = "x".repeat(400);
let inputs = [
StringArray::from_iter_values((0..512).map(|_| long_value.as_str())),
StringArray::new_null(512),
];
let target_bytes = 64 * 1024;
for values in inputs {
let input =
RecordBatch::try_from_iter([("text", Arc::new(values) as ArrayRef)]).unwrap();
let tasks = byte_limited_decode_tasks(&input, 8192, Some(target_bytes))
.await
.collect::<Vec<_>>()
.await;
// Drain all tasks before polling any decode future, so no feedback is visible.
assert_eq!(tasks.len(), 4);
for task in &tasks {
assert_eq!(task.num_rows, 128);
}
let batches = futures::future::try_join_all(tasks.into_iter().map(|task| task.task))
.await
.unwrap();
assert!(
batches
.iter()
.all(|batch| batch.column(0).get_buffer_memory_size() <= target_bytes as usize)
);
let output = arrow_select::concat::concat_batches(&input.schema(), &batches).unwrap();
assert_eq!(output, input);
}
}

#[tokio::test]
async fn test_byte_sized_batches_feedback_convergence() {
use arrow_array::StringArray;
Expand Down
7 changes: 7 additions & 0 deletions rust/lance-encoding/src/encodings/logical/primitive/field.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1200,6 +1200,13 @@ impl StructuralPrimitiveFieldDecoder {
page.num_rows()
};
let take = available.min(remaining);
if matches!(self.field.data_type(), DataType::Utf8) && page.dictionary_len().is_some() {
// A dictionary-page estimate counts the dictionary once. UTF-8
// output expands its values and can require many more bytes.
return Err(lance_core::Error::not_supported(
"Cannot bound expanded UTF-8 dictionary bytes".to_string(),
));
}
total = total
.checked_add(page.decoded_bytes(take)?)
.ok_or_else(|| {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The Lance Authors

Expand Down Expand Up @@ -1275,6 +1275,7 @@
let mut need_preamble = false;
let mut skip_in_chunk = self.offset_in_current_chunk;
let mut instruction_idx = 0usize;
let mut previous_chunk_idx = None;
let mut total_bytes = 0u64;

while rows_desired > 0 || need_preamble {
Expand All @@ -1292,10 +1293,19 @@
instruction_idx += 1;
}

let chunk_idx = drain_inst.chunk_instructions.chunk_idx;
if previous_chunk_idx.replace(chunk_idx) == Some(chunk_idx) {
// Non-adjacent selections within a chunk have separate drain
// instructions. The decode builder can reserve the whole chunk
// again for each instruction, so keep the ordinary batch size.
return Err(Error::not_supported(
"Byte planning is unavailable for repeated miniblock chunks",
));
}
let chunk = self
.loaded_chunks
.iter()
.find(|chunk| chunk.chunk_idx == drain_inst.chunk_instructions.chunk_idx)
.find(|chunk| chunk.chunk_idx == chunk_idx)
.ok_or_else(|| {
Error::not_supported(
"decoded_bytes: chunk not loaded for miniblock decoder".to_string(),
Expand Down Expand Up @@ -1386,11 +1396,16 @@
"decoded_bytes is not implemented for this value decompressor".to_string(),
)
})?;
total_bytes = total_bytes.checked_add(chunk_bytes).ok_or_else(|| {
Error::not_supported(
"decoded_bytes: miniblock decoded byte count overflowed u64".to_string(),
)
})?;
// The builder may reserve twice the stored chunk size even if the
// selection uses only part of that chunk. The batch planner applies
// that factor to this bound.
total_bytes = total_bytes
.checked_add(chunk_bytes.max(chunk.data.len() as u64))
.ok_or_else(|| {
Error::not_supported(
"decoded_bytes: miniblock decoded byte count overflowed u64".to_string(),
)
})?;
}

Ok(total_bytes)
Expand Down Expand Up @@ -2823,7 +2838,7 @@
}

#[rstest::rstest]
fn test_miniblock_planned_binary_bytes_match_partial_drain(
fn test_miniblock_planned_binary_bytes_bound_partial_drain(
#[values(32, 64)] bits_per_offset: u8,
#[values(false, true)] large_header: bool,
) {
Expand All @@ -2837,6 +2852,7 @@
let slices = values.iter().map(Vec::as_slice).collect::<Vec<_>>();
let chunk_data =
miniblock_chunk(&binary_value_buffer(&slices, bits_per_offset), large_header);
let chunk_size = chunk_data.len() as u64;
let mut decoder = MiniBlockDecoder {
structural_projection: None,
rep_decompressor: None,
Expand Down Expand Up @@ -2868,7 +2884,7 @@
let first = decoder.drain(2).unwrap().decode().unwrap();
let planned = decoder.decoded_bytes(3).unwrap();
let actual = decoder.drain(3).unwrap().decode().unwrap();
assert_eq!(planned, actual.data.data_size());
assert_eq!(planned, chunk_size.max(actual.data.data_size()));
for (decoded, selected) in [(first, &values[..2]), (actual, &values[2..])] {
let data = decoded.data.as_variable_width_ref().unwrap();
let offsets = if bits_per_offset == 32 {
Expand Down
68 changes: 68 additions & 0 deletions rust/lance-file/src/reader.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The Lance Authors

Expand Down Expand Up @@ -6032,6 +6032,74 @@
assert_eq!(batches.len(), 1);
}

#[tokio::test]
async fn test_byte_sized_read_keeps_small_first_batch_for_sparse_utf8_ranges() {
let fs = FsFixture::default();
let strings =
StringArray::from_iter_values((0..8192).map(|row| format!("{row:04x}-row-{row:04x}")));
let field = Field::new("text", DataType::Utf8, false).with_metadata(HashMap::from([(
STRUCTURAL_ENCODING_META_KEY.to_string(),
STRUCTURAL_ENCODING_MINIBLOCK.to_string(),
)]));
let schema = Arc::new(ArrowSchema::new(vec![field]));
let input = RecordBatch::try_new(schema.clone(), vec![Arc::new(strings)]).unwrap();
write_lance_file(
RecordBatchIterator::new([Ok(input)], schema),
&fs,
ConcreteFileVersion::V2_2,
FileWriterOptions::default(),
)
.await;

let target = 16 * 1024 * 1024;
let reader = FileReader::try_open(
fs.scheduler
.open_file(&fs.tmp_path, &CachedFileSize::unknown())
.await
.unwrap(),
None,
Arc::<DecoderPlugins>::default(),
&test_cache(),
FileReaderOptions {
batch_size_bytes: Some(target),
..Default::default()
},
)
.await
.unwrap();
let ranges = (0..8192)
.step_by(2)
.map(|row| row..row + 1)
.collect::<Vec<_>>();
let batches = reader
.read_stream(
ReadBatchParams::Ranges(ranges.into()),
8192,
4,
FilterExpression::no_filter(),
)
.await
.unwrap()
.try_collect::<Vec<_>>()
.await
.unwrap();
let first = &batches[0];
let capacity = first.column(0).get_buffer_memory_size();
assert_eq!(
first.num_rows(),
128,
"first batch capacity was {capacity} B"
);
assert!(capacity <= target as usize);
let output = concat_batches(&batches[0].schema(), &batches).unwrap();
let expected = StringArray::from_iter_values(
(0..8192)
.step_by(2)
.map(|row| format!("{row:04x}-row-{row:04x}")),
);
assert_eq!(output.column(0).as_string::<i32>(), &expected);
}

async fn write_file_with_global_buffer(fs: &FsFixture, buffer: Bytes) {
let lance_schema =
lance_core::datatypes::Schema::try_from(&ArrowSchema::new(vec![Field::new(
Expand Down
Loading