From 77ddc091493377aa54f87a68414c6a075d945ad2 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Tue, 1 Dec 2026 15:05:56 -0600 Subject: [PATCH 01/17] storage: close upload durability gaps and bound upload memory Upload verification - P_VERIFY_UPLOAD_HEAD defaults to true again, as upstream checks every upload unconditionally: the size the store reports for an uploaded Parquet file is compared with the staged file before the file is published in the manifest and its staged source is deleted. Only an explicit false/0/no/off opts out, and that is logged. - A single PUT (S3, GCS, Azure) now fails before the request unless the file read is exactly as long as it was measured, as a multipart upload already did. The read is capped one byte past that length. Local filesystem store - Non-Parquet put_object (manifest.json, .stream.json, .schema, ...) is committed through a synced private file and an atomic rename instead of a truncating write in place. The replacement carries the replaced file's mode. A name that only a write through it can serve keeps the in-place write, now synced: a symlink, a file with other hard links, a file of another owner, one this process may not write to. - A staged Parquet file that cannot be hard-linked is streamed once into a private file and renamed over the destination. A destination that appears during the copy no longer costs a second full copy, and no path for a .parquet key reads the file into memory any more. The copy must have the length of its source. - The copy uses std::io::copy on Linux (copy_file_range, then sendfile) and keeps the 256 KiB streaming loop elsewhere. - Every publication syncs the directory entries up to the store root, not only the object's own directory, so a crash cannot drop a newly created date=/hour=/minute= directory with the objects in it. A failed directory sync fails the upload instead of being discarded. - The first cross-device hard-link failure logs once that staging and data on one filesystem allow zero-copy hard links. - Private files of atomic writes all use the reserved upload prefix and are left out of the metadata inventory, so one that a crash leaves behind cannot stop the offline migration. GCS and Azure multipart - Parts are read and sent one at a time through the S3 part-upload helper instead of slicing a whole-file buffer, with its exact-length check, and the upload is aborted on a read, part or completion failure and on cancellation, so no parts are left behind. Upload memory budget - P_MAX_UPLOAD_MEMORY_BYTES (default 256 MiB, read in object_storage.rs) caps the bytes of staged files that concurrent uploads buffer: one part per multipart upload, the whole file for a single PUT. A file reserves its share after its upload slots and before its claim starts, so waiting for memory cannot make the claim expire. The local filesystem store buffers nothing and takes none. Co-Authored-By: Claude Fable 5.2 --- src/storage/azure_blob.rs | 79 +-- src/storage/gcs.rs | 81 +-- src/storage/localfs.rs | 1156 ++++++++++++++++++++++++++++++--- src/storage/object_storage.rs | 613 ++++++++++++++++- src/storage/s3.rs | 140 +++- 5 files changed, 1831 insertions(+), 238 deletions(-) diff --git a/src/storage/azure_blob.rs b/src/storage/azure_blob.rs index db02efaf7..423fb7de8 100644 --- a/src/storage/azure_blob.rs +++ b/src/storage/azure_blob.rs @@ -45,7 +45,7 @@ use object_store::{ path::Path as StorePath, }; use relative_path::{RelativePath, RelativePathBuf}; -use tokio::{fs::OpenOptions, io::AsyncReadExt}; +use tokio::fs::OpenOptions; use tracing::error; use url::Url; @@ -66,7 +66,9 @@ use super::{ STREAM_METADATA_FILE_NAME, metrics_layer::MetricLayer, object_storage::{parseable_json_path, stream_data_listing_prefix}, - partial_path, to_object_store_path, + partial_path, + s3::{read_file_for_single_put, upload_file_parts, use_single_put}, + to_object_store_path, }; use crate::storage::GET_OBJECTS_CONCURRENCY; @@ -542,9 +544,15 @@ impl BlobStore { let total_size = meta.len() as usize; tracing::Span::current().record("total_bytes", total_size); let min_multipart_size = PARSEABLE.options.min_multipart_size as usize; - if total_size < min_multipart_size || !PARSEABLE.options.enable_multipart { - let mut data = Vec::new(); - file.read_to_end(&mut data).await?; + if use_single_put( + total_size, + min_multipart_size, + PARSEABLE.options.enable_multipart, + ) { + // The body is exactly the file that was measured above. One that + // ended early or grew while it was read fails here and is never + // put. + let data = read_file_for_single_put(file, total_size).await?; let result = self.client.put(location, data.into()).await; increment_object_store_calls_by_date( "PUT", @@ -569,54 +577,31 @@ impl BlobStore { return Ok(()); } else { let async_writer = self.client.put_multipart(location).await; - let mut async_writer = match async_writer { + let async_writer = match async_writer { Ok(writer) => writer, Err(err) => { return Err(err.into()); } }; - let mut data = Vec::new(); - file.read_to_end(&mut data).await?; - - // let mut upload_parts = Vec::new(); - - let has_final_partial_part = !total_size.is_multiple_of(min_multipart_size); - let num_full_parts = total_size / min_multipart_size; - let total_parts = num_full_parts + if has_final_partial_part { 1 } else { 0 }; - - // Upload each part with metrics - for part_number in 0..(total_parts) { - let start_pos = part_number * min_multipart_size; - let end_pos = if part_number == num_full_parts && has_final_partial_part { - // Last part might be smaller than 5MB (which is allowed) - total_size - } else { - // All other parts must be at least 5MB - start_pos + min_multipart_size - }; - - // Extract this part's data - let part_data = data[start_pos..end_pos].to_vec(); - - let result = async_writer.put_part(part_data.into()).await; - if result.is_err() { - return Err(result.err().unwrap().into()); - } - increment_object_store_calls_by_date( - "PUT_MULTIPART", - &Utc::now().date_naive().to_string(), - tenant, - ); - } - - // Track multipart completion - let complete_result = async_writer.complete().await; - if let Err(err) = complete_result { - error!("Failed to complete multipart upload. {:?}", err); - async_writer.abort().await?; - return Err(err.into()); - } + // The file is read one part at a time, never whole, and has to + // be exactly as long as it was measured. A read, part or + // completion failure aborts the upload, and so does dropping it + // when the task is cancelled, so that no blocks are left behind. + upload_file_parts( + &mut file, + async_writer, + total_size, + min_multipart_size, + || { + increment_object_store_calls_by_date( + "PUT_MULTIPART", + &Utc::now().date_naive().to_string(), + tenant, + ) + }, + ) + .await?; } Ok(()) } diff --git a/src/storage/gcs.rs b/src/storage/gcs.rs index 55458fe10..bd398cf1d 100644 --- a/src/storage/gcs.rs +++ b/src/storage/gcs.rs @@ -55,7 +55,7 @@ use object_store::{ path::Path as StorePath, }; use relative_path::{RelativePath, RelativePathBuf}; -use tokio::{fs::OpenOptions, io::AsyncReadExt}; +use tokio::fs::OpenOptions; use tracing::error; @@ -65,7 +65,9 @@ use super::{ STREAM_METADATA_FILE_NAME, metrics_layer::MetricLayer, object_storage::{parseable_json_path, stream_data_listing_prefix}, - partial_path, to_object_store_path, + partial_path, + s3::{read_file_for_single_put, upload_file_parts, use_single_put}, + to_object_store_path, }; use crate::storage::GET_OBJECTS_CONCURRENCY; @@ -507,9 +509,15 @@ impl Gcs { let total_size = meta.len() as usize; tracing::Span::current().record("total_bytes", total_size); let min_multipart_size = PARSEABLE.options.min_multipart_size as usize; - if total_size < min_multipart_size || !PARSEABLE.options.enable_multipart { - let mut data = Vec::new(); - file.read_to_end(&mut data).await?; + if use_single_put( + total_size, + min_multipart_size, + PARSEABLE.options.enable_multipart, + ) { + // The body is exactly the file that was measured above. One that + // ended early or grew while it was read fails here and is never + // put. + let data = read_file_for_single_put(file, total_size).await?; // Track single PUT operation for small files let result = self.client.put(location, data.into()).await; @@ -534,56 +542,31 @@ impl Gcs { return Ok(()); } else { let async_writer = self.client.put_multipart(location).await; - let mut async_writer = match async_writer { + let async_writer = match async_writer { Ok(writer) => writer, Err(err) => { return Err(err.into()); } }; - let mut data = Vec::new(); - file.read_to_end(&mut data).await?; - - let has_final_partial_part = !total_size.is_multiple_of(min_multipart_size); - let num_full_parts = total_size / min_multipart_size; - let total_parts = num_full_parts + if has_final_partial_part { 1 } else { 0 }; - - // Upload each part with metrics - for part_number in 0..(total_parts) { - let start_pos = part_number * min_multipart_size; - let end_pos = if part_number == num_full_parts && has_final_partial_part { - // Last part might be smaller than 5MB (which is allowed) - total_size - } else { - // All other parts must be at least 5MB - start_pos + min_multipart_size - }; - - // Extract this part's data - let part_data = data[start_pos..end_pos].to_vec(); - - // Track individual part upload - let result = async_writer.put_part(part_data.into()).await; - if result.is_err() { - return Err(result.err().unwrap().into()); - } - increment_object_store_calls_by_date( - "PUT_MULTIPART", - &Utc::now().date_naive().to_string(), - tenant, - ); - } - // Track multipart completion - let complete_result = async_writer.complete().await; - if let Err(err) = complete_result { - if let Err(abort_err) = async_writer.abort().await { - error!( - "Failed to abort multipart upload after completion failure: {:?}", - abort_err - ); - } - return Err(err.into()); - } + // The file is read one part at a time, never whole, and has to + // be exactly as long as it was measured. A read, part or + // completion failure aborts the upload, and so does dropping it + // when the task is cancelled, so that no parts are left behind. + upload_file_parts( + &mut file, + async_writer, + total_size, + min_multipart_size, + || { + increment_object_store_calls_by_date( + "PUT_MULTIPART", + &Utc::now().date_naive().to_string(), + tenant, + ) + }, + ) + .await?; } Ok(()) } diff --git a/src/storage/localfs.rs b/src/storage/localfs.rs index 612fce67d..f53bcdf6a 100644 --- a/src/storage/localfs.rs +++ b/src/storage/localfs.rs @@ -47,7 +47,8 @@ use crate::{ }; use super::object_storage::{ - ConditionalMetadataError, MetadataVersion, MetadataWriteCondition, VersionedMetadata, + ConditionalMetadataError, MetadataVersion, MetadataWriteCondition, UploadBuffering, + VersionedMetadata, }; use super::{ @@ -258,39 +259,28 @@ impl LocalFS { where L: FnOnce(&Path, &Path) -> std::io::Result<()> + Send + 'static, { - let mut file = if is_immutable_parquet_key(key) { + if is_immutable_parquet_key(key) { let to_path = self.path_in_root(key); - let fallback_source = match hard_link_into_new_file_with(path, &to_path, link).await? { - HardLinkResult::Linked => { - record_local_put_metrics(tenant_id); - return Ok(()); - } - HardLinkResult::UseCopyFallback(source) => { - match copy_into_new_file(source, &to_path).await? { - None => { - record_local_put_metrics(tenant_id); - return Ok(()); - } - Some(source) => source, - } - } - HardLinkResult::UseBufferedFallback(source) => source, - }; - // Stream-replace an existing `.parquet` destination via temp + atomic - // rename so large retries never buffer the whole file in memory and - // never mutate a hard-linked query lease inode in place. - match atomic_replace_parquet_from_file(fallback_source, &to_path).await? { - None => { - record_local_put_metrics(tenant_id); - return Ok(()); + match hard_link_into_new_file_with(&self.root, path, &to_path, link).await? { + HardLinkResult::Linked => {} + // Whatever kept the staged file from being linked, it is + // streamed once into a private file that an atomic rename + // publishes. A new destination and one that is replaced take + // the same single copy, also when the destination appears + // while that copy runs, and no step holds the file in memory. + HardLinkResult::Copy(source) => { + atomic_replace_parquet_from_file(&self.root, source, &to_path).await? } - Some(source) => source, } - } else if !is_dashboard_metadata(key) { + record_local_put_metrics(tenant_id); + return Ok(()); + } + let mut file = if !is_dashboard_metadata(key) { let source = OpenOptions::new().read(true).open(path).await?; let to_path = self.path_in_root(key); match copy_into_new_file(source, &to_path).await? { None => { + sync_ancestors_of_published_object(self.root.clone(), to_path).await?; record_local_put_metrics(tenant_id); return Ok(()); } @@ -299,6 +289,12 @@ impl LocalFS { } else { OpenOptions::new().read(true).open(path).await? }; + // Only metadata gets here: a dashboard document, which is written + // under its generation lock, or another non-Parquet object whose name + // is taken or could not be published. Those are read whole so that + // `put_object` can decide how each is committed, after any error from + // reading the source. A Parquet file, the only large object the + // server uploads, never is. let mut data = Vec::new(); file.read_to_end(&mut data).await?; self.put_object(key, data.into(), tenant_id).await @@ -360,6 +356,13 @@ impl ObjectStorage for LocalFS { .await } + /// A staged Parquet file is hard-linked into the store, or streamed in + /// small chunks where it cannot be: its upload never holds the file in + /// memory, and so takes nothing from the upload memory budget. + fn upload_buffering(&self) -> UploadBuffering { + UploadBuffering::Unbuffered + } + async fn get_buffered_reader( &self, _path: &RelativePath, @@ -731,17 +734,19 @@ impl ObjectStorage for LocalFS { .map_err(local_metadata_error) } else if is_immutable_parquet_key(path) { let path = self.path_in_root(path); - tokio::task::spawn_blocking(move || atomic_parquet_write(&path, &resource)) + let root = self.root.clone(); + tokio::task::spawn_blocking(move || atomic_parquet_write(&root, &path, &resource)) .await .map_err(ObjectStorageError::from)? } else { + // `manifest.json`, `.stream.json`, `.schema` and the like. A + // truncating write in place would leave an empty or partial + // object behind if the process died in the middle of it. let path = self.path_in_root(path); - if let Some(parent) = path.parent() { - fs::create_dir_all(parent).await?; - } - fs::write(path, resource) + let root = self.root.clone(); + tokio::task::spawn_blocking(move || put_plain_object(&root, &path, &resource)) .await - .map_err(ObjectStorageError::from) + .map_err(ObjectStorageError::from)? }; if res.is_ok() { // Record single file written successfully @@ -1154,6 +1159,12 @@ impl ObjectStorage for LocalFS { while let Some(dir) = dirs.pop() { for entry in std::fs::read_dir(dir)? { let entry = entry?; + // A private file of a write in flight, or one a crash left + // behind, is no object. It may also be gone before it can be + // examined. + if is_upload_temp(&entry.path()) { + continue; + } let meta = entry.metadata()?; if entry.file_type()?.is_symlink() { continue; @@ -1299,10 +1310,31 @@ async fn dir_name(entry: DirEntry) -> Result, ObjectStorageError> const UPLOAD_TEMP_PREFIX: &str = ".parseable-upload-"; const UPLOAD_COPY_BUFFER_SIZE: usize = 256 * 1024; +/// Copies the unread remainder of `source` to `dest` and returns its length. +/// +/// On Linux `std::io::copy` between two files stays inside the kernel. It +/// uses `copy_file_range(2)`, which shares extents instead of copying them +/// where the filesystem can, `sendfile(2)` across filesystems, and a +/// read/write loop of its own only when neither works. Elsewhere it is just +/// that loop with a small buffer, so the file is streamed through a larger +/// one here. fn copy_file_buffered( source: &mut std::fs::File, dest: &mut std::fs::File, ) -> std::io::Result { + #[cfg(any(target_os = "linux", target_os = "android"))] + { + std::io::copy(source, dest) + } + #[cfg(not(any(target_os = "linux", target_os = "android")))] + { + copy_file_chunked(source, dest) + } +} + +/// The portable streaming copy: one 256 KiB buffer, whatever the file's size. +#[cfg(any(test, not(any(target_os = "linux", target_os = "android"))))] +fn copy_file_chunked(source: &mut std::fs::File, dest: &mut std::fs::File) -> std::io::Result { use std::io::{Read, Write}; let mut buf = vec![0u8; UPLOAD_COPY_BUFFER_SIZE]; @@ -1326,8 +1358,12 @@ fn copy_file_buffered( /// publication use the original buffered read + put_object path. If copying has /// consumed the source, restore its initial position before returning it. Thus a /// destination appearing during copying still gets buffered overwrite semantics -/// (including symlink, hard-link and mode behavior). Those overwrites remain -/// non-atomic. Copy failures retain their original error and never unlink to_path. +/// (including symlink, hard-link and mode behavior). put_object makes the +/// overwrite of a plain file atomic; one through a link is written in place. +/// Copy failures retain their original error and never unlink to_path. +/// +/// Only non-Parquet objects are published this way. A `.parquet` object that +/// cannot be hard-linked goes through `atomic_replace_parquet_from_file`. async fn copy_into_new_file( source: fs::File, to_path: &Path, @@ -1365,7 +1401,7 @@ where { let mut source = source.into_std().await; let to_path = to_path.to_path_buf(); - let copied = tokio::task::spawn_blocking(move || { + let copied = tokio::task::spawn_blocking(move || -> Result<_, ObjectStorageError> { use std::io::{Seek, SeekFrom}; if !source.metadata().is_ok_and(|meta| meta.is_file()) { @@ -1394,7 +1430,7 @@ where if let Err(err) = copy(&mut source, temp.file.as_mut().expect("open copy file")) { hook(UploadCopyStage::CopyFailed, &temp.path); // Drop closes and removes only this invocation's private name. - return Err(err); + return Err(err.into()); } // Persist copied data before publishing so cross-device fallback has // the same crash durability as the hard-link and atomic-put paths. @@ -1410,7 +1446,9 @@ where source.seek(SeekFrom::Start(position))?; return Ok(Some(source)); } - let _ = sync_upload_parent_directory(parent); + // The new name is durable only once its directory is. A failed sync + // is reported, never taken for an object that a crash could drop. + sync_upload_parent_directory(parent)?; Ok(None) }) .await??; @@ -1480,29 +1518,33 @@ impl Drop for UploadTemp { enum HardLinkResult { Linked, - UseCopyFallback(fs::File), - UseBufferedFallback(fs::File), + /// The staged file could not be linked and is copied instead. + Copy(fs::File), } enum HardLinkBlockingOutcome { Linked, - UseCopyFallback(std::fs::File), - UseBufferedFallback(std::fs::File), + Copy(std::fs::File), } /// Zero-copy fast path for publishing an immutable regular file into a new /// destination on the same filesystem via `hard_link`. /// -/// Preserves existing `upload_multipart` error priority and fallback semantics: -/// - Source open failures return immediately without creating destination directories. -/// - Non-regular sources, pre-existing destinations (including symlinks/directories), -/// parent creation failures, and concurrent `AlreadyExists` races fall back directly -/// to the buffered read + `put_object` path. -/// - Symlink sources and other `hard_link` failures (e.g. cross-device `EXDEV`, -/// `Unsupported`, `PermissionDenied`) fall back to streaming `copy_into_new_file`. -/// - On success, syncs the destination parent directory so the new directory entry is -/// durable before callers unlink `src_path`. +/// - A source that cannot be opened fails here, before any destination +/// directory is created. +/// - A destination that already is this very file is the retry of an upload +/// that went through: its directory entries are synced again and nothing is +/// copied. +/// - Everything else that keeps the file from being linked hands the open +/// source back, to be streamed by [`atomic_replace_parquet_from_file`]: a +/// source that is not a regular file or is reached through a symlink, a +/// destination that exists or appears concurrently, a parent that cannot be +/// created, and any `hard_link` failure such as cross-device `EXDEV`, +/// `Unsupported` or `PermissionDenied`. +/// - On success the destination's directory entries are synced up to the +/// store root, so the new name is durable before callers unlink `src_path`. async fn hard_link_into_new_file_with( + root: &Path, src_path: &Path, to_path: &Path, link: L, @@ -1510,19 +1552,20 @@ async fn hard_link_into_new_file_with( where L: FnOnce(&Path, &Path) -> std::io::Result<()> + Send + 'static, { + let root = root.to_path_buf(); let src_path = src_path.to_path_buf(); let to_path = to_path.to_path_buf(); let outcome = tokio::task::spawn_blocking(move || -> Result<_, ObjectStorageError> { let source = std::fs::OpenOptions::new().read(true).open(&src_path)?; let Ok(src_fd_meta) = source.metadata() else { - return Ok(HardLinkBlockingOutcome::UseBufferedFallback(source)); + return Ok(HardLinkBlockingOutcome::Copy(source)); }; if !src_fd_meta.is_file() { - return Ok(HardLinkBlockingOutcome::UseBufferedFallback(source)); + return Ok(HardLinkBlockingOutcome::Copy(source)); } - // symlink_metadata also catches dangling symlinks. Any lookup error - // other than NotFound belongs to the buffered path, after it has read - // the source (preserving source-read-error priority). + // symlink_metadata also catches dangling symlinks. A destination that + // cannot be examined is left to the copy, which reports why after it + // has read the source. match std::fs::symlink_metadata(&to_path) { Err(err) if err.kind() == std::io::ErrorKind::NotFound => {} #[cfg(unix)] @@ -1530,36 +1573,37 @@ where if dst_meta.file_type().is_file() && same_unix_inode(&src_fd_meta, &dst_meta) => { if let Some(parent) = to_path.parent().filter(|p| !p.as_os_str().is_empty()) { - sync_upload_parent_directory(parent)?; + sync_upload_directories(&root, parent)?; } drop(source); return Ok(HardLinkBlockingOutcome::Linked); } - _ => return Ok(HardLinkBlockingOutcome::UseBufferedFallback(source)), + _ => return Ok(HardLinkBlockingOutcome::Copy(source)), } // Only hard-link when src_path itself is a regular file (not a symlink) // referring to the exact inode we opened; otherwise stream via copy. let Ok(src_path_meta) = std::fs::symlink_metadata(&src_path) else { - return Ok(HardLinkBlockingOutcome::UseCopyFallback(source)); + return Ok(HardLinkBlockingOutcome::Copy(source)); }; if !src_path_meta.file_type().is_file() { - return Ok(HardLinkBlockingOutcome::UseCopyFallback(source)); + return Ok(HardLinkBlockingOutcome::Copy(source)); } #[cfg(unix)] if !same_unix_inode(&src_fd_meta, &src_path_meta) { - return Ok(HardLinkBlockingOutcome::UseCopyFallback(source)); + return Ok(HardLinkBlockingOutcome::Copy(source)); } let Some(parent) = to_path.parent().filter(|p| !p.as_os_str().is_empty()) else { - return Ok(HardLinkBlockingOutcome::UseBufferedFallback(source)); + return Ok(HardLinkBlockingOutcome::Copy(source)); }; if std::fs::create_dir_all(parent).is_err() { - // Preserve source-read-error priority over parent/setup errors. - return Ok(HardLinkBlockingOutcome::UseBufferedFallback(source)); + // The copy meets the same error and reports it, after any error + // from reading the source. + return Ok(HardLinkBlockingOutcome::Copy(source)); } match link(&src_path, &to_path) { Ok(()) => { drop(source); - sync_upload_parent_directory(parent)?; + sync_upload_directories(&root, parent)?; Ok(HardLinkBlockingOutcome::Linked) } Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => { @@ -1569,24 +1613,24 @@ where && same_unix_inode(&src_fd_meta, &dst_meta) { drop(source); - sync_upload_parent_directory(parent)?; + sync_upload_directories(&root, parent)?; return Ok(HardLinkBlockingOutcome::Linked); } - Ok(HardLinkBlockingOutcome::UseBufferedFallback(source)) + Ok(HardLinkBlockingOutcome::Copy(source)) + } + Err(err) => { + if err.kind() == std::io::ErrorKind::CrossesDevices { + warn_cross_device_upload_once(&src_path, &to_path); + } + Ok(HardLinkBlockingOutcome::Copy(source)) } - Err(_) => Ok(HardLinkBlockingOutcome::UseCopyFallback(source)), } }) .await??; Ok(match outcome { HardLinkBlockingOutcome::Linked => HardLinkResult::Linked, - HardLinkBlockingOutcome::UseCopyFallback(file) => { - HardLinkResult::UseCopyFallback(fs::File::from_std(file)) - } - HardLinkBlockingOutcome::UseBufferedFallback(file) => { - HardLinkResult::UseBufferedFallback(fs::File::from_std(file)) - } + HardLinkBlockingOutcome::Copy(file) => HardLinkResult::Copy(fs::File::from_std(file)), }) } @@ -1596,48 +1640,172 @@ fn same_unix_inode(a: &std::fs::Metadata, b: &std::fs::Metadata) -> bool { a.dev() == b.dev() && a.ino() == b.ino() } -/// Stream-replaces an existing `.parquet` destination from an open regular file -/// via a private temporary file, `sync_all`, and atomic `rename`. Returns -/// `Ok(None)` on success, or `Ok(Some(source))` to defer non-regular/setup edge -/// cases to the buffered fallback so source-read error priority is preserved. +/// Whether this is the first staged file the process finds on another +/// filesystem than its destination. +fn first_cross_device_upload() -> bool { + static SEEN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + !SEEN.swap(true, std::sync::atomic::Ordering::Relaxed) +} + +/// Says once per process that uploads are being copied instead of linked. +fn warn_cross_device_upload_once(src_path: &Path, to_path: &Path) { + if first_cross_device_upload() { + tracing::warn!( + "Staged file {} is on a different filesystem than its destination {}, so uploads to the local store are copied instead of hard-linked. Placing the staging directory and the data directory on the same filesystem enables zero-copy hard-linking, which saves writing every Parquet file to disk a second time (about 100 bytes per ingested line).", + src_path.display(), + to_path.display() + ); + } +} + +/// Publishes an open source as a `.parquet` object when it could not be +/// hard-linked: one streamed copy into a private file in the destination's +/// directory, `sync_all`, an atomic `rename`, and a sync of the directory +/// entries up to the store root. +/// +/// The rename serves a new destination and an existing one alike, so a +/// destination that appears while the copy runs costs no second copy. It +/// never writes into the inode it replaces, which may be hard-linked to a +/// staged file that a query lease still reads. Only one copy buffer is held +/// in memory, whatever the file's size and whichever step fails. async fn atomic_replace_parquet_from_file( + root: &Path, source: fs::File, to_path: &Path, -) -> Result, ObjectStorageError> { +) -> Result<(), ObjectStorageError> { + atomic_replace_parquet_from_file_with(root, source, to_path, copy_file_buffered).await +} + +/// [`atomic_replace_parquet_from_file`] with the copy step injected, so that +/// tests can count copies and interleave other writers with one. +async fn atomic_replace_parquet_from_file_with( + root: &Path, + source: fs::File, + to_path: &Path, + copy: C, +) -> Result<(), ObjectStorageError> +where + C: FnOnce(&mut std::fs::File, &mut std::fs::File) -> std::io::Result + Send + 'static, +{ let mut source = source.into_std().await; + let root = root.to_path_buf(); let to_path = to_path.to_path_buf(); - let fallback = tokio::task::spawn_blocking(move || -> Result<_, ObjectStorageError> { - if !source.metadata().is_ok_and(|meta| meta.is_file()) { - return Ok(Some(source)); - } - let Some(parent) = to_path.parent().filter(|p| !p.as_os_str().is_empty()) else { - return Ok(Some(source)); - }; - if std::fs::create_dir_all(parent).is_err() { - return Ok(Some(source)); - } - let Ok(mut temp) = UploadTemp::create(parent, &to_path) else { - return Ok(Some(source)); + tokio::task::spawn_blocking(move || -> Result<(), ObjectStorageError> { + use std::io::Seek; + + // A staged file is complete before it is uploaded, so what is left of + // a regular source has a known length. Any other source ends where + // it ends. + let expected = match source.metadata() { + Ok(metadata) if metadata.is_file() => { + Some(metadata.len().saturating_sub(source.stream_position()?)) + } + _ => None, }; - { - let dst = temp.file.as_mut().expect("open temp file"); - copy_file_buffered(&mut source, dst)?; - dst.sync_all()?; + let (mut temp, copied) = copy_source_into_private_file(&mut source, &to_path, copy)?; + if let Some(expected) = expected { + verify_copied_length(copied, expected)?; } - drop(temp.file.take()); + let private = temp.file.take().expect("open temp file"); + // Persist the data before it gets its public name, so that a crash + // cannot leave the name on a file that is not all there. + private.sync_all()?; + // Close before renaming, including on platforms with restrictive + // file-sharing rules. + drop(private); std::fs::rename(&temp.path, &to_path)?; - sync_upload_parent_directory(parent)?; - Ok(None) + if let Some(parent) = to_path.parent() { + sync_upload_directories(&root, parent)?; + } + Ok(()) }) - .await??; - Ok(fallback.map(fs::File::from_std)) + .await? +} + +/// Streams the unread remainder of `source` into a private file next to +/// `to_path`, and returns that file with the number of bytes it was given. +/// +/// The first buffer is read before anything is created: a source that cannot +/// be read, a directory for one, fails on its own error and leaves no trace +/// in the store. If the private file then cannot be set up, the rest of the +/// source is still read through. An error from reading the source so keeps +/// its precedence over the set-up error, as it had when the whole file was +/// read into memory before the destination was looked at. +fn copy_source_into_private_file( + source: &mut std::fs::File, + to_path: &Path, + copy: C, +) -> Result<(UploadTemp, u64), ObjectStorageError> +where + C: FnOnce(&mut std::fs::File, &mut std::fs::File) -> std::io::Result, +{ + use std::io::Write; + + let mut head = vec![0u8; UPLOAD_COPY_BUFFER_SIZE]; + let head_len = read_until_full(source, &mut head)?; + let private = match to_path.parent().filter(|p| !p.as_os_str().is_empty()) { + Some(parent) => { + std::fs::create_dir_all(parent).and_then(|()| UploadTemp::create(parent, to_path)) + } + None => Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + "parquet object path has no parent directory", + )), + }; + let mut temp = match private { + Ok(temp) => temp, + Err(setup_error) => { + while read_until_full(source, &mut head)? != 0 {} + return Err(setup_error.into()); + } + }; + let file = temp.file.as_mut().expect("open temp file"); + file.write_all(&head[..head_len])?; + // A whole buffer is a multiple of every block size in use, so the kernel + // can still share the extents of the remainder instead of copying them. + drop(head); + let copied = head_len as u64 + copy(source, file)?; + Ok((temp, copied)) +} + +/// Fills `buf` from `source`, stopping short only at the end of the file. +fn read_until_full(source: &mut std::fs::File, buf: &mut [u8]) -> std::io::Result { + use std::io::Read; + + let mut filled = 0; + while filled < buf.len() { + match source.read(&mut buf[filled..]) { + Ok(0) => break, + Ok(read) => filled += read, + Err(err) if err.kind() == std::io::ErrorKind::Interrupted => {} + Err(err) => return Err(err), + } + } + Ok(filled) +} + +/// A copy of any other length than its source had is not a copy of it: the +/// source was truncated or appended to while it was read. The object-store +/// uploads make the same check. +fn verify_copied_length(copied: u64, expected: u64) -> std::io::Result<()> { + match copied.cmp(&expected) { + std::cmp::Ordering::Equal => Ok(()), + std::cmp::Ordering::Less => Err(std::io::Error::new( + std::io::ErrorKind::UnexpectedEof, + format!("file ended after {copied} of {expected} bytes during upload"), + )), + std::cmp::Ordering::Greater => Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + format!("file grew beyond {expected} bytes during upload"), + )), + } } /// Writes an immutable `.parquet` object via a fresh private temporary file /// and atomic rename, so overwriting a key never truncates or mutates an /// existing inode in place (which may be hard-linked to a staging file held /// open by a concurrent query lease). -fn atomic_parquet_write(path: &Path, bytes: &[u8]) -> Result<(), ObjectStorageError> { +fn atomic_parquet_write(root: &Path, path: &Path, bytes: &[u8]) -> Result<(), ObjectStorageError> { use std::io::Write; let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) else { return Err(std::io::Error::new( @@ -1655,10 +1823,203 @@ fn atomic_parquet_write(path: &Path, bytes: &[u8]) -> Result<(), ObjectStorageEr } drop(temp.file.take()); std::fs::rename(&temp.path, path)?; - sync_upload_parent_directory(parent)?; + sync_upload_directories(root, parent)?; Ok(()) } +/// Writes a non-Parquet object that is not dashboard metadata: a +/// `manifest.json`, `.stream.json`, `.schema`, an alert and the like. +/// +/// The object is committed the way dashboard metadata is: a private file is +/// written and synced, renamed over the name, and the directory entries are +/// synced up to the store root. A crash so leaves the old object or the new +/// one, never an empty or partial one, and a concurrent reader never sees a +/// write in progress. +/// +/// A name that only a write through it can serve keeps the write in place it +/// always had, see [`replace_plain_object`]. That write is synced as well. +fn put_plain_object(root: &Path, path: &Path, bytes: &[u8]) -> Result<(), ObjectStorageError> { + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + } + if !replace_plain_object(path, bytes)? { + write_plain_object_in_place(path, bytes)?; + } + match path.parent().filter(|p| !p.as_os_str().is_empty()) { + Some(parent) => sync_upload_directories(root, parent), + None => Ok(()), + } +} + +/// Commits `bytes` under `path` by renaming a synced private file over it, +/// and returns `true`. Returns `false`, with nothing changed, where the name +/// has to be written through instead to keep what it stands for: +/// +/// - a symlink, which is followed to its target; a file with other hard +/// links, whose holders see the write; and anything that is not a regular +/// file, such as a directory, which fails as it always has; +/// - a file that belongs to another owner, which a replacement would hand to +/// this process; +/// - a directory in which no private file can be created. +/// +/// A file this process may not write to is not replaced either. It fails +/// with the error that opening it for writing gives, although a rename over +/// it would have gone through. The replacement carries the mode of the file +/// it replaces. +fn replace_plain_object(path: &Path, bytes: &[u8]) -> Result { + use std::io::Write; + + let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) else { + return Ok(false); + }; + let replaced = match std::fs::symlink_metadata(path) { + Err(err) if err.kind() == std::io::ErrorKind::NotFound => None, + Ok(existing) if is_sole_name_of_regular_file(&existing) => Some(existing), + _ => return Ok(false), + }; + let Ok(mut temp) = UploadTemp::create(parent, path) else { + return Ok(false); + }; + let file = temp.file.as_mut().expect("open temp file"); + if let Some(existing) = &replaced { + if !file + .metadata() + .is_ok_and(|private| has_owner_of_new_files(existing, &private)) + { + warn_in_place_write_once(path); + return Ok(false); + } + match std::fs::OpenOptions::new().write(true).open(path) { + Ok(_) => {} + // Deleted since it was examined: the name is simply new. + Err(err) if err.kind() == std::io::ErrorKind::NotFound => {} + Err(err) => return Err(err.into()), + } + } + file.write_all(bytes)?; + if let Some(existing) = &replaced { + file.set_permissions(existing.permissions())?; + } + // Persist the data before it gets its public name, so that a crash + // cannot leave the name on a file that is not all there. + file.sync_all()?; + // Close before renaming, including on platforms with restrictive + // file-sharing rules. + drop(temp.file.take()); + std::fs::rename(&temp.path, path)?; + Ok(true) +} + +/// Whether `existing` is a regular file that has no other name. A symlink is +/// written through to its target, and a file with other hard links is shared +/// with whoever holds them: neither can be swapped for a new file. +fn is_sole_name_of_regular_file(existing: &std::fs::Metadata) -> bool { + if !existing.file_type().is_file() { + return false; + } + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + existing.nlink() == 1 + } + #[cfg(not(unix))] + { + true + } +} + +/// Whether `existing` is owned the way `private`, a file this process has +/// just created beside it, is. +fn has_owner_of_new_files(existing: &std::fs::Metadata, private: &std::fs::Metadata) -> bool { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + existing.uid() == private.uid() && existing.gid() == private.gid() + } + #[cfg(not(unix))] + { + let _ = (existing, private); + true + } +} + +/// Says once per process that an object of another owner is written in place. +fn warn_in_place_write_once(path: &Path) { + static WARNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + if !WARNED.swap(true, std::sync::atomic::Ordering::Relaxed) { + tracing::warn!( + "{} belongs to another user or group than the files this server creates, so it is written in place, which is not atomic: a crash during the write can leave it incomplete. Give the data directory to the server's user to have such objects replaced atomically.", + path.display() + ); + } +} + +/// The write a plain object always had: through the existing name, into +/// whatever it stands for. The data is synced before the write is +/// acknowledged; a device or pipe behind a link has nothing to sync. +fn write_plain_object_in_place(path: &Path, bytes: &[u8]) -> Result<(), ObjectStorageError> { + use std::io::Write; + + let mut file = std::fs::File::create(path)?; + file.write_all(bytes)?; + match file.sync_all() { + Err(err) + if matches!( + err.kind(), + std::io::ErrorKind::InvalidInput | std::io::ErrorKind::Unsupported + ) => + { + Ok(()) + } + synced => Ok(synced?), + } +} + +/// Makes an object just published in `directory` durable: syncs `directory` +/// for the object's own entry, then every directory above it within `root` +/// for the entries that lead to it. +fn sync_upload_directories(root: &Path, directory: &Path) -> Result<(), ObjectStorageError> { + sync_upload_parent_directory(directory)?; + sync_upload_ancestor_directories(root, directory) +} + +/// Syncs each directory above `directory`, up to and including `root`. That +/// persists the entry of `directory` and of every directory on the way to it. +/// +/// `create_dir_all` may have just created any of them, and so may another +/// upload that races this one into the same new partition. Finding a +/// directory in place therefore proves nothing about its entry, and the +/// whole chain is synced before an object is acknowledged, as it is for +/// dashboard metadata. Otherwise a crash could drop a `date=`, `hour=` or +/// `minute=` directory with every object in it, after the staged sources of +/// those objects were deleted. +fn sync_upload_ancestor_directories( + root: &Path, + directory: &Path, +) -> Result<(), ObjectStorageError> { + for ancestor in directory + .ancestors() + .skip(1) + .take_while(|ancestor| ancestor.starts_with(root)) + { + sync_upload_parent_directory(ancestor)?; + } + Ok(()) +} + +/// [`sync_upload_ancestor_directories`] for an object whose own directory +/// has been synced by the helper that published it. +async fn sync_ancestors_of_published_object( + root: PathBuf, + object: PathBuf, +) -> Result<(), ObjectStorageError> { + tokio::task::spawn_blocking(move || match object.parent() { + Some(parent) => sync_upload_ancestor_directories(&root, parent), + None => Ok(()), + }) + .await? +} + fn sync_upload_parent_directory(directory: &Path) -> Result<(), ObjectStorageError> { match sync_directory(directory) { Ok(()) => Ok(()), @@ -1783,6 +2144,8 @@ fn sync_metadata_parent(path: &Path) -> Result<(), ObjectStorageError> { } fn sync_directory(directory: &Path) -> Result<(), ObjectStorageError> { + #[cfg(test)] + conditional_metadata_tests::injected_directory_sync_failure(directory)?; #[cfg(unix)] std::fs::File::open(directory)?.sync_all()?; #[cfg(test)] @@ -1795,7 +2158,9 @@ fn atomic_metadata_write(path: &Path, bytes: &[u8]) -> Result<(), ObjectStorageE let parent = path .parent() .ok_or_else(|| ObjectStorageError::Custom("metadata path has no parent".into()))?; - let temporary = parent.join(format!(".metadata-{}.tmp", ulid::Ulid::new())); + // The reserved private prefix keeps the file out of every listing, also + // when a crash leaves it behind. + let temporary = parent.join(format!("{UPLOAD_TEMP_PREFIX}{}.tmp", ulid::Ulid::new())); let result = (|| { let mut file = std::fs::OpenOptions::new() .write(true) @@ -1874,6 +2239,43 @@ mod conditional_metadata_tests { .push(directory.to_path_buf()); } + static FAILING_DIRECTORY_SYNCS: std::sync::Mutex> = + std::sync::Mutex::new(Vec::new()); + + /// Makes every sync of `directory` fail for as long as the guard lives. + pub(super) struct FailingDirectorySync(PathBuf); + + pub(super) fn fail_directory_syncs(directory: &Path) -> FailingDirectorySync { + FAILING_DIRECTORY_SYNCS + .lock() + .unwrap() + .push(directory.to_path_buf()); + FailingDirectorySync(directory.to_path_buf()) + } + + impl Drop for FailingDirectorySync { + fn drop(&mut self) { + let mut failing = FAILING_DIRECTORY_SYNCS.lock().unwrap(); + if let Some(index) = failing.iter().position(|directory| *directory == self.0) { + failing.swap_remove(index); + } + } + } + + pub(super) fn injected_directory_sync_failure( + directory: &Path, + ) -> Result<(), ObjectStorageError> { + if FAILING_DIRECTORY_SYNCS + .lock() + .unwrap() + .iter() + .any(|failing| failing.as_path() == directory) + { + return Err(std::io::Error::other("injected directory sync failure").into()); + } + Ok(()) + } + fn take_directory_syncs_under(root: &Path) -> HashSet { let mut syncs = DIRECTORY_SYNCS.lock().unwrap(); let (taken, kept) = std::mem::take(&mut *syncs) @@ -2173,7 +2575,7 @@ mod conditional_metadata_tests { )); } - fn assert_synced_up_to_root(root: &Path, object: &Path, context: &str) { + pub(super) fn assert_synced_up_to_root(root: &Path, object: &Path, context: &str) { let synced = take_directory_syncs_under(root); for ancestor in object .parent() @@ -2704,6 +3106,7 @@ mod conditional_metadata_tests { #[cfg(test)] mod upload_multipart_tests { + use super::conditional_metadata_tests::{assert_synced_up_to_root, fail_directory_syncs}; use super::*; fn assert_no_upload_temps(directory: &Path) { @@ -3780,4 +4183,549 @@ mod upload_multipart_tests { assert_eq!(std::fs::read(&object).unwrap(), br#"{"title":"Test"}"#); assert_ne!(std::fs::metadata(&object).unwrap().ino(), src_ino); } + + fn files_under(directory: &Path) -> Vec { + let mut files = Vec::new(); + let mut pending = vec![directory.to_path_buf()]; + while let Some(directory) = pending.pop() { + for entry in std::fs::read_dir(directory).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + pending.push(path); + } else { + files.push(path); + } + } + } + files.sort(); + files + } + + fn assert_injected_sync_failure(result: Result) { + match result { + Err(ObjectStorageError::IoError(err)) => { + assert_eq!(err.to_string(), "injected directory sync failure") + } + other => panic!("unexpected result: {other:?}"), + } + } + + #[tokio::test] + async fn plain_put_object_replaces_the_object_and_leaves_no_private_file() { + use std::io::Read; + + let dir = tempfile::tempdir().unwrap(); + let storage = LocalFS::new(dir.path().to_path_buf()); + let keys = [ + "logs/.stream/.stream.json", + "logs/.stream/.schema", + "logs/date=2026-11-30/manifest.json", + ".parseable/.parseable.json", + ]; + let first = Bytes::from_static( + br#"{"version":1,"padding":"a first version that is a good deal longer"}"#, + ); + let second = Bytes::from_static(br#"{"version":2}"#); + for key in keys { + let key = RelativePath::new(key); + let object = storage.path_in_root(key); + storage.put_object(key, first.clone(), &None).await.unwrap(); + assert_eq!(std::fs::read(&object).unwrap(), first); + assert_no_upload_temps(object.parent().unwrap()); + + // A reader that has the object open, as a GET in flight has. + let mut reader = std::fs::File::open(&object).unwrap(); + storage + .put_object(key, second.clone(), &None) + .await + .unwrap(); + assert_eq!(std::fs::read(&object).unwrap(), second); + assert_eq!(storage.get_object(key, &None).await.unwrap(), second); + // The old object was replaced, not truncated and written again: + // the reader still gets all of it, never an empty or mixed one. + let mut seen = Vec::new(); + reader.read_to_end(&mut seen).unwrap(); + assert_eq!(seen, first); + assert_no_upload_temps(object.parent().unwrap()); + } + // Nothing but the objects is left anywhere under the store: no + // private file, and no metadata lock, which plain objects do not take. + let mut expected: Vec = keys.iter().map(|key| dir.path().join(key)).collect(); + expected.sort(); + assert_eq!(files_under(dir.path()), expected); + } + + #[cfg(unix)] + #[tokio::test] + async fn plain_put_object_carries_the_mode_of_the_object_it_replaces() { + use std::os::unix::fs::{MetadataExt, PermissionsExt}; + + let dir = tempfile::tempdir().unwrap(); + let storage = LocalFS::new(dir.path().to_path_buf()); + let key = RelativePath::new("logs/.stream/.stream.json"); + let object = storage.path_in_root(key); + storage + .put_object(key, Bytes::from_static(b"old"), &None) + .await + .unwrap(); + std::fs::set_permissions(&object, std::fs::Permissions::from_mode(0o640)).unwrap(); + let before = std::fs::metadata(&object).unwrap(); + + storage + .put_object(key, Bytes::from_static(b"new"), &None) + .await + .unwrap(); + + let after = std::fs::metadata(&object).unwrap(); + assert_eq!(std::fs::read(&object).unwrap(), b"new"); + assert_ne!(after.ino(), before.ino()); + assert_eq!(after.permissions().mode(), before.permissions().mode()); + assert_eq!(after.nlink(), 1); + assert_no_upload_temps(object.parent().unwrap()); + } + + #[tokio::test] + async fn put_object_syncs_every_directory_up_to_the_root() { + for key in [ + "logs/.stream/.stream.json", + "logs/date=2026-11-30/manifest.json", + "logs/date=2026-11-30/hour=10/minute=05/data.parquet", + ] { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().to_path_buf(); + let storage = LocalFS::new(root.clone()); + let object = root.join(key); + storage + .put_object(RelativePath::new(key), Bytes::from_static(b"{}"), &None) + .await + .unwrap(); + assert_synced_up_to_root(&root, &object, &format!("first write of {key}")); + // A directory that is already there proves nothing about its + // entry: another writer may have created it a moment ago. + storage + .put_object(RelativePath::new(key), Bytes::from_static(b"[]"), &None) + .await + .unwrap(); + assert_synced_up_to_root(&root, &object, &format!("overwrite of {key}")); + assert_eq!(std::fs::read(&object).unwrap(), b"[]"); + } + } + + #[tokio::test] + async fn put_object_is_not_acknowledged_when_a_directory_sync_fails() { + for key in [ + "logs/.stream/.stream.json", + "logs/date=2026-11-30/data.parquet", + ] { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().to_path_buf(); + let storage = LocalFS::new(root.clone()); + let object = root.join(key); + // The object's own directory, and one that only leads to it. + for failing in [object.parent().unwrap().to_path_buf(), root.clone()] { + let failure = fail_directory_syncs(&failing); + assert_injected_sync_failure( + storage + .put_object(RelativePath::new(key), Bytes::from_static(b"{}"), &None) + .await, + ); + assert_no_upload_temps(object.parent().unwrap()); + drop(failure); + storage + .put_object(RelativePath::new(key), Bytes::from_static(b"{}"), &None) + .await + .unwrap(); + assert_eq!(std::fs::read(&object).unwrap(), b"{}"); + assert_no_upload_temps(object.parent().unwrap()); + } + } + } + + #[tokio::test] + async fn uploads_sync_every_directory_up_to_the_root() { + let dir = tempfile::tempdir().unwrap(); + let store = dir.path().join("data"); + let source = dir.path().join("staged.parquet"); + std::fs::write(&source, pattern(1024)).unwrap(); + + // Hard-linked into partitions that did not exist. + let key = "logs/date=2026-11-30/hour=10/minute=05/part.parquet"; + upload(&store, key, &source).await.unwrap(); + assert_synced_up_to_root(&store, &store.join(key), "linked upload"); + // A retry of the same file syncs them again: the attempt before it + // may have failed at exactly that step. + upload(&store, key, &source).await.unwrap(); + assert_synced_up_to_root(&store, &store.join(key), "retried linked upload"); + // Another upload may have created the partition a moment ago, so an + // existing one is synced all the same. + let key = "logs/date=2026-11-30/hour=10/minute=05/part-2.parquet"; + upload(&store, key, &source).await.unwrap(); + assert_synced_up_to_root(&store, &store.join(key), "upload into a partition"); + + // Copied instead of linked. + let key = "logs/date=2026-11-30/hour=10/minute=06/part.parquet"; + LocalFS::new(store.clone()) + .upload_multipart_with_link(RelativePath::new(key), &source, &None, |_, _| { + Err(std::io::Error::from(std::io::ErrorKind::CrossesDevices)) + }) + .await + .unwrap(); + assert_synced_up_to_root(&store, &store.join(key), "copied upload"); + + // A non-Parquet object, which is copied into a new name. + let key = "logs/date=2026-12-01/manifest.json"; + upload(&store, key, &source).await.unwrap(); + assert_synced_up_to_root(&store, &store.join(key), "copied plain upload"); + } + + /// A staged file on another filesystem than the store cannot be linked. + /// If the destination appears while the file is being copied, the copy + /// that is already there is renamed over it: the source is not read again. + #[tokio::test] + async fn destination_appearing_during_the_copy_is_replaced_without_a_second_copy() { + use std::io::Read; + + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().join("store"); + let source = dir.path().join("staged.parquet"); + // More than one copy buffer. + let data = pattern(600 * 1024 + 17); + std::fs::write(&source, &data).unwrap(); + let object = root.join("stream/date=2026-11-30/hour=10/minute=05/part.parquet"); + + let copies = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let (leased_tx, leased_rx) = std::sync::mpsc::channel(); + let counted = copies.clone(); + let raced = object.clone(); + atomic_replace_parquet_from_file_with( + &root, + fs::File::open(&source).await.unwrap(), + &object, + move |src, dst| { + counted.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + // Another upload of the key wins the race while this one is + // still copying, and a query takes a lease on its object. + std::fs::write(&raced, b"published by the other upload")?; + leased_tx.send(std::fs::File::open(&raced)?).unwrap(); + copy_file_buffered(src, dst) + }, + ) + .await + .unwrap(); + + assert_eq!(copies.load(std::sync::atomic::Ordering::SeqCst), 1); + assert_eq!(std::fs::read(&object).unwrap(), data); + // The object that was replaced was not written into: the lease on + // it still reads what the other upload published. + let mut leased = leased_rx.recv().unwrap(); + let mut leased_bytes = Vec::new(); + leased.read_to_end(&mut leased_bytes).unwrap(); + assert_eq!(leased_bytes, b"published by the other upload"); + assert_no_upload_temps(object.parent().unwrap()); + assert_eq!(files_under(&root), vec![object.clone()]); + assert_synced_up_to_root(&root, &object, "copy that replaced a raced destination"); + // The staged source is untouched, for its owner to unlink. + assert_eq!(std::fs::read(&source).unwrap(), data); + } + + #[tokio::test] + async fn cross_device_upload_replaces_a_colliding_destination() { + let dir = tempfile::tempdir().unwrap(); + let store = dir.path().join("store"); + let source = dir.path().join("staged.parquet"); + let data = pattern(300 * 1024 + 3); + std::fs::write(&source, &data).unwrap(); + let key = "stream/date=2026-11-30/part.parquet"; + let object = store.join(key); + + let raced = object.clone(); + LocalFS::new(store.clone()) + .upload_multipart_with_link(RelativePath::new(key), &source, &None, move |_, _| { + // The destination appears, and the link fails across devices. + std::fs::write(&raced, b"colliding destination")?; + Err(std::io::Error::from(std::io::ErrorKind::CrossesDevices)) + }) + .await + .unwrap(); + + assert_eq!(std::fs::read(&object).unwrap(), data); + assert_eq!(files_under(&store), vec![object.clone()]); + assert_synced_up_to_root(&store, &object, "cross-device upload over a collision"); + std::fs::remove_file(&source).unwrap(); + assert_eq!(std::fs::read(&object).unwrap(), data); + } + + /// The staged file is deleted once its upload is acknowledged, so an + /// upload whose directory entries may not be durable must not be. + #[tokio::test] + async fn upload_is_not_acknowledged_when_a_directory_sync_fails() { + for cross_device in [false, true] { + let dir = tempfile::tempdir().unwrap(); + let store = dir.path().join("store"); + let source = dir.path().join("staged.parquet"); + let data = pattern(64 * 1024 + 5); + std::fs::write(&source, &data).unwrap(); + let key = "stream/date=2026-11-30/hour=10/part.parquet"; + let object = store.join(key); + let storage = LocalFS::new(store.clone()); + let link = move |src: &Path, dst: &Path| { + if cross_device { + Err(std::io::Error::from(std::io::ErrorKind::CrossesDevices)) + } else { + std::fs::hard_link(src, dst) + } + }; + // The object's own directory, one that leads to it, and the root. + for failing in [ + object.parent().unwrap().to_path_buf(), + store.join("stream"), + store.clone(), + ] { + let failure = fail_directory_syncs(&failing); + assert_injected_sync_failure( + storage + .upload_multipart_with_link(RelativePath::new(key), &source, &None, link) + .await, + ); + assert_eq!(std::fs::read(&source).unwrap(), data); + drop(failure); + // The retry makes durable what the failed attempt published. + storage + .upload_multipart_with_link(RelativePath::new(key), &source, &None, link) + .await + .unwrap(); + assert_eq!(std::fs::read(&object).unwrap(), data); + assert_eq!(files_under(&store), vec![object.clone()]); + } + } + } + + #[tokio::test] + async fn copied_new_object_is_not_acknowledged_when_a_directory_sync_fails() { + let dir = tempfile::tempdir().unwrap(); + let source = dir.path().join("source"); + std::fs::write(&source, b"payload").unwrap(); + let store = dir.path().join("store"); + + // The directory the object is published into. + let object = store.join("out/object"); + let failure = fail_directory_syncs(object.parent().unwrap()); + assert_injected_sync_failure( + copy_into_new_file(fs::File::open(&source).await.unwrap(), &object).await, + ); + assert_no_upload_temps(object.parent().unwrap()); + drop(failure); + + // A directory above it, which the upload syncs after the copy. + let failure = fail_directory_syncs(&store); + assert_injected_sync_failure(upload(&store, "other/dir/object", &source).await); + drop(failure); + upload(&store, "other/dir/object", &source).await.unwrap(); + assert_eq!( + std::fs::read(store.join("other/dir/object")).unwrap(), + b"payload" + ); + assert_no_upload_temps(&store.join("other/dir")); + } + + #[test] + fn copy_length_must_match_the_source() { + verify_copied_length(0, 0).unwrap(); + verify_copied_length(7, 7).unwrap(); + assert_eq!( + verify_copied_length(6, 7).unwrap_err().kind(), + std::io::ErrorKind::UnexpectedEof + ); + assert_eq!( + verify_copied_length(8, 7).unwrap_err().kind(), + std::io::ErrorKind::InvalidData + ); + } + + /// A staged Parquet file is complete before it is uploaded. A copy that + /// ends early, or finds the file longer than it was, is not published. + #[tokio::test] + async fn copy_of_another_length_than_the_source_is_not_published() { + for (grown, kind) in [ + (false, std::io::ErrorKind::UnexpectedEof), + (true, std::io::ErrorKind::InvalidData), + ] { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().join("store"); + let source = dir.path().join("staged.parquet"); + std::fs::write(&source, pattern(600 * 1024 + 17)).unwrap(); + let object = root.join("stream/part.parquet"); + let result = atomic_replace_parquet_from_file_with( + &root, + fs::File::open(&source).await.unwrap(), + &object, + move |src, dst| { + use std::io::{Read, Write}; + + if grown { + let appended = b"appended while it was read"; + let copied = copy_file_buffered(src, dst)?; + dst.write_all(appended)?; + Ok(copied + appended.len() as u64) + } else { + let mut some = [0u8; 100]; + src.read_exact(&mut some)?; + dst.write_all(&some)?; + Ok(some.len() as u64) + } + }, + ) + .await; + match result { + Err(ObjectStorageError::IoError(err)) => assert_eq!(err.kind(), kind), + other => panic!("unexpected result: {other:?}"), + } + assert!(!object.exists()); + assert!(files_under(&root).is_empty()); + } + } + + #[tokio::test] + async fn parquet_source_that_cannot_be_read_fails_before_anything_is_created() { + let dir = tempfile::tempdir().unwrap(); + let source = dir.path().join("source-dir.parquet"); + std::fs::create_dir(&source).unwrap(); + let store = dir.path().join("store"); + + let err = upload(&store, "out/object.parquet", &source) + .await + .unwrap_err(); + + assert!(matches!(err, ObjectStorageError::IoError(_)), "{err:?}"); + assert!(!store.exists()); + } + + #[cfg(target_os = "linux")] + #[tokio::test] + async fn parquet_source_read_error_precedes_a_destination_that_cannot_be_set_up() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join("blocked"), b"not a directory").unwrap(); + // Linux exposes this as a regular file, but offset zero is unreadable. + let source = Path::new("/proc/self/mem"); + let baseline = std::fs::read(source).unwrap_err(); + for key in ["new/parent/part.parquet", "blocked/part.parquet"] { + match upload(dir.path(), key, source).await.unwrap_err() { + ObjectStorageError::IoError(err) => { + assert_eq!(err.raw_os_error(), baseline.raw_os_error()) + } + other => panic!("unexpected error: {other:?}"), + } + } + assert!(!dir.path().join("new/parent/part.parquet").exists()); + assert_eq!( + std::fs::read(dir.path().join("blocked")).unwrap(), + b"not a directory" + ); + assert_no_upload_temps(dir.path()); + } + + #[tokio::test] + async fn parquet_copy_reports_a_destination_that_cannot_be_set_up() { + let dir = tempfile::tempdir().unwrap(); + let blocked = dir.path().join("blocked"); + std::fs::write(&blocked, b"not a directory").unwrap(); + let source = dir.path().join("staged.parquet"); + let data = pattern(600 * 1024 + 17); + std::fs::write(&source, &data).unwrap(); + // What creating the object's directory fails with. + let expected = std::fs::create_dir_all(&blocked).unwrap_err(); + + match upload(dir.path(), "blocked/part.parquet", &source) + .await + .unwrap_err() + { + ObjectStorageError::IoError(err) => assert_eq!(err.kind(), expected.kind()), + other => panic!("unexpected error: {other:?}"), + } + + assert_eq!(std::fs::read(&blocked).unwrap(), b"not a directory"); + assert_eq!(std::fs::read(&source).unwrap(), data); + assert_no_upload_temps(dir.path()); + } + + #[test] + fn streaming_copies_are_exact_from_the_current_position() { + use std::io::{Seek, SeekFrom}; + + let dir = tempfile::tempdir().unwrap(); + let source = dir.path().join("source"); + // Several buffers and a remainder, read from an offset. + let data = pattern(3 * UPLOAD_COPY_BUFFER_SIZE + 5); + std::fs::write(&source, &data).unwrap(); + type FileCopy = fn(&mut std::fs::File, &mut std::fs::File) -> std::io::Result; + let copies: [(&str, FileCopy); 2] = [ + ("chunked", copy_file_chunked), + ("buffered", copy_file_buffered), + ]; + for (name, copy) in copies { + let mut input = std::fs::File::open(&source).unwrap(); + input.seek(SeekFrom::Start(37)).unwrap(); + let dest = dir.path().join(name); + let mut output = std::fs::File::create(&dest).unwrap(); + assert_eq!( + copy(&mut input, &mut output).unwrap(), + (data.len() - 37) as u64, + "{name}" + ); + drop(output); + assert_eq!(std::fs::read(&dest).unwrap(), data[37..], "{name}"); + } + + // A buffer is filled completely, and comes up short only at the end + // of the file. + let mut input = std::fs::File::open(&source).unwrap(); + let mut head = vec![0u8; UPLOAD_COPY_BUFFER_SIZE]; + assert_eq!(read_until_full(&mut input, &mut head).unwrap(), head.len()); + assert_eq!(head, data[..UPLOAD_COPY_BUFFER_SIZE]); + let mut rest = vec![0u8; data.len()]; + let rest_len = read_until_full(&mut input, &mut rest).unwrap(); + assert_eq!(rest[..rest_len], data[UPLOAD_COPY_BUFFER_SIZE..]); + assert_eq!(read_until_full(&mut input, &mut rest).unwrap(), 0); + } + + #[test] + fn cross_device_fallback_is_announced_once() { + // Whichever upload is the first, in this test or another, no later + // one is the first again. + let _ = first_cross_device_upload(); + assert!(!first_cross_device_upload()); + assert!(!first_cross_device_upload()); + } + + /// The private file of a write in flight, or one that a crash left + /// behind, is not an object of the store. + #[tokio::test] + async fn private_files_are_not_in_the_metadata_inventory() { + let dir = tempfile::tempdir().unwrap(); + let storage = LocalFS::new(dir.path().to_path_buf()); + storage + .put_object( + RelativePath::new("logs/.stream/.stream.json"), + Bytes::from_static(b"{}"), + &None, + ) + .await + .unwrap(); + std::fs::write( + dir.path() + .join("logs/.stream") + .join(format!("{UPLOAD_TEMP_PREFIX}crashed.tmp")), + b"half a write", + ) + .unwrap(); + + let keys: Vec = storage + .metadata_inventory() + .await + .unwrap() + .into_iter() + .map(|(key, _)| key) + .collect(); + assert_eq!(keys, ["logs/.stream/.stream.json"]); + } } diff --git a/src/storage/object_storage.rs b/src/storage/object_storage.rs index 67d8400df..4582a2ee8 100644 --- a/src/storage/object_storage.rs +++ b/src/storage/object_storage.rs @@ -65,7 +65,7 @@ use std::path::PathBuf; use std::sync::Arc; use std::time::Duration; use std::time::Instant; -use tokio::sync::Semaphore; +use tokio::sync::{OwnedSemaphorePermit, Semaphore}; use tokio::task::JoinSet; use tracing::{Instrument, error, info, info_span, warn}; use ulid::Ulid; @@ -87,8 +87,9 @@ static UPLOADED_STAGED_FILES_PENDING_CLEANUP: Lazy> = Lazy::new /// pass. The shutdown pass does not take it. /// 2. A stream-sync slot, for the upload phase of one stream's pass: its /// uploads and the snapshot update that publishes them. -/// 3. For one file: a slot of its stream, then a process-wide upload slot. -/// Both are released when that upload ends, before the snapshot update. +/// 3. For one file: a slot of its stream, then a process-wide upload slot, +/// then the memory its upload buffers, see [`UploadMemoryBudget`]. All +/// three are released when that upload ends, before the snapshot update. /// /// Field stats and the schema commit run after the stream-sync slot has been /// released, so `FIELD_STATS_CONCURRENCY_SEMAPHORE` is only ever awaited by a @@ -106,6 +107,8 @@ struct SyncLimits { uploads: Arc, /// The number of permits `uploads` was created with. max_uploads: usize, + /// `P_MAX_UPLOAD_MEMORY_BYTES` + upload_memory: UploadMemoryBudget, } static SYNC_LIMITS: Lazy = Lazy::new(|| { @@ -117,6 +120,14 @@ static SYNC_LIMITS: Lazy = Lazy::new(|| { impl SyncLimits { fn new(max_stream_syncs: usize, max_uploads: usize) -> Self { + Self::with_upload_memory(max_stream_syncs, max_uploads, *MAX_UPLOAD_MEMORY_BYTES) + } + + fn with_upload_memory( + max_stream_syncs: usize, + max_uploads: usize, + max_upload_memory_bytes: u64, + ) -> Self { // The command line rejects 0 and values a semaphore cannot hold. They // still reach here from `Options::default()`, which tests and // embedders build without parsing arguments; there 0 means "not set". @@ -132,6 +143,7 @@ impl SyncLimits { ))), uploads: Arc::new(Semaphore::new(max_uploads)), max_uploads, + upload_memory: UploadMemoryBudget::new(max_upload_memory_bytes), } } @@ -160,26 +172,44 @@ impl SyncLimits { UploadSlots { stream: Arc::new(Semaphore::new(self.max_uploads)), process: self.uploads.clone(), + payload: None, } } + + /// The upload slots for one stream's sync pass to a store that buffers + /// the files it uploads as `buffering` describes. Each upload then also + /// waits for that much of the upload memory budget. A store that buffers + /// nothing gets the plain slots. + fn upload_slots_for(&self, buffering: UploadBuffering) -> UploadSlots { + let mut slots = self.upload_slots(); + if buffering != UploadBuffering::Unbuffered { + slots.payload = Some(UploadPayload { + budget: self.upload_memory.clone(), + buffering, + }); + } + slots + } } -/// The two budgets a file upload runs under, see [`SyncLimits`]. +/// The budgets a file upload runs under, see [`SyncLimits`]. #[derive(Clone)] struct UploadSlots { stream: Arc, process: Arc, + /// Absent for a store whose uploads buffer nothing. + payload: Option, } impl UploadSlots { - /// Runs the upload of a claimed file once both budgets have room for it. + /// Runs the upload of a claimed file once every budget has room for it. async fn upload(self, claim: QueuedUpload, upload: impl FnOnce(PathBuf) -> Fut) -> T where Fut: std::future::Future, { // The stream's slot comes first: a file waiting for its own stream // must not occupy a place in the process-wide queue. Declared in - // this order, the process-wide slot is also the first to be released. + // this order, the process-wide slot is released before it. let _stream_slot = self .stream .acquire_owned() @@ -190,10 +220,154 @@ impl UploadSlots { .acquire_owned() .await .expect("upload semaphore is never closed"); + // The memory comes last, so that a file waiting for a slot holds + // none of it, and before the claim starts: a queued claim does not + // expire, however long the uploads ahead of this one take. + let _payload = match &self.payload { + Some(payload) => payload.reserve(claim.path()).await, + None => None, + }; upload(claim.start()).await } } +/// How much of a staged file [`ObjectStorage::upload_multipart`] holds in +/// memory while it uploads the file. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum UploadBuffering { + /// Nothing that grows with the file: it is linked, or streamed in small + /// chunks, as the local filesystem store does. + Unbuffered, + /// A file below `part_size`, and every file when `multipart` is off, is + /// read whole for a single PUT. Any other file is sent one `part_size` + /// part at a time. + Parts { part_size: u64, multipart: bool }, +} + +impl UploadBuffering { + /// The most bytes of a `file_size`-byte file that are in memory at once. + fn payload_bytes(self, file_size: u64) -> u64 { + match self { + Self::Unbuffered => 0, + Self::Parts { + part_size, + multipart: true, + } => file_size.min(part_size), + Self::Parts { + multipart: false, .. + } => file_size, + } + } +} + +/// One permit of the upload memory budget. A permit stands for a kibibyte, +/// not a byte, so that budgets and files larger than `u32::MAX` bytes fit the +/// 32-bit count a semaphore hands out in one request. +const UPLOAD_MEMORY_PERMIT_BYTES: u64 = 1024; + +/// `P_MAX_UPLOAD_MEMORY_BYTES` when it is not set. +const DEFAULT_MAX_UPLOAD_MEMORY_BYTES: u64 = 256 * 1024 * 1024; + +const MAX_UPLOAD_MEMORY_ENV: &str = "P_MAX_UPLOAD_MEMORY_BYTES"; + +/// Read here, not from the command line options, like `P_VERIFY_UPLOAD_HEAD`. +static MAX_UPLOAD_MEMORY_BYTES: std::sync::LazyLock = std::sync::LazyLock::new(|| { + parse_max_upload_memory_bytes(std::env::var(MAX_UPLOAD_MEMORY_ENV).ok().as_deref()) +}); + +/// The upload memory budget in bytes. Without a value it is the default. A +/// value that is not a positive number of bytes is reported and ignored: the +/// server is already running when this is first read, and uploading without +/// a bound would be the worst reading of a typo. +fn parse_max_upload_memory_bytes(value: Option<&str>) -> u64 { + let Some(value) = value.map(str::trim).filter(|value| !value.is_empty()) else { + return DEFAULT_MAX_UPLOAD_MEMORY_BYTES; + }; + match value.parse::() { + Ok(bytes) if bytes > 0 => bytes, + _ => { + warn!( + "Ignoring {MAX_UPLOAD_MEMORY_ENV}={value:?}: expected a positive number of bytes. Using the default of {DEFAULT_MAX_UPLOAD_MEMORY_BYTES}" + ); + DEFAULT_MAX_UPLOAD_MEMORY_BYTES + } + } +} + +/// Process-wide cap on the bytes of staged files that uploads hold in memory +/// at the same time, `P_MAX_UPLOAD_MEMORY_BYTES`. +/// +/// An object-store upload reads a small file whole and a large one a +/// multipart part at a time. The upload slots alone therefore allow +/// `P_MAX_CONCURRENT_OBJECT_STORE_UPLOADS` buffers of `P_MULTIPART_MIN_SIZE` +/// bytes at once, 2.5 GiB at the defaults. Each upload reserves what it will +/// buffer here first, and waits while the budget is spent. +/// +/// Reservations are granted in the order they were asked for, so a large one +/// is not overtaken for ever by small ones. One that asks for more than the +/// whole budget, such as a large file when multipart is off, is granted all +/// of it: that upload then runs with no other buffer beside it, which is the +/// most this can do for a file that has to be in memory whole. +#[derive(Clone)] +struct UploadMemoryBudget { + permits: Arc, + /// The number of permits `permits` was created with. + capacity: u32, +} + +impl UploadMemoryBudget { + fn new(max_bytes: u64) -> Self { + // At least one permit, so that every reservation can be granted, and + // no more than a semaphore holds or hands out in one request. + let capacity = max_bytes + .div_ceil(UPLOAD_MEMORY_PERMIT_BYTES) + .clamp(1, u64::from(u32::MAX)) + .min(Semaphore::MAX_PERMITS as u64) as u32; + Self { + permits: Arc::new(Semaphore::new(capacity as usize)), + capacity, + } + } + + /// Waits until `bytes` of the budget are free and takes them until the + /// returned permit is dropped. Nothing is taken for no bytes. + async fn reserve(&self, bytes: u64) -> Option { + if bytes == 0 { + return None; + } + let permits = bytes + .div_ceil(UPLOAD_MEMORY_PERMIT_BYTES) + .min(u64::from(self.capacity)) as u32; + Some( + self.permits + .clone() + .acquire_many_owned(permits) + .await + .expect("upload memory semaphore is never closed"), + ) + } +} + +/// What the uploads of one sync pass reserve from the upload memory budget. +#[derive(Clone)] +struct UploadPayload { + budget: UploadMemoryBudget, + buffering: UploadBuffering, +} + +impl UploadPayload { + /// Reserves what uploading `staged` will buffer. A file that cannot be + /// measured reserves nothing: its upload fails on that same error. + async fn reserve(&self, staged: &Path) -> Option { + // The staging directory is local, and one `stat` costs less than a + // round trip to the blocking pool. + let file_size = staged.metadata().ok()?.len(); + self.budget + .reserve(self.buffering.payload_bytes(file_size)) + .await + } +} + /// How long after its upload began a claim is taken to have been leaked. const STALE_UPLOAD_CLAIM_AGE: Duration = Duration::from_secs(300); @@ -350,13 +524,25 @@ struct UploadedParquetFile { } static VERIFY_UPLOAD_HEAD: std::sync::LazyLock = std::sync::LazyLock::new(|| { - parse_verify_upload_head(std::env::var("P_VERIFY_UPLOAD_HEAD").ok().as_deref()) + let verify = parse_verify_upload_head(std::env::var("P_VERIFY_UPLOAD_HEAD").ok().as_deref()); + if !verify { + warn!( + "P_VERIFY_UPLOAD_HEAD is off: uploaded Parquet files are published without checking the size the object store reports for them" + ); + } + verify }); +/// Whether an uploaded Parquet file's remote size is checked before the file +/// is published. As upstream does unconditionally, it is, unless +/// `P_VERIFY_UPLOAD_HEAD` explicitly says otherwise: anything but a +/// recognised "off" keeps the check. fn parse_verify_upload_head(value: Option<&str>) -> bool { - value.is_some_and(|v| { + !value.is_some_and(|v| { let trimmed = v.trim(); - trimmed.eq_ignore_ascii_case("true") || trimmed == "1" + ["false", "0", "no", "off"] + .iter() + .any(|off| trimmed.eq_ignore_ascii_case(off)) }) } @@ -383,7 +569,7 @@ async fn upload_single_parquet_file( .to_str() .expect("filename is valid string"); - // Get the local file size once asynchronously for metrics, manifest, and optional HEAD check + // Get the local file size once asynchronously for metrics, manifest, and the HEAD check let local_file_size = tokio::fs::metadata(&path) .await .map_err(|e| { @@ -410,8 +596,11 @@ async fn upload_single_parquet_file( ) })?; - // Post-PUT HEAD validation is opt-in via P_VERIFY_UPLOAD_HEAD (default false), - // as S3/object-store PUT and multipart completion are strongly consistent and durable. + // Before the object is published in the manifest and its staged source is + // deleted, check that the store reports it with the size of the staged + // file, as upstream does. A truncated or failed upload is then retried + // from staging instead of being recorded. On by default; an operator can + // opt out with P_VERIFY_UPLOAD_HEAD=false. if should_verify_upload_head() { let upload_is_valid = validate_uploaded_parquet_file( &store, @@ -814,6 +1003,15 @@ pub trait ObjectStorage: Debug + Send + Sync + 'static { path: &Path, tenant_id: &Option, ) -> Result<(), ObjectStorageError>; + /// How [`ObjectStorage::upload_multipart`] buffers the file it uploads, + /// for the upload memory budget. The default is what the object stores + /// do: one multipart part at a time, or the whole file for a single PUT. + fn upload_buffering(&self) -> UploadBuffering { + UploadBuffering::Parts { + part_size: PARSEABLE.options.min_multipart_size, + multipart: PARSEABLE.options.enable_multipart, + } + } async fn put_object( &self, path: &RelativePath, @@ -1831,7 +2029,7 @@ async fn process_parquet_files( ) -> Result, ObjectStorageError> { retry_pending_staged_file_cleanup(); - let upload_slots = limits.upload_slots(); + let upload_slots = limits.upload_slots_for(object_store.upload_buffering()); let mut join_set = JoinSet::new(); // collect all parquet files to upload @@ -3290,6 +3488,341 @@ mod sync_limit_tests { assert!(!staged.exists()); assert!(!UPLOADED_STAGED_FILES_PENDING_CLEANUP.contains(&staged)); } + + const KIB: u64 = UPLOAD_MEMORY_PERMIT_BYTES; + const MIB: u64 = 1024 * 1024; + + fn free_upload_memory(budget: &UploadMemoryBudget) -> u64 { + budget.permits.available_permits() as u64 * KIB + } + + #[test] + fn upload_memory_defaults_to_256_mib_and_ignores_unusable_values() { + assert_eq!(DEFAULT_MAX_UPLOAD_MEMORY_BYTES, 256 * MIB); + for unset in [None, Some(""), Some(" ")] { + assert_eq!( + parse_max_upload_memory_bytes(unset), + DEFAULT_MAX_UPLOAD_MEMORY_BYTES + ); + } + for unusable in ["0", "-1", "256MiB", "1.5", "lots"] { + assert_eq!( + parse_max_upload_memory_bytes(Some(unusable)), + DEFAULT_MAX_UPLOAD_MEMORY_BYTES, + "{unusable:?}" + ); + } + assert_eq!(parse_max_upload_memory_bytes(Some("1048576")), MIB); + assert_eq!( + parse_max_upload_memory_bytes(Some(" 8589934592 ")), + 8 * 1024 * MIB + ); + // What the process gets when the variable is not set. + assert_eq!( + free_upload_memory(&UploadMemoryBudget::new(DEFAULT_MAX_UPLOAD_MEMORY_BYTES)), + 256 * MIB + ); + } + + #[test] + fn upload_memory_budget_always_has_a_permit_and_fits_a_semaphore() { + assert_eq!(UploadMemoryBudget::new(0).capacity, 1); + assert_eq!(UploadMemoryBudget::new(1).capacity, 1); + assert_eq!(UploadMemoryBudget::new(KIB + 1).capacity, 2); + // More than `u32::MAX` bytes, which a permit per byte could not hold. + assert_eq!( + UploadMemoryBudget::new(8 * 1024 * MIB).capacity, + 8 * 1024 * 1024 + ); + let largest = UploadMemoryBudget::new(u64::MAX); + assert!(largest.capacity as usize <= Semaphore::MAX_PERMITS); + assert_eq!( + largest.permits.available_permits(), + largest.capacity as usize + ); + } + + #[test] + fn an_upload_buffers_one_part_or_the_whole_file() { + let parts = UploadBuffering::Parts { + part_size: 25 * MIB, + multipart: true, + }; + assert_eq!(parts.payload_bytes(0), 0); + // Below the multipart threshold the whole file is one PUT. + assert_eq!(parts.payload_bytes(MIB), MIB); + assert_eq!(parts.payload_bytes(25 * MIB), 25 * MIB); + // From there on it is one part at a time, whatever the file's size. + assert_eq!(parts.payload_bytes(10 * 1024 * MIB), 25 * MIB); + // With multipart off every file is one PUT. + let single_put = UploadBuffering::Parts { + part_size: 25 * MIB, + multipart: false, + }; + assert_eq!(single_put.payload_bytes(10 * 1024 * MIB), 10 * 1024 * MIB); + assert_eq!(UploadBuffering::Unbuffered.payload_bytes(u64::MAX), 0); + + // The local filesystem store links or streams, and buffers nothing, + // so its uploads are not given a payload to reserve. + let dir = tempfile::tempdir().unwrap(); + let local = LocalFS::new(dir.path().to_path_buf()); + assert_eq!(local.upload_buffering(), UploadBuffering::Unbuffered); + let limits = SyncLimits::with_upload_memory(1, 1, MIB); + assert!( + limits + .upload_slots_for(local.upload_buffering()) + .payload + .is_none() + ); + assert!(limits.upload_slots_for(parts).payload.is_some()); + } + + /// Without the budget a hundred uploads, each holding a 25 MiB part, + /// would buffer 2.5 GiB at once. + #[tokio::test] + async fn concurrent_reservations_never_exceed_the_upload_memory_budget() { + const UPLOADS: usize = 100; + const PART: u64 = 25 * MIB; + const BUDGET: u64 = 64 * MIB; + + let budget = UploadMemoryBudget::new(BUDGET); + let reserved = Arc::new(std::sync::atomic::AtomicU64::new(0)); + let peak = Arc::new(std::sync::atomic::AtomicU64::new(0)); + let mut uploads = JoinSet::new(); + for _ in 0..UPLOADS { + let budget = budget.clone(); + let reserved = reserved.clone(); + let peak = peak.clone(); + uploads.spawn(async move { + let _payload = budget.reserve(PART).await; + let now = reserved.fetch_add(PART, Ordering::SeqCst) + PART; + peak.fetch_max(now, Ordering::SeqCst); + tokio::time::sleep(Duration::from_millis(1)).await; + reserved.fetch_sub(PART, Ordering::SeqCst); + }); + } + tokio::time::timeout(Duration::from_secs(60), async { + while let Some(upload) = uploads.join_next().await { + upload.unwrap(); + } + }) + .await + .expect("every reservation is granted in its turn"); + + // Two parts fit the budget and a third does not. + assert_eq!(peak.load(Ordering::SeqCst), 2 * PART); + assert_eq!(free_upload_memory(&budget), BUDGET); + } + + #[tokio::test] + async fn upload_memory_is_returned_on_drop_error_cancellation_and_panic() { + let budget = UploadMemoryBudget::new(4 * KIB); + + let held = budget.reserve(3 * KIB).await; + assert_eq!(free_upload_memory(&budget), KIB); + drop(held); + assert_eq!(free_upload_memory(&budget), 4 * KIB); + + // An upload that fails returns what it reserved. + let failed: Result<(), ObjectStorageError> = async { + let _payload = budget.reserve(4 * KIB).await; + Err(ObjectStorageError::Custom("upload failed".into())) + } + .await; + assert!(failed.is_err()); + assert_eq!(free_upload_memory(&budget), 4 * KIB); + + // So does one that is cancelled, whether it was still waiting ... + let held = budget.reserve(4 * KIB).await; + let waiting = tokio::spawn({ + let budget = budget.clone(); + async move { + let _payload = budget.reserve(2 * KIB).await; + std::future::pending::<()>().await + } + }); + settle().await; + assert!(!waiting.is_finished()); + waiting.abort(); + assert!(waiting.await.unwrap_err().is_cancelled()); + drop(held); + assert_eq!(free_upload_memory(&budget), 4 * KIB); + + // ... or already uploading. + let uploading = tokio::spawn({ + let budget = budget.clone(); + async move { + let _payload = budget.reserve(2 * KIB).await; + std::future::pending::<()>().await + } + }); + settle().await; + assert_eq!(free_upload_memory(&budget), 2 * KIB); + uploading.abort(); + assert!(uploading.await.unwrap_err().is_cancelled()); + assert_eq!(free_upload_memory(&budget), 4 * KIB); + + // And one that panics. + let panicked = tokio::spawn({ + let budget = budget.clone(); + async move { + let _payload = budget.reserve(KIB).await; + fail_upload(); + } + }) + .await + .unwrap_err(); + assert!(panicked.is_panic()); + assert_eq!(free_upload_memory(&budget), 4 * KIB); + } + + #[tokio::test] + async fn reservation_beyond_the_budget_takes_all_of_it_and_an_empty_one_takes_nothing() { + let budget = UploadMemoryBudget::new(8 * KIB); + + // With multipart off a file can be larger than the whole budget. It + // must not be left waiting for memory that can never be free. + let whole = tokio::time::timeout(Duration::from_secs(30), budget.reserve(1024 * MIB)) + .await + .expect("a reservation is capped at the budget"); + assert_eq!(free_upload_memory(&budget), 0); + // It then runs alone: not one more byte is buffered beside it. + assert!( + tokio::time::timeout(Duration::from_millis(50), budget.reserve(1)) + .await + .is_err() + ); + drop(whole); + assert_eq!(free_upload_memory(&budget), 8 * KIB); + + // An empty file buffers nothing. Any other takes whole permits. + assert!(budget.reserve(0).await.is_none()); + let byte = budget.reserve(1).await; + assert_eq!(free_upload_memory(&budget), 7 * KIB); + drop(byte); + let more = budget.reserve(KIB + 1).await; + assert_eq!(free_upload_memory(&budget), 6 * KIB); + drop(more); + assert_eq!(free_upload_memory(&budget), 8 * KIB); + } + + /// Waiting for upload memory takes as long as the uploads ahead do. The + /// file waits with its claim still queued, which does not expire, so no + /// other pass can pick the file up and upload it a second time. + #[tokio::test] + async fn file_waits_for_upload_memory_with_its_claim_still_queued() { + let dir = tempfile::tempdir().unwrap(); + // Room for one 3 KiB part at a time. + let limits = SyncLimits::with_upload_memory(4, 4, 4 * KIB); + let slots = limits.upload_slots_for(UploadBuffering::Parts { + part_size: 3 * KIB, + multipart: true, + }); + // An upload ends when the test lets it. + let finish = Arc::new(Semaphore::new(0)); + let mut uploads = JoinSet::new(); + let mut staged = Vec::new(); + for name in ["first.parquet", "second.parquet"] { + let path = dir.path().join(name); + std::fs::write(&path, vec![0u8; 8 * 1024]).unwrap(); + let claim = claim_staged_file_for_upload(path.clone()).expect("a new file"); + let finish = finish.clone(); + uploads.spawn(slots.clone().upload(claim, move |path| async move { + finish.acquire().await.unwrap().forget(); + release(&path); + })); + staged.push(path); + } + let started = |staged: &[PathBuf]| { + staged + .iter() + .filter(|path| matches!(claim_on(path), Some(UploadClaim::Started(_)))) + .count() + }; + let queued = |staged: &[PathBuf]| { + staged + .iter() + .filter(|path| claim_on(path) == Some(UploadClaim::Queued)) + .count() + }; + settle().await; + + // Both files have their upload slots. Only one has the memory, and + // only that one has begun: what is left of the budget, which the + // semaphore may already have set aside for the file that waits, is + // not enough for a second part. + assert_eq!(limits.uploads.available_permits(), 2); + assert!(free_upload_memory(&limits.upload_memory) < 3 * KIB); + assert_eq!((started(&staged), queued(&staged)), (1, 1)); + let waiting = staged + .iter() + .find(|path| claim_on(path) == Some(UploadClaim::Queued)) + .expect("one file is waiting") + .clone(); + assert!(!is_stale_upload_claim( + &UploadClaim::Queued, + Instant::now() + 10 * STALE_UPLOAD_CLAIM_AGE + )); + assert!(claim_staged_file_for_upload(waiting).is_none()); + + // The first upload ends and its memory goes to the file that waited. + finish.add_permits(1); + settle().await; + assert_eq!((started(&staged), queued(&staged)), (1, 0)); + assert_eq!(free_upload_memory(&limits.upload_memory), KIB); + + finish.add_permits(1); + while let Some(upload) = uploads.join_next().await { + upload.unwrap(); + } + assert_eq!(free_upload_memory(&limits.upload_memory), 4 * KIB); + assert_eq!(limits.uploads.available_permits(), 4); + } + + /// The local filesystem store links a staged file instead of buffering + /// it, so its uploads go ahead with the upload memory budget spent. + #[tokio::test] + async fn local_store_uploads_do_not_wait_for_upload_memory() { + crate::parseable::install_default_test_parseable(); + let dir = tempfile::tempdir().unwrap(); + let remote = dir.path().join("remote"); + std::fs::create_dir_all(&remote).unwrap(); + let object_store: Arc = Arc::new(LocalFS::new(remote.clone())); + let stream = staged_stream(&dir.path().join("staging"), &new_stream_name()); + let staged: Vec = (0..3) + .map(|minute| stage_parquet(&stream, minute)) + .collect(); + let stream_name = stream.stream_name.clone(); + let upload_context = UploadContext::new(stream.clone()); + + let limits = SyncLimits::with_upload_memory(1, 2, KIB); + // The buffering uploads of other streams hold the whole budget. + let spent = limits.upload_memory.reserve(u64::MAX).await; + assert_eq!(free_upload_memory(&limits.upload_memory), 0); + + let uploaded = tokio::time::timeout( + Duration::from_secs(60), + process_parquet_files( + &upload_context, + &stream_name, + None, + object_store.clone(), + &limits, + ), + ) + .await + .expect("a linked upload needs no upload memory") + .unwrap(); + // Every file passed the size check that is on by default, too. + assert_eq!(uploaded.len(), staged.len()); + assert_eq!(parquet_files_under(&remote), staged.len()); + + drop(spent); + assert_eq!(free_upload_memory(&limits.upload_memory), KIB); + for path in &staged { + release(path); + } + } } #[cfg(test)] @@ -3846,15 +4379,51 @@ mod metadata_key_decode_tests { } #[test] - fn verify_upload_head_defaults_false_and_parses_truthy_values() { - assert!(!parse_verify_upload_head(None)); - assert!(!parse_verify_upload_head(Some(""))); - assert!(!parse_verify_upload_head(Some("false"))); - assert!(!parse_verify_upload_head(Some("0"))); - assert!(!parse_verify_upload_head(Some("yes"))); - assert!(parse_verify_upload_head(Some("true"))); - assert!(parse_verify_upload_head(Some("TRUE"))); - assert!(parse_verify_upload_head(Some(" 1 "))); + fn verify_upload_head_defaults_true_and_only_an_explicit_off_disables_it() { + // Unset is the upstream behaviour: every upload is checked. + assert!(parse_verify_upload_head(None)); + for on in [ + "", + " ", + "true", + "TRUE", + " 1 ", + "yes", + "on", + "anything else", + ] { + assert!(parse_verify_upload_head(Some(on)), "{on:?} keeps the check"); + } + for off in ["false", "FALSE", " False ", "0", " 0 ", "no", "Off"] { + assert!(!parse_verify_upload_head(Some(off)), "{off:?} opts out"); + } + } + + /// The check that is on by default again: an uploaded object is accepted + /// only if the store reports exactly the staged file's size. + #[tokio::test] + async fn upload_validation_accepts_only_the_staged_size() { + let dir = tempfile::tempdir().unwrap(); + let store: Arc = + Arc::new(crate::storage::LocalFS::new(dir.path().to_owned())); + let key = "logs/date=2026-01-01/hour=00/minute=00/file.parquet"; + store + .put_object(RelativePath::new(key), Bytes::from_static(b"12345"), &None) + .await + .unwrap(); + let validate = |key: &'static str, expected_size: u64| { + let store = store.clone(); + async move { + validate_uploaded_parquet_file(&store, key, expected_size, "logs", &None) + .await + .unwrap() + } + }; + assert!(validate(key, 5).await); + // A short upload, one that grew, and one that is not there at all. + assert!(!validate(key, 6).await); + assert!(!validate(key, 4).await); + assert!(!validate("logs/date=2026-01-01/hour=00/minute=00/missing.parquet", 5).await); } #[test] diff --git a/src/storage/s3.rs b/src/storage/s3.rs index 8972f0834..bd056935a 100644 --- a/src/storage/s3.rs +++ b/src/storage/s3.rs @@ -738,20 +738,10 @@ impl S3 { min_multipart_size, PARSEABLE.options.enable_multipart, ) { - // Read directly from the already-opened std::fs::File in one blocking call - // rather than chunked tokio::fs::File::read_to_end (which copies every chunk - // through an internal buffer across multiple blocking-pool round trips). - // The reported length is only a capacity hint: the body is still whatever - // read_to_end returns, as before. - let mut std_file = file.into_std().await; - let data = tokio::task::spawn_blocking(move || -> std::io::Result> { - use std::io::Read; - let mut data = Vec::with_capacity(total_size.saturating_add(1)); - std_file.read_to_end(&mut data)?; - Ok(data) - }) - .await - .map_err(|err| ObjectStorageError::UnhandledError(Box::new(err)))??; + // The body is exactly the file that was measured above. One that + // ended early or grew while it was read fails here and is never + // put, as a multipart upload of it would be aborted. + let data = read_file_for_single_put(file, total_size).await?; // Track single PUT operation for small files (PutPayload::from(Vec) is zero-copy). let result = self.client.put(location, PutPayload::from(data)).await; @@ -1458,11 +1448,62 @@ impl ObjectStorage for S3 { } } +/// Reads the whole of `file` for a single PUT, failing unless that is exactly +/// `total_size` bytes, the length the upload was planned for. +/// +/// Shared by the object-store backends, like the part upload below: a single +/// PUT must not store a file that ended early or grew while it was read any +/// more than a multipart upload does. +pub(super) async fn read_file_for_single_put( + file: tokio::fs::File, + total_size: usize, +) -> Result, ObjectStorageError> { + // One blocking read of the std file, rather than a chunked read through + // tokio's internal buffer over several round trips to the blocking pool. + let mut file = file.into_std().await; + tokio::task::spawn_blocking(move || read_exactly(&mut file, total_size)) + .await + .map_err(|err| ObjectStorageError::UnhandledError(Box::new(err)))? + .map_err(ObjectStorageError::from) +} + +/// Reads `reader` to its end, which has to come after exactly `total_size` +/// bytes. The read stops one byte past that, enough to tell that the source +/// grew without buffering whatever was appended to it. +fn read_exactly(reader: &mut R, total_size: usize) -> std::io::Result> { + use std::io::Read; + + // One spare byte, so that finding the end does not grow the buffer. + let mut data = Vec::with_capacity(total_size.saturating_add(1)); + reader + .by_ref() + .take((total_size as u64).saturating_add(1)) + .read_to_end(&mut data)?; + match data.len().cmp(&total_size) { + std::cmp::Ordering::Equal => Ok(data), + std::cmp::Ordering::Less => Err(std::io::Error::new( + std::io::ErrorKind::UnexpectedEof, + format!( + "file ended after {} of {total_size} bytes during single PUT upload", + data.len() + ), + )), + std::cmp::Ordering::Greater => Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + format!("file grew beyond {total_size} bytes during single PUT upload"), + )), + } +} + // BEGIN multipart-part-upload helper (extracted verbatim by the standalone upload harness) /// Files smaller than the multipart threshold, or every file when multipart is /// disabled, are sent with a single PUT. -fn use_single_put(total_size: usize, min_multipart_size: usize, enable_multipart: bool) -> bool { +pub(crate) fn use_single_put( + total_size: usize, + min_multipart_size: usize, + enable_multipart: bool, +) -> bool { total_size < min_multipart_size || !enable_multipart } @@ -1497,7 +1538,7 @@ impl Drop for AbortOnDrop { /// bytes, or a read/part/complete failure aborts the upload. Read/part failures /// retain their original error. As before, an abort failure after a completion /// failure is returned instead of the completion error. -async fn upload_file_parts( +pub(crate) async fn upload_file_parts( reader: &mut R, upload: Box, total_size: usize, @@ -2033,3 +2074,70 @@ mod multipart_upload_tests { } // END multipart-part-upload tests } + +#[cfg(test)] +mod single_put_read_tests { + use std::io::ErrorKind; + + use super::{ObjectStorageError, read_exactly, read_file_for_single_put}; + + fn pattern(len: usize) -> Vec { + (0..len).map(|i| (i % 251) as u8).collect() + } + + #[test] + fn source_of_the_expected_length_is_read_whole() { + let data = pattern(1000); + assert_eq!( + read_exactly(&mut data.as_slice(), data.len()).unwrap(), + data + ); + assert!(read_exactly(&mut std::io::empty(), 0).unwrap().is_empty()); + } + + #[test] + fn source_that_ends_early_fails_with_unexpected_eof() { + let err = read_exactly(&mut pattern(9).as_slice(), 10).unwrap_err(); + assert_eq!(err.kind(), ErrorKind::UnexpectedEof); + let err = read_exactly(&mut std::io::empty(), 1).unwrap_err(); + assert_eq!(err.kind(), ErrorKind::UnexpectedEof); + } + + #[test] + fn source_that_grew_fails_after_one_byte_too_many() { + let err = read_exactly(&mut pattern(11).as_slice(), 10).unwrap_err(); + assert_eq!(err.kind(), ErrorKind::InvalidData); + // An empty file that is not empty any more. + let err = read_exactly(&mut pattern(1).as_slice(), 0).unwrap_err(); + assert_eq!(err.kind(), ErrorKind::InvalidData); + // However much was appended, it is not buffered: a source without an + // end is given up on after the eleventh byte. + let err = read_exactly(&mut std::io::repeat(7), 10).unwrap_err(); + assert_eq!(err.kind(), ErrorKind::InvalidData); + } + + #[tokio::test] + async fn file_for_a_single_put_must_have_the_length_it_was_measured_with() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("data.parquet"); + let data = pattern(64 * 1024 + 17); + std::fs::write(&path, &data).unwrap(); + + let file = tokio::fs::File::open(&path).await.unwrap(); + assert_eq!( + read_file_for_single_put(file, data.len()).await.unwrap(), + data + ); + // The file was longer, or shorter, when the upload was planned. + for (measured, kind) in [ + (data.len() + 1, ErrorKind::UnexpectedEof), + (data.len() - 1, ErrorKind::InvalidData), + ] { + let file = tokio::fs::File::open(&path).await.unwrap(); + match read_file_for_single_put(file, measured).await { + Err(ObjectStorageError::IoError(err)) => assert_eq!(err.kind(), kind), + other => panic!("unexpected result {other:?}"), + } + } + } +} From 2f74ec86ea2662e37ee293044328dce9916da4cb Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:18:43 -0600 Subject: [PATCH 02/17] Bound staging memory and index flushed IPC batches for projected reads --- src/parseable/staging/disk_source.rs | 291 ++++++++++++- src/parseable/staging/memory_budget.rs | 32 +- src/parseable/staging/reader.rs | 558 ++++++++++++++++++++----- src/parseable/staging/writer.rs | 511 +++++++++++++++------- 4 files changed, 1124 insertions(+), 268 deletions(-) diff --git a/src/parseable/staging/disk_source.rs b/src/parseable/staging/disk_source.rs index cefd5ba87..8f46f4000 100644 --- a/src/parseable/staging/disk_source.rs +++ b/src/parseable/staging/disk_source.rs @@ -43,9 +43,9 @@ use arrow_schema::{ArrowError, Schema}; use super::{ StagingError, reader::{ - DEFAULT_ADAPTIVE_FALLBACK_CONSECUTIVE_MATCHES, MessageRangeReader, TwoPhaseFilteredReader, - ValidatedPrefixPlan, exact_prefix_reader, plan_exact_prefix, stream_reader_for_ranges, - two_phase_filtered_reader, + DEFAULT_ADAPTIVE_FALLBACK_CONSECUTIVE_MATCHES, MessageRangeReader, RangeBatchReader, + TwoPhaseFilteredReader, ValidatedIpcMessage, ValidatedPrefixPlan, exact_prefix_reader, + plan_exact_prefix, reader_for_plan, two_phase_filtered_reader, }, }; use crate::utils::arrow::batch_adapter::BatchAdapter; @@ -98,7 +98,10 @@ impl Seek for BoundedFile { fn seek(&mut self, pos: SeekFrom) -> io::Result { let target = match pos { SeekFrom::Start(offset) => Some(offset), - SeekFrom::End(delta) => self.len.checked_add_signed(delta), + SeekFrom::End(delta) => self + .len + .min(self.file.metadata()?.len()) + .checked_add_signed(delta), SeekFrom::Current(delta) => self.position.checked_add_signed(delta), }; let target = target.ok_or_else(|| { @@ -109,6 +112,85 @@ impl Seek for BoundedFile { } } +/// Certified bounds of the millisecond p_timestamp column. Keeping both +/// extrema under one discriminant makes an index entry 40 bytes on 64-bit. +#[derive(Debug, Clone, Copy, Eq, PartialEq)] +pub enum TimestampBounds { + Unknown, + HasNulls, + NonNull { min: i64, max: i64 }, +} + +#[derive(Debug, Clone, Copy)] +pub struct IndexedIpcBatch { + pub offset: u64, + pub length: u32, + pub num_rows: u32, + pub timestamp: TimestampBounds, +} + +impl IndexedIpcBatch { + fn end(&self) -> u64 { + self.offset + u64::from(self.length) + } +} + +/// Only flush publishes entries. A snapshot owns its selected prefix across +/// further appends, cache clears, publication renames and retirement. +#[derive(Debug)] +pub(super) struct AcknowledgedIpcIndex { + schema: Arc, + schema_len: u64, + batches: parking_lot::Mutex>, +} + +impl AcknowledgedIpcIndex { + pub(super) fn new(schema: Arc, schema_len: u64) -> Self { + Self { + schema, + schema_len, + batches: Default::default(), + } + } + + pub(super) fn commit(&self, provisional: &mut Vec) { + let mut entries = self.batches.lock(); + let mut expected = entries.last().map_or(self.schema_len, IndexedIpcBatch::end); + for entry in provisional.drain(..) { + // A message too large for a compact entry leaves a gap. Keep the + // earlier index valid and let later captures use the byte scanner. + if entry.offset != expected { + break; + } + expected = entry.end(); + entries.push(entry); + } + } + + pub(super) fn snapshot(&self, start: u64, end: u64) -> Option { + let start = if start == 0 { self.schema_len } else { start }; + let entries = self.batches.lock(); + let first = entries.partition_point(|entry| entry.offset < start); + let past = entries.partition_point(|entry| entry.offset < end); + let selected = entries.get(first..past)?; + if selected.first()?.offset != start || selected.last()?.end() != end { + return None; + } + Some(IpcIndexSnapshot { + schema: Arc::clone(&self.schema), + schema_len: usize::try_from(self.schema_len).ok()?, + batches: Arc::from(selected), + }) + } +} + +#[derive(Debug, Clone)] +pub(super) struct IpcIndexSnapshot { + schema: Arc, + schema_len: usize, + batches: Arc<[IndexedIpcBatch]>, +} + /// The exact acknowledged prefix of one staging file, opened for reading. #[derive(Debug, Clone)] pub struct StagingDiskSource { @@ -117,6 +199,7 @@ pub struct StagingDiskSource { start: u64, len: u64, path: PathBuf, + index: Option, } /// Forward or reverse record batches of a [`StagingDiskSource`]. @@ -147,6 +230,7 @@ impl StagingDiskSource { file: Arc::new(file), start, len, + index: None, path: path.to_path_buf(), }); } @@ -165,6 +249,16 @@ impl StagingDiskSource { .into()) } + pub(super) fn with_index(mut self, index: Option) -> Self { + self.index = index; + self + } + + /// Immutable acknowledged record-batch locations and statistics for this range. + pub fn indexed_batches(&self) -> Option<&Arc<[IndexedIpcBatch]>> { + self.index.as_ref().map(|index| &index.batches) + } + /// The path the file had when it was opened. It may have been renamed or /// unlinked since; the descriptor still reads the same inode. pub fn path(&self) -> &Path { @@ -212,12 +306,73 @@ impl StagingDiskSource { /// and complete IPC message index for parallel range reads, column /// projection pushdown, and zero-body-read row counting. pub(crate) fn plan_prefix(&self) -> Result { + self.plan_indexed_or_scan(None, false).map(|(plan, _)| plan) + } + + /// Prune against an exact `[start_ms, end_ms)` predicate on `p_timestamp`. + /// Set `fold_counts` only for a row count with no other residual predicate. + /// Folded rows are excluded from the returned messages. All remaining + /// messages still need the caller's ordinary predicate evaluation. + pub(crate) fn plan_prefix_for_time_range( + &self, + start_ms: i64, + end_ms: i64, + fold_counts: bool, + ) -> Result<(ValidatedPrefixPlan, u64), StagingError> { + self.plan_indexed_or_scan(Some(start_ms..end_ms), fold_counts) + } + + fn plan_indexed_or_scan( + &self, + time: Option>, + fold_counts: bool, + ) -> Result<(ValidatedPrefixPlan, u64), StagingError> { + if let Some(index) = &self.index { + let mut messages = Vec::new(); + let mut folded = 0u64; + for batch in index.batches.iter() { + if let (Some(time), TimestampBounds::NonNull { min, max }) = + (&time, batch.timestamp) + { + if max < time.start || min >= time.end || time.is_empty() { + continue; + } + if fold_counts && time.contains(&min) && time.contains(&max) { + folded = + folded + .checked_add(u64::from(batch.num_rows)) + .ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidData, + "indexed row count overflow", + ) + })?; + continue; + } + } + messages.push(ValidatedIpcMessage { + offset: batch.offset, + size: batch.length as usize, + rows: Some(batch.num_rows as usize), + }); + } + return Ok(( + ValidatedPrefixPlan { + schema: Arc::clone(&index.schema), + schema_range: (0, index.schema_len), + messages, + has_dictionaries: false, + }, + folded, + )); + } self.validate_file_len()?; plan_exact_prefix( BoundedFile::new(Arc::clone(&self.file), self.len), self.start, self.len, ) + .map(|plan| (plan, 0)) .map_err(|err| { StagingError::ObjectStorage(io::Error::new( err.kind(), @@ -234,13 +389,14 @@ impl StagingDiskSource { ranges: Arc<[(u64, usize)]>, projection: Option>, buffer_bytes: usize, - ) -> Result { + ) -> Result, StagingError> { self.validate_file_len()?; - stream_reader_for_ranges( + RangeBatchReader::try_new( BoundedFile::new(Arc::clone(&self.file), self.len), ranges, projection, buffer_bytes, + self.index.as_ref().map(|i| i.schema.clone()), ) .map_err(|err| { StagingError::ObjectStorage(io::Error::new( @@ -291,12 +447,12 @@ impl StagingDiskSource { /// unless the complete IPC messages end exactly at the recorded length. pub(crate) fn reader(&self, reverse: bool) -> Result { self.validate_file_len()?; - exact_prefix_reader( - BoundedFile::new(Arc::clone(&self.file), self.len), - self.start, - self.len, - reverse, - ) + let reader = BoundedFile::new(Arc::clone(&self.file), self.len); + if self.index.is_some() { + reader_for_plan(reader, self.plan_prefix()?, reverse) + } else { + exact_prefix_reader(reader, self.start, self.len, reverse) + } .map_err(|err| { StagingError::ObjectStorage(io::Error::new( err.kind(), @@ -469,6 +625,117 @@ mod tests { out } + #[test] + fn indexed_time_range_folds_only_certified_rows_and_reads_boundaries() { + use super::TimestampBounds; + use crate::parseable::staging::{ + memory_budget::StagingMemoryBudget, + writer::{MemWriter, Writer}, + }; + use crate::utils::time::TimeRange; + use arrow_array::{ArrayRef, TimestampMillisecondArray}; + use arrow_schema::TimeUnit; + use chrono::Utc; + + let dir = TempDir::new().unwrap(); + let path = dir.path().join("time.arrows"); + let schema = Arc::new(Schema::new(vec![ + Field::new( + "p_timestamp", + DataType::Timestamp(TimeUnit::Millisecond, None), + true, + ), + Field::new("payload", DataType::Utf8, false), + ])); + let mut writer = Writer { + mem: Some(MemWriter::with_budget(StagingMemoryBudget::new(0))), + disk: Default::default(), + }; + for times in [ + vec![Some(-2), Some(-1)], + vec![Some(12), Some(15), Some(12)], + vec![Some(10), Some(25), Some(10)], + vec![Some(20)], + vec![Some(14), None], + vec![Some(9), Some(11)], + ] { + let payload = Arc::new(StringArray::from(vec!["unused"; times.len()])) as ArrayRef; + let batch = RecordBatch::try_new( + schema.clone(), + vec![Arc::new(TimestampMillisecondArray::from(times)), payload], + ) + .unwrap(); + writer + .push_disk_and_memory( + "time.arrows", + "time", + &batch, + path.clone(), + TimeRange::granularity_range(Utc::now(), crate::OBJECT_STORE_DATA_GRANULARITY), + ) + .unwrap(); + } + let source = writer.capture(&schema).unwrap().disk.pop().unwrap(); + let index = source.indexed_batches().unwrap(); + assert_eq!(index.len(), 6); + assert_eq!( + index[2].timestamp, + TimestampBounds::NonNull { min: 10, max: 25 } + ); + assert_eq!(index[4].timestamp, TimestampBounds::HasNulls); + assert_eq!(std::mem::size_of::(), 40); + + let (plan, folded) = source.plan_prefix_for_time_range(10, 20, true).unwrap(); + assert_eq!(folded, 3); + assert_eq!( + plan.messages.iter().map(|m| m.offset).collect::>(), + [index[2].offset, index[4].offset, index[5].offset] + ); + let mut ranges = vec![plan.schema_range]; + ranges.extend(plan.messages.iter().map(|m| (m.offset, m.size))); + let mut total = folded; + for batch in source + .reader_for_ranges(ranges.into(), Some(vec![0]), 8192) + .unwrap() + { + let batch = batch.unwrap(); + let times = batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + total += times + .iter() + .flatten() + .filter(|t| (10..20).contains(t)) + .count() as u64; + } + assert_eq!(total, 7); + let (plan, folded) = source.plan_prefix_for_time_range(10, 20, false).unwrap(); + assert_eq!(plan.messages.len(), 4); + assert_eq!(folded, 0); + + let unindexed = StagingDiskSource::open_first(&[source.path()], 0, source.len()).unwrap(); + let (plan, folded) = unindexed.plan_prefix_for_time_range(10, 20, true).unwrap(); + assert_eq!(plan.messages.len(), 6); + assert_eq!(folded, 0); + + // An unreadable prefix still permits purely in-memory planning. The + // executor's independent length check catches physical truncation. + OpenOptions::new() + .write(true) + .open(source.path()) + .unwrap() + .set_len(0) + .unwrap(); + assert!(source.validate_file_len().is_err()); + assert!(unindexed.plan_prefix_for_time_range(10, 20, true).is_err()); + assert_eq!( + source.plan_prefix_for_time_range(10, 20, true).unwrap().1, + 3 + ); + } + #[test] fn disk_source_two_phase_matches_single_phase_forward_reverse_and_nonzero_start() { let dir = TempDir::new().unwrap(); diff --git a/src/parseable/staging/memory_budget.rs b/src/parseable/staging/memory_budget.rs index 69d48d490..0cab42eee 100644 --- a/src/parseable/staging/memory_budget.rs +++ b/src/parseable/staging/memory_budget.rs @@ -35,9 +35,10 @@ use tracing::{info, warn}; pub const MEMORY_STAGING_MAX_BYTES_VAR: &str = "P_MEMORY_STAGING_MAX_BYTES"; /// Fraction of effective memory used when no explicit budget is configured. -const DEFAULT_BUDGET_PERCENT: u64 = 25; +const DEFAULT_BUDGET_PERCENT: u64 = 10; +const MAX_AUTO_BUDGET_BYTES: usize = 512 * 1024 * 1024; /// Used when neither cgroup nor host memory can be read. -const FALLBACK_BUDGET_BYTES: usize = 512 * 1024 * 1024; +const FALLBACK_BUDGET_BYTES: usize = 256 * 1024 * 1024; /// Once over budget, caching resumes only below this share of the budget. const RESUME_PERCENT: usize = 80; @@ -80,6 +81,13 @@ impl StagingMemoryBudget { self.limit.load(Ordering::Acquire) } + /// Reserve room for other segments while allowing a small budget to cache + /// at least one ordinary batch. + pub fn segment_limit(&self) -> usize { + let limit = self.limit(); + (limit / 2).max(1024 * 1024).min(limit) + } + pub fn set_limit(&self, limit: usize) { self.limit.store(limit, Ordering::Release); self.shedding.store(false, Ordering::Release); @@ -182,7 +190,7 @@ impl StagingMemoryBudget { } /// CLI/env wrapper for `P_MEMORY_STAGING_MAX_BYTES` supporting numeric bytes, -/// `0` (disk-only), and `auto` / empty string (automatic 25% sizing). +/// `0` (disk-only), and `auto` / empty string (capped automatic sizing). #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct MemoryStagingBudget(pub Option); @@ -210,10 +218,15 @@ pub fn parse_budget(value: &str) -> Result, String> { /// `DEFAULT_BUDGET_PERCENT` of the effective cgroup/host memory limit. pub fn auto_budget_bytes() -> usize { let total = crate::handlers::http::resource_check::effective_memory_limit_bytes(); + auto_budget_for(total) +} + +fn auto_budget_for(total: u64) -> usize { if total == 0 { return FALLBACK_BUDGET_BYTES; } - usize::try_from(total / 100 * DEFAULT_BUDGET_PERCENT).unwrap_or(usize::MAX) + let share = total / 100 * DEFAULT_BUDGET_PERCENT + total % 100 * DEFAULT_BUDGET_PERCENT / 100; + share.min(MAX_AUTO_BUDGET_BYTES as u64) as usize } fn initial_budget() -> usize { @@ -293,6 +306,17 @@ mod tests { assert!(!disabled.admit(0)); } + #[test] + fn automatic_sizing_caps_large_hosts_and_preserves_small_limits() { + assert_eq!(auto_budget_for(0), 256 << 20); + assert_eq!(auto_budget_for(10_499), 1_049); + assert_eq!(auto_budget_for(24 << 30), 512 << 20); + assert_eq!(auto_budget_for(u64::MAX), 512 << 20); + for (limit, segment) in [(0, 0), (100, 100), (512 << 20, 256 << 20)] { + assert_eq!(StagingMemoryBudget::new(limit).segment_limit(), segment); + } + } + #[test] fn budget_values_parse() { assert_eq!(parse_budget(""), Ok(None)); diff --git a/src/parseable/staging/reader.rs b/src/parseable/staging/reader.rs index ee6f40d61..5f16e07d9 100644 --- a/src/parseable/staging/reader.rs +++ b/src/parseable/staging/reader.rs @@ -22,6 +22,7 @@ use std::{ fmt, fs::File, io::{self, BufReader, Read, Seek, SeekFrom}, + ops::Range, path::PathBuf, ptr::NonNull, sync::{ @@ -39,12 +40,11 @@ use arrow::{ buffer::{BooleanBuffer, Buffer, MutableBuffer, NullBuffer}, }; use arrow_array::{ - Array, ArrayRef, BooleanArray, RecordBatch, RecordBatchOptions, TimestampMillisecondArray, - make_array, + Array, BooleanArray, RecordBatch, RecordBatchOptions, TimestampMillisecondArray, make_array, }; use arrow_ipc::{ MessageHeader, MetadataVersion, - convert::fb_to_schema, + convert::{MessageBuffer, fb_to_schema}, reader::{StreamReader, read_record_batch}, root_as_message, }; @@ -740,6 +740,286 @@ pub(crate) fn stream_reader_for_ranges( }) } +/// For flat fields the IPC buffer ordinals are fixed by the file schema. +fn flat_buffer_layout(schema: &Schema) -> Option>> { + let mut next = 0; + schema + .fields() + .iter() + .map(|field| { + let count = match field.data_type() { + DataType::Null => 0, + DataType::Boolean | DataType::FixedSizeBinary(_) => 2, + ty if ty.is_primitive() => 2, + DataType::Binary | DataType::LargeBinary | DataType::Utf8 | DataType::LargeUtf8 => { + 3 + } + _ => return None, + }; + let start = next; + next += count; + Some(start..next) + }) + .collect() +} + +fn invalid_ipc(msg: &'static str) -> io::Error { + io::Error::new(io::ErrorKind::InvalidData, msg) +} + +// Codec failures can surface as io::Error inside Arrow. All input to this +// decoder is in memory, so distinguish them from a short filesystem read. +fn ipc_decode_error(err: ArrowError) -> ArrowError { + match err { + ArrowError::IoError(_, _) => { + ArrowError::IpcError(format!("IPC decompression failed: {err}")) + } + other => other, + } +} + +/// Framing and layout are validated against the original message before +/// reading body buffers. Nested schemas keep the full body for both phases. +struct BatchMessage { + metadata: MessageBuffer, + body_start: u64, + full_body: Option, +} + +impl BatchMessage { + fn read( + reader: &mut R, + offset: u64, + size: usize, + schema: &Schema, + sparse: bool, + ) -> Result { + let raw = if sparse { + let end = offset + .checked_add(size as u64) + .ok_or_else(|| invalid_ipc("IPC range overflow"))?; + if reader.seek(SeekFrom::End(0))? < end { + return Err(invalid_ipc("Truncated IPC record batch range").into()); + } + read_exact_range(reader, offset, size.min(8))? + } else { + read_exact_range(reader, offset, size)? + }; + let (start, len) = ipc_metadata_range(&raw, size)?; + let header_end = start + len; + let body_start = offset + .checked_add(header_end as u64) + .ok_or_else(|| invalid_ipc("IPC offset overflow"))?; + let metadata = MessageBuffer::try_new(if sparse { + read_exact_range(reader, body_start - len as u64, len)? + } else { + raw.slice_with_length(start, len) + })?; + let message = metadata.as_ref(); + let rb = message.header_as_record_batch().ok_or_else(|| { + ArrowError::IpcError(format!( + "Expected IPC RecordBatch, got {:?}", + message.header_type() + )) + })?; + let body_len = usize::try_from(message.bodyLength()) + .map_err(|_| invalid_ipc("Invalid IPC body length"))?; + let available = size - header_end; + if body_len > available || available - body_len > 7 { + return Err(invalid_ipc("IPC body length does not match its message range").into()); + } + pre_validate_record_batch(schema, rb, message.version(), body_len)?; + let full_body = (!sparse).then(|| raw.slice_with_length(header_end, body_len)); + Ok(Self { + metadata, + body_start, + full_body, + }) + } + + fn decode( + &self, + reader: &mut R, + schema: &Arc, + layout: Option<&[Range]>, + projection: &[usize], + ) -> Result { + let message = self.metadata.as_ref(); + let rb = message + .header_as_record_batch() + .expect("validated record batch"); + let version = message.version(); + if let Some(body) = &self.full_body { + return read_record_batch( + body, + rb, + schema.clone(), + &HashMap::new(), + Some(projection), + &version, + ) + .map_err(ipc_decode_error); + } + + // Rebuild the selected flat fields' nodes and buffer descriptors. + // Arrow decodes this compact body with the original compression + // metadata, including individually stored, uncompressed (-1) frames. + let layout = layout.expect("sparse reads require a flat schema"); + let buffers = rb.buffers().expect("validated buffer vector"); + let nodes = rb.nodes().expect("validated field nodes"); + let mut selected_nodes = Vec::with_capacity(projection.len()); + let mut selected_buffers = Vec::new(); + let mut body = MutableBuffer::new(0); + for &column in projection { + selected_nodes.push(*nodes.get(column)); + for ordinal in layout[column].clone() { + let buffer = buffers.get(ordinal); + let len = buffer.length() as usize; + let dest = body.len().next_multiple_of(8); + let end = dest + .checked_add(len) + .ok_or_else(|| invalid_ipc("Projected IPC body overflow"))?; + // Overlapping malformed descriptors must not amplify allocations. + if end > message.bodyLength() as usize { + return Err(invalid_ipc("Projected buffers exceed original IPC body").into()); + } + body.resize(end, 0); + if len > 0 { + reader.seek(SeekFrom::Start(self.body_start + buffer.offset() as u64))?; + read_ipc_exact(reader, &mut body.as_slice_mut()[dest..])?; + } + selected_buffers.push(arrow_ipc::Buffer::new(dest as i64, len as i64)); + } + } + + let mut fb = Default::default(); + let compression = rb.compression().map(|c| { + arrow_ipc::BodyCompression::create( + &mut fb, + &arrow_ipc::BodyCompressionArgs { + codec: c.codec(), + method: c.method(), + }, + ) + }); + let nodes = fb.create_vector(&selected_nodes); + let buffers = fb.create_vector(&selected_buffers); + let record = arrow_ipc::RecordBatch::create( + &mut fb, + &arrow_ipc::RecordBatchArgs { + length: rb.length(), + nodes: Some(nodes), + buffers: Some(buffers), + compression, + ..Default::default() + }, + ); + let header = arrow_ipc::Message::create( + &mut fb, + &arrow_ipc::MessageArgs { + version, + header_type: MessageHeader::RecordBatch, + header: Some(record.as_union_value()), + bodyLength: body.len() as i64, + ..Default::default() + }, + ); + arrow_ipc::finish_message_buffer(&mut fb, header); + let header = root_as_message(fb.finished_data()) + .map_err(|e| ArrowError::ParseError(e.to_string()))?; + read_record_batch( + &Buffer::from(body), + header.header_as_record_batch().expect("built record batch"), + Arc::new(schema.project(projection)?), + &HashMap::new(), + None, + &version, + ) + .map_err(ipc_decode_error) + } +} + +#[derive(Debug)] +pub(crate) enum RangeBatchReader { + Stream(Box>>>), + Projected { + reader: R, + schema: Arc, + ranges: Arc<[(u64, usize)]>, + next: usize, + layout: Vec>, + projection: Vec, + }, +} + +impl RangeBatchReader { + pub(crate) fn try_new( + mut reader: R, + ranges: Arc<[(u64, usize)]>, + projection: Option>, + buffer_bytes: usize, + known_schema: Option>, + ) -> io::Result { + if let Some(columns) = &projection { + let schema = match known_schema { + Some(schema) => schema, + None => { + let &(offset, size) = ranges + .first() + .ok_or_else(|| invalid_ipc("Missing IPC schema"))?; + if size > MAX_IPC_SCHEMA_MESSAGE_BYTES { + return Err(invalid_ipc("Oversize IPC schema")); + } + parse_schema_message(&read_exact_range(&mut reader, offset, size)?)? + } + }; + if columns.len() < schema.fields().len() + && columns.windows(2).all(|pair| pair[0] < pair[1]) + && columns.last().is_none_or(|&i| i < schema.fields().len()) + && let Some(layout) = flat_buffer_layout(&schema) + { + return Ok(Self::Projected { + reader, + schema, + ranges, + next: 1, + layout, + projection: columns.clone(), + }); + } + } + stream_reader_for_ranges(reader, ranges, projection, buffer_bytes) + .map(|reader| Self::Stream(Box::new(reader))) + } +} + +impl Iterator for RangeBatchReader { + type Item = Result; + fn next(&mut self) -> Option { + match self { + Self::Stream(reader) => reader.next(), + Self::Projected { + reader, + schema, + ranges, + next, + layout, + projection, + } => { + let &(offset, size) = ranges.get(*next)?; + let batch = BatchMessage::read(reader, offset, size, schema, true) + .and_then(|message| message.decode(reader, schema, Some(layout), projection)); + *next = if batch.is_ok() { + *next + 1 + } else { + ranges.len() + }; + Some(batch) + } + } + } +} + /// Arrow IPC streaming continuation marker (`0xFFFFFFFF`). const IPC_CONTINUATION_MARKER: [u8; 4] = [0xFF; 4]; @@ -904,6 +1184,15 @@ pub(crate) enum TwoPhaseReadError { Filter(E), } +impl TwoPhaseReadError { + fn from_decode(error: ArrowError) -> Self { + match error { + ArrowError::IoError(_, err) => Self::Io(err), + other => Self::Arrow(other), + } + } +} + impl fmt::Display for TwoPhaseReadError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { @@ -945,7 +1234,7 @@ enum ColumnSource { enum TwoPhaseReaderSource { TwoPhase(R), - SinglePhase(Box>>>), + SinglePhase(Box>), Exhausted, } @@ -967,7 +1256,7 @@ type CancelCheck = Arc bool + Send + Sync>; /// `ranges[0]` must be the IPC `Schema` message and `ranges[1..]` must be /// `RecordBatch` messages (in any order — forward, reversed, or partitioned). /// For each message admitted under the per-message and shared byte budgets, -/// the raw bytes are read once into a single bounded buffer: +/// flat schemas read only the body buffers needed by each phase: /// 1. Phase 1 decodes only `filter_indices` and calls `eval_filter`. /// 2. If zero rows match, the buffer and budget permit are dropped immediately /// with zero decompression of the remaining output columns. @@ -1000,7 +1289,7 @@ pub(crate) struct TwoPhaseFilteredReader { single_phase_indices: Vec, single_phase_filter_positions: Vec, single_phase_output_positions: Vec, - empty_dictionaries: HashMap, + flat_layout: Option>>, eval_filter: F, max_message_bytes: usize, shared_budget: BudgetHandle, @@ -1213,6 +1502,7 @@ where source: TwoPhaseReaderSource::TwoPhase(reader), ranges, next_range_idx: 1, + flat_layout: flat_buffer_layout(&file_schema), file_schema, filter_schema, output_schema, @@ -1223,7 +1513,6 @@ where single_phase_indices, single_phase_filter_positions, single_phase_output_positions, - empty_dictionaries: HashMap::new(), eval_filter, max_message_bytes: STAGING_TWO_PHASE_MAX_MESSAGE_BYTES, shared_budget: BudgetHandle::Static(&STAGING_TWO_PHASE_SHARED_BUDGET), @@ -1301,9 +1590,8 @@ where }); } - // Acquire shared memory admission BEFORE allocating the raw message - // buffer. Declared before `raw_buf` so `raw_buf` is dropped before - // the permit releases bytes back to the shared budget. + // Admit the message before allocating its metadata or body buffers. + // The permit covers both phases, including the whole-body fallback. let Some(_budget_permit) = self.shared_budget.try_acquire(size) else { let reason = TwoPhaseFallbackReason::SharedBudgetExhausted { message_bytes: size, @@ -1323,67 +1611,23 @@ where let TwoPhaseReaderSource::TwoPhase(reader) = &mut self.source else { return Ok(TwoPhaseStep::Finished); }; - let raw_buf = - read_exact_range(reader, offset, size).map_err(TwoPhaseReadError::Io)?; - let raw_data_ptr = raw_buf.data_ptr(); - - let (meta_start, meta_len) = - parse_ipc_message_prefix(raw_buf.as_slice()).map_err(TwoPhaseReadError::Io)?; - let meta_end = meta_start + meta_len; - let message = - root_as_message(&raw_buf.as_slice()[meta_start..meta_end]).map_err(|err| { - TwoPhaseReadError::Arrow(ArrowError::ParseError(format!( - "Unable to get root as message: {err:?}" - ))) - })?; - if message.header_type() != MessageHeader::RecordBatch { - return Err(TwoPhaseReadError::Arrow(ArrowError::IpcError(format!( - "Expected RecordBatch IPC message in two-phase reader, got {:?}", - message.header_type() - )))); - } - let rb_msg = message.header_as_record_batch().ok_or_else(|| { - TwoPhaseReadError::Arrow(ArrowError::IpcError( - "Unable to read IPC message as record batch".to_string(), - )) - })?; - let body_len = usize::try_from(message.bodyLength()).map_err(|_| { - TwoPhaseReadError::Io(io::Error::new( - io::ErrorKind::InvalidData, - "Invalid Arrow IPC body length", - )) - })?; - let body_end = meta_end.checked_add(body_len).ok_or_else(|| { - TwoPhaseReadError::Io(io::Error::new( - io::ErrorKind::InvalidData, - "Arrow IPC message body length overflow", - )) - })?; - if body_end > raw_buf.len() || raw_buf.len() - body_end > 7 { - return Err(TwoPhaseReadError::Io(io::Error::new( - io::ErrorKind::InvalidData, - format!( - "Arrow IPC message body boundary {body_end} does not match declared range length {}", - raw_buf.len() - ), - ))); - } - let version = message.version(); - pre_validate_record_batch(&self.file_schema, rb_msg, version, body_len) - .map_err(TwoPhaseReadError::Io)?; - - let body_buf = raw_buf.slice_with_length(meta_end, body_len); - - // Phase 1: decompress and decode ONLY the narrow filter columns. - let filter_batch = read_record_batch( - &body_buf, - rb_msg, - Arc::clone(&self.file_schema), - &self.empty_dictionaries, - Some(&self.filter_indices), - &version, + let message = BatchMessage::read( + reader, + offset, + size, + &self.file_schema, + self.flat_layout.is_some() + && self.filter_indices.len() < self.file_schema.fields().len(), ) - .map_err(TwoPhaseReadError::Arrow)?; + .map_err(TwoPhaseReadError::from_decode)?; + let filter_batch = message + .decode( + reader, + &self.file_schema, + self.flat_layout.as_deref(), + &self.filter_indices, + ) + .map_err(TwoPhaseReadError::from_decode)?; let num_rows = filter_batch.num_rows(); if num_rows == 0 { @@ -1405,8 +1649,7 @@ where if true_count == 0 { self.stats.batches_skipped_zero_matches += 1; self.consecutive_matching_batches = 0; - // `body_buf`, `raw_buf`, and `_budget_permit` drop here with - // zero decompression of the remaining payload columns. + // No output buffers are decoded for a rejected batch. continue; } @@ -1425,15 +1668,14 @@ where } else { self.stats.phase2_decodes += 1; Some( - read_record_batch( - &body_buf, - rb_msg, - Arc::clone(&self.file_schema), - &self.empty_dictionaries, - Some(&self.extra_indices), - &version, - ) - .map_err(TwoPhaseReadError::Arrow)?, + message + .decode( + reader, + &self.file_schema, + self.flat_layout.as_deref(), + &self.extra_indices, + ) + .map_err(TwoPhaseReadError::from_decode)?, ) }; @@ -1465,14 +1707,16 @@ where // Ensure emitted arrays never retain a reference to the whole // raw IPC message `Buffer` after `_budget_permit` is released. - if true_count == num_rows { - detach_batch_from_raw(combined, raw_data_ptr) - .map_err(TwoPhaseReadError::Arrow)? + let result = if true_count == num_rows { + combined } else { - let filtered = filter_record_batch(&combined, &mask) - .map_err(TwoPhaseReadError::Arrow)?; - detach_batch_from_raw(filtered, raw_data_ptr) + filter_record_batch(&combined, &mask).map_err(TwoPhaseReadError::Arrow)? + }; + if let Some(body) = &message.full_body { + detach_batch_from_raw(result, body.data_ptr()) .map_err(TwoPhaseReadError::Arrow)? + } else { + result } }; @@ -1514,11 +1758,12 @@ where } }; - let stream_reader = stream_reader_for_ranges( + let stream_reader = RangeBatchReader::try_new( raw_reader, remaining_ranges, projection, MESSAGE_READ_BUFFER_BYTES, + Some(self.file_schema.clone()), ) .map_err(TwoPhaseReadError::Io)?; self.source = TwoPhaseReaderSource::SinglePhase(Box::new(stream_reader)); @@ -1539,10 +1784,7 @@ where return Ok(None); }; self.stats.messages_scanned += 1; - let batch = batch_res.map_err(|err| match err { - ArrowError::IoError(_, io_err) => TwoPhaseReadError::Io(io_err), - other => TwoPhaseReadError::Arrow(other), - })?; + let batch = batch_res.map_err(TwoPhaseReadError::from_decode)?; let num_rows = batch.num_rows(); if num_rows == 0 { @@ -1828,9 +2070,13 @@ fn read_exact_range( ) -> io::Result { reader.seek(SeekFrom::Start(offset))?; let mut buf = MutableBuffer::from_len_zeroed(size); - let slice = buf.as_slice_mut(); + read_ipc_exact(reader, buf.as_slice_mut())?; + Ok(Buffer::from(buf)) +} + +fn read_ipc_exact(reader: &mut impl Read, slice: &mut [u8]) -> io::Result<()> { let mut read_total = 0; - while read_total < size { + while read_total < slice.len() { match reader.read(&mut slice[read_total..]) { Ok(0) => { return Err(io::Error::new( @@ -1843,13 +2089,17 @@ fn read_exact_range( Err(err) => return Err(err), } } - Ok(Buffer::from(buf)) + Ok(()) } /// Parses the length prefix of one framed Arrow IPC message, handling both the /// standard `0xFFFFFFFF` continuation marker and the legacy 4-byte prefix /// identically to `arrow_ipc::reader::StreamReader`. fn parse_ipc_message_prefix(bytes: &[u8]) -> io::Result<(usize, usize)> { + ipc_metadata_range(bytes, bytes.len()) +} + +fn ipc_metadata_range(bytes: &[u8], message_size: usize) -> io::Result<(usize, usize)> { if bytes.len() < 4 { return Err(io::Error::new( io::ErrorKind::InvalidData, @@ -1888,12 +2138,11 @@ fn parse_ipc_message_prefix(bytes: &[u8]) -> io::Result<(usize, usize)> { "Arrow IPC metadata length overflow", ) })?; - if meta_end > bytes.len() { + if meta_end > message_size { return Err(io::Error::new( io::ErrorKind::InvalidData, format!( - "Arrow IPC metadata boundary {meta_end} exceeds declared message range length {}", - bytes.len() + "Arrow IPC metadata boundary {meta_end} exceeds declared message range length {message_size}" ), )); } @@ -2731,7 +2980,15 @@ pub(crate) fn exact_prefix_reader( expected_len: u64, reverse: bool, ) -> Result>>, io::Error> { - let mut plan = plan_exact_prefix(&mut reader, start, expected_len)?; + let plan = plan_exact_prefix(&mut reader, start, expected_len)?; + reader_for_plan(reader, plan, reverse) +} + +pub(super) fn reader_for_plan( + reader: R, + mut plan: ValidatedPrefixPlan, + reverse: bool, +) -> io::Result>>> { if reverse && !plan.has_dictionaries { plan.messages.reverse(); } @@ -4183,6 +4440,109 @@ mod tests { Arc::from(ranges) } + #[test] + fn projected_reader_reads_only_selected_buffers_across_codecs_and_alignments() { + use super::super::RangeBatchReader; + use arrow_ipc::reader::StreamReader; + use std::io::{Read, Seek, SeekFrom}; + use std::ops::Range; + + // Fail the test if the reader touches any byte outside framing, + // metadata, and the exact on-disk buffers of the projection. + struct Guarded<'a> { + cursor: Cursor<&'a [u8]>, + allowed: Vec>, + returned: usize, + } + impl Read for Guarded<'_> { + fn read(&mut self, out: &mut [u8]) -> io::Result { + let pos = self.cursor.position(); + let n = self.cursor.read(out)?; + assert!( + self.allowed + .iter() + .any(|r| r.start <= pos && pos + n as u64 <= r.end), + "unexpected read of {n} bytes at {pos}" + ); + self.returned += n; + Ok(n) + } + } + impl Seek for Guarded<'_> { + fn seek(&mut self, to: SeekFrom) -> io::Result { + self.cursor.seek(to) + } + } + + let wide = wide_schema_with_metadata(); + let batch = make_wide_batch(&wide, 0, 110) + .slice(3, 101) + .project(&[0, 1, 2, 3, 4, 5, 6]) + .unwrap(); + let columns = vec![2, 4, 6]; // nullable Utf8, Boolean, LargeUtf8 + let schema = batch.schema(); + for alignment in [8, 64] { + for codec in [ + None, + Some(CompressionType::LZ4_FRAME), + Some(CompressionType::ZSTD), + ] { + let options = IpcWriteOptions::try_new(alignment, false, MetadataVersion::V5) + .unwrap() + .try_with_compression(codec) + .unwrap() + .try_with_compression_level( + (codec == Some(CompressionType::ZSTD)).then_some(1), + ) + .unwrap(); + let bytes = + write_ipc_with_options(&schema, std::slice::from_ref(&batch), options); + let ranges = build_ranges(&bytes, false); + let (offset, size) = ranges[1]; + let raw = &bytes[offset as usize..offset as usize + size]; + let metadata_len = i32::from_le_bytes(raw[4..8].try_into().unwrap()) as usize; + let header = root_as_message(&raw[8..8 + metadata_len]).unwrap(); + let buffers = header.header_as_record_batch().unwrap().buffers().unwrap(); + let body_start = offset + 8 + metadata_len as u64; + let mut allowed = vec![offset..body_start, 0..ranges[0].1 as u64]; + for ordinal in (4..7).chain(9..11).chain(14..17) { + let b = buffers.get(ordinal); + let start = body_start + b.offset() as u64; + allowed.push(start..start + b.length() as u64); + } + let expected_bytes: usize = + allowed.iter().map(|r| (r.end - r.start) as usize).sum(); + let mut guarded = Guarded { + cursor: Cursor::new(&bytes), + allowed, + returned: 0, + }; + let actual = RangeBatchReader::try_new( + &mut guarded, + ranges, + Some(columns.clone()), + 65536, + None, + ) + .unwrap() + .collect::, _>>() + .unwrap(); + let expected = + StreamReader::try_new(Cursor::new(&bytes), Some(columns.clone())) + .unwrap() + .collect::, _>>() + .unwrap(); + assert_eq!(actual, expected); + for (actual, expected) in actual[0].columns().iter().zip(expected[0].columns()) + { + assert_eq!(actual.to_data().buffers(), expected.to_data().buffers()); + assert_eq!(actual.nulls(), expected.nulls()); + } + assert_eq!(guarded.returned, expected_bytes); + } + } + } + #[test] fn two_phase_matches_single_phase_across_selectivities_and_compressions() { let schema = wide_schema_with_metadata(); diff --git a/src/parseable/staging/writer.rs b/src/parseable/staging/writer.rs index 0619bb90b..57f60a192 100644 --- a/src/parseable/staging/writer.rs +++ b/src/parseable/staging/writer.rs @@ -25,12 +25,16 @@ use std::{ io::{BufWriter, Write}, path::{Path, PathBuf}, str::FromStr, - sync::{Arc, mpsc}, + sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, + mpsc, + }, }; -use arrow_array::RecordBatch; +use arrow_array::{Array, RecordBatch, TimestampMillisecondArray}; use arrow_ipc::{ - CompressionType, + CompressionType, MetadataVersion, writer::{ DictionaryTracker, IpcDataGenerator, IpcWriteContext, IpcWriteOptions, StreamWriter, write_message, @@ -51,7 +55,10 @@ use crate::{ use super::{ StagingError, - disk_source::{StagingCapture, StagingDiskSource}, + disk_source::{ + AcknowledgedIpcIndex, IndexedIpcBatch, IpcIndexSnapshot, StagingCapture, StagingDiskSource, + TimestampBounds, + }, memory_budget::{StagingMemoryBudget, global_budget}, }; @@ -82,6 +89,36 @@ const DISK_WRITER_BUFFER_BYTES: usize = 32 * 1024; // after it released its locks. Larger sets go to the drop thread: freeing // gigabytes of small buffers takes long enough to stall ingestion. const BACKGROUND_DROP_MIN_BYTES: usize = 8 << 20; +const MAX_DEFERRED_DROP_BYTES: usize = 64 << 20; +static DEFERRED_DROP_BYTES: AtomicUsize = AtomicUsize::new(0); + +// A full Utf8 chunk uses (4095 + 1) * 4 = 16384 bytes of offsets. +const MEMORY_BATCH_ROWS: usize = 4095; + +fn staging_options() -> IpcWriteOptions { + IpcWriteOptions::try_new(8, false, MetadataVersion::V5).expect("valid staging IPC alignment") +} + +static ZSTD_OPTIONS: Lazy = Lazy::new(|| { + const VAR: &str = "P_STAGING_IPC_ZSTD_LEVEL"; + let options = staging_options() + .try_with_compression(Some(CompressionType::ZSTD)) + .expect("V5 supports compression"); + if let Ok(value) = std::env::var(VAR) { + if let Some(options) = value + .trim() + .parse::() + .ok() + .and_then(|level| options.clone().try_with_compression_level(Some(level)).ok()) + { + return options; + } + tracing::warn!("Invalid {VAR}={value:?}; using level 1"); + } + options + .try_with_compression_level(Some(1)) + .expect("valid zstd level") +}); pub const STAGING_IPC_COMPRESSION_VAR: &str = "P_STAGING_IPC_COMPRESSION"; @@ -100,18 +137,14 @@ pub enum StagingIpcCompression { impl StagingIpcCompression { pub const ALL: [Self; 2] = [Self::Lz4, Self::Zstd]; - fn codec(self) -> CompressionType { + fn write_options(self) -> IpcWriteOptions { match self { - Self::Lz4 => CompressionType::LZ4_FRAME, - Self::Zstd => CompressionType::ZSTD, + Self::Lz4 => staging_options() + .try_with_compression(Some(CompressionType::LZ4_FRAME)) + .expect("V5 supports compression"), + Self::Zstd => ZSTD_OPTIONS.clone(), } } - - fn write_options(self) -> IpcWriteOptions { - IpcWriteOptions::default() - .try_with_compression(Some(self.codec())) - .expect("default IPC options use a metadata version with compression") - } } impl FromStr for StagingIpcCompression { @@ -169,6 +202,7 @@ pub struct PreEncodedBatch { // into a stream opened with it. schema: SchemaRef, rows: usize, + timestamp: TimestampBounds, bytes: Vec, } @@ -201,7 +235,7 @@ impl PreEncodedBatch { let options = if is_compressed_batch(rb) { compression.write_options() } else { - IpcWriteOptions::default() + staging_options() }; let bytes = PREENCODE_CONTEXT.with(|context| { let mut dictionaries = DictionaryTracker::new(false); @@ -224,6 +258,7 @@ impl PreEncodedBatch { Ok(Some(Self { schema: rb.schema(), rows: rb.num_rows(), + timestamp: timestamp_bounds(rb), bytes, })) } @@ -292,11 +327,24 @@ impl Drop for DeferredDrop { if self.inline || self.bytes < BACKGROUND_DROP_MIN_BYTES || self.batches.is_empty() { return; } - if let Some(thread) = DROP_THREAD.as_ref() { + if let Some(thread) = DROP_THREAD.as_ref() + && DEFERRED_DROP_BYTES + .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |queued| { + queued + .checked_add(self.bytes) + .filter(|&total| total <= MAX_DEFERRED_DROP_BYTES) + }) + .is_ok() + { // Bounded channel: if the drop thread is already backed up (or gone), // `try_send` returns the batches to be freed inline here on the caller // thread, which has already released its writer lock and queue turn. - let _ = thread.try_send(std::mem::take(&mut self.batches)); + if thread + .try_send((std::mem::take(&mut self.batches), self.bytes)) + .is_err() + { + DEFERRED_DROP_BYTES.fetch_sub(self.bytes, Ordering::Relaxed); + } } } } @@ -305,13 +353,15 @@ impl Drop for DeferredDrop { // evicted batches outside the staging memory budget; overflow frees inline // off-lock on the caller. `None` when the thread could not be started. const DROP_THREAD_QUEUE_CAPACITY: usize = 16; -static DROP_THREAD: Lazy>>> = Lazy::new(|| { - let (sender, receiver) = mpsc::sync_channel::>(DROP_THREAD_QUEUE_CAPACITY); +type DropJob = (Vec, usize); +static DROP_THREAD: Lazy>> = Lazy::new(|| { + let (sender, receiver) = mpsc::sync_channel::(DROP_THREAD_QUEUE_CAPACITY); std::thread::Builder::new() .name("staging-drop".to_owned()) .spawn(move || { - for batches in receiver { + for (batches, bytes) in receiver { drop(batches); + DEFERRED_DROP_BYTES.fetch_sub(bytes, Ordering::Relaxed); } }) .map_err(|err| error!("Couldn't start the staging drop thread: {err}")) @@ -360,7 +410,7 @@ pub(crate) struct StagedFile<'a> { // #[derive(Default)] pub struct Writer { - pub mem: Option>, + pub mem: Option>, pub disk: HashMap, } @@ -498,6 +548,7 @@ impl Writer { segment.take_cached(deferred); if acknowledged > start { mem.pending.entry(path).or_default().push(PendingSource { + index: writer.index_snapshot(start, acknowledged), start, len: acknowledged, previous: None, @@ -638,14 +689,9 @@ impl Writer { let key = self.append_disk(filename, rb, preencoded, file_path, range, flush, deferred)?; if let Some(mem) = self.mem.as_mut() { match self.disk.get(key.as_ref()) { - Some(writer) => mem.segment(&key).push_disk_backed( - schema_key, - rb, - writer.path(), - writer.last_batch_start(), - writer.staged_len(), - deferred, - )?, + Some(writer) => mem + .segment(&key) + .push_disk_backed(schema_key, rb, writer, deferred)?, None => mem.push_for_file(&key, schema_key, rb)?, } } @@ -771,9 +817,12 @@ impl Writer { fs::create_dir_all(parent)?; } let mut writer = DiskWriter::try_new_shared(file_path, rb.schema(), range)?; - writer.append(rb, preencoded)?; - if flush { - writer.flush_staged()?; + let result = writer + .append(rb, preencoded) + .and_then(|()| if flush { writer.flush_staged() } else { Ok(()) }); + if let Err(err) = result { + writer.retire_failed(); + return Err(err); } self.disk.insert(key, writer); Ok(()) @@ -840,6 +889,7 @@ impl Writer { .entry(writer.path.clone()) .or_default() .push(PendingSource { + index: writer.index_snapshot(start, len), start, len, previous: None, @@ -974,9 +1024,12 @@ impl Write for CountingFile { pub struct DiskWriter { inner: StreamWriter>, - // StreamWriter owns schema validation, the compressed path and EOS/flush. - // Only dictionary-free small messages bypass its fixed write options. - small: Option, + // Dictionary identity belongs to the stream. Compression scratch belongs + // to the encoding thread so an idle stream never retains a compressor. + dictionaries: DictionaryTracker, + compressed_options: IpcWriteOptions, + index: Option>, + provisional: Vec, // The schema the IPC stream was opened with; every batch must have it. schema: SchemaRef, // For the first writer of a staging file name: the keys of the sibling @@ -1003,52 +1056,25 @@ pub struct DiskWriter { sealed: bool, } -/// Keep dictionary schemas on the original path: reverse staging readers reorder -/// dictionary messages as well as batches. Do not introduce new dictionary state -/// transitions while changing compression. `flattened_fields` includes nested fields. -struct SmallBatchEncoder { - dictionaries: DictionaryTracker, - context: IpcWriteContext, - options: IpcWriteOptions, -} - -impl SmallBatchEncoder { - // Keep IPC encoding machinery out of the large-batch append path. - #[inline(never)] - fn write( - &mut self, - rb: &RecordBatch, - sink: &mut W, - ) -> Result<(), arrow_schema::ArrowError> { - let (dictionaries, message) = IpcDataGenerator::default().encode( - rb, - &mut self.dictionaries, - &self.options, - &mut self.context, - )?; - for dictionary in dictionaries { - write_message(&mut *sink, dictionary, &self.options)?; - } - write_message(sink, message, &self.options)?; - Ok(()) +fn timestamp_bounds(batch: &RecordBatch) -> TimestampBounds { + let Some(times) = batch + .column_by_name(crate::event::DEFAULT_TIMESTAMP_KEY) + .and_then(|col| col.as_any().downcast_ref::()) + else { + return TimestampBounds::Unknown; + }; + if times.null_count() != 0 { + return TimestampBounds::HasNulls; } - - fn for_schema(schema: &Schema) -> Option { - if has_dictionary(schema) { - return None; + // Equal endpoints do not certify a constant or sorted batch. + match times.values().split_first() { + Some((&first, rest)) => { + let (min, max) = rest + .iter() + .fold((first, first), |(min, max), &v| (min.min(v), max.max(v))); + TimestampBounds::NonNull { min, max } } - let options = IpcWriteOptions::default(); - let mut dictionaries = DictionaryTracker::new(false); - IpcDataGenerator::default().schema_to_bytes_with_dictionary_tracker( - schema, - &mut dictionaries, - &options, - ); - Some(Self { - dictionaries, - context: IpcWriteContext::default(), - options, - }) + None => TimestampBounds::Unknown, } } @@ -1094,9 +1120,29 @@ impl DiskWriter { compression.write_options(), )?; + let mut dictionaries = DictionaryTracker::new(false); + let index = if has_dictionary(&schema) { + // Assign the same dictionary IDs as the stream header. + IpcDataGenerator::default().schema_to_bytes_with_dictionary_tracker( + &schema, + &mut dictionaries, + &staging_options(), + ); + None + } else { + let sink = inner.get_ref(); + let schema_len = sink.get_ref().written + sink.buffer().len() as u64; + Some(Arc::new(AcknowledgedIpcIndex::new( + schema.clone(), + schema_len, + ))) + }; Ok(Self { inner, - small: SmallBatchEncoder::for_schema(&schema), + dictionaries, + compressed_options: compression.write_options(), + index, + provisional: Vec::new(), schema, siblings: HashMap::new(), path, @@ -1193,7 +1239,11 @@ impl DiskWriter { /// `self.acknowledged` so neither queries nor recovery see unacknowledged /// bytes. pub(crate) fn retire_failed(&mut self) { + if self.sealed { + return; + } self.sealed = true; + self.provisional.clear(); let counting = self.inner.get_mut().get_mut(); counting.retired = true; if let Err(err) = counting.file.set_len(self.acknowledged) { @@ -1241,6 +1291,10 @@ impl DiskWriter { self.staged } + fn index_snapshot(&self, start: u64, end: u64) -> Option { + self.index.as_ref()?.snapshot(start, end) + } + /// The codec of this file's compressed messages. pub fn compression(&self) -> StagingIpcCompression { self.compression @@ -1264,7 +1318,7 @@ impl DiskWriter { /// `rb`: only when it was encoded from a batch of exactly this stream's /// schema. Schemas with dictionaries are never pre-encoded. fn accepts(&self, preencoded: &PreEncodedBatch, rb: &RecordBatch) -> bool { - self.small.is_some() && preencoded.is_for(rb) && self.has_schema(&preencoded.schema) + self.index.is_some() && preencoded.is_for(rb) && self.has_schema(&preencoded.schema) } /// Returns whether this writer belongs to the current time range. @@ -1288,8 +1342,14 @@ impl DiskWriter { rb: &RecordBatch, preencoded: Option<&PreEncodedBatch>, ) -> Result<(), StagingError> { - self.append(rb, preencoded)?; - self.flush_staged() + // A direct caller owns its DiskWriter without a Writer::retire hook. + let result = self + .append(rb, preencoded) + .and_then(|()| self.flush_staged()); + if result.is_err() { + self.retire_failed(); + } + result } /// Appends `rb` to the stream without flushing or acknowledging it. The @@ -1302,18 +1362,54 @@ impl DiskWriter { rb: &RecordBatch, preencoded: Option<&PreEncodedBatch>, ) -> Result<(), StagingError> { - if let Some(preencoded) = preencoded.filter(|preencoded| self.accepts(preencoded, rb)) { + if self.sealed { + return Err( + ArrowError::IpcError("Cannot append to a retired staging writer".into()).into(), + ); + } + let offset = self.position(); // after the schema, including on the first append + let preencoded = preencoded.filter(|preencoded| self.accepts(preencoded, rb)); + if let Some(preencoded) = preencoded { self.inner .get_mut() .write_all(&preencoded.bytes) .map_err(|err| StagingError::Arrow(err.into()))?; - } else if let Some(small) = self.small.as_mut().filter(|_| !is_compressed_batch(rb)) { - small.write(rb, self.inner.get_mut())?; } else { - self.inner.write(rb).map_err(StagingError::Arrow)?; + let raw_options = staging_options(); + let options = if self.index.is_none() || is_compressed_batch(rb) { + &self.compressed_options + } else { + &raw_options + }; + PREENCODE_CONTEXT.with(|context| -> Result<(), ArrowError> { + let (dictionaries, message) = IpcDataGenerator::default().encode( + rb, + &mut self.dictionaries, + options, + &mut context.borrow_mut(), + )?; + for dictionary in dictionaries { + write_message(self.inner.get_mut(), dictionary, options)?; + } + write_message(self.inner.get_mut(), message, options)?; + Ok(()) + })?; } self.last_batch_start = self.staged; self.staged = self.position(); + if self.index.is_some() + && let (Ok(length), Ok(num_rows)) = ( + u32::try_from(self.staged - offset), + u32::try_from(rb.num_rows()), + ) + { + self.provisional.push(IndexedIpcBatch { + offset, + length, + num_rows, + timestamp: preencoded.map_or_else(|| timestamp_bounds(rb), |p| p.timestamp), + }); + } Ok(()) } @@ -1325,6 +1421,9 @@ impl DiskWriter { self.inner.flush().map_err(StagingError::Arrow)?; self.acknowledged = self.inner.get_ref().get_ref().written; self.staged = self.acknowledged; + if let Some(index) = &self.index { + index.commit(&mut self.provisional); + } #[cfg(test)] { self.flushes += 1; @@ -1425,6 +1524,8 @@ pub struct MemWriter { /// before the segment existed (for instance before `clear`) stay hidden. #[derive(Debug)] struct SegmentDisk { + spilled: bool, + index: Option>, path: PathBuf, start: u64, // The writer's acknowledged length after the last batch cached or skipped. @@ -1437,6 +1538,7 @@ struct SegmentDisk { /// Acknowledged rows of a detached staging file, read from disk by queries. #[derive(Debug, Clone)] struct PendingSource { + index: Option, start: u64, len: u64, // The name before the last re-key: the file is renamed just after its @@ -1524,19 +1626,24 @@ impl MemWriter { /// Caches `rb`, just written to `path` whose staged length is now /// `acknowledged`, as the tail of this segment if the budget allows. /// Otherwise the segment gives its cached batches to `deferred` and - /// serves the file's whole prefix from disk; it caches again once the - /// budget has room, as the tail after that prefix. + /// serves the file from disk for the rest of its lifetime. fn push_disk_backed( &mut self, schema_key: &str, rb: &RecordBatch, - path: &Path, - batch_start: u64, - acknowledged: u64, + writer: &DiskWriter, deferred: &mut DeferredDrop, ) -> Result<(), StagingError> { + let path = writer.path(); + let acknowledged = writer.staged_len(); match self.disk.as_mut() { - Some(disk) if disk.path == path => disk.acknowledged = acknowledged, + Some(disk) if disk.path == path => { + disk.acknowledged = acknowledged; + if disk.spilled { + disk.evicted = acknowledged; + return Ok(()); + } + } _ => { // A segment follows one file; a new file under the same key // starts over. Rows cached for another file must not be served @@ -1544,8 +1651,10 @@ impl MemWriter { // The segment covers its file from this batch on: a segment // created after `clear` must not resurrect cleared rows. self.take_cached(deferred); - let start = batch_start; + let start = writer.last_batch_start(); self.disk = Some(SegmentDisk { + spilled: false, + index: writer.index.clone(), path: path.to_path_buf(), start, acknowledged, @@ -1554,7 +1663,10 @@ impl MemWriter { } } let incoming = rb.get_array_memory_size(); - if self.budget.try_reserve(incoming) { + let segment_limit = self.budget.segment_limit(); + if incoming <= segment_limit.saturating_sub(self.accounted) + && self.budget.try_reserve(incoming) + { self.accounted = self.accounted.saturating_add(incoming); if let Err(err) = self.push(schema_key, rb) { // Disk append already succeeded; fall back to serving this @@ -1566,6 +1678,9 @@ impl MemWriter { "In-memory staging cache update failed after disk append; falling back to disk reads" ); self.evict_to_disk(deferred); + } else if self.accounted > segment_limit || self.budget.is_over() { + // Coalescing or slicing can change the final Arrow charge. + self.evict_to_disk(deferred); } Ok(()) } else { @@ -1580,6 +1695,7 @@ impl MemWriter { let Some(disk) = self.disk.as_mut() else { return 0; }; + disk.spilled = true; disk.evicted = disk.acknowledged; self.take_cached(deferred) } @@ -1739,7 +1855,8 @@ impl MemWriter { Some(previous) => vec![path.as_path(), previous, path.as_path()], None => vec![path.as_path()], }; - let disk = StagingDiskSource::open_first(&candidates, source.start, source.len)?; + let disk = StagingDiskSource::open_first(&candidates, source.start, source.len)? + .with_index(source.index.clone()); capture.disk.push(disk); } } @@ -1757,11 +1874,14 @@ impl MemWriter { if let Some(disk) = self.disk.as_ref().filter(|disk| disk.evicted > disk.start) { // An attached writer's file is never renamed while the writer // lock is held, so its own path is the file. - capture.disk.push(StagingDiskSource::open_first( - &[disk.path.as_path()], - disk.start, - disk.evicted, - )?); + capture.disk.push( + StagingDiskSource::open_first(&[disk.path.as_path()], disk.start, disk.evicted)? + .with_index( + disk.index + .as_ref() + .and_then(|index| index.snapshot(disk.start, disk.evicted)), + ), + ); } let mutable = if self.mutable_buffer.inner.is_empty() { None @@ -1887,7 +2007,7 @@ mod tests { utils::time::TimeRange, }; - use super::{DiskWriter, MemWriter, MutableBuffer, Writer}; + use super::{DiskWriter, MEMORY_BATCH_ROWS, MemWriter, MutableBuffer, Writer}; fn legacy_bytes(schema: &Schema, batches: &[RecordBatch], compressed: bool) -> Vec { let options = arrow_ipc::writer::IpcWriteOptions::default() @@ -1952,15 +2072,12 @@ mod tests { ); let legacy = legacy_bytes(&schema, &batches, true); assert_eq!( - StreamReader::try_new(Cursor::new(legacy.clone()), None) + StreamReader::try_new(Cursor::new(legacy), None) .unwrap() .collect::, _>>() .unwrap(), batches ); - if sizes.iter().all(|n| *n >= 100) { - assert_eq!(bytes, legacy); - } if batches.is_empty() { assert!(get_forward_reader(Cursor::new(&bytes)).is_err()); assert!(get_reverse_reader(Cursor::new(&bytes)).is_err()); @@ -2033,7 +2150,7 @@ mod tests { } #[test] - fn dictionary_staging_retains_legacy_bytes() { + fn dictionary_staging_round_trips() { use arrow_array::{DictionaryArray, types::Int32Type}; let dir = TempDir::new().unwrap(); let path = dir.path().join("dictionary.data.arrows"); @@ -2052,13 +2169,12 @@ mod tests { let schema = batches[0].schema(); let range = TimeRange::granularity_range(Utc::now(), OBJECT_STORE_DATA_GRANULARITY); let mut writer = DiskWriter::try_new(&path, &schema, range).unwrap(); - assert!(writer.small.is_none()); + assert!(writer.index.is_none()); for batch in &batches { writer.write(batch).unwrap(); } drop(writer); let bytes = std::fs::read(path).unwrap(); - assert_eq!(bytes, legacy_bytes(&schema, &batches, true)); assert_eq!( StreamReader::try_new(std::io::Cursor::new(bytes), None) .unwrap() @@ -2184,8 +2300,7 @@ mod tests { let sealed = writer.seal().unwrap_or_else(|(_, e)| panic!("{e}")); let bytes = std::fs::read(&sealed.part).unwrap(); - // Byte-identical to the always-compressed writer, and much smaller than raw. - assert_eq!(bytes, legacy_bytes(&schema, &batches, true)); + // The adaptive writer still compresses these short, large-value batches. assert!(bytes.len() < legacy_bytes(&schema, &batches, false).len() / 4); } @@ -2241,7 +2356,7 @@ mod tests { Field::new("b", DataType::Int32, true), Field::new("a", DataType::Int32, true), ])); - let mut mem = MemWriter::<4096>::default(); + let mut mem = MemWriter::::default(); mem.read_buffer = vec![batch.slice(0, 0), batch.slice(0, 1)]; let mut attached = MemWriter::default(); // Schema clones share Fields even when their Schema Arcs differ. @@ -2346,19 +2461,49 @@ mod tests { fn mutable_buffer_counts_rows_not_batches() { // Prior source: 3,097 pushes of 1,000 rows concatenated 3,097,000 rows. let schema = id_schema(); - let mut mem = MemWriter::<4096>::default(); + let mut mem = MemWriter::::default(); for i in 0..3097 { mem.push("id", &ids_batch(&schema, i * 1000..(i + 1) * 1000)) .unwrap(); } assert_eq!(mem.read_buffer.len(), 756); - assert!(mem.read_buffer.iter().all(|rb| rb.num_rows() == 4096)); - assert_eq!(mem.mutable_buffer.num_rows(), 3_097_000 - 756 * 4096); + assert!( + mem.read_buffer + .iter() + .all(|rb| rb.num_rows() == MEMORY_BATCH_ROWS) + ); + assert_eq!( + mem.mutable_buffer.num_rows(), + 3_097_000 - 756 * MEMORY_BATCH_ROWS + ); let all = mem.recordbatch_cloned(&schema).unwrap(); - assert!(all.iter().all(|rb| rb.num_rows() <= 4096)); + assert!(all.iter().all(|rb| rb.num_rows() <= MEMORY_BATCH_ROWS)); assert_eq!(ids_of(&all), (0..3_097_000).collect::>()); } + #[test] + fn full_utf8_chunk_fits_the_16_kib_offset_allocation() { + let mut mem = MemWriter::::default(); + for rows in [2000, MEMORY_BATCH_ROWS - 2000] { + let batch = RecordBatch::try_from_iter([( + "msg", + Arc::new(StringArray::from_iter_values(std::iter::repeat_n( + "a", rows, + ))) as arrow_array::ArrayRef, + )]) + .unwrap(); + mem.push("msg", &batch).unwrap(); + } + let strings = mem.read_buffer[0] + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + let offsets = strings.offsets().inner().inner(); + assert_eq!(offsets.len(), 16384); + assert_eq!(offsets.capacity(), 16384); + } + #[test] fn mutable_buffer_mixed_sizes_preserve_order() { check_row_accounting::<16>(&[ @@ -2372,7 +2517,9 @@ mod tests { fn mutable_buffer_boundary_shapes_preserve_rows_and_order() { for prefix in [0, 1, 1000, 4095] { for size in [0, 1, 4095, 4096, 4097, 8191, 8192, 8204, 12286] { - check_row_accounting::<4096>(&[prefix, size, 0, 1000, 1000, 4096, 8204, 1]); + check_row_accounting::(&[ + prefix, size, 0, 1000, 1000, 4096, 8204, 1, + ]); } } } @@ -2416,7 +2563,7 @@ mod tests { #[test] fn repeated_8204_primitive_inputs_retain_only_input_allocations() { let schema = Arc::new(Schema::new(vec![Field::new("n", DataType::Int64, false)])); - let mut mem = MemWriter::<4096>::default(); + let mut mem = MemWriter::::default(); let mut input_allocations = HashMap::new(); for push in 0..8 { let start = push * 8204; @@ -2433,13 +2580,13 @@ mod tests { } let captured = mem.recordbatch_cloned(&schema).unwrap(); assert_eq!(allocations(&captured), input_allocations); - // The deliberate cost: one 12-row tail per input, alongside two full + // The deliberate cost: one 14-row tail per input, alongside two full // chunks. The reviewed splitter returned 17 batches for this shape. assert_eq!(captured.len(), 24); for chunks in captured.chunks_exact(3) { assert_eq!( chunks.iter().map(RecordBatch::num_rows).collect::>(), - [4096, 4096, 12] + [4095, 4095, 14] ); } let mut next = 0; @@ -2471,7 +2618,7 @@ mod tests { ), ]); let timestamp = chrono::DateTime::from_timestamp_millis(1_700_000_000_123).unwrap(); - let mut mem = MemWriter::<4096>::default(); + let mut mem = MemWriter::::default(); let mut input_allocations = HashMap::new(); let mut query_schema = None; for push in 0..8 { @@ -2513,7 +2660,7 @@ mod tests { let mut next = 0; for batch in captured { assert!(Arc::ptr_eq(&batch.schema(), &query_schema)); - assert!(batch.num_rows() <= 4096); + assert!(batch.num_rows() <= MEMORY_BATCH_ROWS); let message = batch .column(0) .as_any() @@ -2546,7 +2693,7 @@ mod tests { #[test] fn oversized_pending_snapshot_owns_allocations_until_dropped() { let schema = id_schema(); - let mut mem = MemWriter::<4096>::default(); + let mut mem = MemWriter::::default(); let batch = ids_batch(&schema, 0..8204); // This test guard deliberately keeps one buffer reference so its // strong count can prove that staging and snapshot owners are gone. @@ -2644,11 +2791,11 @@ mod tests { #[test] fn mutable_buffer_row_count_resets_on_clear() { let schema = id_schema(); - let mut mem = MemWriter::<4096>::default(); - mem.push("id", &ids_batch(&schema, 0..4095)).unwrap(); + let mut mem = MemWriter::::default(); + mem.push("id", &ids_batch(&schema, 0..4094)).unwrap(); mem.clear(); assert_eq!(mem.mutable_buffer.num_rows(), 0); - mem.push("id", &ids_batch(&schema, 0..4095)).unwrap(); + mem.push("id", &ids_batch(&schema, 0..4094)).unwrap(); assert!(mem.read_buffer.is_empty()); // Flushing expires ownerless query rows and their count. @@ -2660,19 +2807,19 @@ mod tests { let mem = writer.mem.as_mut().unwrap(); assert!(mem.mutable_buffer.inner.is_empty()); assert_eq!(mem.mutable_buffer.num_rows(), 0); - mem.push("id", &ids_batch(&schema, 0..4095)).unwrap(); + mem.push("id", &ids_batch(&schema, 0..4094)).unwrap(); assert!(mem.read_buffer.is_empty()); - mem.push("id", &ids_batch(&schema, 4095..4096)).unwrap(); + mem.push("id", &ids_batch(&schema, 4094..4095)).unwrap(); assert_eq!(mem.read_buffer.len(), 1); - assert_eq!(mem.read_buffer[0].num_rows(), 4096); + assert_eq!(mem.read_buffer[0].num_rows(), 4095); // A direct clear of the public field cannot leave a stale count. - mem.push("id", &ids_batch(&schema, 4096..8191)).unwrap(); + mem.push("id", &ids_batch(&schema, 4095..8189)).unwrap(); mem.mutable_buffer.inner.clear(); assert_eq!(mem.mutable_buffer.num_rows(), 0); - mem.push("id", &ids_batch(&schema, 8191..12286)).unwrap(); + mem.push("id", &ids_batch(&schema, 8189..12283)).unwrap(); assert_eq!(mem.read_buffer.len(), 1); - assert_eq!(mem.mutable_buffer.num_rows(), 4095); + assert_eq!(mem.mutable_buffer.num_rows(), 4094); } #[test] @@ -2711,7 +2858,12 @@ mod tests { } let segment = &writer.mem.as_ref().unwrap().segments[old]; assert_eq!(segment.read_buffer.len(), 5); - assert!(segment.read_buffer.iter().all(|rb| rb.num_rows() <= 4096)); + assert!( + segment + .read_buffer + .iter() + .all(|rb| rb.num_rows() <= MEMORY_BATCH_ROWS) + ); assert_eq!(rows(&segment.read_buffer), 14000); assert_eq!(segment.mutable_buffer.num_rows(), 0); @@ -2902,7 +3054,7 @@ mod tests { assert_eq!(mem.len(), 2); eprintln!( "memory segment fixed header: {} bytes; filename String header: {} bytes (heap buffers/hash buckets excluded)", - std::mem::size_of::>(), + std::mem::size_of::>(), std::mem::size_of::() ); assert!( @@ -3188,7 +3340,7 @@ mod tests { use chrono::Utc; use temp_dir::TempDir; - use super::{id_schema, ids_batch, ids_of, rows}; + use super::{MEMORY_BATCH_ROWS, id_schema, ids_batch, ids_of, rows}; use crate::{ OBJECT_STORE_DATA_GRANULARITY, parseable::staging::{ @@ -3231,7 +3383,7 @@ mod tests { ids } - fn mem(writer: &Writer) -> &MemWriter<4096> { + fn mem(writer: &Writer) -> &MemWriter { writer.mem.as_ref().unwrap() } @@ -3255,10 +3407,10 @@ mod tests { } #[test] - fn evicted_prefix_and_cached_tail_cover_every_row_once() { + fn spilled_segment_stays_disk_only_until_rollover() { let dir = TempDir::new().unwrap(); let one = ids_batch(&id_schema(), 0..100).get_array_memory_size(); - // Room for two batches; the third evicts, the fourth is the tail. + // Room for two batches; the third spills the segment. let budget = StagingMemoryBudget::new(2 * one + one / 2); let mut writer = writer(&budget); push(&mut writer, &dir, 0..100); @@ -3272,19 +3424,48 @@ mod tests { let acknowledged = writer.disk[FILE].acknowledged_len(); assert_eq!(capture.disk[0].len(), acknowledged); push(&mut writer, &dir, 300..400); - assert!(budget.used() > 0, "caching resumes below the resume mark"); - let capture = writer.capture(&id_schema()).unwrap(); - assert_eq!(capture.disk.len(), 1); - assert_eq!(capture.disk[0].len(), acknowledged); - assert_eq!(ids_of(&capture.memory), (300..400).collect::>()); - assert_eq!(sorted_ids(&writer), (0..400).collect::>()); - // The pressure hook evicts the tail too, and nothing is lost. - assert!(writer.evict_pending_or_segments() > 0); assert_eq!(budget.used(), 0); let capture = writer.capture(&id_schema()).unwrap(); assert!(capture.memory.is_empty()); assert_eq!(capture.disk[0].len(), writer.disk[FILE].acknowledged_len()); assert_eq!(sorted_ids(&writer), (0..400).collect::>()); + let detached = writer.detach_flushable_disk_at(true, Utc::now()); + push(&mut writer, &dir, 400..500); + assert!(budget.used() > 0); + assert_eq!(sorted_ids(&writer), (0..500).collect::>()); + drop(detached); + } + + #[test] + fn segment_limit_leaves_capacity_for_cold_and_memory_only_streams() { + let dir = TempDir::new().unwrap(); + let budget = StagingMemoryBudget::new(4 << 20); + let mut writer = writer(&budget); + let batch = ids_batch(&id_schema(), 0..300_000); + for _ in 0..2 { + writer + .push_disk_and_memory(FILE, "id", &batch, dir.path().join(FILE), current()) + .unwrap(); + } + assert_eq!(budget.used(), 0); + assert_eq!( + writer.capture(&id_schema()).unwrap().disk[0] + .indexed_batches() + .unwrap() + .len(), + 2 + ); + writer + .push_disk_and_memory("cold", "id", &batch, dir.path().join("cold"), current()) + .unwrap(); + assert_eq!(budget.used(), batch.get_array_memory_size()); + + budget.set_limit(0); + let mem = writer.mem.as_mut().unwrap(); + mem.push_for_file("memory-only", "id", &batch).unwrap(); + mem.evict_pending_or_segments(); + assert!(mem.segments["memory-only"].disk.is_none()); + assert_eq!(budget.used(), batch.get_array_memory_size()); } #[test] @@ -3339,11 +3520,18 @@ mod tests { // A capture taken before the move and the unlink still reads. let schema = id_schema(); let before = writer.capture(&schema).unwrap(); + let before_index = before.disk[0].indexed_batches().unwrap(); + assert_eq!(before_index.len(), 10); let processing = dir.path().join("processing_1"); std::fs::create_dir(&processing).unwrap(); let moved = processing.join(sealed.arrow.file_name().unwrap()); mem_mut(&mut writer).rekey_pending(&sealed.arrow, &moved); std::fs::rename(&sealed.arrow, &moved).unwrap(); + let after = writer.capture(&schema).unwrap(); + assert!(Arc::ptr_eq( + before_index, + after.disk[0].indexed_batches().unwrap() + )); assert_eq!(sorted_ids(&writer), (0..500).collect::>()); mem_mut(&mut writer).release_pending(std::slice::from_ref(&moved)); std::fs::remove_file(&moved).unwrap(); @@ -3387,7 +3575,7 @@ mod tests { fn tiny_batches_coalesce_and_accounting_is_exact() { let budget = StagingMemoryBudget::new(usize::MAX); let schema = id_schema(); - let mut mem = MemWriter::<4096>::with_budget(Arc::clone(&budget)); + let mut mem = MemWriter::::with_budget(Arc::clone(&budget)); for id in 0..200 { mem.push_for_file("tiny", "id", &ids_batch(&schema, id..id + 1)) .unwrap(); @@ -3415,8 +3603,8 @@ mod tests { fn oversized_inputs_are_charged_once() { let budget = StagingMemoryBudget::new(usize::MAX); let schema = id_schema(); - let mut mem = MemWriter::<4096>::with_budget(Arc::clone(&budget)); - let batch = ids_batch(&schema, 0..40960); + let mut mem = MemWriter::::with_budget(Arc::clone(&budget)); + let batch = ids_batch(&schema, 0..40950); mem.push("id", &batch).unwrap(); assert_eq!(mem.read_buffer.len(), 10); assert_eq!(budget.used(), batch.get_array_memory_size()); @@ -3459,7 +3647,7 @@ mod tests { assert_eq!(budget.used(), 0); } - fn mem_mut(writer: &mut Writer) -> &mut MemWriter<4096> { + fn mem_mut(writer: &mut Writer) -> &mut MemWriter { writer.mem.as_mut().unwrap() } } @@ -3519,8 +3707,9 @@ mod track_e { prop_assert_eq!(rows, vec![current.clone()]); } let live = writer.capture(&schema).unwrap(); - prop_assert_eq!(live.into_record_batches(&schema).unwrap(), vec![tail, current]); - prop_assert!(budget.used() > 0); + prop_assert!(live.disk[0].indexed_batches().is_none()); + prop_assert_eq!(live.into_record_batches(&schema).unwrap(), vec![current, tail]); + prop_assert_eq!(budget.used(), 0); drop(writer); prop_assert_eq!(budget.used(), 0); } @@ -3713,7 +3902,7 @@ mod staged_group_tests { assert!("snappy".parse::().is_err()); assert_eq!(StagingIpcCompression::default(), StagingIpcCompression::Lz4); // Nothing in the test environment selects another codec, and the - // byte-equality tests against LZ4 rely on that. + // default remains available independently of explicit-codec tests. if std::env::var_os(STAGING_IPC_COMPRESSION_VAR).is_none() { assert_eq!(*STAGING_IPC_COMPRESSION, StagingIpcCompression::Lz4); } @@ -3963,6 +4152,7 @@ mod staged_group_tests { let foreign = PreEncodedBatch { schema: dictionary.schema(), rows: dictionary.num_rows(), + timestamp: TimestampBounds::Unknown, bytes: b"not an IPC message".to_vec(), }; writer @@ -4222,6 +4412,10 @@ mod staged_group_tests { (0, prefix) ); assert_eq!(capture.disk[0].path(), part.as_path()); + let index = capture.disk[0].indexed_batches().unwrap(); + assert_eq!(index.len(), 1); + assert_eq!(index[0].num_rows, 500); + assert_eq!(index[0].offset + u64::from(index[0].length), prefix); assert_eq!(captured(&writer), (0..500).collect::>()); // The next push opens a fresh part and the stream carries on. @@ -4411,7 +4605,9 @@ mod staged_group_tests { drop(deferred); assert_eq!(holders(&first), 1); - // Explicit eviction, as under memory pressure. + // The old segment stays spilled. A new file can cache and then be + // explicitly evicted under pressure. + let detached = writer.detach_flushable_disk_at(true, Utc::now()); budget.set_limit(1 << 30); let third = ids_batch(2000..3000); writer @@ -4432,6 +4628,7 @@ mod staged_group_tests { drop(deferred); assert_eq!(holders(&third), 1); assert_eq!(captured(&writer), (0..3000).collect::>()); + drop(detached); drop(writer); assert_eq!(budget.used(), 0); } @@ -4450,6 +4647,11 @@ mod staged_group_tests { std::thread::sleep(Duration::from_millis(1)); } + let mut oversized = DeferredDrop::default(); + oversized.take(&mut vec![batch.clone()], MAX_DEFERRED_DROP_BYTES + 1); + drop(oversized); + assert_eq!(holders(&batch), 1); + // Below the cutoff, and for callers that free in place, the batches // are gone when the holder is. let mut small = DeferredDrop::default(); @@ -4578,6 +4780,9 @@ mod staged_group_tests { // garbage past `ack_len` on disk to simulate a partial/failed flush. let unacked = ids_batch(10..20); disk.append(&unacked, None).unwrap(); + assert_eq!(disk.provisional.len(), 1); + assert!(disk.index_snapshot(0, disk.staged_len()).is_none()); + assert!(disk.index_snapshot(0, ack_len).is_some()); { use std::io::Write; let mut f = std::fs::OpenOptions::new() From 71713d461512a6b4fd6bc5fa5bb8f592d89e2aed Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Tue, 1 Dec 2026 15:02:00 -0600 Subject: [PATCH 03/17] query: read limited staging scans lazily and bound hidden query memory A `LIMIT` over staging memory reversed every cached batch when the scan was planned: a copy of up to the whole staging cache per query, outside any budget. Several other allocations of the query path were larger than what they hold or not accounted at all. Staging memory scans (stream_schema_provider): - A scan with a limit is now `ReversedStagingMemoryExec`. It keeps the captured batches as they are and reads them newest first as it is polled. It applies the exact time filters itself, takes only the rows the limit still asks for, and copies just those, in reverse order. Rows and schema are those of the eager reversal; the scan now stops at its limit itself instead of leaving that to the limit above it. - Scans without a limit are unchanged. Batch adaptation (utils/arrow/batch_adapter): - The fields a batch lacks are presented by one all-null array per distinct type, shared by all such fields and kept for the next batch of as many rows, instead of one new array per field per batch. Every batch is still validated against the whole table schema. - A column whose type only widens into the table's (nested nullability, list item names) is relabelled around its own buffers. `cast` remains the fallback. Query session (query/mod): - The predicate cache of each Parquet reader defaults to 64 MiB instead of 1 GiB, lowered so that the readers of one query stay within a quarter of the query pool, but not below 8 MiB. `P_PARQUET_PREDICATE_CACHE_SIZE` sets it explicitly. - DataFusion spills into `/.query_spill` instead of the temporary directory of the operating system, which is memory in many containers. The directory is locked by the process using it, which removes what a crashed process left there. Without it, spilling goes where it did. `P_QUERY_SPILL_DIR` names another base directory. Small-file cache (query/small_file_cache): - Admission reserves what the manifests record plus 64 KiB, capped at a maximal body per file, instead of a maximal body for every file, which turned the cache off for scans of more than 256 small files. - A body larger than recorded is reserved for when it is loaded, or not kept, so a view never holds more than it reserved. - Dropping a view returns its reservation exactly once, also when its locks are poisoned. Custom header fields (utils/arrow): - The column repeating a header value is built in buffers of its exact size instead of a value buffer that doubles as it fills. A column too long for 32-bit offsets is an error instead of a panic. Co-Authored-By: Claude Fable 5.2 --- src/query/mod.rs | 444 +++++++++++- src/query/small_file_cache.rs | 378 +++++++++- src/query/stream_schema_provider.rs | 1029 ++++++++++++++++++++++++++- src/utils/arrow/batch_adapter.rs | 445 +++++++++++- src/utils/arrow/mod.rs | 192 ++++- 5 files changed, 2407 insertions(+), 81 deletions(-) diff --git a/src/query/mod.rs b/src/query/mod.rs index 514823f40..1a3a8c40b 100644 --- a/src/query/mod.rs +++ b/src/query/mod.rs @@ -31,7 +31,7 @@ use datafusion::arrow::record_batch::RecordBatch; use datafusion::catalog::SchemaProvider; use datafusion::common::tree_node::{Transformed, TreeNodeRecursion}; use datafusion::error::DataFusionError; -use datafusion::execution::disk_manager::DiskManager; +use datafusion::execution::disk_manager::{DiskManager, DiskManagerMode}; use datafusion::execution::{ RecordBatchStream, SendableRecordBatchStream, SessionState, SessionStateBuilder, }; @@ -54,6 +54,7 @@ use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use std::collections::BTreeSet; use std::ops::Bound; +use std::path::{Path, PathBuf}; use std::pin::Pin; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, RwLock}; @@ -307,6 +308,201 @@ pub(crate) fn resolve_query_memory_pool( } } +/// Environment variable setting how many bytes of decoded filter columns each +/// Parquet reader may cache. +const PARQUET_PREDICATE_CACHE_SIZE_ENV: &str = "P_PARQUET_PREDICATE_CACHE_SIZE"; +/// What a Parquet reader may cache when nothing is configured and the query +/// memory pool is large enough for it. +const DEFAULT_PARQUET_PREDICATE_CACHE_SIZE: usize = 64 * 1024 * 1024; +/// The least the default is lowered to for a small pool or many partitions. +const MIN_PARQUET_PREDICATE_CACHE_SIZE: usize = 8 * 1024 * 1024; + +/// Resolves how many bytes each Parquet reader may hold of the columns it +/// decoded to evaluate pushed-down filters. A reader keeps them until the +/// matching rows are output, so that it does not decode those columns twice. +/// +/// DataFusion does not charge this cache to the query memory pool, and each +/// scan partition has a reader of its own, so up to `target_partitions` of them +/// hold it at once. By default a reader gets 64 MiB, or less where the readers +/// of one query could together hold more than a quarter of the pool, but never +/// less than 8 MiB. A reader whose cache is full decodes the rest of its filter +/// columns again when it outputs them: a smaller cache costs time, never rows. +/// +/// A configured size (`P_PARQUET_PREDICATE_CACHE_SIZE`, in bytes) is used as it +/// is. `0` turns the cache off; a size above the default accepts the memory +/// that takes outside the pool. +pub(crate) fn resolve_parquet_predicate_cache_size( + configured: Option, + query_pool_bytes: usize, + target_partitions: usize, +) -> usize { + if let Some(size) = configured { + return size; + } + let pool_share = query_pool_bytes / target_partitions.max(1).saturating_mul(4); + DEFAULT_PARQUET_PREDICATE_CACHE_SIZE + .min(pool_share) + .max(MIN_PARQUET_PREDICATE_CACHE_SIZE) +} + +/// Reads a size in bytes as `P_PARQUET_PREDICATE_CACHE_SIZE` holds it. `None` +/// when the variable is not set or empty. A value that is not a number of +/// bytes is reported and ignored, rather than failing the first query. +fn parse_parquet_predicate_cache_size(value: Option<&str>) -> Option { + let value = value?.trim(); + if value.is_empty() { + return None; + } + match value.parse() { + Ok(size) => Some(size), + Err(error) => { + tracing::warn!( + %value, + %error, + "Ignoring {PARQUET_PREDICATE_CACHE_SIZE_ENV}: expected a number of bytes" + ); + None + } + } +} + +/// Directory, in the staging directory, that queries spill into. A stream or +/// tenant directory cannot have this name: neither may start with a dot. +const QUERY_SPILL_DIR_NAME: &str = ".query_spill"; +/// Locked by the process that spills into the directory for as long as it runs. +const QUERY_SPILL_OWNER_LOCK: &str = ".owner.lock"; +/// Prefix of the directory a DataFusion disk manager keeps its spill files in. +const DATAFUSION_SPILL_DIR_PREFIX: &str = "datafusion-"; +/// Environment variable naming a directory to keep the query spill directory +/// in, instead of the staging directory. +const QUERY_SPILL_DIR_ENV: &str = "P_QUERY_SPILL_DIR"; + +/// The directory this process spills query state into, with the lock that +/// tells other processes it is in use. +#[derive(Debug)] +struct QuerySpillDir { + path: PathBuf, + // Unlocked by the operating system when the process ends, however it ends. + _owner: std::fs::File, +} + +impl QuerySpillDir { + /// Claims `/.query_spill`, creating it if it does not exist, and + /// removes the spill directories a process that did not exit cleanly left + /// in it. Spill files mean nothing once their query is gone, and they are + /// not small. + /// + /// Fails when the directory cannot be created or locked, or belongs to + /// another running process. Only the owner removes anything. + fn claim(base: &Path) -> std::io::Result { + let path = base.join(QUERY_SPILL_DIR_NAME); + std::fs::create_dir_all(&path)?; + let owner = std::fs::OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .open(path.join(QUERY_SPILL_OWNER_LOCK))?; + match owner.try_lock() { + Ok(()) => {} + Err(std::fs::TryLockError::WouldBlock) => { + return Err(std::io::Error::new( + std::io::ErrorKind::WouldBlock, + "another running process spills into this directory", + )); + } + Err(std::fs::TryLockError::Error(error)) => return Err(error), + } + remove_abandoned_spill_dirs(&path); + Ok(Self { + path, + _owner: owner, + }) + } +} + +/// Removes the directories DataFusion disk managers created in `spill_dir`. +/// Called by the owner of `spill_dir` before it creates any of its own, so +/// that whatever is there was abandoned. Nothing else is touched. +fn remove_abandoned_spill_dirs(spill_dir: &Path) { + let entries = match std::fs::read_dir(spill_dir) { + Ok(entries) => entries, + Err(error) => { + tracing::warn!(path = %spill_dir.display(), %error, "Cannot list the query spill directory"); + return; + } + }; + for entry in entries.flatten() { + // `file_type` does not follow links: a link to a directory is kept. + let abandoned = entry + .file_name() + .to_string_lossy() + .starts_with(DATAFUSION_SPILL_DIR_PREFIX) + && entry.file_type().is_ok_and(|file_type| file_type.is_dir()); + if !abandoned { + continue; + } + let path = entry.path(); + match std::fs::remove_dir_all(&path) { + Ok(()) => { + tracing::info!(path = %path.display(), "Removed abandoned query spill files") + } + Err(error) => { + tracing::warn!(path = %path.display(), %error, "Cannot remove abandoned query spill files") + } + } + } +} + +static QUERY_SPILL_DIR: OnceCell> = OnceCell::new(); + +/// Where the queries of this process spill, claimed on first use: a directory +/// of its own in the staging directory (or in `P_QUERY_SPILL_DIR`). `None` +/// when that directory cannot be used, for instance because the staging +/// directory cannot be written or another process holds it. +fn query_spill_dir() -> Option<&'static Path> { + QUERY_SPILL_DIR + .get_or_init(|| { + let base = std::env::var_os(QUERY_SPILL_DIR_ENV) + .filter(|dir| !dir.is_empty()) + .map(PathBuf::from) + .unwrap_or_else(|| PARSEABLE.options.local_staging_path.clone()); + match QuerySpillDir::claim(&base) { + Ok(spill_dir) => Some(spill_dir), + Err(error) => { + tracing::warn!( + path = %base.display(), + %error, + "Cannot use the query spill directory; queries spill into the temporary directory of the operating system" + ); + None + } + } + }) + .as_ref() + .map(|spill_dir| spill_dir.path.as_path()) +} + +/// A disk manager whose spill files are created in `spill_dir`. `None` when +/// there is no such directory or it cannot be used: the caller then leaves +/// spill files to the temporary directory of the operating system. +fn query_disk_manager(spill_dir: Option<&Path>) -> Option> { + let spill_dir = spill_dir?; + let builder = DiskManager::builder() + .with_mode(DiskManagerMode::Directories(vec![spill_dir.to_path_buf()])); + match builder.build() { + Ok(disk_manager) => Some(Arc::new(disk_manager)), + Err(error) => { + tracing::warn!( + path = %spill_dir.display(), + %error, + "Cannot spill queries into the query spill directory; they spill into the temporary directory of the operating system" + ); + None + } + } +} + /// This function executes a query on the dedicated runtime, ensuring that the query is not isolated to a single thread/CPU /// at a time and has access to the entire thread pool, enabling better concurrent processing, and thus quicker results. pub async fn execute(query: Query, is_streaming: bool, tenant_id: &Option) -> QueryResult { @@ -401,16 +597,29 @@ impl Query { } pub fn create_session_state(storage: Arc) -> SessionState { - let runtime_config = storage + let mut runtime_config = storage .get_datafusion_runtime() - .with_disk_manager_builder(DiskManager::builder()) .with_metadata_cache_limit(PARSEABLE.options.parquet_metadata_cache_size); + // Spill next to staging, which is on a disk. The temporary directory + // of the operating system is often memory (a `tmpfs` in containers), + // where spilling a query that ran out of memory frees none. + match query_disk_manager(query_spill_dir()) { + Some(disk_manager) => { + runtime_config.disk_manager_builder = None; + runtime_config.disk_manager = Some(disk_manager); + } + None => { + runtime_config = runtime_config.with_disk_manager_builder(DiskManager::builder()); + } + } let (pool_size, fraction) = resolve_query_memory_pool( PARSEABLE.options.query_memory_pool_size, PARSEABLE.options.mode, crate::handlers::http::resource_check::effective_memory_limit_bytes(), ); + // As `with_memory_limit` sizes the pool. + let query_pool_bytes = (pool_size as f64 * fraction) as usize; let runtime_config = runtime_config.with_memory_limit(pool_size, fraction); let runtime = Arc::new(runtime_config.build().unwrap()); @@ -466,7 +675,15 @@ impl Query { .options_mut() .execution .parquet - .max_predicate_cache_size = Some(1024 * 1024 * 1024); + .max_predicate_cache_size = Some(resolve_parquet_predicate_cache_size( + parse_parquet_predicate_cache_size( + std::env::var(PARQUET_PREDICATE_CACHE_SIZE_ENV) + .ok() + .as_deref(), + ), + query_pool_bytes, + PARSEABLE.options.target_partitions as usize, + )); //adding this config as it improves query performance as explained here - // https://github.com/apache/datafusion/pull/13101 @@ -2519,6 +2736,225 @@ mod memory_pool_tests { } } +#[cfg(test)] +mod predicate_cache_tests { + use super::{ + DEFAULT_PARQUET_PREDICATE_CACHE_SIZE, MIN_PARQUET_PREDICATE_CACHE_SIZE, + parse_parquet_predicate_cache_size, resolve_parquet_predicate_cache_size, + }; + + const MIB: usize = 1024 * 1024; + const GIB: usize = 1024 * MIB; + + #[test] + fn default_is_64_mib_and_all_readers_stay_within_a_quarter_of_the_pool() { + assert_eq!(DEFAULT_PARQUET_PREDICATE_CACHE_SIZE, 64 * MIB); + assert_eq!(MIN_PARQUET_PREDICATE_CACHE_SIZE, 8 * MIB); + + // A pool with room for it: the default, however large the pool. + for (pool, partitions) in [(64 * GIB, 32), (8 * GIB, 16), (4 * GIB, 16), (GIB, 1)] { + assert_eq!( + resolve_parquet_predicate_cache_size(None, pool, partitions), + 64 * MIB, + "{pool} / {partitions}" + ); + } + // Where the readers of one query would together exceed a quarter of + // the pool, each gets its share of that quarter. + assert_eq!( + resolve_parquet_predicate_cache_size(None, 4 * GIB, 32), + 32 * MIB + ); + assert_eq!( + resolve_parquet_predicate_cache_size(None, 2 * GIB, 16), + 32 * MIB + ); + for (pool, partitions) in [(4 * GIB, 32), (2 * GIB, 16), (8 * GIB, 64), (3 * GIB, 24)] { + let size = resolve_parquet_predicate_cache_size(None, pool, partitions); + assert!(size >= MIN_PARQUET_PREDICATE_CACHE_SIZE); + assert!(size * partitions <= pool / 4, "{pool} / {partitions}"); + } + // But a reader is never left with less than 8 MiB. + for (pool, partitions) in [(GIB, 64), (512 * MIB, 32), (0, 8), (GIB, usize::MAX)] { + assert_eq!( + resolve_parquet_predicate_cache_size(None, pool, partitions), + 8 * MIB, + "{pool} / {partitions}" + ); + } + // No partition count divides by zero. + assert_eq!( + resolve_parquet_predicate_cache_size(None, 64 * GIB, 0), + 64 * MIB + ); + } + + #[test] + fn configured_size_is_used_as_it_is() { + // The former fixed size, the cache turned off, and a size below the + // least the default would be lowered to. + for configured in [GIB, 0, MIB, 64 * MIB] { + for (pool, partitions) in [(64 * GIB, 32), (512 * MIB, 64)] { + assert_eq!( + resolve_parquet_predicate_cache_size(Some(configured), pool, partitions), + configured + ); + } + } + } + + #[test] + fn size_is_read_as_a_number_of_bytes() { + assert_eq!(parse_parquet_predicate_cache_size(None), None); + assert_eq!(parse_parquet_predicate_cache_size(Some("")), None); + assert_eq!(parse_parquet_predicate_cache_size(Some(" ")), None); + assert_eq!( + parse_parquet_predicate_cache_size(Some("134217728")), + Some(128 * MIB) + ); + assert_eq!(parse_parquet_predicate_cache_size(Some(" 0\n")), Some(0)); + // Not a number of bytes: the default applies. + for invalid in ["64MiB", "-1", "1e6", "0x10", "many"] { + assert_eq!( + parse_parquet_predicate_cache_size(Some(invalid)), + None, + "{invalid}" + ); + } + } +} + +#[cfg(test)] +mod query_spill_tests { + use std::{fs, path::Path}; + + use super::{ + DATAFUSION_SPILL_DIR_PREFIX, QUERY_SPILL_DIR_NAME, QUERY_SPILL_OWNER_LOCK, QuerySpillDir, + query_disk_manager, + }; + + fn names(dir: &Path) -> Vec { + let mut names = fs::read_dir(dir) + .unwrap() + .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()) + .collect::>(); + names.sort(); + names + } + + #[test] + fn spill_files_are_created_in_the_claimed_directory() { + let staging = tempfile::tempdir().unwrap(); + let claimed = QuerySpillDir::claim(staging.path()).unwrap(); + assert_eq!(claimed.path, staging.path().join(QUERY_SPILL_DIR_NAME)); + // A name no stream or tenant directory in staging can have. + assert!(QUERY_SPILL_DIR_NAME.starts_with('.')); + assert_eq!(names(staging.path()), [QUERY_SPILL_DIR_NAME]); + + let disk_manager = query_disk_manager(Some(claimed.path.as_path())).unwrap(); + assert!(disk_manager.tmp_files_enabled()); + let temp_dirs = disk_manager.temp_dir_paths(); + assert_eq!(temp_dirs.len(), 1); + assert_eq!(temp_dirs[0].parent(), Some(claimed.path.as_path())); + let spill = disk_manager.create_tmp_file("a test").unwrap(); + let spill_path = spill.path().expect("a local spill file").to_path_buf(); + assert!(spill_path.starts_with(&temp_dirs[0]), "{spill_path:?}"); + assert!(spill_path.exists()); + + // The files go with the file, the directory with the disk manager. + drop(spill); + assert!(!spill_path.exists()); + drop(disk_manager); + assert_eq!(names(&claimed.path), [QUERY_SPILL_OWNER_LOCK]); + } + + #[test] + fn claim_removes_abandoned_spill_directories_and_nothing_else() { + let staging = tempfile::tempdir().unwrap(); + let spill_dir = staging.path().join(QUERY_SPILL_DIR_NAME); + let abandoned = spill_dir.join(format!("{DATAFUSION_SPILL_DIR_PREFIX}Ab3xYz")); + fs::create_dir_all(abandoned.join("nested")).unwrap(); + fs::write(abandoned.join(".tmpQ1w2E3"), [0u8; 4096]).unwrap(); + fs::write(abandoned.join("nested/.tmpR4t5Y6"), b"spilled").unwrap(); + // Not the name of a spill directory, or not a directory. + fs::create_dir(spill_dir.join("keep")).unwrap(); + fs::write(spill_dir.join("keep/file"), b"kept").unwrap(); + fs::write( + spill_dir.join(format!("{DATAFUSION_SPILL_DIR_PREFIX}file")), + b"kept", + ) + .unwrap(); + // Neither is anything beside the spill directory. + let stream = staging.path().join("stream"); + fs::create_dir(&stream).unwrap(); + fs::write(stream.join("minute.data.arrows"), b"staged").unwrap(); + fs::create_dir( + staging + .path() + .join(format!("{DATAFUSION_SPILL_DIR_PREFIX}stream")), + ) + .unwrap(); + + let claimed = QuerySpillDir::claim(staging.path()).unwrap(); + assert_eq!( + names(&spill_dir), + [ + QUERY_SPILL_OWNER_LOCK.to_owned(), + format!("{DATAFUSION_SPILL_DIR_PREFIX}file"), + "keep".to_owned(), + ] + ); + assert_eq!(fs::read(spill_dir.join("keep/file")).unwrap(), b"kept"); + assert_eq!( + names(staging.path()), + [ + QUERY_SPILL_DIR_NAME.to_owned(), + format!("{DATAFUSION_SPILL_DIR_PREFIX}stream"), + "stream".to_owned(), + ] + ); + assert_eq!( + fs::read(stream.join("minute.data.arrows")).unwrap(), + b"staged" + ); + drop(claimed); + } + + #[test] + fn directory_of_a_running_owner_is_neither_claimed_nor_cleaned() { + let staging = tempfile::tempdir().unwrap(); + let owner = QuerySpillDir::claim(staging.path()).unwrap(); + let disk_manager = query_disk_manager(Some(owner.path.as_path())).unwrap(); + let in_use = disk_manager.temp_dir_paths().remove(0); + fs::write(in_use.join(".tmpInUse"), b"spilling").unwrap(); + + // The lock is held through another handle, as another process holds it. + let error = QuerySpillDir::claim(staging.path()).unwrap_err(); + assert_eq!(error.kind(), std::io::ErrorKind::WouldBlock); + assert_eq!(fs::read(in_use.join(".tmpInUse")).unwrap(), b"spilling"); + + // Once the owner is gone, the next process claims and cleans it. + std::mem::forget(disk_manager); + drop(owner); + let next = QuerySpillDir::claim(staging.path()).unwrap(); + assert!(!in_use.exists()); + assert_eq!(names(&next.path), [QUERY_SPILL_OWNER_LOCK]); + } + + #[test] + fn unusable_directory_leaves_spilling_to_the_default() { + assert!(query_disk_manager(None).is_none()); + + let staging = tempfile::tempdir().unwrap(); + let file = staging.path().join("not-a-directory"); + fs::write(&file, b"").unwrap(); + // Neither can be created below a file. + assert!(QuerySpillDir::claim(&file).is_err()); + let below = file.join("spill"); + assert!(query_disk_manager(Some(below.as_path())).is_none()); + } +} + mod small_file_cache; #[cfg(test)] diff --git a/src/query/small_file_cache.rs b/src/query/small_file_cache.rs index ffa9e0464..6f37599d0 100644 --- a/src/query/small_file_cache.rs +++ b/src/query/small_file_cache.rs @@ -38,7 +38,7 @@ use std::{ collections::HashMap, ops::Range, sync::{ - Arc, LazyLock, Mutex, + Arc, LazyLock, Mutex, PoisonError, atomic::{AtomicUsize, Ordering}, }, }; @@ -257,52 +257,135 @@ fn non_partial(error: &object_store::Error) -> bool { // must see the same validation as its metadata reader. Dropping the request's // plans releases these references; subsequent requests get a fresh view. type Loaded = std::result::Result<(u64, Option), Arc>; -#[derive(Debug, Default)] +#[derive(Debug)] pub(super) struct RequestView { files: Mutex>>>, admission: Mutex, trust_immutable: bool, + capacity: &'static ViewCapacity, } -// Reserve the maximum possible small body, rather than trusting manifest sizes. -// Reservations also cover bodies held by readers after their plans are dropped: -// every reader owns the view. No network operation waits for capacity. +// A view reserves what it may hold before it loads anything: the sizes the +// manifests record for the bodies it is admitted for, plus some slack, and +// never more than those bodies can be. A manifest can understate a body, so +// when the bodies loaded outgrow the reservation the difference is reserved +// as well, or the body is not kept (`RequestView::retain`). The reservation +// is therefore always at least what the view holds, without charging a tiny +// file as a maximal one. Reservations also cover bodies held by readers after +// their plans are dropped: every reader owns the view. No network operation +// waits for capacity. const VIEW_BYTES_LIMIT: usize = 64 * 1024 * 1024; -static VIEW_BYTES: AtomicUsize = AtomicUsize::new(0); +/// Reserved with each admission on top of the sizes its manifests record. +const RESERVATION_SLACK: usize = 64 * 1024; +static VIEW_CAPACITY: ViewCapacity = ViewCapacity::new(VIEW_BYTES_LIMIT); + +/// Bytes of small bodies the request views of this process may hold at once. +#[derive(Debug)] +struct ViewCapacity { + used: AtomicUsize, + limit: usize, +} +impl ViewCapacity { + const fn new(limit: usize) -> Self { + Self { + used: AtomicUsize::new(0), + limit, + } + } + + /// Takes `bytes` if they fit under the limit, and nothing otherwise. + fn try_reserve(&self, bytes: usize) -> bool { + self.used + .fetch_update(Ordering::AcqRel, Ordering::Acquire, |used| { + used.checked_add(bytes).filter(|total| *total <= self.limit) + }) + .is_ok() + } + + fn release(&self, bytes: usize) { + self.used.fetch_sub(bytes, Ordering::AcqRel); + } +} + +/// Gives a view's reservation back when dropped, also while unwinding. +struct Reserved(&'static ViewCapacity, usize); +impl Drop for Reserved { + fn drop(&mut self) { + self.0.release(self.1); + } +} + +/// Bytes to reserve for `files` bodies not admitted before, whose manifests +/// record `predicted` bytes in total. +fn reservation(files: usize, predicted: u128) -> usize { + let largest = files.saturating_mul(MAX_FILE as usize); + let predicted = usize::try_from(predicted) + .unwrap_or(usize::MAX) + .saturating_add(RESERVATION_SLACK); + largest.min(predicted) +} + #[derive(Debug, Default)] struct Admission { predicted: u128, reserved: usize, + // Bytes of the admitted bodies the view holds; at most `reserved`. + held: usize, files: HashMap, } +impl Admission { + /// Counts a loaded body of `bytes` bytes as held, calling `reserve` for + /// what the bodies held then exceed the reservation by. Returns whether + /// the body may be held: `false`, with nothing changed, when `reserve` + /// refuses. + fn hold(&mut self, bytes: usize, reserve: impl FnOnce(usize) -> bool) -> bool { + let held = self.held.saturating_add(bytes); + let missing = held.saturating_sub(self.reserved); + if missing > 0 { + if !reserve(missing) { + return false; + } + self.reserved += missing; + } + self.held = held; + true + } +} +impl Default for RequestView { + fn default() -> Self { + Self::new(false) + } +} impl RequestView { pub(super) fn new(trust_immutable: bool) -> Self { + Self::with_capacity(trust_immutable, &VIEW_CAPACITY) + } + + fn with_capacity(trust_immutable: bool, capacity: &'static ViewCapacity) -> Self { Self { files: Mutex::default(), admission: Mutex::default(), trust_immutable, + capacity, } } fn admit(&self, files: HashMap, budget: usize) -> bool { - let mut admission = self.admission.lock().unwrap(); + let mut admission = self + .admission + .lock() + .unwrap_or_else(PoisonError::into_inner); let new: Vec<_> = files .into_iter() .filter(|(key, _)| !admission.files.contains_key(key)) .collect(); - let predicted = - admission.predicted + new.iter().map(|(_, size)| *size as u128).sum::(); + let new_predicted = new.iter().map(|(_, size)| *size as u128).sum::(); + let predicted = admission.predicted + new_predicted; if predicted > budget as u128 || admission.files.len() + new.len() > MAX_ENTRIES { return false; } - let reserve = new.len() * MAX_FILE as usize; - if VIEW_BYTES - .fetch_update(Ordering::AcqRel, Ordering::Acquire, |used| { - used.checked_add(reserve) - .filter(|total| *total <= VIEW_BYTES_LIMIT) - }) - .is_err() - { + let reserve = reservation(new.len(), new_predicted); + if !self.capacity.try_reserve(reserve) { return false; } admission.predicted = predicted; @@ -310,12 +393,40 @@ impl RequestView { admission.files.extend(new); true } + + /// Whether the loaded body of `key`, of `bytes` bytes, may stay in this + /// view until the request ends. + /// + /// The body of an admitted file counts against the view's reservation. + /// Should the bodies outgrow what their manifests promised, the rest is + /// reserved here; a body there is no room for is not kept, and its reader + /// reads the object itself, as it does one that is too large to hold. + fn retain(&self, key: &Key, bytes: usize) -> bool { + let mut admission = self + .admission + .lock() + .unwrap_or_else(PoisonError::into_inner); + // Readers exist only for the files of an admitted scan. A body loaded + // without one (as tests do) was never promised any capacity. + if !admission.files.contains_key(key) { + return true; + } + admission.hold(bytes, |missing| self.capacity.try_reserve(missing)) + } } impl Drop for RequestView { fn drop(&mut self) { - // Drop bodies before making their reserved capacity available again. - self.files.get_mut().unwrap().clear(); - VIEW_BYTES.fetch_sub(self.admission.get_mut().unwrap().reserved, Ordering::AcqRel); + // A poisoned lock only records that a holder panicked. The reservation + // behind it is still returned, exactly once, and only after the bodies + // it covers are dropped: also if dropping them should unwind. + let admission = self + .admission + .get_mut() + .unwrap_or_else(PoisonError::into_inner); + let _reserved = Reserved(self.capacity, std::mem::take(&mut admission.reserved)); + drop(std::mem::take( + self.files.get_mut().unwrap_or_else(PoisonError::into_inner), + )); } } @@ -395,11 +506,19 @@ async fn load_planned( planned_size: u64, ) -> object_store::Result<(u64, Option)> { let key = (scope, Path::from(format!("{namespace}{}", path.as_ref()))); - let cell = view.files.lock().unwrap().entry(key).or_default().clone(); + let cell = view + .files + .lock() + .unwrap() + .entry(key.clone()) + .or_default() + .clone(); let trusted_size = view.trust_immutable.then_some(planned_size); cell.get_or_init(|| async { load_trusting(&CACHE, scope, store, path, namespace, budget, trusted_size) .await + // The cell keeps the body until the request ends. + .map(|(size, bytes)| (size, bytes.filter(|bytes| view.retain(&key, bytes.len())))) .map_err(Arc::new) }) .await @@ -1003,9 +1122,20 @@ mod tests { } } + /// A capacity of its own for one test: the views of other tests running + /// in this process neither see its reservations nor add to them. + fn capacity(limit: usize) -> &'static ViewCapacity { + Box::leak(Box::new(ViewCapacity::new(limit))) + } + + fn used(capacity: &ViewCapacity) -> usize { + capacity.used.load(Ordering::Acquire) + } + #[test] fn cumulative_admission_and_process_bound() { - let view = RequestView::default(); + let capacity = capacity(VIEW_BYTES_LIMIT); + let view = RequestView::with_capacity(false, capacity); let files = |name: &str, size| [((717, Path::from(name)), size)].into(); assert!(view.admit(files("a", 10), 15)); assert!( @@ -1016,14 +1146,210 @@ mod tests { !view.admit(files("b", 10), 15), "UNION scans share a request budget" ); - assert_eq!(view.admission.lock().unwrap().reserved, MAX_FILE as usize); - let too_many = (0..257) - .map(|i| ((718, Path::from(i.to_string())), 1)) + // What the manifest records and the slack, not a maximal body. + assert_eq!( + view.admission.lock().unwrap().reserved, + 10 + RESERVATION_SLACK + ); + assert_eq!(used(capacity), 10 + RESERVATION_SLACK); + + // Bodies the process has no room for bypass the cache at once. + let too_large = (0..300) + .map(|i| ((718, Path::from(i.to_string())), 250 * 1024)) .collect(); + let other = RequestView::with_capacity(false, capacity); assert!( - !RequestView::default().admit(too_many, MAX_BYTES), + !other.admit(too_large, usize::MAX), "process capacity bypasses without waiting" ); + assert_eq!(other.admission.lock().unwrap().reserved, 0); + assert_eq!(used(capacity), 10 + RESERVATION_SLACK); + drop(other); + drop(view); + assert_eq!(used(capacity), 0); + } + + #[test] + fn reservation_is_the_predicted_size_capped_at_maximal_bodies() { + let max = MAX_FILE as usize; + assert_eq!(reservation(0, 0), 0); + assert_eq!(reservation(1, 10), 10 + RESERVATION_SLACK); + assert_eq!( + reservation(300, 300 * 20 * 1024), + 300 * 20 * 1024 + RESERVATION_SLACK + ); + // Never more than the bodies can be, whatever the manifests record. + assert_eq!(reservation(1, MAX_FILE as u128), max); + assert_eq!(reservation(2, 2 * MAX_FILE as u128 - 1), 2 * max); + assert_eq!(reservation(1, u128::MAX), max); + assert_eq!(reservation(usize::MAX, 5), 5 + RESERVATION_SLACK); + } + + /// A query over many tiny files keeps its cache. 300 files of 20 KiB + /// reserve what they hold; a maximal body for each is more than the + /// process allows, which turned the cache off for the whole scan. + #[test] + fn many_tiny_files_reserve_their_predicted_size() { + const FILES: usize = 300; + const SIZE: usize = 20 * 1024; + const PREDICTED: usize = FILES * SIZE; + const { assert!(FILES * MAX_FILE as usize > VIEW_BYTES_LIMIT) }; + let files = |scope: usize| -> HashMap { + (0..FILES) + .map(|i| { + ( + (scope, Path::from(format!("tiny/{i}.parquet"))), + SIZE as u64, + ) + }) + .collect() + }; + let capacity = capacity(VIEW_BYTES_LIMIT); + let view = RequestView::with_capacity(false, capacity); + assert!(view.admit(files(719), MAX_BYTES)); + assert_eq!( + view.admission.lock().unwrap().reserved, + PREDICTED + RESERVATION_SLACK + ); + assert_eq!(used(capacity), PREDICTED + RESERVATION_SLACK); + + // Another scan of the same files in the request reserves nothing. + assert!(view.admit(files(719), MAX_BYTES)); + assert_eq!(used(capacity), PREDICTED + RESERVATION_SLACK); + + // The bodies are then held within that reservation. + for key in files(719).keys() { + assert!(view.retain(key, SIZE)); + } + { + let admission = view.admission.lock().unwrap(); + assert_eq!(admission.held, PREDICTED); + assert_eq!(admission.reserved, PREDICTED + RESERVATION_SLACK); + } + assert_eq!(used(capacity), PREDICTED + RESERVATION_SLACK); + + // Ten such requests at once fit the process, and each returns what + // it reserved. + let concurrent = (0..9) + .map(|request| { + let view = RequestView::with_capacity(false, capacity); + assert!(view.admit(files(1000 + request), MAX_BYTES)); + view + }) + .collect::>(); + assert_eq!(used(capacity), 10 * (PREDICTED + RESERVATION_SLACK)); + drop(concurrent); + assert_eq!(used(capacity), PREDICTED + RESERVATION_SLACK); + drop(view); + assert_eq!(used(capacity), 0); + } + + /// A manifest may understate a body. The view then reserves the rest, or + /// does not keep the body when the process has no room for it: what a + /// view holds never exceeds what it reserved. + #[test] + fn bodies_larger_than_predicted_are_reserved_or_not_kept() { + const MAX: usize = MAX_FILE as usize; + let capacity = capacity(2 * MAX); + let view = RequestView::with_capacity(false, capacity); + let key = |name: &str| (720, Path::from(name)); + assert!(view.admit( + [(key("a"), 10), (key("b"), 10), (key("c"), 10)].into(), + MAX_BYTES + )); + let state = || { + let admission = view.admission.lock().unwrap(); + (admission.held, admission.reserved, used(capacity)) + }; + let reserved = 30 + RESERVATION_SLACK; + assert_eq!(state(), (0, reserved, reserved)); + + // A body the reservation covers, its slack included. + assert!(view.retain(&key("a"), RESERVATION_SLACK)); + assert_eq!(state(), (RESERVATION_SLACK, reserved, reserved)); + + // One that outgrows it reserves what is missing. + assert!(view.retain(&key("b"), MAX)); + let held = RESERVATION_SLACK + MAX; + assert_eq!(state(), (held, held, held)); + + // One the process has no room for is not kept, and changes nothing. + assert!(!view.retain(&key("c"), MAX)); + assert_eq!(state(), (held, held, held)); + + // A body loaded for no admitted file was never promised capacity. + assert!(view.retain(&key("unplanned"), MAX)); + assert_eq!(state(), (held, held, held)); + + drop(view); + assert_eq!(used(capacity), 0); + } + + #[tokio::test] + async fn body_without_capacity_is_read_uncached_by_every_reader() { + let store: Arc = Arc::new(InMemory::new()); + let scope = 99883; + let path = Path::from("grown/file.parquet"); + let body = vec![7u8; 100 * 1024]; + store + .put(&path, Bytes::from(body.clone()).into()) + .await + .unwrap(); + let planned = || [((scope, path.clone()), 10)].into(); + + // Room for what the manifest records and the slack, not for the body. + let tight = RequestView::with_capacity(false, capacity(10 + RESERVATION_SLACK)); + assert!(tight.admit(planned(), MAX_BYTES)); + for _ in 0..2 { + assert_eq!( + load_for_scan(&tight, scope, &store, &path, "", MAX_BYTES) + .await + .unwrap(), + (body.len() as u64, None) + ); + } + assert_eq!(tight.admission.lock().unwrap().held, 0); + + // With room, the same body is kept and accounted. + let roomy = RequestView::with_capacity(false, capacity(VIEW_BYTES_LIMIT)); + assert!(roomy.admit(planned(), MAX_BYTES)); + let (size, bytes) = load_for_scan(&roomy, scope, &store, &path, "", MAX_BYTES) + .await + .unwrap(); + assert_eq!(size, body.len() as u64); + assert_eq!(bytes.unwrap(), body); + let admission = roomy.admission.lock().unwrap(); + assert_eq!(admission.held, body.len()); + assert_eq!(admission.reserved, body.len()); + } + + /// The reservation is returned when the view is dropped, also after a + /// panic poisoned its locks, and the view stays usable until then. + #[test] + fn poisoned_view_still_admits_and_returns_its_reservation() { + let capacity = capacity(VIEW_BYTES_LIMIT); + let view = Arc::new(RequestView::with_capacity(false, capacity)); + let files = |name: &str| [((721, Path::from(name)), 10)].into(); + assert!(view.admit(files("a"), MAX_BYTES)); + assert_eq!(used(capacity), 10 + RESERVATION_SLACK); + + let poisoner = view.clone(); + let panicked = std::thread::spawn(move || { + let _files = poisoner.files.lock().unwrap(); + let _admission = poisoner.admission.lock().unwrap(); + panic!("poison the locks of the view"); + }) + .join(); + assert!(panicked.is_err()); + assert!(view.files.is_poisoned()); + assert!(view.admission.is_poisoned()); + + assert!(view.admit(files("b"), MAX_BYTES)); + assert!(view.retain(&(721, Path::from("b")), 10)); + assert_eq!(used(capacity), 2 * (10 + RESERVATION_SLACK)); + + drop(Arc::into_inner(view).expect("the poisoning thread dropped its view")); + assert_eq!(used(capacity), 0); } #[test] diff --git a/src/query/stream_schema_provider.rs b/src/query/stream_schema_provider.rs index 31cd912ac..1f78f36af 100644 --- a/src/query/stream_schema_provider.rs +++ b/src/query/stream_schema_provider.rs @@ -2726,36 +2726,36 @@ async fn staging_execution_plans( } = staged; if !records.is_empty() { - // Keep newest-first reversed traversal within one partition when the - // scan is asked to stop early. Without a limit, keep batches in - // zero-copy order across parallel partitions; any SQL ordering is - // enforced by DataFusion. - let reverse_rows = limit.is_some(); - let target_partitions = if reverse_rows { - 1 + let arrow_exec = if limit.is_some() { + // A scan asked to stop early reads the newest rows first, from one + // partition, and copies only the rows it emits. + reversed_staging_memory_plan( + records, + schema.clone(), + projection, + filters, + limit, + state, + )? } else { - state + // Without a limit, keep batches in zero-copy order across parallel + // partitions; any SQL ordering is enforced by DataFusion. + let target_partitions = state .config_options() .execution .target_partitions - .min(num_cpus::get()) + .min(num_cpus::get()); + let (mem_table, mem_projection) = projected_staging_mem_table( + records, + schema.clone(), + projection, + filters, + target_partitions, + false, + )?; + scan_enforcing_exact_filters(&mem_table, state, mem_projection.as_ref(), filters, limit) + .await? }; - let (mem_table, mem_projection) = projected_staging_mem_table( - records, - schema.clone(), - projection, - filters, - target_partitions, - reverse_rows, - )?; - let arrow_exec = scan_enforcing_exact_filters( - &mem_table, - state, - mem_projection.as_ref(), - filters, - limit, - ) - .await?; execution_plans.push(arrow_exec); } @@ -3057,6 +3057,391 @@ fn partitioned_mem_table( MemTable::try_new(schema, partitions) } +/// The scan of staging memory for a query with a `LIMIT`: the rows in the +/// order `partitioned_reversed_mem_table` gives them, newest first, but +/// without reversing anything to plan it (see `ReversedStagingMemoryExec`). +/// +/// Enforces the filters `StandardTableProvider` reports as `Exact`, as +/// `scan_enforcing_exact_filters` does for the other staging scans, and applies +/// `limit` to the rows that pass them. +fn reversed_staging_memory_plan( + mut records: Vec, + schema: SchemaRef, + projection: Option<&Vec>, + filters: &[Expr], + limit: Option, + state: &dyn Session, +) -> DataFusionResult> { + let needed_proj = needed_column_projection(&schema, projection, filters)?; + if let Some(needed) = &needed_proj.needed_indices { + // Arrow projects by cloning column references. + for batch in &mut records { + *batch = batch.project(needed)?; + } + } + let scan_schema = needed_proj.schema; + let predicate = conjunction(exact_source_filters(filters)) + .map(|predicate| { + create_physical_expr( + &predicate, + &scan_schema.clone().to_dfschema()?, + state.execution_props(), + &PhysicalPlanningContext::default(), + ) + }) + .transpose()?; + Ok(Arc::new(ReversedStagingMemoryExec::try_new( + records, + &scan_schema, + predicate, + needed_proj.remapped_projection, + limit, + )?)) +} + +/// Batches a `ReversedStagingMemoryStream` scans in one poll without emitting +/// a row, before it lets other tasks run. +const REVERSED_STAGING_BATCHES_PER_POLL: usize = 128; + +/// Scans the batches of staging memory newest row first. +/// +/// The batches stay as they were captured, so planning the scan copies +/// nothing. Each poll of the stream takes the newest batch it has not scanned +/// yet, finds the rows that pass `predicate`, and copies only the rows it +/// emits, in reverse order. It ends once `fetch` rows were emitted: a +/// `LIMIT 10` copies ten rows, whatever the cache holds. Reversing every +/// cached batch when the scan is planned instead copied all of them for each +/// such query, outside any memory budget. +struct ReversedStagingMemoryExec { + /// Oldest first, as captured; scanned from the back. + batches: Arc<[RecordBatch]>, + /// The exact filters the scan enforces, over the schema of `batches`. + predicate: Option>, + /// The columns of `batches` to output, in output order; all when `None`. + projection: Option>, + /// The most rows to emit. + fetch: Option, + properties: Arc, +} + +impl ReversedStagingMemoryExec { + /// `schema` is that of every batch in `batches`. + fn try_new( + batches: Vec, + schema: &SchemaRef, + predicate: Option>, + projection: Option>, + fetch: Option, + ) -> DataFusionResult { + // As a `MemTable` checks the batches it is given. + if batches + .iter() + .any(|batch| !schema.contains(batch.schema_ref())) + { + return Err(DataFusionError::Plan( + "Mismatch between schema and batches".to_string(), + )); + } + let output_schema = match &projection { + Some(projection) => Arc::new(schema.project(projection)?), + None => Arc::clone(schema), + }; + let properties = Arc::new(PlanProperties::new( + EquivalenceProperties::new(output_schema), + Partitioning::UnknownPartitioning(1), + EmissionType::Incremental, + Boundedness::Bounded, + )); + Ok(Self { + batches: batches.into(), + predicate, + projection, + fetch, + properties, + }) + } + + fn compute_statistics(&self, partition: Option) -> DataFusionResult> { + if let Some(idx) = partition + && idx != 0 + { + return Err(DataFusionError::Internal(format!( + "Invalid partition index: {idx}, the partition count is 1" + ))); + } + let staged = self + .batches + .iter() + .fold(0usize, |rows, batch| rows.saturating_add(batch.num_rows())); + let rows = self.fetch.map_or(staged, |fetch| fetch.min(staged)); + Ok(Arc::new(Statistics { + // Every staged row is emitted up to `fetch`, unless a filter + // drops some. + num_rows: if self.predicate.is_none() { + Precision::Exact(rows) + } else { + Precision::Inexact(rows) + }, + total_byte_size: Precision::Absent, + column_statistics: Statistics::new_unknown(&self.schema()).column_statistics, + })) + } +} + +// The batches are the staging cache: name how many, not what they hold. +impl std::fmt::Debug for ReversedStagingMemoryExec { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ReversedStagingMemoryExec") + .field("batches", &self.batches.len()) + .field("predicate", &self.predicate) + .field("projection", &self.projection) + .field("fetch", &self.fetch) + .field("schema", &self.schema()) + .finish() + } +} + +impl DisplayAs for ReversedStagingMemoryExec { + fn fmt_as(&self, _t: DisplayFormatType, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "ReversedStagingMemoryExec: batches={}", + self.batches.len() + )?; + if let Some(fetch) = self.fetch { + write!(f, ", fetch={fetch}")?; + } + if let Some(predicate) = &self.predicate { + write!(f, ", predicate={predicate}")?; + } + Ok(()) + } +} + +impl ExecutionPlan for ReversedStagingMemoryExec { + fn name(&self) -> &str { + "ReversedStagingMemoryExec" + } + + fn properties(&self) -> &Arc { + &self.properties + } + + fn children(&self) -> Vec<&Arc> { + vec![] + } + + fn apply_expressions( + &self, + f: &mut dyn FnMut( + &Arc, + ) -> DataFusionResult, + ) -> DataFusionResult { + match &self.predicate { + Some(predicate) => f(predicate), + None => Ok(TreeNodeRecursion::Continue), + } + } + + fn with_new_children( + self: Arc, + children: Vec>, + ) -> DataFusionResult> { + if !children.is_empty() { + return Err(DataFusionError::Internal( + "ReversedStagingMemoryExec does not accept children".to_string(), + )); + } + Ok(self) + } + + fn execute( + &self, + partition: usize, + _context: Arc, + ) -> DataFusionResult { + if partition != 0 { + return Err(DataFusionError::Internal(format!( + "ReversedStagingMemoryExec invalid partition {partition}, expected 0" + ))); + } + Ok(Box::pin(ReversedStagingMemoryStream { + schema: self.schema(), + batches: Arc::clone(&self.batches), + pending: self.batches.len(), + predicate: self.predicate.clone(), + projection: self.projection.clone(), + remaining: self.fetch, + })) + } + + fn partition_statistics(&self, partition: Option) -> DataFusionResult> { + self.compute_statistics(partition) + } + + fn statistics_from_inputs( + &self, + _input_stats: &[Arc], + args: &datafusion::physical_plan::statistics::StatisticsArgs, + ) -> DataFusionResult> { + self.compute_statistics(args.partition()) + } +} + +/// The rows of one batch a newest-first scan emits. +enum NewestRows { + /// `len` consecutive rows from `start`: all of them, the last one first. + Range { start: usize, len: usize }, + /// The rows at these positions, already newest first. + Rows(Vec), +} + +/// The newest `wanted` rows of `batch` that pass `predicate`, or `None` when +/// no row does. A row the predicate is null for does not pass, as in a +/// `FilterExec`. +fn newest_matching_rows( + predicate: &Arc, + batch: &RecordBatch, + wanted: usize, +) -> DataFusionResult> { + use arrow_array::Array as _; + + let rows = batch.num_rows(); + let mask = predicate.evaluate(batch)?.into_array(rows)?; + let mask = mask + .as_any() + .downcast_ref::() + .ok_or_else(|| { + DataFusionError::Internal( + "Cannot create filter_array from non-boolean predicates".to_string(), + ) + })?; + let matching = mask.true_count(); + if matching == 0 { + return Ok(None); + } + // The usual case: staged rows are recent, and all within the query's range. + if matching == rows { + return Ok(Some(NewestRows::Range { + start: rows - wanted, + len: wanted, + })); + } + let wanted = wanted.min(matching); + let mut positions = Vec::with_capacity(wanted); + for row in (0..rows).rev() { + if mask.value(row) && mask.is_valid(row) { + positions.push(row); + if positions.len() == wanted { + break; + } + } + } + // Consecutive rows are a slice, which is reversed without an index for + // each of its rows. + let (newest, oldest) = (positions[0], positions[positions.len() - 1]); + Ok(Some(if newest - oldest + 1 == positions.len() { + NewestRows::Range { + start: oldest, + len: positions.len(), + } + } else { + NewestRows::Rows(positions) + })) +} + +struct ReversedStagingMemoryStream { + schema: SchemaRef, + batches: Arc<[RecordBatch]>, + /// `batches[..pending]` are still to be scanned, the last of them first. + pending: usize, + predicate: Option>, + projection: Option>, + /// Rows still to emit; `None` when there is no limit. + remaining: Option, +} + +impl ReversedStagingMemoryStream { + /// The rows of `batches[index]` to emit, newest first and at most + /// `remaining`; `None` when it has none. Only those rows are copied. + fn newest_rows_of(&self, index: usize) -> DataFusionResult> { + let batch = &self.batches[index]; + let rows = batch.num_rows(); + let wanted = self.remaining.map_or(rows, |remaining| remaining.min(rows)); + if wanted == 0 { + return Ok(None); + } + let newest = match &self.predicate { + None => NewestRows::Range { + start: rows - wanted, + len: wanted, + }, + Some(predicate) => match newest_matching_rows(predicate, batch, wanted)? { + Some(newest) => newest, + None => return Ok(None), + }, + }; + let columns: Vec = match &self.projection { + Some(projection) => projection + .iter() + .map(|column| Arc::clone(batch.column(*column))) + .collect(), + None => batch.columns().to_vec(), + }; + // A projection without columns still stands for every row. + let output = RecordBatch::try_new_with_options( + Arc::clone(&self.schema), + columns, + &arrow_array::RecordBatchOptions::new().with_row_count(Some(rows)), + )?; + Ok(Some(match newest { + NewestRows::Range { start, len } => { + crate::utils::arrow::reverse(&output.slice(start, len)) + } + NewestRows::Rows(positions) => crate::utils::arrow::take_rows(&output, &positions)?, + })) + } +} + +impl futures_util::Stream for ReversedStagingMemoryStream { + type Item = DataFusionResult; + + fn poll_next( + mut self: std::pin::Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + for _ in 0..REVERSED_STAGING_BATCHES_PER_POLL { + if self.pending == 0 || self.remaining == Some(0) { + return std::task::Poll::Ready(None); + } + self.pending -= 1; + match self.newest_rows_of(self.pending) { + Ok(Some(batch)) => { + if let Some(remaining) = self.remaining.as_mut() { + *remaining = remaining.saturating_sub(batch.num_rows()); + } + return std::task::Poll::Ready(Some(Ok(batch))); + } + Ok(None) => {} + Err(error) => { + // Nothing follows an error. + self.pending = 0; + return std::task::Poll::Ready(Some(Err(error))); + } + } + } + // A long run of batches without a matching row: let other tasks run. + cx.waker().wake_by_ref(); + std::task::Poll::Pending + } +} + +impl datafusion::execution::RecordBatchStream for ReversedStagingMemoryStream { + fn schema(&self) -> SchemaRef { + Arc::clone(&self.schema) + } +} + #[derive(Debug, Clone)] pub enum PartialTimeFilter { Low(Bound), @@ -5810,8 +6195,8 @@ mod track_q1_tests { .collect(); assert_eq!(unlimited_ids, vec![10, 20, 30]); - // 3. Limited memory scan preserves newest-first reversed order in 1 partition - // (and enforces fetch limit when exact filters wrap the scan). + // 3. A limited memory scan reads the newest rows first, from 1 partition, + // and stops at its fetch limit, with and without exact filters. let mut plans = Vec::new(); staging_execution_plans( &schema, @@ -5847,7 +6232,7 @@ mod track_q1_tests { .copied() }) .collect(); - assert_eq!(limited_ids, vec![30, 20, 10]); + assert_eq!(limited_ids, vec![30, 20]); let mut plans = Vec::new(); let filters = [col(DEFAULT_TIMESTAMP_KEY).gt_eq(ts_lit(ts_ms(12, 0, 10)))]; @@ -7943,3 +8328,591 @@ mod track_q1_tests { ); } } + +#[cfg(test)] +mod reversed_staging_memory_tests { + use std::{sync::Arc, task::Poll}; + + use arrow_array::{Int64Array, RecordBatch, StringArray, TimestampMillisecondArray}; + use arrow_schema::{DataType, Field, Schema, SchemaRef, TimeUnit}; + use chrono::NaiveDate; + use datafusion::{ + arrow::compute::concat_batches, + catalog::Session, + common::stats::Precision, + datasource::TableProvider, + execution::context::SessionContext, + logical_expr::{TableProviderFilterPushDown, TableType}, + physical_plan::{ExecutionPlan, collect, displayable}, + prelude::{Expr, col, lit}, + scalar::ScalarValue, + }; + use futures_util::StreamExt; + + use super::{ + REVERSED_STAGING_BATCHES_PER_POLL, ReversedStagingMemoryExec, ReversedStagingMemoryStream, + filter_pushdown, projected_reversed_mem_table, reversed_staging_memory_plan, + scan_enforcing_exact_filters, staging_execution_plans, + }; + use crate::{event::DEFAULT_TIMESTAMP_KEY, parseable::StagingCapture}; + + /// 2026-11-30T12:00:00Z; row `id` is staged `time(id)` milliseconds later. + fn base() -> i64 { + NaiveDate::from_ymd_opt(2026, 11, 30) + .unwrap() + .and_hms_opt(12, 0, 0) + .unwrap() + .and_utc() + .timestamp_millis() + } + + fn schema() -> SchemaRef { + Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + Field::new( + DEFAULT_TIMESTAMP_KEY, + DataType::Timestamp(TimeUnit::Millisecond, None), + true, + ), + Field::new("payload", DataType::Utf8, true), + ])) + } + + /// Batches of `sizes` rows in staging order. `id` counts up through all of + /// them, the timestamp is `time(id)` milliseconds after `base()` (null for + /// `None`), and every third payload is null. + fn batches( + schema: &SchemaRef, + sizes: &[usize], + time: impl Fn(i64) -> Option, + ) -> Vec { + let mut next = 0i64; + sizes + .iter() + .map(|size| { + let ids = next..next + *size as i64; + next = ids.end; + RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(Int64Array::from_iter_values(ids.clone())), + Arc::new(TimestampMillisecondArray::from_iter( + ids.clone().map(|id| time(id).map(|offset| base() + offset)), + )), + Arc::new(StringArray::from_iter( + ids.map(|id| (id % 3 != 0).then(|| format!("payload-{id}"))), + )), + ], + ) + .unwrap() + }) + .collect() + } + + fn time_literal(offset: i64) -> Expr { + lit(ScalarValue::TimestampMillisecond( + Some(base() + offset), + None, + )) + } + + /// Exact filters: bounds on the time partition column. + fn at_least(offset: i64) -> Expr { + col(DEFAULT_TIMESTAMP_KEY).gt_eq(time_literal(offset)) + } + + fn before(offset: i64) -> Expr { + col(DEFAULT_TIMESTAMP_KEY).lt(time_literal(offset)) + } + + fn ids(batch: &RecordBatch) -> Vec { + batch + .column_by_name("id") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap() + .values() + .to_vec() + } + + fn staged( + records: &[RecordBatch], + ) -> ( + StagingCapture, + Vec, + ) { + ( + StagingCapture { + memory: records.to_vec(), + disk: Vec::new(), + }, + Vec::new(), + ) + } + + /// Every row `plan` yields, as one batch. + async fn rows(plan: Arc, ctx: &SessionContext) -> RecordBatch { + let schema = plan.schema(); + let batches = collect(plan, ctx.task_ctx()).await.unwrap(); + concat_batches(&schema, &batches).unwrap() + } + + /// The rows of the limited scan the provider plans over staging memory. + async fn limited( + records: &[RecordBatch], + schema: &SchemaRef, + projection: Option<&Vec>, + filters: &[Expr], + limit: usize, + ctx: &SessionContext, + ) -> RecordBatch { + let mut plans = Vec::new(); + staging_execution_plans( + schema, + &mut plans, + projection, + filters, + Some(limit), + &ctx.state(), + staged(records), + 1024, + ) + .await + .unwrap(); + assert_eq!(plans.len(), 1); + let plan = plans.pop().unwrap(); + assert!(plan.is::()); + assert_eq!(plan.properties().partitioning.partition_count(), 1); + rows(plan, ctx).await + } + + /// The rows the scan yielded when every batch was reversed to plan it: the + /// staged rows newest first, with the exact filters applied above them. + async fn eagerly_reversed( + records: &[RecordBatch], + schema: &SchemaRef, + projection: Option<&Vec>, + filters: &[Expr], + ctx: &SessionContext, + ) -> RecordBatch { + let (table, mapped) = + projected_reversed_mem_table(records.to_vec(), schema.clone(), projection, filters, 1) + .unwrap(); + let plan = + scan_enforcing_exact_filters(&table, &ctx.state(), mapped.as_ref(), filters, None) + .await + .unwrap(); + rows(plan, ctx).await + } + + /// For every limit, the lazy scan yields exactly the first rows of the + /// eagerly reversed table, in its order and under its schema: with and + /// without exact filters, whether the matching rows are all of a batch, + /// consecutive, scattered or none, and for any projection. + #[tokio::test] + async fn limited_scan_yields_the_first_rows_of_the_eager_reversal_in_order() { + let ctx = SessionContext::new(); + let schema = schema(); + let sizes = [5, 1, 0, 8, 3, 6]; + let total: usize = sizes.iter().sum(); + let datasets = [ + // Timestamps in no order, null in every fifth row: the rows a + // bound matches are scattered over a batch. + batches(&schema, &sizes, |id| { + (id % 5 != 4).then_some((id * 7 % 10) * 1000) + }), + // Ascending, never null: the rows a bound matches are consecutive. + batches(&schema, &sizes, |id| Some(id * 1000)), + ]; + let filter_sets = [ + vec![], + vec![at_least(0)], + vec![at_least(5000)], + vec![before(4000)], + vec![at_least(2000), before(7000)], + vec![at_least(20_500)], + vec![before(0)], + ]; + let projections = [None, Some(vec![2, 0]), Some(vec![1]), Some(vec![])]; + + for records in &datasets { + for filters in &filter_sets { + for projection in &projections { + let expected = + eagerly_reversed(records, &schema, projection.as_ref(), filters, &ctx) + .await; + if filters.is_empty() { + assert_eq!(expected.num_rows(), total); + } + for limit in [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 11, + total - 1, + total, + total + 1, + 1000, + ] { + let actual = + limited(records, &schema, projection.as_ref(), filters, limit, &ctx) + .await; + let case = format!( + "limit {limit}, projection {projection:?}, filters {filters:?}" + ); + assert_eq!(actual.schema(), expected.schema(), "{case}"); + assert_eq!( + actual, + expected.slice(0, limit.min(expected.num_rows())), + "{case}" + ); + } + } + } + } + + // The cases above cover each way a batch is cut: the newest rows of a + // batch in which all rows match, consecutive rows inside one, and + // scattered rows. + let newest_first = limited(&datasets[1], &schema, None, &[], 8, &ctx).await; + assert_eq!(ids(&newest_first), [22, 21, 20, 19, 18, 17, 16, 15]); + let consecutive = limited(&datasets[1], &schema, None, &[before(4000)], 3, &ctx).await; + assert_eq!(ids(&consecutive), [3, 2, 1]); + let scattered = limited(&datasets[0], &schema, None, &[at_least(5000)], 4, &ctx).await; + assert_eq!(ids(&scattered), [21, 18, 17, 15]); + } + + /// The stream reverses a batch when it is polled for it, and reads no + /// batch older than those that fill the limit. + #[test] + fn stream_reads_one_batch_per_poll_and_none_past_the_limit() { + let schema = schema(); + let records = batches(&schema, &[4, 4, 4, 4, 4], |id| Some(id * 1000)); + let mut stream = ReversedStagingMemoryStream { + schema: schema.clone(), + batches: records.clone().into(), + pending: records.len(), + predicate: None, + projection: None, + remaining: Some(6), + }; + let first = futures::executor::block_on(stream.next()).unwrap().unwrap(); + assert_eq!(ids(&first), [19, 18, 17, 16]); + assert_eq!((stream.pending, stream.remaining), (4, Some(2))); + + // Only the two newest rows of the next batch are taken. + let second = futures::executor::block_on(stream.next()).unwrap().unwrap(); + assert_eq!(ids(&second), [15, 14]); + assert_eq!(second.schema(), schema); + assert_eq!((stream.pending, stream.remaining), (3, Some(0))); + + // The three oldest batches are never read. + assert!(futures::executor::block_on(stream.next()).is_none()); + assert!(futures::executor::block_on(stream.next()).is_none()); + assert_eq!(stream.pending, 3); + } + + /// A `LIMIT` copies the rows it returns, not the cache. Planning the scan + /// reverses nothing, and running it takes what the limit asks for from + /// the newest batch, where reversing every batch to plan it copied all. + #[test] + fn limited_scan_copies_only_the_rows_it_emits() { + const BATCHES: usize = 64; + const ROWS: usize = 4096; + let schema = schema(); + let records = batches(&schema, &[ROWS; BATCHES], Some); + let cached: usize = records.iter().map(RecordBatch::get_array_memory_size).sum(); + assert!(cached > 4 * 1024 * 1024, "{cached}"); + let ctx = SessionContext::new(); + let (state, task_ctx) = (ctx.state(), ctx.task_ctx()); + let newest = (BATCHES * ROWS) as i64 - 1; + + // Every staged row is in range, as for a query of the recent past. + let in_range = [at_least(0)]; + let unfiltered: [Expr; 0] = []; + for filters in [&in_range[..], &unfiltered[..]] { + let scan = || { + futures::executor::block_on(async { + let mut plans = Vec::new(); + staging_execution_plans( + &schema, + &mut plans, + None, + filters, + Some(10), + &state, + staged(&records), + 1024, + ) + .await + .unwrap(); + collect(plans.pop().unwrap(), task_ctx.clone()) + .await + .unwrap() + }) + }; + // Once unmeasured, for whatever the first scan of a process sets up. + scan(); + let (emitted, allocated) = crate::test_alloc::measure(scan); + assert_eq!(emitted.len(), 1); + assert_eq!( + ids(&emitted[0]), + (0..10).map(|row| newest - row).collect::>() + ); + assert!( + allocated.peak < cached / 100, + "{allocated:?} for a cache of {cached} bytes" + ); + } + + let ((table, _), eager) = crate::test_alloc::measure(|| { + projected_reversed_mem_table(records.clone(), schema.clone(), None, &in_range, 1) + .unwrap() + }); + assert_eq!(table.batches.len(), 1); + assert!( + eager.peak > cached / 2, + "{eager:?} for a cache of {cached} bytes" + ); + } + + /// A long run of batches without a matching row does not hold the thread: + /// the stream gives way after a bounded number of them, and goes on from + /// where it stopped. + #[tokio::test] + async fn stream_gives_way_between_runs_of_batches_without_a_match() { + let ctx = SessionContext::new(); + let schema = schema(); + let sizes = [1; 2 * REVERSED_STAGING_BATCHES_PER_POLL + 10]; + let records = batches(&schema, &sizes, |id| Some(id * 1000)); + // Only the oldest row is in range. + let plan = reversed_staging_memory_plan( + records, + schema.clone(), + None, + &[before(1000)], + Some(5), + &ctx.state(), + ) + .unwrap(); + let mut stream = plan.execute(0, ctx.task_ctx()).unwrap(); + assert!(futures::poll!(stream.next()).is_pending()); + assert!(futures::poll!(stream.next()).is_pending()); + match futures::poll!(stream.next()) { + Poll::Ready(Some(Ok(batch))) => assert_eq!(ids(&batch), [0]), + other => panic!("expected the oldest row, got {other:?}"), + } + assert!(matches!(futures::poll!(stream.next()), Poll::Ready(None))); + } + + #[test] + fn plan_names_its_limit_and_filter_and_counts_what_it_emits() { + let ctx = SessionContext::new(); + let schema = schema(); + let records = batches(&schema, &[5, 3], |id| Some(id * 1000)); + let plan = |filters: &[Expr], limit: Option| { + reversed_staging_memory_plan( + records.clone(), + schema.clone(), + Some(&vec![0]), + filters, + limit, + &ctx.state(), + ) + .unwrap() + }; + let num_rows = |plan: &Arc| { + plan.downcast_ref::() + .unwrap() + .compute_statistics(None) + .unwrap() + .num_rows + }; + + let unfiltered = plan(&[], Some(6)); + assert_eq!(unfiltered.schema().fields().len(), 1); + assert_eq!( + displayable(unfiltered.as_ref()) + .indent(false) + .to_string() + .trim(), + "ReversedStagingMemoryExec: batches=2, fetch=6" + ); + // Every staged row up to the limit, exactly. + assert_eq!(num_rows(&unfiltered), Precision::Exact(6)); + assert_eq!(num_rows(&plan(&[], Some(100))), Precision::Exact(8)); + assert_eq!(num_rows(&plan(&[], None)), Precision::Exact(8)); + + // A filter may drop any of them. + let filtered = plan(&[at_least(3000)], Some(6)); + let display = displayable(filtered.as_ref()).indent(false).to_string(); + assert!(display.contains("fetch=6, predicate="), "{display}"); + assert!(display.contains(DEFAULT_TIMESTAMP_KEY), "{display}"); + assert_eq!(num_rows(&filtered), Precision::Inexact(6)); + assert!( + filtered + .downcast_ref::() + .unwrap() + .compute_statistics(Some(1)) + .is_err() + ); + assert!(filtered.execute(1, ctx.task_ctx()).is_err()); + } + + #[test] + fn batches_of_another_schema_are_refused_when_the_scan_is_planned() { + let other = Arc::new(Schema::new(vec![Field::new("id", DataType::Utf8, false)])); + let batch = + RecordBatch::try_new(other, vec![Arc::new(StringArray::from(vec!["a"]))]).unwrap(); + let error = ReversedStagingMemoryExec::try_new(vec![batch], &schema(), None, None, Some(1)) + .unwrap_err(); + assert!( + error + .to_string() + .contains("Mismatch between schema and batches"), + "{error}" + ); + } + + /// A table whose rows are all in staging memory, with the filter + /// pushdown of `StandardTableProvider`. + #[derive(Debug)] + struct StagedTable { + schema: SchemaRef, + records: Vec, + } + + #[async_trait::async_trait] + impl TableProvider for StagedTable { + fn schema(&self) -> SchemaRef { + self.schema.clone() + } + + fn table_type(&self) -> TableType { + TableType::Base + } + + fn supports_filters_pushdown( + &self, + filters: &[&Expr], + ) -> datafusion::error::Result> { + Ok(filters + .iter() + .map(|filter| filter_pushdown(filter, &None)) + .collect()) + } + + async fn scan( + &self, + state: &dyn Session, + projection: Option<&Vec>, + filters: &[Expr], + limit: Option, + ) -> datafusion::error::Result> { + let mut plans = Vec::new(); + staging_execution_plans( + &self.schema, + &mut plans, + projection, + filters, + limit, + state, + staged(&self.records), + 1024, + ) + .await?; + Ok(plans.pop().expect("the staged rows")) + } + } + + /// Through SQL and the whole optimizer: a `LIMIT` without an order reads + /// the newest staged rows, after exact time bounds and before an offset. + #[tokio::test] + async fn sql_limit_reads_the_newest_staged_rows() { + let schema = schema(); + let ctx = SessionContext::new(); + ctx.register_table( + "t", + Arc::new(StagedTable { + schema: schema.clone(), + records: batches(&schema, &[5, 1, 0, 8, 3, 6], |id| Some(id * 1000)), + }), + ) + .unwrap(); + let first_column = |sql: &'static str| { + let ctx = &ctx; + async move { + let batches = ctx.sql(sql).await.unwrap().collect().await.unwrap(); + batches + .iter() + .flat_map(|batch| { + batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .values() + .to_vec() + }) + .collect::>() + } + }; + + for (sql, expected) in [ + ("SELECT id FROM t LIMIT 3", vec![22, 21, 20]), + ( + "SELECT id FROM t WHERE p_timestamp >= '2026-11-30T12:00:10' LIMIT 4", + vec![22, 21, 20, 19], + ), + ( + "SELECT id FROM t WHERE p_timestamp < '2026-11-30T12:00:03' LIMIT 10", + vec![2, 1, 0], + ), + ("SELECT id FROM t LIMIT 2 OFFSET 3", vec![19, 18]), + ("SELECT count(*) FROM (SELECT id FROM t LIMIT 5)", vec![5]), + ( + "SELECT count(*) FROM (SELECT id FROM t \ + WHERE p_timestamp >= '2026-11-30T12:00:20' LIMIT 5)", + vec![3], + ), + // No limit reaches the scan below a sort or an aggregate. + ("SELECT id FROM t ORDER BY id LIMIT 3", vec![0, 1, 2]), + ("SELECT count(*) FROM t", vec![23]), + ] { + assert_eq!(first_column(sql).await, expected, "{sql}"); + } + + for (sql, limited) in [ + ("SELECT id FROM t LIMIT 3", true), + ( + "SELECT id FROM t WHERE p_timestamp >= '2026-11-30T12:00:10' LIMIT 4", + true, + ), + ("SELECT id FROM t ORDER BY id LIMIT 3", false), + ] { + let plan = ctx + .sql(sql) + .await + .unwrap() + .create_physical_plan() + .await + .unwrap(); + let display = displayable(plan.as_ref()).indent(true).to_string(); + assert_eq!( + display.contains("ReversedStagingMemoryExec"), + limited, + "{sql}:\n{display}" + ); + // The exact bound is enforced by the scan itself. + if limited { + assert!(!display.contains("FilterExec"), "{sql}:\n{display}"); + } + } + } +} diff --git a/src/utils/arrow/batch_adapter.rs b/src/utils/arrow/batch_adapter.rs index 4dc57f6cc..065ccabae 100644 --- a/src/utils/arrow/batch_adapter.rs +++ b/src/utils/arrow/batch_adapter.rs @@ -16,10 +16,11 @@ * */ -use datafusion::arrow::array::ArrayRef; -use datafusion::arrow::array::new_null_array; +use datafusion::arrow::array::{ + Array, ArrayRef, AsArray, GenericListArray, OffsetSizeTrait, StructArray, new_null_array, +}; use datafusion::arrow::compute::cast; -use datafusion::arrow::datatypes::{DataType, Field, Schema}; +use datafusion::arrow::datatypes::{DataType, Field, FieldRef, Schema}; use datafusion::arrow::error::ArrowError; use datafusion::arrow::record_batch::RecordBatch; @@ -45,7 +46,59 @@ struct AdaptationPlan { enum ColumnMapping { Identity, - Indices(Vec>), + Indices { + sources: Vec, + nulls: NullColumns, + }, +} + +/// Where the column of one table field comes from. +#[derive(Clone, Copy)] +enum ColumnSource { + /// This column of the batch. + Batch(usize), + /// The batch has no column of that name: this entry of `NullColumns`. + Null(usize), +} + +/// The all-null columns standing for the table fields a source layout lacks. +/// +/// A wide table read through a narrow layout lacks most fields, and a query +/// usually projects the columns it asked for and drops the rest right after. +/// One array per distinct type therefore stands for every missing field of +/// that type, and is kept for the next batch when that has the same row +/// count, as consecutive staged batches do. A batch then costs one buffer per +/// missing type instead of one per missing field, and a run of equally long +/// batches costs that once. The arrays are immutable, so sharing them changes +/// no value, and each column reports the size it would have had alone. +struct NullColumns { + /// The distinct types of the missing fields, in the order first seen. + types: Vec, + /// One array per type, of `rows` rows; empty until a batch needs them. + arrays: Vec, + rows: usize, +} + +impl NullColumns { + fn new(types: Vec) -> Self { + Self { + types, + arrays: Vec::new(), + rows: 0, + } + } + + /// Makes `arrays` hold `rows` rows for every type. + fn resize(&mut self, rows: usize) { + if self.arrays.len() != self.types.len() || self.rows != rows { + self.arrays = self + .types + .iter() + .map(|data_type| new_null_array(data_type, rows)) + .collect(); + self.rows = rows; + } + } } impl BatchAdapter { @@ -97,41 +150,60 @@ impl BatchAdapter { for (index, field) in source_schema.fields().iter().enumerate() { first_index.entry(field.name().as_str()).or_insert(index); } - let indices: Vec<_> = self + let mut null_types = Vec::new(); + let mut null_index = HashMap::new(); + let sources: Vec<_> = self .table_schema .fields() .iter() - .map(|field| first_index.get(field.name().as_str()).copied()) + .map(|field| match first_index.get(field.name().as_str()) { + Some(index) => ColumnSource::Batch(*index), + None => ColumnSource::Null( + *null_index.entry(field.data_type()).or_insert_with(|| { + null_types.push(field.data_type().clone()); + null_types.len() - 1 + }), + ), + }) .collect(); // Prove positional equivalence from first-occurrence resolution. // Schema pointer/value equality alone is insufficient for duplicates. - let identity = indices.len() == source_schema.fields().len() - && indices.iter().enumerate().all(|(i, idx)| *idx == Some(i)); + let identity = sources.len() == source_schema.fields().len() + && sources + .iter() + .enumerate() + .all(|(i, source)| matches!(source, ColumnSource::Batch(index) if *index == i)); self.last_plan = Some(AdaptationPlan { source_schema: Arc::clone(source_schema), columns: if identity { ColumnMapping::Identity } else { - ColumnMapping::Indices(indices) + ColumnMapping::Indices { + sources, + nulls: NullColumns::new(null_types), + } }, }); } let table_schema = &self.table_schema; - let mapping = &self.last_plan.as_ref().unwrap().columns; + let plan = self.last_plan.as_mut().unwrap(); + // Cache only the mapping: every batch still validates its actual arrays + // and receives typed null arrays sized for its own row count. + if let ColumnMapping::Indices { nulls, .. } = &mut plan.columns { + nulls.resize(batch.num_rows()); + } + let mapping = &plan.columns; let select = || match mapping { ColumnMapping::Identity => batch.columns().to_vec(), - ColumnMapping::Indices(indices) => indices + ColumnMapping::Indices { sources, nulls } => sources .iter() - .zip(table_schema.fields()) - .map(|(index, field)| match index { - Some(index) => Arc::clone(batch.column(*index)), - None => new_null_array(field.data_type(), batch.num_rows()), + .map(|source| match source { + ColumnSource::Batch(index) => Arc::clone(batch.column(*index)), + ColumnSource::Null(index) => Arc::clone(&nulls.arrays[*index]), }) .collect(), }; - // Cache only the mapping: every batch still validates its actual arrays - // and receives fresh typed null arrays sized for its own row count. present(table_schema, select, batch) } } @@ -169,7 +241,12 @@ fn present( .zip(table_schema.fields()) .map(|(column, field)| { if widens(&column, field) { - cast(&column, field.data_type()) + // What `relabel` does not present is left to `cast`, as all + // of it was before, with the error `cast` reports. + match relabel(&column, field.data_type()) { + Some(relabelled) => Ok(relabelled), + None => cast(&column, field.data_type()), + } } else { Ok(column) } @@ -180,6 +257,68 @@ fn present( .map_err(|error| mismatch_error(table_schema, source, error)) } +/// Presents `column` under the type `to` that its own type widens into +/// (`widens_losslessly`) without copying a buffer or converting a value. +/// +/// Such a column already holds the values a column of type `to` would: the +/// types differ only in what a list or struct says about its nested fields. +/// So the offsets, validity and leaf values are shared as they are, and only +/// the list and struct arrays whose nested fields differ are rebuilt around +/// them, through the constructors that check a nested field against its +/// values. `None` when the array is not of the shape `to` describes, or one of +/// those checks refuses it. +fn relabel(column: &ArrayRef, to: &DataType) -> Option { + if column.data_type() == to { + return Some(Arc::clone(column)); + } + match to { + DataType::List(item) => relabel_list::(column, item), + DataType::LargeList(item) => relabel_list::(column, item), + DataType::Struct(fields) => { + let strukt = column.as_struct_opt()?; + // Children are paired by position, which stands for the same + // child only when the names agree in order. + let same_names = strukt.fields().len() == fields.len() + && strukt + .fields() + .iter() + .zip(fields.iter()) + .all(|(own, field)| own.name() == field.name()); + if !same_names { + return None; + } + let children = strukt + .columns() + .iter() + .zip(fields.iter()) + .map(|(child, field)| relabel(child, field.data_type())) + .collect::>>()?; + StructArray::try_new_with_length( + fields.clone(), + children, + strukt.nulls().cloned(), + strukt.len(), + ) + .ok() + .map(|strukt| Arc::new(strukt) as ArrayRef) + } + _ => None, + } +} + +fn relabel_list(column: &ArrayRef, item: &FieldRef) -> Option { + let list = column.as_list_opt::()?; + let values = relabel(list.values(), item.data_type())?; + GenericListArray::::try_new( + Arc::clone(item), + list.offsets().clone(), + values, + list.nulls().cloned(), + ) + .ok() + .map(|list| Arc::new(list) as ArrayRef) +} + /// Whether an array of type `from` holds exactly the values a column of type /// `to` would, so that it can be relabelled without changing or losing data. /// @@ -286,13 +425,18 @@ pub fn try_adapt_batch( } let select = || { + // One all-null array stands for every missing field of its type (see + // `NullColumns`). Nothing is allocated for a batch that lacks none. + let mut nulls: HashMap<&DataType, ArrayRef> = HashMap::new(); table_schema .fields() .iter() .map( |table_field| match first_index.get(table_field.name().as_str()) { Some(&batch_idx) => Arc::clone(batch.column(batch_idx)), - None => new_null_array(table_field.data_type(), batch.num_rows()), + None => Arc::clone(nulls.entry(table_field.data_type()).or_insert_with(|| { + new_null_array(table_field.data_type(), batch.num_rows()) + })), }, ) .collect::>() @@ -591,6 +735,269 @@ mod tests { assert!(error.contains("field s"), "{error}"); } + /// A column that only widens into the table's type is presented without + /// copying a buffer: the result's offsets, validity and leaf values are + /// those of the staged column, at every level of nesting, and the values + /// are the ones Arrow's own cast yields. + #[test] + fn nested_widening_relabel_shares_every_buffer() { + use datafusion::arrow::array::{LargeListArray, ListArray}; + use datafusion::arrow::buffer::{NullBuffer, OffsetBuffer}; + use datafusion::arrow::datatypes::Fields; + + const ROWS: usize = 4096; + const ITEMS: usize = 16; + let item = |name: &str, nullable| Arc::new(Field::new(name, DataType::Utf8, nullable)); + let strings: ArrayRef = Arc::new(StringArray::from_iter_values( + (0..ROWS * ITEMS).map(|i| format!("tag-{i}")), + )); + // `tags`: lists of strings that may not be null; every seventh list is. + let tags: ArrayRef = Arc::new(ListArray::new( + item("item", false), + OffsetBuffer::::from_lengths(std::iter::repeat_n(ITEMS, ROWS)), + strings.clone(), + Some(NullBuffer::from_iter((0..ROWS).map(|row| row % 7 != 0))), + )); + // `event`: a struct of a count and the same strings as large lists. + let counts: ArrayRef = Arc::new(Int64Array::from_iter_values(0..ROWS as i64)); + let large_tags: ArrayRef = Arc::new(LargeListArray::new( + item("item", false), + OffsetBuffer::::from_lengths(std::iter::repeat_n(ITEMS, ROWS)), + strings.clone(), + None, + )); + let event_fields = |item_name: &str, nullable: bool| { + Fields::from(vec![ + Field::new("count", DataType::Int64, nullable), + Field::new( + "tags", + DataType::LargeList(item(item_name, nullable)), + nullable, + ), + ]) + }; + let event: ArrayRef = Arc::new(StructArray::new( + event_fields("item", false), + vec![counts.clone(), large_tags.clone()], + None, + )); + + // The table allows nulls at every level and names list items otherwise. + let wide_tags = DataType::List(item("element", true)); + let wide_event = DataType::Struct(event_fields("element", true)); + let table = Arc::new(Schema::new(vec![ + Field::new("tags", wide_tags.clone(), true), + Field::new("event", wide_event.clone(), true), + ])); + let batch = batch_of( + vec![ + Field::new("tags", tags.data_type().clone(), true), + Field::new("event", event.data_type().clone(), true), + ], + vec![tags.clone(), event.clone()], + ); + assert!(widens_losslessly(tags.data_type(), &wide_tags)); + assert!(widens_losslessly(event.data_type(), &wide_event)); + + let assert_shared = |adapted: &RecordBatch, source: &RecordBatch| { + assert_eq!(adapted.schema(), table); + for (index, wide) in [&wide_tags, &wide_event].into_iter().enumerate() { + assert_eq!( + adapted.column(index).as_ref(), + cast(source.column(index), wide).unwrap().as_ref() + ); + } + let list = adapted.column(0).as_list::(); + let own = source.column(0).as_list::(); + assert!(list.offsets().ptr_eq(own.offsets())); + assert!( + list.nulls() + .unwrap() + .buffer() + .ptr_eq(own.nulls().unwrap().buffer()) + ); + assert!(Arc::ptr_eq(list.values(), &strings)); + + let strukt = adapted.column(1).as_struct(); + let own = source.column(1).as_struct(); + assert!(Arc::ptr_eq(strukt.column(0), own.column(0))); + let list = strukt.column(1).as_list::(); + assert!( + list.offsets() + .ptr_eq(own.column(1).as_list::().offsets()) + ); + assert!(Arc::ptr_eq(list.values(), &strings)); + }; + for adapted in [ + try_adapt_batch(table.clone(), &batch).unwrap(), + BatchAdapter::new(table.clone()).adapt(&batch).unwrap(), + ] { + assert_shared(&adapted, &batch); + assert!(Arc::ptr_eq( + adapted.column(1).as_struct().column(0), + &counts + )); + } + // A slice is relabelled within its own bounds. + let sliced = batch.slice(5, 100); + let adapted = try_adapt_batch(table.clone(), &sliced).unwrap(); + assert_eq!(adapted.num_rows(), 100); + assert_shared(&adapted, &sliced); + + // Relabelling allocates the few list and struct arrays it rebuilds, + // never a buffer: the strings alone are hundreds of kilobytes. + assert!(strings.get_array_memory_size() > 256 * 1024); + for (column, wide) in [(&tags, &wide_tags), (&event, &wide_event)] { + let (relabelled, allocated) = crate::test_alloc::measure(|| relabel(column, wide)); + assert_eq!(relabelled.unwrap().data_type(), wide); + assert!(allocated.peak < 4096, "{allocated:?}"); + } + } + + /// What is not a relabelling is left to the caller: another leaf type, + /// another container, other children, and a nested field that may not be + /// null over values that are. + #[test] + fn relabel_refuses_what_only_a_conversion_presents() { + use datafusion::arrow::array::ListArray; + use datafusion::arrow::datatypes::Int32Type; + + let list_of = |item: DataType, nullable: bool| { + DataType::List(Arc::new(Field::new("item", item, nullable))) + }; + let ints = int_col(&[Some(1), None]); + assert!(Arc::ptr_eq( + &relabel(&ints, &DataType::Int32).unwrap(), + &ints + )); + assert!(relabel(&ints, &DataType::Int64).is_none()); + + let list: ArrayRef = Arc::new(ListArray::from_iter_primitive::([Some([ + Some(1), + None, + ])])); + assert_eq!(list.data_type(), &list_of(DataType::Int32, true)); + assert!(relabel(&list, &list_of(DataType::Int64, true)).is_none()); + assert!(relabel(&list, &list_of(DataType::Int32, false)).is_none()); + assert!( + relabel( + &list, + &DataType::LargeList(Arc::new(Field::new("item", DataType::Int32, true))) + ) + .is_none() + ); + assert!(relabel(&ints, &list_of(DataType::Int32, true)).is_none()); + + let child = |name: &str, nullable: bool| Field::new(name, DataType::Int32, nullable); + let strukt: ArrayRef = Arc::new(StructArray::from(vec![( + Arc::new(child("a", true)), + int_col(&[Some(1), None]), + )])); + let relabelled = relabel( + &strukt, + &DataType::Struct( + vec![ + child("a", true) + .with_metadata(HashMap::from([("k".to_string(), "v".to_string())])), + ] + .into(), + ), + ) + .unwrap(); + assert!(Arc::ptr_eq( + relabelled.as_struct().column(0), + strukt.as_struct().column(0) + )); + for other in [ + vec![child("b", true)], + vec![child("a", false)], + vec![child("a", true), child("b", true)], + vec![Field::new("a", DataType::Int64, true)], + ] { + assert!(relabel(&strukt, &DataType::Struct(other.into())).is_none()); + } + } + + /// The fields a batch lacks are all null whatever array stands for them, + /// so one array stands for every missing field of a type, and for the + /// next batch as long as it has as many rows. A wide table read through a + /// narrow layout then costs a buffer per missing type, not per field. + #[test] + fn missing_fields_share_one_null_array_per_type_and_row_count() { + const TEXT_FIELDS: usize = 200; + const NUMBER_FIELDS: usize = 100; + let mut fields = vec![int_field("a", true)]; + fields + .extend((0..TEXT_FIELDS).map(|i| Field::new(format!("text{i}"), DataType::Utf8, true))); + fields.extend( + (0..NUMBER_FIELDS).map(|i| Field::new(format!("number{i}"), DataType::Int64, true)), + ); + let table = Arc::new(Schema::new(fields)); + let source = Arc::new(Schema::new(vec![int_field("a", true)])); + let rows = |count: i32| { + RecordBatch::try_new( + source.clone(), + vec![Arc::new(Int32Array::from_iter_values(0..count))], + ) + .unwrap() + }; + let batch = rows(4096); + let (text, number) = (1, 1 + TEXT_FIELDS); + + let assert_adapted = |adapted: &RecordBatch, batch: &RecordBatch| { + assert!(Arc::ptr_eq(&adapted.schema(), &table)); + assert!(Arc::ptr_eq(adapted.column(0), batch.column(0))); + for (column, field) in adapted.columns().iter().zip(table.fields()).skip(1) { + assert_eq!(column.data_type(), field.data_type()); + assert_eq!(column.len(), batch.num_rows()); + assert_eq!(column.null_count(), batch.num_rows()); + } + // One array per type, and never one for two types. + for column in &adapted.columns()[text..number] { + assert!(Arc::ptr_eq(column, adapted.column(text))); + } + for column in &adapted.columns()[number..] { + assert!(Arc::ptr_eq(column, adapted.column(number))); + } + assert!(!Arc::ptr_eq(adapted.column(text), adapted.column(number))); + }; + + let (legacy, separate) = + crate::test_alloc::measure(|| legacy_adapt_batch(table.clone(), &batch)); + let mut adapter = BatchAdapter::new(table.clone()); + let (first, shared) = crate::test_alloc::measure(|| adapter.adapt(&batch).unwrap()); + assert_adapted(&first, &batch); + // The same batch as before, and each column reports the size it had. + assert_eq!(first, legacy); + assert_eq!( + first.get_array_memory_size(), + legacy.get_array_memory_size() + ); + assert!(shared.peak * 20 < separate.peak, "{shared:?} {separate:?}"); + + // As many rows again: the arrays of the batch before stand for these. + let (second, reused) = crate::test_alloc::measure(|| adapter.adapt(&batch).unwrap()); + assert_adapted(&second, &batch); + assert!(Arc::ptr_eq(second.column(text), first.column(text))); + assert!(Arc::ptr_eq(second.column(number), first.column(number))); + assert!(reused.peak * 4 < shared.peak, "{reused:?} {shared:?}"); + + // Another row count gets arrays of its own length. + let shorter = rows(100); + let third = adapter.adapt(&shorter).unwrap(); + assert_adapted(&third, &shorter); + assert!(!Arc::ptr_eq(third.column(text), first.column(text))); + assert_eq!(third, legacy_adapt_batch(table.clone(), &shorter)); + assert_eq!(adapter.plan_builds(), 1); + + // The adapter of a single batch shares within that batch. + let (single, once) = + crate::test_alloc::measure(|| try_adapt_batch(table.clone(), &batch).unwrap()); + assert_adapted(&single, &batch); + assert_eq!(single, legacy); + assert!(once.peak * 20 < separate.peak, "{once:?} {separate:?}"); + } + #[test] fn non_nullable_table_field_with_nulls_still_panics() { let table = Arc::new(Schema::new(vec![int_field("a", false)])); diff --git a/src/utils/arrow/mod.rs b/src/utils/arrow/mod.rs index 6fd3a149e..6c6642a43 100644 --- a/src/utils/arrow/mod.rs +++ b/src/utils/arrow/mod.rs @@ -22,7 +22,7 @@ use std::{collections::HashMap, sync::Arc}; use arrow::compute::{CastOptions, cast_with_options, take}; use arrow_array::{ Array, ArrayRef, RecordBatch, RecordBatchOptions, StringArray, TimestampMillisecondArray, - UInt32Array, UInt64Array, + UInt32Array, UInt64Array, builder::StringBuilder, }; use arrow_schema::{ArrowError, DataType, Field, Schema, TimeUnit}; use chrono::{DateTime, Utc}; @@ -153,9 +153,7 @@ pub fn add_parseable_fields( // The usual case: the stream has no such field, or has it as text. None => ( Field::new(key, DataType::Utf8, true), - Arc::new(StringArray::from_iter_values(std::iter::repeat_n( - value, row_count, - ))) as ArrayRef, + Arc::new(repeated_utf8(value, row_count)?) as ArrayRef, ), Some(existing) => match custom_field_value_as(value, existing.data_type(), row_count) { Some(column) => (Field::new(key, existing.data_type().clone(), true), column), @@ -173,6 +171,24 @@ pub fn add_parseable_fields( RecordBatch::try_new(new_schema, columns) } +/// A text column of `rows` copies of `value`, none of them null. +/// +/// Both buffers are allocated once, at their final size. Collecting an +/// iterator of the repeated value instead starts the value buffer empty and +/// doubles it as it fills, which moves the bytes written so far at every +/// growth and can leave up to twice the bytes the column holds allocated. +/// Every request with a custom field builds one such column per field. +fn repeated_utf8(value: &str, rows: usize) -> Result { + // The offsets of a `Utf8` column are 32 bits wide. + let bytes = rows + .checked_mul(value.len()) + .filter(|bytes| i32::try_from(*bytes).is_ok()) + .ok_or_else(|| ArrowError::OffsetOverflowError(rows.saturating_mul(value.len())))?; + let mut builder = StringBuilder::with_capacity(rows, bytes); + builder.append_value_n(value, rows); + Ok(builder.finish()) +} + /// Counts, per stream, the custom fields `add_parseable_fields` left out of /// `rb`: those of `p_custom_fields` the batch has no column for. A custom /// field is otherwise always a column, its own or the body's of that name. @@ -282,6 +298,33 @@ fn reverse_with( .unwrap() } +/// Returns the rows of `rb` at the positions `rows`, in the order given. +/// +/// Every position must be a row of `rb`. A batch without columns keeps one +/// row for each position. +pub fn take_rows(rb: &RecordBatch, rows: &[usize]) -> Result { + // 32-bit indices where the batch allows them, as in `reverse`. + let indices: ArrayRef = if u32::try_from(rb.num_rows()).is_ok() { + Arc::new(UInt32Array::from_iter_values( + rows.iter().map(|row| *row as u32), + )) + } else { + Arc::new(UInt64Array::from_iter_values( + rows.iter().map(|row| *row as u64), + )) + }; + let columns = rb + .columns() + .iter() + .map(|column| take(column, indices.as_ref(), None)) + .collect::, _>>()?; + RecordBatch::try_new_with_options( + rb.schema(), + columns, + &RecordBatchOptions::new().with_row_count(Some(rows.len())), + ) +} + #[cfg(test)] mod tests { use std::sync::Arc; @@ -301,6 +344,116 @@ mod tests { assert!(Arc::ptr_eq(&rb.schema().fields()[1], &field)); } + /// The column of a custom field is the one collecting the repeated value + /// built, in buffers of exactly the size it holds, allocated once. + #[test] + fn repeated_header_column_is_allocated_once_at_its_exact_size() { + const OFFSET: usize = std::mem::size_of::(); + for (value, rows) in [ + ("production-eu-west-1", 20_000), + ("x", 4096), + ("ünïcödé", 1000), + ("", 1000), + ("only", 1), + ("none", 0), + ] { + let collected = StringArray::from_iter_values(std::iter::repeat_n(value, rows)); + let (column, allocated) = + crate::test_alloc::measure(|| repeated_utf8(value, rows).unwrap()); + + // The same `Utf8` column: type, offsets, bytes, and no validity. + assert_eq!(column, collected, "{value:?} x {rows}"); + assert_eq!(column.data_type(), &DataType::Utf8); + assert_eq!(column.len(), rows); + assert_eq!(column.value_offsets(), collected.value_offsets()); + assert_eq!(column.value_data(), collected.value_data()); + assert!(column.nulls().is_none()); + assert_eq!(column.null_count(), 0); + + // Neither buffer has room it does not use. + let bytes = rows * value.len(); + assert_eq!(column.values().len(), bytes); + assert_eq!(column.values().capacity(), bytes, "{value:?} x {rows}"); + assert_eq!( + column.offsets().inner().inner().capacity(), + (rows + 1) * OFFSET + ); + // And nothing was allocated on the way but those two buffers and + // the array around them: no buffer grew. + let exact = bytes + (rows + 1) * OFFSET; + assert!( + allocated.peak <= exact + 1024, + "{value:?} x {rows}: {allocated:?}" + ); + assert!(allocated.retained >= exact as isize); + } + + // Growing the value buffer by doubling holds the old and the new + // buffer at once, and ends with room the column does not use. + let (value, rows) = ("production-eu-west-1", 20_000); + let (collected, grown) = crate::test_alloc::measure(|| { + StringArray::from_iter_values(std::iter::repeat_n(value, rows)) + }); + assert!(collected.values().capacity() > rows * value.len()); + assert!(grown.peak > rows * value.len() + (rows + 1) * OFFSET + 1024); + } + + #[test] + fn repeated_header_column_too_long_for_its_offsets_is_an_error() { + let value = "0123456789abcdef"; + let rows = i32::MAX as usize / value.len() + 1; + assert!(matches!( + repeated_utf8(value, rows), + Err(ArrowError::OffsetOverflowError(_)) + )); + assert!(matches!( + repeated_utf8(value, usize::MAX), + Err(ArrowError::OffsetOverflowError(_)) + )); + } + + #[test] + fn custom_field_column_repeats_its_value_for_every_row() { + let rows = 300; + let rb = RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new("id", DataType::Int64, false)])), + vec![Arc::new(arrow_array::Int64Array::from_iter_values( + 0..rows as i64, + ))], + ) + .unwrap(); + let custom = HashMap::from([ + ("p_src_ip".to_string(), "10.0.0.7".to_string()), + ("environment".to_string(), "production".to_string()), + ]); + let rb = add_parseable_fields(rb, Utc::now(), &custom, &HashMap::new()).unwrap(); + assert_eq!(rb.num_rows(), rows); + // The timestamp, the body, then the custom fields in name order. + let names = rb + .schema() + .fields() + .iter() + .map(|field| field.name().clone()) + .collect::>(); + assert_eq!( + names, + [DEFAULT_TIMESTAMP_KEY, "id", "environment", "p_src_ip"] + ); + for (index, value) in [(2, "production"), (3, "10.0.0.7")] { + let field = rb.schema().field(index).clone(); + assert_eq!(field.data_type(), &DataType::Utf8); + assert!(field.is_nullable()); + let column = rb + .column(index) + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(column.null_count(), 0); + assert!(column.iter().all(|row| row == Some(value))); + assert_eq!(column.values().capacity(), rows * value.len()); + } + } + #[test] fn check_empty_json_to_record_batches() { let r = RecordBatch::new_empty(Arc::new(Schema::empty())); @@ -391,6 +544,37 @@ mod tests { assert_eq!(reverse(&sliced), reverse_reference(&sliced)); } + #[test] + fn take_rows_returns_the_rows_in_the_order_given() { + let batch = reverse_fixture(1000, 6); + // Descending and sparse, as a newest-first scan of matching rows asks. + let rows = [999, 998, 700, 12, 3, 0]; + let taken = take_rows(&batch, &rows).unwrap(); + assert_eq!(taken.schema(), batch.schema()); + assert_eq!(taken.num_rows(), rows.len()); + for (position, row) in rows.iter().enumerate() { + assert_eq!(taken.slice(position, 1), batch.slice(*row, 1), "{row}"); + } + // Every row, last first, is the reversed batch. + let all = (0..batch.num_rows()).rev().collect::>(); + assert_eq!(take_rows(&batch, &all).unwrap(), reverse(&batch)); + // Positions are those of the slice, not of the batch it is cut from. + let sliced = batch.slice(100, 50); + assert_eq!( + take_rows(&sliced, &[49, 0]).unwrap(), + take_rows(&batch, &[149, 100]).unwrap() + ); + assert_eq!(take_rows(&batch, &[]).unwrap().num_rows(), 0); + + let no_columns = RecordBatch::try_new_with_options( + Arc::new(Schema::empty()), + vec![], + &RecordBatchOptions::new().with_row_count(Some(5)), + ) + .unwrap(); + assert_eq!(take_rows(&no_columns, &[4, 1]).unwrap().num_rows(), 2); + } + #[test] fn reverse_keeps_row_count_without_columns() { let batch = RecordBatch::try_new_with_options( From d134ec4389a782b9d3d4cb2f6c8197201eaa7ca7 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:16:28 -0600 Subject: [PATCH 04/17] Tune Parquet encoding and bound clustered log conversion memory --- src/option.rs | 74 +++- src/parseable/streams.rs | 299 +++++++++++++++- src/parseable/streams/log_clustering.rs | 258 ++++++++++---- src/parseable/streams/log_clustering_tests.rs | 54 +-- src/storage/field_stats.rs | 329 ++++++++++-------- 5 files changed, 753 insertions(+), 261 deletions(-) diff --git a/src/option.rs b/src/option.rs index 25c55b5ff..5e37db17a 100644 --- a/src/option.rs +++ b/src/option.rs @@ -74,11 +74,18 @@ pub enum Compression { Lzo, Brotli, Lz4, - #[default] Lz4Raw, + #[default] Zstd, } +fn parquet_zstd_level(value: Option<&str>) -> ZstdLevel { + let level = value + .and_then(|s| s.trim().parse::().ok()) + .unwrap_or(1); + ZstdLevel::try_new(level.clamp(1, 22)).expect("clamped Zstd level is valid") +} + impl From for parquet::basic::Compression { fn from(value: Compression) -> Self { match value { @@ -89,7 +96,9 @@ impl From for parquet::basic::Compression { Compression::Brotli => parquet::basic::Compression::BROTLI(BrotliLevel::default()), Compression::Lz4 => parquet::basic::Compression::LZ4, Compression::Lz4Raw => parquet::basic::Compression::LZ4_RAW, - Compression::Zstd => parquet::basic::Compression::ZSTD(ZstdLevel::default()), + Compression::Zstd => parquet::basic::Compression::ZSTD(parquet_zstd_level( + std::env::var("P_PARQUET_ZSTD_LEVEL").ok().as_deref(), + )), } } } @@ -167,24 +176,37 @@ pub mod validation { pub fn cluster_column(s: &str) -> Result { // Bound startup configuration and per-output schema lookups. const MAX_CANDIDATES: usize = 16; - let mut columns = Vec::new(); - for column in s.split(',').map(str::trim) { - if column.is_empty() { - return Err("P_LOG_SEVERITY_CLUSTER_COLUMN cannot contain empty entries; unset it to disable clustering".to_string()); + let mut candidates = Vec::new(); + for candidate in s.split(',') { + let mut columns = Vec::new(); + for column in candidate.split('+').map(str::trim) { + if column.is_empty() { + return Err("P_LOG_SEVERITY_CLUSTER_COLUMN cannot contain empty entries; unset it to disable clustering".to_string()); + } + if columns.contains(&column) { + return Err(format!("Duplicate column in clustering key: {column}")); + } + if columns.len() == MAX_CANDIDATES { + return Err(format!( + "A clustering key accepts at most {MAX_CANDIDATES} columns" + )); + } + columns.push(column); } - if columns.contains(&column) { + let candidate = columns.join("+"); + if candidates.contains(&candidate) { return Err(format!( - "P_LOG_SEVERITY_CLUSTER_COLUMN contains duplicate column: {column}" + "P_LOG_SEVERITY_CLUSTER_COLUMN contains duplicate candidate: {candidate}" )); } - if columns.len() == MAX_CANDIDATES { + if candidates.len() == MAX_CANDIDATES { return Err(format!( "P_LOG_SEVERITY_CLUSTER_COLUMN accepts at most {MAX_CANDIDATES} candidates" )); } - columns.push(column); + candidates.push(candidate); } - Ok(columns.join(",")) + Ok(candidates.join(",")) } pub fn compression(s: &str) -> Result { @@ -341,6 +363,36 @@ pub mod validation { } } +#[cfg(test)] +mod parquet_option_tests { + use super::{parquet_zstd_level, validation}; + + #[test] + fn parses_and_clamps_parquet_zstd_levels() { + for (input, expected) in [ + (None, 1), + (Some("invalid"), 1), + (Some("-4"), 1), + (Some(" 7 "), 7), + (Some("22"), 22), + (Some("31"), 22), + ] { + assert_eq!(parquet_zstd_level(input).compression_level(), expected); + } + } + + #[test] + fn normalizes_composite_cluster_candidates() { + assert_eq!( + validation::cluster_column(" level + app , severity_text ").unwrap(), + "level+app,severity_text" + ); + for invalid in ["+app", "level+", "level++app", "app+app", "a+b, a + b"] { + assert!(validation::cluster_column(invalid).is_err(), "{invalid}"); + } + } +} + #[cfg(test)] mod ui_tests { use super::{UiRoot, validation}; diff --git a/src/parseable/streams.rs b/src/parseable/streams.rs index a63731010..5cc9c15a9 100644 --- a/src/parseable/streams.rs +++ b/src/parseable/streams.rs @@ -39,7 +39,9 @@ use parquet::{ file::{ FOOTER_SIZE, metadata::SortingColumn, - properties::{BloomFilterPosition, WriterProperties}, + properties::{ + BloomFilterPosition, WriterProperties, WriterPropertiesBuilder, WriterVersion, + }, reader::FileReader, serialized_reader::SerializedFileReader, writer::SerializedFileWriter, @@ -62,7 +64,10 @@ use std::{ sync::{Arc, Mutex, RwLock}, time::{Duration, Instant, SystemTime, UNIX_EPOCH}, }; -use tokio::task::JoinSet; +use tokio::{ + sync::{Semaphore, SemaphorePermit}, + task::JoinSet, +}; use tracing::{debug, error, info, info_span, instrument, trace, warn}; use ulid::Ulid; @@ -79,7 +84,10 @@ use crate::{ metrics, option::Mode, parseable::{DEFAULT_TENANT, PARSEABLE}, - storage::{StreamType, object_storage::to_bytes, retention::Retention}, + storage::{ + StreamType, field_stats::MAX_INLINE_FIELD_STATS_BYTES, object_storage::to_bytes, + retention::Retention, + }, sync::FLUSH_AND_CONVERT_RUNTIME, utils::{ arrow::try_adapt_batch, @@ -146,6 +154,54 @@ fn log_conversion_threads(var: Option<&str>, cpus: usize) -> usize { .unwrap_or_else(|| (cpus / 2).clamp(2, 8)) } +/// Admission is process-wide across scheduled stream conversions. All waiting +/// happens before dispatch so nested Rayon work can still use the entire pool. +static CONVERSION_MEMORY_BUDGET: Lazy = Lazy::new(|| { + let bytes = std::env::var("P_CONVERSION_MEMORY_BUDGET_BYTES") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .filter(|&bytes| bytes > 0) + .unwrap_or(512 * 1024 * 1024); + ConversionMemoryBudget::new(bytes) +}); + +struct ConversionMemoryBudget { + semaphore: Semaphore, + permits: u32, + bytes_per_permit: u64, +} + +impl ConversionMemoryBudget { + fn new(bytes: u64) -> Self { + // Use exact byte permits wherever possible. Larger budgets need + // coarser units because acquire_many accepts at most u32::MAX. + let max_permits = u64::from(u32::MAX).min(Semaphore::MAX_PERMITS as u64); + let bytes_per_permit = bytes.div_ceil(max_permits); + let permits = (bytes / bytes_per_permit) as u32; + Self { + semaphore: Semaphore::new(permits as usize), + permits, + bytes_per_permit, + } + } + + async fn acquire(&self, staged_bytes: u64) -> SemaphorePermit<'_> { + // IPC can be compressed. Allow room for decoded rows, read-ahead, + // and encoder state, and charge at least one wave even for a small + // snapshot. A stream larger than the budget runs alone. + let estimated = staged_bytes + .saturating_mul(4) + .max(LOG_PARALLEL_WAVE_SOFT_BYTES as u64); + let permits = estimated + .div_ceil(self.bytes_per_permit) + .min(u64::from(self.permits)) as u32; + self.semaphore + .acquire_many(permits) + .await + .expect("conversion semaphore stays open") + } +} + const INPROCESS_DIR_PREFIX: &str = "processing_"; const METRIC_NAME_BLOOM_FILTER_NDV: u64 = 32768; const MAX_PERIODIC_PARQUET_GROUPS_PER_STREAM: usize = 2; @@ -1739,6 +1795,48 @@ impl StartupSyncPlan { } } +/// Set fallback encodings on Parquet leaf paths. List elements have a repeated +/// `list` group in the Parquet schema, and map entries keep their Arrow names. +fn parquet_field_encodings( + mut props: WriterPropertiesBuilder, + path: &mut Vec, + field: &Field, +) -> WriterPropertiesBuilder { + use arrow_schema::DataType; + + path.push(field.name().clone()); + match field.data_type() { + DataType::Utf8 | DataType::LargeUtf8 => { + props = props.set_column_encoding( + ColumnPath::new(path.clone()), + Encoding::DELTA_LENGTH_BYTE_ARRAY, + ); + } + DataType::Timestamp(_, _) => { + props = props + .set_column_encoding(ColumnPath::new(path.clone()), Encoding::DELTA_BINARY_PACKED); + } + DataType::Struct(children) => { + for child in children { + props = parquet_field_encodings(props, path, child); + } + } + DataType::List(element) + | DataType::LargeList(element) + | DataType::FixedSizeList(element, _) + | DataType::ListView(element) + | DataType::LargeListView(element) => { + path.push("list".into()); + props = parquet_field_encodings(props, path, element); + path.pop(); + } + DataType::Map(entries, _) => props = parquet_field_encodings(props, path, entries), + _ => {} + } + path.pop(); + props +} + impl Stream { pub fn new( options: Arc, @@ -2979,6 +3077,8 @@ impl Stream { let row_group_bytes = (self.options.row_group_bytes > 0).then_some(self.options.row_group_bytes); let mut props = WriterProperties::builder() + .set_writer_version(WriterVersion::PARQUET_1_0) + .set_dictionary_page_size_limit(128 * 1024) .set_max_row_group_row_count(Some(self.options.row_group_size)) .set_max_row_group_bytes(row_group_bytes) .set_compression(self.options.parquet_compression.into()) @@ -2987,6 +3087,11 @@ impl Stream { Encoding::DELTA_BINARY_PACKED, ); + let mut path = Vec::new(); + for field in merged_schema.fields() { + props = parquet_field_encodings(props, &mut path, field); + } + // Build sorting columns. For OTel-metrics streams, put // `metric_name` ahead of the time partition so per-page parquet // min/max stats can prune by metric (PromQL's universal selector @@ -3058,7 +3163,12 @@ impl Stream { for partition in custom_partition.split(',') { if let Ok(idx) = merged_schema.index_of(partition) { let column_path = ColumnPath::new(vec![partition.to_string()]); - props = props.set_column_encoding(column_path, Encoding::DELTA_BYTE_ARRAY); + if !matches!( + merged_schema.field(idx).data_type(), + arrow_schema::DataType::Timestamp(_, _) + ) { + props = props.set_column_encoding(column_path, Encoding::DELTA_BYTE_ARRAY); + } sorting_column_vec.push(SortingColumn { column_idx: idx as i32, @@ -3832,7 +3942,7 @@ impl Stream { &schema, &props, time_partition, - cluster_key, + cluster_key.as_ref(), ); let artifacts = match write_result { Ok(Some(artifacts)) => { @@ -3960,7 +4070,7 @@ impl Stream { schema: &Arc, props: &WriterProperties, time_partition: Option<&String>, - cluster_key: Option, + cluster_key: Option<&LogClusterKey>, ) -> Result, StagingError> { let _span = info_span!( "write_parquet_part_file", @@ -4050,7 +4160,7 @@ impl Stream { schema: &Arc, props: &WriterProperties, time_partition: Option<&String>, - key: LogClusterKey, + key: &LogClusterKey, collect_stats_max: Option, in_flight: usize, ) -> Result { @@ -4078,7 +4188,7 @@ impl Stream { schema: &Arc, props: &WriterProperties, time_partition: Option<&String>, - key: LogClusterKey, + key: &LogClusterKey, collect_stats_max: Option, in_flight: usize, ) -> Result { @@ -4236,8 +4346,11 @@ impl Stream { let mut timings = LogParquetPhaseTimings::default(); for batch in record_reader.merged_iter(schema.clone(), time_partition.cloned()) { let batch = batch?; - if let Some(stats) = stats.as_mut() { - stats.update(&batch); + if stats.as_mut().is_some_and(|acc| { + acc.update(&batch); + acc.exceeds_inline_budget(MAX_INLINE_FIELD_STATS_BYTES) + }) { + stats = None; } timings.rows += batch.num_rows(); writer.write(&batch)?; @@ -4276,7 +4389,8 @@ impl Stream { finisher.part_path = Some(part_path.to_path_buf()); } let mut source = LogRowGroupSource::new(batches, finisher, max_rows, max_bytes, stats) - .with_merged_schema(merged_columns, merged_row_bytes); + .with_merged_schema(merged_columns, merged_row_bytes) + .with_inline_stats_budget(MAX_INLINE_FIELD_STATS_BYTES); let mut timings = LogParquetPhaseTimings::default(); let prepare = |source: &mut LogRowGroupSource<_>, timings: &mut LogParquetPhaseTimings| { @@ -5669,15 +5783,22 @@ impl Streams { } } } - ready.sort_by_cached_key(|(_, stream, _)| std::cmp::Reverse(stream.pending_conversion_bytes())); + // Rotate every writer before inventorying source bytes. Keep the + // estimate for admission so the scheduler lists each stream once. + let mut ready: Vec<_> = ready.into_iter().map(|(tenant, stream, recovery)| { + (stream.pending_conversion_bytes(), tenant, stream, recovery) + }).collect(); + ready.sort_by_key(|(bytes, ..)| std::cmp::Reverse(*bytes)); (ready, failure) }) .await .map_err(std::io::Error::other)?; let mut completions = Vec::with_capacity(ready.len()); - for (tenant, stream, recovery) in ready { + for (bytes, tenant, stream, recovery) in ready { + let permit = CONVERSION_MEMORY_BUDGET.acquire(bytes).await; let (tx, rx) = tokio::sync::oneshot::channel(); LOG_CONVERSION_THREADPOOL.spawn_fifo(move || { + let _permit = permit; let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { stream.convert_flushed(shutdown_signal, &tenant, recovery) })) @@ -5987,6 +6108,121 @@ mod log_parquet_pipeline_tests { assert!(timestamps.values().windows(2).all(|pair| pair[0] > pair[1])); } + #[test] + fn parquet_writer_uses_typed_dictionary_fallbacks_and_zstd_level() { + // Read the real environment through the writer without changing the + // compression setting for other tests running in this process. + const CHILD: &str = "PARSEABLE_TEST_ZSTD_WRITER"; + if std::env::var_os(CHILD).is_none() { + let name = format!( + "{}::parquet_writer_uses_typed_dictionary_fallbacks_and_zstd_level", + module_path!().split_once("::").unwrap().1, + ); + let result = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", &name, "--nocapture"]) + .env(CHILD, "1") + .env("P_PARQUET_ZSTD_LEVEL", "7") + .output() + .unwrap(); + assert!( + result.status.success() + && String::from_utf8_lossy(&result.stdout).contains("1 passed"), + "{}\n{}", + String::from_utf8_lossy(&result.stdout), + String::from_utf8_lossy(&result.stderr) + ); + return; + } + + let dir = TempDir::new().unwrap(); + let stream = log_stream( + &dir, + "encodings", + Options { + row_group_size: 262_144, + parquet_compression: crate::option::Compression::Zstd, + ..Default::default() + }, + ); + let mut fields = log_schema(true).fields().to_vec(); + fields.extend([ + Arc::new(Field::new("large", DataType::LargeUtf8, true)), + Arc::new(Field::new( + "event_time", + DataType::Timestamp(TimeUnit::Nanosecond, None), + true, + )), + ]); + let props = stream.parquet_writer_props( + &Schema::new(fields), + None, + Some(&"region".to_owned()), + false, + ); + assert_eq!(props.dictionary_page_size_limit(), 128 * 1024); + assert_eq!(props.max_row_group_row_count(), Some(262_144)); + assert_eq!(props.writer_version(), WriterVersion::PARQUET_1_0); + assert!(!props.offset_index_disabled()); + for (parts, encoding) in [ + (vec!["message"], Encoding::DELTA_LENGTH_BYTE_ARRAY), + (vec!["large"], Encoding::DELTA_LENGTH_BYTE_ARRAY), + (vec!["attrs", "label"], Encoding::DELTA_LENGTH_BYTE_ARRAY), + ( + vec!["tags", "list", "item"], + Encoding::DELTA_LENGTH_BYTE_ARRAY, + ), + (vec!["region"], Encoding::DELTA_BYTE_ARRAY), + (vec![DEFAULT_TIMESTAMP_KEY], Encoding::DELTA_BINARY_PACKED), + (vec!["event_time"], Encoding::DELTA_BINARY_PACKED), + ] { + let path = ColumnPath::new(parts.into_iter().map(str::to_owned).collect()); + assert_eq!(props.encoding(&path), Some(encoding), "{path}"); + assert!(props.dictionary_enabled(&path)); + assert_eq!( + props.statistics_enabled(&path), + parquet::file::properties::EnabledStatistics::Page + ); + assert_eq!( + props.compression(&path), + parquet::basic::Compression::ZSTD(parquet::basic::ZstdLevel::try_new(7).unwrap()) + ); + } + } + + #[tokio::test] + async fn conversion_admission_bounds_concurrency_and_runs_oversized_streams_alone() { + const MIB: u64 = 1024 * 1024; + let budget = ConversionMemoryBudget::new(256 * MIB); + let first = budget.acquire(32 * MIB).await; + let second = budget.acquire(16 * MIB).await; + assert_eq!(budget.semaphore.available_permits(), 64 * MIB as usize); + let third = budget.acquire(32 * MIB); + tokio::pin!(third); + assert!(futures::poll!(&mut third).is_pending()); + drop(second); + let third = tokio::time::timeout(Duration::from_secs(1), third) + .await + .unwrap(); + assert_eq!(budget.semaphore.available_permits(), 0); + + let oversized = budget.acquire(u64::MAX); + tokio::pin!(oversized); + drop(first); + assert!(futures::poll!(&mut oversized).is_pending()); + drop(third); + let exclusive = tokio::time::timeout(Duration::from_secs(1), oversized) + .await + .unwrap(); + assert_eq!(budget.semaphore.available_permits(), 0); + drop(exclusive); + assert_eq!(budget.semaphore.available_permits(), 256 * MIB as usize); + + // Coarser units also work for budgets above Tokio's acquire_many limit. + let large = ConversionMemoryBudget::new(u64::MAX); + let _exclusive = large.acquire(u64::MAX).await; + assert_eq!(large.semaphore.available_permits(), 0); + } + #[test] fn log_pipeline_knobs_have_bounded_defaults() { assert_eq!(log_row_group_encode_in_flight(None), 2); @@ -6558,13 +6794,13 @@ mod log_parquet_pipeline_tests { #[test] fn log_conversion_collects_field_stats_of_every_batch_in_order() { let dir = TempDir::new().unwrap(); - let files = stage_arrow_files(&dir, 3, 2, 1500); + let files = stage_arrow_files(&dir, 3, 2, 150); let staging = log_stream( &dir, "log-pipeline-stats", Options { // Row groups cut batches apart; statistics must not notice. - row_group_size: 1100, + row_group_size: 90, row_group_bytes: 96 * 1024, collect_dataset_stats: true, max_field_statistics: 5, @@ -6597,7 +6833,7 @@ mod log_parquet_pipeline_tests { &dir, "log-pipeline-no-stats", Options { - row_group_size: 1100, + row_group_size: 90, collect_dataset_stats: false, ..Default::default() }, @@ -6610,6 +6846,37 @@ mod log_parquet_pipeline_tests { assert!(artifacts.field_stats.is_none()); } + #[test] + fn unclustered_conversion_defers_over_budget_inline_stats() { + let dir = TempDir::new().unwrap(); + let files = stage_arrow_files(&dir, 1, 2, 600); + let schema = Arc::new(reader(&files).merged_schema().unwrap()); + // Exercise both the parallel pipeline and the wide-row sequential fallback. + for row_group_size in [256, 100_000_000] { + let staging = log_stream( + &dir, + "deferred-stats", + Options { + row_group_size, + row_group_bytes: 0, + collect_dataset_stats: true, + max_field_statistics: 5, + ..Default::default() + }, + ); + let props = staging.parquet_writer_props(&schema, None, None, false); + let path = dir + .path() + .join(format!("stats-{row_group_size}.parquet.part")); + let artifacts = staging + .write_parquet_part_file(&path, reader(&files), &schema, &props, None, None) + .unwrap() + .unwrap(); + assert!(artifacts.field_stats.is_none()); + assert_eq!(read_parquet(&path).num_rows(), 1200); + } + } + #[test] fn log_conversion_of_no_rows_writes_no_file() { let dir = TempDir::new().unwrap(); diff --git a/src/parseable/streams/log_clustering.rs b/src/parseable/streams/log_clustering.rs index 4aea587db..430b68b2b 100644 --- a/src/parseable/streams/log_clustering.rs +++ b/src/parseable/streams/log_clustering.rs @@ -21,7 +21,7 @@ //! When `P_LOG_SEVERITY_CLUSTER_COLUMN` is set, the log conversion path //! buffers exactly one row group of rows (the same rows the unclustered //! writer would have placed in that row group), computes a stable order by -//! `(cluster column ASC NULLS LAST, time column DESC NULLS LAST)` and writes +//! `(cluster columns ASC NULLS LAST, time column DESC NULLS LAST)` and writes //! the rows in that order, gathered in small batches from the buffer. Row-group membership, and therefore row-group time ranges, //! are unchanged; only the order of rows inside each row group differs. //! Pages of a selective severity value then become contiguous, which lets @@ -138,9 +138,9 @@ impl Default for ClusterMemoryLimits { } /// Column positions in the merged conversion schema used to cluster one file. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq)] pub(super) struct LogClusterKey { - pub(super) cluster_idx: usize, + pub(super) cluster_indices: Vec, pub(super) time_idx: Option, } @@ -178,9 +178,12 @@ pub(super) fn stream_is_applicable( /// Types whose physical order is cheap to compute and meaningful for /// equality predicates: strings (including dictionary/view encodings) -/// and integers such as OTel `severity_number`. -fn is_supported_cluster_type(data_type: &DataType) -> bool { +/// and integers such as OTel `severity_number`, plus Booleans in composite keys. +fn is_supported_cluster_type(data_type: &DataType, composite: bool) -> bool { match data_type { + // Legacy single-column candidates skip Booleans, including when a + // later fallback is present. + DataType::Boolean => composite, DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View => true, DataType::Int8 | DataType::Int16 @@ -200,55 +203,53 @@ fn is_supported_cluster_type(data_type: &DataType) -> bool { } } -/// Selects the first present, supported candidate in one output's merged schema. -/// Startup validation supplies a normalized comma-separated list. +/// Commas separate fallback candidates. A candidate joined with `+` requires +/// every component in this output's merged schema, in the configured order. pub(super) fn resolve_cluster_key( configured_column: Option<&str>, applicable: bool, merged_schema: &Schema, time_partition: Option<&str>, ) -> Result { - let Some(column) = configured_column else { - return Err(LogClusterSkip::Disabled); - }; + let column = configured_column.ok_or(LogClusterSkip::Disabled)?; if !applicable { return Err(LogClusterSkip::NotApplicable); } let mut skipped = LogClusterSkip::MissingColumn; - let mut selected = None; - for candidate in column.split(',') { - let Ok(index) = merged_schema.index_of(candidate) else { - continue; - }; - let data_type = merged_schema.field(index).data_type(); - if !is_supported_cluster_type(data_type) { - tracing::warn!( - column = candidate, - %data_type, - "Log severity clustering candidate skipped: unsupported column type" - ); - skipped = LogClusterSkip::UnsupportedType(data_type.clone()); - continue; + 'candidates: for candidate in column.split(',') { + let composite = candidate.contains('+'); + let mut cluster_indices = Vec::new(); + for name in candidate.split('+') { + let Ok(index) = merged_schema.index_of(name) else { + continue 'candidates; + }; + let data_type = merged_schema.field(index).data_type(); + if !is_supported_cluster_type(data_type, composite) { + tracing::warn!( + column = name, + %data_type, + "Log severity clustering candidate skipped: unsupported column type" + ); + skipped = LogClusterSkip::UnsupportedType(data_type.clone()); + continue 'candidates; + } + cluster_indices.push(index); } - selected = Some(index); - break; - } - let cluster_idx = selected.ok_or(skipped)?; - let time_field = time_partition.unwrap_or(DEFAULT_TIMESTAMP_KEY); - let time_idx = merged_schema - .index_of(time_field) - .ok() - .filter(|idx| *idx != cluster_idx) - .filter(|idx| { - matches!( - merged_schema.field(*idx).data_type(), - DataType::Timestamp(_, _) - ) + let time_idx = merged_schema + .index_of(time_partition.unwrap_or(DEFAULT_TIMESTAMP_KEY)) + .ok() + .filter(|&idx| { + matches!( + merged_schema.field(idx).data_type(), + DataType::Timestamp(_, _) + ) + }); + return Ok(LogClusterKey { + cluster_indices, + time_idx, }); - Ok(LogClusterKey { - cluster_idx, - time_idx, - }) + } + Err(skipped) } /// Rows per reordered batch handed to the Parquet writer. A multiple of the @@ -256,13 +257,13 @@ pub(super) fn resolve_cluster_key( /// the whole reordered row group at once. pub(super) const CLUSTER_OUTPUT_BATCH_ROWS: usize = 8192; -/// Stable row permutation for `(cluster ASC NULLS LAST, time DESC NULLS LAST)` -/// over the concatenation of `buffer`. Only the (at most two) key columns are -/// concatenated. Returns `None` when the rows are already in that order. +/// Stable row permutation for the cluster columns ascending, then time descending, +/// with nulls last throughout. Only the key columns are concatenated. Returns +/// `None` when the rows are already in that order. fn cluster_indices( buffer: &[RecordBatch], rows_len: usize, - key: LogClusterKey, + key: &LogClusterKey, ) -> Result>, ArrowError> { if rows_len < 2 { return Ok(None); @@ -279,24 +280,24 @@ fn cluster_indices( let parts: Vec<&dyn Array> = buffer.iter().map(|b| b.column(idx).as_ref()).collect(); concat(&parts) }; - let mut arrays: Vec = vec![key_column(key.cluster_idx)?]; - let mut fields = vec![SortField::new_with_options( - arrays[0].data_type().clone(), - SortOptions { - descending: false, - nulls_first: false, - }, - )]; - if let Some(time_idx) = key.time_idx { - let time = key_column(time_idx)?; + let mut arrays = + Vec::with_capacity(key.cluster_indices.len() + usize::from(key.time_idx.is_some())); + let mut fields = Vec::with_capacity(arrays.capacity()); + for (idx, descending) in key + .cluster_indices + .iter() + .map(|&idx| (idx, false)) + .chain(key.time_idx.map(|idx| (idx, true))) + { + let array = key_column(idx)?; fields.push(SortField::new_with_options( - time.data_type().clone(), + array.data_type().clone(), SortOptions { - descending: true, + descending, nulls_first: false, }, )); - arrays.push(time); + arrays.push(array); } let converter = RowConverter::new(fields)?; let rows = converter.convert_columns(&arrays)?; @@ -324,7 +325,7 @@ fn cluster_indices( /// Returns the time spent ordering and gathering rows (excluding `emit`). pub(super) fn cluster_row_group_into( buffer: Vec, - key: LogClusterKey, + key: &LogClusterKey, output_rows: usize, mut emit: impl FnMut(RecordBatch) -> Result<(), StagingError>, ) -> Result { @@ -379,7 +380,7 @@ pub(super) fn cluster_row_group_into( pub(super) fn cluster_row_group( schema: &Arc, buffer: Vec, - key: LogClusterKey, + key: &LogClusterKey, ) -> Result { let mut out = Vec::new(); cluster_row_group_into(buffer, key, CLUSTER_OUTPUT_BATCH_ROWS, |batch| { @@ -437,7 +438,7 @@ pub(super) fn write_clustered_log_parquet( schema: &Arc, props: &WriterProperties, target_rows: usize, - key: LogClusterKey, + key: &LogClusterKey, ) -> Result { // Finished batches have every column of the merged schema. let records = records.map(|record| { @@ -470,7 +471,7 @@ fn write_clustered_log_parquet_sequential( props: &WriterProperties, target_rows: usize, max_bytes: usize, - key: LogClusterKey, + key: &LogClusterKey, ) -> Result<(ParquetMetaData, LogClusterWriteStats), StagingError> { if target_rows == 0 { return Err(zero_target_error()); @@ -601,7 +602,7 @@ pub(super) fn write_clustered_log_parquet_on_pool( schema: &Arc, props: &WriterProperties, target_rows: usize, - key: LogClusterKey, + key: &LogClusterKey, in_flight: usize, stats: Option, part_path: &std::path::Path, @@ -632,7 +633,7 @@ pub(super) fn write_clustered_log_parquet_on_pool_with_limits( schema: &Arc, props: &WriterProperties, target_rows: usize, - key: LogClusterKey, + key: &LogClusterKey, in_flight: usize, stats: Option, part_path: &std::path::Path, @@ -828,7 +829,7 @@ pub(super) fn write_clustered_decoded_sequential( schema: &Arc, props: &WriterProperties, target_rows: usize, - key: LogClusterKey, + key: &LogClusterKey, stats: Option, limits: ClusterMemoryLimits, ) -> Result { @@ -942,7 +943,7 @@ impl ClusteredRowGroupPlan { fn new( mut buffer: Vec, rows: usize, - key: LogClusterKey, + key: &LogClusterKey, ) -> Result { buffer.retain(|batch| batch.num_rows() > 0); let Some(indices) = cluster_indices(&buffer, rows, key)? else { @@ -1032,7 +1033,7 @@ struct ClusteredRowGroupEncoder<'a> { /// Parquet leaf columns under each Arrow field, in field order. leaves_per_field: &'a [usize], columns_per_task: usize, - key: LogClusterKey, + key: &'a LogClusterKey, /// The writer's limits, which `ArrowWriter` applies to every batch. max_rows: Option, max_bytes: Option, @@ -1369,3 +1370,124 @@ impl SplitRowGroupWriter<'_> { Ok(()) } } + +#[cfg(test)] +mod composite_tests { + use super::*; + use arrow_array::{ + BooleanArray, Int32Array, StringArray, TimestampMillisecondArray, UInt32Array, + }; + use arrow_schema::{Field, TimeUnit}; + + #[test] + fn composite_order_is_stable_across_batches_and_preserves_every_row() { + let schema = Arc::new(Schema::new(vec![ + Field::new("level", DataType::Utf8, true), + Field::new("app", DataType::Utf8, true), + Field::new( + DEFAULT_TIMESTAMP_KEY, + DataType::Timestamp(TimeUnit::Millisecond, None), + true, + ), + Field::new("id", DataType::Int32, false), + ])); + let batch = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(StringArray::from(vec![ + Some("info"), + Some("error"), + Some("error"), + Some("error"), + Some("error"), + Some("error"), + None, + Some("error"), + Some("info"), + ])), + Arc::new(StringArray::from(vec![ + Some("a"), + Some("b"), + Some("a"), + Some("a"), + Some("a"), + None, + Some("a"), + Some("a"), + Some("a"), + ])), + Arc::new(TimestampMillisecondArray::from(vec![ + Some(4), + Some(99), + Some(2), + Some(9), + Some(9), + Some(10), + Some(50), + None, + Some(7), + ])), + Arc::new(Int32Array::from_iter_values(0..9)), + ], + ) + .unwrap(); + let key = resolve_cluster_key(Some("level+app"), true, &schema, None).unwrap(); + let actual = + cluster_row_group(&schema, vec![batch.slice(0, 4), batch.slice(4, 5)], &key).unwrap(); + // Includes null primary, secondary and time keys and an exact tie + // spanning the two input batches (ids 3 and 4). + let order = UInt32Array::from(vec![3, 4, 2, 7, 1, 5, 8, 0, 6]); + let expected: Vec<_> = batch + .columns() + .iter() + .map(|c| arrow::compute::take(c, &order, None).unwrap()) + .collect(); + assert_eq!( + actual, + RecordBatch::try_new(schema.clone(), expected).unwrap() + ); + + assert_eq!( + resolve_cluster_key(Some("level+absent,app"), true, &schema, None) + .unwrap() + .cluster_indices, + vec![1] + ); + assert_eq!( + resolve_cluster_key(Some("level,app"), true, &schema, None) + .unwrap() + .cluster_indices, + vec![0] + ); + assert_eq!( + resolve_cluster_key(Some("level+absent"), true, &schema, None), + Err(LogClusterSkip::MissingColumn) + ); + } + + #[test] + fn boolean_and_integer_composite_keys_sort_nulls_last() { + let batch = RecordBatch::try_from_iter(vec![ + ( + "flag", + Arc::new(BooleanArray::from(vec![ + Some(true), + None, + Some(false), + Some(false), + ])) as ArrayRef, + ), + ( + "priority", + Arc::new(Int32Array::from(vec![Some(1), Some(-1), None, Some(8)])) as ArrayRef, + ), + ]) + .unwrap(); + let key = + resolve_cluster_key(Some("flag+priority"), true, batch.schema_ref(), None).unwrap(); + assert_eq!( + cluster_indices(&[batch], 4, &key).unwrap(), + Some(vec![3, 2, 0, 1]) + ); + } +} diff --git a/src/parseable/streams/log_clustering_tests.rs b/src/parseable/streams/log_clustering_tests.rs index 289ba450f..c3c4bad09 100644 --- a/src/parseable/streams/log_clustering_tests.rs +++ b/src/parseable/streams/log_clustering_tests.rs @@ -403,10 +403,10 @@ fn clustering_ties_keep_writer_order() { ) .unwrap(); let key = LogClusterKey { - cluster_idx: 2, + cluster_indices: vec![2], time_idx: Some(0), }; - let clustered = cluster_row_group(&schema, vec![batch.slice(0, 4), batch.slice(4, 2)], key) + let clustered = cluster_row_group(&schema, vec![batch.slice(0, 4), batch.slice(4, 2)], &key) .expect("cluster"); let ids = clustered .column(1) @@ -431,7 +431,7 @@ fn clustering_ties_keep_writer_order() { ], ) .unwrap(); - let clustered = cluster_row_group(&schema, vec![batch], key).unwrap(); + let clustered = cluster_row_group(&schema, vec![batch], &key).unwrap(); let ids = clustered .column(1) .as_any() @@ -445,10 +445,10 @@ fn already_clustered_or_tiny_groups_are_returned_unchanged() { let schema = log_schema(); let batch = requests(&schema, 1).remove(0); let key = LogClusterKey { - cluster_idx: 2, + cluster_indices: vec![2], time_idx: Some(0), }; - let one = cluster_row_group(&schema, vec![batch.clone()], key).unwrap(); + let one = cluster_row_group(&schema, vec![batch.clone()], &key).unwrap(); assert_eq!(one, batch); } @@ -494,7 +494,7 @@ fn integer_and_dictionary_columns_cluster() { ], ) .unwrap(); - let ids = |key| { + let ids = |key: &LogClusterKey| { let batch = cluster_row_group(&schema, vec![batch.clone()], key).unwrap(); batch .column(1) @@ -509,7 +509,7 @@ fn integer_and_dictionary_columns_cluster() { ("level", vec![1, 3, 4, 0, 2]), ] { let key = resolve_cluster_key(Some(column), true, &schema, None).unwrap(); - assert_eq!(ids(key), expected, "{column}"); + assert_eq!(ids(&key), expected, "{column}"); } } @@ -563,7 +563,7 @@ fn resolve_cluster_key_cases() { assert_eq!( resolve_cluster_key(Some(column), true, &schema, None), Ok(LogClusterKey { - cluster_idx: index, + cluster_indices: vec![index], time_idx: Some(0) }) ); @@ -578,7 +578,7 @@ fn resolve_cluster_key_cases() { assert_eq!( resolve_cluster_key(Some(candidates), true, &schema, None), Ok(LogClusterKey { - cluster_idx: index, + cluster_indices: vec![index], time_idx: Some(0) }), "{candidates}" @@ -592,7 +592,7 @@ fn resolve_cluster_key_cases() { assert_eq!( resolve_cluster_key(Some(SEVERITY), true, &schema, Some("event_time")), Ok(LogClusterKey { - cluster_idx: 1, + cluster_indices: vec![1], time_idx: Some(7) }) ); @@ -601,7 +601,7 @@ fn resolve_cluster_key_cases() { assert_eq!( resolve_cluster_key(Some(SEVERITY), true, &schema, Some(time_partition)), Ok(LogClusterKey { - cluster_idx: 1, + cluster_indices: vec![1], time_idx: None }) ); @@ -1005,8 +1005,8 @@ fn zero_row_group_target_is_rejected() { &schema, &WriterProperties::builder().build(), 0, - LogClusterKey { - cluster_idx: 2, + &LogClusterKey { + cluster_indices: vec![2], time_idx: Some(0), }, ) @@ -1105,7 +1105,7 @@ fn reference_cluster(schema: &Arc, slices: &[RecordBatch]) -> RecordBatc fn interleaved_batches_match_reference_order() { let schema = log_schema(); let key = LogClusterKey { - cluster_idx: 2, + cluster_indices: vec![2], time_idx: Some(0), }; // Uneven slices, as the row-group buffer receives them from requests. @@ -1113,7 +1113,7 @@ fn interleaved_batches_match_reference_order() { let expected = reference_cluster(&schema, &slices); for output_rows in [1, 3, 64, 999, 1000, 8192] { let mut out = Vec::new(); - log_clustering::cluster_row_group_into(slices.clone(), key, output_rows, |batch| { + log_clustering::cluster_row_group_into(slices.clone(), &key, output_rows, |batch| { out.push(batch); Ok(()) }) @@ -1128,7 +1128,7 @@ fn interleaved_batches_match_reference_order() { let ordered = expected.clone(); let ordered_slices = vec![ordered.slice(0, 400), ordered.slice(400, 600)]; let mut out = Vec::new(); - log_clustering::cluster_row_group_into(ordered_slices.clone(), key, 64, |batch| { + log_clustering::cluster_row_group_into(ordered_slices.clone(), &key, 64, |batch| { out.push(batch); Ok(()) }) @@ -1177,7 +1177,7 @@ fn chunked_writer_matches_single_batch_write_bytes() { .set_max_row_group_row_count(Some(TARGET)) .build(); let key = LogClusterKey { - cluster_idx: 2, + cluster_indices: vec![2], time_idx: Some(0), }; let dir = TempDir::new().unwrap(); @@ -1188,7 +1188,7 @@ fn chunked_writer_matches_single_batch_write_bytes() { &schema, &props, TARGET, - key, + &key, ) .unwrap(); assert_eq!((stats.rows, stats.row_groups), (BIG_ROWS, 2)); @@ -1377,7 +1377,7 @@ fn sequential_clustered_bytes( schema, props, target_rows, - severity_key(schema), + &severity_key(schema), ) .unwrap(); out @@ -1403,7 +1403,7 @@ fn parallel_clustered( schema, props, target_rows, - severity_key(schema), + &severity_key(schema), in_flight, stats, Path::new("unregistered-clustered-part"), @@ -1565,7 +1565,7 @@ fn parallel_clustered_writer_matches_sequential_bytes() { &schema, &WriterProperties::builder().build(), 0, - severity_key(&schema), + &severity_key(&schema), 2, None, Path::new("unregistered-clustered-part"), @@ -1620,7 +1620,7 @@ fn parallel_clustered_writer_completes_on_one_and_two_thread_pools() { &schema, &props, None, - key, + &key, // Tracks every one of the 2,400 values of a field, so // the counts stay exact and are kept. Some(10_000), @@ -1675,7 +1675,7 @@ fn clustered_conversion_collects_field_stats_inline() { &schema, &props, None, - Some(key), + Some(&key), ) .unwrap() .unwrap(); @@ -1784,7 +1784,7 @@ fn clustered_conversion_collects_field_stats_inline() { &schema, &props, None, - Some(key), + Some(&key), ) .unwrap() .unwrap(); @@ -1962,7 +1962,7 @@ fn parallel_clustered_with_limits( schema, props, target_rows, - severity_key(schema), + &severity_key(schema), in_flight, stats, Path::new("unregistered-clustered-part"), @@ -1991,7 +1991,7 @@ fn sequential_decoded_with_limits( schema, props, target_rows, - severity_key(schema), + &severity_key(schema), stats, limits, ) @@ -2285,7 +2285,7 @@ fn inline_clustered_stats_are_dropped_when_approximate_or_over_budget() { &many_schema, &stream.parquet_writer_props(&many_schema, None, None, true), None, - Some(severity_key(&many_schema)), + Some(&severity_key(&many_schema)), ) .unwrap() .unwrap(); diff --git a/src/storage/field_stats.rs b/src/storage/field_stats.rs index 74a1a1c87..adbfbfb65 100644 --- a/src/storage/field_stats.rs +++ b/src/storage/field_stats.rs @@ -72,9 +72,9 @@ use arrow_schema::TimeUnit; use chrono::DateTime; use chrono::NaiveDateTime; use chrono::Utc; -use dashmap::DashMap; use indexmap::IndexMap; use once_cell::sync::Lazy; +use parking_lot::Mutex; use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder; use rayon::prelude::*; use rayon::{ThreadPool, ThreadPoolBuilder}; @@ -162,7 +162,7 @@ pub struct FieldStat { pub distinct_stats: Vec, } -const MAX_STAGED_FIELD_STATS_CACHE_ENTRIES: usize = 512; +const MAX_STAGED_FIELD_STATS_CACHE_ENTRIES: usize = 4096; const STAGED_FIELD_STATS_CACHE_TTL: Duration = Duration::from_secs(900); /// Approximate bytes of tracked distinct values an inline @@ -185,31 +185,86 @@ const TRACKED_VALUE_OVERHEAD_BYTES: usize = struct CachedFieldStats { max_field_statistics: usize, stats: Vec, - /// Approximate heap bytes of `stats`, see [`field_stats_bytes`]. + /// Heap bytes charged for this entry, including its key and headers. bytes: usize, inserted_at: Instant, } -/// Approximate heap bytes retained by finished statistics. -fn field_stats_bytes(stats: &[FieldStat]) -> usize { - stats - .iter() - .map(|stat| { - std::mem::size_of::() - + stat.field_name.len() - + stat - .distinct_stats - .iter() - .map(|distinct| { - std::mem::size_of::() + distinct.distinct_value.len() - }) - .sum::() - }) - .sum() +/// Heap allocations owned by the finished statistics, including unused capacity. +fn field_stats_bytes(stats: &Vec) -> usize { + stats.capacity() * size_of::() + + stats + .iter() + .map(|stat| { + stat.field_name.capacity() + + stat.distinct_stats.capacity() * size_of::() + + stat + .distinct_stats + .iter() + .map(|value| value.distinct_value.capacity()) + .sum::() + }) + .sum::() } -static STAGED_FIELD_STATS_CACHE: LazyLock> = - LazyLock::new(DashMap::new); +#[derive(Default)] +struct StagedFieldStatsCache { + // Oldest first. Removing and reinserting a path resets its age. + entries: IndexMap, + bytes: usize, +} + +impl StagedFieldStatsCache { + fn remove(&mut self, path: &Path) -> Option { + let entry = self.entries.shift_remove(path)?; + self.bytes -= entry.bytes; + Some(entry) + } + + fn insert( + &mut self, + path: &Path, + max_field_statistics: usize, + stats: Vec, + bytes: usize, + ) { + self.remove(path); + if bytes > MAX_INLINE_FIELD_STATS_BYTES { + debug!(path = %path.display(), bytes, "Not caching staged field statistics over the inline byte budget"); + return; + } + let bytes = bytes + path.as_os_str().len() + size_of::<(PathBuf, CachedFieldStats)>(); + if bytes > MAX_STAGED_FIELD_STATS_CACHE_BYTES { + return; + } + let now = Instant::now(); + let mut evict = 0; + for entry in self.entries.values() { + if self.bytes + bytes <= MAX_STAGED_FIELD_STATS_CACHE_BYTES + && self.entries.len() - evict < MAX_STAGED_FIELD_STATS_CACHE_ENTRIES + && now.duration_since(entry.inserted_at) < STAGED_FIELD_STATS_CACHE_TTL + { + break; + } + self.bytes -= entry.bytes; + evict += 1; + } + self.entries.drain(..evict); + self.entries.insert( + path.to_owned(), + CachedFieldStats { + max_field_statistics, + stats, + bytes, + inserted_at: now, + }, + ); + self.bytes += bytes; + } +} + +static STAGED_FIELD_STATS_CACHE: LazyLock> = + LazyLock::new(Default::default); /// Caches precomputed per-field statistics for a newly staged Parquet file so /// post-upload field stats publication can consume them in memory without @@ -221,94 +276,15 @@ static STAGED_FIELD_STATS_CACHE: LazyLock> = /// together stay within `MAX_STAGED_FIELD_STATS_CACHE_BYTES`. pub fn cache_staged_field_stats(path: &Path, max_field_statistics: usize, stats: Vec) { let bytes = field_stats_bytes(&stats); - // Replacing an entry never keeps the old statistics. - STAGED_FIELD_STATS_CACHE.remove(path); - if bytes > MAX_INLINE_FIELD_STATS_BYTES { - debug!( - path = %path.display(), - bytes, - "Not caching staged field statistics over the inline byte budget" - ); - return; - } - let now = Instant::now(); - evict_staged_field_stats_over_bytes(MAX_STAGED_FIELD_STATS_CACHE_BYTES.saturating_sub(bytes)); - if STAGED_FIELD_STATS_CACHE.len() >= MAX_STAGED_FIELD_STATS_CACHE_ENTRIES { - STAGED_FIELD_STATS_CACHE.retain(|_, entry| { - now.duration_since(entry.inserted_at) < STAGED_FIELD_STATS_CACHE_TTL - }); - let mut attempts = 0usize; - while STAGED_FIELD_STATS_CACHE.len() >= MAX_STAGED_FIELD_STATS_CACHE_ENTRIES && attempts < 8 - { - attempts += 1; - let mut oldest: Option<(Instant, PathBuf)> = None; - for entry in STAGED_FIELD_STATS_CACHE.iter() { - let ts = entry.value().inserted_at; - if oldest.as_ref().is_none_or(|(min_ts, _)| ts < *min_ts) { - oldest = Some((ts, entry.key().clone())); - } - } - let Some((_, key)) = oldest else { - break; - }; - STAGED_FIELD_STATS_CACHE.remove(&key); - } - } - STAGED_FIELD_STATS_CACHE.insert( - path.to_path_buf(), - CachedFieldStats { - max_field_statistics, - stats, - bytes, - inserted_at: now, - }, - ); -} - -/// Evicts expired, then oldest, staged statistics until the entries hold at -/// most `max_bytes` approximate bytes together. -fn evict_staged_field_stats_over_bytes(max_bytes: usize) { - let total = || { - STAGED_FIELD_STATS_CACHE - .iter() - .map(|entry| entry.value().bytes) - .fold(0usize, usize::saturating_add) - }; - if total() <= max_bytes { - return; - } - let now = Instant::now(); STAGED_FIELD_STATS_CACHE - .retain(|_, entry| now.duration_since(entry.inserted_at) < STAGED_FIELD_STATS_CACHE_TTL); - let mut entries: Vec<(Instant, PathBuf, usize)> = STAGED_FIELD_STATS_CACHE - .iter() - .map(|entry| { - ( - entry.value().inserted_at, - entry.key().clone(), - entry.value().bytes, - ) - }) - .collect(); - entries.sort_by_key(|(inserted_at, _, _)| *inserted_at); - let mut held = entries - .iter() - .map(|(_, _, bytes)| *bytes) - .fold(0usize, usize::saturating_add); - for (_, path, bytes) in entries { - if held <= max_bytes { - break; - } - if STAGED_FIELD_STATS_CACHE.remove(&path).is_some() { - held = held.saturating_sub(bytes); - } - } + .lock() + .insert(path, max_field_statistics, stats, bytes); } /// Takes and removes cached field statistics for `path` if present, fresh, and computed /// with the same `max_field_statistics` bound. pub fn take_staged_field_stats(path: &Path, max_field_statistics: usize) -> Option> { - let (_, cached) = STAGED_FIELD_STATS_CACHE.remove(path)?; + let cached = STAGED_FIELD_STATS_CACHE.lock().remove(path)?; if cached.inserted_at.elapsed() < STAGED_FIELD_STATS_CACHE_TTL && cached.max_field_statistics == max_field_statistics { @@ -320,17 +296,14 @@ pub fn take_staged_field_stats(path: &Path, max_field_statistics: usize) -> Opti /// Removes any cached field statistics for `path` (e.g. when a staged file is retired). pub fn evict_staged_field_stats(path: &Path) { - STAGED_FIELD_STATS_CACHE.remove(path); + STAGED_FIELD_STATS_CACHE.lock().remove(path); } /// Clears all cached staged field statistics under memory pressure and returns /// the number of evicted entries. pub fn clear_staged_field_stats_cache() -> usize { - let len = STAGED_FIELD_STATS_CACHE.len(); - if len > 0 { - STAGED_FIELD_STATS_CACHE.clear(); - } - len + let old = std::mem::take(&mut *STAGED_FIELD_STATS_CACHE.lock()); + old.entries.len() } fn filter_field_stats_for_schema(cached: Vec, schema: &Schema) -> Vec { @@ -739,7 +712,9 @@ impl FieldStatsAccumulator { /// counted in, so they can differ from a count of the written file when /// that file's rows are in another order (such as clustered files). pub fn is_approximate(&self) -> bool { - self.field_counts.iter().any(|(_, state)| state.approximate) + self.field_counts + .iter() + .any(|(_, state)| state.hll.is_some()) } /// Approximate heap bytes of the distinct values tracked by all fields. @@ -965,12 +940,10 @@ fn accumulate_str_chunk<'a>( ordered.insert(value, count); } for (value, count) in ordered { - total.hll.add(value); total.track_value(Cow::Borrowed(value), count); } } else { for (&value, &count) in &scratch.str_counts { - total.hll.add(value); total.track_value(Cow::Borrowed(value), count); } } @@ -1065,7 +1038,6 @@ fn accumulate_native_chunk( *ordered.entry(&scratch.text_arena[start..end]).or_insert(0) += count; } for (value, count) in ordered { - total.hll.add(value); total.track_value(Cow::Borrowed(value), count); } } else { @@ -1073,7 +1045,6 @@ fn accumulate_native_chunk( scratch.format_buf.clear(); format_row(&mut scratch.format_buf, row_idx, &mut fmt_at); let text = scratch.format_buf.as_str(); - total.hll.add(text); total.track_value(Cow::Borrowed(text), count); } } @@ -1105,7 +1076,6 @@ fn accumulate_generic_chunk( } total.total_count += chunk_len as i64; for (value, count) in chunk_counts { - total.hll.add(value); total.track_value(Cow::Borrowed(value), count); } } @@ -1280,7 +1250,6 @@ fn accumulate_array_chunks<'a>( DataType::Null => { for offset in (0..len).step_by(MIN_TRACKED_DISTINCT_VALUES_PER_FIELD) { let chunk_len = (len - offset).min(MIN_TRACKED_DISTINCT_VALUES_PER_FIELD) as i64; - total.hll.add(NULL_VALUE); total.total_count += chunk_len; total.track_value(Cow::Borrowed(NULL_VALUE), chunk_len); } @@ -1366,13 +1335,12 @@ struct FieldCountState { field_name: String, total_count: i64, counts: FxHashMap, - hll: HyperLogLog, + hll: Option, max_tracked_values: usize, /// Lower bound on the smallest count currently in `counts`. Tracked counts only ever grow, so a /// stale value stays a valid lower bound. Lets `track_value` reject candidates that cannot /// possibly evict anything without paying for a linear scan of `counts`. min_count_hint: i64, - approximate: bool, log_cardinality_cap: bool, /// Approximate heap bytes of the values in `counts`. retained_bytes: usize, @@ -1399,10 +1367,9 @@ impl FieldCountState { field_name, total_count: 0, counts: FxHashMap::default(), - hll: HyperLogLog::new(), + hll: None, max_tracked_values: tracked_distinct_value_limit(max_field_statistics), min_count_hint: i64::MAX, - approximate: false, log_cardinality_cap, retained_bytes: 0, } @@ -1410,7 +1377,6 @@ impl FieldCountState { #[cfg(test)] fn record_value(&mut self, value: Cow<'_, str>) { - self.hll.add(value.as_ref()); self.total_count += 1; self.track_value(value, 1); } @@ -1418,7 +1384,6 @@ impl FieldCountState { #[cfg(test)] fn merge_counts(&mut self, counts: HashMap) { for (value, count) in counts { - self.hll.add(&value); self.total_count += count; self.track_value(Cow::Owned(value), count); } @@ -1426,16 +1391,13 @@ impl FieldCountState { #[cfg(test)] fn merge_state(&mut self, state: FieldCountState) { - self.hll.merge(&state.hll); self.total_count += state.total_count; - - if state.approximate { - self.mark_approximate(); - } - for (value, count) in state.counts { self.track_value(Cow::Owned(value), count); } + if let Some(hll) = state.hll { + self.sketch().merge(&hll); + } } fn track_value(&mut self, value: Cow<'_, str>, count: i64) { @@ -1444,6 +1406,10 @@ impl FieldCountState { return; } + if self.counts.len() >= self.max_tracked_values || self.hll.is_some() { + self.sketch().add(value.as_ref()); + } + if self.counts.len() < self.max_tracked_values { self.min_count_hint = self.min_count_hint.min(count); self.retained_bytes = self @@ -1453,8 +1419,6 @@ impl FieldCountState { return; } - self.mark_approximate(); - // `min_count_hint` is a lower bound on the smallest tracked count, so a candidate that // cannot beat the hint cannot beat the real minimum either. This short-circuits the common // high-cardinality case (every row a fresh value with count 1) before the linear scan. @@ -1477,16 +1441,21 @@ impl FieldCountState { } } - fn mark_approximate(&mut self) { - if !self.approximate { - self.approximate = true; + /// Seed the sketch before an overflow can discard the first distinct value. + fn sketch(&mut self) -> &mut HyperLogLog { + self.hll.get_or_insert_with(|| { if self.log_cardinality_cap { debug!( "Field stats cardinality cap reached for stream {} field {}. Tracking bounded top-value candidates with max_tracked_values={}", self.stream_name, self.field_name, self.max_tracked_values ); } - } + let mut hll = HyperLogLog::new(); + for value in self.counts.keys() { + hll.add(value); + } + hll + }) } fn current_min_value(&self) -> Option<(String, i64)> { @@ -1501,8 +1470,8 @@ impl FieldCountState { } fn distinct_count(&self) -> i64 { - if self.approximate { - (self.hll.estimate().round() as i64).max(self.counts.len() as i64) + if let Some(hll) = &self.hll { + (hll.estimate().round() as i64).max(self.counts.len() as i64) } else { self.counts.len() as i64 } @@ -1524,6 +1493,7 @@ impl FieldCountState { .then_with(|| left.distinct_value.cmp(&right.distinct_value)) }); distinct_stats.truncate(max_field_statistics); + distinct_stats.shrink_to_fit(); distinct_stats } } @@ -1535,6 +1505,7 @@ fn tracked_distinct_value_limit(max_field_statistics: usize) -> usize { ) } +#[derive(Debug, PartialEq, Eq)] struct HyperLogLog { registers: Vec, } @@ -2291,7 +2262,7 @@ mod tests { let (_, old) = legacy_collect_field_counts("test", &batch, field.name(), 50).unwrap(); let (_, new) = collect_field_counts("test", &batch, field.name(), 50).unwrap(); assert_eq!(old.counts, new.counts); - assert_eq!(old.hll.registers, new.hll.registers); + assert_eq!(old.hll, new.hll); } for offset in (0..n).step_by(1024) { let chunk = batch.slice(offset, (n - offset).min(1024)); @@ -2300,7 +2271,7 @@ mod tests { legacy_collect_field_counts("test", &chunk, field.name(), 50).unwrap(); let (_, new) = collect_field_counts("test", &chunk, field.name(), 50).unwrap(); assert_eq!(old.counts, new.counts); - assert_eq!(old.hll.registers, new.hll.registers); + assert_eq!(old.hll, new.hll); } } let dir = TempDir::new().unwrap(); @@ -2777,6 +2748,86 @@ mod tests { ); } + #[test] + fn lazy_sketch_matches_eager_registers_across_evictions_and_compacts_top_values() { + use super::{Cow, HyperLogLog, MIN_TRACKED_DISTINCT_VALUES_PER_FIELD}; + + let mut state = FieldCountState::new("stream".into(), "field".into(), 50); + let mut eager = HyperLogLog::new(); + let limit = MIN_TRACKED_DISTINCT_VALUES_PER_FIELD; + for id in 0..limit { + let value = format!("{id:04}"); + eager.add(&value); + state.record_value(Cow::Owned(value)); + } + state.record_value(Cow::Borrowed("0000")); + assert!(state.hll.is_none()); + assert_eq!(state.total_count, (limit + 1) as i64); + assert_eq!(state.distinct_count(), limit as i64); + assert_eq!(state.counts["0000"], 2); + + for id in limit..(3 * limit) { + let value = format!("{id:04}"); + eager.add(&value); + state.track_value(Cow::Owned(value), 1); + } + eager.add("frequent"); + state.track_value(Cow::Borrowed("frequent"), 100); + assert_eq!(state.hll.as_ref(), Some(&eager)); + assert_eq!(state.distinct_count(), eager.estimate().round() as i64); + + let top = state.into_distinct_stats(50); + assert_eq!(top.len(), 50); + assert_eq!(top.capacity(), 50); + assert_eq!( + (top[0].distinct_value.as_str(), top[0].count), + ("frequent", 100) + ); + assert_eq!((top[1].distinct_value.as_str(), top[1].count), ("0000", 2)); + assert_eq!(top[49].distinct_value, "0048"); + } + + #[test] + fn staged_cache_charges_capacity_and_evicts_the_oldest_entry() { + use super::{ + MAX_INLINE_FIELD_STATS_BYTES, MAX_STAGED_FIELD_STATS_CACHE_BYTES, + StagedFieldStatsCache, field_stats_bytes, + }; + use std::path::Path; + + let mut stats = Vec::with_capacity(8); + let mut distinct_stats = Vec::with_capacity(50); + distinct_stats.push(DistinctStat { + distinct_value: String::with_capacity(64), + count: 1, + }); + stats.push(FieldStat { + field_name: String::with_capacity(32), + count: 1, + distinct_count: 1, + distinct_stats, + }); + assert_eq!( + field_stats_bytes(&stats), + 8 * size_of::() + 50 * size_of::() + 32 + 64 + ); + + let mut cache = StagedFieldStatsCache::default(); + for key in ["a", "b", "c", "d", "e"] { + let stats = + Vec::with_capacity((MAX_INLINE_FIELD_STATS_BYTES - 1024) / size_of::()); + let bytes = field_stats_bytes(&stats); + cache.insert(Path::new(key), 50, stats, bytes); + assert!(cache.bytes <= MAX_STAGED_FIELD_STATS_CACHE_BYTES); + } + assert!(cache.remove(Path::new("a")).is_none()); + assert_eq!(cache.entries.len(), 4); + for key in ["b", "c", "d", "e"] { + assert!(cache.remove(Path::new(key)).is_some()); + } + assert_eq!(cache.bytes, 0); + } + #[test] fn test_field_count_state_caps_high_cardinality_values() { let mut state = @@ -2789,7 +2840,7 @@ mod tests { state.merge_counts(counts); } - assert!(state.approximate); + assert!(state.hll.is_some()); assert_eq!(state.total_count, 100); assert_eq!(state.counts.len(), 8); assert!(state.distinct_count() > 80); From a35d207afb813f8ae57879ea90ef718143481c61 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Tue, 1 Dec 2026 15:16:55 -0600 Subject: [PATCH 05/17] perf(memory): stream manifest codec, bound metadata caches by bytes, trim ingest buffers Cuts transient and retained memory on the ingest, sync and query-planning paths without changing what is stored or how it is read back. Manifest codec (catalog/manifest.rs) - encode_manifest compresses the JSON as serde writes it; the uncompressed JSON (15-25x the stored size) is never held whole. - encode_manifest_blocking borrows the manifest instead of taking a clone: it serializes a chunk of file entries at a time and hands each chunk to the blocking pool for zstd. Output decompresses to the JSON serde writes. - decode_manifest parses a compressed manifest through a 1 MiB window, one file entry at a time, with serde_json's slice parser. Only the layout the encoders write is taken; any other layout and every failure falls back to the previous whole-buffer decode, so results and errors are unchanged. Plain-JSON manifests are parsed exactly as before. - DECODE_PERMITS is half the cores, clamped to 2..=4. - The staged Parquet footer cache is bounded by 64 MiB of ParquetMetaData::memory_size as well as by entries, and evicts the oldest footer in O(1) instead of scanning for it. - Manifest::memory_size / File::memory_size estimate decoded size. Metadata cache (metastore/metadata_cache.rs) - Every kind of entry has a byte limit next to its entry limit: 128 MiB of decoded manifests, 32 MiB of stream JSONs, 4 MiB per listing kind. - Values are charged when their load completes. Room is made one entry at a time: entries past their TTL, then the ones filled longest ago. The drain-everything cliff at capacity is gone, slots that are still loading are the last to go, and a value over the limit by itself is kept alone. - Expired entries are dropped whenever the cache is used. - clear_metadata_cache() and evict_expired(); soft memory-pressure relief calls evict_expired(). Schema writes (metastore/metastores/document_metastore.rs) - put_schema writes nothing when the get_schema the same task made just before returned the same schema (top-level field order aside): a sync whose staged schema adds nothing no longer rewrites the schema object and no longer invalidates the stream's cached metadata. Ingest (handlers/http/ingest.rs, event/format/json.rs) - A flat body is dropped once its batch is known to be staged as built, before the request waits for its turn to stage. - JsonBytes returns a single-chunk body as that chunk, and sizes the buffer of a multi-chunk body from Content-Length (at most 2 MiB ahead). - decode_rows_direct makes a column when a row first names its field; a field no row names becomes a null column without a pre-sized builder. - Finished columns of batches of 100 rows or more give back buffer capacity beyond 25% + 4 KiB of what they use. Smaller batches are left alone, so the staging writer's size-based compression choice is the same. Allocator (main.rs) - cache_oblivious:false: no padding page on every large allocation. dirty_decay_ms and narenas are unchanged. Not compiled or run locally; unit tests are added for each area. Co-Authored-By: Claude Fable 5.2 --- src/catalog/manifest.rs | 1162 ++++++++++++++++- src/event/format/json.rs | 574 +++++++- src/handlers/http/ingest.rs | 165 ++- src/handlers/http/resource_check.rs | 32 +- src/main.rs | 23 +- src/metastore/metadata_cache.rs | 1029 +++++++++++++-- .../metastores/document_metastore.rs | 410 +++++- 7 files changed, 3192 insertions(+), 203 deletions(-) diff --git a/src/catalog/manifest.rs b/src/catalog/manifest.rs index 34c89541d..ba505237f 100644 --- a/src/catalog/manifest.rs +++ b/src/catalog/manifest.rs @@ -17,13 +17,13 @@ */ use std::{ - collections::HashMap, - path::{Path, PathBuf}, - sync::{Arc, LazyLock}, + collections::{HashMap, VecDeque}, + io::{Read, Write}, + path::Path, + sync::{Arc, LazyLock, Mutex, MutexGuard, PoisonError}, time::{Duration, Instant}, }; -use dashmap::DashMap; use parquet::{ basic::{ ConvertedType, LogicalType, SortOrder as ParquetSortOrder, TimeUnit as ParquetTimeUnit, @@ -74,13 +74,38 @@ const ZSTD_MAGIC: [u8; 4] = [0x28, 0xB5, 0x2F, 0xFD]; /// this cheap level; higher levels cost write time for very little extra. const ZSTD_LEVEL: i32 = 3; -/// Cap on manifests being decoded at once by [`decode_manifest_blocking`]. +/// JSON the serializer hands to the compressor at a time. /// -/// Decoding is CPU bound, so there is nothing to gain past the core count, and -/// each in-flight decode holds a fully decompressed manifest in memory — which -/// is two orders of magnitude larger than the compressed form. -static DECODE_PERMITS: std::sync::LazyLock> = - std::sync::LazyLock::new(|| std::sync::Arc::new(tokio::sync::Semaphore::new(num_cpus::get()))); +/// A manifest's JSON is 15-25x its stored size, so it is never held whole: +/// it is produced and compressed in pieces of about this size, and read back +/// through a window of [`DECODE_WINDOW_BYTES`]. +const ENCODE_CHUNK_BYTES: usize = 256 * 1024; + +/// Buffer between the serializer, which writes a few bytes at a time, and the +/// compressor in [`encode_manifest`]. +const ENCODE_BUFFER_BYTES: usize = 64 * 1024; + +/// Decompressed JSON a decode reads ahead of its parser. One file entry of a +/// wide stream is tens of kilobytes; an entry larger than the window grows it. +const DECODE_WINDOW_BYTES: usize = 1024 * 1024; + +/// Manifests [`decode_manifest_blocking`] decodes at once: half the cores, +/// but no fewer than two and no more than four. +/// +/// Decoding is CPU bound, and each in-flight decode holds the manifest it is +/// building, which for a large daily manifest is hundreds of megabytes. One +/// decode per core let a burst of them hold gigabytes on a large machine. +fn decode_permits(cores: Option) -> usize { + cores.map_or(4, |cores| (cores / 2).clamp(2, 4)) +} + +/// Cap on manifests being decoded at once by [`decode_manifest_blocking`]. +static DECODE_PERMITS: LazyLock> = LazyLock::new(|| { + let cores = std::thread::available_parallelism() + .ok() + .map(std::num::NonZeroUsize::get); + Arc::new(tokio::sync::Semaphore::new(decode_permits(cores))) +}); #[derive(Debug, thiserror::Error)] pub enum ManifestCodecError { @@ -100,35 +125,342 @@ pub enum ManifestCodecError { Parse(serde_json::Error), } -/// Encode a manifest for storage. This and [`decode_manifest`] are the only -/// places manifest bytes are produced or interpreted; going around them would -/// write a manifest nothing else can read. +type ManifestEncoder = zstd::stream::write::Encoder<'static, Vec>; + +fn manifest_encoder() -> Result { + zstd::stream::write::Encoder::new(Vec::new(), ZSTD_LEVEL).map_err(ManifestCodecError::Compress) +} + +/// The error of a serializer that writes into the compressor: its own, or the +/// compressor's, which it reports as an I/O error. +fn encode_error(err: serde_json::Error) -> ManifestCodecError { + if err.is_io() { + ManifestCodecError::Compress(err.into()) + } else { + ManifestCodecError::Serialize(err) + } +} + +/// Encode a manifest for storage. This, [`encode_manifest_blocking`] and +/// [`decode_manifest`] are the only places manifest bytes are produced or +/// interpreted; going around them would write a manifest nothing else can +/// read. +/// +/// The JSON is compressed as it is written, so the uncompressed form is never +/// in memory beyond a buffer. pub fn encode_manifest(manifest: &Manifest) -> Result { - let json = serde_json::to_vec(manifest).map_err(ManifestCodecError::Serialize)?; - let compressed = - zstd::encode_all(json.as_slice(), ZSTD_LEVEL).map_err(ManifestCodecError::Compress)?; + let mut writer = std::io::BufWriter::with_capacity(ENCODE_BUFFER_BYTES, manifest_encoder()?); + serde_json::to_writer(&mut writer, manifest).map_err(encode_error)?; + let encoder = writer + .into_inner() + .map_err(|err| ManifestCodecError::Compress(err.into_error()))?; + let compressed = encoder.finish().map_err(ManifestCodecError::Compress)?; Ok(bytes::Bytes::from(compressed)) } -/// Encode a manifest on the blocking pool so JSON serialization and zstd -/// compression for large daily manifests do not stall async Tokio workers. +/// Compresses `json` on the blocking pool, and returns the encoder with the +/// emptied buffer for the next chunk. +async fn compress_chunk( + encoder: Option, + mut json: Vec, +) -> Result<(ManifestEncoder, Vec), ManifestCodecError> { + tokio::task::spawn_blocking(move || { + let mut encoder = match encoder { + Some(encoder) => encoder, + None => manifest_encoder()?, + }; + encoder + .write_all(&json) + .map_err(ManifestCodecError::Compress)?; + json.clear(); + Ok::<_, ManifestCodecError>((encoder, json)) + }) + .await? +} + +/// Encode a manifest with the compression on the blocking pool, so zstd for a +/// large daily manifest does not stall async Tokio workers. +/// +/// The manifest is only borrowed. Its JSON is written here, a chunk of file +/// entries at a time, and each chunk is handed to the blocking pool, which +/// this awaits: the caller's task yields between chunks, and neither a copy +/// of the manifest nor its whole JSON is ever held. The bytes decompress to +/// exactly the JSON [`encode_manifest`] compresses. pub async fn encode_manifest_blocking( - manifest: Manifest, + manifest: &Manifest, ) -> Result { - tokio::task::spawn_blocking(move || encode_manifest(&manifest)).await? + // Every field is named, so that one added to `Manifest` has to be written + // here as the derived `Serialize` writes it. + let Manifest { version, files } = manifest; + let mut json = Vec::new(); + json.extend_from_slice(b"{\"version\":"); + serde_json::to_writer(&mut json, version).map_err(ManifestCodecError::Serialize)?; + json.extend_from_slice(b",\"files\":["); + let mut encoder = None; + for (index, file) in files.iter().enumerate() { + if index > 0 { + json.push(b','); + } + serde_json::to_writer(&mut json, file).map_err(ManifestCodecError::Serialize)?; + if json.len() >= ENCODE_CHUNK_BYTES { + let (next, emptied) = compress_chunk(encoder.take(), json).await?; + encoder = Some(next); + json = emptied; + } + } + json.extend_from_slice(b"]}"); + tokio::task::spawn_blocking(move || { + let mut encoder = match encoder { + Some(encoder) => encoder, + None => manifest_encoder()?, + }; + encoder + .write_all(&json) + .map_err(ManifestCodecError::Compress)?; + // Not needed while the last blocks are flushed + drop(json); + let compressed = encoder.finish().map_err(ManifestCodecError::Compress)?; + Ok::<_, ManifestCodecError>(bytes::Bytes::from(compressed)) + }) + .await? } /// Decode a manifest, accepting both the compressed and the plain JSON form. /// /// Existing manifests are never rewritten, so uncompressed ones stay readable /// indefinitely rather than being migrated. +/// +/// A compressed manifest is parsed as it is decompressed, one file entry at a +/// time, so its JSON is never in memory beyond a window. That path only takes +/// a manifest laid out as the encoders write it; any other compressed +/// manifest, and every one that fails to decode, is decompressed whole and +/// parsed as before, which also keeps the errors what they were. pub fn decode_manifest(bytes: &[u8]) -> Result { - if bytes.starts_with(&ZSTD_MAGIC) { - let json = zstd::decode_all(bytes).map_err(ManifestCodecError::Decompress)?; - serde_json::from_slice(&json).map_err(ManifestCodecError::Parse) + if !bytes.starts_with(&ZSTD_MAGIC) { + return serde_json::from_slice(bytes).map_err(ManifestCodecError::Parse); + } + match decode_compressed_streaming(bytes, DECODE_WINDOW_BYTES) { + Some(manifest) => Ok(manifest), + None => decode_compressed_buffered(bytes), + } +} + +/// Decompresses a manifest whole, then parses it. This is the reference +/// [`decode_compressed_streaming`] must agree with wherever it succeeds. +fn decode_compressed_buffered(bytes: &[u8]) -> Result { + let json = zstd::decode_all(bytes).map_err(ManifestCodecError::Decompress)?; + serde_json::from_slice(&json).map_err(ManifestCodecError::Parse) +} + +/// Decodes a compressed manifest through a window of about `window` bytes of +/// its JSON, without ever holding the whole of it. +/// +/// `Some` only for a stream that decompresses to its end without error into +/// exactly `{"version": , "files": [, ...]}`, with any JSON +/// whitespace between the tokens and nothing but whitespace after it. For +/// that shape the derived `Deserialize` of `Manifest` does what is done here: +/// it reads the version as a `String` and each element with `File`'s +/// `Deserialize`, from the same bytes. The one difference is that an element +/// is parsed on its own, so serde_json's nesting limit counts from the +/// element instead of from two levels above it. No manifest comes near it. +/// +/// `None` for everything else: other key orders, unknown or repeated keys, +/// values of other types, invalid JSON and broken streams. The caller then +/// decodes the manifest whole, so nothing is accepted or refused here that +/// was not before. +fn decode_compressed_streaming(bytes: &[u8], window: usize) -> Option { + let mut json = JsonWindow::new(bytes, window)?; + json.token(b'{')?; + json.literal(b"\"version\"")?; + json.token(b':')?; + let version: String = json.value(b'"')?; + json.token(b',')?; + json.literal(b"\"files\"")?; + json.token(b':')?; + json.token(b'[')?; + let mut files = Vec::new(); + if json.peek()? == b']' { + json.token(b']')?; } else { - serde_json::from_slice(bytes).map_err(ManifestCodecError::Parse) + loop { + files.push(json.value::(b'{')?); + if json.peek()? == b']' { + json.token(b']')?; + break; + } + json.token(b',')?; + } } + json.token(b'}')?; + json.end()?; + Some(Manifest { version, files }) +} + +/// The decompressed JSON of a manifest, read a window at a time. Every +/// method returns `None` to give up on the stream. +struct JsonWindow<'a> { + decoder: zstd::stream::read::Decoder<'static, &'a [u8]>, + /// Decompressed bytes; those before `pos` have been parsed. + buf: Vec, + pos: usize, + /// Bytes to read at the next refill + chunk: usize, + /// Upper bound of `chunk` + window: usize, + /// The decoder reached the end of its last frame + exhausted: bool, +} + +impl<'a> JsonWindow<'a> { + fn new(compressed: &'a [u8], window: usize) -> Option { + let window = window.max(1); + Some(Self { + decoder: zstd::stream::read::Decoder::with_buffer(compressed).ok()?, + buf: Vec::new(), + pos: 0, + // A small manifest is read in one piece of about its size, not + // into a window sized for a large one. + chunk: compressed.len().saturating_mul(32).clamp(1, window), + window, + exhausted: false, + }) + } + + /// Drops the parsed bytes and reads on behind the others, by at least + /// `at_least` bytes if the stream has them. `Some(false)` at the end of + /// the stream. + fn refill(&mut self, at_least: usize) -> Option { + if self.exhausted { + return Some(false); + } + let start = self.buf.len() - self.pos; + self.buf.copy_within(self.pos.., 0); + self.buf.truncate(start); + self.pos = 0; + let want = self.chunk.max(at_least); + self.chunk = self.chunk.saturating_mul(2).min(self.window); + self.buf.resize(start.saturating_add(want), 0); + let mut end = start; + while end < self.buf.len() { + match self.decoder.read(&mut self.buf[end..]) { + Ok(0) => { + self.exhausted = true; + break; + } + Ok(read) => end += read, + Err(err) if err.kind() == std::io::ErrorKind::Interrupted => {} + Err(_) => return None, + } + } + self.buf.truncate(end); + Some(end > start) + } + + /// The next byte that is not whitespace, left in place. `Some(None)` at + /// the end of the stream. + fn skip_whitespace(&mut self) -> Option> { + loop { + while let Some(&byte) = self.buf.get(self.pos) { + // The whitespace of JSON + if !matches!(byte, b' ' | b'\n' | b'\t' | b'\r') { + return Some(Some(byte)); + } + self.pos += 1; + } + if !self.refill(0)? { + return Some(None); + } + } + } + + /// The next byte that is not whitespace, left in place + fn peek(&mut self) -> Option { + self.skip_whitespace().flatten() + } + + /// Takes the next byte that is not whitespace, which has to be `expected` + fn token(&mut self, expected: u8) -> Option<()> { + if self.peek()? != expected { + return None; + } + self.pos += 1; + Some(()) + } + + /// Takes `expected`, after any whitespace + fn literal(&mut self, expected: &[u8]) -> Option<()> { + self.peek()?; + while self.buf.len() - self.pos < expected.len() { + if !self.refill(0)? { + return None; + } + } + if !self.buf[self.pos..].starts_with(expected) { + return None; + } + self.pos += expected.len(); + Some(()) + } + + /// Takes the JSON value after any whitespace, which has to start with + /// `first`: a `"` or a `{`, so that the value ends where its own syntax + /// says and not where the window does. + fn value(&mut self, first: u8) -> Option { + debug_assert!(matches!(first, b'"' | b'{')); + if self.peek()? != first { + return None; + } + loop { + let unparsed = &self.buf[self.pos..]; + let parsed = { + let mut values = serde_json::Deserializer::from_slice(unparsed).into_iter::(); + values.next().map(|value| (value, values.byte_offset())) + }; + match parsed { + Some((Ok(value), consumed)) => { + self.pos += consumed; + return Some(value); + } + // The window ends inside the value: read on and parse it + // again, from at least twice the bytes, so a value larger + // than the window is not parsed again for every chunk of it. + Some((Err(err), _)) if stopped_at_end(&err, unparsed) => { + let pending = unparsed.len(); + if !self.refill(pending)? { + return None; + } + } + _ => return None, + } + } + } + + /// Reads to the end of the stream, which may only hold whitespace + fn end(&mut self) -> Option<()> { + match self.skip_whitespace()? { + None => Some(()), + Some(_) => None, + } + } +} + +/// Whether serde_json gave up on `json` at its very end, as it does for a +/// value that is cut off. Most such errors are of its EOF category, but a +/// number cut after its sign or exponent mark is reported as invalid, at the +/// position this compares: the line and column of the end of the input. +fn stopped_at_end(err: &serde_json::Error, json: &[u8]) -> bool { + if err.is_eof() { + return true; + } + let line_start = json + .iter() + .rposition(|&byte| byte == b'\n') + .map_or(0, |newline| newline + 1); + let line = 1 + json[..line_start] + .iter() + .filter(|&&byte| byte == b'\n') + .count(); + err.line() == line && err.column() == json.len() - line_start } /// Decode a manifest on the blocking pool. @@ -186,7 +518,46 @@ impl Default for Manifest { } } +impl File { + /// Estimate of the bytes this entry holds in memory, its columns + /// included. Like `ParquetMetaData::memory_size`, it counts what was + /// asked of the allocator and not what the allocator adds to it. + pub fn memory_size(&self) -> usize { + std::mem::size_of::() + + self.file_path.capacity() + + self.columns.capacity() * std::mem::size_of::() + + self + .columns + .iter() + .map(|column| { + column.name.capacity() + + match &column.stats { + Some(TypedStatistics::String(stats)) => { + stats.min.capacity() + stats.max.capacity() + } + _ => 0, + } + }) + .sum::() + + self.sort_order_id.capacity() * std::mem::size_of::() + + self + .sort_order_id + .iter() + .map(|(column, _)| column.capacity()) + .sum::() + } +} + impl Manifest { + /// Estimate of the bytes a decoded manifest holds in memory: what a + /// cache of manifests is bounded by. See [`File::memory_size`]. + pub fn memory_size(&self) -> usize { + std::mem::size_of::() + + self.version.capacity() + + (self.files.capacity() - self.files.len()) * std::mem::size_of::() + + self.files.iter().map(File::memory_size).sum::() + } + pub fn apply_change(&mut self, change: File) { if let Some(pos) = self .files @@ -250,74 +621,194 @@ impl MetastoreObject for Manifest { } const MAX_PARQUET_METADATA_CACHE_ENTRIES: usize = 2048; +/// Bytes of footers kept for staged files, as `ParquetMetaData::memory_size` +/// estimates them. The footer of a wide file is megabytes, so a count alone +/// let a backlog of them hold gigabytes. +const MAX_PARQUET_METADATA_CACHE_BYTES: usize = 64 * 1024 * 1024; const PARQUET_METADATA_CACHE_TTL: Duration = Duration::from_secs(900); struct CachedParquetMetaData { metadata: Arc, inserted_at: Instant, + /// `ParquetMetaData::memory_size` of `metadata` + bytes: usize, + /// Tells this entry from an earlier one cached under the same path + sequence: u64, +} + +/// Footers of staged Parquet files by path, bounded in entries and in bytes. +/// +/// Entries leave in the order they were cached, which is also the order they +/// expire in, so making room is a pop from the front of `order` rather than a +/// scan for the oldest entry. +struct ParquetMetadataCache { + entries: HashMap, CachedParquetMetaData>, + /// Paths as they were cached, oldest first. An entry that was taken, + /// removed or replaced leaves its path here; its sequence then matches no + /// entry, and it is skipped when it reaches the front. + order: VecDeque<(u64, Arc)>, + bytes: usize, + next_sequence: u64, + max_entries: usize, + max_bytes: usize, +} + +impl ParquetMetadataCache { + fn new(max_entries: usize, max_bytes: usize) -> Self { + Self { + entries: HashMap::new(), + order: VecDeque::new(), + bytes: 0, + next_sequence: 0, + max_entries, + max_bytes, + } + } + + fn remove(&mut self, path: &Path) -> Option { + let entry = self.entries.remove(path)?; + self.bytes = self.bytes.saturating_sub(entry.bytes); + Some(entry) + } + + /// When the oldest entry was cached. Paths at the front of `order` whose + /// entry is gone are dropped on the way. + fn oldest(&mut self) -> Option { + loop { + let (sequence, path) = self.order.front()?; + let cached = self + .entries + .get::(path) + .filter(|entry| entry.sequence == *sequence) + .map(|entry| entry.inserted_at); + if cached.is_some() { + return cached; + } + drop(self.order.pop_front()); + } + } + + fn remove_oldest(&mut self) -> Option { + self.oldest()?; + let (_, path) = self.order.pop_front()?; + self.remove(&path) + } + + /// Caches `metadata` of `bytes` for `path` as of `now`, and returns the + /// entries this displaced for the caller to drop once it holds no lock: + /// an earlier one of the same path, those that expired, and the oldest + /// ones for as long as the cache is over one of its limits. + /// + /// A footer larger than the whole byte limit is not cached. It is then + /// read back from its file, like any other that is no longer here. + fn insert( + &mut self, + path: &Path, + metadata: Arc, + bytes: usize, + now: Instant, + ) -> Vec { + // The footer of an earlier file of this path is never served for + // this one, whether or not this one is cached. + let mut displaced: Vec<_> = self.remove(path).into_iter().collect(); + if bytes > self.max_bytes || self.max_entries == 0 { + return displaced; + } + while self + .oldest() + .is_some_and(|cached| now.duration_since(cached) >= PARQUET_METADATA_CACHE_TTL) + || self.entries.len() >= self.max_entries + || self.bytes.saturating_add(bytes) > self.max_bytes + { + match self.remove_oldest() { + Some(entry) => displaced.push(entry), + None => break, + } + } + let path: Arc = Arc::from(path); + let sequence = self.next_sequence; + self.next_sequence += 1; + self.order.push_back((sequence, path.clone())); + self.entries.insert( + path, + CachedParquetMetaData { + metadata, + inserted_at: now, + bytes, + sequence, + }, + ); + self.bytes += bytes; + // Paths of entries that left by `remove` are only dropped from the + // front. Staged files are cached and taken in about the same order, + // which keeps the front moving; this bounds the queue when they are + // not, at a cost spread over the removals that made it necessary. + if self.order.len() > 2 * self.entries.len() + 64 { + let entries = &self.entries; + self.order.retain(|(sequence, path)| { + entries + .get::(path) + .is_some_and(|entry| entry.sequence == *sequence) + }); + } + displaced + } + + /// Empties the cache and returns what it held + fn clear(&mut self) -> HashMap, CachedParquetMetaData> { + self.order.clear(); + self.bytes = 0; + std::mem::take(&mut self.entries) + } } -static PARQUET_METADATA_CACHE: LazyLock> = - LazyLock::new(DashMap::new); +static PARQUET_METADATA_CACHE: LazyLock> = LazyLock::new(|| { + Mutex::new(ParquetMetadataCache::new( + MAX_PARQUET_METADATA_CACHE_ENTRIES, + MAX_PARQUET_METADATA_CACHE_BYTES, + )) +}); + +/// The cache is only ever a shortcut for reading a footer back from its file, +/// so a panic while it was locked is no reason to stop using it. +fn parquet_metadata_cache() -> MutexGuard<'static, ParquetMetadataCache> { + PARQUET_METADATA_CACHE + .lock() + .unwrap_or_else(PoisonError::into_inner) +} /// Caches the `ParquetMetaData` returned by `ArrowWriter::close()` for a newly /// staged Parquet file so upload manifest creation can reuse it in memory /// without re-opening the file and re-parsing its footer. +/// +/// The cache is bounded in entries and in bytes, and makes room by dropping +/// the footers cached first. A footer that is no longer cached is read from +/// its file. pub fn cache_parquet_metadata(path: &Path, metadata: Arc) { - let now = Instant::now(); - if !PARQUET_METADATA_CACHE.contains_key(path) - && PARQUET_METADATA_CACHE.len() >= MAX_PARQUET_METADATA_CACHE_ENTRIES - { - PARQUET_METADATA_CACHE - .retain(|_, entry| now.duration_since(entry.inserted_at) < PARQUET_METADATA_CACHE_TTL); - let mut attempts = 0usize; - while PARQUET_METADATA_CACHE.len() >= MAX_PARQUET_METADATA_CACHE_ENTRIES && attempts < 8 { - attempts += 1; - let mut oldest: Option<(Instant, PathBuf)> = None; - for entry in PARQUET_METADATA_CACHE.iter() { - let ts = entry.value().inserted_at; - if oldest.as_ref().is_none_or(|(min_ts, _)| ts < *min_ts) { - oldest = Some((ts, entry.key().clone())); - } - } - let Some((_, key)) = oldest else { - break; - }; - PARQUET_METADATA_CACHE.remove(&key); - } - } - PARQUET_METADATA_CACHE.insert( - path.to_path_buf(), - CachedParquetMetaData { - metadata, - inserted_at: now, - }, - ); + // Sized before the lock is taken: it walks every column of every row group + let bytes = metadata.memory_size(); + let displaced = parquet_metadata_cache().insert(path, metadata, bytes, Instant::now()); + // Freed here, with the lock released + drop(displaced); } /// Takes and removes cached `ParquetMetaData` for a staged Parquet path, if present and fresh. pub fn take_parquet_metadata(path: &Path) -> Option> { - let (_, entry) = PARQUET_METADATA_CACHE.remove(path)?; - if entry.inserted_at.elapsed() < PARQUET_METADATA_CACHE_TTL { - Some(entry.metadata) - } else { - None - } + let entry = parquet_metadata_cache().remove(path)?; + (entry.inserted_at.elapsed() < PARQUET_METADATA_CACHE_TTL).then_some(entry.metadata) } /// Removes any cached `ParquetMetaData` for `path` (e.g. when a staged file is retired). pub fn evict_parquet_metadata(path: &Path) { - PARQUET_METADATA_CACHE.remove(path); + let removed = parquet_metadata_cache().remove(path); + drop(removed); } /// Clears all cached staged `ParquetMetaData` entries under memory pressure and /// returns the number of evicted entries. pub fn clear_parquet_metadata_cache() -> usize { - let len = PARQUET_METADATA_CACHE.len(); - if len > 0 { - PARQUET_METADATA_CACHE.clear(); - } - len + let cleared = parquet_metadata_cache().clear(); + cleared.len() } /// Builds a manifest `File` entry directly from in-memory `ParquetMetaData` and @@ -679,6 +1170,541 @@ mod codec_tests { Err(ManifestCodecError::Parse(_)) )); } + + /// A manifest with every kind of value a manifest holds: strings that + /// are escaped, numbers with signs and exponents, absent optional fields. + fn varied_manifest(file_count: usize) -> Manifest { + use crate::catalog::column::{BoolType, Float64Type, Int64Type, Utf8Type}; + + let column = |file: usize, index: usize| Column { + name: format!("col\t{index} \u{1f600}"), + stats: match (file + index) % 5 { + 0 => None, + 1 => Some(TypedStatistics::Bool(BoolType { + min: false, + max: true, + })), + 2 => Some(TypedStatistics::Int(Int64Type { + min: i64::MIN + index as i64, + max: -(file as i64), + })), + 3 => Some(TypedStatistics::Float(Float64Type { + min: -1.5e-7 * (file as f64 + 1.0), + max: 2.5e300, + })), + _ => Some(TypedStatistics::String(Utf8Type { + min: "a\\\"\u{0}".to_owned(), + max: "z\u{7f}\u{e9}\n".to_owned(), + })), + }, + null_count: (index % 2 == 0).then_some(index as u64), + uncompressed_size: 1024 + index as u64, + compressed_size: 512, + stats_provenance: (index % 3 == 0).then_some(StatsProvenance { + complete_row_groups: true, + exact_min_max: index % 2 == 0, + timestamp_unit: (index % 6 == 0).then_some(ManifestTimeUnit::Millisecond), + }), + }; + let files = (0..file_count) + .map(|file| File { + file_path: format!("tenant/a \"stream\"\\{file}/date=2026-07-29/\u{96ea}.parquet"), + num_rows: file as u64 * 7, + file_size: u64::MAX - file as u64, + ingestion_size: file as u64, + columns: (0..file % 7).map(|index| column(file, index)).collect(), + sort_order_id: if file % 3 == 0 { + vec![("ts".to_owned(), SortOrder::DescNullsLast)] + } else { + Vec::new() + }, + }) + .collect(); + Manifest { + version: CURRENT_MANIFEST_VERSION.to_string(), + files, + } + } + + fn json_of(manifest: &Manifest) -> Vec { + serde_json::to_vec(manifest).unwrap() + } + + /// A manifest as it was stored while it was compressed in one piece + fn compress(json: &[u8]) -> Vec { + zstd::encode_all(json, ZSTD_LEVEL).unwrap() + } + + fn manifests() -> Vec { + vec![ + Manifest::default(), + Manifest { + version: "a \"quoted\" \\ version\n".to_owned(), + files: Vec::new(), + }, + sample_manifest(1), + varied_manifest(1), + varied_manifest(40), + ] + } + + #[test] + fn memory_size_counts_the_entries_and_what_they_point_to() { + let empty = Manifest::default(); + assert_eq!( + empty.memory_size(), + std::mem::size_of::() + empty.version.capacity() + ); + let manifest = sample_manifest(8); + let file = &manifest.files[3]; + // The entry, its path, its columns and their names + assert!( + file.memory_size() + >= std::mem::size_of::() + + file.file_path.len() + + file.columns.len() * std::mem::size_of::() + + file + .columns + .iter() + .map(|column| column.name.len()) + .sum::() + ); + assert!( + manifest.memory_size() >= manifest.files.iter().map(File::memory_size).sum::() + ); + // More than the JSON it was decoded from would suggest is never + // charged: the estimate stays in the range of the data itself + let json = json_of(&manifest).len(); + assert!((json / 4..json * 4).contains(&manifest.memory_size())); + // Strings of statistics and sort columns are counted + let varied = varied_manifest(30); + let fixed: usize = varied + .files + .iter() + .map(|file| { + std::mem::size_of::() + + file.file_path.capacity() + + file.columns.capacity() * std::mem::size_of::() + + file + .columns + .iter() + .map(|column| column.name.capacity()) + .sum::() + }) + .sum(); + assert!(varied.memory_size() > fixed + varied.version.capacity()); + } + + #[test] + fn decode_permits_are_half_the_cores_between_two_and_four() { + for (cores, permits) in [ + (None, 4), + (Some(1), 2), + (Some(2), 2), + (Some(4), 2), + (Some(5), 2), + (Some(6), 3), + (Some(7), 3), + (Some(8), 4), + (Some(64), 4), + ] { + assert_eq!(decode_permits(cores), permits, "{cores:?}"); + } + } + + /// The stored form is still the zstd frame of the JSON serde writes, so + /// every reader of it, old or new, reads what it read before. + #[test] + fn a_manifest_is_stored_as_the_compressed_json_serde_writes() { + // Larger than the buffer between the serializer and the compressor + let large = sample_manifest(40); + assert!(json_of(&large).len() > 2 * ENCODE_BUFFER_BYTES); + for manifest in manifests().into_iter().chain([large]) { + let encoded = encode_manifest(&manifest).unwrap(); + assert!(encoded.starts_with(&ZSTD_MAGIC)); + assert_eq!(zstd::decode_all(&encoded[..]).unwrap(), json_of(&manifest)); + } + } + + #[tokio::test] + async fn the_borrowing_encoder_stores_the_same_json() { + // Compressed in several chunks + let large = sample_manifest(140); + assert!(json_of(&large).len() > 3 * ENCODE_CHUNK_BYTES); + // One file entry that is a chunk of its own + let mut wide = sample_manifest(3); + wide.files[1].columns = (0..4096) + .map(|c| Column { + name: format!("a_column_of_a_very_wide_stream_{c}"), + stats: None, + null_count: Some(c), + uncompressed_size: 1024, + compressed_size: 512, + stats_provenance: None, + }) + .collect(); + assert!(serde_json::to_vec(&wide.files[1]).unwrap().len() > ENCODE_CHUNK_BYTES); + for manifest in manifests().into_iter().chain([large, wide]) { + let json = json_of(&manifest); + let encoded = encode_manifest_blocking(&manifest).await.unwrap(); + assert!(encoded.starts_with(&ZSTD_MAGIC)); + assert_eq!(zstd::decode_all(&encoded[..]).unwrap(), json); + // And it is read back like any other manifest + assert_eq!(json_of(&decode_manifest(&encoded).unwrap()), json); + assert_eq!( + json_of(&decode_manifest_blocking(encoded).await.unwrap()), + json + ); + } + } + + /// The decoder that never holds the whole JSON returns what parsing the + /// whole JSON returns, wherever its window happens to cut the JSON. + #[test] + fn a_manifest_is_decoded_the_same_through_any_window() { + for manifest in manifests() { + let json = json_of(&manifest); + // As both encoders store it, and as it was stored before them + for encoded in [ + encode_manifest(&manifest).unwrap().to_vec(), + compress(&json), + // Whitespace between the tokens is skipped + compress(&serde_json::to_vec_pretty(&manifest).unwrap()), + ] { + for window in (1..=67).chain([256, 4096, DECODE_WINDOW_BYTES]) { + let decoded = decode_compressed_streaming(&encoded, window) + .unwrap_or_else(|| panic!("not streamed through a window of {window}")); + assert_eq!(json_of(&decoded), json, "window {window}"); + } + assert_eq!( + json_of(&decode_compressed_buffered(&encoded).unwrap()), + json + ); + assert_eq!(json_of(&decode_manifest(&encoded).unwrap()), json); + } + // Plain JSON never was compressed, and is parsed as it always was + assert_eq!(json_of(&decode_manifest(&json).unwrap()), json); + } + } + + /// Several windows of a manifest larger than the window of a decode + #[test] + fn a_manifest_larger_than_the_window_is_decoded() { + let manifest = sample_manifest(400); + let json = json_of(&manifest); + assert!(json.len() > 2 * DECODE_WINDOW_BYTES); + let encoded = encode_manifest(&manifest).unwrap(); + let decoded = decode_compressed_streaming(&encoded, DECODE_WINDOW_BYTES) + .expect("an encoded manifest is streamed"); + assert_eq!(json_of(&decoded), json); + assert_eq!(json_of(&decode_manifest(&encoded).unwrap()), json); + } + + /// A value the window cuts off is read again with more of the stream, + /// whatever byte it is cut after; a value that is wrong is not. + #[test] + fn a_cut_off_value_is_told_from_an_invalid_one() { + fn error(json: &[u8]) -> serde_json::Error { + serde_json::Deserializer::from_slice(json) + .into_iter::() + .next() + .expect("not only whitespace") + .expect_err("not a whole file entry") + } + for file in &varied_manifest(12).files { + for json in [ + serde_json::to_vec(file).unwrap(), + serde_json::to_vec_pretty(file).unwrap(), + ] { + for cut in 1..json.len() { + let cut_off = &json[..cut]; + assert!( + stopped_at_end(&error(cut_off), cut_off), + "{}", + String::from_utf8_lossy(cut_off) + ); + } + } + } + for invalid in [ + &br#"{"file_path":1,"num_rows":2,"file_size":3}"#[..], + br#"{"file_path":"a","num_rows":-1,"file_size":3}"#, + b"{\"file_path\":\"a\",\n\"num_rows\":tru,\n\"file_size\":3}", + br#"{"file_path":"a" "num_rows":1}"#, + br#"[1,2,3] "#, + ] { + assert!( + !stopped_at_end(&error(invalid), invalid), + "{}", + String::from_utf8_lossy(invalid) + ); + } + } + + /// Manifests laid out in another way than the encoders write them are + /// left to the decoder that parses the whole JSON. + #[test] + fn other_layouts_are_decoded_whole() { + let manifest = varied_manifest(9); + let json = json_of(&manifest); + let files = serde_json::to_string(&manifest.files).unwrap(); + for body in [ + format!(r#"{{"files":{files},"version":"v1"}}"#), + format!(r#"{{"version":"v1","since":{{"a":[1,"]}}"]}},"files":{files}}}"#), + format!(r#"{{"version":"v1","files":{files},"since":null}}"#), + format!(r#"{{"\u0076ersion":"v1","files":{files}}}"#), + ] { + let encoded = compress(body.as_bytes()); + for window in [1, 64, DECODE_WINDOW_BYTES] { + assert!( + decode_compressed_streaming(&encoded, window).is_none(), + "{body}" + ); + } + assert_eq!(json_of(&decode_manifest(&encoded).unwrap()), json, "{body}"); + } + } + + /// What the whole-JSON decoder refuses is refused with its error. + #[test] + fn refused_manifests_are_refused_as_before() { + let files = serde_json::to_string(&varied_manifest(5).files).unwrap(); + for body in [ + String::new(), + " ".to_owned(), + "null".to_owned(), + "[]".to_owned(), + r#"{"version":"v1"}"#.to_owned(), + r#"{"version":"v1","files":null}"#.to_owned(), + r#"{"version":1,"files":[]}"#.to_owned(), + r#"{"version":"v1","files":[1]}"#.to_owned(), + r#"{"version":"v1","files":[{}]}"#.to_owned(), + r#"{"version":"v1","files":[],}"#.to_owned(), + r#"{"version":"v1","files":["#.to_owned(), + r#"{"version":"v1","files":[]"#.to_owned(), + r#"{"version":"v1" "files":[]}"#.to_owned(), + format!(r#"{{"version":"v1","files":{files}}} x"#), + format!(r#"{{"version":"v1","files":{files}}}{{}}"#), + format!(r#"{{"version":"v1","version":"v1","files":{files}}}"#), + format!(r#"{{"version":"v1","files":{files},"files":[]}}"#), + format!( + r#"{{"version":"v1","files":{}}}"#, + files.replacen("num_rows", "rows", 1) + ), + format!( + r#"{{"version":"v1","files":{}}}"#, + &files[..files.len() - 2] + ), + format!( + r#"{{"version":"v1","files":{},]}}"#, + &files[..files.len() - 1] + ), + ] { + let encoded = compress(body.as_bytes()); + for window in [1, 16, DECODE_WINDOW_BYTES] { + assert!( + decode_compressed_streaming(&encoded, window).is_none(), + "{body}" + ); + } + let refused = decode_manifest(&encoded).expect_err(&body); + let before = decode_compressed_buffered(&encoded).expect_err(&body); + assert!(matches!(refused, ManifestCodecError::Parse(_)), "{body}"); + assert_eq!(refused.to_string(), before.to_string(), "{body}"); + } + } + + /// A stream that does not decompress to its end is refused, however much + /// of the manifest came out of it before. + #[test] + fn broken_streams_are_refused_as_before() { + let encoded = encode_manifest(&sample_manifest(8)).unwrap(); + let mut trailing = encoded.to_vec(); + trailing.extend_from_slice(b"not a zstd frame"); + for broken in [ + &encoded[..encoded.len() - 1], + &encoded[..encoded.len() / 2], + &encoded[..ZSTD_MAGIC.len()], + &trailing[..], + ] { + for window in [1, 4096, DECODE_WINDOW_BYTES] { + assert!(decode_compressed_streaming(broken, window).is_none()); + } + let refused = decode_manifest(broken).unwrap_err(); + let before = decode_compressed_buffered(broken).unwrap_err(); + assert!(matches!(refused, ManifestCodecError::Decompress(_))); + assert_eq!(refused.to_string(), before.to_string()); + } + // Two frames are one stream, as they are to the whole-JSON decoder + let json = json_of(&sample_manifest(2)); + let (head, tail) = json.split_at(json.len() / 3); + let mut frames = compress(head); + frames.extend_from_slice(&compress(tail)); + for window in [1, 4096, DECODE_WINDOW_BYTES] { + let decoded = decode_compressed_streaming(&frames, window).expect("two frames"); + assert_eq!(json_of(&decoded), json); + } + assert_eq!(json_of(&decode_manifest(&frames).unwrap()), json); + } +} + +/// The cache of staged footers stays within its limits by dropping the +/// footers cached first, one at a time. +#[cfg(test)] +mod parquet_metadata_cache_tests { + use std::path::PathBuf; + + use parquet::{ + file::{properties::WriterProperties, writer::SerializedFileWriter}, + schema::parser::parse_message_type, + }; + + use super::*; + + fn footer() -> Arc { + let schema = Arc::new(parse_message_type("message test { REQUIRED INT64 n; }").unwrap()); + let writer = SerializedFileWriter::new( + Vec::new(), + schema, + Arc::new(WriterProperties::builder().build()), + ) + .unwrap(); + Arc::new(writer.close().unwrap()) + } + + fn path(index: usize) -> PathBuf { + PathBuf::from(format!("/staging/stream/file-{index}.parquet")) + } + + fn cached(cache: &ParquetMetadataCache) -> Vec { + let mut cached: Vec = (0..64) + .filter(|&index| cache.entries.contains_key(path(index).as_path())) + .collect(); + cached.sort_unstable(); + cached + } + + #[test] + fn the_byte_limit_drops_the_footers_cached_first() { + let footer = footer(); + let now = Instant::now(); + let mut cache = ParquetMetadataCache::new(1000, 100); + for index in 0..4 { + assert!( + cache + .insert(&path(index), footer.clone(), 25, now) + .is_empty() + ); + } + assert_eq!((cache.bytes, cached(&cache)), (100, vec![0, 1, 2, 3])); + + // Room is made for exactly what is added, oldest first + let displaced = cache.insert(&path(4), footer.clone(), 30, now); + assert_eq!(displaced.len(), 2); + assert_eq!((cache.bytes, cached(&cache)), (80, vec![2, 3, 4])); + let displaced = cache.insert(&path(5), footer.clone(), 100, now); + assert_eq!(displaced.len(), 3); + assert_eq!((cache.bytes, cached(&cache)), (100, vec![5])); + + // A footer over the whole limit is not cached, and displaces nothing + // but an earlier footer of its own path + assert!(cache.insert(&path(6), footer.clone(), 101, now).is_empty()); + assert_eq!((cache.bytes, cached(&cache)), (100, vec![5])); + assert_eq!(cache.insert(&path(5), footer.clone(), 101, now).len(), 1); + assert_eq!((cache.bytes, cached(&cache)), (0, vec![])); + assert!(cache.remove(&path(5)).is_none()); + } + + #[test] + fn the_entry_limit_drops_one_footer_for_each_added() { + let footer = footer(); + let now = Instant::now(); + let mut cache = ParquetMetadataCache::new(3, usize::MAX); + for index in 0..10 { + let displaced = cache.insert(&path(index), footer.clone(), 1, now); + assert_eq!(displaced.len(), usize::from(index >= 3), "{index}"); + assert!(cache.entries.len() <= 3); + } + assert_eq!((cache.bytes, cached(&cache)), (3, vec![7, 8, 9])); + } + + #[test] + fn a_footer_cached_again_replaces_the_earlier_one() { + let footer = footer(); + let now = Instant::now(); + let mut cache = ParquetMetadataCache::new(3, 100); + for index in 0..3 { + cache.insert(&path(index), footer.clone(), 10, now); + } + // The earlier footer of the path is displaced, and the path is now + // the one cached last + assert_eq!(cache.insert(&path(0), footer.clone(), 40, now).len(), 1); + assert_eq!((cache.bytes, cached(&cache)), (60, vec![0, 1, 2])); + assert_eq!(cache.insert(&path(3), footer.clone(), 10, now).len(), 1); + assert_eq!((cache.bytes, cached(&cache)), (60, vec![0, 2, 3])); + assert_eq!(cache.insert(&path(4), footer.clone(), 10, now).len(), 1); + assert_eq!((cache.bytes, cached(&cache)), (60, vec![0, 3, 4])); + assert_eq!(cache.remove(&path(0)).map(|entry| entry.bytes), Some(40)); + assert_eq!((cache.bytes, cached(&cache)), (20, vec![3, 4])); + } + + #[test] + fn expired_footers_are_dropped_when_one_is_cached() { + let footer = footer(); + let start = Instant::now(); + let mut cache = ParquetMetadataCache::new(1000, usize::MAX); + cache.insert(&path(0), footer.clone(), 1, start); + cache.insert(&path(1), footer.clone(), 1, start); + let later = start + PARQUET_METADATA_CACHE_TTL / 2; + assert!(cache.insert(&path(2), footer.clone(), 1, later).is_empty()); + let expired = start + PARQUET_METADATA_CACHE_TTL; + assert_eq!(cache.insert(&path(3), footer.clone(), 1, expired).len(), 2); + assert_eq!((cache.bytes, cached(&cache)), (2, vec![2, 3])); + } + + /// Footers are mostly taken by the upload of their file, in no fixed + /// order. The paths they leave in the queue do not pile up. + #[test] + fn taken_footers_do_not_grow_the_queue() { + let footer = footer(); + let now = Instant::now(); + let mut cache = ParquetMetadataCache::new(1000, usize::MAX); + // One footer that is never taken keeps the front of the queue still + cache.insert(&path(0), footer.clone(), 1, now); + for index in 1..10_000 { + let staged = PathBuf::from(format!("/staging/stream/taken-{index}.parquet")); + cache.insert(&staged, footer.clone(), 1, now); + assert!(cache.remove(&staged).is_some()); + assert!(cache.order.len() <= 128, "{}", cache.order.len()); + } + assert_eq!((cache.bytes, cached(&cache)), (1, vec![0])); + assert_eq!(cache.clear().len(), 1); + assert!(cache.order.is_empty() && cache.entries.is_empty()); + assert_eq!(cache.bytes, 0); + } + + #[test] + fn a_staged_footer_is_weighed_cached_and_taken_once() { + let footer = footer(); + assert!(footer.memory_size() > 0); + assert!(footer.memory_size() < MAX_PARQUET_METADATA_CACHE_BYTES); + let staged = PathBuf::from(format!( + "/staging/{}/weighed.parquet", + ulid::Ulid::new().to_string().to_lowercase() + )); + // Another test may clear the cache under memory pressure in between + let taken = (0..1000) + .find_map(|_| { + cache_parquet_metadata(&staged, footer.clone()); + take_parquet_metadata(&staged) + }) + .expect("cached"); + assert!(Arc::ptr_eq(&taken, &footer)); + assert!(take_parquet_metadata(&staged).is_none()); + cache_parquet_metadata(&staged, footer); + evict_parquet_metadata(&staged); + assert!(take_parquet_metadata(&staged).is_none()); + } } #[cfg(test)] @@ -1059,7 +2085,7 @@ mod handoff_and_batch_tests { test_file("stream/file-1.parquet", 20), ], }; - let encoded = encode_manifest_blocking(manifest.clone()).await.unwrap(); + let encoded = encode_manifest_blocking(&manifest).await.unwrap(); let decoded = decode_manifest_blocking(encoded).await.unwrap(); assert_eq!( serde_json::to_value(&decoded).unwrap(), diff --git a/src/event/format/json.rs b/src/event/format/json.rs index ba499e704..5c13d3559 100644 --- a/src/event/format/json.rs +++ b/src/event/format/json.rs @@ -26,8 +26,10 @@ use arrow_array::builder::{ Int32Builder, Int64Builder, StringBuilder, TimestampMillisecondBuilder, UInt8Builder, UInt16Builder, UInt32Builder, UInt64Builder, }; -use arrow_array::types::Date32Type; -use arrow_array::{ArrayRef, RecordBatch, RecordBatchOptions}; +use arrow_array::types::{ArrowPrimitiveType, Date32Type}; +use arrow_array::{ + Array, ArrayRef, BooleanArray, PrimitiveArray, RecordBatch, RecordBatchOptions, StringArray, +}; use arrow_json::reader::{ReaderBuilder, infer_json_schema_from_iterator}; use arrow_schema::{DataType, Field, Fields, Schema, TimeUnit}; use chrono::{DateTime, NaiveDate, NaiveDateTime, Utc}; @@ -250,6 +252,27 @@ macro_rules! each_builder { } impl ColumnBuilder { + /// Whether `new` builds a column of the type, without building one + fn builds(data_type: &DataType) -> bool { + matches!( + data_type, + DataType::Boolean + | DataType::Int8 + | DataType::Int16 + | DataType::Int32 + | DataType::Int64 + | DataType::UInt8 + | DataType::UInt16 + | DataType::UInt32 + | DataType::UInt64 + | DataType::Float32 + | DataType::Float64 + | DataType::Utf8 + | DataType::Timestamp(TimeUnit::Millisecond, None) + | DataType::Date32 + ) + } + /// `None` for a type that is left to Arrow's JSON decoder: nested types, /// `Float16`, and timestamps of another unit or with a time zone. fn new(data_type: &DataType, rows: usize) -> Option { @@ -357,8 +380,66 @@ impl ColumnBuilder { } fn finish(&mut self) -> ArrayRef { - each_builder!(self, builder => Arc::new(builder.finish())) + each_builder!(self, builder => finish_array(builder.finish())) + } +} + +/// Rows from which a finished column gives back buffer capacity it does not +/// use. This is the row count from which the staging writer compresses a +/// batch whatever its size (`MIN_COMPRESSED_BATCH_ROWS`). Below it the writer +/// goes by the memory the batch holds, capacity included, so the buffers of a +/// smaller batch are left as the builders made them and that choice stays +/// what it was. +const SHRINK_MIN_ROWS: usize = 100; + +/// Unused capacity a column keeps on top of a quarter of what it uses. +/// Giving back less than this is not worth a reallocation. +const SHRINK_MIN_SLACK_BYTES: usize = 4096; + +/// Bytes of the buffers of a finished column that hold its rows, as opposed +/// to the capacity its builder allocated them with. +trait UsedBufferBytes: Array { + fn used_buffer_bytes(&self) -> usize; +} + +fn null_buffer_bytes(array: &impl Array) -> usize { + array.nulls().map_or(0, |nulls| nulls.buffer().len()) +} + +impl UsedBufferBytes for PrimitiveArray { + fn used_buffer_bytes(&self) -> usize { + self.values().inner().len() + null_buffer_bytes(self) + } +} + +impl UsedBufferBytes for BooleanArray { + fn used_buffer_bytes(&self) -> usize { + self.values().inner().len() + null_buffer_bytes(self) + } +} + +impl UsedBufferBytes for StringArray { + fn used_buffer_bytes(&self) -> usize { + self.offsets().inner().inner().len() + self.values().len() + null_buffer_bytes(self) + } +} + +/// The column a builder finished, without the buffer capacity it did not +/// come to use when that is a material part of it. +/// +/// A builder is sized for the rows a batch is expected to have and grows by +/// doubling, so a finished column can hold a multiple of its data in +/// capacity, and a staged batch keeps its columns for as long as it is +/// cached. The column's rows are not touched: its buffers, which nothing else +/// refers to yet, are reallocated to the length they already have. +fn finish_array(mut array: A) -> ArrayRef { + if array.len() >= SHRINK_MIN_ROWS { + let used = array.used_buffer_bytes(); + if array.get_buffer_memory_size() > used + used / 4 + SHRINK_MIN_SLACK_BYTES { + array.shrink_to_fit(); + } } + Arc::new(array) } struct DirectColumn<'a> { @@ -367,7 +448,8 @@ struct DirectColumn<'a> { /// Rows the builder holds. A column is only brought up to the current row /// when it gets a value, so a row costs nothing for the columns it lacks. rows: usize, - /// Length of the field's name as a JSON string + /// Length of the field's name as a JSON string. Not measured for a + /// column of `add_unnamed`, whose rows are not measured either. key_len: usize, } @@ -413,14 +495,46 @@ impl<'a> DirectColumns<'a> { Some(column) } - /// The column of the next key of the current row, if there is one - fn find(&self, key: &str) -> Option { + /// The columns of a batch whose keys are resolved by the caller, which + /// adds them with `add_unnamed`: no column is found by its name. + fn unnamed(columns: usize) -> Self { + Self { + columns: Vec::with_capacity(columns), + by_name: rustc_hash::FxHashMap::default(), + order: Vec::with_capacity(columns), + position: 0, + row: 0, + } + } + + /// `add` without the lookup by name: the caller knows the field from its + /// column. `None` when the type of the field is not built here. + fn add_unnamed(&mut self, field: &'a Arc, rows: usize) -> Option { + let builder = ColumnBuilder::new(field.data_type(), rows)?; + self.columns.push(DirectColumn { + field, + builder, + rows: 0, + key_len: 0, + }); + Some(self.columns.len() - 1) + } + + /// The column the previous row had where the current row has its next + /// key, when that key is its field + fn predicted(&self, key: &str) -> Option { match self.order.get(self.position) { Some(&column) if self.columns[column].field.name() == key => Some(column), - _ => self.by_name.get(key).copied(), + _ => None, } } + /// The column of the next key of the current row, if there is one + fn find(&self, key: &str) -> Option { + self.predicted(key) + .or_else(|| self.by_name.get(key).copied()) + } + /// Records that the next key of the current row stands for `column`. /// `None` when the row already has that key. fn take_key(&mut self, column: usize) -> Option<()> { @@ -451,25 +565,45 @@ impl<'a> DirectColumns<'a> { self.position = 0; } + /// The array of `column` for the completed rows + fn finish_column(&mut self, column: usize) -> ArrayRef { + let rows = self.row; + let column = &mut self.columns[column]; + if column.rows < rows { + column.builder.append_nulls(rows - column.rows); + } + column.builder.finish() + } + /// The batch of the completed rows, with the columns in the order of /// `schema`. `None` when Arrow refuses it, as for a null in a field that /// is not nullable. fn finish(mut self, schema: Arc) -> Option { - let rows = self.row; let mut arrays = Vec::with_capacity(schema.fields().len()); for field in schema.fields() { - let column = &mut self.columns[*self.by_name.get(field.name().as_str())?]; - if column.rows < rows { - column.builder.append_nulls(rows - column.rows); - } - arrays.push(column.builder.finish()); + let column = *self.by_name.get(field.name().as_str())?; + arrays.push(self.finish_column(column)); } - // The row count is given for a batch without columns, as of `{}` - let options = RecordBatchOptions::new().with_row_count(Some(rows)); - RecordBatch::try_new_with_options(schema, arrays, &options).ok() + direct_batch(schema, arrays, self.row) } } +/// The batch of `rows` rows of `arrays`. `None` when Arrow refuses it, as for +/// a null in a field that is not nullable. +fn direct_batch(schema: Arc, arrays: Vec, rows: usize) -> Option { + // The row count is given for a batch without columns, as of `{}` + let options = RecordBatchOptions::new().with_row_count(Some(rows)); + RecordBatch::try_new_with_options(schema, arrays, &options).ok() +} + +/// A field of the schema `decode_rows_direct` decodes rows with +enum DirectField<'a> { + /// No row has named it so far + Unseen(&'a Arc), + /// Its column in the batch + Column(usize), +} + /// Builds the batch `decode_rows_arrow_json` decodes from `data`, straight /// from the values: the decoder first writes every key and value of every row /// to its tape, and reads the columns from there. @@ -480,19 +614,47 @@ impl<'a> DirectColumns<'a> { /// accepts, other than those of rare types or with a string that a static /// schema casts. The decoder also takes over every batch it would reject, to /// report the error. +/// +/// A field gets its column, with room for every row, when a row first names +/// it. A field that no row names holds no builder while the rows are read, +/// and ends up as a column of nulls made in one piece. fn decode_rows_direct(data: &[impl Borrow], schema: &Arc) -> Option { if data.is_empty() { return None; } - let mut columns = DirectColumns::with_capacity(schema.fields().len()); - for field in schema.fields() { - columns.add(field, data.len())?; + let rows = data.len(); + let fields = schema.fields(); + let mut by_name = + rustc_hash::FxHashMap::with_capacity_and_hasher(fields.len(), Default::default()); + for field in fields { + // What adding a column for each of them up front refused + if !ColumnBuilder::builds(field.data_type()) + || by_name + .insert(field.name().as_str(), DirectField::Unseen(field)) + .is_some() + { + return None; + } } + let mut columns = DirectColumns::unnamed(fields.len()); for row in data { for (key, value) in row.borrow().as_object()? { - // The decoder skips a key that is not in the schema; it is rare - // enough to leave to it - let column = columns.find(key)?; + let column = match columns.predicted(key) { + Some(column) => column, + None => { + // The decoder skips a key that is not in the schema; it + // is rare enough to leave to it + let field = by_name.get_mut(key.as_str())?; + match *field { + DirectField::Column(column) => column, + DirectField::Unseen(unseen) => { + let column = columns.add_unnamed(unseen, rows)?; + *field = DirectField::Column(column); + column + } + } + } + }; columns.take_key(column)?; let builder = columns.value(column); match value { @@ -513,7 +675,20 @@ fn decode_rows_direct(data: &[impl Borrow], schema: &Arc) -> Opti } columns.end_row(); } - columns.finish(schema.clone()) + let mut arrays = Vec::with_capacity(fields.len()); + for field in fields { + arrays.push(match by_name.get(field.name().as_str())? { + DirectField::Column(column) => columns.finish_column(*column), + DirectField::Unseen(_) => { + // The nulls a column added up front would have been given + // row by row, without the room for values it never gets + let mut builder = ColumnBuilder::new(field.data_type(), 0)?; + builder.append_nulls(rows); + builder.finish() + } + }); + } + direct_batch(schema.clone(), arrays, rows) } /// A batch built from the bytes of a request body, and the length of its @@ -3870,6 +4045,359 @@ mod direct_batch_tests { } } + #[test] + fn the_types_that_are_built_are_told_without_a_builder() { + let mut types: Vec = stream_schema() + .into_values() + .map(|field| field.data_type().clone()) + .collect(); + types.extend([ + DataType::Null, + DataType::Float16, + DataType::LargeUtf8, + DataType::Binary, + DataType::Date64, + DataType::Timestamp(TimeUnit::Second, None), + DataType::Timestamp(TimeUnit::Microsecond, None), + DataType::Timestamp(TimeUnit::Millisecond, Some("UTC".into())), + DataType::Duration(TimeUnit::Millisecond), + ]); + let mut built = 0; + for data_type in &types { + let builder = ColumnBuilder::new(data_type, 0); + assert_eq!( + ColumnBuilder::builds(data_type), + builder.is_some(), + "{data_type}" + ); + built += builder.is_some() as usize; + } + // A field of every kind of column that is built is among them + assert!(built >= 14, "{built}"); + } + + /// `decode_rows_direct` as it was while it gave every field of the schema + /// a column, with room for every row, before it read the first row + fn decode_rows_eagerly(data: &[Value], schema: &Arc) -> Option { + if data.is_empty() { + return None; + } + let mut columns = DirectColumns::with_capacity(schema.fields().len()); + for field in schema.fields() { + columns.add(field, data.len())?; + } + for row in data { + for (key, value) in row.as_object()? { + let column = columns.find(key)?; + columns.take_key(column)?; + let builder = columns.value(column); + match value { + Value::Null => builder.append_nulls(1), + Value::Bool(value) => builder.append_bool(*value)?, + Value::Number(number) => { + if let Some(value) = number.as_u64() { + builder.append_u64(value)? + } else if let Some(value) = number.as_i64() { + builder.append_i64(value)? + } else { + builder.append_f64(number.as_f64()?)? + } + } + Value::String(value) => builder.append_str(value)?, + Value::Array(_) | Value::Object(_) => return None, + } + } + columns.end_row(); + } + columns.finish(schema.clone()) + } + + /// `count` nullable fields, of every type that is built directly in turn + fn wide_fields(count: usize) -> Vec> { + let types = [ + DataType::Utf8, + DataType::Float64, + DataType::Int64, + DataType::Boolean, + MILLIS, + DataType::Utf8, + DataType::UInt64, + DataType::Float32, + DataType::Int32, + DataType::Date32, + DataType::Int8, + DataType::Int16, + DataType::UInt8, + DataType::UInt16, + DataType::UInt32, + ]; + (0..count) + .map(|index| { + let data_type = types[index % types.len()].clone(); + Arc::new(Field::new(format!("f{index:02}"), data_type, true)) + }) + .collect() + } + + /// A value the builder of the type takes, or a null + fn sparse_value(rng: &mut Rng, data_type: &DataType) -> Value { + if rng.one_in(9) { + return Value::Null; + } + match data_type { + DataType::Utf8 => Value::from("x".repeat(rng.below(40))), + DataType::Boolean => Value::from(rng.one_in(2)), + DataType::Float64 if rng.one_in(2) => Value::from(rng.below(1000) as u64), + DataType::Float64 => Value::from(rng.below(1000) as f64 / 8.0), + DataType::Float32 => Value::from(rng.below(1000) as f64 + 0.5), + DataType::Timestamp(_, _) => { + Value::from(format!("2025-01-02T03:04:{:02}Z", rng.below(60))) + } + DataType::Date32 => Value::from(format!("2025-01-{:02}", 1 + rng.below(28))), + // The integer types, within the range of the smallest of them + _ => Value::from(rng.below(100) as u64), + } + } + + /// Rows that each name a few of the first `named` fields, in no order. + /// The later a row, the more of those fields it picks from, so that + /// fields are first named anywhere in the batch. + fn sparse_rows(rng: &mut Rng, fields: &[Arc], named: usize, rows: usize) -> Vec { + (0..rows) + .map(|row| { + let reach = (named * (row + 1)).div_ceil(rows).max(1); + let mut object = serde_json::Map::new(); + for _ in 0..rng.below(6) { + let field = &fields[rng.below(reach)]; + object.insert(field.name().clone(), sparse_value(rng, field.data_type())); + } + Value::Object(object) + }) + .collect() + } + + /// Columns are made when a row first names their field. The batch is the + /// one built with a column for every field of the schema up front, for + /// rows that name few of the fields, name them late, or never. + #[test] + fn sparse_rows_are_decoded_as_with_a_column_for_every_field_up_front() { + let fields = wide_fields(60); + let schema = Arc::new(Schema::new(fields.clone())); + let mut rng = Rng(0x9E37_79B9_7F4A_7C15); + let (mut decoded, mut total) = (0, 0); + for round in 0..700 { + // From a single row to more rows than capacity is given back from + let count = [1, 2, 7, 33, 99, 100, 180][round % 7]; + let mut rows = sparse_rows(&mut rng, &fields, 40, count); + // Now and then a row the builders do not take + if round % 5 == 4 { + let row = rng.below(count); + let fault = [ + ("f00", json!({"nested": 1})), + ("f00", json!(["a"])), + ("f01", json!("not a number")), + ("f02", json!(1.5)), + ("f10", json!(128)), + ("unknown", json!(1)), + ][rng.below(6)] + .clone(); + match fault { + (_, Value::Array(_)) if rng.one_in(2) => rows[row] = json!("not a row"), + (key, value) => { + rows[row] + .as_object_mut() + .unwrap() + .insert(key.to_owned(), value); + } + } + } + let lazy = decode_rows_direct(&rows, &schema); + let eager = decode_rows_eagerly(&rows, &schema); + assert_eq!(lazy, eager, "{rows:?}"); + total += 1; + let (Some(lazy), Some(eager)) = (lazy, eager) else { + // Left to Arrow, which decodes the rows or reports them + check_rows(&rows, schema.clone()); + continue; + }; + decoded += 1; + assert_eq!(lazy.num_rows(), rows.len()); + assert_eq!(lazy.schema(), schema); + // The same columns: value for value, null for null + for (index, field) in fields.iter().enumerate() { + let (lazy, eager) = (lazy.column(index), eager.column(index)); + assert_eq!(lazy.to_data(), eager.to_data(), "{}", field.name()); + assert_eq!(lazy.null_count(), eager.null_count(), "{}", field.name()); + assert_eq!(lazy.len(), rows.len()); + if !rows.iter().any(|row| row.get(field.name()).is_some()) { + assert_eq!(lazy.null_count(), rows.len(), "{}", field.name()); + } + } + // Which are the columns Arrow's decoder makes of the rows + assert!(check_rows(&rows, schema.clone())); + } + assert!( + decoded * 2 > total, + "{decoded} of {total} batches decoded directly" + ); + + // A field that leaves the batch to Arrow does so whether or not a + // row names it + let rows = sparse_rows(&mut rng, &fields, 40, 20); + for extra in [ + Field::new("required", DataType::Utf8, false), + Field::new("half", DataType::Float16, true), + // A second field of a name + Field::new("f00", DataType::Utf8, true), + ] { + let mut fields = fields.clone(); + fields.push(Arc::new(extra)); + let schema = Arc::new(Schema::new(fields)); + assert_eq!(decode_rows_direct(&rows, &schema), None); + assert_eq!(decode_rows_eagerly(&rows, &schema), None); + } + } + + /// A field that no row names takes no room for values it never gets. + #[test] + fn fields_that_no_row_names_hold_no_room_for_values() { + let fields: Vec<_> = (0..50) + .map(|index| Arc::new(Field::new(format!("s{index:02}"), DataType::Utf8, true))) + .collect(); + let schema = Arc::new(Schema::new(fields)); + // Fewer rows than capacity is given back from, to compare the + // batches as their builders left them + let rows: Vec = (0..SHRINK_MIN_ROWS - 1) + .map(|row| json!({"s00": format!("row {row}")})) + .collect(); + let lazy = decode_rows_direct(&rows, &schema).unwrap(); + let eager = decode_rows_eagerly(&rows, &schema).unwrap(); + assert_eq!(lazy, eager); + // The column with values is built the same either way + assert_eq!( + lazy.column(0).get_array_memory_size(), + eager.column(0).get_array_memory_size() + ); + // The 49 others are without the 16 bytes a row that a column made + // up front is given for its values. (Half of that is asked for, to + // leave room for how the buffers of offsets and nulls are sized.) + let saved = 49 * 16 * rows.len(); + assert!( + lazy.get_array_memory_size() + saved / 2 <= eager.get_array_memory_size(), + "{} and {}", + lazy.get_array_memory_size(), + eager.get_array_memory_size() + ); + } + + /// The row count from which capacity is given back is the one from which + /// the staging writer compresses a batch whatever memory it holds. For + /// fewer rows the writer goes by that memory, which is then left as it is. + #[test] + fn capacity_is_given_back_where_rows_alone_decide_the_compression() { + use crate::parseable::staging::writer::is_compressed_batch; + let batch = |rows: usize| { + RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new("i", DataType::Int64, false)])), + vec![Arc::new(Int64Array::from(vec![0i64; rows]))], + ) + .unwrap() + }; + assert!(is_compressed_batch(&batch(SHRINK_MIN_ROWS))); + assert!(!is_compressed_batch(&batch(SHRINK_MIN_ROWS - 1))); + } + + /// Bytes the buffers of a column use, and bytes they are allocated with + fn buffer_bytes(rb: &RecordBatch, name: &str) -> (usize, usize) { + let column = rb.column_by_name(name).unwrap(); + let used = match column.data_type() { + DataType::Utf8 => column + .as_any() + .downcast_ref::() + .unwrap() + .used_buffer_bytes(), + _ => column + .as_any() + .downcast_ref::() + .unwrap() + .used_buffer_bytes(), + }; + (used, column.get_buffer_memory_size()) + } + + #[test] + fn a_column_built_from_bytes_gives_back_the_capacity_it_does_not_use() { + let schema = stream_schema(); + // Rows this long are far fewer than their bytes suggest, which is + // what the builders of a body are sized by + let long = "x".repeat(2000); + let body = |rows: usize| { + let rows: Vec = (0..rows) + .map(|row| json!({"s": format!("{row} {long}"), "f": row as f64 + 0.5})) + .collect(); + serde_json::to_vec(&rows).unwrap() + }; + + let bytes = body(SHRINK_MIN_ROWS); + // The batch is still the one the general path builds + assert!(check_body(&bytes, &schema, FlattenLimits::DEFAULT)); + let rb = direct(&bytes, &schema).unwrap().rb; + assert_eq!(rb.num_rows(), SHRINK_MIN_ROWS); + // The numbers were given room for many times the rows there are + assert_eq!( + buffer_bytes(&rb, "f"), + (SHRINK_MIN_ROWS * 8, SHRINK_MIN_ROWS * 8) + ); + // No column is left with more than a quarter of its bytes, and a + // little, to spare. One that has less to spare is not reallocated. + for name in ["s", "f"] { + let (used, allocated) = buffer_bytes(&rb, name); + assert!( + used <= allocated && allocated <= used + used / 4 + SHRINK_MIN_SLACK_BYTES, + "{name}: {used} of {allocated}" + ); + } + + // With a row less, the batch is as its builders left it + let bytes = body(SHRINK_MIN_ROWS - 1); + assert!(check_body(&bytes, &schema, FlattenLimits::DEFAULT)); + let rb = direct(&bytes, &schema).unwrap().rb; + assert_eq!(rb.num_rows(), SHRINK_MIN_ROWS - 1); + let (used, allocated) = buffer_bytes(&rb, "f"); + assert!( + allocated > used + used / 4 + SHRINK_MIN_SLACK_BYTES, + "{used} of {allocated}" + ); + } + + #[test] + fn a_column_built_from_values_gives_back_the_capacity_it_does_not_use() { + let schema = Arc::new(Schema::new(vec![ + Field::new("s", DataType::Utf8, true), + Field::new("f", DataType::Float64, true), + ])); + // Strings of eight times the bytes a row is given room for: the + // buffer of the values grows by doubling, to nearly twice their size + let rows: Vec = (0..2 * SHRINK_MIN_ROWS) + .map(|row| { + if row % 3 == 0 { + json!({"s": "x".repeat(130), "f": row}) + } else { + json!({"s": "y".repeat(130), "f": null}) + } + }) + .collect(); + // The batch is still the one Arrow's decoder builds + assert!(check_rows(&rows, schema.clone())); + let rb = decode_rows_direct(&rows, &schema).unwrap(); + let (used, allocated) = buffer_bytes(&rb, "s"); + assert_eq!(used, rows.len() * 130 + (rows.len() + 1) * 4); + assert_eq!(allocated, used); + // A column that was sized right is left as it is + let (used, allocated) = buffer_bytes(&rb, "f"); + assert!(used <= allocated && allocated <= used + SHRINK_MIN_SLACK_BYTES); + } + /// A batch of 2,000 flat rows of 12 existing fields, as a log shipper /// posts it: parsed to a `StrictValue` and decoded by Arrow's JSON decoder /// (`old`), parsed to a `StrictValue` and built from the values diff --git a/src/handlers/http/ingest.rs b/src/handlers/http/ingest.rs index 28f54a807..84eb0d9a3 100644 --- a/src/handlers/http/ingest.rs +++ b/src/handlers/http/ingest.rs @@ -164,6 +164,22 @@ impl Default for JsonBytesConfig { /// JSON on the Actix worker thread. pub struct JsonBytes(pub web::Bytes); +/// The most a declared `Content-Length` reserves for a body before any of it +/// beyond the first chunk has arrived. A longer body grows the buffer as it +/// comes in, so a header that declares more than is sent reserves no more +/// than this. +const BODY_RESERVE_MAX_BYTES: usize = 2 * 1024 * 1024; + +/// Capacity of the buffer that joins the chunks of a body, of which `arrived` +/// bytes are here: the declared length, so that the buffer is allocated once +/// and holds nothing but the body, within [`BODY_RESERVE_MAX_BYTES`]. +fn body_buffer_capacity(declared: Option, arrived: usize) -> usize { + declared + .unwrap_or(0) + .min(BODY_RESERVE_MAX_BYTES) + .max(arrived) +} + impl From for JsonBytes { fn from(bytes: web::Bytes) -> Self { Self(bytes) @@ -183,11 +199,12 @@ impl actix_web::FromRequest for JsonBytes { .map_or_else(crate::handlers::http::max_event_payload_size, |cfg| { cfg.limit }); - if let Some(len) = req + let declared = req .headers() .get(actix_web::http::header::CONTENT_LENGTH) .and_then(|v| v.to_str().ok()) - .and_then(|s| s.parse::().ok()) + .and_then(|s| s.parse::().ok()); + if let Some(len) = declared && len > limit { return Box::pin(async move { @@ -197,15 +214,36 @@ impl actix_web::FromRequest for JsonBytes { let mut stream = payload.take(); Box::pin(async move { use futures_util::StreamExt; - let mut buf = actix_web::web::BytesMut::new(); + // A body that arrives in one chunk is that chunk, not a copy of + // it. The chunks of any other body are joined in a buffer, which + // is allocated when the second one arrives. + let mut body = web::Bytes::new(); + let mut joined: Option = None; while let Some(chunk) = stream.next().await { let chunk = chunk.map_err(JsonPayloadError::Payload)?; - if buf.len().saturating_add(chunk.len()) > limit { + if chunk.is_empty() { + continue; + } + let len = joined.as_ref().map_or(body.len(), |buf| buf.len()); + if len.saturating_add(chunk.len()) > limit { return Err(JsonPayloadError::Overflow { limit }.into()); } - buf.extend_from_slice(&chunk); + if let Some(buf) = joined.as_mut() { + buf.extend_from_slice(&chunk); + } else if body.is_empty() { + body = chunk; + } else { + let mut buf = actix_web::web::BytesMut::with_capacity(body_buffer_capacity( + declared, + len + chunk.len(), + )); + buf.extend_from_slice(&body); + buf.extend_from_slice(&chunk); + body = web::Bytes::new(); + joined = Some(buf); + } } - Ok(JsonBytes(buf.freeze())) + Ok(JsonBytes(joined.map_or(body, |buf| buf.freeze()))) }) } } @@ -457,6 +495,11 @@ async fn stage_flat_body_async( } return Ok(()); } + // The body was kept for the general path above only. Staging can wait for + // its turn behind other requests, and from here it does so without the + // body, which is otherwise the largest thing the request still holds + // besides its batch. + drop(bytes); let stream_name = stream.stream_name.clone(); count_custom_fields_not_applied(&rb, &p_custom_fields, &stream_name, &tenant_id); @@ -2543,6 +2586,116 @@ mod ingest_body_tests { } } + /// A body is the chunks it arrives in, joined in order, whatever length + /// the request declares. A body of one chunk is that chunk. + #[actix_web::test] + async fn a_body_is_the_chunks_it_arrives_in() { + use actix_web::error::PayloadError; + + const LIMIT: usize = 64; + async fn extract( + declared: Option, + chunks: Vec>, + ) -> Result { + let mut request = TestRequest::post() + .app_data(JsonBytesConfig { limit: LIMIT }) + .insert_header((CONTENT_TYPE, "application/json")); + if let Some(declared) = declared { + request = request.insert_header(("content-length", declared.to_string())); + } + let req = request.to_http_request(); + let mut payload: actix_web::dev::Payload = actix_web::dev::Payload::Stream { + payload: Box::pin(futures_util::stream::iter(chunks)), + }; + match JsonBytes::from_request(&req, &mut payload).await { + Ok(JsonBytes(body)) => Ok(body), + Err(error) => Err(error.error_response().status()), + } + } + let chunk = |text: &'static str| -> Result { + Ok(web::Bytes::from_static(text.as_bytes())) + }; + + // One chunk is returned as it arrived: the same bytes, not a copy of + // them. Chunks without bytes do not count. + let one = web::Bytes::from(r#"[{"a":1}]"#.to_owned()); + for chunks in [ + vec![Ok(one.clone())], + vec![chunk(""), Ok(one.clone()), chunk(""), chunk("")], + ] { + let body = extract(Some(one.len()), chunks).await.unwrap(); + assert_eq!(body, one); + assert_eq!(body.as_ptr(), one.as_ptr()); + } + assert!(extract(None, vec![]).await.unwrap().is_empty()); + assert!(extract(Some(0), vec![chunk("")]).await.unwrap().is_empty()); + + // Several chunks are joined, with the declared length only a hint of + // how many bytes there are + let parts = [r#"[{"a":"#, "", r#"1},"#, r#"{"b":"two"}"#, "]"]; + let whole = parts.concat(); + for declared in [None, Some(whole.len()), Some(1), Some(LIMIT)] { + let chunks = parts.iter().copied().map(chunk).collect(); + assert_eq!( + extract(declared, chunks).await.unwrap(), + whole, + "{declared:?}" + ); + } + + // The limit is that of the bytes that arrive, at the chunk that + // crosses it, and of the declared length before any arrive + let half = "x".repeat(LIMIT / 2); + let halves = |count: usize| -> Vec> { + (0..count) + .map(|_| Ok(web::Bytes::from(half.clone()))) + .collect() + }; + assert_eq!(extract(None, halves(2)).await.unwrap().len(), LIMIT); + for declared in [None, Some(LIMIT), Some(1)] { + let mut over = halves(2); + over.push(chunk("x")); + assert_eq!( + extract(declared, over).await, + Err(StatusCode::PAYLOAD_TOO_LARGE), + "{declared:?}" + ); + } + assert_eq!( + extract(Some(LIMIT + 1), vec![chunk("{}")]).await, + Err(StatusCode::PAYLOAD_TOO_LARGE) + ); + + // A chunk that fails is the answer, also after chunks that arrived + for chunks in [ + vec![Err(PayloadError::EncodingCorrupted)], + vec![chunk("{"), Err(PayloadError::EncodingCorrupted)], + vec![chunk("{"), chunk("}"), Err(PayloadError::EncodingCorrupted)], + ] { + assert_eq!(extract(None, chunks).await, Err(StatusCode::BAD_REQUEST)); + } + } + + #[test] + fn the_declared_length_sizes_the_buffer_of_a_body_within_bounds() { + // As declared, so that the buffer is the body and nothing more + assert_eq!(body_buffer_capacity(Some(4096), 100), 4096); + // Never less than what is here already + assert_eq!(body_buffer_capacity(Some(50), 100), 100); + assert_eq!(body_buffer_capacity(None, 100), 100); + assert_eq!(body_buffer_capacity(Some(0), 0), 0); + // And no more than the bound, whatever is declared + for declared in [BODY_RESERVE_MAX_BYTES + 1, 10 << 20, usize::MAX] { + assert_eq!( + body_buffer_capacity(Some(declared), 100), + BODY_RESERVE_MAX_BYTES + ); + } + // A body that is longer grows the buffer as it arrives + let arrived = BODY_RESERVE_MAX_BYTES + 100; + assert_eq!(body_buffer_capacity(Some(usize::MAX), arrived), arrived); + } + /// What the extractor answered for the usual mistakes, which come before /// anything the handler refuses #[actix_web::test] diff --git a/src/handlers/http/resource_check.rs b/src/handlers/http/resource_check.rs index 4810bd214..3be4eb7f3 100644 --- a/src/handlers/http/resource_check.rs +++ b/src/handlers/http/resource_check.rs @@ -993,6 +993,12 @@ pub fn effective_memory_limit_bytes() -> u64 { fn run_soft_pressure_relief() { let field_stats_evicted = crate::storage::field_stats::clear_staged_field_stats_cache(); let metadata_evicted = crate::catalog::manifest::clear_parquet_metadata_cache(); + // Decoded manifests and stream JSONs that are past their TTL. They are + // never served again, yet stay resident until the cache is next used. + // The live ones are left to the queries sharing them: they are bounded, + // expire within seconds, and dropping them would only make those queries + // fetch and decode them again while memory is short. + let stream_metadata = crate::metastore::metadata_cache::evict_expired(); let small_file_bytes = crate::query::clear_small_file_cache(); trigger_memory_pressure_eviction(); if let Err(err) = crate::utils::allocator::purge_all_arenas() { @@ -1000,7 +1006,11 @@ fn run_soft_pressure_relief() { } info!( field_stats_evicted, - metadata_evicted, small_file_bytes, "Memory soft-pressure relief completed" + metadata_evicted, + stream_metadata_evicted = stream_metadata.entries, + stream_metadata_bytes = stream_metadata.bytes, + small_file_bytes, + "Memory soft-pressure relief completed" ); } @@ -1664,6 +1674,8 @@ mod backpressure_tests { #[test] fn soft_pressure_relief_invokes_registered_hook_and_clears_caches() { + use crate::metastore::metadata_cache::METADATA_CACHE; + let hits = Arc::new(AtomicUsize::new(0)); let hits_clone = Arc::clone(&hits); register_memory_pressure_hook(move || { @@ -1673,6 +1685,20 @@ mod backpressure_tests { let dummy_path = std::path::Path::new("/tmp/parseable-soft-pressure-test.parquet"); crate::storage::field_stats::cache_staged_field_stats(dummy_path, 16, Vec::new()); + // A manifest of a query that is past its TTL in the process-wide + // metadata cache (which a TTL of zero turns off). Nothing serves it + // any more, but it is still held. + let stream = "soft-pressure-relief-test"; + let ttl = METADATA_CACHE.ttl(); + if ttl <= std::time::Duration::from_secs(5) + && let Some((_slot, lease)) = METADATA_CACHE.reserve_manifest_slot(stream, &None, "m") + { + lease + .expect("no other test reserves this manifest") + .fulfill(Some(crate::catalog::manifest::Manifest::default())); + std::thread::sleep(ttl + std::time::Duration::from_millis(20)); + } + run_soft_pressure_relief(); assert!( @@ -1683,6 +1709,10 @@ mod backpressure_tests { crate::storage::field_stats::take_staged_field_stats(dummy_path, 16).is_none(), "staged field stats cache should be cleared under soft pressure" ); + assert!( + !METADATA_CACHE.holds_manifest(stream, &None, "m"), + "expired stream metadata should be dropped under soft pressure" + ); } #[actix_web::test] diff --git a/src/main.rs b/src/main.rs index 4469ca4a7..203e5c214 100644 --- a/src/main.rs +++ b/src/main.rs @@ -62,11 +62,23 @@ unsafe impl Sync for MallocConf {} /// `tikv-jemallocator` already builds jemalloc with this as its default; it /// is repeated here so that this list is the whole configuration and stays in /// force if that feature is ever dropped. +/// +/// `cache_oblivious:false` stops jemalloc from padding every large allocation +/// (anything above its 14 KiB small-class limit) with one extra page to +/// randomise where the allocation starts within its first page. Arrow buffers, +/// IPC messages and request bodies are mostly such allocations, so the padding +/// was a 4 KiB tax on each of them: up to a quarter of a 16 KiB buffer. The +/// randomisation only spreads cache-index conflicts between allocations whose +/// first lines are hot; turning it off costs no CPU. +/// +/// `dirty_decay_ms` and `narenas` are deliberately not tightened: profiling +/// under load showed lower values trade the memory for `madvise` and arena +/// contention (far more CPU, several times slower SQL). #[cfg(all(not(target_env = "msvc"), not(feature = "hotpath")))] #[used] #[unsafe(export_name = "_rjem_malloc_conf")] pub static MALLOC_CONF: MallocConf = MallocConf( - c"dirty_decay_ms:1000,muzzy_decay_ms:0,narenas:16,tcache_max:16384,background_thread:true" + c"dirty_decay_ms:1000,muzzy_decay_ms:0,narenas:16,tcache_max:16384,background_thread:true,cache_oblivious:false" .as_ptr(), ); @@ -263,6 +275,15 @@ mod jemalloc_conf_tests { assert_eq!(narenas, 16); assert_eq!(tcache_max, 16384); + // SAFETY: `opt.cache_oblivious` is a `bool` in jemalloc. + let cache_oblivious: bool = + unsafe { tikv_jemalloc_ctl::raw::read(b"opt.cache_oblivious\0") } + .expect("opt.cache_oblivious readable"); + assert!( + !cache_oblivious, + "compiled-in cache_oblivious:false was not applied" + ); + // Checked on Linux, where jemalloc always has background threads. // Other platforms may be built without them; there is then nothing // to check. diff --git a/src/metastore/metadata_cache.rs b/src/metastore/metadata_cache.rs index 7011deb26..5ef14a518 100644 --- a/src/metastore/metadata_cache.rs +++ b/src/metastore/metadata_cache.rs @@ -24,6 +24,14 @@ //! expire `P_METADATA_CACHE_TTL_MS` milliseconds after they were filled //! (default 2000, `0` disables the cache). //! +//! Each kind of entry is bounded twice: in entries, and in the bytes its +//! values hold. A decoded manifest of a busy stream is megabytes, so a count +//! alone bounds very little. Room is made an entry at a time: the entries +//! past their TTL first, then the ones filled longest ago. A value is charged +//! when its load completes; a value that is over the byte limit by itself is +//! still kept, alone, so that the queries of a burst share its load. A slot +//! that is still loading holds no bytes and is the last to make way. +//! //! Every metastore write that changes what an entry describes (stream JSON, //! manifests, partitions, schema, stream deletion) invalidates the stream's //! entries after the write returns, so writes made on this node are visible to @@ -32,9 +40,9 @@ //! need staging-window freshness. use std::{ - collections::{HashMap, HashSet}, + collections::{HashMap, HashSet, VecDeque}, hash::Hash, - sync::{Arc, LazyLock, Mutex}, + sync::{Arc, LazyLock, Mutex, MutexGuard, PoisonError}, time::{Duration, Instant}, }; @@ -47,12 +55,34 @@ const DEFAULT_TTL_MS: u64 = 2000; const MAX_MANIFESTS: usize = 4096; /// Upper bound on resident per-stream (and per-tenant listing) entries. const MAX_STREAMS: usize = 1024; +/// Upper bound on the bytes of resident manifests, as +/// [`Manifest::memory_size`] estimates them. +const MAX_MANIFEST_BYTES: usize = 128 * 1024 * 1024; +/// Upper bound on the bytes of resident stream JSONs: half of it for the raw +/// `.stream.json` of every node of a stream, half for the decoded ones. +const MAX_STREAM_JSON_BYTES: usize = 32 * 1024 * 1024; +/// Upper bound on the bytes of each kind of resident listing: the date +/// partitions of a stream, and the streams of a tenant. +const MAX_LISTING_BYTES: usize = 4 * 1024 * 1024; pub const TTL_ENV: &str = "P_METADATA_CACHE_TTL_MS"; pub static METADATA_CACHE: LazyLock = LazyLock::new(|| MetadataCache::new(parse_ttl(std::env::var(TTL_ENV).ok().as_deref()))); +/// Drops every entry of the process-wide cache, for a process that is short +/// of memory. Nothing is lost but the loads the entries saved: the next reads +/// fetch and decode again, and a load in flight still serves its waiters. +pub fn clear_metadata_cache() -> Evicted { + METADATA_CACHE.clear() +} + +/// Drops the entries of the process-wide cache that are past their TTL. They +/// are never served again, and otherwise stay until room is needed. +pub fn evict_expired() -> Evicted { + METADATA_CACHE.evict_expired() +} + fn parse_ttl(value: Option<&str>) -> Duration { let millis = match value.map(str::trim) { None | Some("") => DEFAULT_TTL_MS, @@ -66,6 +96,65 @@ fn parse_ttl(value: Option<&str>) -> Duration { Duration::from_millis(millis) } +/// Entries dropped from the cache, and the bytes that were charged for them. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Evicted { + pub entries: usize, + pub bytes: usize, +} + +/// Bytes a cached value is charged for against the byte limit of its kind: +/// an estimate of what the value keeps in memory. +trait CacheWeight { + fn cache_weight(&self) -> usize; +} + +impl CacheWeight for Option { + fn cache_weight(&self) -> usize { + self.as_ref().map_or(0, Manifest::memory_size) + } +} + +impl CacheWeight for ObjectStoreFormat { + fn cache_weight(&self) -> usize { + // What grows with the stream: a manifest item for each day and node, + // and the known fields of its log sources. + let manifests = &self.snapshot.manifest_list; + std::mem::size_of::() + + std::mem::size_of_val(manifests.as_slice()) + + manifests + .iter() + .map(|item| item.manifest_path.capacity()) + .sum::() + + self + .log_source + .iter() + .flat_map(|entry| &entry.fields) + .map(|field| std::mem::size_of::() + field.capacity()) + .sum::() + } +} + +impl CacheWeight for Vec { + fn cache_weight(&self) -> usize { + self.capacity() * std::mem::size_of::() + self.iter().map(Bytes::len).sum::() + } +} + +impl CacheWeight for Vec { + fn cache_weight(&self) -> usize { + self.capacity() * std::mem::size_of::() + + self.iter().map(String::capacity).sum::() + } +} + +impl CacheWeight for HashSet { + fn cache_weight(&self) -> usize { + self.capacity() * std::mem::size_of::() + + self.iter().map(String::capacity).sum::() + } +} + #[derive(Clone, Debug, Eq, Hash, PartialEq)] struct StreamKey { tenant: Option, @@ -109,9 +198,41 @@ impl Slot { } } +/// The cache a manifest slot was reserved in, and its key there: where the +/// manifest is charged once the slot is filled. +#[derive(Clone)] +struct ManifestHome { + inner: Arc>, + key: Arc<(StreamKey, String)>, + ttl: Duration, +} + +impl std::fmt::Debug for ManifestHome { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + // Only the key: `inner` is the whole cache + f.debug_struct("ManifestHome") + .field("key", &self.key) + .finish_non_exhaustive() + } +} + +impl ManifestHome { + fn charge(&self, slot: &Arc>>, bytes: usize) { + let evicted = + lock(&self.inner) + .manifests + .charge(&self.key, slot, bytes, self.ttl, Instant::now()); + // Dropped with the cache unlocked + drop(evicted); + } +} + /// Handle to a reserved manifest slot in [`MetadataCache`]. #[derive(Clone, Debug)] -pub struct ManifestSlot(Arc>>); +pub struct ManifestSlot { + slot: Arc>>, + home: ManifestHome, +} impl ManifestSlot { /// Returns the cached manifest if populated, waiting for any in-flight @@ -121,24 +242,32 @@ impl ManifestSlot { F: FnOnce() -> Fut, Fut: Future, E>>, { - if let Some((_, value)) = self.0.cell.get() { + if let Some((_, value)) = self.slot.cell.get() { return Ok(value.clone()); } let _permit = self - .0 + .slot .batch_sem .acquire() .await .expect("slot semaphore is never closed"); + // Set by the load only, so the manifest is charged by whoever loaded it + let mut loaded = None; + let loaded_bytes = &mut loaded; let (_, value) = self - .0 + .slot .cell - .get_or_try_init(|| async { - let value = load().await?; - Ok((Instant::now(), Arc::new(value))) + .get_or_try_init(move || async move { + let value = Arc::new(load().await?); + *loaded_bytes = Some(value.cache_weight()); + Ok((Instant::now(), value)) }) .await?; - Ok(value.clone()) + let value = value.clone(); + if let Some(bytes) = loaded { + self.home.charge(&self.slot, bytes); + } + Ok(value) } } @@ -151,27 +280,60 @@ impl ManifestSlot { #[derive(Debug)] pub struct ManifestBatchLease { slot: Arc>>, + home: ManifestHome, _permit: tokio::sync::OwnedSemaphorePermit, } impl ManifestBatchLease { pub fn fulfill(self, value: Option) { - let _ = self.slot.cell.set((Instant::now(), Arc::new(value))); + let value = Arc::new(value); + let bytes = value.cache_weight(); + if self.slot.cell.set((Instant::now(), value)).is_ok() { + self.home.charge(&self.slot, bytes); + } // Dropping `self` releases `_permit` and wakes any waiters. } } +#[derive(Debug)] +struct Entry { + slot: Arc>, + /// Bytes charged for the value of the slot; none before it is filled + bytes: usize, + /// Where the entry is queued, in `loading` or in `filled` + sequence: u64, +} + #[derive(Debug)] struct SlotMap { - slots: HashMap>>, + slots: HashMap>, + /// Keys of the slots that are still loading, in the order they were + /// reserved in. + loading: VecDeque<(u64, K)>, + /// Keys of the filled entries with the time they were filled at, in the + /// order they were filled in, which is the order they expire in. + /// + /// An entry that is removed, or that moves from `loading` to here, leaves + /// its key where it was queued. The sequence there then matches no entry, + /// and the key is skipped when it reaches the front of its queue. + filled: VecDeque<(u64, Instant, K)>, + next_sequence: u64, capacity: usize, + max_bytes: usize, + /// Bytes charged for the filled entries + bytes: usize, } impl SlotMap { - fn new(capacity: usize) -> Self { + fn new(capacity: usize, max_bytes: usize) -> Self { Self { slots: HashMap::new(), + loading: VecDeque::new(), + filled: VecDeque::new(), + next_sequence: 0, capacity, + max_bytes, + bytes: 0, } } @@ -181,39 +343,182 @@ impl SlotMap { .is_some_and(|(filled, _)| now.duration_since(*filled) >= ttl) } - /// Returns `(slot, is_new, evicted)` so the caller can drop evicted slots - /// after releasing the cache mutex. - fn slot(&mut self, key: &K, ttl: Duration, now: Instant) -> (Arc>, Vec>>) { - let mut evicted = Vec::new(); - if let Some(slot) = self.slots.get(key) - && !Self::expired(slot, ttl, now) - { - return (slot.clone(), evicted); + fn get(&self, key: &K) -> Option<&Arc>> { + self.slots.get(key).map(|entry| &entry.slot) + } + + fn remove(&mut self, key: &K) -> Option>> { + let entry = self.slots.remove(key)?; + self.bytes = self.bytes.saturating_sub(entry.bytes); + Some(entry.slot) + } + + /// Keys of entries that are gone are only dropped from the front of + /// their queue. This bounds the queues when a front stays put, at a cost + /// spread over the removals that made it necessary. + fn compact(&mut self) { + if self.loading.len() + self.filled.len() > 2 * self.slots.len() + 64 { + let slots = &self.slots; + let queued = |sequence: u64, key: &K| { + slots + .get(key) + .is_some_and(|entry| entry.sequence == sequence) + }; + self.loading + .retain(|(sequence, key)| queued(*sequence, key)); + self.filled + .retain(|(sequence, _, key)| queued(*sequence, key)); } - if !self.slots.contains_key(key) && self.slots.len() >= self.capacity { - let expired_keys: Vec = self + } + + /// Drops the entries that are past their TTL: those at the front of + /// `filled`, up to the first one that was filled less than a TTL ago. + /// While that one is at the front, which is nearly always, this looks at + /// nothing but its time. + fn drop_expired(&mut self, ttl: Duration, now: Instant, evicted: &mut Vec>>) { + while let Some((sequence, filled, key)) = self.filled.front() { + if now.duration_since(*filled) < ttl { + break; + } + // Unless its entry is gone, or was filled anew since + let queued = self .slots - .iter() - .filter(|(_, slot)| Self::expired(slot, ttl, now)) - .map(|(k, _)| k.clone()) - .collect(); - for expired_key in expired_keys { - if let Some(old) = self.slots.remove(&expired_key) { - evicted.push(old); - } + .get(key) + .is_some_and(|entry| entry.sequence == *sequence); + if let Some((_, _, key)) = self.filled.pop_front() + && queued + && let Some(slot) = self.remove(&key) + { + evicted.push(slot); } - if self.slots.len() >= self.capacity { - // Still full of live entries: start over rather than track - // recency. In-flight loads keep their detached slot. - evicted.extend(self.slots.drain().map(|(_, slot)| slot)); + } + } + + /// Removes the entry that was filled longest ago, unless it is `keep` + fn evict_filled(&mut self, keep: Option<&K>) -> Option>> { + loop { + let (sequence, _, key) = self.filled.front()?; + let queued = self + .slots + .get(key) + .is_some_and(|entry| entry.sequence == *sequence); + if queued && keep == Some(key) { + return None; + } + let (_, _, key) = self.filled.pop_front()?; + if queued { + return self.remove(&key); } } - let slot = Arc::new(Slot::new()); - if let Some(old) = self.slots.insert(key.clone(), slot.clone()) { + } + + /// Removes the slot that has been loading longest + fn evict_loading(&mut self) -> Option>> { + loop { + let (sequence, key) = self.loading.pop_front()?; + if self + .slots + .get(&key) + .is_some_and(|entry| entry.sequence == sequence) + { + return self.remove(&key); + } + } + } + + /// Returns the slot of `key`, a new one unless a live one is resident, + /// and the slots this evicted, for the caller to drop after releasing + /// the cache mutex. + /// + /// A new slot holds no bytes yet, so it only has to fit the limit on + /// entries. Entries past their TTL make way for it first, then the entry + /// filled longest ago, and only when every entry is still loading the one + /// reserved longest ago, whose load then serves its waiters alone. + fn slot(&mut self, key: &K, ttl: Duration, now: Instant) -> (Arc>, Vec>>) { + let mut evicted = Vec::new(); + self.drop_expired(ttl, now, &mut evicted); + if let Some(entry) = self.slots.get(key) + && !Self::expired(&entry.slot, ttl, now) + { + return (entry.slot.clone(), evicted); + } + // An expired slot of the key is replaced. In-flight loads keep the + // slot they have, detached. + if let Some(old) = self.remove(key) { evicted.push(old); } + while self.slots.len() >= self.capacity { + match self.evict_filled(None).or_else(|| self.evict_loading()) { + Some(slot) => evicted.push(slot), + None => break, + } + } + let slot = Arc::new(Slot::new()); + let sequence = self.next_sequence; + self.next_sequence += 1; + self.slots.insert( + key.clone(), + Entry { + slot: slot.clone(), + bytes: 0, + sequence, + }, + ); + self.loading.push_back((sequence, key.clone())); + self.compact(); (slot, evicted) } + + /// Charges `bytes` for the value `slot` was just filled with, and returns + /// the slots evicted to stay within the byte limit, for the caller to + /// drop after releasing the cache mutex: the entries past their TTL + /// first, then those filled longest ago, one at a time. The entry that is + /// charged stays, also when it is over the limit by itself. + /// + /// Nothing is charged for a slot that is no longer the resident one of + /// `key`: it was invalidated or evicted while it loaded, and is only held + /// by those who wait for it. + fn charge( + &mut self, + key: &K, + slot: &Arc>, + bytes: usize, + ttl: Duration, + now: Instant, + ) -> Vec>> { + let mut evicted = Vec::new(); + let sequence = self.next_sequence; + let Some(entry) = self.slots.get_mut(key) else { + return evicted; + }; + if !Arc::ptr_eq(&entry.slot, slot) { + return evicted; + } + let charged = std::mem::replace(&mut entry.bytes, bytes); + // Filled last, it expires last: queued behind every filled entry + entry.sequence = sequence; + let filled = slot.cell.get().map_or(now, |(filled, _)| *filled); + self.next_sequence += 1; + self.bytes = self.bytes.saturating_sub(charged).saturating_add(bytes); + self.filled.push_back((sequence, filled, key.clone())); + self.drop_expired(ttl, now, &mut evicted); + while self.bytes > self.max_bytes { + match self.evict_filled(Some(key)) { + Some(slot) => evicted.push(slot), + None => break, + } + } + self.compact(); + evicted + } + + /// Empties the map and returns its slots + fn clear(&mut self) -> Vec>> { + self.loading.clear(); + self.filled.clear(); + self.bytes = 0; + self.slots.drain().map(|(_, entry)| entry.slot).collect() + } } #[derive(Debug)] @@ -225,23 +530,51 @@ struct Inner { listings: SlotMap, HashSet>, } +impl Inner { + fn bytes(&self) -> usize { + self.formats.bytes + + self.all_stream_jsons.bytes + + self.stream_dates.bytes + + self.manifests.bytes + + self.listings.bytes + } + + fn entries(&self) -> usize { + self.formats.slots.len() + + self.all_stream_jsons.slots.len() + + self.stream_dates.slots.len() + + self.manifests.slots.len() + + self.listings.slots.len() + } +} + +/// The cache state is whole between any two statements that change it, so a +/// panic while it was locked is no reason to fail every read after it. +fn lock(inner: &Mutex) -> MutexGuard<'_, Inner> { + inner.lock().unwrap_or_else(PoisonError::into_inner) +} + #[derive(Debug)] pub struct MetadataCache { ttl: Duration, - inner: Mutex, + inner: Arc>, } impl MetadataCache { pub fn new(ttl: Duration) -> Self { + Self::with_manifest_limits(ttl, MAX_MANIFESTS, MAX_MANIFEST_BYTES) + } + + fn with_manifest_limits(ttl: Duration, manifests: usize, manifest_bytes: usize) -> Self { Self { ttl, - inner: Mutex::new(Inner { - formats: SlotMap::new(MAX_STREAMS), - all_stream_jsons: SlotMap::new(MAX_STREAMS), - stream_dates: SlotMap::new(MAX_STREAMS), - manifests: SlotMap::new(MAX_MANIFESTS), - listings: SlotMap::new(MAX_STREAMS), - }), + inner: Arc::new(Mutex::new(Inner { + formats: SlotMap::new(MAX_STREAMS, MAX_STREAM_JSON_BYTES / 2), + all_stream_jsons: SlotMap::new(MAX_STREAMS, MAX_STREAM_JSON_BYTES / 2), + stream_dates: SlotMap::new(MAX_STREAMS, MAX_LISTING_BYTES), + manifests: SlotMap::new(manifests, manifest_bytes), + listings: SlotMap::new(MAX_STREAMS, MAX_LISTING_BYTES), + })), } } @@ -249,30 +582,102 @@ impl MetadataCache { !self.ttl.is_zero() } - async fn get_or_load( + /// How long an entry is served after it was filled + pub fn ttl(&self) -> Duration { + self.ttl + } + + /// Bytes charged for the resident values of every kind + pub fn resident_bytes(&self) -> usize { + lock(&self.inner).bytes() + } + + /// Drops every entry. A load in flight keeps its slot, detached, and + /// still serves those who wait for it. + pub fn clear(&self) -> Evicted { + let (evicted, dropped) = { + let mut inner = lock(&self.inner); + let evicted = Evicted { + entries: inner.entries(), + bytes: inner.bytes(), + }; + let dropped = ( + inner.formats.clear(), + inner.all_stream_jsons.clear(), + inner.stream_dates.clear(), + inner.manifests.clear(), + inner.listings.clear(), + ); + (evicted, dropped) + }; + // Dropped with the cache unlocked + drop(dropped); + evicted + } + + /// Drops the entries that are past their TTL + pub fn evict_expired(&self) -> Evicted { + let now = Instant::now(); + let mut dropped = (Vec::new(), Vec::new(), Vec::new(), Vec::new(), Vec::new()); + let evicted = { + let mut inner = lock(&self.inner); + let (entries, bytes) = (inner.entries(), inner.bytes()); + inner.formats.drop_expired(self.ttl, now, &mut dropped.0); + inner + .all_stream_jsons + .drop_expired(self.ttl, now, &mut dropped.1); + inner + .stream_dates + .drop_expired(self.ttl, now, &mut dropped.2); + inner.manifests.drop_expired(self.ttl, now, &mut dropped.3); + inner.listings.drop_expired(self.ttl, now, &mut dropped.4); + Evicted { + entries: entries - inner.entries(), + bytes: bytes.saturating_sub(inner.bytes()), + } + }; + // Dropped with the cache unlocked + drop(dropped); + evicted + } + + async fn get_or_load( &self, - select: impl FnOnce(&mut Inner, Duration, Instant) -> (Arc>, Vec>>), + map: impl Fn(&mut Inner) -> &mut SlotMap, + key: &K, load: F, ) -> Result, E> where + K: Eq + Hash + Clone + 'static, + T: CacheWeight + 'static, F: FnOnce() -> Fut, Fut: Future>, { if !self.enabled() { return load().await.map(Arc::new); } - let (slot, evicted) = select(&mut self.inner.lock().unwrap(), self.ttl, Instant::now()); + let (slot, evicted) = map(&mut lock(&self.inner)).slot(key, self.ttl, Instant::now()); // Drop evicted entries outside the mutex. drop(evicted); + // Set by the load only, so the value is charged by whoever loaded it + let mut loaded = None; + let loaded_bytes = &mut loaded; // The lock is not held across the load. let (_, value) = slot .cell - .get_or_try_init(|| async { - let value = load().await?; - Ok((Instant::now(), Arc::new(value))) + .get_or_try_init(move || async move { + let value = Arc::new(load().await?); + *loaded_bytes = Some(value.cache_weight()); + Ok((Instant::now(), value)) }) .await?; - Ok(value.clone()) + let value = value.clone(); + if let Some(bytes) = loaded { + let evicted = + map(&mut lock(&self.inner)).charge(key, &slot, bytes, self.ttl, Instant::now()); + drop(evicted); + } + Ok(value) } /// Decoded `.stream.json` of `stream` as read by the query planner. @@ -287,7 +692,7 @@ impl MetadataCache { Fut: Future>, { let key = StreamKey::new(stream, tenant); - self.get_or_load(|inner, ttl, now| inner.formats.slot(&key, ttl, now), load) + self.get_or_load(|inner| &mut inner.formats, &key, load) .await } @@ -303,11 +708,8 @@ impl MetadataCache { Fut: Future, E>>, { let key = StreamKey::new(stream, tenant); - self.get_or_load( - |inner, ttl, now| inner.all_stream_jsons.slot(&key, ttl, now), - load, - ) - .await + self.get_or_load(|inner| &mut inner.all_stream_jsons, &key, load) + .await } /// Date partition directories (`date=YYYY-MM-DD`) of `stream` in object storage. @@ -322,11 +724,8 @@ impl MetadataCache { Fut: Future, E>>, { let key = StreamKey::new(stream, tenant); - self.get_or_load( - |inner, ttl, now| inner.stream_dates.slot(&key, ttl, now), - load, - ) - .await + self.get_or_load(|inner| &mut inner.stream_dates, &key, load) + .await } /// Decoded manifest at `path` of `stream`; `None` when it does not exist. @@ -343,7 +742,7 @@ impl MetadataCache { Fut: Future, E>>, { let key = (StreamKey::new(stream, tenant), path.to_owned()); - self.get_or_load(|inner, ttl, now| inner.manifests.slot(&key, ttl, now), load) + self.get_or_load(|inner| &mut inner.manifests, &key, load) .await } @@ -364,10 +763,15 @@ impl MetadataCache { } let key = (StreamKey::new(stream, tenant), path.to_owned()); let (slot, evicted) = { - let mut inner = self.inner.lock().unwrap(); + let mut inner = lock(&self.inner); inner.manifests.slot(&key, self.ttl, Instant::now()) }; drop(evicted); + let home = ManifestHome { + inner: self.inner.clone(), + key: Arc::new(key), + ttl: self.ttl, + }; let lease = if slot.cell.get().is_none() { slot.batch_sem .clone() @@ -376,12 +780,13 @@ impl MetadataCache { .filter(|_| slot.cell.get().is_none()) .map(|permit| ManifestBatchLease { slot: slot.clone(), + home: home.clone(), _permit: permit, }) } else { None }; - Some((ManifestSlot(slot), lease)) + Some((ManifestSlot { slot, home }, lease)) } /// A resident manifest, without loading it. @@ -396,12 +801,19 @@ impl MetadataCache { return None; } let key = (StreamKey::new(stream, tenant), path.to_owned()); - let inner = self.inner.lock().unwrap(); - let slot = inner.manifests.slots.get(&key)?; + let inner = lock(&self.inner); + let slot = inner.manifests.get(&key)?; let (filled, value) = slot.cell.get()?; (Instant::now().duration_since(*filled) < self.ttl).then(|| value.clone()) } + /// Whether a slot for the manifest is held, be it loading, live or expired. + #[cfg(test)] + pub fn holds_manifest(&self, stream: &str, tenant: &Option, path: &str) -> bool { + let key = (StreamKey::new(stream, tenant), path.to_owned()); + lock(&self.inner).manifests.get(&key).is_some() + } + /// Names of the tenant's streams, as returned by `Metastore::list_streams`. pub async fn stream_listing( &self, @@ -413,7 +825,7 @@ impl MetadataCache { Fut: Future, E>>, { let key = tenant_key(tenant); - self.get_or_load(|inner, ttl, now| inner.listings.slot(&key, ttl, now), load) + self.get_or_load(|inner| &mut inner.listings, &key, load) .await } @@ -423,10 +835,10 @@ impl MetadataCache { pub fn invalidate_stream(&self, stream: &str, tenant: &Option) { let key = StreamKey::new(stream, tenant); let (old_format, old_jsons, old_dates, old_manifests, old_listing) = { - let mut inner = self.inner.lock().unwrap(); - let old_format = inner.formats.slots.remove(&key); - let old_jsons = inner.all_stream_jsons.slots.remove(&key); - let old_dates = inner.stream_dates.slots.remove(&key); + let mut inner = lock(&self.inner); + let old_format = inner.formats.remove(&key); + let old_jsons = inner.all_stream_jsons.remove(&key); + let old_dates = inner.stream_dates.remove(&key); let manifest_keys: Vec<_> = inner .manifests .slots @@ -436,18 +848,17 @@ impl MetadataCache { .collect(); let mut old_manifests = Vec::with_capacity(manifest_keys.len()); for manifest_key in manifest_keys { - if let Some(slot) = inner.manifests.slots.remove(&manifest_key) { + if let Some(slot) = inner.manifests.remove(&manifest_key) { old_manifests.push(slot); } } let listed = inner .listings - .slots .get(&key.tenant) .and_then(|slot| slot.cell.get()) .is_some_and(|(_, names)| names.contains(stream)); let old_listing = if !listed { - inner.listings.slots.remove(&key.tenant) + inner.listings.remove(&key.tenant) } else { None }; @@ -459,13 +870,7 @@ impl MetadataCache { /// The stream was deleted (or marked for deletion) on this node. pub fn invalidate_stream_removed(&self, stream: &str, tenant: &Option) { self.invalidate_stream(stream, tenant); - let old_listing = self - .inner - .lock() - .unwrap() - .listings - .slots - .remove(&tenant_key(tenant)); + let old_listing = lock(&self.inner).listings.remove(&tenant_key(tenant)); drop(old_listing); } } @@ -660,27 +1065,453 @@ mod tests { assert_eq!(loads.load(Ordering::SeqCst), 3); } + /// Fills `slot` as a load does, and charges `bytes` for it + fn fill( + map: &mut SlotMap, + key: usize, + slot: &Arc>, + bytes: usize, + ttl: Duration, + now: Instant, + ) -> usize { + slot.cell.set((now, Arc::new(()))).unwrap(); + map.charge(&key, slot, bytes, ttl, now).len() + } + + /// The keys of the map, sorted + fn keys(map: &SlotMap) -> Vec { + let mut keys: Vec = map.slots.keys().copied().collect(); + keys.sort_unstable(); + keys + } + #[test] - fn slot_map_is_bounded() { - let mut map = SlotMap::::new(4); + fn a_full_slot_map_evicts_one_entry_for_each_added() { + let mut map = SlotMap::::new(4, usize::MAX); let ttl = Duration::from_secs(60); let now = Instant::now(); for key in 0..10 { - let (slot, _evicted) = map.slot(&key, ttl, now); - slot.cell.set((now, Arc::new(()))).unwrap(); - assert!(map.slots.len() <= 4); - } - // Expired entries are evicted before live ones. - let later = now + ttl; - let mut map = SlotMap::::new(2); - let (slot0, _) = map.slot(&0, ttl, now); - slot0.cell.set((now, Arc::new(()))).unwrap(); - let (slot1, _) = map.slot(&1, ttl, later); - slot1.cell.set((later, Arc::new(()))).unwrap(); - let (_slot2, evicted) = map.slot(&2, ttl, later); + let (slot, evicted) = map.slot(&key, ttl, now); + // Never more than the one entry that has to go, and never all + assert_eq!(evicted.len(), usize::from(key >= 4), "{key}"); + assert_eq!(fill(&mut map, key, &slot, 1, ttl, now), 0); + assert_eq!(map.slots.len(), (key + 1).min(4)); + } + // The entries added last are the ones that stay + assert_eq!(keys(&map), [6, 7, 8, 9]); + assert_eq!(map.bytes, 4); + // A resident key is served its slot, and evicts nothing + let (again, evicted) = map.slot(&9, ttl, now); + assert!(evicted.is_empty() && again.cell.get().is_some()); + assert_eq!(keys(&map), [6, 7, 8, 9]); + } + + #[test] + fn the_byte_limit_evicts_the_entries_filled_first() { + let mut map = SlotMap::::new(1000, 100); + let ttl = Duration::from_secs(60); + let now = Instant::now(); + let mut slots = Vec::new(); + // Slots are reserved first and filled later, as a batch of a query is + for key in 0..6 { + let (slot, evicted) = map.slot(&key, ttl, now); + assert!(evicted.is_empty()); + slots.push(slot); + } + // Nothing is charged for a slot before it is filled + assert_eq!(map.bytes, 0); + // Filled in another order than they were reserved in + for (key, evicted) in [(3, 0), (0, 0), (5, 0), (1, 1), (2, 1)] { + assert_eq!( + fill(&mut map, key, &slots[key], 30, ttl, now), + evicted, + "{key}" + ); + assert!(map.bytes <= 100); + } + // Those filled first went: 3 and 0. The slot that is still loading + // holds no bytes, and stays, though it was reserved before them. + assert_eq!(keys(&map), [1, 2, 4, 5]); + assert_eq!(map.bytes, 90); + // Its value takes the room of every other one + assert_eq!(fill(&mut map, 4, &slots[4], 100, ttl, now), 3); + assert_eq!((keys(&map), map.bytes), (vec![4], 100)); + } + + #[test] + fn a_slot_that_is_loading_is_the_last_to_make_way() { + let ttl = Duration::from_secs(60); + let now = Instant::now(); + // A filled entry goes before the slots reserved ahead of it + let mut map = SlotMap::::new(3, usize::MAX); + let (first, _) = map.slot(&0, ttl, now); + let (slot, _) = map.slot(&1, ttl, now); + fill(&mut map, 1, &slot, 5, ttl, now); + let (_third, _) = map.slot(&2, ttl, now); + let (_, evicted) = map.slot(&3, ttl, now); + assert_eq!(evicted.len(), 1); + assert_eq!((keys(&map), map.bytes), (vec![0, 2, 3], 0)); + // With nothing but loading slots, the one reserved first goes. Its + // load still completes, for those who wait for it only. + let (_, evicted) = map.slot(&4, ttl, now); + assert_eq!(evicted.len(), 1); + assert!(Arc::ptr_eq(&evicted[0], &first)); + assert_eq!(keys(&map), [2, 3, 4]); + assert_eq!(fill(&mut map, 0, &first, 9, ttl, now), 0); + assert_eq!((keys(&map), map.bytes), (vec![2, 3, 4], 0)); + } + + #[test] + fn a_value_over_the_byte_limit_is_kept_alone() { + let mut map = SlotMap::::new(1000, 100); + let ttl = Duration::from_secs(60); + let now = Instant::now(); + for key in 0..3 { + let (slot, _) = map.slot(&key, ttl, now); + assert_eq!(fill(&mut map, key, &slot, 10, ttl, now), 0); + } + // The other entries make way; the value itself stays, so that the + // queries waiting for its load and those right behind them share it + let (large, _) = map.slot(&3, ttl, now); + assert_eq!(fill(&mut map, 3, &large, 500, ttl, now), 3); + assert_eq!((keys(&map), map.bytes), (vec![3], 500)); + let (resident, evicted) = map.slot(&3, ttl, now); + assert!(Arc::ptr_eq(&resident, &large) && evicted.is_empty()); + // Until the next value is filled + let (slot, evicted) = map.slot(&4, ttl, now); + assert!(evicted.is_empty()); + assert_eq!(fill(&mut map, 4, &slot, 10, ttl, now), 1); + assert_eq!((keys(&map), map.bytes), (vec![4], 10)); + } + + #[test] + fn expired_entries_are_evicted_before_live_ones() { + let ttl = Duration::from_secs(60); + let start = Instant::now(); + let at = |seconds: u64| start + Duration::from_secs(seconds); + + // Expired entries are dropped as the map is used, full or not + let mut map = SlotMap::::new(3, usize::MAX); + for (key, filled) in [(0, 0), (1, 10), (2, 20)] { + let (slot, _) = map.slot(&key, ttl, at(filled)); + fill(&mut map, key, &slot, 7, ttl, at(filled)); + } + let (_, evicted) = map.slot(&1, ttl, at(59)); + assert!(evicted.is_empty()); + let (_, evicted) = map.slot(&1, ttl, at(60)); assert_eq!(evicted.len(), 1); - assert!(map.slots.contains_key(&1) && map.slots.contains_key(&2)); - assert!(!map.slots.contains_key(&0)); + assert_eq!((keys(&map), map.bytes), (vec![1, 2], 14)); + // And the key that expired gets a new slot + let (renewed, evicted) = map.slot(&1, ttl, at(70)); + assert_eq!(evicted.len(), 1); + assert!(renewed.cell.get().is_none()); + assert_eq!((keys(&map), map.bytes), (vec![1, 2], 7)); + + // A slot that is still loading, and so does not expire, does not + // hold back the expired entries reserved after it + let mut map = SlotMap::::new(3, usize::MAX); + let (loading, _) = map.slot(&0, ttl, at(0)); + let (slot, _) = map.slot(&1, ttl, at(0)); + fill(&mut map, 1, &slot, 7, ttl, at(0)); + let (slot, _) = map.slot(&2, ttl, at(30)); + fill(&mut map, 2, &slot, 7, ttl, at(30)); + let (_, evicted) = map.slot(&3, ttl, at(60)); + assert_eq!(evicted.len(), 1); + assert_eq!((keys(&map), map.bytes), (vec![0, 2, 3], 7)); + assert!(Arc::ptr_eq(map.get(&0).unwrap(), &loading)); + } + + #[test] + fn a_slot_that_left_the_map_is_not_charged() { + let mut map = SlotMap::::new(4, 100); + let ttl = Duration::from_secs(60); + let now = Instant::now(); + // Invalidated while it loads + let (stale, _) = map.slot(&0, ttl, now); + assert!(map.remove(&0).is_some()); + assert_eq!(fill(&mut map, 0, &stale, 50, ttl, now), 0); + assert_eq!((keys(&map), map.bytes), (vec![], 0)); + // Replaced while it loads: the new slot of the key is not charged + // for it either + let (stale, _) = map.slot(&0, ttl, now); + assert!(map.remove(&0).is_some()); + let (fresh, _) = map.slot(&0, ttl, now); + assert_eq!(fill(&mut map, 0, &stale, 50, ttl, now), 0); + assert_eq!(map.bytes, 0); + assert_eq!(fill(&mut map, 0, &fresh, 20, ttl, now), 0); + assert_eq!(map.bytes, 20); + // What was charged is released with the entry + assert!(map.remove(&0).is_some()); + assert_eq!(map.bytes, 0); + assert_eq!(map.clear().len(), 0); + } + + /// Slots that are reserved and invalidated without ever reaching the + /// front of the queue do not make it grow. + #[test] + fn removed_slots_do_not_grow_the_queue() { + let mut map = SlotMap::::new(1000, usize::MAX); + let ttl = Duration::from_secs(60); + let now = Instant::now(); + // A live entry at the front, which stays there + let (slot, _) = map.slot(&0, ttl, now); + fill(&mut map, 0, &slot, 1, ttl, now); + for key in 1..10_000 { + let (slot, _) = map.slot(&key, ttl, now); + fill(&mut map, key, &slot, 1, ttl, now); + assert!(map.remove(&key).is_some()); + let queued = map.loading.len() + map.filled.len(); + assert!(queued <= 128, "{queued}"); + } + assert_eq!((keys(&map), map.bytes), (vec![0], 1)); + } + + /// A manifest of `columns` columns in each of `files` files + fn sized_manifest(files: usize, columns: usize) -> Manifest { + Manifest { + version: "v1".to_owned(), + files: (0..files) + .map(|file| crate::catalog::manifest::File { + file_path: format!("stream/date=2026-01-01/file-{file}.parquet"), + num_rows: 1, + file_size: 1, + ingestion_size: 1, + columns: (0..columns) + .map(|column| crate::catalog::column::Column { + name: format!("column_{column}"), + stats: None, + null_count: None, + uncompressed_size: 1, + compressed_size: 1, + stats_provenance: None, + }) + .collect(), + sort_order_id: vec![], + }) + .collect(), + } + } + + #[test] + fn values_are_weighed_by_what_they_hold() { + assert_eq!(None::.cache_weight(), 0); + let small = Some(sized_manifest(1, 1)).cache_weight(); + let wide = Some(sized_manifest(1, 100)).cache_weight(); + let long = Some(sized_manifest(100, 1)).cache_weight(); + assert!(small > 0); + // At least the structs of the columns and files, and their names + assert!(wide >= small + 99 * std::mem::size_of::()); + assert!(long >= small + 99 * std::mem::size_of::()); + + let jsons = vec![Bytes::from(vec![0u8; 1000]), Bytes::from(vec![0u8; 24])]; + assert!(jsons.cache_weight() >= 1024); + assert!(vec!["date=2026-01-01".to_owned(); 10].cache_weight() >= 150); + assert!(HashSet::from(["a-stream".to_owned()]).cache_weight() >= 8); + assert!( + ObjectStoreFormat::default().cache_weight() >= std::mem::size_of::() + ); + } + + #[tokio::test] + async fn resident_manifests_stay_within_the_byte_limit() { + let weight = Some(sized_manifest(4, 16)).cache_weight(); + // Room for three manifests, not for four + let cache = + MetadataCache::with_manifest_limits(Duration::from_secs(60), 4096, 3 * weight + 1); + let path = |index: usize| format!("m{index}"); + for index in 0..12 { + let loaded = cache + .manifest("logs", &None, &path(index), || async { + R::Ok(Some(sized_manifest(4, 16))) + }) + .await + .unwrap(); + assert_eq!(loaded.as_ref().as_ref().unwrap().files.len(), 4); + // One manifest makes way for each one over the limit: the cache + // never empties, and never holds more than its limit + assert_eq!(cache.resident_bytes(), weight * (index + 1).min(3)); + for resident in index.saturating_sub(2)..=index { + assert!( + cache + .cached_manifest("logs", &None, &path(resident)) + .is_some(), + "{resident} of {index}" + ); + } + if index >= 3 { + assert!( + cache + .cached_manifest("logs", &None, &path(index - 3)) + .is_none() + ); + } + } + // A manifest that does not exist is cached, and weighs nothing + cache + .manifest("logs", &None, "missing", || async { R::Ok(None) }) + .await + .unwrap(); + assert_eq!(cache.resident_bytes(), 3 * weight); + assert!(cache.cached_manifest("logs", &None, "missing").is_some()); + + // Invalidation releases what was charged for the stream + cache.invalidate_stream("logs", &None); + assert_eq!(cache.resident_bytes(), 0); + } + + #[tokio::test] + async fn batched_and_fallback_loads_are_charged_once() { + let weight = Some(sized_manifest(2, 8)).cache_weight(); + let cache = MetadataCache::with_manifest_limits(Duration::from_secs(60), 4096, 2 * weight); + + // Filled by the owner of the batch + let (slot, lease) = cache.reserve_manifest_slot("logs", &None, "a").unwrap(); + lease.unwrap().fulfill(Some(sized_manifest(2, 8))); + assert_eq!(cache.resident_bytes(), weight); + // Reading it back charges nothing more + let read = slot + .get_or_load(|| async { R::Ok(Some(sized_manifest(9, 9))) }) + .await + .unwrap(); + assert_eq!(read.as_ref().as_ref().unwrap().files.len(), 2); + assert_eq!(cache.resident_bytes(), weight); + + // Filled by a waiter, after the owner of the batch gave up + let (slot, lease) = cache.reserve_manifest_slot("logs", &None, "b").unwrap(); + drop(lease); + slot.get_or_load(|| async { R::Ok(Some(sized_manifest(2, 8))) }) + .await + .unwrap(); + assert_eq!(cache.resident_bytes(), 2 * weight); + + // The third manifest evicts the first, whichever way it is loaded + let (_slot, lease) = cache.reserve_manifest_slot("logs", &None, "c").unwrap(); + lease.unwrap().fulfill(Some(sized_manifest(2, 8))); + assert_eq!(cache.resident_bytes(), 2 * weight); + assert!(cache.cached_manifest("logs", &None, "a").is_none()); + assert!(cache.cached_manifest("logs", &None, "b").is_some()); + assert!(cache.cached_manifest("logs", &None, "c").is_some()); + + // A slot invalidated before it is filled is charged nothing + let (_slot, lease) = cache.reserve_manifest_slot("other", &None, "d").unwrap(); + cache.invalidate_stream("other", &None); + lease.unwrap().fulfill(Some(sized_manifest(2, 8))); + assert_eq!(cache.resident_bytes(), 2 * weight); + } + + #[tokio::test] + async fn stream_jsons_are_charged_by_their_bytes() { + let cache = MetadataCache::new(Duration::from_secs(60)); + let jsons = cache + .all_stream_jsons("logs", &None, || async { + R::Ok(vec![ + Bytes::from(vec![b' '; 4096]), + Bytes::from_static(b"{}"), + ]) + }) + .await + .unwrap(); + assert_eq!(jsons.len(), 2); + let charged = cache.resident_bytes(); + assert!((4098..4098 + 1024).contains(&charged), "{charged}"); + cache + .stream_dates("logs", &None, || async { + R::Ok(vec!["date=2026-11-29".to_owned()]) + }) + .await + .unwrap(); + assert!(cache.resident_bytes() > charged); + cache.invalidate_stream("logs", &None); + assert_eq!(cache.resident_bytes(), 0); + } + + #[tokio::test] + async fn clearing_drops_every_entry_and_keeps_loads_in_flight_working() { + let cache = Arc::new(MetadataCache::new(Duration::from_secs(60))); + assert_eq!(cache.clear(), Evicted::default()); + cache + .manifest("logs", &None, "m", || async { + R::Ok(Some(sized_manifest(2, 8))) + }) + .await + .unwrap(); + cache + .stream_listing(&None, || async { + R::Ok(HashSet::from(["logs".to_owned()])) + }) + .await + .unwrap(); + let (started_tx, started_rx) = tokio::sync::oneshot::channel(); + let (release_tx, release_rx) = tokio::sync::oneshot::channel::<()>(); + let in_flight = { + let cache = cache.clone(); + tokio::spawn(async move { + cache + .manifest("logs", &None, "slow", || async move { + started_tx.send(()).unwrap(); + release_rx.await.unwrap(); + R::Ok(Some(sized_manifest(3, 8))) + }) + .await + }) + }; + started_rx.await.unwrap(); + + let charged = cache.resident_bytes(); + assert!(charged > 0); + // Two values and the slot of the load in flight + assert_eq!( + cache.clear(), + Evicted { + entries: 3, + bytes: charged + } + ); + assert_eq!(cache.resident_bytes(), 0); + assert!(cache.cached_manifest("logs", &None, "m").is_none()); + + // The load in flight still answers its caller, and is not published + release_tx.send(()).unwrap(); + let loaded = in_flight.await.unwrap().unwrap(); + assert_eq!(loaded.as_ref().as_ref().unwrap().files.len(), 3); + assert_eq!(cache.resident_bytes(), 0); + assert!(cache.cached_manifest("logs", &None, "slow").is_none()); + + // The next read loads again + let reloaded = cache + .manifest("logs", &None, "m", || async { + R::Ok(Some(sized_manifest(5, 8))) + }) + .await + .unwrap(); + assert_eq!(reloaded.as_ref().as_ref().unwrap().files.len(), 5); + } + + #[tokio::test] + async fn expired_entries_are_dropped_on_request() { + let cache = MetadataCache::new(Duration::from_millis(200)); + for path in ["a", "b"] { + cache + .manifest("logs", &None, path, || async { + R::Ok(Some(sized_manifest(2, 8))) + }) + .await + .unwrap(); + } + let expiring = cache.resident_bytes(); + assert_eq!(cache.evict_expired(), Evicted::default()); + tokio::time::sleep(Duration::from_millis(260)).await; + // Expired, and still resident: nothing has used the cache since + assert_eq!(cache.resident_bytes(), expiring); + assert_eq!( + cache.evict_expired(), + Evicted { + entries: 2, + bytes: expiring + } + ); + assert_eq!(cache.resident_bytes(), 0); + assert_eq!(cache.evict_expired(), Evicted::default()); } #[tokio::test] diff --git a/src/metastore/metastores/document_metastore.rs b/src/metastore/metastores/document_metastore.rs index cf43c33f9..e26b14907 100644 --- a/src/metastore/metastores/document_metastore.rs +++ b/src/metastore/metastores/document_metastore.rs @@ -299,6 +299,101 @@ pub fn is_missing_optional_dir(err: &ObjectStorageError) -> bool { } } +/// How long a `put_schema` may rely on what `get_schema` returned. The two +/// calls of a schema merge follow each other at once; this only bounds how +/// long a fetch that no write followed is remembered. +const FETCHED_SCHEMA_TTL: std::time::Duration = std::time::Duration::from_secs(5); + +/// Fetches remembered at a time. Beyond it a fetch is not remembered, and the +/// write that follows it is made. +const MAX_FETCHED_SCHEMAS: usize = 1024; + +/// What `get_schema` returned for a schema object, for the `put_schema` that +/// follows it. +struct FetchedSchema { + /// Holds the allocation of the store, so that its address, which is part + /// of the key of this entry, is not that of another store while the entry + /// exists. + _storage: std::sync::Weak<$storage>, + /// The task that fetched it. A write of another task does not rely on it. + task: Option, + fetched: std::time::Instant, + bytes: Bytes, +} + +/// The schema objects fetched last, by store and path. +/// +/// A sync merges a staged schema into the stored one by `get_schema`, a merge +/// and `put_schema`. Most of the time the staged schema adds nothing, and the +/// write would store what was just read. This lets `put_schema` see that. +static FETCHED_SCHEMAS: std::sync::LazyLock> = + std::sync::LazyLock::new(DashMap::new); + +fn fetched_schema_key(storage: &Arc<$storage>, path: &RelativePath) -> (usize, String) { + (Arc::as_ptr(storage) as *const () as usize, path.to_string()) +} + +fn remember_fetched_schema(storage: &Arc<$storage>, path: &RelativePath, bytes: &Bytes) { + // Fetches no write followed are dropped once they are of no use + if FETCHED_SCHEMAS.len() >= 16 { + FETCHED_SCHEMAS.retain(|_, fetched| fetched.fetched.elapsed() < FETCHED_SCHEMA_TTL); + } + let key = fetched_schema_key(storage, path); + if FETCHED_SCHEMAS.len() >= MAX_FETCHED_SCHEMAS { + // Nor is an earlier fetch of this object left to be relied on + drop(FETCHED_SCHEMAS.remove(&key)); + return; + } + FETCHED_SCHEMAS.insert( + key, + FetchedSchema { + _storage: Arc::downgrade(storage), + task: tokio::task::try_id(), + fetched: std::time::Instant::now(), + bytes: bytes.clone(), + }, + ); +} + +/// Forgets what was fetched for a schema object that is written or removed. +fn forget_fetched_schema(storage: &Arc<$storage>, path: &RelativePath) -> Option { + FETCHED_SCHEMAS + .remove(&fetched_schema_key(storage, path)) + .map(|(_, fetched)| fetched) +} + +/// Whether two schemas are the same but for the order of their top-level +/// fields, which is immaterial to a stored schema: its readers merge it by +/// field name. Nested types, nullability and metadata all have to match. +fn same_stored_schema(a: &Schema, b: &Schema) -> bool { + if a.metadata != b.metadata || a.fields.len() != b.fields.len() { + return false; + } + let by_name = |schema: &Schema| { + let mut fields = schema.fields.to_vec(); + fields.sort_by(|left, right| left.name().cmp(right.name())); + fields + }; + by_name(a) == by_name(b) +} + +/// Whether the schema object already holds `schema`, going by what this task +/// fetched for it just before: writing it again would change nothing. +/// +/// Only a fetch of this same task, moments ago, with no write of the object +/// through this store since, is relied on. What it cannot see is a write by +/// another process in those moments. The write skipped here would have +/// overwritten that one blindly; left alone, the object keeps what the other +/// process stored, which the next merge reads. +fn schema_is_stored(fetched: Option, schema: &Schema) -> bool { + fetched.is_some_and(|fetched| { + fetched.task == tokio::task::try_id() + && fetched.fetched.elapsed() < FETCHED_SCHEMA_TTL + && serde_json::from_slice::(&fetched.bytes) + .is_ok_and(|stored| same_stored_schema(&stored, schema)) + }) +} + #[async_trait] impl Metastore for $name { /// Since Parseable already starts with a connection to an object store, no need to implement this @@ -1204,7 +1299,7 @@ impl Metastore for $name { let path = partition_path(stream_name, lower_bound, upper_bound, tenant_id) .join(&manifest_file_name); - let encoded = encode_manifest_blocking(manifest.clone()).await?; + let encoded = encode_manifest_blocking(manifest).await?; let result = self.storage.put_object(&path, encoded, tenant_id).await; crate::metastore::metadata_cache::METADATA_CACHE.invalidate_stream(stream_name, tenant_id); @@ -1403,6 +1498,9 @@ impl Metastore for $name { STREAM_ROOT_DIRECTORY, schema_file, ]); + // Whether or not the write lands, what was fetched no longer + // tells what the object holds + drop(forget_fetched_schema(&self.storage, &path)); self.storage .put_object(&path, to_bytes(&merged), tenant_id) .await?; @@ -1415,12 +1513,15 @@ impl Metastore for $name { stream_name: &str, tenant_id: &Option, ) -> Result { - Ok(self - .storage - .get_object(&schema_path(stream_name, tenant_id), tenant_id) - .await?) + let path = schema_path(stream_name, tenant_id); + let bytes = self.storage.get_object(&path, tenant_id).await?; + remember_fetched_schema(&self.storage, &path, &bytes); + Ok(bytes) } + /// Stores the schema, unless the `get_schema` this task made just before + /// returned the same one: a merge that added nothing to the stored schema + /// writes nothing, and leaves the metadata cache as it is. async fn put_schema( &self, obj: Schema, @@ -1428,6 +1529,11 @@ impl Metastore for $name { tenant_id: &Option, ) -> Result<(), MetastoreError> { let path = schema_path(stream_name, tenant_id); + // Taken before the write, so that a failed write, which may still + // have landed, is not mistaken for the stored schema later + if schema_is_stored(forget_fetched_schema(&self.storage, &path), &obj) { + return Ok(()); + } let result = self .storage .put_object(&path, to_bytes(&obj), tenant_id) @@ -1711,3 +1817,297 @@ pub(crate) fn document_scope(key: &str) -> Option<(String, &'static str)> { super::postgres_documents::kind(relative_path::RelativePath::new(key)), )) } + +/// `put_schema` writes nothing when the `get_schema` of its task just before +/// returned the schema it is given, and writes in every other case. +#[cfg(test)] +mod schema_write_tests { + use std::{collections::HashMap, path::PathBuf, sync::Arc}; + + use arrow_schema::{DataType, Field, Schema}; + + use crate::{ + metastore::{ + metastore_traits::Metastore, metastores::object_store_metastore::ObjectStoreMetastore, + }, + storage::{ + LocalFS, ObjectStorage, + object_storage::{schema_path, to_bytes}, + }, + }; + + /// A store over a directory of its own, and the file of the stream's + /// schema in it + struct Stored { + store: Arc, + storage: Arc, + stream: &'static str, + file: PathBuf, + // Removed with the test + _dir: tempfile::TempDir, + } + + /// Bytes no write of a schema leaves in the file: the schema in another + /// field order and layout, as another writer could have stored it + fn marker(schema: &Schema) -> Vec { + let mut fields = schema.fields.to_vec(); + fields.reverse(); + serde_json::to_vec_pretty(&Schema::new_with_metadata(fields, schema.metadata.clone())) + .unwrap() + } + + impl Stored { + fn new(stream: &'static str) -> Self { + crate::parseable::install_default_test_parseable(); + let dir = tempfile::tempdir().unwrap(); + let storage = Arc::new(LocalFS::new(dir.path().to_owned())); + let file = schema_path(stream, &None).to_path(dir.path()); + // The test writes the file by itself too, to tell whether the + // store wrote it + std::fs::create_dir_all(file.parent().unwrap()).unwrap(); + Self { + store: Arc::new(ObjectStoreMetastore { + storage: storage.clone(), + }), + storage, + stream, + file, + _dir: dir, + } + } + + /// Fetches the schema, as a merge does first, and then marks the file + async fn fetch(&self, mark: &[u8]) -> Schema { + let fetched = self.store.get_schema(self.stream, &None).await.unwrap(); + std::fs::write(&self.file, mark).unwrap(); + serde_json::from_slice(&fetched).unwrap() + } + + async fn put(&self, schema: &Schema) { + self.store + .put_schema(schema.clone(), self.stream, &None) + .await + .unwrap(); + } + + fn file(&self) -> Vec { + std::fs::read(&self.file).unwrap() + } + + /// Whether a `put_schema` of `put`, right after a fetch that returned + /// `stored`, wrote the file + async fn writes(&self, stored: &Schema, put: &Schema) -> bool { + std::fs::write(&self.file, to_bytes(stored)).unwrap(); + let mark = marker(stored); + assert_eq!(&self.fetch(&mark).await, stored); + self.put(put).await; + if self.file() == mark { + return false; + } + assert_eq!(self.file(), to_bytes(put)); + true + } + } + + fn schema() -> Schema { + Schema::new(vec![ + Field::new("a", DataType::Int64, true), + Field::new("b", DataType::Utf8, true), + Field::new( + "c", + DataType::List(Arc::new(Field::new("item", DataType::Float64, true))), + true, + ), + ]) + } + + #[tokio::test] + async fn a_schema_just_fetched_is_not_written_again() { + let stored = Stored::new("schema-write-fetched"); + let schema = schema(); + // Nothing was fetched: the schema is written + stored.put(&schema).await; + assert_eq!(stored.file(), to_bytes(&schema)); + + assert!(!stored.writes(&schema, &schema).await); + // In another order of its fields too, which no reader tells apart + let mut fields = schema.fields.to_vec(); + fields.rotate_left(1); + assert!(!stored.writes(&schema, &Schema::new(fields)).await); + + // The fetch is relied on once. The same schema is written when + // nothing was fetched since. + let mark = marker(&schema); + stored.fetch(&mark).await; + stored.put(&schema).await; + assert_eq!(stored.file(), mark); + stored.put(&schema).await; + assert_eq!(stored.file(), to_bytes(&schema)); + } + + #[tokio::test] + async fn a_schema_that_differs_from_the_fetched_one_is_written() { + let stored = Stored::new("schema-write-differs"); + let schema = schema(); + let with = |index: usize, field: Field| { + let mut fields = schema.fields.to_vec(); + fields[index] = Arc::new(field); + Schema::new(fields) + }; + for other in [ + // What a merge stores: a field more + Schema::try_merge([ + schema.clone(), + Schema::new(vec![Field::new("d", DataType::Boolean, true)]), + ]) + .unwrap(), + Schema::new(schema.fields[..2].to_vec()), + Schema::empty(), + with(0, Field::new("a", DataType::Float64, true)), + with(0, Field::new("a", DataType::Int64, false)), + with(0, Field::new("A", DataType::Int64, true)), + with( + 1, + Field::new("b", DataType::Utf8, true) + .with_metadata(HashMap::from([("k".to_owned(), "v".to_owned())])), + ), + with( + 2, + Field::new( + "c", + DataType::List(Arc::new(Field::new("item", DataType::Float64, false))), + true, + ), + ), + schema + .clone() + .with_metadata(HashMap::from([("k".to_owned(), "v".to_owned())])), + ] { + assert!(stored.writes(&schema, &other).await, "{other:?}"); + assert!(stored.writes(&other, &schema).await, "{other:?}"); + assert!(!stored.writes(&other, &other).await, "{other:?}"); + } + } + + #[tokio::test] + async fn only_the_fetch_of_the_writing_task_and_store_is_relied_on() { + let stored = Stored::new("schema-write-task"); + let schema = schema(); + stored.put(&schema).await; + let mark = marker(&schema); + + // Fetched here, written by another task + stored.fetch(&mark).await; + let (store, written) = (stored.store.clone(), schema.clone()); + tokio::spawn(async move { + store + .put_schema(written, "schema-write-task", &None) + .await + .unwrap() + }) + .await + .unwrap(); + assert_eq!(stored.file(), to_bytes(&schema)); + + // Fetched and written by one task, other than this one + let (store, file, written, marked) = ( + stored.store.clone(), + stored.file.clone(), + schema.clone(), + mark.clone(), + ); + tokio::spawn(async move { + store.get_schema("schema-write-task", &None).await.unwrap(); + std::fs::write(file, marked).unwrap(); + store + .put_schema(written, "schema-write-task", &None) + .await + .unwrap(); + }) + .await + .unwrap(); + assert_eq!(stored.file(), mark); + + // Fetched through this store, written through another one of the + // same directory + std::fs::write(&stored.file, to_bytes(&schema)).unwrap(); + stored.fetch(&mark).await; + let other = ObjectStoreMetastore { + storage: Arc::new(LocalFS::new(stored._dir.path().to_owned())), + }; + other + .put_schema(schema.clone(), stored.stream, &None) + .await + .unwrap(); + assert_eq!(stored.file(), to_bytes(&schema)); + } + + /// `refresh_schema` writes the schema object by itself. What was fetched + /// before it is then not what the object holds. + #[tokio::test] + async fn a_refresh_that_writes_the_schema_voids_the_fetch() { + let stored = Stored::new("schema-write-refresh"); + let schema = schema(); + stored.put(&schema).await; + let fetched = stored.fetch(&to_bytes(&schema)).await; + assert_eq!(fetched, schema); + + // Another node's schema has a field this one lacks + let node = Schema::new(vec![Field::new("on_another_node", DataType::Utf8, true)]); + let node_path = schema_path(stored.stream, &None) + .parent() + .unwrap() + .join(".ingestor.other.schema"); + stored + .storage + .put_object(&node_path, to_bytes(&node), &None) + .await + .unwrap(); + let refreshed = stored + .store + .refresh_schema(stored.stream, &None, ".schema") + .await + .unwrap(); + assert!(refreshed.field_with_name("on_another_node").is_ok()); + assert_eq!( + serde_json::from_slice::(&stored.file()).unwrap(), + refreshed + ); + + // The schema fetched before the refresh is written, over the refresh + stored.put(&schema).await; + assert_eq!(stored.file(), to_bytes(&schema)); + } + + /// A write that is skipped changed nothing, and leaves the stream's + /// cached metadata in place. A write that is made drops it. + #[tokio::test] + async fn a_skipped_write_keeps_the_cached_metadata() { + use crate::{ + catalog::manifest::Manifest, + metastore::{MetastoreError, metadata_cache::METADATA_CACHE}, + }; + let stored = Stored::new("schema-write-cache"); + if !METADATA_CACHE.enabled() { + return; + } + let schema = schema(); + stored.put(&schema).await; + let cached = || { + METADATA_CACHE + .cached_manifest(stored.stream, &None, "m") + .is_some() + }; + METADATA_CACHE + .manifest(stored.stream, &None, "m", || async { + Ok::<_, MetastoreError>(Some(Manifest::default())) + }) + .await + .unwrap(); + assert!(cached()); + assert!(!stored.writes(&schema, &schema).await); + assert!(cached()); + stored.put(&schema).await; + assert!(!cached()); + } +} From 0a265c0f3714679d6d6ca85e6e52baeffdd84817 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:22:11 -0600 Subject: [PATCH 06/17] Bound HotTier and Kafka resource use and preserve failed Kafka offsets --- src/cli.rs | 45 +- src/connectors/kafka/consumer.rs | 101 ++- src/connectors/kafka/partition_stream.rs | 161 ++-- src/connectors/kafka/processor.rs | 341 ++++++--- src/connectors/kafka/rebalance_listener.rs | 7 +- src/connectors/kafka/sink.rs | 15 +- src/connectors/mod.rs | 13 +- src/hottier.rs | 702 +++++++++++++----- src/hottier/local_state.rs | 12 +- src/hottier/planner.rs | 126 ++-- .../metastores/postgres_metastore.rs | 63 +- src/storage/retention.rs | 23 +- 12 files changed, 1120 insertions(+), 489 deletions(-) diff --git a/src/cli.rs b/src/cli.rs index ce904c4a7..7e0431ebe 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -42,8 +42,8 @@ pub const DEFAULT_MAX_FLATTEN_BYTES_PER_REQUEST: usize = 64 * 1024 * 1024; // The upload default equals the number of uploads a single stream ran at once // before these caps existed, so one stream syncs as it did then. The stream default // lets a 100-stream sync wave through without queueing -pub const DEFAULT_MAX_CONCURRENT_OBJECT_STORE_UPLOADS: usize = 100; -pub const DEFAULT_MAX_CONCURRENT_STREAM_SYNCS: usize = 100; +pub const DEFAULT_MAX_CONCURRENT_OBJECT_STORE_UPLOADS: usize = 32; +pub const DEFAULT_MAX_CONCURRENT_STREAM_SYNCS: usize = 32; const DEFAULT_PARQUET_METADATA_CACHE_SIZE: usize = 50 * 1024 * 1024; // 50 MB pub const DEFAULT_PARQUET_ROW_GROUP_BYTES: usize = 128 * 1024 * 1024; // 128 MiB #[derive(Parser)] @@ -502,7 +502,7 @@ pub struct Options { #[arg( long, env = "P_MEMORY_STAGING_MAX_BYTES", - help = "Maximum bytes of Arrow batches cached in memory across all streams to serve queries of staged (not yet converted) rows. Rows over the budget are read from their staging files instead. 0 disables the cache, auto/empty uses 25% of effective memory" + help = "Maximum bytes of Arrow batches cached in memory across all streams to serve queries of staged (not yet converted) rows. Rows over the budget are read from their staging files instead. 0 disables the cache, auto/empty uses the smaller of 10% of effective RAM and 512 MiB" )] pub memory_staging_max_bytes: Option, @@ -578,7 +578,7 @@ pub struct Options { long, env = "P_LOG_SEVERITY_CLUSTER_COLUMN", value_parser = validation::cluster_column, - help = "Ordered comma-separated top-level log columns (maximum 16); first present supported column clusters each Parquet row group; unset disables clustering" + help = "Comma-separated clustering choices for Parquet row groups (maximum 16). The first supported choice present is used. Join columns with + for composite clustering, e.g. level+app. Unset disables clustering." )] pub log_severity_cluster_column: Option, @@ -602,7 +602,7 @@ pub struct Options { #[arg( long = "compression-algo", env = "P_PARQUET_COMPRESSION_ALGO", - default_value = "lz4_raw", + default_value = "zstd", value_parser = validation::compression, help = "Parquet compression algorithm" )] @@ -878,9 +878,9 @@ pub struct Options { #[arg( long, env = "P_MULTIPART_MIN_SIZE", - default_value = "26214400", - value_parser = clap::value_parser!(u64).range(26214400..), - help = "Minimum file size for multipart uploads (25MB)" + default_value = "16777216", + value_parser = clap::value_parser!(u64).range(5_242_880..), + help = "Minimum file size in bytes for multipart uploads (at least 5 MiB)" )] pub min_multipart_size: u64, } @@ -1076,6 +1076,35 @@ mod tests { use super::{DEFAULT_PARQUET_ROW_GROUP_BYTES, Options}; use crate::{event::DEFAULT_TIMESTAMP_KEY, metadata::LogStreamMetadata, parseable::Stream}; + #[test] + fn storage_resource_defaults_and_overrides() { + use crate::option::Compression; + + let defaults = Options::try_parse_from(["parseable"]).unwrap(); + assert_eq!(defaults.parquet_compression, Compression::Zstd); + assert_eq!(defaults.min_multipart_size, 16 * 1024 * 1024); + assert_eq!(defaults.max_concurrent_object_store_uploads, 32); + assert_eq!(defaults.max_concurrent_stream_syncs, 32); + + let overrides = Options::try_parse_from([ + "parseable", + "--compression-algo", + "lz4_raw", + "--min-multipart-size", + "5242880", + "--max-concurrent-object-store-uploads", + "4", + "--max-concurrent-stream-syncs", + "2", + ]) + .unwrap(); + assert_eq!(overrides.parquet_compression, Compression::Lz4Raw); + assert_eq!(overrides.min_multipart_size, 5 * 1024 * 1024); + assert_eq!(overrides.max_concurrent_object_store_uploads, 4); + assert_eq!(overrides.max_concurrent_stream_syncs, 2); + assert!(Options::try_parse_from(["parseable", "--min-multipart-size", "5242879"]).is_err()); + } + #[test] fn parquet_row_group_bytes_cli_defaults_and_overrides() { let defaults = Options::try_parse_from(["parseable"]).unwrap(); diff --git a/src/connectors/kafka/consumer.rs b/src/connectors/kafka/consumer.rs index 97baaf266..72d658d0d 100644 --- a/src/connectors/kafka/consumer.rs +++ b/src/connectors/kafka/consumer.rs @@ -18,11 +18,9 @@ use crate::connectors::common::ConnectorError; use crate::connectors::common::shutdown::Shutdown; -use crate::connectors::kafka::partition_stream::{PartitionStreamReceiver, PartitionStreamSender}; +use crate::connectors::kafka::partition_stream::PartitionStreamReceiver; use crate::connectors::kafka::state::StreamState; -use crate::connectors::kafka::{ - ConsumerRecord, KafkaContext, StreamConsumer, TopicPartition, partition_stream, -}; +use crate::connectors::kafka::{KafkaContext, StreamConsumer, TopicPartition, partition_stream}; use futures_util::FutureExt; use rdkafka::Message; use rdkafka::Statistics; @@ -79,6 +77,10 @@ impl KafkaStreams { Arc::clone(&self.consumer) } + pub(super) fn shutdown_handle(&self) -> Shutdown { + self.shutdown_handle.clone() + } + pub fn statistics(&self) -> Arc> { Arc::clone(&self.statistics) } @@ -133,12 +135,11 @@ impl KafkaStreams { tokio_handle.block_on(async move { loop { let result: Result<(), ConnectorError> = tokio::select! { - result = consumer.recv() => { - match result { - Ok(msg) => KafkaStreams::handle_message(msg, &stream_state, &stream_tx, configured_tenant.as_deref(), multi_tenant).await.map_err(Into::into), - Err(e) => Err(e.into()) - } - } + result = async { + let msg = consumer.recv().await?; + KafkaStreams::handle_message(msg, &stream_state, &stream_tx, configured_tenant.as_deref(), multi_tenant) + .await.map_err(|err| ConnectorError::Fatal(err.to_string())) + } => result, _ = shutdown_handle.recv() => { KafkaStreams::shutdown(&consumer, &stream_state).await; break; @@ -183,52 +184,29 @@ impl KafkaStreams { multi_tenant: bool, ) -> anyhow::Result<()> { let tp = TopicPartition::new(msg.topic().to_owned(), msg.partition()); - let consumer_record = ConsumerRecord::from_message(msg, configured_tenant, multi_tenant); - let mut state = stream_state.write().await; - - let partition_stream_tx = - KafkaStreams::get_or_create_partition_stream(&mut state, stream_tx, tp).await; - partition_stream_tx.send(consumer_record).await; - - Ok(()) - } - - async fn get_or_create_partition_stream( - state: &mut StreamState, - stream_tx: &mpsc::Sender, - tp: TopicPartition, - ) -> PartitionStreamSender { - if let Some(ps_tx) = state.get_partition_sender(&tp) { - ps_tx.clone() - } else { - Self::create_new_partition_stream(state, stream_tx, tp).await - } - } - - async fn create_new_partition_stream( - state: &mut StreamState, - stream_tx: &mpsc::Sender, - tp: TopicPartition, - ) -> PartitionStreamSender { - info!("Creating new stream for {:?}", tp); - - let (ps_tx, ps_rx) = partition_stream::bounded(100_000, tp.clone()); - state.insert_partition_sender(tp.clone(), ps_tx.clone()); - - if let Err(e) = stream_tx.send(ps_rx).await { - error!( - "Failed to send partition stream receiver for {:?}: {:?}", - tp, e - ); + let (sender, new_receiver) = { + let mut state = stream_state.write().await; + if let Some(sender) = state.get_partition_sender(&tp) { + (sender.clone(), None) + } else { + info!("Creating new stream for {:?}", tp); + let (sender, receiver) = partition_stream::bounded(10_000, tp.clone()); + state.insert_partition_sender(tp, sender.clone()); + (sender, Some(receiver)) + } + }; + if let Some(receiver) = new_receiver { + stream_tx + .send(receiver) + .await + .map_err(|_| anyhow::anyhow!("Kafka stream listener closed"))?; } - - ps_tx + sender.send(msg, configured_tenant, multi_tenant).await } async fn shutdown(consumer: &Arc, stream_state: &RwLock) { info!("Gracefully stopping kafka partition streams!"); - let mut state = stream_state.write().await; - state.clear(); + stream_state.write().await.clear(); consumer.unsubscribe(); } @@ -273,8 +251,27 @@ impl KafkaStreams { #[cfg(test)] mod routing_tests { use super::*; + use crate::connectors::kafka::ConsumerRecord; use futures_util::StreamExt; + #[tokio::test] + async fn publishing_a_new_receiver_does_not_block_revocation() { + let state = RwLock::new(StreamState::new(1)); + let (tx, _rx) = mpsc::channel(1); + let (_sender, first) = partition_stream::bounded(1, TopicPartition::new("first".into(), 0)); + tx.send(first).await.unwrap(); + let routing = KafkaStreams::handle_message( + crate::connectors::kafka::message_conversion_tests::message("tenant-b"), + &state, + &tx, + Some("tenant-a"), + true, + ); + tokio::pin!(routing); + assert!(futures_util::poll!(&mut routing).is_pending()); + assert!(state.try_write().is_ok()); + } + #[tokio::test] async fn rejected_record_is_delivered_to_partition_stream_receiver() { let state = RwLock::new(StreamState::new(1)); @@ -303,7 +300,7 @@ mod routing_tests { .expect("marker must be routed to the partition receiver") .unwrap(); assert_eq!( - record, + record.record, ConsumerRecord::new( None, None, diff --git a/src/connectors/kafka/partition_stream.rs b/src/connectors/kafka/partition_stream.rs index a6f5070df..ece1bcdf0 100644 --- a/src/connectors/kafka/partition_stream.rs +++ b/src/connectors/kafka/partition_stream.rs @@ -18,76 +18,87 @@ use crate::connectors::kafka::{ConsumerRecord, TopicPartition}; use std::sync::Arc; -use tokio::sync::{Notify, mpsc}; +use tokio::sync::{OwnedSemaphorePermit, Semaphore, mpsc}; use tokio_stream::wrappers::ReceiverStream; -use tracing::{error, info}; +use tokio_util::sync::CancellationToken; +use tracing::info; + +pub(super) const PARTITION_BYTES: u32 = 32 * 1024 * 1024; + +/// The byte reservation follows the record through queuing, batching and staging. +pub struct QueuedRecord { + pub(super) record: ConsumerRecord, + pub(super) permit: OwnedSemaphorePermit, +} #[derive(Clone)] pub struct PartitionStreamSender { - inner: mpsc::Sender, - notify: Arc, + inner: mpsc::Sender, + bytes: Arc, + revoked: CancellationToken, } impl PartitionStreamSender { - fn new(inner: mpsc::Sender, notify: Arc) -> Self { - Self { inner, notify } - } - pub fn terminate(&self) { - self.notify.notify_waiters(); + self.revoked.cancel(); } - pub async fn send(&self, consumer_record: ConsumerRecord) { - if let Err(e) = self.inner.send(consumer_record).await { - error!("Failed to send message to partition stream: {:?}", e); + pub(super) async fn send( + &self, + msg: M, + configured_tenant: Option<&str>, + multi_tenant: bool, + ) -> anyhow::Result<()> { + let charge = msg + .payload() + .map_or(0, <[u8]>::len) + .saturating_add(msg.key().map_or(0, <[u8]>::len)) + .clamp(1, PARTITION_BYTES as usize) as u32; + // Reserve before copying the librdkafka payload. An oversized record + // takes all permits and runs alone, so it can always make progress. + let result = tokio::select! { + biased; + _ = self.revoked.cancelled() => return Ok(()), + _ = self.inner.closed() => Err(anyhow::anyhow!("Kafka partition receiver closed")), + result = async { + let mut permit = self.bytes.clone().acquire_many_owned(charge).await?; + let slot = self.inner.reserve().await?; + let record = ConsumerRecord::from_message(msg, configured_tenant, multi_tenant); + if record.payload.is_none() && record.key.is_none() && charge > 1 { + drop(permit.split((charge - 1) as usize)); + } + slot.send(QueuedRecord { record, permit }); + Ok(()) + } => result, + }; + if self.revoked.is_cancelled() { + Ok(()) + } else { + result } } - - pub fn sender(&self) -> mpsc::Sender { - self.inner.clone() - } } pub struct PartitionStreamReceiver { - inner: ReceiverStream, + inner: ReceiverStream, topic_partition: TopicPartition, - notify: Arc, + revoked: CancellationToken, } impl PartitionStreamReceiver { - fn new( - receiver: mpsc::Receiver, - topic_partition: TopicPartition, - notify: Arc, - ) -> Self { - Self { - inner: ReceiverStream::new(receiver), - topic_partition, - notify, - } - } - - /// Processes the stream with a provided callback and listens for termination. - /// - /// # Parameters - /// - `invoke`: A callback function that processes the `ReceiverStream`. - /// - /// # Behavior - /// - The callback runs until either the stream is completed or a termination signal is received. pub async fn run_drain(self, f: F) where - F: Fn(ReceiverStream) -> Fut, + F: Fn(ReceiverStream) -> Fut, Fut: futures_util::Future, { - let notify = self.notify.clone(); - tokio::select! { + biased; + _ = self.revoked.cancelled() => { + info!("Received termination signal for {:?}.", self.topic_partition); + } _ = f(self.inner) => { info!("PartitionStreamReceiver completed processing for {:?}.", self.topic_partition); } - _ = notify.notified() => { - info!("Received termination signal for {:?}.", self.topic_partition); - } } } @@ -101,10 +112,66 @@ pub fn bounded( topic_partition: TopicPartition, ) -> (PartitionStreamSender, PartitionStreamReceiver) { let (tx, rx) = mpsc::channel(size); - let notify = Arc::new(Notify::new()); + let revoked = CancellationToken::new(); + let sender = PartitionStreamSender { + inner: tx, + bytes: Arc::new(Semaphore::new(PARTITION_BYTES as usize)), + revoked: revoked.clone(), + }; + let receiver = PartitionStreamReceiver { + inner: ReceiverStream::new(rx), + topic_partition, + revoked, + }; + (sender, receiver) +} - let sender = PartitionStreamSender::new(tx, notify.clone()); - let receiver = PartitionStreamReceiver::new(rx, topic_partition, notify); +#[cfg(test)] +mod tests { + use super::*; + use futures_util::StreamExt; - (sender, receiver) + fn message() -> rdkafka::message::OwnedMessage { + rdkafka::message::OwnedMessage::new( + Some(vec![0; 3]), + Some(vec![0; 2]), + "logs".into(), + rdkafka::message::Timestamp::NotAvailable, + 0, + 0, + None, + ) + } + + #[tokio::test] + async fn partition_bytes_apply_backpressure_until_processing_releases_the_record() { + let (tx, mut rx) = bounded(10_000, TopicPartition::new("logs".into(), 0)); + let _other_records = tx + .bytes + .clone() + .acquire_many_owned(PARTITION_BYTES - 5) + .await + .unwrap(); + tx.send(message(), None, false).await.unwrap(); + let next = tx.send(message(), None, false); + tokio::pin!(next); + assert!(futures_util::poll!(&mut next).is_pending()); + let processing = rx.inner.next().await.unwrap(); + assert!(futures_util::poll!(&mut next).is_pending()); + drop(processing); + next.await.unwrap(); + } + + #[tokio::test] + async fn revoke_cancels_queued_receiver_and_blocked_sender() { + let (tx, rx) = bounded(1, TopicPartition::new("logs".into(), 0)); + tx.send(message(), None, false).await.unwrap(); + let next = tx.send(message(), None, false); + tokio::pin!(next); + assert!(futures_util::poll!(&mut next).is_pending()); + tx.terminate(); + next.await.unwrap(); + rx.run_drain(|_| async { panic!("revoked receiver ran") }) + .await; + } } diff --git a/src/connectors/kafka/processor.rs b/src/connectors/kafka/processor.rs index 6250a9b61..f23b0f901 100644 --- a/src/connectors/kafka/processor.rs +++ b/src/connectors/kafka/processor.rs @@ -24,13 +24,13 @@ //! Schemas are accumulated in record order and published as one union; only //! conflicting records are skipped, without adding any of their fields. //! -//! Offsets are committed after processing, including when records are skipped or -//! processing fails. Storage is not atomic across the chunk: a later store error -//! can leave earlier records stored while the rest are dropped (tracked separately). +//! A failed chunk retries in place and holds back later offset commits. A retry +//! can replay records staged before a storage error in the same chunk. +use super::partition_stream::{PARTITION_BYTES, QueuedRecord}; use crate::{ LOCK_EXPECT, - connectors::common::processor::Processor, + connectors::common::{processor::Processor, shutdown::Shutdown}, event::{ Event, USER_AGENT_KEY, error::EventError, @@ -51,11 +51,31 @@ use serde_json::Value; use std::collections::HashMap; use std::num::NonZeroU32; use std::sync::{Arc, RwLock}; +use std::time::Duration; use tokio_stream::wrappers::ReceiverStream; use tracing::{debug, error, warn}; use super::{ConsumerRecord, StreamConsumer, TopicPartition, config::BufferConfig}; +// Keep the byte reservation with the data. A Rayon job can outlive the async +// worker on revocation, and must hold its permits until its records are dropped. +struct PartitionBatch { + records: Vec, + _bytes: tokio::sync::OwnedSemaphorePermit, +} + +#[derive(Clone)] +pub struct BatchAttempt { + batch: Arc, + retrying: bool, +} + +impl BatchAttempt { + pub fn records(&self) -> &[ConsumerRecord] { + &self.batch.records + } +} + #[derive(Default, Debug, Clone)] pub struct ParseableSinkProcessor; @@ -117,21 +137,20 @@ impl StreamMeta { /// poll/commit/recv), same reasoning as the rayon offload used for otel and /// prometheus remote-write ingestion. fn build_and_process_event( - records: Vec, + attempt: BatchAttempt, stream_name: String, tenant_id: Option, meta: StreamMeta, ) -> anyhow::Result<()> { - // Offsets are committed whether or not the chunk is ingested and the - // producer gets no rejection signal, so the dataset field limit is not - // enforced here: rejecting would silently drop the whole chunk. - let mut events = build_events(&records, &stream_name, &tenant_id, &meta)?; - if meta.is_partitioned() && !events.is_empty() { + let mut events = build_events(attempt.records(), &stream_name, &tenant_id, &meta); + if !events.is_empty() && (meta.is_partitioned() || events.len() > 1 || attempt.retrying) { // Select schemas in source order, then stage the accepted union once. let stream = PARSEABLE.get_stream(&stream_name, &tenant_id)?; let (accepted, committed) = commit_compatible_events(&stream.metadata, events)?; events = accepted; - finish_schema_commit(&mut events, committed, || { + // A previous attempt may have published the schema in memory and then + // failed to stage it. Re-stage the accepted schema before replay. + finish_schema_commit(&mut events, committed || attempt.retrying, || { if !stream.get_static_schema_flag() { stream.stage_schema_file(stream.get_schema().as_ref().clone())?; } @@ -249,7 +268,7 @@ fn build_events<'a>( stream_name: &str, tenant_id: &Option, meta: &StreamMeta, -) -> anyhow::Result>> { +) -> Vec> { let mut p_custom_fields = HashMap::new(); p_custom_fields.insert(USER_AGENT_KEY.to_string(), "kafka".to_string()); @@ -324,23 +343,42 @@ fn build_events<'a>( && !json_vec.is_empty() && let Some(record) = records.first() { - events.push(RecordEvent { - event: into_event(Value::Array(json_vec), total_payload_size)?, - record, - }); + match into_event(Value::Array(json_vec), total_payload_size) { + Ok(event) => events.push(RecordEvent { event, record }), + Err(_) => { + // Isolate permanently malformed input before retryable staging. + // Reparse on this error path to avoid cloning the normal batch. + for record in records { + let Some(payload) = &record.payload else { + continue; + }; + let Ok(value) = serde_json::from_slice(payload) else { + continue; + }; + match into_event(Value::Array(vec![value]), payload.len() as u64) { + Ok(event) => events.push(RecordEvent { event, record }), + Err(err) => { + let _span = record_span(record).entered(); + warn!(error = %err, "Skipping Kafka record that failed event conversion"); + } + } + } + } + } } - Ok(events) + events } #[async_trait] -impl Processor, ()> for ParseableSinkProcessor { - async fn process(&self, records: Vec) -> anyhow::Result<()> { +impl Processor for ParseableSinkProcessor { + async fn process(&self, attempt: BatchAttempt) -> anyhow::Result<()> { + let records = attempt.records(); let len = records.len(); debug!("Processing {len} records"); // Offset-only markers and tombstones need no stream or metadata access. - if !chunk_needs_stream(&records) { + if !chunk_needs_stream(records) { return Ok(()); } @@ -351,7 +389,7 @@ impl Processor, ()> for ParseableSinkProcessor { let (tx, rx) = tokio::sync::oneshot::channel(); rayon::spawn(move || { - let res = build_and_process_event(records, stream_name, tenant_id, meta); + let res = build_and_process_event(attempt, stream_name, tenant_id, meta); let _ = tx.send(res); }); rx.await??; @@ -364,18 +402,19 @@ impl Processor, ()> for ParseableSinkProcessor { #[derive(Clone)] pub struct StreamWorker

where - P: Processor, ()>, + P: Processor, { processor: Arc

, consumer: Arc, buffer_config: BufferConfig, + shutdown: Shutdown, } impl

StreamWorker

where - P: Processor, ()> + Send + Sync + 'static, + P: Processor + Send + Sync + 'static, { - pub fn new(processor: Arc

, consumer: Arc) -> Self { + pub fn new(processor: Arc

, consumer: Arc, shutdown: Shutdown) -> Self { let buffer_config = consumer .context() .config() @@ -387,29 +426,31 @@ where processor, consumer, buffer_config, + shutdown, } } pub async fn process_partition( &self, tp: TopicPartition, - record_stream: ReceiverStream, + record_stream: ReceiverStream, ) -> anyhow::Result<()> { - let chunked_stream = tokio_stream::StreamExt::chunks_timeout( - record_stream, - self.buffer_config.buffer_size, - self.buffer_config.buffer_timeout, - ); - - process_partition_chunks(self.processor.as_ref(), tp, chunked_stream, |tpl| { - // Synchronous commits avoid librdkafka's asynchronous commit race. - if let Err(e) = self.consumer.commit(tpl, CommitMode::Sync) { - error!(error = %e, "Failed to commit offsets for {:?}", tpl); - } else { - debug!("Committed offsets for {:?}", tpl); - } - }) - .await; + let chunked_stream = partition_chunks(record_stream, &self.buffer_config); + process_partition_chunks( + self.processor.as_ref(), + tp, + &self.shutdown, + chunked_stream, + |tpl| { + // Synchronous commits avoid librdkafka's asynchronous commit race. + if let Err(e) = self.consumer.commit(tpl, CommitMode::Sync) { + error!(error = %e, "Failed to commit offsets for {:?}", tpl); + } else { + debug!("Committed offsets for {:?}", tpl); + } + }, + ) + .await?; self.processor.post_stream().await?; @@ -425,38 +466,76 @@ fn chunk_needs_stream(records: &[ConsumerRecord]) -> bool { records.iter().any(|record| record.payload.is_some()) } +/// Flush by bytes as well as count and time. Otherwise a worker holding the +/// partition's permits could wait the full batch timeout for the next record. +fn partition_chunks( + receiver: ReceiverStream, + config: &BufferConfig, +) -> impl futures_util::Stream { + let max_records = config.buffer_size; + let timeout = config.buffer_timeout; + futures_util::stream::unfold(receiver, move |mut receiver| async move { + let first = receiver.next().await?; + let deadline = tokio::time::Instant::now() + timeout; + let mut records = vec![first.record]; + let mut bytes = first.permit; + while records.len() < max_records && bytes.num_permits() < PARTITION_BYTES as usize / 4 { + let Ok(Some(next)) = tokio::time::timeout_at(deadline, receiver.next()).await else { + break; + }; + records.push(next.record); + bytes.merge(next.permit); + } + Some(( + PartitionBatch { + records, + _bytes: bytes, + }, + receiver, + )) + }) +} + /// Process chunks concurrently, yielding commit offsets in partition input order. async fn process_partition_chunks( processor: &P, tp: TopicPartition, + shutdown: &Shutdown, chunks: S, mut commit: impl FnMut(&rdkafka::TopicPartitionList), -) where - P: Processor, ()>, - S: futures_util::Stream>, +) -> anyhow::Result<()> +where + P: Processor, + S: futures_util::Stream, { - let completed = chunks.map(|records| { + let completed = chunks.map(|batch| { let tp = &tp; async move { - let last_record = records.iter().max_by_key(|r| r.offset)?; - let tpl = last_record.offset_to_commit().unwrap(); - let record_count = records.len(); - if let Err(e) = processor.process(records).await { - // Preserve the connector's existing drop-on-processing-error policy. - error!( - "Failed to process {} records for {:?}; offsets up to {:?} will still be committed and these records are dropped: {:?}", - record_count, tp, tpl, e - ); + let Some(last) = batch.records.iter().max_by_key(|r| r.offset) else { + return Ok::<_, anyhow::Error>(None); + }; + let tpl = last.offset_to_commit()?; + let mut attempt = BatchAttempt { batch: Arc::new(batch), retrying: false }; + let mut delay = Duration::from_secs(1); + while let Err(err) = processor.process(attempt.clone()).await { + attempt.retrying = true; + warn!(?tp, offsets = ?tpl, %err, ?delay, "Kafka staging failed; retrying chunk before committing"); + tokio::select! { + _ = shutdown.recv() => return Err(err), + _ = tokio::time::sleep(delay) => {} + } + delay = (delay * 2).min(Duration::from_secs(30)); } - Some(tpl) + Ok(Some(tpl)) } }).buffered(MAX_IN_FLIGHT_CHUNKS_PER_PARTITION); futures_util::pin_mut!(completed); - while let Some(tpl) = completed.next().await { - if let Some(tpl) = tpl { + while let Some(result) = completed.next().await { + if let Some(tpl) = result? { commit(&tpl); } } + Ok(()) } #[cfg(test)] @@ -504,7 +583,7 @@ mod tests { schema: meta.schema.clone(), ..Default::default() }); - let events = build_events(&records, "test", &None, &meta).unwrap(); + let events = build_events(&records, "test", &None, &meta); assert_eq!(events.len(), 2); assert!(events.iter().all(|event| event.event.is_first_event)); @@ -531,8 +610,7 @@ mod tests { fn staging_failure_leaves_inference_flags_set() { let _guard = TEST_LOCK.lock().unwrap(); let records = vec![record(r#"{"region":"west","n":1}"#)]; - let mut events = - build_events(&records, "test", &None, &stream_meta(Some("region"))).unwrap(); + let mut events = build_events(&records, "test", &None, &stream_meta(Some("region"))); let result = finish_schema_commit(&mut events, true, || { Err(ArrowError::SchemaError("staging failed".to_owned()).into()) }); @@ -578,8 +656,7 @@ mod tests { )) }) .collect(); - let events = - build_events(&records, "test", &None, &stream_meta(Some("region"))).unwrap(); + let events = build_events(&records, "test", &None, &stream_meta(Some("region"))); let base_fields = events[0].event.rb.schema().fields().len() - 1; let metadata = RwLock::new(LogStreamMetadata::default()); let (accepted, committed) = commit_compatible_events(&metadata, events).unwrap(); @@ -602,7 +679,7 @@ mod tests { fn static_schema_chunk_keeps_metadata_and_does_not_stage() { let _guard = TEST_LOCK.lock().unwrap(); let records = vec![record(r#"{"region":"west","new_field":1}"#)]; - let events = build_events(&records, "test", &None, &stream_meta(Some("region"))).unwrap(); + let events = build_events(&records, "test", &None, &stream_meta(Some("region"))); let metadata = RwLock::new(LogStreamMetadata { static_schema_flag: true, ..Default::default() @@ -624,7 +701,7 @@ mod tests { ]; let meta = stream_meta(Some("region")); let metadata = RwLock::new(LogStreamMetadata::default()); - let events = build_events(&records, "test", &None, &meta).unwrap(); + let events = build_events(&records, "test", &None, &meta); let (accepted, committed) = commit_compatible_events(&metadata, events).unwrap(); assert!(committed); @@ -663,7 +740,7 @@ mod tests { ..Default::default() }); let before = metadata.read().unwrap().schema.clone(); - let events = build_events(&records, "test", &None, &meta).unwrap(); + let events = build_events(&records, "test", &None, &meta); assert_eq!(events.len(), 2); let (accepted, committed) = commit_compatible_events(&metadata, events).unwrap(); @@ -725,7 +802,7 @@ mod tests { .finish(); let check = || { let meta = stream_meta(Some("region")); - let events = build_events(&records, "test", &None, &meta).unwrap(); + let events = build_events(&records, "test", &None, &meta); let metadata = RwLock::new(LogStreamMetadata::default()); let (accepted, _) = commit_compatible_events(&metadata, events).unwrap(); assert_eq!(accepted.len(), 1); @@ -735,8 +812,7 @@ mod tests { "test", &None, &time_stream_meta(None, Some(1)), - ) - .unwrap(); + ); assert!(events.is_empty()); }; tracing::subscriber::with_default(subscriber, check); @@ -780,8 +856,7 @@ mod tests { "test", &tenant_id, &stream_meta(Some(" region , status ")), - ) - .unwrap(); + ); assert_eq!(events.len(), 2); for (event, record_index, region, status) in [ @@ -816,7 +891,7 @@ mod tests { record(r#"{"region": "east", "p_timestamp": "reserved"}"#), record(r#"{"region": "north", "n": 2}"#), ]; - let events = build_events(&records, "test", &None, &stream_meta(Some("region"))).unwrap(); + let events = build_events(&records, "test", &None, &stream_meta(Some("region"))); let regions: Vec<_> = events .iter() @@ -845,7 +920,7 @@ mod tests { record(r#""west""#), record(r#"{"region": false}"#), ]; - let events = build_events(&records, "test", &None, &stream_meta(Some("region"))).unwrap(); + let events = build_events(&records, "test", &None, &stream_meta(Some("region"))); assert_eq!(events.len(), 1); assert_eq!( @@ -876,7 +951,7 @@ mod tests { let meta = time_stream_meta(None, Some(1)); // A single-record chunk must also avoid the batch-array path. for chunk in [&records[..1], &records[..]] { - let events = build_events(chunk, "test", &None, &meta).unwrap(); + let events = build_events(chunk, "test", &None, &meta); assert_eq!(events.len(), chunk.len()); for (index, event) in events.iter().enumerate() { assert_eq!( @@ -911,8 +986,7 @@ mod tests { record("null"), timed_record(now, "east"), ]; - let events = - build_events(&records, "test", &None, &time_stream_meta(None, Some(1))).unwrap(); + let events = build_events(&records, "test", &None, &time_stream_meta(None, Some(1))); assert_eq!(events.len(), 2); assert!(std::ptr::eq(events[0].record, &records[0])); assert!(std::ptr::eq(events[1].record, &records[9])); @@ -929,8 +1003,7 @@ mod tests { timed_record(now - chrono::Duration::days(old_days), "old"), timed_record(accepted, "accepted"), ]; - let events = - build_events(&records, "test", &None, &time_stream_meta(None, limit)).unwrap(); + let events = build_events(&records, "test", &None, &time_stream_meta(None, limit)); assert_eq!(events.len(), 1); assert!(std::ptr::eq(events[0].record, &records[1])); assert_eq!(events[0].event.parsed_timestamp, accepted.naive_utc()); @@ -948,8 +1021,7 @@ mod tests { timed_record(now - chrono::Duration::hours(max_age + 1), "old"), timed_record(now + chrono::Duration::minutes(1), "new"), ]; - let events = - build_events(&records, "test", &None, &time_stream_meta(None, Some(30))).unwrap(); + let events = build_events(&records, "test", &None, &time_stream_meta(None, Some(30))); assert_eq!(events.len(), 2); assert!(std::ptr::eq(events[0].record, &records[0])); assert!(std::ptr::eq(events[1].record, &records[2])); @@ -969,7 +1041,7 @@ mod tests { timed_record(second, "east"), ]; let meta = time_stream_meta(Some("region"), Some(1)); - let events = build_events(&records, "test", &None, &meta).unwrap(); + let events = build_events(&records, "test", &None, &meta); assert_eq!(events.len(), 2); for (event, index, timestamp, region) in [ (&events[0], 1, now, "west"), @@ -993,7 +1065,7 @@ mod tests { record("not json"), record(r#"{"message": "second"}"#), ]; - let events = build_events(&records, "test", &None, &stream_meta(None)).unwrap(); + let events = build_events(&records, "test", &None, &stream_meta(None)); assert_eq!(events.len(), 1); assert_eq!(events[0].event.rb.num_rows(), 2); @@ -1007,6 +1079,20 @@ mod tests { ); } + #[test] + fn invalid_non_partitioned_record_does_not_drop_or_block_its_neighbors() { + let _guard = TEST_LOCK.lock().unwrap(); + let records = [ + record(r#"{"message":"first"}"#), + record(r#"{"p_timestamp":"reserved"}"#), + record(r#"{"message":"last"}"#), + ]; + let events = build_events(&records, "test", &None, &stream_meta(None)); + assert_eq!(events.len(), 2); + assert!(std::ptr::eq(events[0].record, &records[0])); + assert!(std::ptr::eq(events[1].record, &records[2])); + } + #[test] fn empty_or_invalid_chunks_build_no_events() { let _guard = TEST_LOCK.lock().unwrap(); @@ -1015,12 +1101,8 @@ mod tests { let invalid_records = vec![record("not json"), missing_payload]; for custom_partition in [None, Some("region")] { let meta = stream_meta(custom_partition); - assert!(build_events(&[], "test", &None, &meta).unwrap().is_empty()); - assert!( - build_events(&invalid_records, "test", &None, &meta) - .unwrap() - .is_empty() - ); + assert!(build_events(&[], "test", &None, &meta).is_empty()); + assert!(build_events(&invalid_records, "test", &None, &meta).is_empty()); } } } @@ -1034,6 +1116,15 @@ mod offset_marker_tests { ConsumerRecord::new(None, None, "rejected".into(), 2, offset, Some(123), None) } + fn batch(records: Vec) -> PartitionBatch { + PartitionBatch { + records, + _bytes: Arc::new(tokio::sync::Semaphore::new(1)) + .try_acquire_owned() + .unwrap(), + } + } + fn committed_offset(tpl: &rdkafka::TopicPartitionList) -> i64 { assert_eq!(tpl.count(), 1); let entry = tpl.find_partition("rejected", 2).unwrap(); @@ -1045,6 +1136,7 @@ mod offset_marker_tests { #[tokio::test] async fn all_rejected_partition_commits_next_offset() { + let shutdown = Shutdown::default(); let mut commits = Vec::new(); process_partition_chunks( &GatedProcessor { @@ -1052,21 +1144,72 @@ mod offset_marker_tests { processed: Mutex::new(Vec::new()), }, TopicPartition::new("rejected".into(), 2), - futures_util::stream::iter([vec![marker(10), marker(11)], vec![marker(12)]]), + &shutdown, + futures_util::stream::iter([vec![marker(10), marker(11)], vec![marker(12)]]).map(batch), |tpl| commits.push(committed_offset(tpl)), ) - .await; + .await + .unwrap(); assert_eq!(commits, [12, 13]); } + struct FailFirst(std::sync::atomic::AtomicBool); + + #[async_trait] + impl Processor for FailFirst { + async fn process(&self, attempt: BatchAttempt) -> anyhow::Result<()> { + let records = attempt.records(); + if records[0].offset == 10 && self.0.swap(false, std::sync::atomic::Ordering::Relaxed) { + anyhow::bail!("staging unavailable"); + } + Ok(()) + } + } + + #[tokio::test] + async fn retryable_error_holds_later_commits_until_recovery() { + let processor = FailFirst(true.into()); + let shutdown = Shutdown::default(); + let commits = Mutex::new(Vec::new()); + let processing = process_partition_chunks( + &processor, + TopicPartition::new("rejected".into(), 2), + &shutdown, + futures_util::stream::iter([batch(vec![marker(10)]), batch(vec![marker(11)])]), + |tpl| commits.lock().unwrap().push(committed_offset(tpl)), + ); + tokio::pin!(processing); + assert!(futures_util::poll!(&mut processing).is_pending()); + assert!(commits.lock().unwrap().is_empty()); + processing.await.unwrap(); + assert_eq!(*commits.lock().unwrap(), [11, 12]); + } + + #[tokio::test] + async fn shutdown_leaves_failed_and_later_offsets_uncommitted() { + let processor = FailFirst(true.into()); + let shutdown = Shutdown::default(); + shutdown.start(); + let result = process_partition_chunks( + &processor, + TopicPartition::new("rejected".into(), 2), + &shutdown, + futures_util::stream::iter([batch(vec![marker(10)]), batch(vec![marker(11)])]), + |_| panic!("failed chunk or later offsets committed"), + ) + .await; + assert!(result.is_err()); + } + struct GatedProcessor { release: Mutex>>, processed: Mutex>, } #[async_trait] - impl Processor, ()> for GatedProcessor { - async fn process(&self, records: Vec) -> anyhow::Result<()> { + impl Processor for GatedProcessor { + async fn process(&self, attempt: BatchAttempt) -> anyhow::Result<()> { + let records = attempt.records(); let release = self.release.lock().unwrap().take(); if let Some(release) = release { release.await?; @@ -1091,10 +1234,13 @@ mod offset_marker_tests { let mut accepted = marker(10); accepted.payload = Some(br#"{"value":1}"#.to_vec()); let commits = Mutex::new(Vec::new()); + let shutdown = Shutdown::default(); let processing = process_partition_chunks( &processor, TopicPartition::new("rejected".into(), 2), - futures_util::stream::iter([vec![accepted, marker(11)], vec![marker(12), marker(13)]]), + &shutdown, + futures_util::stream::iter([vec![accepted, marker(11)], vec![marker(12), marker(13)]]) + .map(batch), |tpl| { assert_eq!(*processor.processed.lock().unwrap(), [10]); commits.lock().unwrap().push(committed_offset(tpl)); @@ -1104,7 +1250,7 @@ mod offset_marker_tests { assert!(futures_util::poll!(&mut processing).is_pending()); assert!(commits.lock().unwrap().is_empty()); release.send(()).unwrap(); - processing.await; + processing.await.unwrap(); assert_eq!(*commits.lock().unwrap(), [12, 14]); } @@ -1123,8 +1269,9 @@ mod offset_marker_tests { } #[async_trait] - impl Processor, ()> for OverlapProcessor { - async fn process(&self, records: Vec) -> anyhow::Result<()> { + impl Processor for OverlapProcessor { + async fn process(&self, attempt: BatchAttempt) -> anyhow::Result<()> { + let records = attempt.records(); let offset = records[0].offset; self.started.lock().unwrap().push(offset); if offset == 10 { @@ -1143,10 +1290,12 @@ mod offset_marker_tests { started: Mutex::new(Vec::new()), }; let commits = Mutex::new(Vec::new()); + let shutdown = Shutdown::default(); let processing = process_partition_chunks( &processor, TopicPartition::new("rejected".into(), 2), - futures_util::stream::iter([vec![marker(10)], vec![marker(11)]]), + &shutdown, + futures_util::stream::iter([vec![marker(10)], vec![marker(11)]]).map(batch), |tpl| commits.lock().unwrap().push(committed_offset(tpl)), ); tokio::pin!(processing); @@ -1154,7 +1303,7 @@ mod offset_marker_tests { assert_eq!(*processor.started.lock().unwrap(), [10, 11]); assert!(commits.lock().unwrap().is_empty()); release.send(()).unwrap(); - processing.await; + processing.await.unwrap(); assert_eq!(*commits.lock().unwrap(), [11, 12]); } } diff --git a/src/connectors/kafka/rebalance_listener.rs b/src/connectors/kafka/rebalance_listener.rs index 422c2a31d..e94733da0 100644 --- a/src/connectors/kafka/rebalance_listener.rs +++ b/src/connectors/kafka/rebalance_listener.rs @@ -58,12 +58,7 @@ impl RebalanceListener { Some(RebalanceEvent::Assign(tpl)) => info!("RebalanceEvent Assign: {:?}", tpl), Some(RebalanceEvent::Revoke(tpl, callback)) => { info!("RebalanceEvent Revoke: {:?}", tpl); - if let Ok(mut stream_state) = stream_state.try_write() { - stream_state.terminate_partition_streams(tpl).await; - drop(stream_state); - } else { - warn!("Stream state lock is busy, skipping rebalance revoke for {:?}", tpl); - } + stream_state.write().await.terminate_partition_streams(tpl).await; if let Err(err) = callback.send(()) { warn!("Error during sending response to context. Cause: {:?}", err); } diff --git a/src/connectors/kafka/sink.rs b/src/connectors/kafka/sink.rs index e7b01949c..8948cbc98 100644 --- a/src/connectors/kafka/sink.rs +++ b/src/connectors/kafka/sink.rs @@ -17,9 +17,8 @@ */ use crate::connectors::common::build_runtime; use crate::connectors::common::processor::Processor; -use crate::connectors::kafka::ConsumerRecord; use crate::connectors::kafka::consumer::KafkaStreams; -use crate::connectors::kafka::processor::StreamWorker; +use crate::connectors::kafka::processor::{BatchAttempt, StreamWorker}; use anyhow::Result; use futures_util::StreamExt; use rdkafka::consumer::Consumer; @@ -59,7 +58,7 @@ impl Drop for WorkerRuntime { pub struct KafkaSinkConnector

where - P: Processor, ()>, + P: Processor, { streams: KafkaStreams, stream_processor: Arc>, @@ -68,13 +67,14 @@ where impl

KafkaSinkConnector

where - P: Processor, ()> + Send + Sync + 'static, + P: Processor + Send + Sync + 'static, { pub fn new(kafka_streams: KafkaStreams, processor: P) -> Self { let consumer = kafka_streams.consumer(); let stream_processor = Arc::new(StreamWorker::new( Arc::new(processor), Arc::clone(&consumer), + kafka_streams.shutdown_handle(), )); let runtime = build_runtime( @@ -101,10 +101,9 @@ where .run_drain(|partition_records| async { info!("Starting task for partition: {:?}", tp); - worker - .process_partition(tp.clone(), partition_records) - .await - .unwrap(); + if let Err(err) = worker.process_partition(tp.clone(), partition_records).await { + error!(?tp, %err, "Kafka partition stopped with uncommitted offsets"); + } }) .await; diff --git a/src/connectors/mod.rs b/src/connectors/mod.rs index 40a5016c7..a3815bfb8 100644 --- a/src/connectors/mod.rs +++ b/src/connectors/mod.rs @@ -21,9 +21,14 @@ use std::sync::Arc; use actix_web_prometheus::PrometheusMetrics; use common::{processor::Processor, shutdown::Shutdown}; use kafka::{ - ConsumerRecord, KafkaContext, config::KafkaConfig, consumer::KafkaStreams, - metrics::KafkaMetricsCollector, processor::ParseableSinkProcessor, - rebalance_listener::RebalanceListener, sink::KafkaSinkConnector, state::StreamState, + KafkaContext, + config::KafkaConfig, + consumer::KafkaStreams, + metrics::KafkaMetricsCollector, + processor::{BatchAttempt, ParseableSinkProcessor}, + rebalance_listener::RebalanceListener, + sink::KafkaSinkConnector, + state::StreamState, }; use prometheus::Registry; use tokio::sync::RwLock; @@ -77,7 +82,7 @@ async fn run_kafka2parseable

( shutdown_handle: Shutdown, ) -> anyhow::Result<()> where - P: Processor, ()> + Send + Sync + 'static, + P: Processor + Send + Sync + 'static, { info!("Initializing KafkaSink connector..."); diff --git a/src/hottier.rs b/src/hottier.rs index 1933ccfb6..5309d76b6 100644 --- a/src/hottier.rs +++ b/src/hottier.rs @@ -17,7 +17,7 @@ */ use std::{ - collections::{BTreeMap, HashMap, VecDeque}, + collections::{BTreeMap, HashMap, HashSet, VecDeque}, future::Future, io, path::{Path, PathBuf}, @@ -53,7 +53,7 @@ use futures_util::TryFutureExt; use object_store::{ObjectStoreExt, local::LocalFileSystem}; use parquet::errors::ParquetError; use relative_path::RelativePathBuf; -use std::time::Duration; +use std::time::{Duration, Instant}; use tokio::fs::{self, DirEntry}; use tokio_stream::wrappers::ReadDirStream; use tracing::{Instrument, error, info}; @@ -88,7 +88,16 @@ where let Some(item) = pending.pop_front() else { break; }; - let prepared = match prepare(item).await { + let preparing = prepare(item); + tokio::pin!(preparing); + let result = loop { + tokio::select! { + biased; + result = &mut preparing => break result, + Some(outcome) = in_flight.next(), if !in_flight.is_empty() => outcomes.push(outcome), + } + }; + let prepared = match result { Ok(prepared) => prepared, Err(outcome) => { outcomes.push(outcome); @@ -259,7 +268,10 @@ pub struct StreamHotTier { } /// Per-stream in-memory bookkeeping. Downloads run outside the lock. +#[derive(Default)] struct StreamSyncState { + sync: AsyncMutex<()>, + failures: StdMutex, runtime: AsyncMutex, eviction: Arc>, query_pins: StdMutex>, @@ -336,11 +348,41 @@ struct DownloadContext { } struct PreparedWork { + reservation: DiskReservation, + _download_permits: tokio::sync::OwnedSemaphorePermit, item: WorkItem, minute: String, evicted_bytes: u64, } +const GLOBAL_DOWNLOAD_BYTES: u32 = 256 * 1024 * 1024; +// Charge at least one default range per file to bound simultaneous small downloads, too. +const MIN_DOWNLOAD_CHARGE: u32 = 8 * 1024 * 1024; +const MAX_DOWNLOAD_FAILURES: usize = 1024; + +#[derive(Default)] +struct DownloadFailures(indexmap::IndexMap); + +impl DownloadFailures { + fn ready(&self, path: &str, now: Instant) -> bool { + self.0 + .get(path) + .is_none_or(|(_, retry_at)| now >= *retry_at) + } + + fn record(&mut self, path: &str, now: Instant) { + let previous = self.0.shift_remove(path).map_or(0, |(count, _)| count); + if self.0.len() == MAX_DOWNLOAD_FAILURES { + self.0.shift_remove_index(0); + } + let delay = [60, 300, 900][usize::from(previous.min(2))]; + self.0.insert( + path.to_owned(), + (previous.saturating_add(1), now + Duration::from_secs(delay)), + ); + } +} + #[derive(Debug, Default)] struct TickStats { inventory_files: usize, @@ -432,6 +474,9 @@ struct StreamTasks { pub struct HotTierManager { filesystem: LocalFileSystem, + disk_budget: AsyncRwLock>, + disk_refresh: AsyncMutex<()>, + download_bytes: Arc, hot_tier_path: &'static Path, tenant_gates: AsyncMutex>>>, state_cache: AsyncRwLock>>, @@ -546,6 +591,9 @@ impl HotTierManager { std::fs::create_dir_all(hot_tier_path).unwrap(); HotTierManager { filesystem: LocalFileSystem::new(), + disk_budget: AsyncRwLock::new(None), + disk_refresh: AsyncMutex::new(()), + download_bytes: Arc::new(tokio::sync::Semaphore::new(GLOBAL_DOWNLOAD_BYTES as usize)), hot_tier_path, tenant_gates: AsyncMutex::new(HashMap::new()), state_cache: AsyncRwLock::new(HashMap::new()), @@ -640,9 +688,7 @@ impl HotTierManager { let runtime = load_or_rebuild(&stream_root).await?; let state = Arc::new(StreamSyncState { runtime: AsyncMutex::new(runtime), - eviction: Arc::new(AsyncRwLock::new(())), - query_pins: StdMutex::new(HashMap::new()), - next_query_pin: AtomicU64::new(0), + ..StreamSyncState::default() }); self.state_cache .write() @@ -1107,6 +1153,7 @@ impl HotTierManager { ) -> Result<(), HotTierError> { let started = std::time::Instant::now(); let state = self.get_or_load_state(stream, tenant_id).await?; + let _sync = state.sync.lock().await; let latest_minutes = PARSEABLE.options.hot_tier_latest_minutes; let previous_watermark = state.runtime.lock().await.source_watermark; let candidate_dates = Self::inventory_dates(anchor, previous_watermark, latest_minutes); @@ -1127,7 +1174,7 @@ impl HotTierManager { .await .map_err(|error| HotTierError::Anyhow(error.into()))?; let stream_root = self.stream_root(stream, tenant_id); - let total_bytes: u64 = plan.items.iter().map(|item| item.file.file_size).sum(); + let total_bytes: u64 = plan.items.iter().map(|item| item.size).sum(); let oldest_missing_lag_seconds = plan .items .last() @@ -1155,48 +1202,35 @@ impl HotTierManager { // files cannot inflate runtime usage. { let mut runtime = state.runtime.lock().await; - runtime.source_watermark = plan.source_watermark.or(previous_watermark); + if let Some(watermark) = plan.source_watermark + && runtime.source_watermark != Some(watermark) + { + runtime.source_watermark = Some(watermark); + runtime.dirty = true; + } for minute_path in &plan.active_minute_paths { let Ok(minute) = minute_path.strip_prefix(&stream_root) else { continue; }; let key = minute.to_string_lossy().into_owned(); - runtime - .minutes - .insert(key.clone(), verify_bucket(&stream_root, &key).await?); + let totals = verify_bucket(&stream_root, &key).await?; + if runtime.minutes.get(&key) != Some(&totals) { + runtime.minutes.insert(key, totals); + runtime.dirty = true; + } } } - let quota = self.read_hot_tier_config(stream, tenant_id).await?.size; - let mut stats = TickStats { + let stats = TickStats { inventory_files: plan.inventory_files, missing_files: plan.items.len(), missing_bytes: total_bytes, - ..TickStats::default() + ..self + .download_work(stream, tenant_id, &state, &stream_root, plan.items) + .await? }; - let download_stats = self - .download_work(stream, tenant_id, &state, &stream_root, quota, plan.items) - .await; - stats.downloaded = download_stats.downloaded; - stats.failed = download_stats.failed; - stats.capacity = download_stats.capacity; - stats.downloaded_bytes = download_stats.downloaded_bytes; - stats.evicted_bytes = download_stats.evicted_bytes; - stats.max_in_flight = download_stats.max_in_flight; - - let (used, reserved, watermark) = { - let runtime = state.runtime.lock().await; - persist_checkpoint(&stream_root, &runtime).await?; - ( - runtime.used_bytes(), - runtime.reserved_bytes(), - runtime.source_watermark, - ) - }; - let mut metadata = self.read_hot_tier_config(stream, tenant_id).await?; - metadata.used_size = used; - metadata.available_size = quota.saturating_sub(used.saturating_add(reserved)); - self.put_hot_tier(stream, &mut metadata, tenant_id).await?; + let (used, reserved, watermark) = + self.flush_state_if_dirty(stream, tenant_id, &state).await?; if let Some(watermark) = watermark { HOT_TIER_SOURCE_WATERMARK_SECONDS @@ -1248,6 +1282,28 @@ impl HotTierManager { Ok(()) } + // Dirty stays set across failed writes. A subsequent tick retries even if + // its inventory, watermark and download counts are otherwise unchanged. + async fn flush_state_if_dirty( + &self, + stream: &str, + tenant_id: &Option, + state: &StreamSyncState, + ) -> Result<(u64, u64, Option>), HotTierError> { + let mut runtime = state.runtime.lock().await; + let used = runtime.used_bytes(); + let reserved = runtime.reserved_bytes(); + if runtime.dirty { + persist_checkpoint(&self.stream_root(stream, tenant_id), &runtime).await?; + let mut metadata = self.read_hot_tier_config(stream, tenant_id).await?; + metadata.used_size = used; + metadata.available_size = metadata.size.saturating_sub(used.saturating_add(reserved)); + self.put_hot_tier(stream, &mut metadata, tenant_id).await?; + runtime.dirty = false; + } + Ok((used, reserved, runtime.source_watermark)) + } + fn inventory_dates( anchor: DateTime, previous_watermark: Option>, @@ -1304,11 +1360,28 @@ impl HotTierManager { tenant_id: &Option, state: &Arc, stream_root: &Path, - quota: u64, - work: Vec, - ) -> TickStats { + mut work: Vec, + ) -> Result { + { + let failures = state + .failures + .lock() + .expect("hot-tier failure lock poisoned"); + let now = Instant::now(); + work.retain(|item| failures.ready(&item.path, now)); + } + if work.is_empty() { + return Ok(TickStats::default()); + } + let quota = self.read_hot_tier_config(stream, tenant_id).await?.size; let concurrency = PARSEABLE.options.hot_tier_files_per_stream_concurrency as usize; - let disk_budget = self.snapshot_disk_budget().await; + let budget = self.shared_disk_budget().await; + let Some((_, disk_budget)) = budget.as_ref() else { + return Ok(TickStats { + capacity: work.len(), + ..TickStats::default() + }); + }; let active = Arc::new(AtomicUsize::new(0)); let maximum = Arc::new(AtomicUsize::new(0)); let context = DownloadContext { @@ -1318,7 +1391,7 @@ impl HotTierManager { state: state.clone(), stream_root: stream_root.to_path_buf(), quota, - disk_budget, + disk_budget: disk_budget.clone(), active: active.clone(), maximum: maximum.clone(), }; @@ -1352,7 +1425,16 @@ impl HotTierManager { DownloadKind::Capacity => stats.capacity += 1, } } - stats + Ok(stats) + } + + async fn reserve_download_bytes(&self, size: u64) -> tokio::sync::OwnedSemaphorePermit { + let charge = size.clamp(MIN_DOWNLOAD_CHARGE.into(), GLOBAL_DOWNLOAD_BYTES.into()) as u32; + self.download_bytes + .clone() + .acquire_many_owned(charge) + .await + .expect("hot-tier download semaphore remains open") } async fn prepare_work_item( @@ -1360,13 +1442,15 @@ impl HotTierManager { context: DownloadContext, item: WorkItem, ) -> Result { - let minute = match item.minute_path.strip_prefix(&context.stream_root) { - Ok(value) => value.to_string_lossy().into_owned(), - Err(error) => { - error!(file = %item.file.file_path, %error, "invalid hot-tier minute path"); - return Err(DownloadOutcome::failed(0)); - } + let local_path = self.hot_tier_path.join(&item.path); + let Some(minute) = planner::minute_ancestor(&local_path) + .and_then(|path| path.strip_prefix(&context.stream_root).ok()) + else { + error!(file = %item.path, "invalid hot-tier minute path"); + return Err(DownloadOutcome::failed(0)); }; + let minute = minute.to_string_lossy().into_owned(); + let permits = self.reserve_download_bytes(item.size).await; let reservation = self .reserve_item( &context.state, @@ -1377,15 +1461,17 @@ impl HotTierManager { &context.disk_budget, ) .await; - let evicted_bytes = match reservation { - Ok(Some(bytes)) => bytes, + let (evicted_bytes, reservation) = match reservation { + Ok(Some(reserved)) => reserved, Ok(None) => return Err(DownloadOutcome::capacity(0)), Err(error) => { - error!(stream = %context.stream, tenant = ?context.tenant_id, file = %item.file.file_path, %error, "reservation failed"); + error!(stream = %context.stream, tenant = ?context.tenant_id, file = %item.path, %error, "reservation failed"); return Err(DownloadOutcome::failed(0)); } }; Ok(PreparedWork { + reservation, + _download_permits: permits, item, minute, evicted_bytes, @@ -1398,6 +1484,8 @@ impl HotTierManager { prepared: PreparedWork, ) -> DownloadOutcome { let PreparedWork { + reservation, + _download_permits, item, minute, evicted_bytes, @@ -1409,41 +1497,42 @@ impl HotTierManager { context.tenant_label.clone(), ); - if let Some(parent) = item.local_path.parent() + let local_path = self.hot_tier_path.join(&item.path); + if let Some(parent) = local_path.parent() && let Err(error) = fs::create_dir_all(parent).await { - self.finish_reservation(&context.state, &context.disk_budget, &item, &minute, false) + self.finish_reservation(&context.state, reservation, &item, &minute, false) .await; - error!(file = %item.file.file_path, %error, "failed to create hot-tier directory"); + error!(file = %item.path, %error, "failed to create hot-tier directory"); return DownloadOutcome::failed(evicted_bytes); } let result = PARSEABLE .hottier_connection_pool .parallel_chunked_download( - &RelativePathBuf::from(item.file.file_path.clone()), + &RelativePathBuf::from(item.path.clone()), &context.tenant_id, - item.local_path.clone(), + local_path.clone(), ) .await; let valid = result.is_ok() - && fs::metadata(&item.local_path) + && fs::metadata(&local_path) .await - .is_ok_and(|metadata| metadata.len() == item.file.file_size); + .is_ok_and(|metadata| metadata.len() == item.size); if !valid { - self.remove_file_if_unpinned(&context.state, &minute, &item.local_path) + self.remove_file_if_unpinned(&context.state, &minute, &local_path) .await; } - self.finish_reservation(&context.state, &context.disk_budget, &item, &minute, valid) + self.finish_reservation(&context.state, reservation, &item, &minute, valid) .await; match result { - Ok(()) if valid => DownloadOutcome::downloaded(item.file.file_size, evicted_bytes), + Ok(()) if valid => DownloadOutcome::downloaded(item.size, evicted_bytes), Ok(()) => { - error!(file = %item.file.file_path, expected_size = item.file.file_size, "hot-tier download size mismatch"); + error!(file = %item.path, expected_size = item.size, "hot-tier download size mismatch"); DownloadOutcome::failed(evicted_bytes) } Err(error) => { - error!(stream = %context.stream, tenant = ?context.tenant_id, file = %item.file.file_path, %error, "hot-tier download failed"); + error!(stream = %context.stream, tenant = ?context.tenant_id, file = %item.path, %error, "hot-tier download failed"); DownloadOutcome::failed(evicted_bytes) } } @@ -1457,8 +1546,8 @@ impl HotTierManager { item: &WorkItem, quota: u64, disk_budget: &DiskBudget, - ) -> Result, HotTierError> { - if item.file.file_size > quota { + ) -> Result, HotTierError> { + if item.size > quota { return Ok(None); } let Some(removed_wrong_sized_file) = self @@ -1469,6 +1558,7 @@ impl HotTierManager { }; let mut runtime = state.runtime.lock().await; if removed_wrong_sized_file { + runtime.dirty = true; runtime .minutes .insert(minute.to_owned(), verify_bucket(stream_root, minute).await?); @@ -1476,8 +1566,8 @@ impl HotTierManager { runtime.mark_bucket_inflight(minute); let reclaim_target = required_reclaim( runtime.free_bytes(quota), - disk_budget.deficit(item.file.file_size).await, - item.file.file_size, + disk_budget.deficit(item.size), + item.size, ); let mut reclaim = ReclaimBudget::new(reclaim_target); let mut evicted = 0_u64; @@ -1523,18 +1613,14 @@ impl HotTierManager { } } let removed = runtime.remove_bucket(&oldest); - disk_budget.credit_eviction(removed).await; + disk_budget.credit_eviction(removed); evicted = evicted.saturating_add(removed); reclaim.record_eviction(removed); } - if disk_budget - .try_reserve(&item.file.file_path, item.file.file_size) - .await + if let Some(reservation) = disk_budget.try_reserve(&item.path, item.size) + && runtime.try_reserve(&item.path, item.size, quota) { - if runtime.try_reserve(&item.file.file_path, item.file.file_size, quota) { - return Ok(Some(evicted)); - } - disk_budget.finish(&item.file.file_path, false).await; + return Ok(Some((evicted, reservation))); } runtime.unmark_bucket_inflight(minute); Ok(None) @@ -1547,19 +1633,20 @@ impl HotTierManager { item: &WorkItem, disk_budget: &DiskBudget, ) -> Result, HotTierError> { - let removed_wrong_sized_file = match fs::metadata(&item.local_path).await { - Ok(metadata) if metadata.len() == item.file.file_size => return Ok(None), + let local_path = self.hot_tier_path.join(&item.path); + let removed_wrong_sized_file = match fs::metadata(&local_path).await { + Ok(metadata) if metadata.len() == item.size => return Ok(None), Ok(_) => { let _reconciliation_guard = state.eviction.write().await; if state.bucket_is_pinned(minute) { return Ok(None); } - match fs::metadata(&item.local_path).await { - Ok(metadata) if metadata.len() == item.file.file_size => return Ok(None), + match fs::metadata(&local_path).await { + Ok(metadata) if metadata.len() == item.size => return Ok(None), Ok(metadata) => { let removed_bytes = metadata.len(); - fs::remove_file(&item.local_path).await?; - disk_budget.credit_eviction(removed_bytes).await; + fs::remove_file(&local_path).await?; + disk_budget.credit_eviction(removed_bytes); true } Err(error) if error.kind() == io::ErrorKind::NotFound => false, @@ -1586,17 +1673,80 @@ impl HotTierManager { async fn finish_reservation( &self, - state: &Arc, - disk_budget: &DiskBudget, + state: &StreamSyncState, + mut reservation: DiskReservation, item: &WorkItem, minute: &str, commit: bool, ) { - { + state + .runtime + .lock() + .await + .finish_item(&item.path, minute, commit); + reservation.committed = commit; + let mut failures = state + .failures + .lock() + .expect("hot-tier failure lock poisoned"); + if commit { + failures.0.shift_remove(&item.path); + } else { + failures.record(&item.path, Instant::now()); + } + } + + /// Revisit local dates even after the remote inventory has forgotten them. + /// A date pinned on this run can then be reclaimed on a later retention pass. + pub(crate) async fn prune_retention_dates( + &self, + stream: &str, + tenant_id: &Option, + retain_until: NaiveDate, + failed_deletions: &HashSet, + ) -> Result<(), HotTierError> { + if !self.check_stream_hot_tier_exists(stream, tenant_id) { + return Ok(()); + } + let admission = self + .tenant_admission(tenant_id) + .await + .map_err(|()| HotTierValidationError::NotFound(stream.to_owned()))?; + let state = self + .get_or_load_state_with_admission(stream, tenant_id) + .await?; + // Finish any inventory/download that started before the remote deletion. + let _sync = state.sync.lock().await; + let stream_root = self.stream_root(stream, tenant_id); + for date in self.fetch_hot_tier_dates(stream, tenant_id).await? { + let key = format!("date={date}"); + if date >= retain_until || failed_deletions.contains(&key) { + continue; + } + let _eviction = state.eviction.write().await; + if state + .query_pins + .lock() + .expect("hot-tier query pins lock poisoned") + .values() + .any(|pin| pin.start.date_naive() <= date && date <= pin.end.date_naive()) + { + continue; + } + match fs::remove_dir_all(stream_root.join(&key)).await { + Ok(()) => {} + Err(err) if err.kind() == io::ErrorKind::NotFound => {} + Err(err) => return Err(err.into()), + } let mut runtime = state.runtime.lock().await; - runtime.finish_item(&item.file.file_path, minute, commit); + runtime + .minutes + .retain(|minute, _| !Path::new(minute).starts_with(&key)); + runtime.dirty = true; } - disk_budget.finish(&item.file.file_path, commit).await; + self.flush_state_if_dirty(stream, tenant_id, &state).await?; + drop(admission); + Ok(()) } /// fetch the list of dates available in the hot tier directory for the stream and sort them @@ -1691,37 +1841,47 @@ impl HotTierManager { /// check if the disk is available to download the parquet file /// check if the disk usage is above the threshold pub async fn is_disk_available(&self, size_to_download: u64) -> bool { - if let Some(DiskUtil { - total_space, - available_space, - used_space, - }) = self.get_disk_usage() - { - if available_space < size_to_download { - return false; - } - - if ((used_space + size_to_download) as f64 * 100.0 / total_space as f64) - > PARSEABLE.options.max_disk_usage - { - return false; - } - } - - true + self.shared_disk_budget() + .await + .as_ref() + .is_some_and(|(_, budget)| budget.deficit(size_to_download) == 0) } - async fn snapshot_disk_budget(&self) -> DiskBudget { - let hot_tier_path = self.hot_tier_path.to_path_buf(); - let usage = - match tokio::task::spawn_blocking(move || disk_usage_for_path(&hot_tier_path)).await { - Ok(usage) => usage, - Err(error) => { - error!(%error, "failed to snapshot hot-tier disk usage"); - None - } - }; - DiskBudget::new(usage, PARSEABLE.options.max_disk_usage) + // A read lease spans the download batch. Refresh exclusively between batches + // so a filesystem sample cannot race a reservation, commit or eviction. + async fn shared_disk_budget( + &self, + ) -> tokio::sync::RwLockReadGuard<'_, Option<(Instant, DiskBudget)>> { + let fresh = |budget: &Option<(Instant, DiskBudget)>| { + budget + .as_ref() + .is_some_and(|(at, _)| at.elapsed() < Duration::from_secs(30)) + }; + let budget = self.disk_budget.read().await; + if fresh(&budget) { + return budget; + } + drop(budget); + let _refresh = self.disk_refresh.lock().await; + let budget = self.disk_budget.read().await; + if fresh(&budget) { + return budget; + } + drop(budget); + let mut budget = self.disk_budget.write().await; + let path = self.hot_tier_path; + let usage = tokio::task::spawn_blocking(move || disk_usage_for_path(path)).await; + *budget = match usage { + Ok(Some(usage)) => Some(( + Instant::now(), + DiskBudget::new(usage, PARSEABLE.options.max_disk_usage), + )), + _ => { + error!("Cannot measure available hot-tier disk space; postponing downloads"); + None + } + }; + tokio::sync::RwLockWriteGuard::downgrade(budget) } pub async fn get_oldest_date_time_entry( @@ -1858,7 +2018,7 @@ impl HotTierManager { #[derive(Clone)] struct DiskBudget { - state: Arc>>, + state: Arc>, } struct DiskBudgetState { @@ -1870,24 +2030,21 @@ struct DiskBudgetState { } impl DiskBudget { - fn new(usage: Option, max_disk_usage: f64) -> Self { - let state = usage.map(|usage| DiskBudgetState { + fn new(usage: DiskUtil, max_disk_usage: f64) -> Self { + let state = DiskBudgetState { total_space: usage.total_space, available_space: usage.available_space, used_space: usage.used_space, max_used_space: ((max_disk_usage * usage.total_space as f64) / 100.0) as u64, reservations: HashMap::new(), - }); + }; Self { - state: Arc::new(AsyncMutex::new(state)), + state: Arc::new(StdMutex::new(state)), } } - async fn deficit(&self, bytes: u64) -> u64 { - let state = self.state.lock().await; - let Some(state) = state.as_ref() else { - return 0; - }; + fn deficit(&self, bytes: u64) -> u64 { + let state = self.state.lock().expect("disk budget lock poisoned"); bytes.saturating_sub(state.available_space).max( state .used_space @@ -1896,28 +2053,26 @@ impl DiskBudget { ) } - async fn try_reserve(&self, path: &str, bytes: u64) -> bool { - let mut state = self.state.lock().await; - let Some(state) = state.as_mut() else { - return true; - }; + fn try_reserve(&self, path: &str, bytes: u64) -> Option { + let mut state = self.state.lock().expect("disk budget lock poisoned"); if state.reservations.contains_key(path) || bytes > state.available_space || state.used_space.saturating_add(bytes) > state.max_used_space { - return false; + return None; } state.available_space -= bytes; state.used_space = state.used_space.saturating_add(bytes); state.reservations.insert(path.to_owned(), bytes); - true + Some(DiskReservation { + budget: self.clone(), + path: path.to_owned(), + committed: false, + }) } - async fn finish(&self, path: &str, commit: bool) { - let mut state = self.state.lock().await; - let Some(state) = state.as_mut() else { - return; - }; + fn finish(&self, path: &str, commit: bool) { + let mut state = self.state.lock().expect("disk budget lock poisoned"); let Some(bytes) = state.reservations.remove(path) else { return; }; @@ -1930,11 +2085,8 @@ impl DiskBudget { } } - async fn credit_eviction(&self, bytes: u64) { - let mut state = self.state.lock().await; - let Some(state) = state.as_mut() else { - return; - }; + fn credit_eviction(&self, bytes: u64) { + let mut state = self.state.lock().expect("disk budget lock poisoned"); state.used_space = state.used_space.saturating_sub(bytes); state.available_space = state .available_space @@ -1943,6 +2095,18 @@ impl DiskBudget { } } +struct DiskReservation { + budget: DiskBudget, + path: String, + committed: bool, +} + +impl Drop for DiskReservation { + fn drop(&mut self) { + self.budget.finish(&self.path, self.committed); + } +} + fn required_reclaim(stream_free_bytes: u64, disk_deficit: u64, item_bytes: u64) -> u64 { item_bytes .saturating_sub(stream_free_bytes) @@ -2068,11 +2232,11 @@ mod tests { fn disk_budget() -> DiskBudget { DiskBudget::new( - Some(DiskUtil { + DiskUtil { total_space: 1_000, available_space: 400, used_space: 600, - }), + }, 80.0, ) } @@ -2104,48 +2268,145 @@ mod tests { manager.finish_tenant_cleanup(&tenant).await; } - #[tokio::test] - async fn disk_budget_reports_threshold_deficit() { - let budget = disk_budget(); - - assert_eq!(budget.deficit(250).await, 50); + #[test] + fn disk_budget_reports_threshold_deficit() { + assert_eq!(disk_budget().deficit(250), 50); } - #[tokio::test] - async fn disk_budget_reservations_are_shared() { + #[test] + fn disk_budget_reservations_are_shared_and_refunded_on_drop() { let budget = disk_budget(); - - assert!(budget.try_reserve("first", 150).await); - assert!(!budget.try_reserve("second", 100).await); + let other_stream = budget.clone(); + let reservation = budget.try_reserve("first", 150).unwrap(); + assert!(other_stream.try_reserve("second", 100).is_none()); + drop(reservation); + assert!(other_stream.try_reserve("second", 200).is_some()); } - #[tokio::test] - async fn disk_budget_failed_download_refunds_reservation() { + #[test] + fn disk_budget_successful_download_consumes_capacity() { let budget = disk_budget(); - assert!(budget.try_reserve("first", 200).await); - - budget.finish("first", false).await; - - assert!(budget.try_reserve("second", 200).await); + let mut reservation = budget.try_reserve("first", 200).unwrap(); + reservation.committed = true; + drop(reservation); + assert!(budget.try_reserve("second", 1).is_none()); } - #[tokio::test] - async fn disk_budget_successful_download_consumes_capacity() { + #[test] + fn disk_budget_eviction_credits_capacity() { let budget = disk_budget(); - assert!(budget.try_reserve("first", 200).await); - - budget.finish("first", true).await; + budget.credit_eviction(75); + assert!(budget.try_reserve("file", 250).is_some()); + } - assert!(!budget.try_reserve("second", 1).await); + #[test] + fn failed_downloads_back_off_and_tracking_is_bounded() { + let mut failures = super::DownloadFailures::default(); + let mut now = super::Instant::now(); + for delay in [60, 300, 900, 900] { + assert!(failures.ready("bad", now)); + failures.record("bad", now); + assert!(!failures.ready("bad", now + Duration::from_secs(delay - 1))); + now += Duration::from_secs(delay); + } + for i in 0..super::MAX_DOWNLOAD_FAILURES { + failures.record(&format!("file-{i}"), now); + } + assert_eq!(failures.0.len(), super::MAX_DOWNLOAD_FAILURES); + assert!(!failures.0.contains_key("bad")); } #[tokio::test] - async fn disk_budget_eviction_credits_capacity() { - let budget = disk_budget(); - - budget.credit_eviction(75).await; + async fn idle_tick_skips_writes_and_failed_checkpoints_are_retried() { + let root = Box::leak(tempfile::tempdir().unwrap().keep().into_boxed_path()); + let (sender, _receiver) = tokio::sync::mpsc::unbounded_channel(); + let manager = HotTierManager::new(root, sender); + let state = StreamSyncState::default(); + // Even the config is absent: an idle flush must do no filesystem I/O. + manager + .flush_state_if_dirty("logs", &None, &state) + .await + .unwrap(); + assert!(!root.join("logs").exists()); + state.runtime.lock().await.dirty = true; + assert!( + manager + .flush_state_if_dirty("logs", &None, &state) + .await + .is_err() + ); + assert!(state.runtime.lock().await.dirty); + tokio::fs::write( + root.join("logs").join(super::STREAM_HOT_TIER_FILENAME), + serde_json::to_vec(&super::StreamHotTier::default()).unwrap(), + ) + .await + .unwrap(); + manager + .flush_state_if_dirty("logs", &None, &state) + .await + .unwrap(); + assert!(!state.runtime.lock().await.dirty); + let checkpoint = root.join("logs").join(super::local_state::INDEX_FILENAME); + tokio::fs::remove_file(&checkpoint).await.unwrap(); + manager + .flush_state_if_dirty("logs", &None, &state) + .await + .unwrap(); + assert!(!checkpoint.exists()); + } - assert!(budget.try_reserve("file", 250).await); + #[tokio::test] + async fn retention_revisits_pinned_dates_and_preserves_failed_dates() { + let root = Box::leak(tempfile::tempdir().unwrap().keep().into_boxed_path()); + let (sender, _receiver) = tokio::sync::mpsc::unbounded_channel(); + let manager = HotTierManager::new(root, sender); + let stream_root = root.join("logs"); + for day in 1..=4 { + let minute = stream_root.join(format!("date=2026-07-0{day}/hour=12/minute=00")); + tokio::fs::create_dir_all(&minute).await.unwrap(); + tokio::fs::write(minute.join("entry.parquet"), [1]) + .await + .unwrap(); + } + tokio::fs::write( + stream_root.join(super::STREAM_HOT_TIER_FILENAME), + serde_json::to_vec(&super::StreamHotTier::default()).unwrap(), + ) + .await + .unwrap(); + let start = Utc.with_ymd_and_hms(2026, 7, 1, 12, 0, 0).unwrap(); + let pin = manager + .query_guard("logs", &None, start, start) + .await + .unwrap(); + let retained = start.date_naive() + chrono::Days::new(3); + let failed = std::collections::HashSet::from(["date=2026-07-02".to_owned()]); + manager + .prune_retention_dates("logs", &None, retained, &failed) + .await + .unwrap(); + assert!(stream_root.join("date=2026-07-01").exists()); + assert!(stream_root.join("date=2026-07-02").exists()); + assert!(!stream_root.join("date=2026-07-03").exists()); + assert!(stream_root.join("date=2026-07-04").exists()); + drop(pin); + manager + .prune_retention_dates("logs", &None, retained, &failed) + .await + .unwrap(); + assert!(!stream_root.join("date=2026-07-01").exists()); + assert_eq!( + manager + .get_or_load_state("logs", &None) + .await + .unwrap() + .runtime + .lock() + .await + .used_bytes(), + 2 + ); } #[test] @@ -2190,15 +2451,12 @@ mod tests { } let state = Arc::new(StreamSyncState { runtime: tokio::sync::Mutex::new(runtime), - eviction: Arc::new(tokio::sync::RwLock::new(())), - query_pins: std::sync::Mutex::new(std::collections::HashMap::new()), - next_query_pin: std::sync::atomic::AtomicU64::new(0), + ..StreamSyncState::default() }); let item = WorkItem { timestamp: Utc::now(), - minute_path: stream_root.join("date=2026-07-16/hour=12/minute=02"), - local_path: stream_root.join("date=2026-07-16/hour=12/minute=02/new.parquet"), - file: manifest_file("logs/date=2026-07-16/hour=12/minute=02/new.parquet", 275), + path: "logs/date=2026-07-16/hour=12/minute=02/new.parquet".to_owned(), + size: 275, }; let budget = disk_budget(); let (sender, _receiver) = tokio::sync::mpsc::unbounded_channel(); @@ -2216,7 +2474,7 @@ mod tests { .await .unwrap(); - assert_eq!(evicted, Some(100)); + assert_eq!(evicted.map(|(bytes, _)| bytes), Some(100)); assert!(!stream_root.join(oldest).exists()); assert!(stream_root.join(next).exists()); } @@ -2243,9 +2501,7 @@ mod tests { ); let state = Arc::new(StreamSyncState { runtime: tokio::sync::Mutex::new(runtime), - eviction: Arc::new(tokio::sync::RwLock::new(())), - query_pins: std::sync::Mutex::new(std::collections::HashMap::new()), - next_query_pin: std::sync::atomic::AtomicU64::new(0), + ..StreamSyncState::default() }); let query_guard = state.pin_query( Utc.with_ymd_and_hms(2026, 7, 16, 12, 0, 30).unwrap(), @@ -2256,9 +2512,8 @@ mod tests { let manager = HotTierManager::new(root, sender); let item = WorkItem { timestamp: Utc::now(), - minute_path: stream_root.join("date=2026-07-16/hour=12/minute=01"), - local_path: stream_root.join("date=2026-07-16/hour=12/minute=01/new.parquet"), - file: manifest_file("logs/date=2026-07-16/hour=12/minute=01/new.parquet", 100), + path: "logs/date=2026-07-16/hour=12/minute=01/new.parquet".to_owned(), + size: 100, }; let evicted = manager @@ -2273,7 +2528,7 @@ mod tests { .await .unwrap(); - assert_eq!(evicted, None); + assert!(evicted.is_none()); assert!(oldest_directory.exists()); drop(query_guard); @@ -2288,7 +2543,7 @@ mod tests { ) .await .unwrap(); - assert_eq!(evicted, Some(100)); + assert_eq!(evicted.map(|(bytes, _)| bytes), Some(100)); assert!(!oldest_directory.exists()); } @@ -2314,9 +2569,7 @@ mod tests { ); let state = Arc::new(StreamSyncState { runtime: tokio::sync::Mutex::new(runtime), - eviction: Arc::new(tokio::sync::RwLock::new(())), - query_pins: std::sync::Mutex::new(std::collections::HashMap::new()), - next_query_pin: std::sync::atomic::AtomicU64::new(0), + ..StreamSyncState::default() }); let query_guard = state.pin_query( Utc.with_ymd_and_hms(2026, 7, 16, 12, 0, 0).unwrap(), @@ -2324,16 +2577,15 @@ mod tests { ); let item = WorkItem { timestamp: Utc::now(), - minute_path: stream_root.join(minute), - local_path: local_path.clone(), - file: manifest_file("logs/date=2026-07-16/hour=12/minute=00/cached.parquet", 50), + path: "logs/date=2026-07-16/hour=12/minute=00/cached.parquet".to_owned(), + size: 50, }; let budget = DiskBudget::new( - Some(DiskUtil { + DiskUtil { total_space: 1_000, available_space: 0, used_space: 1_000, - }), + }, 100.0, ); let (sender, _receiver) = tokio::sync::mpsc::unbounded_channel(); @@ -2344,7 +2596,7 @@ mod tests { .await .unwrap(); - assert_eq!(reservation, None); + assert!(reservation.is_none()); assert_eq!(tokio::fs::metadata(&local_path).await.unwrap().len(), 100); drop(query_guard); @@ -2353,7 +2605,7 @@ mod tests { .await .unwrap(); - assert_eq!(reservation, Some(0)); + assert_eq!(reservation.map(|(bytes, _)| bytes), Some(0)); assert!(!local_path.exists()); } @@ -2384,9 +2636,7 @@ mod tests { } let state = Arc::new(StreamSyncState { runtime: tokio::sync::Mutex::new(runtime), - eviction: Arc::new(tokio::sync::RwLock::new(())), - query_pins: std::sync::Mutex::new(std::collections::HashMap::new()), - next_query_pin: std::sync::atomic::AtomicU64::new(0), + ..StreamSyncState::default() }); let _query_guard = state.pin_query( Utc.with_ymd_and_hms(2026, 7, 16, 12, 1, 30).unwrap(), @@ -2394,9 +2644,8 @@ mod tests { ); let item = WorkItem { timestamp: Utc::now(), - minute_path: stream_root.join("date=2026-07-16/hour=12/minute=02"), - local_path: stream_root.join("date=2026-07-16/hour=12/minute=02/new.parquet"), - file: manifest_file("logs/date=2026-07-16/hour=12/minute=02/new.parquet", 100), + path: "logs/date=2026-07-16/hour=12/minute=02/new.parquet".to_owned(), + size: 100, }; let (sender, _receiver) = tokio::sync::mpsc::unbounded_channel(); let manager = HotTierManager::new(root, sender); @@ -2413,7 +2662,7 @@ mod tests { .await .unwrap(); - assert_eq!(evicted, Some(100)); + assert_eq!(evicted.map(|(bytes, _)| bytes), Some(100)); assert!(!stream_root.join(oldest).exists()); assert!(stream_root.join(pinned).exists()); } @@ -2472,6 +2721,49 @@ mod tests { assert_eq!(outcomes, vec![11, 12, 13, 14]); } + #[tokio::test] + async fn large_hot_tier_downloads_cannot_overlap_across_streams() { + let root = Box::leak(tempfile::tempdir().unwrap().keep().into_boxed_path()); + let (sender, _receiver) = tokio::sync::mpsc::unbounded_channel(); + let manager = HotTierManager::new(root, sender); + let first = manager.reserve_download_bytes(200 * 1024 * 1024).await; + let second = manager.reserve_download_bytes(64 * 1024 * 1024); + tokio::pin!(second); + assert!(futures_util::poll!(&mut second).is_pending()); + drop(first); + drop(second.await); + let oversized = manager.reserve_download_bytes(u64::MAX).await; + assert_eq!( + oversized.num_permits(), + super::GLOBAL_DOWNLOAD_BYTES as usize + ); + assert_eq!(manager.download_bytes.available_permits(), 0); + } + + #[tokio::test] + async fn waiting_for_global_bytes_drives_existing_downloads() { + let bytes = Arc::new(Semaphore::new(1)); + let work = run_bounded_newest_first( + vec![1, 2, 3], + 4, + |item| { + let bytes = bytes.clone(); + async move { Ok::<_, i32>((item, bytes.acquire_owned().await.unwrap())) } + }, + |(item, permit)| async move { + tokio::task::yield_now().await; + drop(permit); + item + }, + ); + assert_eq!( + tokio::time::timeout(Duration::from_secs(2), work) + .await + .unwrap(), + [1, 2, 3] + ); + } + #[tokio::test] async fn failed_newer_download_does_not_reorder_remaining_starts() { let started = Arc::new(Mutex::new(Vec::new())); diff --git a/src/hottier/local_state.rs b/src/hottier/local_state.rs index 32951ca3d..4116486d3 100644 --- a/src/hottier/local_state.rs +++ b/src/hottier/local_state.rs @@ -31,6 +31,7 @@ pub(super) struct MinuteTotals { #[derive(Debug, Default)] pub(super) struct RuntimeState { pub source_watermark: Option>, + pub dirty: bool, pub minutes: BTreeMap, reservations: HashMap, inflight_buckets: HashMap, @@ -69,6 +70,7 @@ impl RuntimeState { totals.bytes = totals.bytes.saturating_add(bytes); totals.files = totals.files.saturating_add(1); totals.verified = true; + self.dirty = true; } pub fn mark_bucket_inflight(&mut self, minute: &str) { @@ -114,10 +116,12 @@ impl RuntimeState { } pub fn remove_bucket(&mut self, minute: &str) -> u64 { - self.minutes - .remove(minute) - .map(|totals| totals.bytes) - .unwrap_or_default() + if let Some(totals) = self.minutes.remove(minute) { + self.dirty = true; + totals.bytes + } else { + 0 + } } } diff --git a/src/hottier/planner.rs b/src/hottier/planner.rs index 4901d1940..753474696 100644 --- a/src/hottier/planner.rs +++ b/src/hottier/planner.rs @@ -5,17 +5,13 @@ use std::{ use chrono::{DateTime, Utc}; -use crate::{ - catalog::manifest::{File, Manifest}, - utils::extract_datetime, -}; +use crate::{catalog::manifest::Manifest, utils::extract_datetime}; #[derive(Debug)] pub(super) struct WorkItem { pub timestamp: DateTime, - pub minute_path: PathBuf, - pub local_path: PathBuf, - pub file: File, + pub path: String, + pub size: u64, } #[derive(Debug, Default)] @@ -32,59 +28,50 @@ pub(super) fn build_work( cache_root: &Path, is_valid_local: impl Fn(&Path, u64) -> bool, ) -> WorkPlan { - let discovered = manifests + let files = manifests .values() .flatten() - .flat_map(|manifest| manifest.files.iter()) - .filter_map(|file| { - extract_datetime(&file.file_path).map(|timestamp| (timestamp.and_utc(), file)) - }) - .collect::>(); - let mut unique = BTreeMap::new(); - for (timestamp, file) in discovered { - unique - .entry(file.file_path.clone()) - .or_insert((timestamp, file)); - } - let mut files = unique.into_values().collect::>(); - let source_watermark = files.iter().map(|(timestamp, _)| *timestamp).max(); - let Some(watermark) = source_watermark else { + .flat_map(|manifest| &manifest.files); + let Some(watermark) = files + .clone() + .filter_map(|file| extract_datetime(&file.file_path)) + .max() + .map(|ts| ts.and_utc()) + else { return WorkPlan::default(); }; let cutoff = watermark - chrono::Duration::minutes(latest_minutes as i64); - - let active = files - .drain(..) - .filter(|(timestamp, _)| *timestamp > cutoff) - .collect::>(); - let active_minute_paths = active - .iter() - .filter_map(|(_, file)| { - minute_ancestor(&cache_root.join(&file.file_path)).map(Path::to_path_buf) - }) - .collect(); - let inventory_files = active.len(); - let mut items = active - .into_iter() - .filter_map(|(timestamp, file)| { - let local_path = cache_root.join(&file.file_path); - if is_valid_local(&local_path, file.file_size) { - return None; - } - let minute_path = minute_ancestor(&local_path)?.to_path_buf(); - Some(WorkItem { + let mut seen = BTreeSet::new(); + let mut active_minute_paths = BTreeSet::new(); + let mut items = Vec::new(); + for file in files { + let Some(timestamp) = extract_datetime(&file.file_path).map(|ts| ts.and_utc()) else { + continue; + }; + if timestamp <= cutoff || !seen.insert(file.file_path.as_str()) { + continue; + } + let Ok(local_path) = super::hot_tier_disk_path(cache_root, &file.file_path) else { + continue; + }; + let Some(minute) = minute_ancestor(&local_path) else { + continue; + }; + active_minute_paths.insert(minute.to_owned()); + if !is_valid_local(&local_path, file.file_size) { + items.push(WorkItem { timestamp, - minute_path, - local_path, - file: file.clone(), - }) - }) - .collect::>(); + path: file.file_path.clone(), + size: file.file_size, + }); + } + } + let inventory_files = seen.len(); items.sort_by(|left, right| { right .timestamp .cmp(&left.timestamp) - .then_with(|| right.file.file_path.cmp(&left.file.file_path)) + .then_with(|| right.path.cmp(&left.path)) }); WorkPlan { @@ -176,7 +163,7 @@ mod tests { assert_eq!( plan.items .iter() - .map(|item| item.file.file_path.as_str()) + .map(|item| item.path.as_str()) .collect::>(), vec![ "logs/date=2026-07-16/hour=12/minute=14/b.parquet", @@ -186,6 +173,43 @@ mod tests { ); } + #[test] + fn cutoff_and_duplicates_are_filtered_before_local_checks() { + let active = "logs/date=2026-07-16/hour=12/minute=15/a.parquet"; + let manifests = BTreeMap::from([( + "date=2026-07-16".into(), + vec![Manifest { + files: vec![ + file("logs/date=2026-07-16/hour=12/minute=00/old.parquet", 5), + file(active, 7), + file(active, 999), + ], + ..Manifest::default() + }], + )]); + let checks = std::cell::Cell::new(0); + let plan = build_work(&manifests, 15, Path::new("/cache"), |_, size| { + checks.set(checks.get() + 1); + assert_eq!(size, 7); + false + }); + assert_eq!(checks.get(), 1); + assert_eq!(plan.inventory_files, 1); + let [ + super::WorkItem { + path, + size, + timestamp, + }, + ] = plan.items.as_slice() + else { + panic!("expected one missing file") + }; + assert_eq!(path, active); + assert_eq!(*size, 7); + assert_eq!(Some(*timestamp), plan.source_watermark); + } + #[test] fn custom_partition_file_groups_by_date_hour_minute_ancestor() { let path = Path::new( diff --git a/src/metastore/metastores/postgres_metastore.rs b/src/metastore/metastores/postgres_metastore.rs index b597d3ed5..d48db9f53 100644 --- a/src/metastore/metastores/postgres_metastore.rs +++ b/src/metastore/metastores/postgres_metastore.rs @@ -85,6 +85,60 @@ super::document_metastore::document_metastore!( } ); +impl PostgresMetastore { + /// A hot-tier inventory uses at most one pooled connection at a time. + /// Each manifest chunk releases its connection before decoding begins. + pub(crate) async fn get_manifest_files_for_dates_streaming( + &self, + stream: &str, + tenant: &Option, + dates: &[String], + ) -> Result>, MetastoreError> { + let mut result = BTreeMap::new(); + for date in dates { + let prefix = crate::storage::object_storage::stream_data_path(stream, &[date], tenant); + let listing = self + .storage + .list_with_delimiter( + Some(object_store::path::Path::from(prefix.as_str())), + tenant, + ) + .await?; + let paths: Vec<_> = listing + .objects + .into_iter() + .filter(|object| { + object + .location + .filename() + .is_some_and(|name| name.ends_with("manifest.json")) + }) + .map(|object| object.location.to_string()) + .collect(); + let mut manifests = Vec::with_capacity(paths.len()); + let chunks = self.storage.manifest_chunks(&paths, tenant); + futures::pin_mut!(chunks); + while let Some(rows) = chunks.try_next().await? { + for (path, body) in rows { + // manifest_chunks omits keys deleted between listing and retrieval. + // Preserve the inventory's all-or-error contract on concurrent retention. + if path != paths[manifests.len()] { + return Err( + ObjectStorageError::NoSuchKey(paths[manifests.len()].clone()).into(), + ); + } + manifests.push(decode_manifest_blocking(body).await?); + } + } + if let Some(missing) = paths.get(manifests.len()) { + return Err(ObjectStorageError::NoSuchKey(missing.clone()).into()); + } + result.insert(date.clone(), manifests); + } + Ok(result) + } +} + // Parse tuning as text first: whether it is meaningful depends on the parsed URL, // including CLI overrides of environment values. Do not inspect process argv. #[derive(clap::Args)] @@ -1166,8 +1220,15 @@ mod contract_tests { assert!(store.stream_exists("alias", &None).await.unwrap()); assert!(documents.get_object(RelativePath::new("alias/.stream/.stream.json"), &None).await.is_ok()); let paths: Vec<_> = (0..70).map(|i| format!("batch/date=2026-01-01/{i}.manifest.json")).collect(); - for key in &paths { documents.put_object(RelativePath::new(key), Bytes::new(), &None).await.unwrap(); } + let manifest = Bytes::from(serde_json::to_vec(&Manifest::default()).unwrap()); + for key in &paths { + documents.put_object(RelativePath::new(key), manifest.clone(), &None).await.unwrap(); + } assert_eq!(documents.manifest_batch(&paths, &None).await.unwrap().len(), 70); + let dates = ["date=2026-01-01".to_owned(), "date=2026-01-02".to_owned()]; + let inventory = store.get_manifest_files_for_dates_streaming("batch", &None, &dates).await.unwrap(); + assert_eq!(inventory[&dates[0]].len(), 70); + assert!(inventory[&dates[1]].is_empty()); let large_paths: Vec<_> = (0..3).map(|i| format!("large/date=2026-01-01/{i}.manifest.json")).collect(); for key in &large_paths { documents.put_object(RelativePath::new(key), Bytes::from(vec![b'x'; 5 * 1024 * 1024]), &None).await.unwrap(); } // Model growth between the size lookup and the body read: diff --git a/src/storage/retention.rs b/src/storage/retention.rs index cdd06b97b..b03243880 100644 --- a/src/storage/retention.rs +++ b/src/storage/retention.rs @@ -275,6 +275,7 @@ mod action { .into_iter() .filter(|date| string_to_date(date) < retain_until) .collect_vec(); + let mut failed_deletions = std::collections::HashSet::new(); let dates = dates_to_delete.clone(); if !dates.is_empty() { let delete_tasks = FuturesUnordered::new(); @@ -292,23 +293,31 @@ mod action { // The tenant's own data, not a same-named stream of the default tenant. let stream_name = &stream_name; delete_tasks.push(async move { - PARSEABLE + let result = PARSEABLE .metastore .delete_stream_partition(stream_name, &date, tenant_id) - .await - .map_err(crate::metastore::MetastoreError::into_storage_error) + .await; + (date, result) }); } let res: Vec<_> = delete_tasks.collect().await; - for res in res { - if let Err(err) = res { - error!("Failed to run delete task {err:?}"); - return; + for (date, result) in res { + if let Err(err) = result { + error!(%date, "Failed to run delete task {err:?}"); + failed_deletions.insert(date); } } } + + if let Some(manager) = crate::hottier::GLOBAL_HOTTIER.get() + && let Err(err) = manager + .prune_retention_dates(&stream_name, tenant_id, retain_until, &failed_deletions) + .await + { + error!(%stream_name, ?tenant_id, %err, "Failed to prune hot-tier retention partitions"); + } } fn get_retain_until(current_date: NaiveDate, days: u64) -> NaiveDate { From 39b6e57f3f08f4d89e0e0a130f279f0d46075fe0 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Tue, 1 Dec 2026 15:36:04 -0600 Subject: [PATCH 07/17] Address adversarial review findings and harden cross-track integration --- src/catalog/manifest.rs | 12 +- src/connectors/kafka/processor.rs | 27 + src/hottier.rs | 80 ++- src/main.rs | 6 +- src/metastore/metadata_cache.rs | 63 +- .../metastores/document_metastore.rs | 583 +++--------------- .../metastores/postgres_metastore.rs | 8 +- src/parseable/staging/disk_source.rs | 42 +- src/parseable/staging/reader.rs | 42 +- src/parseable/staging/writer.rs | 10 +- src/parseable/streams.rs | 51 +- src/parseable/streams/crash_recovery_tests.rs | 75 +++ src/query/listing_table_builder.rs | 28 +- src/query/mod.rs | 161 ++++- src/query/small_file_cache.rs | 34 +- src/query/stream_schema_provider.rs | 284 +++++++-- src/storage/localfs.rs | 41 +- src/storage/object_storage.rs | 18 +- src/utils/arrow/mod.rs | 6 +- 19 files changed, 872 insertions(+), 699 deletions(-) diff --git a/src/catalog/manifest.rs b/src/catalog/manifest.rs index ba505237f..b39692e9a 100644 --- a/src/catalog/manifest.rs +++ b/src/catalog/manifest.rs @@ -1197,13 +1197,15 @@ mod codec_tests { max: "z\u{7f}\u{e9}\n".to_owned(), })), }, - null_count: (index % 2 == 0).then_some(index as u64), + null_count: index.is_multiple_of(2).then_some(index as u64), uncompressed_size: 1024 + index as u64, compressed_size: 512, - stats_provenance: (index % 3 == 0).then_some(StatsProvenance { + stats_provenance: index.is_multiple_of(3).then_some(StatsProvenance { complete_row_groups: true, - exact_min_max: index % 2 == 0, - timestamp_unit: (index % 6 == 0).then_some(ManifestTimeUnit::Millisecond), + exact_min_max: index.is_multiple_of(2), + timestamp_unit: index + .is_multiple_of(6) + .then_some(ManifestTimeUnit::Millisecond), }), }; let files = (0..file_count) @@ -1213,7 +1215,7 @@ mod codec_tests { file_size: u64::MAX - file as u64, ingestion_size: file as u64, columns: (0..file % 7).map(|index| column(file, index)).collect(), - sort_order_id: if file % 3 == 0 { + sort_order_id: if file.is_multiple_of(3) { vec![("ts".to_owned(), SortOrder::DescNullsLast)] } else { Vec::new() diff --git a/src/connectors/kafka/processor.rs b/src/connectors/kafka/processor.rs index f23b0f901..b94498fc4 100644 --- a/src/connectors/kafka/processor.rs +++ b/src/connectors/kafka/processor.rs @@ -496,6 +496,29 @@ fn partition_chunks( }) } +/// Distinguishes permanent payload/schema/limit rejections (which would never +/// succeed on retry and would wedge the shared consumer poll loop) from +/// transient storage, metastore, or I/O failures. +fn is_permanent_kafka_chunk_error(err: &anyhow::Error) -> bool { + if let Some(event_err) = err.downcast_ref::() { + return matches!( + event_err, + EventError::FieldsCountLimitExceeded(..) | EventError::Staging(StagingError::Arrow(_)) + ); + } + if let Some(staging_err) = err.downcast_ref::() { + return matches!(staging_err, StagingError::Arrow(_)); + } + if let Some(metastore_err) = err.downcast_ref::() { + return matches!( + metastore_err, + crate::metastore::MetastoreError::Error { status_code, .. } + if status_code.is_client_error() + ); + } + false +} + /// Process chunks concurrently, yielding commit offsets in partition input order. async fn process_partition_chunks( processor: &P, @@ -518,6 +541,10 @@ where let mut attempt = BatchAttempt { batch: Arc::new(batch), retrying: false }; let mut delay = Duration::from_secs(1); while let Err(err) = processor.process(attempt.clone()).await { + if is_permanent_kafka_chunk_error(&err) { + error!(?tp, offsets = ?tpl, %err, "Skipping Kafka chunk after permanent validation/schema error"); + break; + } attempt.retrying = true; warn!(?tp, offsets = ?tpl, %err, ?delay, "Kafka staging failed; retrying chunk before committing"); tokio::select! { diff --git a/src/hottier.rs b/src/hottier.rs index 5309d76b6..0876780a6 100644 --- a/src/hottier.rs +++ b/src/hottier.rs @@ -1294,8 +1294,8 @@ impl HotTierManager { let used = runtime.used_bytes(); let reserved = runtime.reserved_bytes(); if runtime.dirty { - persist_checkpoint(&self.stream_root(stream, tenant_id), &runtime).await?; let mut metadata = self.read_hot_tier_config(stream, tenant_id).await?; + persist_checkpoint(&self.stream_root(stream, tenant_id), &runtime).await?; metadata.used_size = used; metadata.available_size = metadata.size.saturating_sub(used.saturating_add(reserved)); self.put_hot_tier(stream, &mut metadata, tenant_id).await?; @@ -1375,8 +1375,7 @@ impl HotTierManager { } let quota = self.read_hot_tier_config(stream, tenant_id).await?.size; let concurrency = PARSEABLE.options.hot_tier_files_per_stream_concurrency as usize; - let budget = self.shared_disk_budget().await; - let Some((_, disk_budget)) = budget.as_ref() else { + let Some(disk_budget) = self.shared_disk_budget().await else { return Ok(TickStats { capacity: work.len(), ..TickStats::default() @@ -1718,6 +1717,7 @@ impl HotTierManager { // Finish any inventory/download that started before the remote deletion. let _sync = state.sync.lock().await; let stream_root = self.stream_root(stream, tenant_id); + let mut prune_err: Option = None; for date in self.fetch_hot_tier_dates(stream, tenant_id).await? { let key = format!("date={date}"); if date >= retain_until || failed_deletions.contains(&key) { @@ -1736,7 +1736,11 @@ impl HotTierManager { match fs::remove_dir_all(stream_root.join(&key)).await { Ok(()) => {} Err(err) if err.kind() == io::ErrorKind::NotFound => {} - Err(err) => return Err(err.into()), + Err(err) => { + error!(stream = %stream, tenant = ?tenant_id, date = %key, error = %err, "Failed to prune hot-tier date directory"); + prune_err.get_or_insert_with(|| err.into()); + continue; + } } let mut runtime = state.runtime.lock().await; runtime @@ -1746,6 +1750,9 @@ impl HotTierManager { } self.flush_state_if_dirty(stream, tenant_id, &state).await?; drop(admission); + if let Some(err) = prune_err { + return Err(err); + } Ok(()) } @@ -1843,45 +1850,51 @@ impl HotTierManager { pub async fn is_disk_available(&self, size_to_download: u64) -> bool { self.shared_disk_budget() .await - .as_ref() - .is_some_and(|(_, budget)| budget.deficit(size_to_download) == 0) + .is_some_and(|budget| budget.deficit(size_to_download) == 0) } - // A read lease spans the download batch. Refresh exclusively between batches - // so a filesystem sample cannot race a reservation, commit or eviction. - async fn shared_disk_budget( - &self, - ) -> tokio::sync::RwLockReadGuard<'_, Option<(Instant, DiskBudget)>> { + // Clones the Arc-backed DiskBudget so no RwLock guard is held across download + // batches. Periodic refreshes update the counters in place while preserving + // active in-flight reservations. + async fn shared_disk_budget(&self) -> Option { let fresh = |budget: &Option<(Instant, DiskBudget)>| { budget .as_ref() .is_some_and(|(at, _)| at.elapsed() < Duration::from_secs(30)) }; - let budget = self.disk_budget.read().await; - if fresh(&budget) { - return budget; + { + let budget = self.disk_budget.read().await; + if fresh(&budget) { + return budget.as_ref().map(|(_, b)| b.clone()); + } } - drop(budget); let _refresh = self.disk_refresh.lock().await; - let budget = self.disk_budget.read().await; - if fresh(&budget) { - return budget; + { + let budget = self.disk_budget.read().await; + if fresh(&budget) { + return budget.as_ref().map(|(_, b)| b.clone()); + } } - drop(budget); - let mut budget = self.disk_budget.write().await; let path = self.hot_tier_path; let usage = tokio::task::spawn_blocking(move || disk_usage_for_path(path)).await; - *budget = match usage { - Ok(Some(usage)) => Some(( - Instant::now(), - DiskBudget::new(usage, PARSEABLE.options.max_disk_usage), - )), + let mut budget = self.disk_budget.write().await; + match usage { + Ok(Some(usage)) => { + let refreshed = if let Some((_, existing)) = budget.as_ref() { + existing.refresh(usage, PARSEABLE.options.max_disk_usage); + existing.clone() + } else { + DiskBudget::new(usage, PARSEABLE.options.max_disk_usage) + }; + *budget = Some((Instant::now(), refreshed.clone())); + Some(refreshed) + } _ => { error!("Cannot measure available hot-tier disk space; postponing downloads"); + *budget = None; None } - }; - tokio::sync::RwLockWriteGuard::downgrade(budget) + } } pub async fn get_oldest_date_time_entry( @@ -2043,6 +2056,19 @@ impl DiskBudget { } } + fn refresh(&self, usage: DiskUtil, max_disk_usage: f64) { + let mut state = self.state.lock().expect("disk budget lock poisoned"); + let reserved: u64 = state + .reservations + .values() + .copied() + .fold(0u64, u64::saturating_add); + state.total_space = usage.total_space; + state.max_used_space = ((max_disk_usage * usage.total_space as f64) / 100.0) as u64; + state.available_space = usage.available_space.saturating_sub(reserved); + state.used_space = usage.used_space.saturating_add(reserved); + } + fn deficit(&self, bytes: u64) -> u64 { let state = self.state.lock().expect("disk budget lock poisoned"); bytes.saturating_sub(state.available_space).max( diff --git a/src/main.rs b/src/main.rs index 203e5c214..0f238e0ef 100644 --- a/src/main.rs +++ b/src/main.rs @@ -67,9 +67,9 @@ unsafe impl Sync for MallocConf {} /// (anything above its 14 KiB small-class limit) with one extra page to /// randomise where the allocation starts within its first page. Arrow buffers, /// IPC messages and request bodies are mostly such allocations, so the padding -/// was a 4 KiB tax on each of them: up to a quarter of a 16 KiB buffer. The -/// randomisation only spreads cache-index conflicts between allocations whose -/// first lines are hot; turning it off costs no CPU. +/// was a 4 KiB tax on each of them: up to a quarter of a 16 KiB buffer. Note +/// that disabling `cache_oblivious` trades away CPU-cache set randomization +/// for lower page-rounding overhead. /// /// `dirty_decay_ms` and `narenas` are deliberately not tightened: profiling /// under load showed lower values trade the memory for `madvise` and arena diff --git a/src/metastore/metadata_cache.rs b/src/metastore/metadata_cache.rs index 5ef14a518..82a86e554 100644 --- a/src/metastore/metadata_cache.rs +++ b/src/metastore/metadata_cache.rs @@ -117,21 +117,55 @@ impl CacheWeight for Option { impl CacheWeight for ObjectStoreFormat { fn cache_weight(&self) -> usize { - // What grows with the stream: a manifest item for each day and node, - // and the known fields of its log sources. + // Account for variable-size collections that grow with the stream: + // manifest list, log sources + fields, permissions, tags, and labels. let manifests = &self.snapshot.manifest_list; + let log_source_bytes = self.log_source.capacity() + * std::mem::size_of::() + + self + .log_source + .iter() + .map(|entry| { + let name_bytes = match &entry.log_source_format { + crate::event::format::LogSource::Custom(name) => name.capacity(), + _ => 0, + }; + let fields_bytes = entry.fields.capacity() * std::mem::size_of::() + + entry.fields.iter().map(String::capacity).sum::(); + name_bytes + fields_bytes + }) + .sum::(); + let permissions_bytes = self.permissions.capacity() + * std::mem::size_of::() + + self + .permissions + .iter() + .map(|perm| { + perm.id.capacity() + + perm.group.capacity() + + perm.access.capacity() * std::mem::size_of::() + + perm.access.iter().map(String::capacity).sum::() + }) + .sum::(); + let labels_bytes = self.dataset_labels.capacity() * std::mem::size_of::() + + self + .dataset_labels + .iter() + .map(String::capacity) + .sum::(); + let tags_bytes = + self.dataset_tags.capacity() * std::mem::size_of::(); + std::mem::size_of::() - + std::mem::size_of_val(manifests.as_slice()) + + manifests.capacity() * std::mem::size_of::() + manifests .iter() .map(|item| item.manifest_path.capacity()) .sum::() - + self - .log_source - .iter() - .flat_map(|entry| &entry.fields) - .map(|field| std::mem::size_of::() + field.capacity()) - .sum::() + + log_source_bytes + + permissions_bytes + + labels_bytes + + tags_bytes } } @@ -495,12 +529,19 @@ impl SlotMap { return evicted; } let charged = std::mem::replace(&mut entry.bytes, bytes); - // Filled last, it expires last: queued behind every filled entry + // Order `filled` by actual fill instant so concurrent loads that finish + // out of order still expire and evict in true chronological order. entry.sequence = sequence; let filled = slot.cell.get().map_or(now, |(filled, _)| *filled); self.next_sequence += 1; self.bytes = self.bytes.saturating_sub(charged).saturating_add(bytes); - self.filled.push_back((sequence, filled, key.clone())); + let insert_at = self + .filled + .iter() + .rposition(|(_, existing, _)| *existing <= filled) + .map_or(0, |idx| idx + 1); + self.filled + .insert(insert_at, (sequence, filled, key.clone())); self.drop_expired(ttl, now, &mut evicted); while self.bytes > self.max_bytes { match self.evict_filled(Some(key)) { diff --git a/src/metastore/metastores/document_metastore.rs b/src/metastore/metastores/document_metastore.rs index e26b14907..5fd3336eb 100644 --- a/src/metastore/metastores/document_metastore.rs +++ b/src/metastore/metastores/document_metastore.rs @@ -14,6 +14,15 @@ macro_rules! postgres_list_streams { Ok($s.storage.list_streams($t).await?) }; } +macro_rules! postgres_manifest_files_for_dates { + (true, $s:ident, $stream:expr, $tenant:expr, $dates:expr, $body:block) => { + $body + }; + (false, $s:ident, $stream:expr, $tenant:expr, $dates:expr, $body:block) => { + $s.get_manifest_files_for_dates_streaming($stream, $tenant, $dates) + .await + }; +} // Shared path, encoding and behavioral contract for document metastores. macro_rules! document_metastore { ($name:ident, $storage:ty, $local_listing:tt, {$($lifecycle:tt)*}) => { @@ -299,101 +308,6 @@ pub fn is_missing_optional_dir(err: &ObjectStorageError) -> bool { } } -/// How long a `put_schema` may rely on what `get_schema` returned. The two -/// calls of a schema merge follow each other at once; this only bounds how -/// long a fetch that no write followed is remembered. -const FETCHED_SCHEMA_TTL: std::time::Duration = std::time::Duration::from_secs(5); - -/// Fetches remembered at a time. Beyond it a fetch is not remembered, and the -/// write that follows it is made. -const MAX_FETCHED_SCHEMAS: usize = 1024; - -/// What `get_schema` returned for a schema object, for the `put_schema` that -/// follows it. -struct FetchedSchema { - /// Holds the allocation of the store, so that its address, which is part - /// of the key of this entry, is not that of another store while the entry - /// exists. - _storage: std::sync::Weak<$storage>, - /// The task that fetched it. A write of another task does not rely on it. - task: Option, - fetched: std::time::Instant, - bytes: Bytes, -} - -/// The schema objects fetched last, by store and path. -/// -/// A sync merges a staged schema into the stored one by `get_schema`, a merge -/// and `put_schema`. Most of the time the staged schema adds nothing, and the -/// write would store what was just read. This lets `put_schema` see that. -static FETCHED_SCHEMAS: std::sync::LazyLock> = - std::sync::LazyLock::new(DashMap::new); - -fn fetched_schema_key(storage: &Arc<$storage>, path: &RelativePath) -> (usize, String) { - (Arc::as_ptr(storage) as *const () as usize, path.to_string()) -} - -fn remember_fetched_schema(storage: &Arc<$storage>, path: &RelativePath, bytes: &Bytes) { - // Fetches no write followed are dropped once they are of no use - if FETCHED_SCHEMAS.len() >= 16 { - FETCHED_SCHEMAS.retain(|_, fetched| fetched.fetched.elapsed() < FETCHED_SCHEMA_TTL); - } - let key = fetched_schema_key(storage, path); - if FETCHED_SCHEMAS.len() >= MAX_FETCHED_SCHEMAS { - // Nor is an earlier fetch of this object left to be relied on - drop(FETCHED_SCHEMAS.remove(&key)); - return; - } - FETCHED_SCHEMAS.insert( - key, - FetchedSchema { - _storage: Arc::downgrade(storage), - task: tokio::task::try_id(), - fetched: std::time::Instant::now(), - bytes: bytes.clone(), - }, - ); -} - -/// Forgets what was fetched for a schema object that is written or removed. -fn forget_fetched_schema(storage: &Arc<$storage>, path: &RelativePath) -> Option { - FETCHED_SCHEMAS - .remove(&fetched_schema_key(storage, path)) - .map(|(_, fetched)| fetched) -} - -/// Whether two schemas are the same but for the order of their top-level -/// fields, which is immaterial to a stored schema: its readers merge it by -/// field name. Nested types, nullability and metadata all have to match. -fn same_stored_schema(a: &Schema, b: &Schema) -> bool { - if a.metadata != b.metadata || a.fields.len() != b.fields.len() { - return false; - } - let by_name = |schema: &Schema| { - let mut fields = schema.fields.to_vec(); - fields.sort_by(|left, right| left.name().cmp(right.name())); - fields - }; - by_name(a) == by_name(b) -} - -/// Whether the schema object already holds `schema`, going by what this task -/// fetched for it just before: writing it again would change nothing. -/// -/// Only a fetch of this same task, moments ago, with no write of the object -/// through this store since, is relied on. What it cannot see is a write by -/// another process in those moments. The write skipped here would have -/// overwritten that one blindly; left alone, the object keeps what the other -/// process stored, which the next merge reads. -fn schema_is_stored(fetched: Option, schema: &Schema) -> bool { - fetched.is_some_and(|fetched| { - fetched.task == tokio::task::try_id() - && fetched.fetched.elapsed() < FETCHED_SCHEMA_TTL - && serde_json::from_slice::(&fetched.bytes) - .is_ok_and(|stored| same_stored_schema(&stored, schema)) - }) -} - #[async_trait] impl Metastore for $name { /// Since Parseable already starts with a connection to an object store, no need to implement this @@ -1148,102 +1062,104 @@ impl Metastore for $name { tenant_id: &Option, dates: &[String], ) -> Result>, MetastoreError> { - let inventory_limit = Arc::new(tokio::sync::Semaphore::new(16)); - let date_futures = dates.iter().map(|date| { - let stream = stream_name.to_string(); - let tenant = tenant_id.clone(); - let date = date.clone(); - let inventory_limit = inventory_limit.clone(); - async move { - let t_start = std::time::Instant::now(); - let date_path = if let Some(tenant) = tenant.as_ref().filter(|t| !t.is_empty() && t.as_str() != DEFAULT_TENANT) { - object_store::path::Path::from(format!("{}/{}/{}", tenant, stream, date)) - } else { - object_store::path::Path::from(format!("{}/{}", stream, date)) - }; + postgres_manifest_files_for_dates!($local_listing, self, stream_name, tenant_id, dates, { + let inventory_limit = Arc::new(tokio::sync::Semaphore::new(16)); + let date_futures = dates.iter().map(|date| { + let stream = stream_name.to_string(); + let tenant = tenant_id.clone(); + let date = date.clone(); + let inventory_limit = inventory_limit.clone(); + async move { + let t_start = std::time::Instant::now(); + let date_path = if let Some(tenant) = tenant.as_ref().filter(|t| !t.is_empty() && t.as_str() != DEFAULT_TENANT) { + object_store::path::Path::from(format!("{}/{}/{}", tenant, stream, date)) + } else { + object_store::path::Path::from(format!("{}/{}", stream, date)) + }; + + let t_list = std::time::Instant::now(); + let list_permit = inventory_limit + .clone() + .acquire_owned() + .await + .expect("inventory semaphore remains open"); + let list_result = scoped_delimiter!($local_listing, self, Some(date_path), &tenant); + drop(list_permit); + let resp = match list_result { + Ok(r) => r, + Err(ObjectStorageError::NoSuchKey(_)) => { + info!( + stream = %stream, + tenant = ?tenant, + date = %date, + list_ms = t_list.elapsed().as_millis() as u64, + "manifest fetch: date prefix not found" + ); + return Ok::<(String, Vec), MetastoreError>((date, Vec::new())); + } + Err(e) => return Err(e.into()), + }; + let list_ms = t_list.elapsed().as_millis() as u64; + + let manifest_paths: Vec = resp + .objects + .iter() + .filter(|name| name.location.filename().unwrap().ends_with("manifest.json")) + .map(|name| name.location.to_string()) + .collect(); + let manifest_count = manifest_paths.len(); + + let t_gets = std::time::Instant::now(); + let manifests = futures::stream::iter(manifest_paths) + .map(|path| { + let tenant = tenant.clone(); + let inventory_limit = inventory_limit.clone(); + async move { + let _permit = inventory_limit + .acquire_owned() + .await + .expect("inventory semaphore remains open"); + let bytes = self + .storage + .get_object(&RelativePathBuf::from(path), &tenant) + .await?; + Ok::(decode_manifest_blocking(bytes).await?) + } + }) + .buffer_unordered(16) + .try_collect::>() + .await?; + let gets_ms = t_gets.elapsed().as_millis() as u64; + let total_ms = t_start.elapsed().as_millis() as u64; - let t_list = std::time::Instant::now(); - let list_permit = inventory_limit - .clone() - .acquire_owned() - .await - .expect("inventory semaphore remains open"); - let list_result = scoped_delimiter!($local_listing, self, Some(date_path), &tenant); - drop(list_permit); - let resp = match list_result { - Ok(r) => r, - Err(ObjectStorageError::NoSuchKey(_)) => { + if total_ms > 100 { info!( stream = %stream, tenant = ?tenant, date = %date, - list_ms = t_list.elapsed().as_millis() as u64, - "manifest fetch: date prefix not found" + list_ms, + gets_ms, + total_ms, + manifest_count, + "manifest fetch per-date timing" ); - return Ok::<(String, Vec), MetastoreError>((date, Vec::new())); } - Err(e) => return Err(e.into()), - }; - let list_ms = t_list.elapsed().as_millis() as u64; - - let manifest_paths: Vec = resp - .objects - .iter() - .filter(|name| name.location.filename().unwrap().ends_with("manifest.json")) - .map(|name| name.location.to_string()) - .collect(); - let manifest_count = manifest_paths.len(); - - let t_gets = std::time::Instant::now(); - let manifests = futures::stream::iter(manifest_paths) - .map(|path| { - let tenant = tenant.clone(); - let inventory_limit = inventory_limit.clone(); - async move { - let _permit = inventory_limit - .acquire_owned() - .await - .expect("inventory semaphore remains open"); - let bytes = self - .storage - .get_object(&RelativePathBuf::from(path), &tenant) - .await?; - Ok::(decode_manifest_blocking(bytes).await?) - } - }) - .buffer_unordered(16) - .try_collect::>() - .await?; - let gets_ms = t_gets.elapsed().as_millis() as u64; - let total_ms = t_start.elapsed().as_millis() as u64; - - if total_ms > 100 { - info!( - stream = %stream, - tenant = ?tenant, - date = %date, - list_ms, - gets_ms, - total_ms, - manifest_count, - "manifest fetch per-date timing" - ); + Ok((date, manifests)) } - Ok((date, manifests)) - } - }); + }); - let results: Vec<(String, Vec)> = - futures::future::try_join_all(date_futures).await?; + let results: Vec<(String, Vec)> = + futures::future::try_join_all(date_futures).await?; - let mut result_file_list: BTreeMap> = BTreeMap::new(); - for (date, manifests) in results { - if !manifests.is_empty() { - result_file_list.insert(date, manifests); + let mut result_file_list: BTreeMap> = BTreeMap::new(); + for (date, manifests) in results { + if !manifests.is_empty() { + result_file_list.insert(date, manifests); + } } - } - Ok(result_file_list) + Ok(result_file_list) + }) } /// Fetch a specific `Manifest` file @@ -1498,9 +1414,6 @@ impl Metastore for $name { STREAM_ROOT_DIRECTORY, schema_file, ]); - // Whether or not the write lands, what was fetched no longer - // tells what the object holds - drop(forget_fetched_schema(&self.storage, &path)); self.storage .put_object(&path, to_bytes(&merged), tenant_id) .await?; @@ -1514,14 +1427,9 @@ impl Metastore for $name { tenant_id: &Option, ) -> Result { let path = schema_path(stream_name, tenant_id); - let bytes = self.storage.get_object(&path, tenant_id).await?; - remember_fetched_schema(&self.storage, &path, &bytes); - Ok(bytes) + Ok(self.storage.get_object(&path, tenant_id).await?) } - /// Stores the schema, unless the `get_schema` this task made just before - /// returned the same one: a merge that added nothing to the stored schema - /// writes nothing, and leaves the metadata cache as it is. async fn put_schema( &self, obj: Schema, @@ -1529,11 +1437,6 @@ impl Metastore for $name { tenant_id: &Option, ) -> Result<(), MetastoreError> { let path = schema_path(stream_name, tenant_id); - // Taken before the write, so that a failed write, which may still - // have landed, is not mistaken for the stored schema later - if schema_is_stored(forget_fetched_schema(&self.storage, &path), &obj) { - return Ok(()); - } let result = self .storage .put_object(&path, to_bytes(&obj), tenant_id) @@ -1817,297 +1720,3 @@ pub(crate) fn document_scope(key: &str) -> Option<(String, &'static str)> { super::postgres_documents::kind(relative_path::RelativePath::new(key)), )) } - -/// `put_schema` writes nothing when the `get_schema` of its task just before -/// returned the schema it is given, and writes in every other case. -#[cfg(test)] -mod schema_write_tests { - use std::{collections::HashMap, path::PathBuf, sync::Arc}; - - use arrow_schema::{DataType, Field, Schema}; - - use crate::{ - metastore::{ - metastore_traits::Metastore, metastores::object_store_metastore::ObjectStoreMetastore, - }, - storage::{ - LocalFS, ObjectStorage, - object_storage::{schema_path, to_bytes}, - }, - }; - - /// A store over a directory of its own, and the file of the stream's - /// schema in it - struct Stored { - store: Arc, - storage: Arc, - stream: &'static str, - file: PathBuf, - // Removed with the test - _dir: tempfile::TempDir, - } - - /// Bytes no write of a schema leaves in the file: the schema in another - /// field order and layout, as another writer could have stored it - fn marker(schema: &Schema) -> Vec { - let mut fields = schema.fields.to_vec(); - fields.reverse(); - serde_json::to_vec_pretty(&Schema::new_with_metadata(fields, schema.metadata.clone())) - .unwrap() - } - - impl Stored { - fn new(stream: &'static str) -> Self { - crate::parseable::install_default_test_parseable(); - let dir = tempfile::tempdir().unwrap(); - let storage = Arc::new(LocalFS::new(dir.path().to_owned())); - let file = schema_path(stream, &None).to_path(dir.path()); - // The test writes the file by itself too, to tell whether the - // store wrote it - std::fs::create_dir_all(file.parent().unwrap()).unwrap(); - Self { - store: Arc::new(ObjectStoreMetastore { - storage: storage.clone(), - }), - storage, - stream, - file, - _dir: dir, - } - } - - /// Fetches the schema, as a merge does first, and then marks the file - async fn fetch(&self, mark: &[u8]) -> Schema { - let fetched = self.store.get_schema(self.stream, &None).await.unwrap(); - std::fs::write(&self.file, mark).unwrap(); - serde_json::from_slice(&fetched).unwrap() - } - - async fn put(&self, schema: &Schema) { - self.store - .put_schema(schema.clone(), self.stream, &None) - .await - .unwrap(); - } - - fn file(&self) -> Vec { - std::fs::read(&self.file).unwrap() - } - - /// Whether a `put_schema` of `put`, right after a fetch that returned - /// `stored`, wrote the file - async fn writes(&self, stored: &Schema, put: &Schema) -> bool { - std::fs::write(&self.file, to_bytes(stored)).unwrap(); - let mark = marker(stored); - assert_eq!(&self.fetch(&mark).await, stored); - self.put(put).await; - if self.file() == mark { - return false; - } - assert_eq!(self.file(), to_bytes(put)); - true - } - } - - fn schema() -> Schema { - Schema::new(vec![ - Field::new("a", DataType::Int64, true), - Field::new("b", DataType::Utf8, true), - Field::new( - "c", - DataType::List(Arc::new(Field::new("item", DataType::Float64, true))), - true, - ), - ]) - } - - #[tokio::test] - async fn a_schema_just_fetched_is_not_written_again() { - let stored = Stored::new("schema-write-fetched"); - let schema = schema(); - // Nothing was fetched: the schema is written - stored.put(&schema).await; - assert_eq!(stored.file(), to_bytes(&schema)); - - assert!(!stored.writes(&schema, &schema).await); - // In another order of its fields too, which no reader tells apart - let mut fields = schema.fields.to_vec(); - fields.rotate_left(1); - assert!(!stored.writes(&schema, &Schema::new(fields)).await); - - // The fetch is relied on once. The same schema is written when - // nothing was fetched since. - let mark = marker(&schema); - stored.fetch(&mark).await; - stored.put(&schema).await; - assert_eq!(stored.file(), mark); - stored.put(&schema).await; - assert_eq!(stored.file(), to_bytes(&schema)); - } - - #[tokio::test] - async fn a_schema_that_differs_from_the_fetched_one_is_written() { - let stored = Stored::new("schema-write-differs"); - let schema = schema(); - let with = |index: usize, field: Field| { - let mut fields = schema.fields.to_vec(); - fields[index] = Arc::new(field); - Schema::new(fields) - }; - for other in [ - // What a merge stores: a field more - Schema::try_merge([ - schema.clone(), - Schema::new(vec![Field::new("d", DataType::Boolean, true)]), - ]) - .unwrap(), - Schema::new(schema.fields[..2].to_vec()), - Schema::empty(), - with(0, Field::new("a", DataType::Float64, true)), - with(0, Field::new("a", DataType::Int64, false)), - with(0, Field::new("A", DataType::Int64, true)), - with( - 1, - Field::new("b", DataType::Utf8, true) - .with_metadata(HashMap::from([("k".to_owned(), "v".to_owned())])), - ), - with( - 2, - Field::new( - "c", - DataType::List(Arc::new(Field::new("item", DataType::Float64, false))), - true, - ), - ), - schema - .clone() - .with_metadata(HashMap::from([("k".to_owned(), "v".to_owned())])), - ] { - assert!(stored.writes(&schema, &other).await, "{other:?}"); - assert!(stored.writes(&other, &schema).await, "{other:?}"); - assert!(!stored.writes(&other, &other).await, "{other:?}"); - } - } - - #[tokio::test] - async fn only_the_fetch_of_the_writing_task_and_store_is_relied_on() { - let stored = Stored::new("schema-write-task"); - let schema = schema(); - stored.put(&schema).await; - let mark = marker(&schema); - - // Fetched here, written by another task - stored.fetch(&mark).await; - let (store, written) = (stored.store.clone(), schema.clone()); - tokio::spawn(async move { - store - .put_schema(written, "schema-write-task", &None) - .await - .unwrap() - }) - .await - .unwrap(); - assert_eq!(stored.file(), to_bytes(&schema)); - - // Fetched and written by one task, other than this one - let (store, file, written, marked) = ( - stored.store.clone(), - stored.file.clone(), - schema.clone(), - mark.clone(), - ); - tokio::spawn(async move { - store.get_schema("schema-write-task", &None).await.unwrap(); - std::fs::write(file, marked).unwrap(); - store - .put_schema(written, "schema-write-task", &None) - .await - .unwrap(); - }) - .await - .unwrap(); - assert_eq!(stored.file(), mark); - - // Fetched through this store, written through another one of the - // same directory - std::fs::write(&stored.file, to_bytes(&schema)).unwrap(); - stored.fetch(&mark).await; - let other = ObjectStoreMetastore { - storage: Arc::new(LocalFS::new(stored._dir.path().to_owned())), - }; - other - .put_schema(schema.clone(), stored.stream, &None) - .await - .unwrap(); - assert_eq!(stored.file(), to_bytes(&schema)); - } - - /// `refresh_schema` writes the schema object by itself. What was fetched - /// before it is then not what the object holds. - #[tokio::test] - async fn a_refresh_that_writes_the_schema_voids_the_fetch() { - let stored = Stored::new("schema-write-refresh"); - let schema = schema(); - stored.put(&schema).await; - let fetched = stored.fetch(&to_bytes(&schema)).await; - assert_eq!(fetched, schema); - - // Another node's schema has a field this one lacks - let node = Schema::new(vec![Field::new("on_another_node", DataType::Utf8, true)]); - let node_path = schema_path(stored.stream, &None) - .parent() - .unwrap() - .join(".ingestor.other.schema"); - stored - .storage - .put_object(&node_path, to_bytes(&node), &None) - .await - .unwrap(); - let refreshed = stored - .store - .refresh_schema(stored.stream, &None, ".schema") - .await - .unwrap(); - assert!(refreshed.field_with_name("on_another_node").is_ok()); - assert_eq!( - serde_json::from_slice::(&stored.file()).unwrap(), - refreshed - ); - - // The schema fetched before the refresh is written, over the refresh - stored.put(&schema).await; - assert_eq!(stored.file(), to_bytes(&schema)); - } - - /// A write that is skipped changed nothing, and leaves the stream's - /// cached metadata in place. A write that is made drops it. - #[tokio::test] - async fn a_skipped_write_keeps_the_cached_metadata() { - use crate::{ - catalog::manifest::Manifest, - metastore::{MetastoreError, metadata_cache::METADATA_CACHE}, - }; - let stored = Stored::new("schema-write-cache"); - if !METADATA_CACHE.enabled() { - return; - } - let schema = schema(); - stored.put(&schema).await; - let cached = || { - METADATA_CACHE - .cached_manifest(stored.stream, &None, "m") - .is_some() - }; - METADATA_CACHE - .manifest(stored.stream, &None, "m", || async { - Ok::<_, MetastoreError>(Some(Manifest::default())) - }) - .await - .unwrap(); - assert!(cached()); - assert!(!stored.writes(&schema, &schema).await); - assert!(cached()); - stored.put(&schema).await; - assert!(!cached()); - } -} diff --git a/src/metastore/metastores/postgres_metastore.rs b/src/metastore/metastores/postgres_metastore.rs index d48db9f53..203fedce7 100644 --- a/src/metastore/metastores/postgres_metastore.rs +++ b/src/metastore/metastores/postgres_metastore.rs @@ -133,7 +133,9 @@ impl PostgresMetastore { if let Some(missing) = paths.get(manifests.len()) { return Err(ObjectStorageError::NoSuchKey(missing.clone()).into()); } - result.insert(date.clone(), manifests); + if !manifests.is_empty() { + result.insert(date.clone(), manifests); + } } Ok(result) } @@ -1226,9 +1228,9 @@ mod contract_tests { } assert_eq!(documents.manifest_batch(&paths, &None).await.unwrap().len(), 70); let dates = ["date=2026-01-01".to_owned(), "date=2026-01-02".to_owned()]; - let inventory = store.get_manifest_files_for_dates_streaming("batch", &None, &dates).await.unwrap(); + let inventory = store.get_manifest_files_for_dates("batch", &None, &dates).await.unwrap(); assert_eq!(inventory[&dates[0]].len(), 70); - assert!(inventory[&dates[1]].is_empty()); + assert!(!inventory.contains_key(&dates[1])); let large_paths: Vec<_> = (0..3).map(|i| format!("large/date=2026-01-01/{i}.manifest.json")).collect(); for key in &large_paths { documents.put_object(RelativePath::new(key), Bytes::from(vec![b'x'; 5 * 1024 * 1024]), &None).await.unwrap(); } // Model growth between the size lookup and the body read: diff --git a/src/parseable/staging/disk_source.rs b/src/parseable/staging/disk_source.rs index 8f46f4000..e5ca7fa40 100644 --- a/src/parseable/staging/disk_source.rs +++ b/src/parseable/staging/disk_source.rs @@ -167,7 +167,7 @@ impl AcknowledgedIpcIndex { } } - pub(super) fn snapshot(&self, start: u64, end: u64) -> Option { + pub(super) fn snapshot(self: &Arc, start: u64, end: u64) -> Option { let start = if start == 0 { self.schema_len } else { start }; let entries = self.batches.lock(); let first = entries.partition_point(|entry| entry.offset < start); @@ -177,18 +177,20 @@ impl AcknowledgedIpcIndex { return None; } Some(IpcIndexSnapshot { - schema: Arc::clone(&self.schema), schema_len: usize::try_from(self.schema_len).ok()?, - batches: Arc::from(selected), + index: Arc::clone(self), + first, + past, }) } } #[derive(Debug, Clone)] pub(super) struct IpcIndexSnapshot { - schema: Arc, schema_len: usize, - batches: Arc<[IndexedIpcBatch]>, + index: Arc, + first: usize, + past: usize, } /// The exact acknowledged prefix of one staging file, opened for reading. @@ -255,8 +257,20 @@ impl StagingDiskSource { } /// Immutable acknowledged record-batch locations and statistics for this range. - pub fn indexed_batches(&self) -> Option<&Arc<[IndexedIpcBatch]>> { - self.index.as_ref().map(|index| &index.batches) + pub fn indexed_batches(&self) -> Option> { + let snap = self.index.as_ref()?; + let entries = snap.index.batches.lock(); + Some(entries[snap.first..snap.past].to_vec()) + } + + #[cfg(test)] + pub(super) fn shares_index_with(&self, other: &Self) -> bool { + match (&self.index, &other.index) { + (Some(a), Some(b)) => { + Arc::ptr_eq(&a.index, &b.index) && a.first == b.first && a.past == b.past + } + _ => false, + } } /// The path the file had when it was opened. It may have been renamed or @@ -327,10 +341,12 @@ impl StagingDiskSource { time: Option>, fold_counts: bool, ) -> Result<(ValidatedPrefixPlan, u64), StagingError> { - if let Some(index) = &self.index { - let mut messages = Vec::new(); + if let Some(snap) = &self.index { + let entries = snap.index.batches.lock(); + let batches = &entries[snap.first..snap.past]; + let mut messages = Vec::with_capacity(batches.len()); let mut folded = 0u64; - for batch in index.batches.iter() { + for batch in batches { if let (Some(time), TimestampBounds::NonNull { min, max }) = (&time, batch.timestamp) { @@ -358,8 +374,8 @@ impl StagingDiskSource { } return Ok(( ValidatedPrefixPlan { - schema: Arc::clone(&index.schema), - schema_range: (0, index.schema_len), + schema: Arc::clone(&snap.index.schema), + schema_range: (0, snap.schema_len), messages, has_dictionaries: false, }, @@ -396,7 +412,7 @@ impl StagingDiskSource { ranges, projection, buffer_bytes, - self.index.as_ref().map(|i| i.schema.clone()), + self.index.as_ref().map(|i| i.index.schema.clone()), ) .map_err(|err| { StagingError::ObjectStorage(io::Error::new( diff --git a/src/parseable/staging/reader.rs b/src/parseable/staging/reader.rs index 5f16e07d9..6020c5460 100644 --- a/src/parseable/staging/reader.rs +++ b/src/parseable/staging/reader.rs @@ -778,6 +778,10 @@ fn ipc_decode_error(err: ArrowError) -> ArrowError { } } +/// Below this IPC message size, reading the whole message in a single read and +/// projecting in memory beats issuing multiple sparse seeks and reads. +const SPARSE_PROJECTION_MIN_MESSAGE_BYTES: usize = 64 * 1024; + /// Framing and layout are validated against the original message before /// reading body buffers. Nested schemas keep the full body for both phases. struct BatchMessage { @@ -793,12 +797,17 @@ impl BatchMessage { size: usize, schema: &Schema, sparse: bool, + known_file_len: Option, ) -> Result { let raw = if sparse { let end = offset .checked_add(size as u64) .ok_or_else(|| invalid_ipc("IPC range overflow"))?; - if reader.seek(SeekFrom::End(0))? < end { + let file_len = match known_file_len { + Some(len) => len, + None => reader.seek(SeekFrom::End(0))?, + }; + if file_len < end { return Err(invalid_ipc("Truncated IPC record batch range").into()); } read_exact_range(reader, offset, size.min(8))? @@ -949,6 +958,8 @@ pub(crate) enum RangeBatchReader { next: usize, layout: Vec>, projection: Vec, + file_len: u64, + min_sparse_bytes: usize, }, } @@ -978,6 +989,7 @@ impl RangeBatchReader { && columns.last().is_none_or(|&i| i < schema.fields().len()) && let Some(layout) = flat_buffer_layout(&schema) { + let file_len = reader.seek(SeekFrom::End(0))?; return Ok(Self::Projected { reader, schema, @@ -985,12 +997,25 @@ impl RangeBatchReader { next: 1, layout, projection: columns.clone(), + file_len, + min_sparse_bytes: SPARSE_PROJECTION_MIN_MESSAGE_BYTES, }); } } stream_reader_for_ranges(reader, ranges, projection, buffer_bytes) .map(|reader| Self::Stream(Box::new(reader))) } + + #[cfg(test)] + fn with_min_sparse_bytes(mut self, threshold: usize) -> Self { + if let Self::Projected { + min_sparse_bytes, .. + } = &mut self + { + *min_sparse_bytes = threshold; + } + self + } } impl Iterator for RangeBatchReader { @@ -1005,10 +1030,16 @@ impl Iterator for RangeBatchReader { next, layout, projection, + file_len, + min_sparse_bytes, } => { let &(offset, size) = ranges.get(*next)?; - let batch = BatchMessage::read(reader, offset, size, schema, true) - .and_then(|message| message.decode(reader, schema, Some(layout), projection)); + let sparse = size >= *min_sparse_bytes; + let batch = + BatchMessage::read(reader, offset, size, schema, sparse, Some(*file_len)) + .and_then(|message| { + message.decode(reader, schema, Some(layout), projection) + }); *next = if batch.is_ok() { *next + 1 } else { @@ -1616,8 +1647,10 @@ where offset, size, &self.file_schema, - self.flat_layout.is_some() + size >= SPARSE_PROJECTION_MIN_MESSAGE_BYTES + && self.flat_layout.is_some() && self.filter_indices.len() < self.file_schema.fields().len(), + None, ) .map_err(TwoPhaseReadError::from_decode)?; let filter_batch = message @@ -4525,6 +4558,7 @@ mod tests { None, ) .unwrap() + .with_min_sparse_bytes(0) .collect::, _>>() .unwrap(); let expected = diff --git a/src/parseable/staging/writer.rs b/src/parseable/staging/writer.rs index 57f60a192..68c2c60cd 100644 --- a/src/parseable/staging/writer.rs +++ b/src/parseable/staging/writer.rs @@ -821,7 +821,12 @@ impl Writer { .append(rb, preencoded) .and_then(|()| if flush { writer.flush_staged() } else { Ok(()) }); if let Err(err) = result { + let orphan = (writer.acknowledged() == 0).then(|| writer.path().to_path_buf()); writer.retire_failed(); + drop(writer); + if let Some(path) = orphan { + let _ = fs::remove_file(path); + } return Err(err); } self.disk.insert(key, writer); @@ -3528,10 +3533,7 @@ mod tests { mem_mut(&mut writer).rekey_pending(&sealed.arrow, &moved); std::fs::rename(&sealed.arrow, &moved).unwrap(); let after = writer.capture(&schema).unwrap(); - assert!(Arc::ptr_eq( - before_index, - after.disk[0].indexed_batches().unwrap() - )); + assert!(before.disk[0].shares_index_with(&after.disk[0])); assert_eq!(sorted_ids(&writer), (0..500).collect::>()); mem_mut(&mut writer).release_pending(std::slice::from_ref(&moved)); std::fs::remove_file(&moved).unwrap(); diff --git a/src/parseable/streams.rs b/src/parseable/streams.rs index 5cc9c15a9..4389c6200 100644 --- a/src/parseable/streams.rs +++ b/src/parseable/streams.rs @@ -175,9 +175,10 @@ impl ConversionMemoryBudget { fn new(bytes: u64) -> Self { // Use exact byte permits wherever possible. Larger budgets need // coarser units because acquire_many accepts at most u32::MAX. + let bytes = bytes.max(1); let max_permits = u64::from(u32::MAX).min(Semaphore::MAX_PERMITS as u64); - let bytes_per_permit = bytes.div_ceil(max_permits); - let permits = (bytes / bytes_per_permit) as u32; + let bytes_per_permit = bytes.div_ceil(max_permits).max(1); + let permits = (bytes / bytes_per_permit).max(1) as u32; Self { semaphore: Semaphore::new(permits as usize), permits, @@ -185,6 +186,13 @@ impl ConversionMemoryBudget { } } + fn is_exclusive(&self, staged_bytes: u64) -> bool { + let estimated = staged_bytes + .saturating_mul(4) + .max(LOG_PARALLEL_WAVE_SOFT_BYTES as u64); + estimated.div_ceil(self.bytes_per_permit) >= u64::from(self.permits) + } + async fn acquire(&self, staged_bytes: u64) -> SemaphorePermit<'_> { // IPC can be compressed. Allow room for decoded rows, read-ahead, // and encoder state, and charge at least one wave even for a small @@ -959,14 +967,15 @@ impl)>> LogRowGroupSo } let newly_finished = self.finisher.finish(decoded)?; - // Statistics see every batch whole and in source order, whatever row - // groups its rows end up in. + // Unclustered conversion feeds batches in exact file order, so + // approximate HLL counts remain identical to a post-write reread; drop + // inline stats only if retained heap exceeds the configured byte budget. if let Some(stats) = self.stats.as_mut() { for batch in &newly_finished { stats.update(batch); if self .inline_stats_max_bytes - .is_some_and(|max_bytes| stats.exceeds_inline_budget(max_bytes)) + .is_some_and(|max_bytes| stats.retained_bytes() > max_bytes) { self.stats = None; break; @@ -3078,7 +3087,7 @@ impl Stream { (self.options.row_group_bytes > 0).then_some(self.options.row_group_bytes); let mut props = WriterProperties::builder() .set_writer_version(WriterVersion::PARQUET_1_0) - .set_dictionary_page_size_limit(128 * 1024) + .set_dictionary_page_size_limit(256 * 1024) .set_max_row_group_row_count(Some(self.options.row_group_size)) .set_max_row_group_bytes(row_group_bytes) .set_compression(self.options.parquet_compression.into()) @@ -3163,9 +3172,12 @@ impl Stream { for partition in custom_partition.split(',') { if let Ok(idx) = merged_schema.index_of(partition) { let column_path = ColumnPath::new(vec![partition.to_string()]); - if !matches!( + if matches!( merged_schema.field(idx).data_type(), - arrow_schema::DataType::Timestamp(_, _) + arrow_schema::DataType::Utf8 + | arrow_schema::DataType::LargeUtf8 + | arrow_schema::DataType::Binary + | arrow_schema::DataType::LargeBinary ) { props = props.set_column_encoding(column_path, Encoding::DELTA_BYTE_ARRAY); } @@ -4348,7 +4360,7 @@ impl Stream { let batch = batch?; if stats.as_mut().is_some_and(|acc| { acc.update(&batch); - acc.exceeds_inline_budget(MAX_INLINE_FIELD_STATS_BYTES) + acc.retained_bytes() > MAX_INLINE_FIELD_STATS_BYTES }) { stats = None; } @@ -5564,17 +5576,16 @@ impl Stream { } }; for entry in entries.flatten() { + // Skip `processing_*` directories because they may belong to an + // overlapping conversion cycle already holding its own permit. if entry .file_name() .to_str() .is_some_and(|s| s.starts_with(INPROCESS_DIR_PREFIX)) { - if let Ok(children) = entry.path().read_dir() { - bytes += children.flatten().map(arrow_bytes).sum::(); - } - } else { - bytes += arrow_bytes(entry); + continue; } + bytes += arrow_bytes(entry); } bytes } @@ -5788,7 +5799,15 @@ impl Streams { let mut ready: Vec<_> = ready.into_iter().map(|(tenant, stream, recovery)| { (stream.pending_conversion_bytes(), tenant, stream, recovery) }).collect(); - ready.sort_by_key(|(bytes, ..)| std::cmp::Reverse(*bytes)); + // Dispatch non-exclusive streams before exclusive ones so a + // single giant stream does not head-of-line block parallel + // conversions of smaller streams. + ready.sort_by_key(|(bytes, ..)| { + ( + CONVERSION_MEMORY_BUDGET.is_exclusive(*bytes), + std::cmp::Reverse(*bytes), + ) + }); (ready, failure) }) .await @@ -6159,7 +6178,7 @@ mod log_parquet_pipeline_tests { Some(&"region".to_owned()), false, ); - assert_eq!(props.dictionary_page_size_limit(), 128 * 1024); + assert_eq!(props.dictionary_page_size_limit(), 256 * 1024); assert_eq!(props.max_row_group_row_count(), Some(262_144)); assert_eq!(props.writer_version(), WriterVersion::PARQUET_1_0); assert!(!props.offset_index_disabled()); diff --git a/src/parseable/streams/crash_recovery_tests.rs b/src/parseable/streams/crash_recovery_tests.rs index 462a0d429..88f781ffc 100644 --- a/src/parseable/streams/crash_recovery_tests.rs +++ b/src/parseable/streams/crash_recovery_tests.rs @@ -2200,3 +2200,78 @@ fn failed_part_sync_removes_unjournaled_part_and_retries_sources() { assert_eq!(capture_pairs(&stream), (vec![], expected_pairs(false))); assert_clean_residue(&stream); } + +#[test] +fn zstd_parquet_and_compressed_staging_zero_memory_recovers_every_boundary() { + use crate::parseable::staging::{MemWriter, StagingMemoryBudget}; + + for boundary in [ + Boundary::PartSynced, + Boundary::JournalInstalled, + Boundary::AfterPublish, + Boundary::SourcesRetired, + ] { + let dir = TempDir::new().unwrap(); + let options = Arc::new(Options { + local_staging_path: dir.path().to_path_buf(), + row_group_size: 1048576, + parquet_compression: crate::option::Compression::Zstd, + ..Default::default() + }); + let stream = fresh(options.clone()); + // Force disk-only staging (0-byte memory budget) with batches above the + // IPC compression threshold (>= 100 rows) and Zstd Parquet output. + let budget = Arc::new(StagingMemoryBudget::new(0)); + stream.writer.lock().unwrap().mem = Some(MemWriter::with_budget(budget)); + stream.stage_schema_file(schema(false)).unwrap(); + + let now = DateTime::parse_from_rfc3339("2020-01-02T12:34:30.500Z") + .unwrap() + .with_timezone(&Utc); + let total_rows = 250i32; + for (key, start, end) in [("batch-a", 0, 125), ("batch-b", 125, total_rows)] { + let count = (end - start) as usize; + let columns: Vec = vec![ + Arc::new(TimestampMillisecondArray::from(vec![ + now.timestamp_millis(); + count + ])), + Arc::new(Int32Array::from((start..end).collect::>())), + ]; + let batch = RecordBatch::try_new(Arc::new(schema(false)), columns).unwrap(); + stream + .push( + key, + &batch, + now.naive_utc(), + &HashMap::new(), + StreamType::UserDefined, + ) + .unwrap(); + } + // Before flush, disk-backed capture must see every acknowledged row. + let expected: Vec = (0..total_rows).map(|id| (id, None)).collect(); + let (mut staged_before_flush, parquet_before_flush) = capture_pairs(&stream); + staged_before_flush.sort(); + assert_eq!(staged_before_flush, expected, "boundary={boundary:?}"); + assert!(parquet_before_flush.is_empty()); + + stream.flush_with_clock(true, || now).unwrap(); + arm_boundary(&stream, boundary); + let crashed = catch_unwind(AssertUnwindSafe(|| { + let _ = stream.prepare_parquet(false, true, &None); + })); + assert!(crashed.is_err(), "expected crash at {boundary:?}"); + drop(stream); + + // Fresh Stream restart recovers and converges cleanly over two cycles. + let restarted = fresh(options); + restarted.prepare_parquet(true, false, &None).unwrap(); + restarted.prepare_parquet(true, false, &None).unwrap(); + let (staged_after, mut parquet_after) = capture_pairs(&restarted); + parquet_after.sort(); + assert!(staged_after.is_empty(), "boundary={boundary:?}"); + assert_eq!(parquet_after, expected, "boundary={boundary:?}"); + assert_clean_residue(&restarted); + } +} diff --git a/src/query/listing_table_builder.rs b/src/query/listing_table_builder.rs index 38a3ad0a1..31f8b1f03 100644 --- a/src/query/listing_table_builder.rs +++ b/src/query/listing_table_builder.rs @@ -23,6 +23,7 @@ use chrono::TimeDelta; use datafusion::{ catalog::Session, common::Statistics, + config::TableParquetOptions, datasource::{ file_format::{ FileFormat, FileMeta, file_compression_type::FileCompressionType, @@ -54,6 +55,7 @@ const LEGACY_LISTING_CONCURRENCY: usize = 16; pub struct ListingTableBuilder { stream: String, listing: Vec, + parquet_options: Option, } impl ListingTableBuilder { @@ -64,6 +66,11 @@ impl ListingTableBuilder { } } + pub fn with_parquet_options(mut self, options: TableParquetOptions) -> Self { + self.parquet_options = Some(options); + self + } + #[cfg(test)] pub async fn populate_via_listing( self, @@ -113,8 +120,8 @@ impl ListingTableBuilder { let effective_start = if start_excluded { let Some(next) = start_ts.checked_add_signed(TimeDelta::nanoseconds(1)) else { return Ok(Self { - stream: self.stream, listing: Vec::new(), + ..self }); }; next @@ -132,8 +139,8 @@ impl ListingTableBuilder { }; if is_empty { return Ok(Self { - stream: self.stream, listing: Vec::new(), + ..self }); } @@ -155,8 +162,8 @@ impl ListingTableBuilder { if prefixes.is_empty() { return Ok(Self { - stream: self.stream, listing: Vec::new(), + ..self }); } @@ -200,8 +207,8 @@ impl ListingTableBuilder { if prefixes.is_empty() { return Ok(Self { - stream: self.stream, listing: Vec::new(), + ..self }); } @@ -232,10 +239,7 @@ impl ListingTableBuilder { .rev() .collect_vec(); - Ok(Self { - stream: self.stream, - listing, - }) + Ok(Self { listing, ..self }) } pub fn build( @@ -247,8 +251,12 @@ impl ListingTableBuilder { return Ok(None); } - let file_format = - UnorderedParquetFormat(ParquetFormat::default().with_enable_pruning(true)); + let parquet_format = match self.parquet_options { + Some(options) => ParquetFormat::default().with_options(options), + None => ParquetFormat::default(), + } + .with_enable_pruning(true); + let file_format = UnorderedParquetFormat(parquet_format); let listing_options = ListingOptions::new(Arc::new(file_format)).with_file_extension(".parquet"); let config = ListingTableConfig::new_with_multi_paths(map(self.listing)) diff --git a/src/query/mod.rs b/src/query/mod.rs index 1a3a8c40b..9d29dfdca 100644 --- a/src/query/mod.rs +++ b/src/query/mod.rs @@ -314,8 +314,6 @@ const PARQUET_PREDICATE_CACHE_SIZE_ENV: &str = "P_PARQUET_PREDICATE_CACHE_SIZE"; /// What a Parquet reader may cache when nothing is configured and the query /// memory pool is large enough for it. const DEFAULT_PARQUET_PREDICATE_CACHE_SIZE: usize = 64 * 1024 * 1024; -/// The least the default is lowered to for a small pool or many partitions. -const MIN_PARQUET_PREDICATE_CACHE_SIZE: usize = 8 * 1024 * 1024; /// Resolves how many bytes each Parquet reader may hold of the columns it /// decoded to evaluate pushed-down filters. A reader keeps them until the @@ -324,9 +322,9 @@ const MIN_PARQUET_PREDICATE_CACHE_SIZE: usize = 8 * 1024 * 1024; /// DataFusion does not charge this cache to the query memory pool, and each /// scan partition has a reader of its own, so up to `target_partitions` of them /// hold it at once. By default a reader gets 64 MiB, or less where the readers -/// of one query could together hold more than a quarter of the pool, but never -/// less than 8 MiB. A reader whose cache is full decodes the rest of its filter -/// columns again when it outputs them: a smaller cache costs time, never rows. +/// of one query could together hold more than a quarter of the pool. A reader +/// whose cache is full decodes the rest of its filter columns again when it +/// outputs them: a smaller cache costs time, never rows. /// /// A configured size (`P_PARQUET_PREDICATE_CACHE_SIZE`, in bytes) is used as it /// is. `0` turns the cache off; a size above the default accepts the memory @@ -340,9 +338,7 @@ pub(crate) fn resolve_parquet_predicate_cache_size( return size; } let pool_share = query_pool_bytes / target_partitions.max(1).saturating_mul(4); - DEFAULT_PARQUET_PREDICATE_CACHE_SIZE - .min(pool_share) - .max(MIN_PARQUET_PREDICATE_CACHE_SIZE) + DEFAULT_PARQUET_PREDICATE_CACHE_SIZE.min(pool_share) } /// Reads a size in bytes as `P_PARQUET_PREDICATE_CACHE_SIZE` holds it. `None` @@ -386,23 +382,76 @@ struct QuerySpillDir { _owner: std::fs::File, } +/// Marker bytes written into `.owner.lock` so cleanup only removes abandoned +/// `datafusion-*` directories inside a directory this binary actually initialized. +const QUERY_SPILL_OWNER_MARKER: &[u8] = b"parseable-query-spill-v1\n"; +/// Default cap on query spill space inside the staging volume (4 GiB) so a +/// runaway spill cannot exhaust disk space needed by ingestion. +const DEFAULT_QUERY_SPILL_MAX_BYTES: u64 = 4 * 1024 * 1024 * 1024; +const QUERY_SPILL_MAX_BYTES_ENV: &str = "P_QUERY_SPILL_MAX_BYTES"; + +fn resolve_query_spill_max_bytes() -> u64 { + std::env::var(QUERY_SPILL_MAX_BYTES_ENV) + .ok() + .and_then(|v| v.trim().parse::().ok()) + .filter(|&v| v > 0) + .unwrap_or(DEFAULT_QUERY_SPILL_MAX_BYTES) +} + impl QuerySpillDir { /// Claims `/.query_spill`, creating it if it does not exist, and /// removes the spill directories a process that did not exit cleanly left /// in it. Spill files mean nothing once their query is gone, and they are /// not small. /// - /// Fails when the directory cannot be created or locked, or belongs to - /// another running process. Only the owner removes anything. + /// Fails when the directory cannot be created or locked, is a symlink, or + /// belongs to another running process. Only the owner removes anything. fn claim(base: &Path) -> std::io::Result { + use std::io::{Read, Seek, Write}; + let path = base.join(QUERY_SPILL_DIR_NAME); - std::fs::create_dir_all(&path)?; - let owner = std::fs::OpenOptions::new() + match std::fs::symlink_metadata(&path) { + Ok(meta) => { + if meta.file_type().is_symlink() || !meta.is_dir() { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + "query spill path exists and is not a real directory", + )); + } + } + Err(err) if err.kind() == std::io::ErrorKind::NotFound => { + std::fs::create_dir_all(base)?; + match std::fs::create_dir(&path) { + Ok(()) => {} + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => { + let meta = std::fs::symlink_metadata(&path)?; + if meta.file_type().is_symlink() || !meta.is_dir() { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + "query spill path exists and is not a real directory", + )); + } + } + Err(e) => return Err(e), + } + } + Err(err) => return Err(err), + } + let lock_path = path.join(QUERY_SPILL_OWNER_LOCK); + if let Ok(meta) = std::fs::symlink_metadata(&lock_path) + && (meta.file_type().is_symlink() || !meta.is_file()) + { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + "query spill owner lock is not a regular file", + )); + } + let mut owner = std::fs::OpenOptions::new() .read(true) .write(true) .create(true) .truncate(false) - .open(path.join(QUERY_SPILL_OWNER_LOCK))?; + .open(&lock_path)?; match owner.try_lock() { Ok(()) => {} Err(std::fs::TryLockError::WouldBlock) => { @@ -413,7 +462,17 @@ impl QuerySpillDir { } Err(std::fs::TryLockError::Error(error)) => return Err(error), } - remove_abandoned_spill_dirs(&path); + let mut marker = Vec::new(); + owner.read_to_end(&mut marker)?; + let already_owned_spill_dir = marker == QUERY_SPILL_OWNER_MARKER; + if !already_owned_spill_dir { + owner.set_len(0)?; + owner.rewind()?; + owner.write_all(QUERY_SPILL_OWNER_MARKER)?; + owner.sync_data()?; + } else { + remove_abandoned_spill_dirs(&path); + } Ok(Self { path, _owner: owner, @@ -489,7 +548,8 @@ fn query_spill_dir() -> Option<&'static Path> { fn query_disk_manager(spill_dir: Option<&Path>) -> Option> { let spill_dir = spill_dir?; let builder = DiskManager::builder() - .with_mode(DiskManagerMode::Directories(vec![spill_dir.to_path_buf()])); + .with_mode(DiskManagerMode::Directories(vec![spill_dir.to_path_buf()])) + .with_max_temp_directory_size(resolve_query_spill_max_bytes()); match builder.build() { Ok(disk_manager) => Some(Arc::new(disk_manager)), Err(error) => { @@ -2739,8 +2799,8 @@ mod memory_pool_tests { #[cfg(test)] mod predicate_cache_tests { use super::{ - DEFAULT_PARQUET_PREDICATE_CACHE_SIZE, MIN_PARQUET_PREDICATE_CACHE_SIZE, - parse_parquet_predicate_cache_size, resolve_parquet_predicate_cache_size, + DEFAULT_PARQUET_PREDICATE_CACHE_SIZE, parse_parquet_predicate_cache_size, + resolve_parquet_predicate_cache_size, }; const MIB: usize = 1024 * 1024; @@ -2749,7 +2809,6 @@ mod predicate_cache_tests { #[test] fn default_is_64_mib_and_all_readers_stay_within_a_quarter_of_the_pool() { assert_eq!(DEFAULT_PARQUET_PREDICATE_CACHE_SIZE, 64 * MIB); - assert_eq!(MIN_PARQUET_PREDICATE_CACHE_SIZE, 8 * MIB); // A pool with room for it: the default, however large the pool. for (pool, partitions) in [(64 * GIB, 32), (8 * GIB, 16), (4 * GIB, 16), (GIB, 1)] { @@ -2769,19 +2828,28 @@ mod predicate_cache_tests { resolve_parquet_predicate_cache_size(None, 2 * GIB, 16), 32 * MIB ); - for (pool, partitions) in [(4 * GIB, 32), (2 * GIB, 16), (8 * GIB, 64), (3 * GIB, 24)] { + for (pool, partitions) in [ + (4 * GIB, 32), + (2 * GIB, 16), + (8 * GIB, 64), + (3 * GIB, 24), + (GIB, 64), + (512 * MIB, 32), + ] { let size = resolve_parquet_predicate_cache_size(None, pool, partitions); - assert!(size >= MIN_PARQUET_PREDICATE_CACHE_SIZE); assert!(size * partitions <= pool / 4, "{pool} / {partitions}"); } - // But a reader is never left with less than 8 MiB. - for (pool, partitions) in [(GIB, 64), (512 * MIB, 32), (0, 8), (GIB, usize::MAX)] { - assert_eq!( - resolve_parquet_predicate_cache_size(None, pool, partitions), - 8 * MIB, - "{pool} / {partitions}" - ); - } + // Small or zero pools never exceed the quarter-pool bound via a hard floor. + assert_eq!(resolve_parquet_predicate_cache_size(None, GIB, 64), 4 * MIB); + assert_eq!( + resolve_parquet_predicate_cache_size(None, 512 * MIB, 32), + 4 * MIB + ); + assert_eq!(resolve_parquet_predicate_cache_size(None, 0, 8), 0); + assert_eq!( + resolve_parquet_predicate_cache_size(None, GIB, usize::MAX), + 0 + ); // No partition count divides by zero. assert_eq!( resolve_parquet_predicate_cache_size(None, 64 * GIB, 0), @@ -2829,8 +2897,8 @@ mod query_spill_tests { use std::{fs, path::Path}; use super::{ - DATAFUSION_SPILL_DIR_PREFIX, QUERY_SPILL_DIR_NAME, QUERY_SPILL_OWNER_LOCK, QuerySpillDir, - query_disk_manager, + DATAFUSION_SPILL_DIR_PREFIX, QUERY_SPILL_DIR_NAME, QUERY_SPILL_OWNER_LOCK, + QUERY_SPILL_OWNER_MARKER, QuerySpillDir, query_disk_manager, }; fn names(dir: &Path) -> Vec { @@ -2874,6 +2942,11 @@ mod query_spill_tests { let spill_dir = staging.path().join(QUERY_SPILL_DIR_NAME); let abandoned = spill_dir.join(format!("{DATAFUSION_SPILL_DIR_PREFIX}Ab3xYz")); fs::create_dir_all(abandoned.join("nested")).unwrap(); + fs::write( + spill_dir.join(QUERY_SPILL_OWNER_LOCK), + QUERY_SPILL_OWNER_MARKER, + ) + .unwrap(); fs::write(abandoned.join(".tmpQ1w2E3"), [0u8; 4096]).unwrap(); fs::write(abandoned.join("nested/.tmpR4t5Y6"), b"spilled").unwrap(); // Not the name of a spill directory, or not a directory. @@ -2920,6 +2993,34 @@ mod query_spill_tests { drop(claimed); } + #[test] + fn claim_does_not_delete_unmarked_or_symlinked_spill_directories() { + let staging = tempfile::tempdir().unwrap(); + let spill_dir = staging.path().join(QUERY_SPILL_DIR_NAME); + let preexisting = spill_dir.join(format!("{DATAFUSION_SPILL_DIR_PREFIX}preexisting")); + fs::create_dir_all(&preexisting).unwrap(); + fs::write(preexisting.join("keep.arrows"), b"staged").unwrap(); + + // Without an existing ownership marker, claim writes the marker but does + // not recursively remove pre-existing datafusion-* directories. + let claimed = QuerySpillDir::claim(staging.path()).unwrap(); + assert!(preexisting.exists()); + drop(claimed); + + #[cfg(unix)] + { + let staging2 = tempfile::tempdir().unwrap(); + let target = staging2.path().join("real_stream_dir"); + let child = target.join(format!("{DATAFUSION_SPILL_DIR_PREFIX}victim")); + fs::create_dir_all(&child).unwrap(); + fs::write(child.join("staged.arrows"), b"keep").unwrap(); + std::os::unix::fs::symlink(&target, staging2.path().join(QUERY_SPILL_DIR_NAME)) + .unwrap(); + assert!(QuerySpillDir::claim(staging2.path()).is_err()); + assert!(child.join("staged.arrows").exists()); + } + } + #[test] fn directory_of_a_running_owner_is_neither_claimed_nor_cleaned() { let staging = tempfile::tempdir().unwrap(); diff --git a/src/query/small_file_cache.rs b/src/query/small_file_cache.rs index 6f37599d0..0cd495971 100644 --- a/src/query/small_file_cache.rs +++ b/src/query/small_file_cache.rs @@ -509,17 +509,32 @@ async fn load_planned( let cell = view .files .lock() - .unwrap() + .unwrap_or_else(|e| e.into_inner()) .entry(key.clone()) .or_default() .clone(); let trusted_size = view.trust_immutable.then_some(planned_size); cell.get_or_init(|| async { - load_trusting(&CACHE, scope, store, path, namespace, budget, trusted_size) - .await - // The cell keeps the body until the request ends. - .map(|(size, bytes)| (size, bytes.filter(|bytes| view.retain(&key, bytes.len())))) - .map_err(Arc::new) + match load_trusting(&CACHE, scope, store, path, namespace, budget, trusted_size).await { + Ok((size, Some(bytes))) => { + if view.retain(&key, bytes.len()) { + Ok((size, Some(bytes))) + } else { + // Fail closed rather than falling back to unpinned path reads + // that could mix footer and page bytes across versions. + Err(Arc::new(object_store::Error::Generic { + store: "small_file_cache", + source: format!( + "small file {path} ({} bytes) exceeded request view reservation budget", + bytes.len() + ) + .into(), + })) + } + } + Ok((size, None)) => Ok((size, None)), + Err(err) => Err(Arc::new(err)), + } }) .await .clone() @@ -1298,14 +1313,15 @@ mod tests { let planned = || [((scope, path.clone()), 10)].into(); // Room for what the manifest records and the slack, not for the body. + // Fail closed rather than falling back to unpinned path reads that could + // mix versions mid-query. let tight = RequestView::with_capacity(false, capacity(10 + RESERVATION_SLACK)); assert!(tight.admit(planned(), MAX_BYTES)); for _ in 0..2 { - assert_eq!( + assert!( load_for_scan(&tight, scope, &store, &path, "", MAX_BYTES) .await - .unwrap(), - (body.len() as u64, None) + .is_err() ); } assert_eq!(tight.admission.lock().unwrap().held, 0); diff --git a/src/query/stream_schema_provider.rs b/src/query/stream_schema_provider.rs index 1f78f36af..7d39b7031 100644 --- a/src/query/stream_schema_provider.rs +++ b/src/query/stream_schema_provider.rs @@ -780,6 +780,7 @@ impl StandardTableProvider { limit: Option, ) -> Result<(), DataFusionError> { ListingTableBuilder::new(self.stream.to_owned()) + .with_parquet_options(state.default_table_options().parquet) .populate_via_listing_with_cache( glob_storage.clone(), time_filters, @@ -2152,6 +2153,116 @@ fn split_ipc_messages_by_bytes( chunks } +/// Extracts an inclusive-start, exclusive-end millisecond range `[start_ms, end_ms)` +/// on `p_timestamp` from DataFusion filter expressions for indexed staging-batch +/// pruning and (when `all_exact_time_only` is true) zero-decode `COUNT(*)` folding. +fn extract_staging_timestamp_ms_range( + schema: &Schema, + filters: &[Expr], +) -> Option<(i64, i64, bool)> { + let field = schema.field_with_name(DEFAULT_TIMESTAMP_KEY).ok()?; + if !matches!( + field.data_type(), + arrow_schema::DataType::Timestamp(arrow_schema::TimeUnit::Millisecond, _) + ) { + return None; + } + + let mut stack: Vec<&Expr> = filters.iter().collect(); + let mut start_ms = i64::MIN; + let mut end_ms = i64::MAX; + let mut saw_bound = false; + let mut all_exact_time_only = !filters.is_empty(); + + while let Some(expr) = stack.pop() { + if let Expr::BinaryExpr(bin) = expr + && bin.op == Operator::And + { + stack.push(bin.right.as_ref()); + stack.push(bin.left.as_ref()); + continue; + } + let Some(bound) = PartialTimeFilter::try_from_expr(expr, &None) else { + all_exact_time_only = false; + continue; + }; + saw_bound = true; + match bound { + PartialTimeFilter::Low(Bound::Included(t)) => { + let utc = t.and_utc(); + let ms = utc.timestamp_millis(); + if utc.timestamp_subsec_nanos().is_multiple_of(1_000_000) { + start_ms = start_ms.max(ms); + } else { + all_exact_time_only = false; + start_ms = start_ms.max(ms); + } + } + PartialTimeFilter::Low(Bound::Excluded(t)) => { + let utc = t.and_utc(); + let ms = utc.timestamp_millis(); + if utc.timestamp_subsec_nanos().is_multiple_of(1_000_000) { + if let Some(next) = ms.checked_add(1) { + start_ms = start_ms.max(next); + } else { + // `p_timestamp > i64::MAX` matches nothing. + return Some((1, 0, all_exact_time_only)); + } + } else { + all_exact_time_only = false; + start_ms = start_ms.max(ms); + } + } + PartialTimeFilter::High(Bound::Excluded(t)) => { + let utc = t.and_utc(); + let ms = utc.timestamp_millis(); + if utc.timestamp_subsec_nanos().is_multiple_of(1_000_000) { + end_ms = end_ms.min(ms); + } else { + all_exact_time_only = false; + end_ms = end_ms.min(ms.saturating_add(1)); + } + } + PartialTimeFilter::High(Bound::Included(t)) => { + let utc = t.and_utc(); + let ms = utc.timestamp_millis(); + if utc.timestamp_subsec_nanos().is_multiple_of(1_000_000) { + if let Some(next) = ms.checked_add(1) { + end_ms = end_ms.min(next); + } else { + all_exact_time_only = false; + } + } else { + all_exact_time_only = false; + end_ms = end_ms.min(ms.saturating_add(1)); + } + } + PartialTimeFilter::Eq(t) => { + let utc = t.and_utc(); + let ms = utc.timestamp_millis(); + if utc.timestamp_subsec_nanos().is_multiple_of(1_000_000) { + start_ms = start_ms.max(ms); + if let Some(next) = ms.checked_add(1) { + end_ms = end_ms.min(next); + } else { + all_exact_time_only = false; + } + } else { + all_exact_time_only = false; + start_ms = start_ms.max(ms); + end_ms = end_ms.min(ms.saturating_add(1)); + } + } + PartialTimeFilter::Low(Bound::Unbounded) + | PartialTimeFilter::High(Bound::Unbounded) => { + all_exact_time_only = false; + } + } + } + + saw_bound.then_some((start_ms, end_ms, all_exact_time_only)) +} + /// A scan over staging files whose rows the memory cache does not hold, /// pushing column projections down into Arrow IPC decoding, counting rows from /// validated IPC headers when no columns are needed, and splitting large files @@ -2167,6 +2278,9 @@ async fn staging_disk_plan( if sources.is_empty() { return Ok(None); } + let time_range = extract_staging_timestamp_ms_range(&schema, filters); + let can_fold_counts = + projection.is_some_and(|p| p.is_empty()) && time_range.is_some_and(|(_, _, exact)| exact); let needed_proj = needed_column_projection(&schema, projection, filters)?; let projected_schema = needed_proj.schema; let disk_projection = needed_proj.remapped_projection; @@ -2188,6 +2302,7 @@ async fn staging_disk_plan( reverse_rows: true, batch_size, two_phase_filter, + time_range: time_range.map(|(s, e, _)| (s, e)), }) as Arc; let table = StreamingTable::try_new(projected_schema, vec![partition])?; return scan_enforcing_exact_filters( @@ -2213,25 +2328,41 @@ async fn staging_disk_plan( let table_schema_for_plan = schema.clone(); let projected_for_plan = projected_schema.clone(); let filter_schema_for_plan = two_phase_filter.as_ref().map(|f| f.filter_schema.clone()); - let work_units = tokio::task::spawn_blocking(move || { + let (work_units, folded_units) = tokio::task::spawn_blocking(move || { let mut units = Vec::with_capacity(sources.len()); + let mut folded_units = Vec::new(); for source in sources { if cancel_flag.load(std::sync::atomic::Ordering::Relaxed) { break; } - let plan = match source.plan_prefix() { - Ok(plan) => plan, - Err(err) => { - units.push(StagingDiskWork::Failed(format!( - "Cannot read staging rows: {err}" - ))); - continue; + let (plan, folded_rows) = match time_range { + Some((start_ms, end_ms, _)) => { + match source.plan_prefix_for_time_range(start_ms, end_ms, can_fold_counts) { + Ok(res) => res, + Err(err) => { + units.push(StagingDiskWork::Failed(format!( + "Cannot read staging rows: {err}" + ))); + continue; + } + } } + None => match source.plan_prefix() { + Ok(plan) => (plan, 0), + Err(err) => { + units.push(StagingDiskWork::Failed(format!( + "Cannot read staging rows: {err}" + ))); + continue; + } + }, }; - if !plan.messages.iter().any(|m| m.rows.is_some()) { + let has_messages = plan.messages.iter().any(|m| m.rows.is_some()); + if !has_messages && folded_rows == 0 { continue; } - let has_rows = plan.messages.iter().any(|m| m.rows.is_some_and(|r| r > 0)); + let has_rows = + folded_rows > 0 || plan.messages.iter().any(|m| m.rows.is_some_and(|r| r > 0)); if let Err(err) = validate_file_schema_for_table( &table_schema_for_plan, &plan.schema, @@ -2241,6 +2372,15 @@ async fn staging_disk_plan( units.push(StagingDiskWork::Failed(err)); continue; } + if folded_rows > 0 { + folded_units.push(StagingDiskWork::RowCounts { + source: source.clone(), + total_rows: folded_rows, + }); + } + if !has_messages { + continue; + } let ipc_projection = match ipc_projection_for_file(&plan.schema, &projected_for_plan) { IpcProjection::Empty => { match checked_total_rows(&plan.messages, source.path()) { @@ -2303,59 +2443,87 @@ async fn staging_disk_plan( } } } - units + (units, folded_units) }) .await .map_err(|err| DataFusionError::Execution(format!("Staging disk planning failed: {err}")))?; - if work_units.is_empty() { + if work_units.is_empty() && folded_units.is_empty() { return Ok(None); } - let num_buckets = work_units.len().min(max_partitions).max(1); - let mut buckets: Vec> = (0..num_buckets).map(|_| Vec::new()).collect(); - if num_buckets == 1 { - buckets[0] = work_units; - } else { - let mut indexed: Vec<(usize, StagingDiskWork)> = - work_units.into_iter().enumerate().collect(); - // Balance total bytes across partitions using largest-first bin packing. - indexed.sort_by(|a, b| { - b.1.byte_weight() - .cmp(&a.1.byte_weight()) - .then_with(|| a.0.cmp(&b.0)) - }); - let mut loads = vec![0usize; num_buckets]; - for (_, unit) in indexed { - let target = loads - .iter() - .enumerate() - .min_by_key(|(_, load)| **load) - .map(|(idx, _)| idx) - .unwrap_or(0); - loads[target] = loads[target].saturating_add(unit.byte_weight()); - buckets[target].push(unit); + let mut sub_plans: Vec> = Vec::with_capacity(2); + if !folded_units.is_empty() { + // Folded batches are already certified to satisfy all time predicates + // and carry zero projected columns, so emit them directly without FilterExec. + let empty_schema = Arc::new(Schema::empty()); + let partition = Arc::new(StagingDiskPartition { + table_schema: schema.clone(), + schema: empty_schema.clone(), + work: folded_units, + reverse_rows: false, + batch_size, + two_phase_filter: None, + time_range: None, + }) as Arc; + let table = StreamingTable::try_new(empty_schema, vec![partition])?; + sub_plans.push(table.scan(state, None, &[], limit).await?); + } + + if !work_units.is_empty() { + let num_buckets = work_units.len().min(max_partitions).max(1); + let mut buckets: Vec> = (0..num_buckets).map(|_| Vec::new()).collect(); + if num_buckets == 1 { + buckets[0] = work_units; + } else { + let mut indexed: Vec<(usize, StagingDiskWork)> = + work_units.into_iter().enumerate().collect(); + // Balance total bytes across partitions using largest-first bin packing. + indexed.sort_by(|a, b| { + b.1.byte_weight() + .cmp(&a.1.byte_weight()) + .then_with(|| a.0.cmp(&b.0)) + }); + let mut loads = vec![0usize; num_buckets]; + for (_, unit) in indexed { + let target = loads + .iter() + .enumerate() + .min_by_key(|(_, load)| **load) + .map(|(idx, _)| idx) + .unwrap_or(0); + loads[target] = loads[target].saturating_add(unit.byte_weight()); + buckets[target].push(unit); + } } + + let partitions = buckets + .into_iter() + .filter(|b| !b.is_empty()) + .map(|work| { + Arc::new(StagingDiskPartition { + table_schema: schema.clone(), + schema: projected_schema.clone(), + work, + reverse_rows: false, + batch_size, + two_phase_filter: two_phase_filter.clone(), + time_range: None, + }) as Arc + }) + .collect(); + let table = StreamingTable::try_new(projected_schema, partitions)?; + sub_plans.push( + scan_enforcing_exact_filters(&table, state, disk_projection.as_ref(), filters, limit) + .await?, + ); } - let partitions = buckets - .into_iter() - .filter(|b| !b.is_empty()) - .map(|work| { - Arc::new(StagingDiskPartition { - table_schema: schema.clone(), - schema: projected_schema.clone(), - work, - reverse_rows: false, - batch_size, - two_phase_filter: two_phase_filter.clone(), - }) as Arc - }) - .collect(); - let table = StreamingTable::try_new(projected_schema, partitions)?; - scan_enforcing_exact_filters(&table, state, disk_projection.as_ref(), filters, limit) - .await - .map(Some) + if sub_plans.len() == 1 { + Ok(sub_plans.pop()) + } else { + Ok(Some(UnionExec::try_new(sub_plans)?)) + } } /// Emits lazy row-count-only batches (for `COUNT(*)` or all-missing nullable @@ -2538,6 +2706,7 @@ struct StagingDiskPartition { reverse_rows: bool, batch_size: usize, two_phase_filter: Option, + time_range: Option<(i64, i64)>, } impl PartitionStream for StagingDiskPartition { @@ -2554,6 +2723,7 @@ impl PartitionStream for StagingDiskPartition { let reverse_rows = self.reverse_rows; let batch_size = self.batch_size; let two_phase_filter = self.two_phase_filter.clone(); + let time_range = self.time_range; builder.spawn_blocking(move || { let empty_schema = Arc::new(Schema::empty()); let mut adapter = BatchAdapter::new(schema.clone()); @@ -2566,7 +2736,13 @@ impl PartitionStream for StagingDiskPartition { return Err(DataFusionError::Execution(err)); } StagingDiskWork::LazySource(source) => { - let plan = source.plan_prefix().map_err(|err| { + let plan = match time_range { + Some((start_ms, end_ms)) => source + .plan_prefix_for_time_range(start_ms, end_ms, false) + .map(|(plan, _)| plan), + None => source.plan_prefix(), + } + .map_err(|err| { DataFusionError::Execution(format!("Cannot read staging rows: {err}")) })?; if !plan.messages.iter().any(|m| m.rows.is_some()) { diff --git a/src/storage/localfs.rs b/src/storage/localfs.rs index f53bcdf6a..ab3905e64 100644 --- a/src/storage/localfs.rs +++ b/src/storage/localfs.rs @@ -1162,7 +1162,7 @@ impl ObjectStorage for LocalFS { // A private file of a write in flight, or one a crash left // behind, is no object. It may also be gone before it can be // examined. - if is_upload_temp(&entry.path()) { + if is_upload_temp(&entry.path()) || is_legacy_metadata_temp(&entry.path()) { continue; } let meta = entry.metadata()?; @@ -1874,11 +1874,20 @@ fn replace_plain_object(path: &Path, bytes: &[u8]) -> Result None, + Err(err) => return Err(err.into()), Ok(existing) if is_sole_name_of_regular_file(&existing) => Some(existing), - _ => return Ok(false), + Ok(_) => return Ok(false), }; - let Ok(mut temp) = UploadTemp::create(parent, path) else { - return Ok(false); + let mut temp = match UploadTemp::create(parent, path) { + Ok(temp) => temp, + // Only fall back to in-place writes when the parent directory denies + // creating a sibling temp file for an existing writable target; never + // fall back on ENOSPC/I/O errors where `File::create` would truncate + // the previous valid manifest. + Err(err) if replaced.is_some() && err.kind() == std::io::ErrorKind::PermissionDenied => { + return Ok(false); + } + Err(err) => return Err(err.into()), }; let file = temp.file.as_mut().expect("open temp file"); if let Some(existing) = &replaced { @@ -1895,11 +1904,10 @@ fn replace_plain_object(path: &Path, bytes: &[u8]) -> Result {} Err(err) => return Err(err.into()), } - } - file.write_all(bytes)?; - if let Some(existing) = &replaced { + // Apply restrictive/existing permissions before writing payload bytes. file.set_permissions(existing.permissions())?; } + file.write_all(bytes)?; // Persist the data before it gets its public name, so that a crash // cannot leave the name on a file that is not all there. file.sync_all()?; @@ -2020,19 +2028,14 @@ async fn sync_ancestors_of_published_object( .await? } +fn is_legacy_metadata_temp(path: &Path) -> bool { + path.file_name() + .and_then(|name| name.to_str()) + .is_some_and(|name| name.starts_with(".metadata-") && name.ends_with(".tmp")) +} + fn sync_upload_parent_directory(directory: &Path) -> Result<(), ObjectStorageError> { - match sync_directory(directory) { - Ok(()) => Ok(()), - Err(ObjectStorageError::IoError(err)) - if matches!( - err.kind(), - std::io::ErrorKind::InvalidInput | std::io::ErrorKind::Unsupported - ) => - { - Ok(()) - } - Err(err) => Err(err), - } + sync_directory(directory) } impl From for ObjectStorageError { diff --git a/src/storage/object_storage.rs b/src/storage/object_storage.rs index 4582a2ee8..20b6afa0d 100644 --- a/src/storage/object_storage.rs +++ b/src/storage/object_storage.rs @@ -748,7 +748,7 @@ async fn validate_uploaded_parquet_file( "Failed to get metadata for uploaded file in stream {}: {e}", stream_name ); - Ok(false) + Err(e) } } } @@ -4420,10 +4420,22 @@ mod metadata_key_decode_tests { } }; assert!(validate(key, 5).await); - // A short upload, one that grew, and one that is not there at all. + // A short upload or one that grew fails validation with Ok(false). assert!(!validate(key, 6).await); assert!(!validate(key, 4).await); - assert!(!validate("logs/date=2026-01-01/hour=00/minute=00/missing.parquet", 5).await); + // A missing object or transient HEAD error propagates Err so callers + // retain staging and retry rather than deleting a potentially valid key. + assert!( + validate_uploaded_parquet_file( + &store, + "logs/date=2026-01-01/hour=00/minute=00/missing.parquet", + 5, + "logs", + &None, + ) + .await + .is_err() + ); } #[test] diff --git a/src/utils/arrow/mod.rs b/src/utils/arrow/mod.rs index 6c6642a43..eb1a0e115 100644 --- a/src/utils/arrow/mod.rs +++ b/src/utils/arrow/mod.rs @@ -179,7 +179,11 @@ pub fn add_parseable_fields( /// growth and can leave up to twice the bytes the column holds allocated. /// Every request with a custom field builds one such column per field. fn repeated_utf8(value: &str, rows: usize) -> Result { - // The offsets of a `Utf8` column are 32 bits wide. + // The offsets of a `Utf8` column are 32 bits wide; guard both the data + // buffer length and the `(rows + 1) * 4` offsets buffer allocation. + rows.checked_add(1) + .and_then(|n| n.checked_mul(std::mem::size_of::())) + .ok_or_else(|| ArrowError::OffsetOverflowError(rows))?; let bytes = rows .checked_mul(value.len()) .filter(|bytes| i32::try_from(*bytes).is_ok()) From 13a10ad590dbe1ac7dd584e185b91265ae2b7255 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Tue, 1 Dec 2026 15:40:42 -0600 Subject: [PATCH 08/17] Fix minor import paths and field accessor after review integration --- src/metastore/metadata_cache.rs | 4 ++-- src/metastore/metastores/document_metastore.rs | 2 ++ src/parseable/staging/writer.rs | 2 +- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/metastore/metadata_cache.rs b/src/metastore/metadata_cache.rs index 82a86e554..f4ac6e848 100644 --- a/src/metastore/metadata_cache.rs +++ b/src/metastore/metadata_cache.rs @@ -154,10 +154,10 @@ impl CacheWeight for ObjectStoreFormat { .map(String::capacity) .sum::(); let tags_bytes = - self.dataset_tags.capacity() * std::mem::size_of::(); + self.dataset_tags.capacity() * std::mem::size_of::(); std::mem::size_of::() - + manifests.capacity() * std::mem::size_of::() + + manifests.capacity() * std::mem::size_of::() + manifests .iter() .map(|item| item.manifest_path.capacity()) diff --git a/src/metastore/metastores/document_metastore.rs b/src/metastore/metastores/document_metastore.rs index 5fd3336eb..a33e2de16 100644 --- a/src/metastore/metastores/document_metastore.rs +++ b/src/metastore/metastores/document_metastore.rs @@ -54,9 +54,11 @@ use arrow_schema::Schema; use bytes::Bytes; use chrono::{DateTime, Utc}; use dashmap::DashMap; +#[allow(unused_imports)] use futures::{StreamExt, TryStreamExt}; use relative_path::{RelativePath, RelativePathBuf}; use tonic::async_trait; +#[allow(unused_imports)] use tracing::{info, warn}; use ulid::Ulid; diff --git a/src/parseable/staging/writer.rs b/src/parseable/staging/writer.rs index 68c2c60cd..cbe47dac3 100644 --- a/src/parseable/staging/writer.rs +++ b/src/parseable/staging/writer.rs @@ -821,7 +821,7 @@ impl Writer { .append(rb, preencoded) .and_then(|()| if flush { writer.flush_staged() } else { Ok(()) }); if let Err(err) = result { - let orphan = (writer.acknowledged() == 0).then(|| writer.path().to_path_buf()); + let orphan = (writer.acknowledged_len() == 0).then(|| writer.path().to_path_buf()); writer.retire_failed(); drop(writer); if let Some(path) = orphan { From 46c6fe750191bc5f050ded5679afbcac75274d17 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Tue, 1 Dec 2026 15:42:38 -0600 Subject: [PATCH 09/17] Box Job in push_queue Waiter::Async to satisfy clippy::large_enum_variant --- src/parseable/streams/push_queue.rs | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/parseable/streams/push_queue.rs b/src/parseable/streams/push_queue.rs index a5c43b9e7..930eaacef 100644 --- a/src/parseable/streams/push_queue.rs +++ b/src/parseable/streams/push_queue.rs @@ -58,7 +58,7 @@ enum Waiter { Blocking(u64), /// The job of a task awaiting `Stream::push_async`, admitted by /// `PushQueue::advance`. - Async(u64, Job), + Async(u64, Box), } impl State { @@ -98,7 +98,7 @@ impl State { return; } if let Some(Waiter::Async(_, job)) = self.line.pop_front() { - self.enqueue(job); + self.enqueue(*job); } } } @@ -518,7 +518,7 @@ impl Stream { // The job waits in line on its own. Leaders, flushes and // other callers move it on; this task only awaits the answer. let id = state.next_waiter(); - state.line.push_back(Waiter::Async(id, job)); + state.line.push_back(Waiter::Async(id, Box::new(job))); Some(Parked { queue, id }) } }; @@ -770,13 +770,15 @@ mod tests { ..Default::default() }; let first = state.next_waiter(); - state.line.push_back(Waiter::Async(first, job(1))); + state.line.push_back(Waiter::Async(first, Box::new(job(1)))); let second = state.next_waiter(); - state.line.push_back(Waiter::Async(second, job(MAX_BYTES))); + state + .line + .push_back(Waiter::Async(second, Box::new(job(MAX_BYTES)))); let blocked = state.next_waiter(); state.line.push_back(Waiter::Blocking(blocked)); let last = state.next_waiter(); - state.line.push_back(Waiter::Async(last, job(1))); + state.line.push_back(Waiter::Async(last, Box::new(job(1)))); // The second job does not fit behind the first: nobody overtakes it. state.advance(); From ee7b9dbb0fa7f6ab869eb13524b438e05c971fe4 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Tue, 1 Dec 2026 16:00:40 -0600 Subject: [PATCH 10/17] Fix MemWriter import path in crash recovery test --- src/parseable/streams/crash_recovery_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/parseable/streams/crash_recovery_tests.rs b/src/parseable/streams/crash_recovery_tests.rs index 88f781ffc..68a19ed34 100644 --- a/src/parseable/streams/crash_recovery_tests.rs +++ b/src/parseable/streams/crash_recovery_tests.rs @@ -2203,7 +2203,7 @@ fn failed_part_sync_removes_unjournaled_part_and_retries_sources() { #[test] fn zstd_parquet_and_compressed_staging_zero_memory_recovers_every_boundary() { - use crate::parseable::staging::{MemWriter, StagingMemoryBudget}; + use crate::parseable::staging::{StagingMemoryBudget, writer::MemWriter}; for boundary in [ Boundary::PartSynced, From 0d3296919bdc226dac2b887f8a235640523ba812 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Tue, 1 Dec 2026 16:07:53 -0600 Subject: [PATCH 11/17] Remove redundant Arc::new around StagingMemoryBudget::new in crash recovery test --- src/parseable/streams/crash_recovery_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/parseable/streams/crash_recovery_tests.rs b/src/parseable/streams/crash_recovery_tests.rs index 68a19ed34..bd0c547dc 100644 --- a/src/parseable/streams/crash_recovery_tests.rs +++ b/src/parseable/streams/crash_recovery_tests.rs @@ -2221,7 +2221,7 @@ fn zstd_parquet_and_compressed_staging_zero_memory_recovers_every_boundary() { let stream = fresh(options.clone()); // Force disk-only staging (0-byte memory budget) with batches above the // IPC compression threshold (>= 100 rows) and Zstd Parquet output. - let budget = Arc::new(StagingMemoryBudget::new(0)); + let budget = StagingMemoryBudget::new(0); stream.writer.lock().unwrap().mem = Some(MemWriter::with_budget(budget)); stream.stage_schema_file(schema(false)).unwrap(); From d1e6936c445261b5b873eb194de35384c1ffd6fd Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Tue, 1 Dec 2026 16:20:11 -0600 Subject: [PATCH 12/17] Fix clustered vs unclustered inline stats budget and align unit tests --- src/hottier.rs | 2 + src/parseable/streams.rs | 59 ++++++++++++++----- src/parseable/streams/crash_recovery_tests.rs | 22 ++++--- src/parseable/streams/log_clustering.rs | 2 +- src/parseable/streams/push_queue.rs | 5 +- 5 files changed, 65 insertions(+), 25 deletions(-) diff --git a/src/hottier.rs b/src/hottier.rs index 0876780a6..b7839a84b 100644 --- a/src/hottier.rs +++ b/src/hottier.rs @@ -2362,6 +2362,8 @@ mod tests { .is_err() ); assert!(state.runtime.lock().await.dirty); + assert!(!root.join("logs").exists()); + tokio::fs::create_dir_all(root.join("logs")).await.unwrap(); tokio::fs::write( root.join("logs").join(super::STREAM_HOT_TIER_FILENAME), serde_json::to_vec(&super::StreamHotTier::default()).unwrap(), diff --git a/src/parseable/streams.rs b/src/parseable/streams.rs index 4389c6200..fb71a9820 100644 --- a/src/parseable/streams.rs +++ b/src/parseable/streams.rs @@ -815,11 +815,12 @@ struct LogRowGroupSource { /// batches missing many columns budget their post-adaptation footprint. merged_row_bytes: usize, stats: Option, - /// When set, `stats` is dropped as soon as it exceeds this inline budget - /// (see `FieldStatsAccumulator::exceeds_inline_budget`), releasing its - /// tracked values; the file's statistics are then computed after the - /// write from the file itself. - inline_stats_max_bytes: Option, + /// When set, `stats` is dropped as soon as it exceeds `(max_bytes, drop_on_approximate)`, + /// releasing its tracked values; the file's statistics are then computed after + /// the write from the file itself. Clustered conversion sets `drop_on_approximate = true` + /// because row-order changes affect approximate counts; unclustered conversion + /// feeds exact file order and only drops when retained bytes exceed `max_bytes`. + inline_stats_budget: Option<(usize, bool)>, /// Whether row groups report the bytes their rows retain. measure_retained_bytes: bool, exhausted: bool, @@ -842,7 +843,7 @@ impl)>> LogRowGroupSo merged_columns: 0, merged_row_bytes: 0, stats, - inline_stats_max_bytes: None, + inline_stats_budget: None, measure_retained_bytes: false, exhausted: false, } @@ -855,10 +856,10 @@ impl)>> LogRowGroupSo self } - /// Drops the statistics once they exceed `max_bytes` or become - /// approximate, see [`Self::inline_stats_max_bytes`]. - fn with_inline_stats_budget(mut self, max_bytes: usize) -> Self { - self.inline_stats_max_bytes = Some(max_bytes); + /// Drops the statistics once they exceed `max_bytes` (and, when + /// `drop_on_approximate` is true, once they become approximate). + fn with_inline_stats_budget(mut self, max_bytes: usize, drop_on_approximate: bool) -> Self { + self.inline_stats_budget = Some((max_bytes, drop_on_approximate)); self } @@ -974,8 +975,14 @@ impl)>> LogRowGroupSo for batch in &newly_finished { stats.update(batch); if self - .inline_stats_max_bytes - .is_some_and(|max_bytes| stats.retained_bytes() > max_bytes) + .inline_stats_budget + .is_some_and(|(max_bytes, drop_on_approximate)| { + if drop_on_approximate { + stats.exceeds_inline_budget(max_bytes) + } else { + stats.retained_bytes() > max_bytes + } + }) { self.stats = None; break; @@ -4402,7 +4409,7 @@ impl Stream { } let mut source = LogRowGroupSource::new(batches, finisher, max_rows, max_bytes, stats) .with_merged_schema(merged_columns, merged_row_bytes) - .with_inline_stats_budget(MAX_INLINE_FIELD_STATS_BYTES); + .with_inline_stats_budget(MAX_INLINE_FIELD_STATS_BYTES, false); let mut timings = LogParquetPhaseTimings::default(); let prepare = |source: &mut LogRowGroupSource<_>, timings: &mut LogParquetPhaseTimings| { @@ -6870,7 +6877,15 @@ mod log_parquet_pipeline_tests { let dir = TempDir::new().unwrap(); let files = stage_arrow_files(&dir, 1, 2, 600); let schema = Arc::new(reader(&files).merged_schema().unwrap()); - // Exercise both the parallel pipeline and the wide-row sequential fallback. + let expected = crate::storage::field_stats::compute_field_stats_from_batches( + &merged_batches(&files, &schema), + "deferred-stats", + &schema, + 5, + ); + // Unclustered conversion feeds rows in exact file order, so >1024 + // distinct values that stay under MAX_INLINE_FIELD_STATS_BYTES keep + // their inline stats instead of triggering a full Parquet reread. for row_group_size in [256, 100_000_000] { let staging = log_stream( &dir, @@ -6891,9 +6906,23 @@ mod log_parquet_pipeline_tests { .write_parquet_part_file(&path, reader(&files), &schema, &props, None, None) .unwrap() .unwrap(); - assert!(artifacts.field_stats.is_none()); + let (max_stats, stats) = artifacts.field_stats.expect("inline stats retained"); + assert_eq!(max_stats, 5); + assert_eq!(stats, expected); assert_eq!(read_parquet(&path).num_rows(), 1200); } + + // Dropping still triggers when retained heap exceeds the byte budget. + let (batches, finisher) = reader(&files).into_log_batches(schema.clone(), None); + let stats = Some(crate::storage::field_stats::FieldStatsAccumulator::new( + "deferred-stats", + &schema, + 5, + )); + let mut source = LogRowGroupSource::new(batches, finisher, 256, None, stats) + .with_inline_stats_budget(1, false); + while !source.next_row_groups(1).unwrap().is_empty() {} + assert!(source.stats.is_none()); } #[test] diff --git a/src/parseable/streams/crash_recovery_tests.rs b/src/parseable/streams/crash_recovery_tests.rs index bd0c547dc..2398e88a7 100644 --- a/src/parseable/streams/crash_recovery_tests.rs +++ b/src/parseable/streams/crash_recovery_tests.rs @@ -2265,13 +2265,19 @@ fn zstd_parquet_and_compressed_staging_zero_memory_recovers_every_boundary() { drop(stream); // Fresh Stream restart recovers and converges cleanly over two cycles. - let restarted = fresh(options); - restarted.prepare_parquet(true, false, &None).unwrap(); - restarted.prepare_parquet(true, false, &None).unwrap(); - let (staged_after, mut parquet_after) = capture_pairs(&restarted); - parquet_after.sort(); - assert!(staged_after.is_empty(), "boundary={boundary:?}"); - assert_eq!(parquet_after, expected, "boundary={boundary:?}"); - assert_clean_residue(&restarted); + for _ in 0..2 { + let restarted = fresh(options.clone()); + restarted + .prepare_startup_sync(None) + .unwrap() + .execute() + .unwrap(); + restarted.prepare_parquet(false, true, &None).unwrap(); + let (staged_after, mut parquet_after) = capture_pairs(&restarted); + parquet_after.sort(); + assert!(staged_after.is_empty(), "boundary={boundary:?}"); + assert_eq!(parquet_after, expected, "boundary={boundary:?}"); + assert_clean_residue(&restarted); + } } } diff --git a/src/parseable/streams/log_clustering.rs b/src/parseable/streams/log_clustering.rs index 430b68b2b..35bd08e2a 100644 --- a/src/parseable/streams/log_clustering.rs +++ b/src/parseable/streams/log_clustering.rs @@ -707,7 +707,7 @@ pub(super) fn write_clustered_log_parquet_on_pool_with_limits( stats, ) .with_merged_schema(merged_columns, merged_row_bytes) - .with_inline_stats_budget(limits.inline_stats_max_bytes) + .with_inline_stats_budget(limits.inline_stats_max_bytes, true) .measuring_retained_bytes(); let mut write_stats = LogClusterWriteStats { columns_per_task: encoder.columns_per_task, diff --git a/src/parseable/streams/push_queue.rs b/src/parseable/streams/push_queue.rs index 930eaacef..4ec11c8bd 100644 --- a/src/parseable/streams/push_queue.rs +++ b/src/parseable/streams/push_queue.rs @@ -1375,8 +1375,10 @@ mod tests { assert_eq!(budget.used(), 0); assert_eq!(frees(), [true, true]); - // Eviction under memory pressure. + // Eviction under memory pressure: roll over the spilled segment first + // since spill is sticky per segment until flush. budget.set_limit(1 << 30); + stream.flush(true).unwrap(); pushed(probed(2000..3000)); assert!(budget.used() > 0); assert!(stream.evict_staging_memory() > 0); @@ -1384,6 +1386,7 @@ mod tests { assert_eq!(frees(), [true; 3]); // Rollover: the flush detaches the segment under both locks. + stream.flush(true).unwrap(); pushed(probed(3000..4000)); assert!(budget.used() > 0); stream.flush(true).unwrap(); From b2615bf29e2816df48f2561c9c47264e680fbaf0 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Tue, 1 Dec 2026 17:04:34 -0600 Subject: [PATCH 13/17] Eliminate sparse pread syscall tax on wide staging scans and expose certified p_timestamp bounds to ProgressiveTopK --- src/parseable/staging/disk_source.rs | 23 +- src/parseable/staging/reader.rs | 14 +- src/query/ordered_topk.rs | 38 +++- src/query/stream_schema_provider.rs | 321 +++++++++++++++++++++++---- 4 files changed, 344 insertions(+), 52 deletions(-) diff --git a/src/parseable/staging/disk_source.rs b/src/parseable/staging/disk_source.rs index e5ca7fa40..a3f6426b2 100644 --- a/src/parseable/staging/disk_source.rs +++ b/src/parseable/staging/disk_source.rs @@ -320,7 +320,8 @@ impl StagingDiskSource { /// and complete IPC message index for parallel range reads, column /// projection pushdown, and zero-body-read row counting. pub(crate) fn plan_prefix(&self) -> Result { - self.plan_indexed_or_scan(None, false).map(|(plan, _)| plan) + self.plan_indexed_or_scan(None, false) + .map(|(plan, _, _)| plan) } /// Prune against an exact `[start_ms, end_ms)` predicate on `p_timestamp`. @@ -334,17 +335,31 @@ impl StagingDiskSource { fold_counts: bool, ) -> Result<(ValidatedPrefixPlan, u64), StagingError> { self.plan_indexed_or_scan(Some(start_ms..end_ms), fold_counts) + .map(|(plan, folded, _)| (plan, folded)) + } + + /// Plans the prefix with optional time-range pruning/count folding and + /// returns certified per-message `p_timestamp` bounds when the source carries + /// an in-memory IPC index (so `ProgressiveTopKExec` can prune older slices + /// of large disk-backed staging files unopened). + pub(crate) fn plan_prefix_with_bounds( + &self, + time: Option<(i64, i64)>, + fold_counts: bool, + ) -> Result<(ValidatedPrefixPlan, u64, Option>), StagingError> { + self.plan_indexed_or_scan(time.map(|(s, e)| s..e), fold_counts) } fn plan_indexed_or_scan( &self, time: Option>, fold_counts: bool, - ) -> Result<(ValidatedPrefixPlan, u64), StagingError> { + ) -> Result<(ValidatedPrefixPlan, u64, Option>), StagingError> { if let Some(snap) = &self.index { let entries = snap.index.batches.lock(); let batches = &entries[snap.first..snap.past]; let mut messages = Vec::with_capacity(batches.len()); + let mut bounds = Vec::with_capacity(batches.len()); let mut folded = 0u64; for batch in batches { if let (Some(time), TimestampBounds::NonNull { min, max }) = @@ -371,6 +386,7 @@ impl StagingDiskSource { size: batch.length as usize, rows: Some(batch.num_rows as usize), }); + bounds.push(batch.timestamp); } return Ok(( ValidatedPrefixPlan { @@ -380,6 +396,7 @@ impl StagingDiskSource { has_dictionaries: false, }, folded, + Some(bounds), )); } self.validate_file_len()?; @@ -388,7 +405,7 @@ impl StagingDiskSource { self.start, self.len, ) - .map(|plan| (plan, 0)) + .map(|plan| (plan, 0, None)) .map_err(|err| { StagingError::ObjectStorage(io::Error::new( err.kind(), diff --git a/src/parseable/staging/reader.rs b/src/parseable/staging/reader.rs index 6020c5460..bc9a32d1a 100644 --- a/src/parseable/staging/reader.rs +++ b/src/parseable/staging/reader.rs @@ -778,9 +778,9 @@ fn ipc_decode_error(err: ArrowError) -> ArrowError { } } -/// Below this IPC message size, reading the whole message in a single read and -/// projecting in memory beats issuing multiple sparse seeks and reads. -const SPARSE_PROJECTION_MIN_MESSAGE_BYTES: usize = 64 * 1024; +/// Below this IPC message size, reading the whole message in a single buffered +/// read and projecting in memory beats issuing multiple sparse seeks and reads. +const SPARSE_PROJECTION_MIN_MESSAGE_BYTES: usize = 256 * 1024; /// Framing and layout are validated against the original message before /// reading body buffers. Nested schemas keep the full body for both phases. @@ -984,7 +984,8 @@ impl RangeBatchReader { parse_schema_message(&read_exact_range(&mut reader, offset, size)?)? } }; - if columns.len() < schema.fields().len() + if columns.len().saturating_mul(2) <= schema.fields().len() + && columns.len() < schema.fields().len() && columns.windows(2).all(|pair| pair[0] < pair[1]) && columns.last().is_none_or(|&i| i < schema.fields().len()) && let Some(layout) = flat_buffer_layout(&schema) @@ -1649,7 +1650,10 @@ where &self.file_schema, size >= SPARSE_PROJECTION_MIN_MESSAGE_BYTES && self.flat_layout.is_some() - && self.filter_indices.len() < self.file_schema.fields().len(), + && self.filter_indices.len() < self.file_schema.fields().len() + && (self.output_indices.len().saturating_mul(2) + <= self.file_schema.fields().len() + || self.stats.batches_skipped_zero_matches > 0), None, ) .map_err(TwoPhaseReadError::from_decode)?; diff --git a/src/query/ordered_topk.rs b/src/query/ordered_topk.rs index aa39a2cc8..20481ebaa 100644 --- a/src/query/ordered_topk.rs +++ b/src/query/ordered_topk.rs @@ -104,6 +104,9 @@ use datafusion::physical_plan::{ }; use futures::{StreamExt, TryStreamExt}; +use crate::event::DEFAULT_TIMESTAMP_KEY; +use crate::query::stream_schema_provider::StagingDiskScanExec; + /// Largest `fetch` (LIMIT + OFFSET) the progressive TopK handles. It holds at /// most `fetch` rows plus one in-flight batch per running unit. Above 1,000 rows, /// stock parallel `SortExec` outperforms sequential progressive waves. @@ -384,7 +387,7 @@ fn trace_primary(source: &Arc, mut index: usize) -> Option() { + if node.is::() || node.is::() { return Some(Traced { path, leaf_index: index, @@ -569,6 +572,39 @@ fn analyze_source( return Ok(unbounded()); }; let leaf = traced.path.last().expect("path ends at the scan"); + if let Some(staging_exec) = leaf.downcast_ref::() { + let output_schema = leaf.schema(); + let Some(output_field) = output_schema.fields().get(traced.leaf_index) else { + return Ok(unbounded()); + }; + if output_field.name() != DEFAULT_TIMESTAMP_KEY { + return Ok(unbounded()); + } + let DataType::Timestamp(datafusion::arrow::datatypes::TimeUnit::Millisecond, tz) = + output_field.data_type() + else { + return Ok(unbounded()); + }; + let topk_units = staging_exec.topk_units(); + if topk_units.len() < 2 || !topk_units.iter().any(|(b, _)| b.is_some()) { + return Ok(unbounded()); + } + let mut units = Vec::with_capacity(topk_units.len()); + for (bounds, slice_plan) in topk_units { + let bound = bounds.map(|(min_ms, max_ms)| UnitBound { + value: ScalarValue::TimestampMillisecond( + Some(if key.descending { max_ms } else { min_ms }), + tz.clone(), + ), + no_nulls: true, + }); + units.push(Unit { + plan: rebuild_path(&traced.path, Arc::clone(slice_plan))?, + bound, + }); + } + return Ok(units); + } let exec = leaf .downcast_ref::() .expect("trace ends at DataSourceExec"); diff --git a/src/query/stream_schema_provider.rs b/src/query/stream_schema_provider.rs index 7d39b7031..3ced7e243 100644 --- a/src/query/stream_schema_provider.rs +++ b/src/query/stream_schema_provider.rs @@ -2153,6 +2153,185 @@ fn split_ipc_messages_by_bytes( chunks } +/// Leaf wrapper over a parallel `StreamingTable` staging-disk scan that also +/// exposes chronologically sliced, `p_timestamp`-bounded single-partition plans +/// to `ProgressiveTopKRule`. Non-TopK queries execute `inner` directly with zero +/// overhead; `ORDER BY p_timestamp DESC/ASC LIMIT N` splits into bounded slices +/// so the newest slice fills the TopK threshold and prunes older slices unopened. +#[derive(Debug)] +pub(crate) struct StagingDiskScanExec { + inner: Arc, + topk_units: Vec<(Option<(i64, i64)>, Arc)>, +} + +impl StagingDiskScanExec { + pub(crate) fn topk_units(&self) -> &[(Option<(i64, i64)>, Arc)] { + &self.topk_units + } +} + +impl DisplayAs for StagingDiskScanExec { + fn fmt_as(&self, _t: DisplayFormatType, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "StagingDiskScanExec: topk_units={}", + self.topk_units.len() + ) + } +} + +impl ExecutionPlan for StagingDiskScanExec { + fn name(&self) -> &str { + "StagingDiskScanExec" + } + + fn properties(&self) -> &Arc { + self.inner.properties() + } + + fn children(&self) -> Vec<&Arc> { + vec![] + } + + fn apply_expressions( + &self, + _f: &mut dyn FnMut( + &Arc, + ) -> DataFusionResult, + ) -> DataFusionResult { + Ok(TreeNodeRecursion::Continue) + } + + fn with_new_children( + self: Arc, + children: Vec>, + ) -> DataFusionResult> { + if !children.is_empty() { + return Err(DataFusionError::Internal( + "StagingDiskScanExec does not accept children".to_string(), + )); + } + Ok(self) + } + + fn execute( + &self, + partition: usize, + context: Arc, + ) -> DataFusionResult { + self.inner.execute(partition, context) + } + + fn partition_statistics(&self, partition: Option) -> DataFusionResult> { + self.inner.partition_statistics(partition) + } +} + +#[derive(Debug)] +struct BoundedStagingTable { + inner: StreamingTable, + slices: Vec<(Option<(i64, i64)>, StreamingTable)>, +} + +#[async_trait::async_trait] +impl TableProvider for BoundedStagingTable { + fn as_any(&self) -> &dyn Any { + self + } + + fn schema(&self) -> SchemaRef { + self.inner.schema() + } + + fn table_type(&self) -> TableType { + TableType::Base + } + + async fn scan( + &self, + state: &dyn Session, + projection: Option<&Vec>, + filters: &[Expr], + limit: Option, + ) -> DataFusionResult> { + let inner = self.inner.scan(state, projection, filters, limit).await?; + if limit.is_some() || self.slices.len() < 2 || !self.slices.iter().any(|(b, _)| b.is_some()) + { + return Ok(inner); + } + let mut topk_units = Vec::with_capacity(self.slices.len()); + for (bounds, slice_table) in &self.slices { + let plan = slice_table.scan(state, projection, filters, None).await?; + topk_units.push((*bounds, plan)); + } + Ok(Arc::new(StagingDiskScanExec { inner, topk_units })) + } +} + +/// Groups newest-first indexed IPC messages into contiguous chronological slices +/// (starting with small newest slices so `ORDER BY p_timestamp DESC LIMIT N` +/// satisfies the limit in milliseconds) and computes certified `(min_ms, max_ms)` +/// bounds for each slice whose batches are all `TimestampBounds::NonNull`. +fn slice_indexed_messages_for_topk( + messages: &[crate::parseable::staging::reader::ValidatedIpcMessage], + bounds: &[crate::parseable::staging::TimestampBounds], +) -> Vec<(Option<(i64, i64)>, Vec<(u64, usize)>)> { + use crate::parseable::staging::TimestampBounds; + + let n = messages.len(); + if n == 0 || n != bounds.len() { + return Vec::new(); + } + let mut slices = Vec::new(); + let mut cursor = 0usize; + let initial_sizes = [16usize, 32, 64, 128]; + for &step in &initial_sizes { + if cursor >= n { + break; + } + let end = (cursor + step).min(n); + slices.push(cursor..end); + cursor = end; + } + if cursor < n { + let remaining = n - cursor; + let tail_chunks = 12usize.min(remaining); + let base = remaining / tail_chunks; + let extra = remaining % tail_chunks; + for i in 0..tail_chunks { + let len = base + usize::from(i < extra); + if len > 0 { + slices.push(cursor..cursor + len); + cursor += len; + } + } + } + + let mut out = Vec::with_capacity(slices.len()); + for range in slices { + let mut min_ms = i64::MAX; + let mut max_ms = i64::MIN; + let mut all_non_null = true; + let mut chunk = Vec::with_capacity(range.len()); + for idx in range { + let msg = &messages[idx]; + chunk.push((msg.offset, msg.size)); + match bounds[idx] { + TimestampBounds::NonNull { min, max } => { + min_ms = min_ms.min(min); + max_ms = max_ms.max(max); + } + TimestampBounds::HasNulls | TimestampBounds::Unknown => { + all_non_null = false; + } + } + } + let certified = (all_non_null && min_ms <= max_ms).then_some((min_ms, max_ms)); + out.push((certified, chunk)); + } + out +} + /// Extracts an inclusive-start, exclusive-end millisecond range `[start_ms, end_ms)` /// on `p_timestamp` from DataFusion filter expressions for indexed staging-batch /// pruning and (when `all_exact_time_only` is true) zero-decode `COUNT(*)` folding. @@ -2328,35 +2507,26 @@ async fn staging_disk_plan( let table_schema_for_plan = schema.clone(); let projected_for_plan = projected_schema.clone(); let filter_schema_for_plan = two_phase_filter.as_ref().map(|f| f.filter_schema.clone()); - let (work_units, folded_units) = tokio::task::spawn_blocking(move || { + let (work_units, folded_units, topk_work_slices) = tokio::task::spawn_blocking(move || { let mut units = Vec::with_capacity(sources.len()); let mut folded_units = Vec::new(); + let mut topk_slices: Vec<(Option<(i64, i64)>, StagingDiskWork)> = Vec::new(); + let time_bounds = time_range.map(|(s, e, _)| (s, e)); for source in sources { if cancel_flag.load(std::sync::atomic::Ordering::Relaxed) { break; } - let (plan, folded_rows) = match time_range { - Some((start_ms, end_ms, _)) => { - match source.plan_prefix_for_time_range(start_ms, end_ms, can_fold_counts) { - Ok(res) => res, - Err(err) => { - units.push(StagingDiskWork::Failed(format!( - "Cannot read staging rows: {err}" - ))); - continue; - } - } - } - None => match source.plan_prefix() { - Ok(plan) => (plan, 0), + let (plan, folded_rows, batch_bounds) = + match source.plan_prefix_with_bounds(time_bounds, can_fold_counts) { + Ok(res) => res, Err(err) => { - units.push(StagingDiskWork::Failed(format!( - "Cannot read staging rows: {err}" - ))); + let failed = + StagingDiskWork::Failed(format!("Cannot read staging rows: {err}")); + units.push(failed.clone()); + topk_slices.push((None, failed)); continue; } - }, - }; + }; let has_messages = plan.messages.iter().any(|m| m.rows.is_some()); if !has_messages && folded_rows == 0 { continue; @@ -2369,7 +2539,9 @@ async fn staging_disk_plan( has_rows, source.path(), ) { - units.push(StagingDiskWork::Failed(err)); + let failed = StagingDiskWork::Failed(err); + units.push(failed.clone()); + topk_slices.push((None, failed)); continue; } if folded_rows > 0 { @@ -2385,10 +2557,16 @@ async fn staging_disk_plan( IpcProjection::Empty => { match checked_total_rows(&plan.messages, source.path()) { Ok(total_rows) if total_rows > 0 => { - units.push(StagingDiskWork::RowCounts { source, total_rows }); + let rc = StagingDiskWork::RowCounts { source, total_rows }; + units.push(rc.clone()); + topk_slices.push((None, rc)); } Ok(_) => {} - Err(err) => units.push(StagingDiskWork::Failed(err)), + Err(err) => { + let failed = StagingDiskWork::Failed(err); + units.push(failed.clone()); + topk_slices.push((None, failed)); + } } continue; } @@ -2405,45 +2583,65 @@ async fn staging_disk_plan( }; let mut messages = plan.messages; + let mut batch_bounds = batch_bounds; // Dictionary-encoded streams keep forward IPC order so dictionary // definitions precede the batches referencing them. if !plan.has_dictionaries { messages.reverse(); + if let Some(bounds) = batch_bounds.as_mut() { + bounds.reverse(); + } } - let total_bytes: usize = messages.iter().map(|m| m.size).sum(); - let splits = if max_partitions <= 1 - || plan.has_dictionaries - || messages.len() <= 1 - || total_bytes < STAGING_DISK_MIN_SPLIT_BYTES - { - 1 - } else { - max_partitions.min(messages.len()) - }; - for chunk in split_ipc_messages_by_bytes(&messages, splits) { + + let make_work = |chunk: Vec<(u64, usize)>| { let byte_weight: usize = chunk.iter().map(|(_, size)| *size).sum(); let mut ranges = Vec::with_capacity(chunk.len() + 1); ranges.push(plan.schema_range); ranges.extend(chunk); if let Some((filter_indices, output_indices)) = two_phase_cols.as_ref() { - units.push(StagingDiskWork::TwoPhaseRanges { + StagingDiskWork::TwoPhaseRanges { source: source.clone(), ranges: Arc::from(ranges), filter_indices: filter_indices.clone(), output_indices: output_indices.clone(), byte_weight, - }); + } } else { - units.push(StagingDiskWork::Ranges { + StagingDiskWork::Ranges { source: source.clone(), ranges: Arc::from(ranges), ipc_projection: ipc_projection.clone(), byte_weight, - }); + } } + }; + + if let Some(bounds) = batch_bounds.as_deref() + && !plan.has_dictionaries + { + for (certified, chunk) in slice_indexed_messages_for_topk(&messages, bounds) { + topk_slices.push((certified, make_work(chunk))); + } + } else { + let all_ranges = messages.iter().map(|m| (m.offset, m.size)).collect(); + topk_slices.push((None, make_work(all_ranges))); + } + + let total_bytes: usize = messages.iter().map(|m| m.size).sum(); + let splits = if max_partitions <= 1 + || plan.has_dictionaries + || messages.len() <= 1 + || total_bytes < STAGING_DISK_MIN_SPLIT_BYTES + { + 1 + } else { + max_partitions.min(messages.len()) + }; + for chunk in split_ipc_messages_by_bytes(&messages, splits) { + units.push(make_work(chunk)); } } - (units, folded_units) + (units, folded_units, topk_slices) }) .await .map_err(|err| DataFusionError::Execution(format!("Staging disk planning failed: {err}")))?; @@ -2512,11 +2710,48 @@ async fn staging_disk_plan( }) as Arc }) .collect(); - let table = StreamingTable::try_new(projected_schema, partitions)?; - sub_plans.push( - scan_enforcing_exact_filters(&table, state, disk_projection.as_ref(), filters, limit) + let inner_table = StreamingTable::try_new(projected_schema.clone(), partitions)?; + if topk_work_slices.len() >= 2 && topk_work_slices.iter().any(|(b, _)| b.is_some()) { + let mut slices = Vec::with_capacity(topk_work_slices.len()); + for (bounds, work) in topk_work_slices { + let part = Arc::new(StagingDiskPartition { + table_schema: schema.clone(), + schema: projected_schema.clone(), + work: vec![work], + reverse_rows: false, + batch_size, + two_phase_filter: two_phase_filter.clone(), + time_range: None, + }) as Arc; + let slice_table = StreamingTable::try_new(projected_schema.clone(), vec![part])?; + slices.push((bounds, slice_table)); + } + let bounded_table = BoundedStagingTable { + inner: inner_table, + slices, + }; + sub_plans.push( + scan_enforcing_exact_filters( + &bounded_table, + state, + disk_projection.as_ref(), + filters, + limit, + ) .await?, - ); + ); + } else { + sub_plans.push( + scan_enforcing_exact_filters( + &inner_table, + state, + disk_projection.as_ref(), + filters, + limit, + ) + .await?, + ); + } } if sub_plans.len() == 1 { From d0f4f7120f51ffb4338509edc230173ac0968296 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Tue, 1 Dec 2026 18:36:19 -0600 Subject: [PATCH 14/17] Fix live & post-drain query regressions: certified staging/parquet TopK bounds, unit-local dynamic filter, interior time-filter stripping --- src/parseable/staging/disk_source.rs | 31 +- src/parseable/staging/reader.rs | 12 +- src/parseable/streams.rs | 23 +- src/query/ordered_topk.rs | 152 +++- src/query/stream_schema_provider.rs | 663 ++++++++++++------ .../stream_schema_provider/staging_parquet.rs | 156 ++++- 6 files changed, 786 insertions(+), 251 deletions(-) diff --git a/src/parseable/staging/disk_source.rs b/src/parseable/staging/disk_source.rs index a3f6426b2..c915dcd8c 100644 --- a/src/parseable/staging/disk_source.rs +++ b/src/parseable/staging/disk_source.rs @@ -328,31 +328,32 @@ impl StagingDiskSource { /// Set `fold_counts` only for a row count with no other residual predicate. /// Folded rows are excluded from the returned messages. All remaining /// messages still need the caller's ordinary predicate evaluation. + #[cfg(test)] pub(crate) fn plan_prefix_for_time_range( &self, start_ms: i64, end_ms: i64, fold_counts: bool, ) -> Result<(ValidatedPrefixPlan, u64), StagingError> { - self.plan_indexed_or_scan(Some(start_ms..end_ms), fold_counts) + self.plan_indexed_or_scan(Some((Some(start_ms), Some(end_ms))), fold_counts) .map(|(plan, folded, _)| (plan, folded)) } - /// Plans the prefix with optional time-range pruning/count folding and - /// returns certified per-message `p_timestamp` bounds when the source carries - /// an in-memory IPC index (so `ProgressiveTopKExec` can prune older slices - /// of large disk-backed staging files unopened). + /// Plans the prefix with optional half-open `[start_ms, end_ms)` time-range + /// pruning/count folding (`None` means unbounded on that side) and returns + /// certified per-message `p_timestamp` bounds when the source carries an + /// in-memory IPC index. pub(crate) fn plan_prefix_with_bounds( &self, - time: Option<(i64, i64)>, + time: Option<(Option, Option)>, fold_counts: bool, ) -> Result<(ValidatedPrefixPlan, u64, Option>), StagingError> { - self.plan_indexed_or_scan(time.map(|(s, e)| s..e), fold_counts) + self.plan_indexed_or_scan(time, fold_counts) } fn plan_indexed_or_scan( &self, - time: Option>, + time: Option<(Option, Option)>, fold_counts: bool, ) -> Result<(ValidatedPrefixPlan, u64, Option>), StagingError> { if let Some(snap) = &self.index { @@ -362,13 +363,19 @@ impl StagingDiskSource { let mut bounds = Vec::with_capacity(batches.len()); let mut folded = 0u64; for batch in batches { - if let (Some(time), TimestampBounds::NonNull { min, max }) = - (&time, batch.timestamp) + if let (Some((start_ms, end_ms)), TimestampBounds::NonNull { min, max }) = + (time, batch.timestamp) { - if max < time.start || min >= time.end || time.is_empty() { + let empty_range = matches!((start_ms, end_ms), (Some(s), Some(e)) if s >= e); + let outside = empty_range + || start_ms.is_some_and(|s| max < s) + || end_ms.is_some_and(|e| min >= e); + if outside { continue; } - if fold_counts && time.contains(&min) && time.contains(&max) { + let fully_inside = + start_ms.is_none_or(|s| min >= s) && end_ms.is_none_or(|e| max < e); + if fold_counts && fully_inside { folded = folded .checked_add(u64::from(batch.num_rows)) diff --git a/src/parseable/staging/reader.rs b/src/parseable/staging/reader.rs index bc9a32d1a..58aead669 100644 --- a/src/parseable/staging/reader.rs +++ b/src/parseable/staging/reader.rs @@ -778,9 +778,11 @@ fn ipc_decode_error(err: ArrowError) -> ArrowError { } } -/// Below this IPC message size, reading the whole message in a single buffered -/// read and projecting in memory beats issuing multiple sparse seeks and reads. -const SPARSE_PROJECTION_MIN_MESSAGE_BYTES: usize = 256 * 1024; +/// Narrow single-phase projections (`<= 50%` of columns) benefit from sparse +/// buffer reads above 64 KiB, whereas wide two-phase scans (`SELECT *`) use a +/// higher 256 KiB threshold to avoid per-column syscall overhead when batches match. +const NARROW_SPARSE_MIN_MESSAGE_BYTES: usize = 64 * 1024; +const WIDE_SPARSE_MIN_MESSAGE_BYTES: usize = 256 * 1024; /// Framing and layout are validated against the original message before /// reading body buffers. Nested schemas keep the full body for both phases. @@ -999,7 +1001,7 @@ impl RangeBatchReader { layout, projection: columns.clone(), file_len, - min_sparse_bytes: SPARSE_PROJECTION_MIN_MESSAGE_BYTES, + min_sparse_bytes: NARROW_SPARSE_MIN_MESSAGE_BYTES, }); } } @@ -1648,7 +1650,7 @@ where offset, size, &self.file_schema, - size >= SPARSE_PROJECTION_MIN_MESSAGE_BYTES + size >= WIDE_SPARSE_MIN_MESSAGE_BYTES && self.flat_layout.is_some() && self.filter_indices.len() < self.file_schema.fields().len() && (self.output_indices.len().saturating_mul(2) diff --git a/src/parseable/streams.rs b/src/parseable/streams.rs index fb71a9820..8d898ca12 100644 --- a/src/parseable/streams.rs +++ b/src/parseable/streams.rs @@ -4740,21 +4740,32 @@ impl Stream { /// The query calls this on its immutable lease, propagating access/metadata /// failures while retaining the uploader's corrupt/empty-file skip policy. pub(crate) fn validate_parquet_file(path: &Path, stream_name: &str) -> std::io::Result { + Ok(Self::validate_parquet_file_metadata(path, stream_name)?.is_some()) + } + + /// Validates a staged Parquet file and returns its parsed footer metadata + /// when non-empty, allowing callers to reuse certified column statistics + /// without reopening the file. + pub(crate) fn validate_parquet_file_metadata( + path: &Path, + stream_name: &str, + ) -> std::io::Result>> { let file = std::fs::File::open(path)?; let size = file.metadata()?.len(); if size < FOOTER_SIZE as u64 { error!( "Invalid parquet file {path:?} detected for stream {stream_name}, size: {size} bytes" ); - return Ok(false); + return Ok(None); } match SerializedFileReader::new(file) { Ok(reader) => { - let valid = reader.metadata().file_metadata().num_rows() != 0; - if !valid { + let metadata = reader.metadata(); + if metadata.file_metadata().num_rows() == 0 { error!("Invalid parquet file {path:?} for stream {stream_name}: no rows"); + return Ok(None); } - Ok(valid) + Ok(Some(Arc::new(metadata.clone()))) } Err(parquet::errors::ParquetError::External(error)) => { // Actual filesystem read errors are capture failures too. @@ -4764,13 +4775,13 @@ impl Stream { error!( "Failed to read parquet file {path:?} for stream {stream_name}: {error}" ); - Ok(false) + Ok(None) } } } Err(error) => { error!("Failed to read parquet file {path:?} for stream {stream_name}: {error}"); - Ok(false) + Ok(None) } } } diff --git a/src/query/ordered_topk.rs b/src/query/ordered_topk.rs index 20481ebaa..041f9ac6e 100644 --- a/src/query/ordered_topk.rs +++ b/src/query/ordered_topk.rs @@ -519,6 +519,23 @@ fn rebuild_path( Ok(plan) } +/// Rebuilds `path` over a single-partition staging slice, dropping any +/// intermediate `RepartitionExec`/`CoalescePartitionsExec` so each slice stays +/// single-partition and never consumes the whole concurrency budget. +fn rebuild_staging_path( + path: &[Arc], + leaf: Arc, +) -> Result> { + let mut plan = leaf; + for node in path.iter().rev().skip(1) { + if is_repartitioning(node) { + continue; + } + plan = replace_children_if_necessary(Arc::clone(node), vec![plan])?; + } + Ok(plan) +} + /// Size used to balance file pieces across groups. fn piece_size(file: &PartitionedFile) -> u64 { match &file.range { @@ -586,7 +603,7 @@ fn analyze_source( return Ok(unbounded()); }; let topk_units = staging_exec.topk_units(); - if topk_units.len() < 2 || !topk_units.iter().any(|(b, _)| b.is_some()) { + if topk_units.is_empty() || !topk_units.iter().any(|(b, _)| b.is_some()) { return Ok(unbounded()); } let mut units = Vec::with_capacity(topk_units.len()); @@ -599,7 +616,7 @@ fn analyze_source( no_nulls: true, }); units.push(Unit { - plan: rebuild_path(&traced.path, Arc::clone(slice_plan))?, + plan: rebuild_staging_path(&traced.path, Arc::clone(slice_plan))?, bound, }); } @@ -688,6 +705,14 @@ fn analyze_source( no_nulls: path_no_nulls || no_nulls, }) }; + if locations.len() == 1 + && let Some(bound) = file_bound(&locations[0].1) + { + return Ok(vec![Unit { + plan: Arc::clone(source), + bound: Some(bound), + }]); + } let split = locations.len() >= 2 && locations .iter() @@ -1111,20 +1136,44 @@ impl Drop for CompleteOnDrop { } } +/// Marks a unit-local dynamic filter complete however the unit ends. +struct MarkCompleteOnDrop(Option>); + +impl Drop for MarkCompleteOnDrop { + fn drop(&mut self) { + if let Some(filter) = &self.0 { + filter.mark_complete(); + } + } +} + /// Rebinds every copy of the template dynamic filter in `predicate` to the -/// execution's filter, keeping each copy's column remapping. +/// execution's filter (and, when supplied, conjoins a unit-local TopK filter so +/// each Parquet scan also prunes its own row groups from its local `SortExec`). fn rebind_predicate( predicate: &Arc, filter: &RunFilter, + unit_filter: Option<&Arc>, ) -> Result>> { let fresh: Arc = Arc::clone(&filter.filter) as Arc; + let unit_fresh: Option> = + unit_filter.map(|f| Arc::clone(f) as Arc); Arc::clone(predicate).transform_down(|node| { if node.downcast_ref::().is_some() && node.expression_id() == Some(filter.template_id) { - let children = node.children().into_iter().cloned().collect(); - let rebound = Arc::clone(&fresh).with_new_children(children)?; - Ok(Transformed::new(rebound, true, TreeNodeRecursion::Jump)) + let children: Vec> = + node.children().into_iter().cloned().collect(); + let rebound = Arc::clone(&fresh).with_new_children(children.clone())?; + let combined = match &unit_fresh { + Some(unit) => { + let unit_rebound = Arc::clone(unit).with_new_children(children)?; + Arc::new(BinaryExpr::new(rebound, Operator::And, unit_rebound)) + as Arc + } + None => rebound, + }; + Ok(Transformed::new(combined, true, TreeNodeRecursion::Jump)) } else { Ok(Transformed::no(node)) } @@ -1135,6 +1184,7 @@ fn rebind_predicate( fn rebind_scan( node: &Arc, filter: &RunFilter, + unit_filter: Option<&Arc>, ) -> Result>> { let Some(exec) = node.downcast_ref::() else { return Ok(None); @@ -1148,7 +1198,7 @@ fn rebind_scan( let Some(predicate) = config.file_source().filter() else { return Ok(None); }; - let rebound = rebind_predicate(&predicate, filter)?; + let rebound = rebind_predicate(&predicate, filter, unit_filter)?; if !rebound.transformed { return Ok(None); } @@ -1162,21 +1212,31 @@ fn rebind_scan( /// A fresh, executable copy of a unit's plan: per-execution node state (such /// as a scan's shared work queue) is reset, and the scans use this -/// execution's dynamic filter. +/// execution's dynamic filter (plus an optional unit-local TopK filter). +/// Returns `(prepared_plan, rebound_any_scan)`. fn prepare_unit( plan: &Arc, filter: Option<&RunFilter>, -) -> Result> { - Arc::clone(plan) + unit_filter: Option<&Arc>, +) -> Result<(Arc, bool)> { + let mut rebound_any = false; + let prepared = Arc::clone(plan) .transform_up(|node| { let node = node.reset_state()?; let node = match filter { - Some(filter) => rebind_scan(&node, filter)?.unwrap_or(node), + Some(filter) => match rebind_scan(&node, filter, unit_filter)? { + Some(rebound) => { + rebound_any = true; + rebound + } + None => node, + }, None => node, }; Ok(Transformed::yes(node)) - }) - .map(|transformed| transformed.data) + })? + .data; + Ok((prepared, rebound_any)) } /// At most `fetch` sorted rows, with their memory (and the merge buffers @@ -1352,13 +1412,22 @@ impl ProgressiveRun { index: usize| -> Result<()> { self.executed.add(1); - let plan = prepare_unit(&self.units[index].plan, self.filter.0.as_ref())?; + let unit_filter = self.filter.0.as_ref().map(|run| { + let children = run.filter.children().into_iter().cloned().collect(); + Arc::new(DynamicFilterPhysicalExpr::new(children, lit(true))) + }); + let (plan, rebound_any) = prepare_unit( + &self.units[index].plan, + self.filter.0.as_ref(), + unit_filter.as_ref(), + )?; let handle = tasks.spawn(run_unit( plan, self.expr.clone(), self.fetch, Arc::clone(&self.schema), Arc::clone(&context), + rebound_any.then_some(unit_filter).flatten(), )); running.insert(handle.id(), (index, handle)); Ok(()) @@ -1517,13 +1586,17 @@ async fn run_unit( fetch: usize, schema: SchemaRef, context: Arc, + unit_filter: Option>, ) -> Result> { + let _complete_guard = MarkCompleteOnDrop(unit_filter.clone()); let partitions = plan.output_partitioning().partition_count(); - let sort: Arc = Arc::new( - SortExec::new(expr.clone(), plan) - .with_fetch(Some(fetch)) - .with_preserve_partitioning(true), - ); + let mut sort_exec = SortExec::new(expr.clone(), plan) + .with_fetch(Some(fetch)) + .with_preserve_partitioning(true); + if let Some(filter) = unit_filter { + sort_exec = sort_exec.with_dynamic_filter_expr(filter)?; + } + let sort: Arc = Arc::new(sort_exec); let top: Arc = if partitions > 1 { Arc::new(CoalescePartitionsExec::new(sort)) } else { @@ -3269,14 +3342,51 @@ mod tests { filter: Arc::clone(&filters[0]), }; let fresh = filters[0].expression_id().unwrap(); + let unit_local = Arc::new(DynamicFilterPhysicalExpr::new( + filters[0].children().into_iter().cloned().collect(), + lit(true), + )); + let unit_local_id = unit_local.expression_id().unwrap(); for unit in exec.units.iter() { let before = scan_filter_ids(&unit.plan); - let after = scan_filter_ids(&prepare_unit(&unit.plan, Some(&run)).unwrap()); + let expected_count = before.iter().filter(|id| **id == template_id).count(); + let (prepared_global, rebound_global) = + prepare_unit(&unit.plan, Some(&run), None).unwrap(); + let after = scan_filter_ids(&prepared_global); + assert_eq!(rebound_global, expected_count > 0); assert!(!after.contains(&template_id)); assert_eq!( after.iter().filter(|id| **id == fresh).count(), - before.iter().filter(|id| **id == template_id).count() + expected_count + ); + + let (prepared_both, rebound_both) = + prepare_unit(&unit.plan, Some(&run), Some(&unit_local)).unwrap(); + let after_both = scan_filter_ids(&prepared_both); + assert_eq!(rebound_both, expected_count > 0); + assert!(!after_both.contains(&template_id)); + assert_eq!( + after_both.iter().filter(|id| **id == fresh).count(), + expected_count + ); + assert_eq!( + after_both.iter().filter(|id| **id == unit_local_id).count(), + expected_count ); } } + + #[test] + fn single_file_scan_with_per_file_stats_is_certified_bounded() { + let file = fake_file(0, Some(ts_stats(100, 200, 0))); + let scan = fake_scan(vec![vec![file]], None); + let units = analyze_source(&scan, DESC_NULLS_LAST, 4).unwrap(); + assert_eq!(units.len(), 1); + let bound = units[0] + .bound + .as_ref() + .expect("single file with exact per-file stats must be bounded"); + assert_eq!(bound.value, ScalarValue::Int64(Some(200))); + assert!(bound.no_nulls); + } } diff --git a/src/query/stream_schema_provider.rs b/src/query/stream_schema_provider.rs index 3ced7e243..cf9188492 100644 --- a/src/query/stream_schema_provider.rs +++ b/src/query/stream_schema_provider.rs @@ -19,7 +19,7 @@ use std::{any::Any, cmp::Reverse, collections::HashMap, ops::Bound, sync::Arc}; pub(crate) mod staging_parquet; -use staging_parquet::{lease_staging_parquet, validate_staging_parquet}; +use staging_parquet::{lease_staging_parquet, validate_staging_parquet_with_schema}; use arrow_array::RecordBatch; use arrow_schema::{Schema, SchemaRef}; @@ -894,7 +894,7 @@ pub fn partitioned_files( let total_files = manifest_files.len(); let num_fields = schema.fields().len(); let within_stats_budget = total_files.saturating_mul(num_fields) <= MAX_PER_FILE_COLUMN_STATS; - let attach_per_file_stats = total_files >= 2 && within_stats_budget; + let attach_per_file_stats = within_stats_budget; let time_col_idx = schema.index_of(time_column).ok(); let file_groups = balanced_file_groups(manifest_files, target_partitions); @@ -1450,7 +1450,10 @@ impl TableProvider for StandardTableProvider { })?; // The hard links retain the captured inodes after the // publication lock is released. - Ok((records, validate_staging_parquet(files?)?)) + Ok(( + records, + validate_staging_parquet_with_schema(files?, Some(&self.schema))?, + )) } Err(_) => Ok((StagingCapture::default(), Vec::new())), } @@ -2235,10 +2238,6 @@ struct BoundedStagingTable { #[async_trait::async_trait] impl TableProvider for BoundedStagingTable { - fn as_any(&self) -> &dyn Any { - self - } - fn schema(&self) -> SchemaRef { self.inner.schema() } @@ -2255,7 +2254,9 @@ impl TableProvider for BoundedStagingTable { limit: Option, ) -> DataFusionResult> { let inner = self.inner.scan(state, projection, filters, limit).await?; - if limit.is_some() || self.slices.len() < 2 || !self.slices.iter().any(|(b, _)| b.is_some()) + if limit.is_some() + || self.slices.is_empty() + || !self.slices.iter().any(|(b, _)| b.is_some()) { return Ok(inner); } @@ -2274,17 +2275,21 @@ impl TableProvider for BoundedStagingTable { /// bounds for each slice whose batches are all `TimestampBounds::NonNull`. fn slice_indexed_messages_for_topk( messages: &[crate::parseable::staging::reader::ValidatedIpcMessage], - bounds: &[crate::parseable::staging::TimestampBounds], + bounds: &[crate::parseable::staging::disk_source::TimestampBounds], ) -> Vec<(Option<(i64, i64)>, Vec<(u64, usize)>)> { - use crate::parseable::staging::TimestampBounds; + use crate::parseable::staging::disk_source::TimestampBounds; let n = messages.len(); - if n == 0 || n != bounds.len() { + if n == 0 { return Vec::new(); } + if n != bounds.len() { + // Fail closed: keep all messages in one unbounded slice rather than dropping rows. + return vec![(None, messages.iter().map(|m| (m.offset, m.size)).collect())]; + } let mut slices = Vec::new(); let mut cursor = 0usize; - let initial_sizes = [16usize, 32, 64, 128]; + let initial_sizes = [2usize, 4, 8, 16, 32, 64, 128]; for &step in &initial_sizes { if cursor >= n { break; @@ -2332,13 +2337,23 @@ fn slice_indexed_messages_for_topk( out } +/// Extracted `p_timestamp` millisecond range `[start_ms, end_ms)` (`None` means +/// unbounded on that side) plus residual filters not absorbed by the range. +struct StagingTimeRange { + start_ms: Option, + end_ms: Option, + all_exact_time_only: bool, + has_exact_time_filter: bool, + residual_filters: Vec, +} + /// Extracts an inclusive-start, exclusive-end millisecond range `[start_ms, end_ms)` /// on `p_timestamp` from DataFusion filter expressions for indexed staging-batch -/// pruning and (when `all_exact_time_only` is true) zero-decode `COUNT(*)` folding. +/// pruning, interior time-filter stripping, and zero-decode `COUNT(*)` folding. fn extract_staging_timestamp_ms_range( schema: &Schema, filters: &[Expr], -) -> Option<(i64, i64, bool)> { +) -> Option { let field = schema.field_with_name(DEFAULT_TIMESTAMP_KEY).ok()?; if !matches!( field.data_type(), @@ -2348,10 +2363,20 @@ fn extract_staging_timestamp_ms_range( } let mut stack: Vec<&Expr> = filters.iter().collect(); - let mut start_ms = i64::MIN; - let mut end_ms = i64::MAX; + let mut start_ms: Option = None; + let mut end_ms: Option = None; + let mut impossible = false; let mut saw_bound = false; + let mut has_exact_time_filter = false; let mut all_exact_time_only = !filters.is_empty(); + let mut residual_filters = Vec::new(); + + let tighten_start = |slot: &mut Option, v: i64| { + *slot = Some(slot.map_or(v, |cur| cur.max(v))); + }; + let tighten_end = |slot: &mut Option, v: i64| { + *slot = Some(slot.map_or(v, |cur| cur.min(v))); + }; while let Some(expr) = stack.pop() { if let Expr::BinaryExpr(bin) = expr @@ -2363,6 +2388,7 @@ fn extract_staging_timestamp_ms_range( } let Some(bound) = PartialTimeFilter::try_from_expr(expr, &None) else { all_exact_time_only = false; + residual_filters.push(expr.clone()); continue; }; saw_bound = true; @@ -2370,36 +2396,44 @@ fn extract_staging_timestamp_ms_range( PartialTimeFilter::Low(Bound::Included(t)) => { let utc = t.and_utc(); let ms = utc.timestamp_millis(); + tighten_start(&mut start_ms, ms); if utc.timestamp_subsec_nanos().is_multiple_of(1_000_000) { - start_ms = start_ms.max(ms); + has_exact_time_filter = true; } else { all_exact_time_only = false; - start_ms = start_ms.max(ms); + residual_filters.push(expr.clone()); } } PartialTimeFilter::Low(Bound::Excluded(t)) => { let utc = t.and_utc(); let ms = utc.timestamp_millis(); if utc.timestamp_subsec_nanos().is_multiple_of(1_000_000) { + has_exact_time_filter = true; if let Some(next) = ms.checked_add(1) { - start_ms = start_ms.max(next); + tighten_start(&mut start_ms, next); } else { // `p_timestamp > i64::MAX` matches nothing. - return Some((1, 0, all_exact_time_only)); + impossible = true; + residual_filters.push(expr.clone()); } } else { all_exact_time_only = false; - start_ms = start_ms.max(ms); + tighten_start(&mut start_ms, ms); + residual_filters.push(expr.clone()); } } PartialTimeFilter::High(Bound::Excluded(t)) => { let utc = t.and_utc(); let ms = utc.timestamp_millis(); if utc.timestamp_subsec_nanos().is_multiple_of(1_000_000) { - end_ms = end_ms.min(ms); + tighten_end(&mut end_ms, ms); + has_exact_time_filter = true; } else { all_exact_time_only = false; - end_ms = end_ms.min(ms.saturating_add(1)); + if let Some(next) = ms.checked_add(1) { + tighten_end(&mut end_ms, next); + } + residual_filters.push(expr.clone()); } } PartialTimeFilter::High(Bound::Included(t)) => { @@ -2407,39 +2441,111 @@ fn extract_staging_timestamp_ms_range( let ms = utc.timestamp_millis(); if utc.timestamp_subsec_nanos().is_multiple_of(1_000_000) { if let Some(next) = ms.checked_add(1) { - end_ms = end_ms.min(next); + tighten_end(&mut end_ms, next); + has_exact_time_filter = true; } else { all_exact_time_only = false; + residual_filters.push(expr.clone()); } } else { all_exact_time_only = false; - end_ms = end_ms.min(ms.saturating_add(1)); + if let Some(next) = ms.checked_add(1) { + tighten_end(&mut end_ms, next); + } + residual_filters.push(expr.clone()); } } PartialTimeFilter::Eq(t) => { let utc = t.and_utc(); let ms = utc.timestamp_millis(); + tighten_start(&mut start_ms, ms); if utc.timestamp_subsec_nanos().is_multiple_of(1_000_000) { - start_ms = start_ms.max(ms); if let Some(next) = ms.checked_add(1) { - end_ms = end_ms.min(next); + tighten_end(&mut end_ms, next); + has_exact_time_filter = true; } else { all_exact_time_only = false; + residual_filters.push(expr.clone()); } } else { all_exact_time_only = false; - start_ms = start_ms.max(ms); - end_ms = end_ms.min(ms.saturating_add(1)); + if let Some(next) = ms.checked_add(1) { + tighten_end(&mut end_ms, next); + } + residual_filters.push(expr.clone()); } } PartialTimeFilter::Low(Bound::Unbounded) | PartialTimeFilter::High(Bound::Unbounded) => { all_exact_time_only = false; + residual_filters.push(expr.clone()); } } } - saw_bound.then_some((start_ms, end_ms, all_exact_time_only)) + let (start_ms, end_ms) = if impossible { + (Some(1), Some(0)) + } else { + (start_ms, end_ms) + }; + saw_bound.then_some(StagingTimeRange { + start_ms, + end_ms, + all_exact_time_only, + has_exact_time_filter, + residual_filters, + }) +} + +fn build_parallel_staging_table( + work_units: Vec, + table_schema: SchemaRef, + projected_schema: SchemaRef, + two_phase_filter: Option, + max_partitions: usize, + batch_size: usize, +) -> DataFusionResult { + let num_buckets = work_units.len().min(max_partitions).max(1); + let mut buckets: Vec> = (0..num_buckets).map(|_| Vec::new()).collect(); + if num_buckets == 1 { + buckets[0] = work_units; + } else { + let mut indexed: Vec<(usize, StagingDiskWork)> = + work_units.into_iter().enumerate().collect(); + // Balance total bytes across partitions using largest-first bin packing. + indexed.sort_by(|a, b| { + b.1.byte_weight() + .cmp(&a.1.byte_weight()) + .then_with(|| a.0.cmp(&b.0)) + }); + let mut loads = vec![0usize; num_buckets]; + for (_, unit) in indexed { + let target = loads + .iter() + .enumerate() + .min_by_key(|(_, load)| **load) + .map(|(idx, _)| idx) + .unwrap_or(0); + loads[target] = loads[target].saturating_add(unit.byte_weight()); + buckets[target].push(unit); + } + } + let partitions = buckets + .into_iter() + .filter(|b| !b.is_empty()) + .map(|work| { + Arc::new(StagingDiskPartition { + table_schema: table_schema.clone(), + schema: projected_schema.clone(), + work, + reverse_rows: false, + batch_size, + two_phase_filter: two_phase_filter.clone(), + time_range: None, + }) as Arc + }) + .collect(); + StreamingTable::try_new(projected_schema, partitions) } /// A scan over staging files whose rows the memory cache does not hold, @@ -2458,8 +2564,9 @@ async fn staging_disk_plan( return Ok(None); } let time_range = extract_staging_timestamp_ms_range(&schema, filters); - let can_fold_counts = - projection.is_some_and(|p| p.is_empty()) && time_range.is_some_and(|(_, _, exact)| exact); + let time_bounds = time_range.as_ref().map(|r| (r.start_ms, r.end_ms)); + let can_fold_counts = projection.is_some_and(|p| p.is_empty()) + && time_range.as_ref().is_some_and(|r| r.all_exact_time_only); let needed_proj = needed_column_projection(&schema, projection, filters)?; let projected_schema = needed_proj.schema; let disk_projection = needed_proj.remapped_projection; @@ -2481,7 +2588,7 @@ async fn staging_disk_plan( reverse_rows: true, batch_size, two_phase_filter, - time_range: time_range.map(|(s, e, _)| (s, e)), + time_range: time_bounds, }) as Arc; let table = StreamingTable::try_new(projected_schema, vec![partition])?; return scan_enforcing_exact_filters( @@ -2495,6 +2602,34 @@ async fn staging_disk_plan( .map(Some); } + let output_has_timestamp = schema + .index_of(DEFAULT_TIMESTAMP_KEY) + .ok() + .is_some_and(|ts_idx| projection.is_none_or(|p| p.contains(&ts_idx))); + // For unlimited aggregates/scans that do not project `p_timestamp` (e.g., + // `GROUP BY app` or filtered `COUNT(*)`), batches certified completely + // inside `[start_ms, end_ms)` skip decoding `p_timestamp` and evaluating + // the absorbed time filters. + let interior_plan = if !can_fold_counts + && !output_has_timestamp + && time_range.as_ref().is_some_and(|r| r.has_exact_time_filter) + { + let residual_filters = time_range + .as_ref() + .map(|r| r.residual_filters.clone()) + .unwrap_or_default(); + let interior_needed = needed_column_projection(&schema, projection, &residual_filters)?; + if interior_needed.schema.fields().len() < projected_schema.fields().len() { + let interior_two_phase = + build_staging_two_phase_filter(&interior_needed.schema, &residual_filters, state); + Some((interior_needed, residual_filters, interior_two_phase)) + } else { + None + } + } else { + None + }; + let max_partitions = state .config_options() .execution @@ -2507,150 +2642,285 @@ async fn staging_disk_plan( let table_schema_for_plan = schema.clone(); let projected_for_plan = projected_schema.clone(); let filter_schema_for_plan = two_phase_filter.as_ref().map(|f| f.filter_schema.clone()); - let (work_units, folded_units, topk_work_slices) = tokio::task::spawn_blocking(move || { - let mut units = Vec::with_capacity(sources.len()); - let mut folded_units = Vec::new(); - let mut topk_slices: Vec<(Option<(i64, i64)>, StagingDiskWork)> = Vec::new(); - let time_bounds = time_range.map(|(s, e, _)| (s, e)); - for source in sources { - if cancel_flag.load(std::sync::atomic::Ordering::Relaxed) { - break; - } - let (plan, folded_rows, batch_bounds) = - match source.plan_prefix_with_bounds(time_bounds, can_fold_counts) { - Ok(res) => res, - Err(err) => { - let failed = - StagingDiskWork::Failed(format!("Cannot read staging rows: {err}")); - units.push(failed.clone()); - topk_slices.push((None, failed)); - continue; + let interior_schema_for_plan = interior_plan.as_ref().map(|(n, _, _)| n.schema.clone()); + let interior_filter_schema_for_plan = interior_plan + .as_ref() + .and_then(|(_, _, tp)| tp.as_ref().map(|f| f.filter_schema.clone())); + let (work_units, interior_units, folded_units, topk_work_slices) = + tokio::task::spawn_blocking(move || { + use crate::parseable::staging::disk_source::TimestampBounds; + + let mut units = Vec::with_capacity(sources.len()); + let mut interior_units = Vec::new(); + let mut folded_units = Vec::new(); + let mut topk_slices: Vec<(Option<(i64, i64)>, StagingDiskWork)> = Vec::new(); + let push_split_work = + |target: &mut Vec, + source: &StagingDiskSource, + plan_schema: &SchemaRef, + schema_range: (u64, usize), + has_dictionaries: bool, + messages: &[crate::parseable::staging::reader::ValidatedIpcMessage], + target_schema: &SchemaRef, + target_filter_schema: Option<&SchemaRef>| { + let ipc_projection = match ipc_projection_for_file(plan_schema, target_schema) { + IpcProjection::Empty => { + match checked_total_rows(messages, source.path()) { + Ok(total_rows) if total_rows > 0 => { + target.push(StagingDiskWork::RowCounts { + source: source.clone(), + total_rows, + }); + } + Ok(_) => {} + Err(err) => { + target.push(StagingDiskWork::Failed(err)); + } + } + return; + } + IpcProjection::Full => None, + IpcProjection::Columns(cols) => Some(cols), + }; + let two_phase_cols = if !has_dictionaries { + target_filter_schema.and_then(|filter_schema| { + two_phase_file_indices(plan_schema, filter_schema, target_schema) + }) + } else { + None + }; + let total_bytes: usize = messages.iter().map(|m| m.size).sum(); + let splits = if max_partitions <= 1 + || has_dictionaries + || messages.len() <= 1 + || total_bytes < STAGING_DISK_MIN_SPLIT_BYTES + { + 1 + } else { + max_partitions.min(messages.len()) + }; + for chunk in split_ipc_messages_by_bytes(messages, splits) { + let byte_weight: usize = chunk.iter().map(|(_, size)| *size).sum(); + let mut ranges = Vec::with_capacity(chunk.len() + 1); + ranges.push(schema_range); + ranges.extend(chunk); + if let Some((filter_indices, output_indices)) = two_phase_cols.as_ref() { + target.push(StagingDiskWork::TwoPhaseRanges { + source: source.clone(), + ranges: Arc::from(ranges), + filter_indices: filter_indices.clone(), + output_indices: output_indices.clone(), + byte_weight, + }); + } else { + target.push(StagingDiskWork::Ranges { + source: source.clone(), + ranges: Arc::from(ranges), + ipc_projection: ipc_projection.clone(), + byte_weight, + }); + } } }; - let has_messages = plan.messages.iter().any(|m| m.rows.is_some()); - if !has_messages && folded_rows == 0 { - continue; - } - let has_rows = - folded_rows > 0 || plan.messages.iter().any(|m| m.rows.is_some_and(|r| r > 0)); - if let Err(err) = validate_file_schema_for_table( - &table_schema_for_plan, - &plan.schema, - has_rows, - source.path(), - ) { - let failed = StagingDiskWork::Failed(err); - units.push(failed.clone()); - topk_slices.push((None, failed)); - continue; - } - if folded_rows > 0 { - folded_units.push(StagingDiskWork::RowCounts { - source: source.clone(), - total_rows: folded_rows, - }); - } - if !has_messages { - continue; - } - let ipc_projection = match ipc_projection_for_file(&plan.schema, &projected_for_plan) { - IpcProjection::Empty => { - match checked_total_rows(&plan.messages, source.path()) { - Ok(total_rows) if total_rows > 0 => { - let rc = StagingDiskWork::RowCounts { source, total_rows }; - units.push(rc.clone()); - topk_slices.push((None, rc)); - } - Ok(_) => {} + + for source in sources { + if cancel_flag.load(std::sync::atomic::Ordering::Relaxed) { + break; + } + let (plan, folded_rows, batch_bounds) = + match source.plan_prefix_with_bounds(time_bounds, can_fold_counts) { + Ok(res) => res, Err(err) => { - let failed = StagingDiskWork::Failed(err); + let failed = + StagingDiskWork::Failed(format!("Cannot read staging rows: {err}")); units.push(failed.clone()); - topk_slices.push((None, failed)); + if output_has_timestamp { + topk_slices.push((None, failed)); + } + continue; } + }; + let has_messages = plan.messages.iter().any(|m| m.rows.is_some()); + if !has_messages && folded_rows == 0 { + continue; + } + let has_rows = + folded_rows > 0 || plan.messages.iter().any(|m| m.rows.is_some_and(|r| r > 0)); + if let Err(err) = validate_file_schema_for_table( + &table_schema_for_plan, + &plan.schema, + has_rows, + source.path(), + ) { + let failed = StagingDiskWork::Failed(err); + units.push(failed.clone()); + if output_has_timestamp { + topk_slices.push((None, failed)); } continue; } - IpcProjection::Full => None, - IpcProjection::Columns(cols) => Some(cols), - }; - - let two_phase_cols = if !plan.has_dictionaries { - filter_schema_for_plan.as_ref().and_then(|filter_schema| { - two_phase_file_indices(&plan.schema, filter_schema, &projected_for_plan) - }) - } else { - None - }; + if folded_rows > 0 { + folded_units.push(StagingDiskWork::RowCounts { + source: source.clone(), + total_rows: folded_rows, + }); + } + if !has_messages { + continue; + } - let mut messages = plan.messages; - let mut batch_bounds = batch_bounds; - // Dictionary-encoded streams keep forward IPC order so dictionary - // definitions precede the batches referencing them. - if !plan.has_dictionaries { - messages.reverse(); - if let Some(bounds) = batch_bounds.as_mut() { - bounds.reverse(); + let mut messages = plan.messages; + let mut batch_bounds = batch_bounds; + // Dictionary-encoded streams keep forward IPC order so dictionary + // definitions precede the batches referencing them. + if !plan.has_dictionaries { + messages.reverse(); + if let Some(bounds) = batch_bounds.as_mut() { + bounds.reverse(); + } } - } - let make_work = |chunk: Vec<(u64, usize)>| { - let byte_weight: usize = chunk.iter().map(|(_, size)| *size).sum(); - let mut ranges = Vec::with_capacity(chunk.len() + 1); - ranges.push(plan.schema_range); - ranges.extend(chunk); - if let Some((filter_indices, output_indices)) = two_phase_cols.as_ref() { - StagingDiskWork::TwoPhaseRanges { - source: source.clone(), - ranges: Arc::from(ranges), - filter_indices: filter_indices.clone(), - output_indices: output_indices.clone(), - byte_weight, + if let (Some(interior_schema), Some((start_ms, end_ms)), Some(bounds)) = ( + interior_schema_for_plan.as_ref(), + time_bounds, + batch_bounds.as_deref(), + ) && !plan.has_dictionaries + && bounds.len() == messages.len() + { + let empty_range = matches!((start_ms, end_ms), (Some(s), Some(e)) if s >= e); + if !empty_range { + let mut interior_msgs = Vec::new(); + let mut boundary_msgs = Vec::new(); + for (msg, bound) in messages.into_iter().zip(bounds.iter().copied()) { + let inside = matches!( + bound, + TimestampBounds::NonNull { min, max } + if start_ms.is_none_or(|s| min >= s) + && end_ms.is_none_or(|e| max < e) + ); + if inside { + interior_msgs.push(msg); + } else { + boundary_msgs.push(msg); + } + } + if !interior_msgs.is_empty() { + push_split_work( + &mut interior_units, + &source, + &plan.schema, + plan.schema_range, + false, + &interior_msgs, + interior_schema, + interior_filter_schema_for_plan.as_ref(), + ); + } + if boundary_msgs.is_empty() { + continue; + } + messages = boundary_msgs; + batch_bounds = None; } + } + + let ipc_projection = + match ipc_projection_for_file(&plan.schema, &projected_for_plan) { + IpcProjection::Empty => { + match checked_total_rows(&messages, source.path()) { + Ok(total_rows) if total_rows > 0 => { + let rc = StagingDiskWork::RowCounts { source, total_rows }; + units.push(rc.clone()); + if output_has_timestamp { + topk_slices.push((None, rc)); + } + } + Ok(_) => {} + Err(err) => { + let failed = StagingDiskWork::Failed(err); + units.push(failed.clone()); + if output_has_timestamp { + topk_slices.push((None, failed)); + } + } + } + continue; + } + IpcProjection::Full => None, + IpcProjection::Columns(cols) => Some(cols), + }; + + let two_phase_cols = if !plan.has_dictionaries { + filter_schema_for_plan.as_ref().and_then(|filter_schema| { + two_phase_file_indices(&plan.schema, filter_schema, &projected_for_plan) + }) } else { - StagingDiskWork::Ranges { - source: source.clone(), - ranges: Arc::from(ranges), - ipc_projection: ipc_projection.clone(), - byte_weight, + None + }; + + let make_work = |chunk: Vec<(u64, usize)>| { + let byte_weight: usize = chunk.iter().map(|(_, size)| *size).sum(); + let mut ranges = Vec::with_capacity(chunk.len() + 1); + ranges.push(plan.schema_range); + ranges.extend(chunk); + if let Some((filter_indices, output_indices)) = two_phase_cols.as_ref() { + StagingDiskWork::TwoPhaseRanges { + source: source.clone(), + ranges: Arc::from(ranges), + filter_indices: filter_indices.clone(), + output_indices: output_indices.clone(), + byte_weight, + } + } else { + StagingDiskWork::Ranges { + source: source.clone(), + ranges: Arc::from(ranges), + ipc_projection: ipc_projection.clone(), + byte_weight, + } } - } - }; + }; - if let Some(bounds) = batch_bounds.as_deref() - && !plan.has_dictionaries - { - for (certified, chunk) in slice_indexed_messages_for_topk(&messages, bounds) { - topk_slices.push((certified, make_work(chunk))); + if output_has_timestamp { + if let Some(bounds) = batch_bounds.as_deref() + && !plan.has_dictionaries + { + for (certified, chunk) in slice_indexed_messages_for_topk(&messages, bounds) + { + topk_slices.push((certified, make_work(chunk))); + } + } else { + let all_ranges = messages.iter().map(|m| (m.offset, m.size)).collect(); + topk_slices.push((None, make_work(all_ranges))); + } } - } else { - let all_ranges = messages.iter().map(|m| (m.offset, m.size)).collect(); - topk_slices.push((None, make_work(all_ranges))); - } - let total_bytes: usize = messages.iter().map(|m| m.size).sum(); - let splits = if max_partitions <= 1 - || plan.has_dictionaries - || messages.len() <= 1 - || total_bytes < STAGING_DISK_MIN_SPLIT_BYTES - { - 1 - } else { - max_partitions.min(messages.len()) - }; - for chunk in split_ipc_messages_by_bytes(&messages, splits) { - units.push(make_work(chunk)); + let total_bytes: usize = messages.iter().map(|m| m.size).sum(); + let splits = if max_partitions <= 1 + || plan.has_dictionaries + || messages.len() <= 1 + || total_bytes < STAGING_DISK_MIN_SPLIT_BYTES + { + 1 + } else { + max_partitions.min(messages.len()) + }; + for chunk in split_ipc_messages_by_bytes(&messages, splits) { + units.push(make_work(chunk)); + } } - } - (units, folded_units, topk_slices) - }) - .await - .map_err(|err| DataFusionError::Execution(format!("Staging disk planning failed: {err}")))?; + (units, interior_units, folded_units, topk_slices) + }) + .await + .map_err(|err| { + DataFusionError::Execution(format!("Staging disk planning failed: {err}")) + })?; - if work_units.is_empty() && folded_units.is_empty() { + if work_units.is_empty() && interior_units.is_empty() && folded_units.is_empty() { return Ok(None); } - let mut sub_plans: Vec> = Vec::with_capacity(2); + let mut sub_plans: Vec> = Vec::with_capacity(3); if !folded_units.is_empty() { // Folded batches are already certified to satisfy all time predicates // and carry zero projected columns, so emit them directly without FilterExec. @@ -2668,50 +2938,39 @@ async fn staging_disk_plan( sub_plans.push(table.scan(state, None, &[], limit).await?); } - if !work_units.is_empty() { - let num_buckets = work_units.len().min(max_partitions).max(1); - let mut buckets: Vec> = (0..num_buckets).map(|_| Vec::new()).collect(); - if num_buckets == 1 { - buckets[0] = work_units; - } else { - let mut indexed: Vec<(usize, StagingDiskWork)> = - work_units.into_iter().enumerate().collect(); - // Balance total bytes across partitions using largest-first bin packing. - indexed.sort_by(|a, b| { - b.1.byte_weight() - .cmp(&a.1.byte_weight()) - .then_with(|| a.0.cmp(&b.0)) - }); - let mut loads = vec![0usize; num_buckets]; - for (_, unit) in indexed { - let target = loads - .iter() - .enumerate() - .min_by_key(|(_, load)| **load) - .map(|(idx, _)| idx) - .unwrap_or(0); - loads[target] = loads[target].saturating_add(unit.byte_weight()); - buckets[target].push(unit); - } - } + if !interior_units.is_empty() + && let Some((interior_needed, residual_filters, interior_two_phase)) = interior_plan + { + let interior_table = build_parallel_staging_table( + interior_units, + schema.clone(), + interior_needed.schema, + interior_two_phase, + max_partitions, + batch_size, + )?; + sub_plans.push( + scan_enforcing_exact_filters( + &interior_table, + state, + interior_needed.remapped_projection.as_ref(), + &residual_filters, + limit, + ) + .await?, + ); + } - let partitions = buckets - .into_iter() - .filter(|b| !b.is_empty()) - .map(|work| { - Arc::new(StagingDiskPartition { - table_schema: schema.clone(), - schema: projected_schema.clone(), - work, - reverse_rows: false, - batch_size, - two_phase_filter: two_phase_filter.clone(), - time_range: None, - }) as Arc - }) - .collect(); - let inner_table = StreamingTable::try_new(projected_schema.clone(), partitions)?; - if topk_work_slices.len() >= 2 && topk_work_slices.iter().any(|(b, _)| b.is_some()) { + if !work_units.is_empty() { + let inner_table = build_parallel_staging_table( + work_units, + schema.clone(), + projected_schema.clone(), + two_phase_filter.clone(), + max_partitions, + batch_size, + )?; + if !topk_work_slices.is_empty() && topk_work_slices.iter().any(|(b, _)| b.is_some()) { let mut slices = Vec::with_capacity(topk_work_slices.len()); for (bounds, work) in topk_work_slices { let part = Arc::new(StagingDiskPartition { @@ -2941,7 +3200,7 @@ struct StagingDiskPartition { reverse_rows: bool, batch_size: usize, two_phase_filter: Option, - time_range: Option<(i64, i64)>, + time_range: Option<(Option, Option)>, } impl PartitionStream for StagingDiskPartition { @@ -2972,9 +3231,9 @@ impl PartitionStream for StagingDiskPartition { } StagingDiskWork::LazySource(source) => { let plan = match time_range { - Some((start_ms, end_ms)) => source - .plan_prefix_for_time_range(start_ms, end_ms, false) - .map(|(plan, _)| plan), + Some(bounds) => source + .plan_prefix_with_bounds(Some(bounds), false) + .map(|(plan, _, _)| plan), None => source.plan_prefix(), } .map_err(|err| { diff --git a/src/query/stream_schema_provider/staging_parquet.rs b/src/query/stream_schema_provider/staging_parquet.rs index a03bc7f9e..76335e7e6 100644 --- a/src/query/stream_schema_provider/staging_parquet.rs +++ b/src/query/stream_schema_provider/staging_parquet.rs @@ -7,10 +7,18 @@ use std::{ sync::Arc, }; +use arrow_schema::{DataType, SchemaRef, TimeUnit}; use datafusion::{ + common::{ColumnStatistics, ScalarValue, Statistics, stats::Precision}, datasource::listing::PartitionedFile, error::{DataFusionError, Result}, }; +use parquet::{ + basic::Type as PhysicalType, + file::{metadata::ParquetMetaData, statistics::Statistics as ParquetStatistics}, +}; + +use crate::event::DEFAULT_TIMESTAMP_KEY; /// Keep the original name for canonical upload-path comparison; scans use only /// the leased path. Published `.parquet` files must never be rewritten in place. @@ -213,7 +221,87 @@ fn capture_paths(directory: &Path, paths: Vec) -> Result Option { + let ts_idx = table_schema.index_of(DEFAULT_TIMESTAMP_KEY).ok()?; + let DataType::Timestamp(TimeUnit::Millisecond, tz) = + table_schema.field(ts_idx).data_type().clone() + else { + return None; + }; + let descr = metadata.file_metadata().schema_descr(); + let parquet_col_idx = descr.columns().iter().position(|col| { + let is_millis = matches!( + col.logical_type_ref(), + Some(parquet::basic::LogicalType::Timestamp { + unit: parquet::basic::TimeUnit::MILLIS, + .. + }) + ) || col.converted_type() + == parquet::basic::ConvertedType::TIMESTAMP_MILLIS; + col.path().parts() == [DEFAULT_TIMESTAMP_KEY] + && col.physical_type() == PhysicalType::INT64 + && is_millis + })?; + let row_groups = metadata.row_groups(); + if row_groups.is_empty() { + return None; + } + let mut min_ms = i64::MAX; + let mut max_ms = i64::MIN; + let mut total_rows = 0usize; + for rg in row_groups { + let rg_rows = usize::try_from(rg.num_rows()).ok()?; + if rg_rows == 0 { + continue; + } + total_rows = total_rows.checked_add(rg_rows)?; + let stats = rg.column(parquet_col_idx).statistics()?; + if !stats.min_is_exact() || !stats.max_is_exact() || stats.null_count_opt() != Some(0) { + return None; + } + let ParquetStatistics::Int64(int_stats) = stats else { + return None; + }; + let lo = *int_stats.min_opt()?; + let hi = *int_stats.max_opt()?; + min_ms = min_ms.min(lo); + max_ms = max_ms.max(hi); + } + if min_ms > max_ms || total_rows == 0 { + return None; + } + let mut column_statistics = vec![ColumnStatistics::new_unknown(); table_schema.fields().len()]; + column_statistics[ts_idx] = ColumnStatistics { + null_count: Precision::Exact(0), + max_value: Precision::Exact(ScalarValue::TimestampMillisecond(Some(max_ms), tz.clone())), + min_value: Precision::Exact(ScalarValue::TimestampMillisecond(Some(min_ms), tz)), + sum_value: Precision::Absent, + distinct_count: Precision::Absent, + byte_size: Precision::Absent, + }; + Some(Statistics { + num_rows: Precision::Exact(total_rows), + total_byte_size: Precision::Absent, + column_statistics, + }) +} + +#[cfg(test)] pub(super) fn validate_staging_parquet(files: Vec) -> Result> { + validate_staging_parquet_with_schema(files, None) +} + +pub(super) fn validate_staging_parquet_with_schema( + files: Vec, + table_schema: Option<&SchemaRef>, +) -> Result> { let mut captured = Vec::with_capacity(files.len()); for LeasedFile { original, @@ -225,15 +313,21 @@ pub(super) fn validate_staging_parquet(files: Vec) -> Result Date: Tue, 1 Dec 2026 18:45:54 -0600 Subject: [PATCH 15/17] Fix Parquet LogicalType::Timestamp pattern and deprecated partition_statistics override --- src/query/stream_schema_provider.rs | 4 ---- src/query/stream_schema_provider/staging_parquet.rs | 6 ++---- 2 files changed, 2 insertions(+), 8 deletions(-) diff --git a/src/query/stream_schema_provider.rs b/src/query/stream_schema_provider.rs index cf9188492..c1ef4f3a9 100644 --- a/src/query/stream_schema_provider.rs +++ b/src/query/stream_schema_provider.rs @@ -2224,10 +2224,6 @@ impl ExecutionPlan for StagingDiskScanExec { ) -> DataFusionResult { self.inner.execute(partition, context) } - - fn partition_statistics(&self, partition: Option) -> DataFusionResult> { - self.inner.partition_statistics(partition) - } } #[derive(Debug)] diff --git a/src/query/stream_schema_provider/staging_parquet.rs b/src/query/stream_schema_provider/staging_parquet.rs index 76335e7e6..0fd37ca2a 100644 --- a/src/query/stream_schema_provider/staging_parquet.rs +++ b/src/query/stream_schema_provider/staging_parquet.rs @@ -239,10 +239,8 @@ fn certified_timestamp_statistics( let parquet_col_idx = descr.columns().iter().position(|col| { let is_millis = matches!( col.logical_type_ref(), - Some(parquet::basic::LogicalType::Timestamp { - unit: parquet::basic::TimeUnit::MILLIS, - .. - }) + Some(parquet::basic::LogicalType::Timestamp(ts)) + if matches!(ts.unit, parquet::basic::TimeUnit::MILLIS) ) || col.converted_type() == parquet::basic::ConvertedType::TIMESTAMP_MILLIS; col.path().parts() == [DEFAULT_TIMESTAMP_KEY] From f5b07a5d524b3e9c4eb90b52ab8cdcde55dd7fd0 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Tue, 1 Dec 2026 18:49:30 -0600 Subject: [PATCH 16/17] Factor StagingTopKUnit type aliases for clippy::type_complexity --- src/query/stream_schema_provider.rs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/query/stream_schema_provider.rs b/src/query/stream_schema_provider.rs index c1ef4f3a9..9ddeb55e9 100644 --- a/src/query/stream_schema_provider.rs +++ b/src/query/stream_schema_provider.rs @@ -2156,6 +2156,10 @@ fn split_ipc_messages_by_bytes( chunks } +pub(crate) type CertifiedTimeBounds = Option<(i64, i64)>; +pub(crate) type StagingTopKUnit = (CertifiedTimeBounds, Arc); +type StagingTopKMessageSlice = (CertifiedTimeBounds, Vec<(u64, usize)>); + /// Leaf wrapper over a parallel `StreamingTable` staging-disk scan that also /// exposes chronologically sliced, `p_timestamp`-bounded single-partition plans /// to `ProgressiveTopKRule`. Non-TopK queries execute `inner` directly with zero @@ -2164,11 +2168,11 @@ fn split_ipc_messages_by_bytes( #[derive(Debug)] pub(crate) struct StagingDiskScanExec { inner: Arc, - topk_units: Vec<(Option<(i64, i64)>, Arc)>, + topk_units: Vec, } impl StagingDiskScanExec { - pub(crate) fn topk_units(&self) -> &[(Option<(i64, i64)>, Arc)] { + pub(crate) fn topk_units(&self) -> &[StagingTopKUnit] { &self.topk_units } } @@ -2272,7 +2276,7 @@ impl TableProvider for BoundedStagingTable { fn slice_indexed_messages_for_topk( messages: &[crate::parseable::staging::reader::ValidatedIpcMessage], bounds: &[crate::parseable::staging::disk_source::TimestampBounds], -) -> Vec<(Option<(i64, i64)>, Vec<(u64, usize)>)> { +) -> Vec { use crate::parseable::staging::disk_source::TimestampBounds; let n = messages.len(); From f6a45b7884ed72daee510167992560350aafa6b5 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Tue, 1 Dec 2026 19:09:06 -0600 Subject: [PATCH 17/17] Fix expected ScalarValue type in single_file_scan_with_per_file_stats_is_certified_bounded --- src/query/ordered_topk.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/query/ordered_topk.rs b/src/query/ordered_topk.rs index 041f9ac6e..e19c98fbd 100644 --- a/src/query/ordered_topk.rs +++ b/src/query/ordered_topk.rs @@ -3386,7 +3386,10 @@ mod tests { .bound .as_ref() .expect("single file with exact per-file stats must be bounded"); - assert_eq!(bound.value, ScalarValue::Int64(Some(200))); + assert_eq!( + bound.value, + ScalarValue::TimestampMillisecond(Some(200), None) + ); assert!(bound.no_nulls); } }