diff --git a/crates/s3select-api/src/input_stream.rs b/crates/s3select-api/src/input_stream.rs index 06942d4b47..d7333ae64b 100644 --- a/crates/s3select-api/src/input_stream.rs +++ b/crates/s3select-api/src/input_stream.rs @@ -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, ) -> ObjectStoreResult>> { 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, + record_size: RecordSizeTracker, + max_processed_bytes: u64, + query_guard: Option, +) -> ObjectStoreResult>> { 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( + stream: S, + record_size: RecordSizeTracker, + map_error: fn(SelectError) -> E, +) -> BoxStream<'static, Result> +where + S: Stream> + 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, - prefix: Vec, +enum RecordDelimiterMatcher { + /// Default CSV line endings (`\r`, `\n`, or `\r\n`) when no custom `RecordDelimiter` is configured. + DefaultCsvLineEnding, + SingleByte(u8), + MultiByte { + delimiter: Vec, + prefix: Vec, + matched: usize, + }, +} + +pub(crate) struct RecordSizeTracker { + matcher: RecordDelimiterMatcher, record_bytes: usize, - matched: usize, } impl RecordSizeTracker { - fn new(delimiter: Vec) -> Result { + pub(crate) fn default_csv() -> Self { + Self { + matcher: RecordDelimiterMatcher::DefaultCsvLineEnding, + record_bytes: 0, + } + } + + pub(crate) fn new(delimiter: Vec) -> Result { 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> { diff --git a/crates/s3select-api/src/object_store.rs b/crates/s3select-api/src/object_store.rs index 3498ed62a4..49307fd9f3 100644 --- a/crates/s3select-api/src/object_store.rs +++ b/crates/s3select-api/src/object_store.rs @@ -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 { + 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(&self, stream: S) -> Result>> + where + S: Stream> + 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> { 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::>().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::>().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; diff --git a/crates/s3select-api/src/query/session.rs b/crates/s3select-api/src/query/session.rs index e44daadcc1..81030c1c22 100644 --- a/crates/s3select-api/src/query/session.rs +++ b/crates/s3select-api/src/query/session.rs @@ -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::())).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); } } diff --git a/crates/s3select-query/src/dispatcher/delimited_table.rs b/crates/s3select-query/src/dispatcher/delimited_table.rs new file mode 100644 index 0000000000..ebdfb26e8e --- /dev/null +++ b/crates/s3select-query/src/dispatcher/delimited_table.rs @@ -0,0 +1,1036 @@ +// Copyright 2024 RustFS Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! CSV and JSON Lines input decoded in byte-bounded, memory-pool-accounted batches. +//! +//! DataFusion's stock CSV and JSON listing sources buffer `batch_size` rows regardless +//! of record byte length or schema width and reserve nothing from the query memory pool. +//! This table preserves DataFusion's file-scan integration while driving Arrow's CSV +//! and JSON decoders directly: rows per batch are bounded by schema width, batches +//! flush once `DECODE_BATCH_BYTES` of complete records accumulate (or less under tight +//! memory limits), and buffered decoder memory is charged to the session memory pool. + +use std::{ + fmt, + pin::Pin, + sync::Arc, + task::{Context, Poll}, +}; + +use async_trait::async_trait; +use bytes::{Buf as _, Bytes}; +use datafusion::{ + arrow::{csv, datatypes::SchemaRef, error::ArrowError, json, record_batch::RecordBatch}, + catalog::Session, + common::{DataFusionError, Result as DFResult, config::CsvOptions, tree_node::TreeNodeRecursion}, + datasource::{ + TableProvider, + listing::PartitionedFile, + physical_plan::{FileOpenFuture, FileOpener, FileScanConfig, FileScanConfigBuilder, FileSource}, + projection::{ProjectionOpener, SplitProjection}, + source::DataSourceExec, + table_schema::TableSchema, + }, + execution::{ + memory_pool::{MemoryConsumer, MemoryLimit, MemoryPool, MemoryReservation}, + object_store::ObjectStoreUrl, + }, + logical_expr::{Expr, TableType}, + object_store::{GetOptions, ObjectStore, ObjectStoreExt as _, path::Path}, + physical_expr::projection::ProjectionExprs, + physical_plan::{DisplayFormatType, ExecutionPlan, PhysicalExpr, apply_expression_roots, metrics::ExecutionPlanMetricsSet}, +}; +use futures::{Stream, StreamExt as _, TryStreamExt as _, stream::BoxStream}; +use rustfs_s3select_api::QueryResult; + +use super::json_document_table::json_decoder_layout; + +/// Input bytes of complete records after which a batch is flushed. Records are +/// capped at 1 MiB upstream, so a batch holds at most this plus one record. +const DECODE_BATCH_BYTES: usize = 1024 * 1024; +/// Maximum input chunk fed to a decoder before re-evaluating flush and memory state. +const DECODE_STEP_BYTES: usize = 64 * 1024; +/// Pool charge per input byte held by a decoder: unescaped bytes or JSON tape, +/// offsets, materialized columns, and builder growth. A batch of conformant 1 MiB +/// records peaks around 32 MiB, half the default 64 MiB query limit. +const DECODE_MEMORY_MULTIPLIER: usize = 16; +/// Held input is charged in steps of this size to avoid per-line reservation churn. +const DECODE_RESERVATION_STEP_BYTES: usize = 4 * 1024; +/// Arrow's CSV decoder zero-fills a `usize` offset and 8 data bytes for every +/// field of a batch before reading the first record. +const CSV_DECODER_BYTES_PER_FIELD: usize = 2 * std::mem::size_of::(); +const CSV_DECODER_BUFFER_TARGET_BYTES: usize = 4 * 1024 * 1024; +const CSV_DECODER_PER_COLUMN_METADATA_BYTES: usize = 256; + +/// The record syntax of a CSV or JSON Lines object. +#[derive(Clone, Debug)] +pub(super) enum DelimitedFormat { + Csv(Box), + JsonLines, +} + +pub(super) struct DelimitedSelectTable { + schema: SchemaRef, + object_store_url: ObjectStoreUrl, + object_path: String, + object_size: u64, + format: DelimitedFormat, + memory_pool: Arc, +} + +impl fmt::Debug for DelimitedSelectTable { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("DelimitedSelectTable") + .field("object_store_url", &self.object_store_url) + .field("object_path", &self.object_path) + .field("object_size", &self.object_size) + .field("format", &self.format) + .finish_non_exhaustive() + } +} + +impl DelimitedSelectTable { + pub(super) async fn try_new( + state: &dyn Session, + object_store_url: ObjectStoreUrl, + key: &str, + schema: SchemaRef, + format: DelimitedFormat, + ) -> QueryResult> { + let store = state.runtime_env().object_store(&object_store_url)?; + let object_meta = store.head(&Path::from(key)).await.map_err(DataFusionError::from)?; + Ok(Arc::new(Self { + schema, + object_store_url, + object_path: key.to_string(), + object_size: object_meta.size, + format, + memory_pool: Arc::clone(&state.runtime_env().memory_pool), + })) + } +} + +#[async_trait] +impl TableProvider for DelimitedSelectTable { + fn schema(&self) -> SchemaRef { + Arc::clone(&self.schema) + } + + fn table_type(&self) -> TableType { + TableType::Base + } + + async fn scan( + &self, + _state: &dyn Session, + projection: Option<&Vec>, + filters: &[Expr], + limit: Option, + ) -> DFResult> { + let scan_limit = if filters.is_empty() { limit } else { None }; + let file_source = Arc::new(DelimitedSource::new( + Arc::clone(&self.schema), + self.format.clone(), + Arc::clone(&self.memory_pool), + )); + let config = FileScanConfigBuilder::new(self.object_store_url.clone(), file_source) + .with_file(PartitionedFile::new(self.object_path.clone(), self.object_size)) + .with_projection_indices(projection.cloned())? + .with_limit(scan_limit) + .build(); + let plan: Arc = DataSourceExec::from_data_source(config); + Ok(plan) + } +} + +/// A [`FileSource`] shaped like DataFusion's `CsvSource` and `JsonSource`, +/// except that its opener decodes through [`DelimitedBatchStream`]. +#[derive(Clone)] +struct DelimitedSource { + format: DelimitedFormat, + table_schema: TableSchema, + projection: SplitProjection, + batch_size: Option, + metrics: ExecutionPlanMetricsSet, + memory_pool: Arc, +} + +impl DelimitedSource { + fn new(schema: SchemaRef, format: DelimitedFormat, memory_pool: Arc) -> Self { + let table_schema = TableSchema::from(schema); + Self { + format, + projection: SplitProjection::unprojected(&table_schema), + table_schema, + batch_size: None, + metrics: ExecutionPlanMetricsSet::new(), + memory_pool, + } + } +} + +impl FileSource for DelimitedSource { + fn create_file_opener( + &self, + object_store: Arc, + _base_config: &FileScanConfig, + _partition: usize, + ) -> DFResult> { + let file_schema = self.table_schema.file_schema(); + let opener = Arc::new(DelimitedOpener { + format: self.format.clone(), + schema: Arc::clone(file_schema), + projection: self.projection.file_indices.clone(), + batch_size: self + .batch_size + .ok_or_else(|| DataFusionError::Internal("batch size must be set before opening S3 Select input".to_string()))?, + object_store, + memory_pool: Arc::clone(&self.memory_pool), + }) as Arc; + ProjectionOpener::try_new(self.projection.clone(), opener, file_schema) + } + + fn table_schema(&self) -> &TableSchema { + &self.table_schema + } + + fn with_batch_size(&self, batch_size: usize) -> Arc { + let mut source = self.clone(); + source.batch_size = Some(batch_size); + Arc::new(source) + } + + fn try_pushdown_projection(&self, projection: &ProjectionExprs) -> DFResult>> { + let mut source = self.clone(); + let projection = self.projection.source.try_merge(projection)?; + source.projection = SplitProjection::new(self.table_schema.file_schema(), &projection); + Ok(Some(Arc::new(source))) + } + + fn projection(&self) -> Option<&ProjectionExprs> { + Some(&self.projection.source) + } + + fn metrics(&self) -> &ExecutionPlanMetricsSet { + &self.metrics + } + + fn file_type(&self) -> &str { + match self.format { + DelimitedFormat::Csv(_) => "csv", + DelimitedFormat::JsonLines => "json", + } + } + + fn supports_repartitioning(&self) -> bool { + // S3 Select reads one object through a single metered input stream. + false + } + + fn fmt_extra(&self, t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result { + match (t, &self.format) { + (DisplayFormatType::Default | DisplayFormatType::Verbose, DelimitedFormat::Csv(options)) => { + write!(f, ", has_header={}", csv_has_header(options)) + } + _ => Ok(()), + } + } + + fn apply_expressions( + &self, + f: &mut dyn FnMut(&Arc) -> DFResult, + ) -> DFResult { + apply_expression_roots(self.projection.source.iter(), f) + } +} + +struct DelimitedOpener { + format: DelimitedFormat, + schema: SchemaRef, + projection: Vec, + batch_size: usize, + object_store: Arc, + memory_pool: Arc, +} + +impl FileOpener for DelimitedOpener { + fn open(&self, partitioned_file: PartitionedFile) -> DFResult { + let store = Arc::clone(&self.object_store); + let (decoder, batch_size, decoder_reservation) = + RecordDecoder::try_new(&self.format, &self.schema, &self.projection, self.batch_size.max(1))?; + let reservation = MemoryConsumer::new("S3 Select record decoder").register(&self.memory_pool); + reservation.try_resize(decoder_reservation)?; + // A tighter limit is met with smaller batches, leaving half of the budget + // for the record that crosses the flush threshold. + let batch_bytes = match self.memory_pool.memory_limit() { + MemoryLimit::Finite(limit) => DECODE_BATCH_BYTES.min(limit / (2 * DECODE_MEMORY_MULTIPLIER)), + MemoryLimit::Infinite | MemoryLimit::Unknown => DECODE_BATCH_BYTES, + }; + Ok(Box::pin(async move { + let result = store + .get_opts(&partitioned_file.object_meta.location, GetOptions::default()) + .await?; + let stream = DelimitedBatchStream { + input: result.into_stream().map_err(DataFusionError::from).boxed(), + current: Bytes::new(), + decoder, + reservation, + decoder_reservation, + batch_size, + batch_bytes, + row_bytes: 0, + pending_bytes: 0, + reserved_bytes: 0, + input_finished: false, + done: false, + }; + Ok(stream.boxed()) + })) + } +} + +fn csv_has_header(options: &CsvOptions) -> bool { + options.has_header.unwrap_or(true) +} + +/// Mirrors what DataFusion's `CsvSource` passes to Arrow for these options. +fn csv_decoder(options: &CsvOptions, schema: SchemaRef, projection: &[usize], batch_size: usize) -> csv::reader::Decoder { + let mut builder = csv::ReaderBuilder::new(schema) + .with_delimiter(options.delimiter) + .with_batch_size(batch_size) + .with_header(csv_has_header(options)) + .with_quote(options.quote) + .with_truncated_rows(options.truncated_rows.unwrap_or(false)) + .with_projection(projection.to_vec()); + if let Some(terminator) = options.terminator { + builder = builder.with_terminator(terminator); + } + if let Some(escape) = options.escape { + builder = builder.with_escape(escape); + } + if let Some(comment) = options.comment { + builder = builder.with_comment(comment); + } + builder.build_decoder() +} + +/// Bounds the rows of a CSV batch so the decoder's upfront buffers fit the +/// target for this schema width, and returns them with their pool charge. +fn csv_decoder_layout(columns: usize, requested_batch_size: usize) -> DFResult<(usize, usize)> { + let bytes_per_row = columns + .max(1) + .checked_mul(CSV_DECODER_BYTES_PER_FIELD) + .ok_or_else(decoder_resource_error)?; + let metadata_bytes = columns + .checked_mul(CSV_DECODER_PER_COLUMN_METADATA_BYTES) + .ok_or_else(decoder_resource_error)?; + let buffer_budget = CSV_DECODER_BUFFER_TARGET_BYTES.saturating_sub(metadata_bytes); + let batch_size = requested_batch_size.min((buffer_budget / bytes_per_row).max(1)); + let reservation = bytes_per_row + .checked_mul(batch_size) + .and_then(|bytes| bytes.checked_add(metadata_bytes)) + .ok_or_else(decoder_resource_error)?; + Ok((batch_size, reservation)) +} + +/// Where Arrow's CSV parser stands after the physical lines it has consumed. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum CsvPosition { + /// Between records: the decoder holds complete records only. + RecordStart, + /// Inside a comment line that started between records. + Comment, + /// Possibly partway through a record. + Record, +} + +enum RecordDecoder { + Csv { + decoder: Box, + /// `None` keeps Arrow's default, where `\r`, `\n`, and `\r\n` end a record. + terminator: Option, + comment: Option, + quote: u8, + escape: Option, + header_pending: bool, + in_header_quotes: bool, + header_escaped: bool, + position: CsvPosition, + batch_size: usize, + }, + Json(json::reader::Decoder), +} + +impl RecordDecoder { + /// Returns the decoder along with its bounded batch size and upfront pool charge. + fn try_new( + format: &DelimitedFormat, + schema: &SchemaRef, + projection: &[usize], + requested_batch_size: usize, + ) -> DFResult<(Self, usize, usize)> { + match format { + DelimitedFormat::Csv(options) => { + let (batch_size, reservation) = csv_decoder_layout(schema.fields().len(), requested_batch_size)?; + let decoder = Self::Csv { + decoder: Box::new(csv_decoder(options, Arc::clone(schema), projection, batch_size)), + terminator: options.terminator, + comment: options.comment, + quote: options.quote, + escape: options.escape, + header_pending: csv_has_header(options), + in_header_quotes: false, + header_escaped: false, + position: CsvPosition::RecordStart, + batch_size, + }; + Ok((decoder, batch_size, reservation)) + } + DelimitedFormat::JsonLines => { + let schema = Arc::new(schema.project(projection)?); + let (batch_size, reservation) = json_decoder_layout(&schema, requested_batch_size)?; + let decoder = json::ReaderBuilder::new(schema).with_batch_size(batch_size).build_decoder()?; + Ok((Self::Json(decoder), batch_size, reservation)) + } + } + } + + /// How many bytes of `buf` to feed next. + /// + /// Arrow's CSV decoder does not expose whether it is partway through a record, + /// so it is fed one physical line at a time: Arrow completes a record only on + /// an unquoted terminator, and each fed slice contains at most one terminator, + /// so a slice that advances the row count leaves the decoder between records. + /// The JSON decoder reports partial records directly and takes up to `bulk` + /// bytes before feeding line by line toward a record boundary. + fn next_input_len(&self, buf: &[u8], bulk: usize) -> usize { + let buf = &buf[..buf.len().min(DECODE_STEP_BYTES)]; + let line_end = match self { + Self::Csv { + terminator: Some(terminator), + .. + } => buf.iter().position(|byte| *byte == *terminator), + Self::Csv { terminator: None, .. } => buf.iter().position(|byte| matches!(*byte, b'\r' | b'\n')), + Self::Json(_) if bulk > 0 => return buf.len().min(bulk), + Self::Json(_) => buf.iter().position(|byte| *byte == b'\n'), + }; + line_end.map_or(buf.len(), |end| end + 1) + } + + fn decode(&mut self, buf: &[u8]) -> Result { + match self { + Self::Csv { + decoder, + terminator, + comment, + quote, + escape, + header_pending, + in_header_quotes, + header_escaped, + position, + .. + } => { + let capacity = decoder.capacity(); + let decoded = decoder.decode(buf)?; + let line = &buf[..decoded]; + let Some(&last) = line.last() else { + return Ok(decoded); + }; + let ends_line = decoded == buf.len() + && match terminator { + Some(terminator) => last == *terminator, + None => matches!(last, b'\r' | b'\n'), + }; + if decoder.capacity() < capacity { + *header_pending = false; + *in_header_quotes = false; + *header_escaped = false; + *position = CsvPosition::RecordStart; + } else { + match *position { + // Arrow skips empty lines and, up to the next `\n`, + // lines starting with the comment byte. + CsvPosition::RecordStart if ends_line && line.len() == 1 => { + *position = CsvPosition::RecordStart; + } + CsvPosition::RecordStart if *comment == Some(line[0]) => { + *position = if ends_line && last == b'\n' { + CsvPosition::RecordStart + } else { + CsvPosition::Comment + }; + } + CsvPosition::Comment => { + if ends_line && last == b'\n' { + *position = CsvPosition::RecordStart; + } + } + CsvPosition::RecordStart | CsvPosition::Record if *header_pending => { + // Track quote state across the header record so completing the + // header returns to `RecordStart` and subsequent blank/comment + // lines before the first data row are not charged as pending data. + let content = if ends_line { &line[..line.len() - 1] } else { line }; + for &byte in content { + if *header_escaped { + *header_escaped = false; + } else if *in_header_quotes && *escape == Some(byte) { + *header_escaped = true; + } else if byte == *quote { + *in_header_quotes = !*in_header_quotes; + } + } + if ends_line && !*in_header_quotes { + *header_pending = false; + *header_escaped = false; + *position = CsvPosition::RecordStart; + } else { + *position = CsvPosition::Record; + } + } + CsvPosition::RecordStart | CsvPosition::Record => { + *position = CsvPosition::Record; + } + } + } + Ok(decoded) + } + Self::Json(decoder) => decoder.decode(buf), + } + } + + fn flush(&mut self) -> Result, ArrowError> { + match self { + Self::Csv { decoder, .. } => decoder.flush(), + Self::Json(decoder) => decoder.flush(), + } + } + + /// Complete records buffered since the last flush. + fn rows(&self) -> usize { + match self { + Self::Csv { decoder, batch_size, .. } => batch_size.saturating_sub(decoder.capacity()), + Self::Json(decoder) => decoder.len().saturating_sub(usize::from(decoder.has_partial_record())), + } + } + + /// Whether the decoder is known to hold complete records only. + fn at_record_boundary(&self) -> bool { + match self { + Self::Csv { position, .. } => *position == CsvPosition::RecordStart, + Self::Json(decoder) => !decoder.has_partial_record(), + } + } +} + +/// Decodes the object stream into batches bounded by rows, bytes, and the memory pool. +struct DelimitedBatchStream { + input: BoxStream<'static, DFResult>, + current: Bytes, + decoder: RecordDecoder, + reservation: MemoryReservation, + decoder_reservation: usize, + batch_size: usize, + batch_bytes: usize, + /// Input bytes belonging to complete records buffered since the last flush. + row_bytes: usize, + /// Input bytes fed since the decoder was last known to be between records. + pending_bytes: usize, + /// Held input bytes currently covered by the pool reservation. + reserved_bytes: usize, + input_finished: bool, + done: bool, +} + +impl DelimitedBatchStream { + /// Charges the memory pool for `bytes` of additional input held by the decoder. + fn reserve_input(&mut self, bytes: usize) -> DFResult<()> { + let held = self + .row_bytes + .checked_add(self.pending_bytes) + .and_then(|held| held.checked_add(bytes)) + .ok_or_else(decoder_resource_error)?; + if held <= self.reserved_bytes { + return Ok(()); + } + let reserved = held + .checked_next_multiple_of(DECODE_RESERVATION_STEP_BYTES) + .ok_or_else(decoder_resource_error)?; + let reservation = reserved + .checked_mul(DECODE_MEMORY_MULTIPLIER) + .and_then(|work| work.checked_add(self.decoder_reservation)) + .ok_or_else(decoder_resource_error)?; + self.reservation.try_resize(reservation)?; + self.reserved_bytes = reserved; + Ok(()) + } + + fn flush(&mut self) -> DFResult> { + let batch = self.decoder.flush()?; + self.row_bytes = 0; + self.pending_bytes = 0; + self.reserved_bytes = 0; + self.reservation.try_resize(self.decoder_reservation)?; + Ok(batch) + } + + fn fail(&mut self, error: DataFusionError) -> Poll>> { + self.done = true; + self.current = Bytes::new(); + self.reservation.free(); + Poll::Ready(Some(Err(error))) + } +} + +impl Stream for DelimitedBatchStream { + type Item = DFResult; + + fn poll_next(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll> { + let stream = self.as_mut().get_mut(); + loop { + if stream.done { + return Poll::Ready(None); + } + // Both conditions first hold right after a record completes, so the + // decoder is between records whenever it is flushed. + let rows = stream.decoder.rows(); + if rows >= stream.batch_size || (rows > 0 && stream.pending_bytes == 0 && stream.row_bytes >= stream.batch_bytes) { + return match stream.flush() { + Ok(Some(batch)) => Poll::Ready(Some(Ok(batch))), + Ok(None) => stream.fail(DataFusionError::Execution( + "Arrow decoder reached a flush boundary without producing a batch".to_string(), + )), + Err(error) => stream.fail(error), + }; + } + if stream.current.is_empty() { + if stream.input_finished { + stream.done = true; + // Arrow completes a final record without trailing terminator on empty input. + if let Err(error) = stream.decoder.decode(&[]) { + return stream.fail(DataFusionError::from(error)); + } + return match stream.flush() { + Ok(batch) => Poll::Ready(batch.map(Ok)), + Err(error) => stream.fail(error), + }; + } + match stream.input.poll_next_unpin(context) { + Poll::Ready(Some(Ok(bytes))) => stream.current = bytes, + Poll::Ready(Some(Err(error))) => return stream.fail(error), + Poll::Ready(None) => stream.input_finished = true, + Poll::Pending => return Poll::Pending, + } + continue; + } + + let bulk = stream + .batch_bytes + .saturating_sub(stream.row_bytes.saturating_add(stream.pending_bytes)); + let available = stream.decoder.next_input_len(&stream.current, bulk); + if let Err(error) = stream.reserve_input(available) { + return stream.fail(error); + } + let decoded = match stream.decoder.decode(&stream.current[..available]) { + Ok(decoded) => decoded, + Err(error) => return stream.fail(DataFusionError::from(error)), + }; + if decoded == 0 { + return stream.fail(DataFusionError::Execution("Arrow decoder made no progress".to_string())); + } + stream.current.advance(decoded); + stream.pending_bytes = stream.pending_bytes.saturating_add(decoded); + if stream.decoder.at_record_boundary() { + // Input that completed no record (header, comment, or blank line) holds no row memory. + if stream.decoder.rows() > rows { + stream.row_bytes = stream.row_bytes.saturating_add(stream.pending_bytes); + } + stream.pending_bytes = 0; + } + } + } +} + +fn decoder_resource_error() -> DataFusionError { + DataFusionError::ResourcesExhausted("S3 Select record decoder exceeds the query memory limit".to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + use datafusion::{ + arrow::{ + array::{Array as _, Int64Array, StringArray}, + datatypes::{DataType, Field, Schema}, + }, + datasource::{ + file_format::csv::CsvFormat, + listing::{ListingOptions, ListingTable, ListingTableConfig, ListingTableUrl}, + }, + execution::runtime_env::RuntimeEnvBuilder, + object_store::memory::InMemory, + prelude::{SessionConfig, SessionContext}, + }; + + const BUCKET: &str = "bucket"; + const MIB: usize = 1024 * 1024; + + fn session(memory_limit: usize) -> (SessionContext, Arc) { + let store = Arc::new(InMemory::new()); + let runtime = RuntimeEnvBuilder::new() + .with_memory_limit(memory_limit, 1.0) + .build_arc() + .expect("runtime"); + let context = SessionContext::new_with_config_rt(SessionConfig::new().with_target_partitions(1), runtime); + let url = ObjectStoreUrl::parse(format!("s3://{BUCKET}")).expect("store URL"); + context.register_object_store(url.as_ref(), Arc::clone(&store) as Arc); + (context, store) + } + + fn utf8_schema(columns: &[&str]) -> SchemaRef { + Arc::new(Schema::new( + columns + .iter() + .map(|name| Field::new(*name, DataType::Utf8, true)) + .collect::>(), + )) + } + + async fn register( + context: &SessionContext, + store: &InMemory, + key: &str, + data: Vec, + schema: SchemaRef, + format: DelimitedFormat, + ) { + store + .put(&Path::from(key), Bytes::from(data).into()) + .await + .expect("put fixture"); + let url = ObjectStoreUrl::parse(format!("s3://{BUCKET}")).expect("store URL"); + let provider = DelimitedSelectTable::try_new(&context.state(), url, key, schema, format) + .await + .expect("prepare delimited table"); + context.register_table("S3Object", provider).expect("register table"); + } + + fn csv_format(options: CsvOptions) -> DelimitedFormat { + DelimitedFormat::Csv(Box::new(options)) + } + + fn csv_options(has_header: bool) -> CsvOptions { + CsvOptions { + has_header: Some(has_header), + ..Default::default() + } + } + + async fn collect(context: &SessionContext, sql: &str) -> DFResult> { + context.sql(sql).await.expect("plan query").collect().await + } + + fn strings(batches: &[RecordBatch], column: usize) -> Vec> { + batches + .iter() + .flat_map(|batch| { + let values = batch + .column(column) + .as_any() + .downcast_ref::() + .expect("utf8 column"); + (0..values.len()) + .map(|index| values.is_valid(index).then(|| values.value(index).to_string())) + .collect::>() + }) + .collect() + } + + fn ids(range: std::ops::Range) -> Vec> { + range.map(|id| Some(id.to_string())).collect() + } + + #[tokio::test] + async fn batches_flush_on_input_bytes_at_record_boundaries() { + const ROWS: usize = 6; + const PAYLOAD_BYTES: usize = 600 * 1024; + let payload = "x".repeat(PAYLOAD_BYTES); + let mut csv = b"id,payload\n".to_vec(); + let mut json = Vec::new(); + for id in 0..ROWS { + csv.extend_from_slice(format!("{id},{payload}\n").as_bytes()); + json.extend_from_slice(format!("{{\"id\":\"{id}\",\"payload\":\"{payload}\"}}\n").as_bytes()); + } + for (data, format) in [(csv, csv_format(csv_options(true))), (json, DelimitedFormat::JsonLines)] { + let (context, store) = session(64 * MIB); + register(&context, &store, "rows", data, utf8_schema(&["id", "payload"]), format).await; + + let batches = collect(&context, "SELECT id FROM S3Object").await.expect("execute query"); + // At most 1 MiB of buffered input plus the record that crosses the threshold. + assert!(batches.iter().all(|batch| batch.num_rows() <= 2), "{batches:?}"); + assert_eq!(strings(&batches, 0), ids(0..ROWS)); + } + } + + #[tokio::test] + async fn records_of_the_maximum_size_fit_the_default_memory_limit_including_empty_projection() { + const ROWS: usize = 24; + let payload = "x".repeat(MIB - 4); + let mut csv = Vec::new(); + let mut json = Vec::new(); + for id in 10..10 + ROWS { + csv.extend_from_slice(format!("{id},{payload}\n").as_bytes()); + json.extend_from_slice(format!("{{\"id\":\"{id}\",\"payload\":\"{}\"}}\n", &payload[..MIB - 24]).as_bytes()); + } + for (data, format) in [(csv, csv_format(csv_options(false))), (json, DelimitedFormat::JsonLines)] { + for sql in [ + "SELECT count(*) FROM S3Object", + "SELECT count(*) FROM S3Object WHERE id <> ''", + ] { + let (context, store) = session(64 * MIB); + register(&context, &store, "rows", data.clone(), utf8_schema(&["id", "payload"]), format.clone()).await; + + let batches = collect(&context, sql) + .await + .expect("conformant records must not exhaust the default limit"); + let count = batches[0] + .column(0) + .as_any() + .downcast_ref::() + .expect("count column") + .value(0); + assert_eq!(count, ROWS as i64, "sql={sql}"); + } + } + } + + #[tokio::test] + async fn tight_memory_limits_are_met_with_smaller_batches() { + const ROWS: usize = 30_000; + let payload = "x".repeat(90); + let mut csv = Vec::new(); + let mut json = Vec::new(); + for id in 0..ROWS { + csv.extend_from_slice(format!("{id},{payload}\n").as_bytes()); + json.extend_from_slice(format!("{{\"id\":\"{id}\",\"payload\":\"{payload}\"}}\n").as_bytes()); + } + for (data, format) in [(csv, csv_format(csv_options(false))), (json, DelimitedFormat::JsonLines)] { + let (context, store) = session(4 * MIB); + register(&context, &store, "rows", data, utf8_schema(&["id", "payload"]), format).await; + + let batches = collect(&context, "SELECT id FROM S3Object") + .await + .expect("small records fit a tight memory limit"); + assert!(batches.len() > 16, "{}", batches.len()); + assert_eq!(strings(&batches, 0), ids(0..ROWS)); + } + } + + #[tokio::test] + async fn logical_records_beyond_the_memory_limit_are_rejected() { + const LINE_BYTES: usize = 512 * 1024; + let line = "x".repeat(LINE_BYTES); + + let quoted = [line.as_str(); 8].join("\n"); + let (context, store) = session(32 * MIB); + let data = format!("0,\"{quoted}\"\n").into_bytes(); + let format = csv_format(csv_options(false)); + register(&context, &store, "record.csv", data, utf8_schema(&["_1", "_2"]), format).await; + let error = collect(&context, "SELECT _1 FROM S3Object") + .await + .expect_err("an oversized CSV record must not be buffered outside the pool"); + assert!(matches!(error, DataFusionError::ResourcesExhausted(_)), "{error}"); + + let items = vec![format!("\"{line}\""); 8].join(",\n"); + let (context, store) = session(32 * MIB); + let data = format!("{{\"id\":\"0\",\"items\":[{items}]}}\n").into_bytes(); + register(&context, &store, "record.json", data, utf8_schema(&["id"]), DelimitedFormat::JsonLines).await; + let error = collect(&context, "SELECT id FROM S3Object") + .await + .expect_err("an oversized JSON record must not be buffered outside the pool"); + assert!(matches!(error, DataFusionError::ResourcesExhausted(_)), "{error}"); + } + + #[tokio::test] + async fn skipped_lines_are_not_charged_to_the_memory_pool() { + const SKIPPED_BYTES: usize = 3 * MIB; + for (newline, comment) in [("\n", false), ("\r\n", false), ("\n", true), ("\r\n", true)] { + let skipped = if comment { + format!("# {}{newline}", "x".repeat(62)).repeat(SKIPPED_BYTES / 64) + } else { + newline.repeat(SKIPPED_BYTES) + }; + // Include skipped runs immediately after the header AND between data rows. + let data = format!("id,name{newline}{skipped}0,a{newline}{skipped}1,b{newline}{skipped}").into_bytes(); + let options = CsvOptions { + comment: comment.then_some(b'#'), + ..csv_options(true) + }; + // Each skipped run alone would be charged 48 MiB if retained in pending_bytes. + let (context, store) = session(8 * MIB); + let format = csv_format(options); + register(&context, &store, "sparse.csv", data, utf8_schema(&["id", "name"]), format).await; + let batches = collect(&context, "SELECT id FROM S3Object") + .await + .expect("blank and comment lines hold no decoder memory"); + assert_eq!(strings(&batches, 0), ids(0..2), "newline={newline:?} comment={comment}"); + } + + let (context, store) = session(8 * MIB); + let data = format!("{{\"id\":\"0\"}}\n{}{{\"id\":\"1\"}}\n", " \n".repeat(SKIPPED_BYTES / 2)).into_bytes(); + register(&context, &store, "sparse.json", data, utf8_schema(&["id"]), DelimitedFormat::JsonLines).await; + let batches = collect(&context, "SELECT id FROM S3Object") + .await + .expect("blank lines hold no decoder memory"); + assert_eq!(strings(&batches, 0), ids(0..2)); + } + + #[tokio::test] + async fn wide_schemas_bound_the_rows_of_a_csv_batch() { + const COLUMNS: usize = 10_000; + assert_eq!(csv_decoder_layout(2, 8192).expect("narrow layout"), (8192, 8192 * 2 * 16 + 2 * 256)); + let (batch_size, reservation) = csv_decoder_layout(COLUMNS, 8192).expect("wide layout"); + assert_eq!(batch_size, 10); + assert!(reservation <= CSV_DECODER_BUFFER_TARGET_BYTES); + let (batch_size, reservation) = csv_decoder_layout(1_000_000, 8192).expect("widest layout"); + assert_eq!((batch_size, reservation), (1, 1_000_000 * (16 + 256))); + + let names = (1..=COLUMNS).map(|index| format!("_{index}")).collect::>(); + let schema = utf8_schema(&names.iter().map(String::as_str).collect::>()); + let row = format!("{}\n", vec!["v"; COLUMNS].join(",")); + + let (context, store) = session(16 * MIB); + let format = csv_format(csv_options(false)); + register( + &context, + &store, + "wide.csv", + row.repeat(25).into_bytes(), + Arc::clone(&schema), + format.clone(), + ) + .await; + let batches = collect(&context, "SELECT _1, _10000 FROM S3Object").await.expect("wide rows"); + assert!(batches.iter().all(|batch| batch.num_rows() <= 10), "{batches:?}"); + assert_eq!(strings(&batches, 1), vec![Some("v".to_string()); 25]); + + let (context, store) = session(MIB); + register(&context, &store, "wide.csv", row.into_bytes(), schema, format).await; + let error = collect(&context, "SELECT _1 FROM S3Object") + .await + .expect_err("the decoder's per-column buffers are charged to the pool"); + assert!(matches!(error, DataFusionError::ResourcesExhausted(_)), "{error}"); + } + + #[tokio::test] + async fn projection_filter_and_limit_are_applied() { + let (context, store) = session(64 * MIB); + let data = b"id,name\n1,Alice\n2,Bob\n3,Carol\n".to_vec(); + let format = csv_format(csv_options(true)); + register(&context, &store, "people.csv", data, utf8_schema(&["id", "name"]), format).await; + + let batches = collect(&context, "SELECT name FROM S3Object WHERE id = '2'") + .await + .expect("filter"); + assert_eq!(batches[0].schema().fields().len(), 1); + assert_eq!(strings(&batches, 0), [Some("Bob".to_string())]); + + let batches = collect(&context, "SELECT name, id FROM S3Object LIMIT 2") + .await + .expect("limit"); + assert_eq!(strings(&batches, 0), [Some("Alice".to_string()), Some("Bob".to_string())]); + assert_eq!(strings(&batches, 1), ids(1..3)); + + let (context, store) = session(64 * MIB); + let data = b"{\"id\":\"1\",\"name\":\"Alice\"}\n{\"name\":\"Bob\"}\n{\"id\":\"3\"}".to_vec(); + register( + &context, + &store, + "people.json", + data, + utf8_schema(&["id", "name"]), + DelimitedFormat::JsonLines, + ) + .await; + let batches = collect(&context, "SELECT name FROM S3Object").await.expect("projection"); + assert_eq!(strings(&batches, 0), [Some("Alice".to_string()), Some("Bob".to_string()), None]); + } + + #[tokio::test] + async fn csv_batches_match_the_stock_datafusion_scan() { + let padding = "p".repeat(2000); + let fixture = |newline: &str, terminator: &str, comments: bool| { + let mut data = format!("{terminator}id,text,pad{terminator}"); + if comments { + data.insert_str(0, &format!("# leading comment{newline}")); + } + for id in 0..2000 { + let text = match id % 8 { + 0 => format!("\"multi{newline}line {id}\""), + 1 => "\"quoted \"\"text\"\", with delimiter\"".to_string(), + 2 => String::new(), + 3 => format!("\"#{id}\""), + _ => format!("plain {id}"), + }; + data.push_str(&format!("{id},{text},{padding}{terminator}")); + match id % 16 { + 5 => data.push_str(terminator), + 9 if comments => data.push_str(&format!("# comment {id}{newline}")), + 13 if comments => data.push_str(&format!("#\"open quote{newline}{terminator}{terminator}")), + _ => {} + } + } + data.push_str("2000,last,record without terminator"); + data.into_bytes() + }; + let cases = [ + ("\n", "\n", None, true), + ("\r\n", "\r\n", None, true), + ("\n", "\r", None, true), + ("\n", "\n", Some(b'\n'), true), + ("\n", ";", Some(b';'), false), + ]; + for (newline, terminator, custom_terminator, comments) in cases { + let options = CsvOptions { + comment: comments.then_some(b'#'), + terminator: custom_terminator, + ..csv_options(true) + }; + let data = fixture(newline, terminator, comments); + let schema = utf8_schema(&["id", "text", "pad"]); + let sql = "SELECT id, text FROM S3Object"; + + let (context, store) = session(64 * MIB); + store + .put(&Path::from("stock.csv"), Bytes::from(data.clone()).into()) + .await + .expect("put fixture"); + let file_format = CsvFormat::default().with_options(options.clone()); + let config = ListingTableConfig::new(ListingTableUrl::parse(format!("s3://{BUCKET}/stock.csv")).expect("table URL")) + .with_listing_options(ListingOptions::new(Arc::new(file_format)).with_file_extension("")) + .with_schema(Arc::clone(&schema)); + let provider = Arc::new(ListingTable::try_new(config).expect("stock table")); + context.register_table("S3Object", provider).expect("register table"); + let expected = collect(&context, sql).await.expect("stock scan"); + assert_eq!(strings(&expected, 0), ids(0..2001), "terminator={terminator:?}"); + + let (context, store) = session(64 * MIB); + register(&context, &store, "bounded.csv", data, schema, csv_format(options)).await; + let batches = collect(&context, sql).await.expect("bounded scan"); + assert!(batches.len() > 2, "the byte target must split the scan into several batches"); + assert_eq!(strings(&batches, 0), strings(&expected, 0), "terminator={terminator:?}"); + assert_eq!(strings(&batches, 1), strings(&expected, 1), "terminator={terminator:?}"); + } + } +} diff --git a/crates/s3select-query/src/dispatcher/json_document_table.rs b/crates/s3select-query/src/dispatcher/json_document_table.rs index 767c5ddfb9..88b78eaadb 100644 --- a/crates/s3select-query/src/dispatcher/json_document_table.rs +++ b/crates/s3select-query/src/dispatcher/json_document_table.rs @@ -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 diff --git a/crates/s3select-query/src/dispatcher/manager.rs b/crates/s3select-query/src/dispatcher/manager.rs index 4d48233b40..767beb1e1b 100644 --- a/crates/s3select-query/src/dispatcher/manager.rs +++ b/crates/s3select-query/src/dispatcher/manager.rs @@ -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 = LazyLock::new(|| FileHeaderInfo::IGNORE); static NONE: LazyLock = LazyLock::new(|| FileHeaderInfo::NONE); static USE: LazyLock = 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::>() + .await + .map(|batches| batches.iter().map(RecordBatch::num_rows).sum::()) + .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"] { diff --git a/crates/s3select-query/src/dispatcher/mod.rs b/crates/s3select-query/src/dispatcher/mod.rs index b987774c77..a567313c4b 100644 --- a/crates/s3select-query/src/dispatcher/mod.rs +++ b/crates/s3select-query/src/dispatcher/mod.rs @@ -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; diff --git a/crates/s3select-query/src/dispatcher/schema_inference.rs b/crates/s3select-query/src/dispatcher/schema_inference.rs index 80da1328b8..391f10b820 100644 --- a/crates/s3select-query/src/dispatcher/schema_inference.rs +++ b/crates/s3select-query/src/dispatcher/schema_inference.rs @@ -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 { 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 }) } diff --git a/crates/s3select-query/src/sql/physical/planner.rs b/crates/s3select-query/src/sql/physical/planner.rs index 934e8d151f..55e61a8456 100644 --- a/crates/s3select-query/src/sql/physical/planner.rs +++ b/crates/s3select-query/src/sql/physical/planner.rs @@ -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, _config: &ConfigOptions) -> DFResult> { + plan.transform_up(|node| { + let Some(filter) = node.downcast_ref::() else { + return Ok(Transformed::no(node)); + }; + let filter: Arc = 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, _session: &SessionCtx) -> QueryResult> { 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::>(); + 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 = Arc::new(FilterExec::try_new(predicate, input).expect("filter")); + let rows = |batches: Vec| batches.iter().map(RecordBatch::num_rows).collect::>(); + + 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]); + } +}