fix(s3select): bound uncompressed record sizes and decoding

Apply RecordSizeTracker (MAX_SELECT_RECORD_BYTES) across uncompressed plain, ScanRange, and ScanRange header reads in EcObjectStore, recognizing CR, LF, and CRLF line endings for default CSV inputs without a custom RecordDelimiter.

Bound session batch sizes and disable batch coalescing for CSV and JSON Lines, replace DataFusion's unbounded stock listing table scan with a byte-bounded, memory-pool-accounted DelimitedSelectTable, keep multi-record JSON Lines schema sampling within the session memory pool budget, and add a StreamFilterOutput physical optimizer rule so FilterExec streams filtered batches without re-coalescing.

Refs: rustfs/backlog#3348
This commit is contained in:
overtrue
2026-11-26 09:42:48 +08:00
parent 11c6203988
commit 76308ae4e1
9 changed files with 1616 additions and 139 deletions
+149 -68
View File
@@ -20,8 +20,9 @@ use async_compression::tokio::bufread::BzDecoder;
use bytes::{Buf as _, Bytes};
use datafusion::object_store::{Error as ObjectStoreError, Result as ObjectStoreResult};
use flate2::bufread::GzDecoder;
use futures::{StreamExt, stream};
use futures::{Stream, StreamExt, TryStreamExt as _, stream};
use futures_core::stream::BoxStream;
use memchr::{memchr, memchr2};
use std::{
error::Error as StdError,
io::{self, BufRead as _, Read as _},
@@ -356,7 +357,8 @@ impl io::Read for BlockingChannelReader {
}
}
pub(crate) fn compressed_input_stream(
#[cfg(test)]
fn compressed_input_stream(
reader: SelectInputReader,
compressed_size: u64,
format: CompressionFormat,
@@ -366,22 +368,58 @@ pub(crate) fn compressed_input_stream(
query_guard: Option<QueryExecutionGuard>,
) -> ObjectStoreResult<BoxStream<'static, ObjectStoreResult<Bytes>>> {
let record_size = RecordSizeTracker::new(record_delimiter).map_err(select_object_store_error)?;
compressed_input_stream_with_tracker(
reader,
compressed_size,
format,
input_metrics,
record_size,
max_processed_bytes,
query_guard,
)
}
pub(crate) fn compressed_input_stream_with_tracker(
reader: SelectInputReader,
compressed_size: u64,
format: CompressionFormat,
input_metrics: Arc<SelectInputMetrics>,
record_size: RecordSizeTracker,
max_processed_bytes: u64,
query_guard: Option<QueryExecutionGuard>,
) -> ObjectStoreResult<BoxStream<'static, ObjectStoreResult<Bytes>>> {
let reader = compressed_input_reader(reader, compressed_size, format, input_metrics, max_processed_bytes, query_guard);
let stream = ReaderStream::with_capacity(reader, SELECT_DECODE_CHUNK_BYTES);
Ok(stream::try_unfold((stream, record_size), |(mut stream, mut record_size)| async move {
let stream = ReaderStream::with_capacity(reader, SELECT_DECODE_CHUNK_BYTES).map_err(input_io_error);
Ok(record_size_limited_stream(stream, record_size, select_object_store_error))
}
/// Fails the stream with `OverMaxRecordSize` once a record exceeds
/// `MAX_SELECT_RECORD_BYTES`. The `ScanRange` splitter and the Arrow decoders
/// buffer whole records, so every CSV and JSON Lines input path applies it,
/// compressed or uncompressed.
pub(crate) fn record_size_limited_stream<S, E>(
stream: S,
record_size: RecordSizeTracker,
map_error: fn(SelectError) -> E,
) -> BoxStream<'static, Result<Bytes, E>>
where
S: Stream<Item = Result<Bytes, E>> + Send + 'static,
E: Send + 'static,
{
stream::try_unfold((stream.boxed(), record_size), move |(mut stream, mut record_size)| async move {
match stream.next().await {
Some(Ok(bytes)) => {
record_size.observe(&bytes).map_err(select_object_store_error)?;
record_size.observe(&bytes).map_err(map_error)?;
Ok(Some((bytes, (stream, record_size))))
}
Some(Err(error)) => Err(input_io_error(error)),
Some(Err(error)) => Err(error),
None => {
record_size.finish().map_err(select_object_store_error)?;
record_size.finish().map_err(map_error)?;
Ok(None)
}
}
})
.boxed())
.boxed()
}
pub(crate) fn input_io_error(source: io::Error) -> ObjectStoreError {
@@ -395,7 +433,7 @@ pub(crate) fn input_io_error(source: io::Error) -> ObjectStoreError {
}
}
fn select_object_store_error(source: SelectError) -> ObjectStoreError {
pub(crate) fn select_object_store_error(source: SelectError) -> ObjectStoreError {
ObjectStoreError::Generic {
store: "EcObjectStore",
source: Box::new(source),
@@ -657,84 +695,127 @@ pub(crate) fn find_error_source<'a, T: StdError + 'static>(error: &'a (dyn StdEr
None
}
struct RecordSizeTracker {
delimiter: Vec<u8>,
prefix: Vec<usize>,
enum RecordDelimiterMatcher {
/// Default CSV line endings (`\r`, `\n`, or `\r\n`) when no custom `RecordDelimiter` is configured.
DefaultCsvLineEnding,
SingleByte(u8),
MultiByte {
delimiter: Vec<u8>,
prefix: Vec<usize>,
matched: usize,
},
}
pub(crate) struct RecordSizeTracker {
matcher: RecordDelimiterMatcher,
record_bytes: usize,
matched: usize,
}
impl RecordSizeTracker {
fn new(delimiter: Vec<u8>) -> Result<Self, SelectError> {
pub(crate) fn default_csv() -> Self {
Self {
matcher: RecordDelimiterMatcher::DefaultCsvLineEnding,
record_bytes: 0,
}
}
pub(crate) fn new(delimiter: Vec<u8>) -> Result<Self, SelectError> {
if delimiter.is_empty() {
return Err(SelectError::InvalidDataSource);
}
let mut prefix = vec![0; delimiter.len()];
let mut matched = 0;
for index in 1..delimiter.len() {
while matched > 0 && delimiter[index] != delimiter[matched] {
matched = prefix[matched - 1];
let matcher = if delimiter.len() == 1 {
RecordDelimiterMatcher::SingleByte(delimiter[0])
} else {
let mut prefix = vec![0; delimiter.len()];
let mut matched = 0;
for index in 1..delimiter.len() {
while matched > 0 && delimiter[index] != delimiter[matched] {
matched = prefix[matched - 1];
}
if delimiter[index] == delimiter[matched] {
matched += 1;
}
prefix[index] = matched;
}
if delimiter[index] == delimiter[matched] {
matched += 1;
RecordDelimiterMatcher::MultiByte {
delimiter,
prefix,
matched: 0,
}
prefix[index] = matched;
}
};
Ok(Self {
delimiter,
prefix,
matcher,
record_bytes: 0,
matched: 0,
})
}
fn observe(&mut self, bytes: &[u8]) -> Result<(), SelectError> {
if self.delimiter.len() == 1 {
return self.observe_single_byte_delimiter(bytes);
}
for &byte in bytes {
self.record_bytes = self.record_bytes.checked_add(1).ok_or(SelectError::OverMaxRecordSize)?;
while self.matched > 0 && byte != self.delimiter[self.matched] {
self.matched = self.prefix[self.matched - 1];
}
if byte == self.delimiter[self.matched] {
self.matched += 1;
}
if self.matched == self.delimiter.len() {
let payload_bytes = self.record_bytes - self.delimiter.len();
if payload_bytes > MAX_SELECT_RECORD_BYTES {
fn observe(&mut self, mut bytes: &[u8]) -> Result<(), SelectError> {
match &mut self.matcher {
RecordDelimiterMatcher::DefaultCsvLineEnding => {
while let Some(index) = memchr2(b'\r', b'\n', bytes) {
let payload_bytes = self.record_bytes.checked_add(index).ok_or(SelectError::OverMaxRecordSize)?;
if payload_bytes > MAX_SELECT_RECORD_BYTES {
return Err(SelectError::OverMaxRecordSize);
}
self.record_bytes = 0;
bytes = &bytes[index + 1..];
}
self.record_bytes = self
.record_bytes
.checked_add(bytes.len())
.ok_or(SelectError::OverMaxRecordSize)?;
if self.record_bytes > MAX_SELECT_RECORD_BYTES {
return Err(SelectError::OverMaxRecordSize);
}
self.record_bytes = 0;
self.matched = 0;
} else if self.record_bytes - self.matched > MAX_SELECT_RECORD_BYTES {
return Err(SelectError::OverMaxRecordSize);
Ok(())
}
RecordDelimiterMatcher::SingleByte(delimiter) => {
let delimiter = *delimiter;
while let Some(index) = memchr(delimiter, bytes) {
let payload_bytes = self.record_bytes.checked_add(index).ok_or(SelectError::OverMaxRecordSize)?;
if payload_bytes > MAX_SELECT_RECORD_BYTES {
return Err(SelectError::OverMaxRecordSize);
}
self.record_bytes = 0;
bytes = &bytes[index + 1..];
}
self.record_bytes = self
.record_bytes
.checked_add(bytes.len())
.ok_or(SelectError::OverMaxRecordSize)?;
if self.record_bytes > MAX_SELECT_RECORD_BYTES {
return Err(SelectError::OverMaxRecordSize);
}
Ok(())
}
RecordDelimiterMatcher::MultiByte {
delimiter,
prefix,
matched,
} => {
for &byte in bytes {
self.record_bytes = self.record_bytes.checked_add(1).ok_or(SelectError::OverMaxRecordSize)?;
while *matched > 0 && byte != delimiter[*matched] {
*matched = prefix[*matched - 1];
}
if byte == delimiter[*matched] {
*matched += 1;
}
if *matched == delimiter.len() {
let payload_bytes = self.record_bytes - delimiter.len();
if payload_bytes > MAX_SELECT_RECORD_BYTES {
return Err(SelectError::OverMaxRecordSize);
}
self.record_bytes = 0;
*matched = 0;
} else if self.record_bytes - *matched > MAX_SELECT_RECORD_BYTES {
return Err(SelectError::OverMaxRecordSize);
}
}
Ok(())
}
}
Ok(())
}
fn observe_single_byte_delimiter(&mut self, mut bytes: &[u8]) -> Result<(), SelectError> {
let delimiter = self.delimiter[0];
while let Some(index) = bytes.iter().position(|byte| *byte == delimiter) {
let payload_bytes = self.record_bytes.checked_add(index).ok_or(SelectError::OverMaxRecordSize)?;
if payload_bytes > MAX_SELECT_RECORD_BYTES {
return Err(SelectError::OverMaxRecordSize);
}
self.record_bytes = 0;
bytes = &bytes[index + 1..];
}
self.record_bytes = self
.record_bytes
.checked_add(bytes.len())
.ok_or(SelectError::OverMaxRecordSize)?;
if self.record_bytes > MAX_SELECT_RECORD_BYTES {
return Err(SelectError::OverMaxRecordSize);
}
Ok(())
}
fn finish(&self) -> Result<(), SelectError> {
+197 -22
View File
@@ -22,8 +22,9 @@ use crate::{
SelectInputMetrics, SelectObjectOptions, SelectObjectSnapshot, SelectObjectSnapshotReadError, SelectStorageError,
SelectStore, SnapshotConsistencyError,
input_stream::{
CompressionFormat, SELECT_DECODE_CHUNK_BYTES, compressed_input_reader, compressed_input_stream, input_io_error,
processed_bytes_limit,
CompressionFormat, MAX_SELECT_RECORD_BYTES, RecordSizeTracker, SELECT_DECODE_CHUNK_BYTES, compressed_input_reader,
compressed_input_stream_with_tracker, input_io_error, processed_bytes_limit, record_size_limited_stream,
select_object_store_error,
},
query::{
ast::{JsonPathSegment, JsonSource},
@@ -346,6 +347,37 @@ impl EcObjectStore {
.unwrap_or_else(|| b"\n".to_vec())
}
fn record_size_tracker(&self) -> Result<RecordSizeTracker> {
if let Some(csv) = self.input.request.input_serialization.csv.as_ref() {
if csv.record_delimiter.is_none() {
return Ok(RecordSizeTracker::default_csv());
}
return RecordSizeTracker::new(self.record_delimiter()).map_err(select_object_store_error);
}
RecordSizeTracker::new(b"\n".to_vec()).map_err(select_object_store_error)
}
/// Applies the 1 MiB record size limit to uncompressed CSV and JSON Lines input,
/// matching compressed input enforcement.
fn limit_record_size<S>(&self, stream: S) -> Result<BoxStream<'static, Result<Bytes>>>
where
S: Stream<Item = Result<Bytes>> + Send + 'static,
{
if self
.input
.request
.input_serialization
.csv
.as_ref()
.is_some_and(|csv| csv.allow_quoted_record_delimiter.unwrap_or(false))
{
// The CSV normalizer owns logical-record limits.
return Ok(stream.boxed());
}
let record_size = self.record_size_tracker()?;
Ok(record_size_limited_stream(stream, record_size, select_object_store_error))
}
fn record_delimiter_for_conversion(&self) -> Option<Vec<u8>> {
let delimiter = self.record_delimiter();
(self.need_convert || (delimiter.len() == 2 && delimiter != NORMALIZED_RECORD_DELIMITER)).then_some(delimiter)
@@ -468,16 +500,22 @@ impl EcObjectStore {
return Ok(Bytes::new());
}
let mut end = select_default_read_buffer_size_u64().min(object_size);
let max_probe = u64::try_from(MAX_SELECT_RECORD_BYTES.saturating_add(delimiter.len())).unwrap_or(u64::MAX);
let mut end = select_default_read_buffer_size_u64().min(object_size).min(max_probe);
loop {
let bytes = self.read_raw_range(0..end).await?;
if let Some(pos) = find_delimiter(&bytes, delimiter) {
let header_end = find_delimiter(&bytes, delimiter);
// Stop widening the read once the header cannot fit the 1 MiB record limit.
if header_end.unwrap_or(bytes.len()) > MAX_SELECT_RECORD_BYTES {
return Err(select_object_store_error(SelectError::OverMaxRecordSize));
}
if let Some(pos) = header_end {
return Ok(bytes.slice(0..pos + delimiter.len()));
}
if end == object_size {
return Ok(bytes);
}
end = end.saturating_mul(2).min(object_size);
end = end.saturating_mul(2).min(object_size).min(max_probe);
}
}
@@ -973,17 +1011,13 @@ impl ObjectStore for EcObjectStore {
let stream = ReaderStream::with_capacity(reader, SELECT_DECODE_CHUNK_BYTES).map_err(input_io_error);
GetResultPayload::Stream(self.convert_csv_stream(stream))
} else {
let input_record_delimiter = if self.input.request.input_serialization.csv.is_some() {
self.record_delimiter()
} else {
b"\n".to_vec()
};
let stream = compressed_input_stream(
let record_size = self.record_size_tracker()?;
let stream = compressed_input_stream_with_tracker(
reader.stream,
original_size,
compression,
Arc::clone(&self.input_metrics),
input_record_delimiter,
record_size,
max_processed_bytes,
query_guard,
)?;
@@ -1023,10 +1057,17 @@ impl ObjectStore for EcObjectStore {
} else {
None
};
// The ScanRange splitter buffers each record up to its delimiter, so the
// record size limit has to come first.
let record_size = RecordSizeTracker::new(delimiter.clone()).map_err(select_object_store_error)?;
let stream = scan_range_stream(
meter_uncompressed_input_stream(
ReaderStream::with_capacity(reader.stream, SELECT_DEFAULT_READ_BUFFER_SIZE),
Arc::clone(&self.input_metrics),
record_size_limited_stream(
meter_uncompressed_input_stream(
ReaderStream::with_capacity(reader.stream, SELECT_DEFAULT_READ_BUFFER_SIZE),
Arc::clone(&self.input_metrics),
),
record_size,
|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error),
),
delimiter,
scan_range,
@@ -1050,6 +1091,7 @@ impl ObjectStore for EcObjectStore {
let stream = bytes_stream(ReaderStream::with_capacity(reader.stream, SELECT_DEFAULT_READ_BUFFER_SIZE), stream_size);
if meter_input {
let stream = meter_uncompressed_input_stream(stream, Arc::clone(&self.input_metrics));
let stream = self.limit_record_size(stream)?;
let stream = self.convert_csv_stream(stream);
GetResultPayload::Stream(stream)
} else {
@@ -1273,13 +1315,7 @@ where
Some(Ok(bytes)) => state.push_chunk(&bytes),
Some(Err(err)) => {
state.done = true;
return Some((
Err(o_Error::Generic {
store: "EcObjectStore",
source: Box::new(err),
}),
state,
));
return Some((Err(input_io_error(err)), state));
}
None => {
if state.offset < state.expected_end {
@@ -3262,6 +3298,145 @@ mod test {
}
}
#[tokio::test]
async fn uncompressed_input_enforces_the_record_size_limit() {
const BUCKET: &str = "select-uncompressed-record-limit";
let env = crate::storage_api::select_test_ecstore_env().await;
env.make_bucket(BUCKET, false).await;
// (JSON Lines, ScanRange, ScanRange starting after CSV header)
let cases = [
(false, false, false),
(false, true, false),
(false, true, true),
(true, false, false),
(true, true, false),
];
for (json, scan_range, after_header) in cases {
for size in [MAX_SELECT_RECORD_BYTES, MAX_SELECT_RECORD_BYTES + 1] {
let mut data = if json {
let mut record = br#"{"v":""#.to_vec();
record.resize(size - 2, b'a');
record.extend_from_slice(b"\"}");
record
} else {
vec![b'a'; size]
};
data.push(b'\n');
if after_header {
data.extend_from_slice(b"1\n");
}
let object = format!("{json}-{scan_range}-{after_header}-{size}");
let mut reader = SelectPutObjReader::from_vec(data.clone());
env.ecstore
.put_object(BUCKET, &object, &mut reader, &Default::default())
.await
.expect("write record limit fixture");
let mut input = if json {
(*json_input(BUCKET, &object, JsonType::LINES)).clone()
} else {
(*csv_input(BUCKET, &object)).clone()
};
if after_header {
let csv = input.request.input_serialization.csv.as_mut().expect("CSV input");
csv.file_header_info = Some(FileHeaderInfo::USE);
}
if scan_range {
let start = if after_header { size + 1 } else { 0 };
input.request.scan_range = Some(ScanRange {
start: Some(i64::try_from(start).expect("fixture offset")),
end: Some(i64::try_from(start + 1).expect("fixture offset")),
});
}
let store = EcObjectStore::build_with_snapshot(
Arc::new(input),
Arc::new(GreedyMemoryPool::new(4 * MAX_SELECT_RECORD_BYTES)),
None,
Arc::new(SelectInputMetrics::default()),
prepare_test_snapshot(BUCKET, &object).await,
JsonSource::default(),
)
.expect("record limit store");
let output = match store.get_opts(&Path::from(object.as_str()), GetOptions::default()).await {
Ok(result) => {
let GetResultPayload::Stream(stream) = result.payload else { panic!("uncompressed stream") };
stream.try_collect::<Vec<_>>().await
}
Err(error) => Err(error),
};
if size > MAX_SELECT_RECORD_BYTES {
let error = output.expect_err("uncompressed records over 1 MiB must fail like compressed ones");
assert_eq!(
QueryError::from(DataFusionError::from(error)).select_error(),
SelectError::OverMaxRecordSize,
"object={object}"
);
} else {
assert_eq!(output.expect("records within the limit must pass").concat(), data, "object={object}");
}
}
}
}
#[tokio::test]
async fn default_csv_record_limit_handles_cr_only_line_endings() {
const BUCKET: &str = "select-cr-only-csv-limit";
let env = crate::storage_api::select_test_ecstore_env().await;
env.make_bucket(BUCKET, false).await;
let valid_cr_csv = format!("a,b\r{}", format!("{},val\r", "x".repeat(95)).repeat(15_000)).into_bytes();
assert!(
valid_cr_csv.len() > MAX_SELECT_RECORD_BYTES,
"fixture must span more than 1 MiB across CR-only records"
);
let mut oversized_cr_csv = vec![b'a'; MAX_SELECT_RECORD_BYTES + 1];
oversized_cr_csv.push(b'\r');
for compression in [None, Some(CompressionFormat::Gzip)] {
for (name, raw, should_fail) in [("valid-cr", &valid_cr_csv, false), ("oversized-cr", &oversized_cr_csv, true)] {
let bytes = match compression {
Some(format) => encode_compressed_fixture(format, raw).await,
None => raw.clone(),
};
let object = format!("{name}-{compression:?}");
let mut reader = SelectPutObjReader::from_vec(bytes);
env.ecstore
.put_object(BUCKET, &object, &mut reader, &Default::default())
.await
.expect("write CR CSV fixture");
let mut input = (*csv_input(BUCKET, &object)).clone();
input.request.input_serialization.compression_type = compression.map(|format| match format {
CompressionFormat::Gzip => CompressionType::GZIP,
CompressionFormat::Bzip2 => CompressionType::BZIP2,
});
let store = EcObjectStore::build_with_snapshot(
Arc::new(input),
Arc::new(GreedyMemoryPool::new(4 * MAX_SELECT_RECORD_BYTES)),
None,
Arc::new(SelectInputMetrics::default()),
prepare_test_snapshot(BUCKET, &object).await,
JsonSource::default(),
)
.expect("CR CSV store");
let result = store
.get_opts(&Path::from(object.as_str()), GetOptions::default())
.await
.expect("open CR CSV stream");
let GetResultPayload::Stream(stream) = result.payload else { panic!("CSV stream") };
let output = stream.try_collect::<Vec<_>>().await;
if should_fail {
let error = output.expect_err("oversized CR-only record must fail");
assert_eq!(
QueryError::from(DataFusionError::from(error)).select_error(),
SelectError::OverMaxRecordSize,
"object={object}"
);
} else {
assert_eq!(output.expect("valid CR-only CSV over 1 MiB must pass").concat(), *raw, "object={object}");
}
}
}
}
#[tokio::test]
async fn quoted_record_delimiters_preserve_compressed_crlf_size_boundaries() {
use crate::input_stream::MAX_SELECT_RECORD_BYTES;
+36 -14
View File
@@ -441,12 +441,20 @@ impl SessionCtxFactory {
};
let rt = RuntimeEnvBuilder::new().with_memory_limit(memory_limit_bytes, 1.0).build()?;
let config = SessionConfig::new().with_target_partitions(self.target_partitions);
// Arrow CSV reserves two usize offsets for every cell outside the
// DataFusion memory pool. Bound that reservation to at most 4 MiB and
// one sixteenth of the configured query budget, including narrow input.
let config = if context.input.request.input_serialization.csv.is_some() {
// Bound decoder batch rows for CSV and JSON Lines to match the configured
// query budget, and disable batch coalescing across S3 Select formats so
// downstream operators cannot re-buffer unbounded batches outside the pool.
let config = if context.input.request.input_serialization.csv.is_some()
|| (context.input.request.input_serialization.json.is_some() && !is_json_document_input(&context.input))
{
let batch_rows = (memory_limit_bytes / 16 / (MAX_SELECT_COLUMNS * 2 * size_of::<usize>())).clamp(1, 256);
config.with_batch_size(batch_rows)
let mut config = config.with_batch_size(batch_rows);
config.options_mut().execution.coalesce_batches = false;
config
} else if is_json_document_input(&context.input) {
let mut config = config;
config.options_mut().execution.coalesce_batches = false;
config
} else {
config
};
@@ -1035,12 +1043,26 @@ mod tests {
#[tokio::test]
async fn decoder_batch_budgets_keep_parquet_downstream_execution_single_row() {
let factory = SessionCtxFactory::new(true);
for (budget, expected) in [(64 * 1024 * 1024, 256), (8 * 1024 * 1024, 32), (1024, 1)] {
let session = factory
.create_session_ctx_inner(&test_context(), None, JsonSource::default(), None, None, budget)
.await
.expect("CSV session");
assert_eq!(session.inner().config().batch_size(), expected);
for json_lines in [false, true] {
let mut context = test_context();
if json_lines {
let input = Arc::make_mut(&mut context.input);
input.request.input_serialization.csv = None;
input.request.input_serialization.json = Some(JsonInput {
r#type: Some(JsonType::LINES),
});
}
for (budget, expected) in [(64 * 1024 * 1024, 256), (8 * 1024 * 1024, 32), (1024, 1)] {
let session = factory
.create_session_ctx_inner(&context, None, JsonSource::default(), None, None, budget)
.await
.expect("delimited session");
assert_eq!(session.inner().config().batch_size(), expected, "json_lines={json_lines}");
assert!(
!session.inner().config().options().execution.coalesce_batches,
"coalesce_batches must be disabled for json_lines={json_lines}"
);
}
}
for parquet in [false, true] {
let mut context = test_context();
@@ -1050,16 +1072,16 @@ mod tests {
input.request.input_serialization.parquet = Some(ParquetInput::default());
} else {
input.request.input_serialization.json = Some(JsonInput {
r#type: Some(JsonType::LINES),
r#type: Some(JsonType::DOCUMENT),
});
}
let session = factory.create_session_ctx(&context).await.expect("non-CSV session");
let session = factory.create_session_ctx(&context).await.expect("non-delimited session");
assert_eq!(
session.inner().config().batch_size(),
if parquet { 1 } else { SessionConfig::new().batch_size() }
);
assert!(!session.inner().config().options().execution.coalesce_batches);
if parquet {
assert!(!session.inner().config().options().execution.coalesce_batches);
assert_eq!(session.inner().config().target_partitions(), 1);
}
}
File diff suppressed because it is too large Load Diff
@@ -637,7 +637,7 @@ impl Stream for JsonDocumentBatchStream {
}
}
fn json_decoder_layout(schema: &SchemaRef, requested_batch_size: usize) -> DFResult<(usize, usize)> {
pub(super) fn json_decoder_layout(schema: &SchemaRef, requested_batch_size: usize) -> DFResult<(usize, usize)> {
let fields = schema.flattened_fields().len();
let field_slots = fields.checked_mul(2).ok_or_else(decoder_resource_error)?;
let offset_bytes_per_row = field_slots
+101 -27
View File
@@ -28,8 +28,8 @@ use datafusion::{
record_batch::RecordBatch,
},
datasource::{
file_format::{DEFAULT_SCHEMA_INFER_MAX_RECORD, csv::CsvFormat, json::JsonFormat},
listing::{ListingOptions, ListingTable, ListingTableConfig, ListingTableUrl},
file_format::{DEFAULT_SCHEMA_INFER_MAX_RECORD, csv::CsvFormat},
listing::ListingTableUrl,
},
error::{DataFusionError, Result as DFResult},
execution::{RecordBatchStream, SendableRecordBatchStream},
@@ -62,7 +62,12 @@ use tokio::{
};
use crate::{
dispatcher::{json_document_table::JsonDocumentTable, json_lines_schema, parquet_table::ParquetSelectTable},
dispatcher::{
delimited_table::{DelimitedFormat, DelimitedSelectTable},
json_document_table::JsonDocumentTable,
json_lines_schema,
parquet_table::ParquetSelectTable,
},
execution::factory::QueryExecutionFactoryRef,
instance::{DEFAULT_MAX_CONCURRENT_QUERIES, DEFAULT_QUERY_TIMEOUT_SECS},
metadata::{MetadataProvider, TableHandleProviderRef, base_table::BaseTableProvider},
@@ -75,7 +80,6 @@ use super::schema_inference::{PrefixBoundary, infer_csv_schema, read_schema_pref
static IGNORE: LazyLock<FileHeaderInfo> = LazyLock::new(|| FileHeaderInfo::IGNORE);
static NONE: LazyLock<FileHeaderInfo> = LazyLock::new(|| FileHeaderInfo::NONE);
static USE: LazyLock<FileHeaderInfo> = LazyLock::new(|| FileHeaderInfo::USE);
const EXACT_OBJECT_FILE_EXTENSION: &str = "";
#[derive(Clone)]
pub struct SimpleQueryDispatcher {
@@ -447,7 +451,7 @@ impl SimpleQueryDispatcher {
let path = format!("s3://{}/{}", self.input.bucket, self.input.key);
let table_path = ListingTableUrl::parse(path)?;
let mut csv_format = None;
let (listing_options, need_rename_volume_name, need_ignore_volume_name) =
let (format, need_rename_volume_name, need_ignore_volume_name) =
if let Some(csv) = self.input.request.input_serialization.csv.as_ref() {
let mut need_rename_volume_name = false;
let mut need_ignore_volume_name = false;
@@ -509,19 +513,11 @@ impl SimpleQueryDispatcher {
.with_comment(None)
.with_newlines_in_values(true);
}
csv_format = Some(CsvFormat::default().with_options(file_format.options().clone()));
(
ListingOptions::new(Arc::new(file_format)).with_file_extension(EXACT_OBJECT_FILE_EXTENSION),
need_rename_volume_name,
need_ignore_volume_name,
)
let options = file_format.options().clone();
csv_format = Some(CsvFormat::default().with_options(options.clone()));
(DelimitedFormat::Csv(Box::new(options)), need_rename_volume_name, need_ignore_volume_name)
} else if self.input.request.input_serialization.json.is_some() {
let file_format = JsonFormat::default();
(
ListingOptions::new(Arc::new(file_format)).with_file_extension(EXACT_OBJECT_FILE_EXTENSION),
false,
false,
)
(DelimitedFormat::JsonLines, false, false)
} else {
return Err(SelectError::InvalidDataSource.into());
};
@@ -559,7 +555,7 @@ impl SimpleQueryDispatcher {
Ok(schema)
})
.await?;
let config = if need_rename_volume_name {
let schema = if need_rename_volume_name {
let mut new_fields = Vec::new();
for (i, field) in resolve_schema.fields().iter().enumerate() {
let f_name = field.name();
@@ -574,17 +570,12 @@ impl SimpleQueryDispatcher {
new_fields.push(mut_field);
}
}
let new_schema = Arc::new(Schema::new(new_fields).with_metadata(resolve_schema.metadata().clone()));
ListingTableConfig::new(table_path)
.with_listing_options(listing_options)
.with_schema(new_schema)
Arc::new(Schema::new(new_fields).with_metadata(resolve_schema.metadata().clone()))
} else {
ListingTableConfig::new(table_path)
.with_listing_options(listing_options)
.with_schema(resolve_schema)
resolve_schema
};
// rename default
let provider = Arc::new(ListingTable::try_new(config)?);
let provider =
DelimitedSelectTable::try_new(session.inner(), table_path.object_store(), &self.input.key, schema, format).await?;
let current_session_table_provider = self.build_table_handle_provider()?;
let metadata_provider =
MetadataProvider::new(provider, current_session_table_provider, self.func_manager.clone(), session.clone());
@@ -2049,6 +2040,89 @@ mod tests {
assert_eq!(field_names(batches[0].schema().fields()), ["z", "a"]);
}
#[tokio::test]
async fn delimited_input_stays_within_tight_memory_budget_and_enforces_record_limit() {
const TIGHT_MEMORY_LIMIT_BYTES: usize = 8 * 1024 * 1024;
const RECORDS: usize = 64;
let line = "x".repeat(256 * 1024);
// 64 rows * 128 KiB = 8 MiB CSV payload processed with a WHERE filter under an 8 MiB pool.
let csv_records = format!("id,name\n{}", format!("1,{}\n", &line[..line.len() / 2]).repeat(RECORDS));
// 64 rows * 128 KiB = 8 MiB JSON Lines payload processed with a WHERE filter under an 8 MiB pool.
let json_records = format!("{{\"id\":\"1\",\"name\":\"{}\"}}\n", &line[..line.len() / 2]).repeat(RECORDS);
// Oversized single uncompressed records (> 1 MiB) must fail with OverMaxRecordSize.
let oversized_csv = format!("id,name\n1,{}\n", "x".repeat(1024 * 1024 + 1));
let oversized_json = format!("{{\"id\":\"1\",\"name\":\"{}\"}}\n", "x".repeat(1024 * 1024));
// Logical quoted CSV record spanning 64 * 256 KiB = 16 MiB must fail under the 8 MiB pool.
let oversized_quoted_csv = format!("id,name\n1,\"{}\"\n", [line.as_str(); RECORDS].join("\n"));
let cases = [
(csv_records, false, TIGHT_MEMORY_LIMIT_BYTES, Ok(RECORDS)),
(json_records, true, TIGHT_MEMORY_LIMIT_BYTES, Ok(RECORDS)),
(
oversized_csv,
false,
DEFAULT_S3SELECT_MEMORY_LIMIT_BYTES,
Err(SelectError::OverMaxRecordSize),
),
(
oversized_json,
true,
DEFAULT_S3SELECT_MEMORY_LIMIT_BYTES,
Err(SelectError::OverMaxRecordSize),
),
(oversized_quoted_csv, false, TIGHT_MEMORY_LIMIT_BYTES, Err(SelectError::ResourceExhausted)),
// Valid large JSON Lines object (120 * 70 KiB = ~8.4 MiB) must succeed under the default 64 MiB limit.
(
format!("{{\"id\":\"1\",\"name\":\"{}\"}}\n", "x".repeat(70_000)).repeat(120),
true,
DEFAULT_S3SELECT_MEMORY_LIMIT_BYTES,
Ok(120),
),
];
let env = snapshot_test_env().await;
for (index, (data, json, memory_limit, expected)) in cases.into_iter().enumerate() {
let mut input = test_input();
input.bucket = format!("select-delimited-budget-{index}");
input.key = "records".to_owned();
if json {
input.request.input_serialization.csv = None;
input.request.input_serialization.json = Some(JsonInput {
r#type: Some(JsonType::LINES),
});
}
env.make_bucket(&input.bucket, false).await;
env.put_object_bytes(&input.bucket, &input.key, data.into_bytes()).await;
let snapshot = env.prepare_select_object_snapshot(&input.bucket, &input.key).await;
let input = Arc::new(input);
let optimizer = Arc::new(CascadeOptimizerBuilder::default().build());
let dispatcher = SimpleQueryDispatcherBuilder::default()
.with_input(Arc::clone(&input))
.with_default_table_provider(Arc::new(BaseTableProvider::default()))
.with_session_factory(Arc::new(SessionCtxFactory::new(false)))
.with_parser(Arc::new(DefaultParser::default()))
.with_query_execution_factory(Arc::new(SqlQueryExecutionFactory::new(optimizer, Arc::new(LocalScheduler {}))))
.with_func_manager(Arc::new(SimpleFunctionMetadataManager::default()))
.with_memory_limit_bytes(memory_limit)
.build()
.expect("query dispatcher should build");
// Keep every row through a FilterExec to confirm filtered batches stream without coalescing.
let sql = "SELECT s.id FROM S3Object s WHERE s.name <> ''".to_owned();
let query = Query::new_with_snapshot(QueryContext { input }, sql, snapshot);
let rows = match dispatcher.execute_query(&query).await {
Ok(output) => output
.into_record_batch_stream()
.expect("record stream")
.try_collect::<Vec<_>>()
.await
.map(|batches| batches.iter().map(RecordBatch::num_rows).sum::<usize>())
.map_err(|error| QueryError::from(error).select_error()),
Err(error) => Err(error.select_error()),
};
assert_eq!(rows, expected, "fixture={index}");
}
}
#[tokio::test(flavor = "current_thread")]
async fn blocking_select_planning_keeps_runtime_responsive_and_admission_after_cancel() {
for phase in ["SQL parse", "schema inference", "SQL plan"] {
@@ -12,6 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
mod delimited_table;
mod json_document_schema;
mod json_document_table;
mod json_lines_schema;
@@ -21,7 +21,7 @@ use datafusion::{
},
datasource::file_format::{DEFAULT_SCHEMA_INFER_MAX_RECORD, csv::CsvFormat},
error::{DataFusionError, Result},
execution::memory_pool::{MemoryConsumer, MemoryPool, MemoryReservation},
execution::memory_pool::{MemoryConsumer, MemoryLimit, MemoryPool, MemoryReservation},
object_store::Error as ObjectStoreError,
};
use futures::{StreamExt, stream::BoxStream};
@@ -65,7 +65,7 @@ impl PrefixBoundary {
}
}
fn consume(&mut self, input: &[u8], prefix: &[u8]) -> Result<(usize, bool)> {
fn consume(&mut self, input: &[u8], prefix: &[u8], json_sample_limit: usize) -> Result<(usize, bool)> {
match self {
Self::JsonLines { records, line_start } => {
for (index, byte) in input.iter().enumerate() {
@@ -83,7 +83,7 @@ impl PrefixBoundary {
if nonblank {
*records += 1;
}
if *records == DEFAULT_SCHEMA_INFER_MAX_RECORD {
if *records == DEFAULT_SCHEMA_INFER_MAX_RECORD || (*records > 0 && end >= json_sample_limit) {
return Ok((index + 1, true));
}
}
@@ -129,17 +129,31 @@ pub(super) async fn read_schema_prefix(
mut boundary: PrefixBoundary,
) -> Result<SchemaPrefix> {
let reservation = MemoryConsumer::new("S3 Select schema prefix").register(memory_pool);
// Keep multi-record JSON Lines inference samples within the query memory budget
// (accounting for downstream schema-inference working memory) while still allowing
// a single record to probe up to MAX_SCHEMA_PREFIX_BYTES.
let json_sample_limit = match memory_pool.memory_limit() {
MemoryLimit::Finite(limit) => MAX_SCHEMA_PREFIX_BYTES.min((limit / 32).max(1)),
MemoryLimit::Infinite | MemoryLimit::Unknown => MAX_SCHEMA_PREFIX_BYTES,
};
let mut bytes = Vec::new();
let mut parsed = 0;
while let Some(chunk) = stream.next().await.transpose()? {
let mut offset = 0;
while offset < chunk.len() {
let remaining = MAX_SCHEMA_PREFIX_BYTES - bytes.len();
let step_limit = match &boundary {
PrefixBoundary::JsonLines { records, .. } if *records > 0 => json_sample_limit,
PrefixBoundary::JsonLines { .. } if bytes.len() < json_sample_limit => json_sample_limit,
_ => MAX_SCHEMA_PREFIX_BYTES,
};
let remaining = step_limit.saturating_sub(bytes.len());
if remaining == 0 {
if let PrefixBoundary::JsonLines { records, line_start } = &boundary
&& *records > 0
{
bytes.truncate(*line_start);
bytes.shrink_to_fit();
reservation.try_resize(bytes.capacity())?;
return Ok(SchemaPrefix { bytes, reservation });
}
return Err(prefix_limit_error());
@@ -162,19 +176,21 @@ pub(super) async fn read_schema_prefix(
offset = end;
continue;
}
let (consumed, done) = boundary.consume(&bytes[parsed..], &bytes)?;
let (consumed, done) = boundary.consume(&bytes[parsed..], &bytes, json_sample_limit)?;
parsed += consumed;
bytes.truncate(parsed);
offset = end;
if done {
bytes.shrink_to_fit();
reservation.try_resize(bytes.capacity())?;
return Ok(SchemaPrefix { bytes, reservation });
}
}
}
if parsed < bytes.len() {
boundary.consume(&bytes[parsed..], &bytes)?;
boundary.consume(&bytes[parsed..], &bytes, json_sample_limit)?;
}
boundary.consume(&[], &bytes)?;
boundary.consume(&[], &bytes, json_sample_limit)?;
Ok(SchemaPrefix { bytes, reservation })
}
@@ -15,12 +15,16 @@
use std::sync::Arc;
use async_trait::async_trait;
use datafusion::common::config::ConfigOptions;
use datafusion::common::tree_node::{Transformed, TransformedResult as _, TreeNode as _};
use datafusion::error::Result as DFResult;
use datafusion::execution::SessionStateBuilder;
use datafusion::logical_expr::LogicalPlan;
use datafusion::physical_optimizer::PhysicalOptimizerRule;
use datafusion::physical_optimizer::aggregate_statistics::AggregateStatistics;
use datafusion::physical_optimizer::join_selection::JoinSelection;
use datafusion::physical_plan::ExecutionPlan;
use datafusion::physical_plan::filter::FilterExec;
use datafusion::physical_planner::{
DefaultPhysicalPlanner as DFDefaultPhysicalPlanner, ExtensionPlanner, PhysicalPlanner as DFPhysicalPlanner,
};
@@ -55,6 +59,7 @@ impl Default for DefaultPhysicalPlanner {
// repartitioning and local sorting steps to meet distribution and ordering requirements.
// Therefore, it should run before EnforceDistribution and EnforceSorting.
Arc::new(JoinSelection::new()),
Arc::new(StreamFilterOutput),
];
Self {
@@ -91,6 +96,35 @@ impl PhysicalPlanner for DefaultPhysicalPlanner {
}
}
/// Prevents `FilterExec` from coalescing filtered rows across input batches.
///
/// DataFusion's `FilterExec` buffers surviving rows until it reaches `batch_size`
/// outside the query memory pool. S3 Select scans emit already byte-bounded batches,
/// so setting `batch_size = 1` streams every non-empty filtered batch immediately.
#[derive(Debug)]
struct StreamFilterOutput;
impl PhysicalOptimizerRule for StreamFilterOutput {
fn optimize(&self, plan: Arc<dyn ExecutionPlan>, _config: &ConfigOptions) -> DFResult<Arc<dyn ExecutionPlan>> {
plan.transform_up(|node| {
let Some(filter) = node.downcast_ref::<FilterExec>() else {
return Ok(Transformed::no(node));
};
let filter: Arc<dyn ExecutionPlan> = Arc::new(filter.with_batch_size(1)?);
Ok(Transformed::yes(filter))
})
.data()
}
fn name(&self) -> &str {
"StreamFilterOutput"
}
fn schema_check(&self) -> bool {
true
}
}
impl PhysicalOptimizer for DefaultPhysicalPlanner {
fn optimize(&self, plan: Arc<dyn ExecutionPlan>, _session: &SessionCtx) -> QueryResult<Arc<dyn ExecutionPlan>> {
Ok(plan)
@@ -100,3 +134,41 @@ impl PhysicalOptimizer for DefaultPhysicalPlanner {
self.ext_physical_optimizer_rules.push(optimizer_rule);
}
}
#[cfg(test)]
mod tests {
use super::*;
use datafusion::arrow::array::{Int64Array, RecordBatch};
use datafusion::arrow::datatypes::{DataType, Field, Schema};
use datafusion::datasource::memory::MemorySourceConfig;
use datafusion::execution::TaskContext;
use datafusion::logical_expr::Operator;
use datafusion::physical_expr::expressions::{binary, col, lit};
use datafusion::physical_plan::collect;
#[tokio::test]
async fn filter_output_is_not_coalesced_across_input_batches() {
let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int64, false)]));
let batches = [vec![1, 2, 3], vec![4, 5], vec![6], vec![7, 8, 9]]
.into_iter()
.map(|ids| RecordBatch::try_new(Arc::clone(&schema), vec![Arc::new(Int64Array::from(ids))]).expect("batch"))
.collect::<Vec<_>>();
let input = MemorySourceConfig::try_new_exec(&[batches], Arc::clone(&schema), None).expect("input");
let predicate = binary(col("id", &schema).expect("column"), Operator::NotEq, lit(6_i64), &schema).expect("predicate");
let filter: Arc<dyn ExecutionPlan> = Arc::new(FilterExec::try_new(predicate, input).expect("filter"));
let rows = |batches: Vec<RecordBatch>| batches.iter().map(RecordBatch::num_rows).collect::<Vec<_>>();
let coalesced = collect(Arc::clone(&filter), Arc::new(TaskContext::default()))
.await
.expect("stock filter");
assert_eq!(rows(coalesced), [8]);
let filter = StreamFilterOutput
.optimize(filter, &ConfigOptions::default())
.expect("optimized filter");
let streamed = collect(filter, Arc::new(TaskContext::default()))
.await
.expect("streaming filter");
assert_eq!(rows(streamed), [3, 2, 3]);
}
}