diff --git a/docs/log-severity-clustering.md b/docs/log-severity-clustering.md index d4a745e6f..02649d71a 100644 --- a/docs/log-severity-clustering.md +++ b/docs/log-severity-clustering.md @@ -23,16 +23,33 @@ different columns; this is fallback selection, not a multi-column sort. ## What changes when enabled -During Arrow-to-Parquet conversion of a log stream, the writer buffers exactly -the rows of one row group (`P_PARQUET_ROW_GROUP_SIZE`, 262,144 by default). It -stably reorders them by the cluster column ascending, then by the stream's time -column (`p_timestamp` or its time partition) descending, with NULLs last in both -keys. The final row group of a file may be partial and is clustered the same way. - -- **Row groups contain the same rows as without clustering.** Their time ranges - are therefore unchanged and row-group time pruning is unaffected. Inside a - row group, rows of one severity are contiguous, so page indexes on the - timestamp column are less selective for queries that do not filter severity. +During Arrow-to-Parquet conversion of a log stream, the writer buffers the rows +of one row group (`P_PARQUET_ROW_GROUP_SIZE`, 262,144 by default). It stably +reorders them by the cluster column ascending, then by the stream's time column +(`p_timestamp` or its time partition) descending, with NULLs last in both keys. +The final row group of a file may be partial and is clustered the same way. + +A buffered row group is also capped at 128 MiB of Arrow data: rows stop +accumulating into it once its rows reach 128 MiB (each row counted at the data +size per row of the batch it was decoded from), and the next row group starts +there. Only row groups of large rows are affected. At the default row-group size +that means rows averaging more than about 512 bytes. Every other row group holds +exactly the rows it would hold without clustering, and the parallel writer +writes the same bytes as the sequential one. + +- **Row groups that are not cut short contain the same rows as without + clustering.** For them, time ranges and row-group time pruning are unchanged. + This holds only while the writer's own `P_PARQUET_ROW_GROUP_BYTES` + (`row_group_bytes`) limit does not split a clustered row group: that limit + applies after clustering, so it splits a group's clustered rows, not its + time-ordered rows. The resulting Parquet row groups each cover a severity + range across the whole group's time span. A group cut short at 128 MiB + covers a shorter time span than the default writer's row group, which + splits its rows by `row_group_bytes` (when set) at different points. In + both cases, row-group time pruning is weaker or different than without + clustering. Inside a row group, rows of one severity are contiguous, so page + indexes on the timestamp column are less selective for queries that do not + filter severity. - **Schema, values, timestamp units, row counts, manifest statistics** (min/max, `null_count`), file names, manifests, ingestion acknowledgements and every HTTP, OTLP, Flight and gRPC request/response format are unchanged. @@ -40,12 +57,37 @@ keys. The final row group of a file may be partial and is clustered the same way manifest `sort_order_id` is empty. They contain no file-level timestamp order, and the query engine does not trust footer order claims for any file. Without clustering, the existing `p_timestamp DESC` claim is still written. -- **Memory:** clustering holds up to one row group of decoded Arrow rows per - file being converted, plus one reordered batch of 8,192 rows at a time. - Rows are gathered from the buffered input in order; neither a concatenated - copy of the row group nor a full reordered copy is built. The existing - writer holds one row group of encoded column data. At most two conversions - run per stream. +- **Memory:** parallel clustered conversion pipelines bounded waves of row groups + on `LOG_CONVERSION_THREADPOOL`, gathering and encoding each column independently + in 8,192-row chunks without building a full reordered copy of the row group. + The writer bounds memory with schema estimates and with the measured size of + the rows it reads: + - Row groups whose schema floor estimate is above 64 MiB drop to one group per + wave. + - Row groups whose schema estimate is above 128 MiB (e.g., wide schemas under + churn) fall back to the sequential writer, which holds a single row group at + a time. + - Whatever the estimate, a row group stops taking rows at 128 MiB of actual + Arrow data, so a group of 2 KiB string payloads holds about 65,000 rows + instead of 512 MiB. + - Once a row group's decoded rows retain more than 64 MiB of allocations + (measured from the buffers the rows keep alive, each counted once), the rest + of the file is read, clustered, encoded and appended one row group at a time, + with no read-ahead or overlap. + - When the writer's byte limit splits one clustered row group, later row + groups of the file go straight to the split-aware encoder instead of being + encoded twice. + + At most two conversions run per stream. +- **Field statistics:** dataset statistics (`P_COLLECT_DATASET_STATS`) are counted + inline from the rows as they are read, in source order. A clustered file's + rows are stored in another order, so the inline counts are kept only while + they are exact and small. The writer drops them, releasing their values, as + soon as any field sees more distinct values than it tracks (at least 1,024). + Past that point its top values depend on counting order. It also drops them + when the tracked values exceed 16 MiB for the file. The upload path then + computes the statistics from the written file. Cached statistics waiting for + upload are capped at 16 MiB per file and 64 MiB in total. ## When clustering is skipped diff --git a/src/catalog/column.rs b/src/catalog/column.rs index bc0e49c85..9b304cf87 100644 --- a/src/catalog/column.rs +++ b/src/catalog/column.rs @@ -140,14 +140,46 @@ impl TypedStatistics { ScalarValue::Boolean(Some(stats.min)), ScalarValue::Boolean(Some(stats.max)), ), - (TypedStatistics::Int(stats), DataType::Int32) => ( - ScalarValue::Int32(Some(stats.min as i32)), - ScalarValue::Int32(Some(stats.max as i32)), - ), - (TypedStatistics::Int(stats), DataType::Int64) => ( - ScalarValue::Int64(Some(stats.min)), - ScalarValue::Int64(Some(stats.max)), - ), + (TypedStatistics::Int(stats), DataType::Int32) => { + if stats.min > stats.max { + return None; + } + let min = i32::try_from(stats.min).ok()?; + let max = i32::try_from(stats.max).ok()?; + (ScalarValue::Int32(Some(min)), ScalarValue::Int32(Some(max))) + } + (TypedStatistics::Int(stats), DataType::Int64) => { + if stats.min > stats.max { + return None; + } + ( + ScalarValue::Int64(Some(stats.min)), + ScalarValue::Int64(Some(stats.max)), + ) + } + (TypedStatistics::Int(stats), DataType::Timestamp(unit, tz)) => { + if stats.min > stats.max { + return None; + } + match unit { + arrow_schema::TimeUnit::Second => ( + ScalarValue::TimestampSecond(Some(stats.min), tz.clone()), + ScalarValue::TimestampSecond(Some(stats.max), tz.clone()), + ), + arrow_schema::TimeUnit::Millisecond => ( + ScalarValue::TimestampMillisecond(Some(stats.min), tz.clone()), + ScalarValue::TimestampMillisecond(Some(stats.max), tz.clone()), + ), + arrow_schema::TimeUnit::Microsecond => ( + ScalarValue::TimestampMicrosecond(Some(stats.min), tz.clone()), + ScalarValue::TimestampMicrosecond(Some(stats.max), tz.clone()), + ), + arrow_schema::TimeUnit::Nanosecond => ( + ScalarValue::TimestampNanosecond(Some(stats.min), tz.clone()), + ScalarValue::TimestampNanosecond(Some(stats.max), tz.clone()), + ), + } + } (TypedStatistics::Float(stats), DataType::Float32) => { let min_f32 = stats.min as f32; let max_f32 = stats.max as f32; @@ -195,6 +227,80 @@ fn is_valid_float_range(min: f64, max: f64) -> bool { !(min.is_nan() || max.is_nan() || min > max) } +/// Timestamp unit recorded in Parquet column metadata for a manifest column. +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub enum ManifestTimeUnit { + Second, + Millisecond, + Microsecond, + Nanosecond, +} + +impl ManifestTimeUnit { + pub const fn from_arrow(unit: arrow_schema::TimeUnit) -> Self { + match unit { + arrow_schema::TimeUnit::Second => Self::Second, + arrow_schema::TimeUnit::Millisecond => Self::Millisecond, + arrow_schema::TimeUnit::Microsecond => Self::Microsecond, + arrow_schema::TimeUnit::Nanosecond => Self::Nanosecond, + } + } + + pub const fn to_arrow(self) -> arrow_schema::TimeUnit { + match self { + Self::Second => arrow_schema::TimeUnit::Second, + Self::Millisecond => arrow_schema::TimeUnit::Millisecond, + Self::Microsecond => arrow_schema::TimeUnit::Microsecond, + Self::Nanosecond => arrow_schema::TimeUnit::Nanosecond, + } + } + + const fn nanos_per_unit(self) -> i64 { + match self { + Self::Second => 1_000_000_000, + Self::Millisecond => 1_000_000, + Self::Microsecond => 1_000, + Self::Nanosecond => 1, + } + } + + /// Converts `value` from `self` into `target` only when the conversion is + /// exact and lossless (no `i64` overflow and no sub-unit truncation). + pub fn convert_exact(self, value: i64, target: Self) -> Option { + let src_ns = self.nanos_per_unit(); + let dst_ns = target.nanos_per_unit(); + if src_ns == dst_ns { + Some(value) + } else if src_ns > dst_ns { + let scale = src_ns / dst_ns; + value.checked_mul(scale) + } else { + let scale = dst_ns / src_ns; + if value % scale != 0 { + return None; + } + value.checked_div(scale) + } + } +} + +/// Provenance metadata certifying how a manifest [`Column`]'s statistics were +/// derived from Parquet row-group footers. +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct StatsProvenance { + /// `true` iff every non-empty row group in the Parquet file either + /// contributed valid min/max statistics or was provably all-null. + pub complete_row_groups: bool, + /// `true` iff every contributing row group reported both `min_is_exact` + /// and `max_is_exact` with a Parquet-defined total sort order (never + /// truncated byte arrays or `INT96`). + pub exact_min_max: bool, + /// Physical/logical timestamp unit recorded in Parquet column metadata, + /// if the column is a timestamp. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub timestamp_unit: Option, +} + /// Column statistics are used to track statistics for a column in a given file. /// This is similar to and derived from parquet statistics. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] @@ -205,6 +311,118 @@ pub struct Column { pub null_count: Option, pub uncompressed_size: u64, pub compressed_size: u64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub stats_provenance: Option, +} + +impl Column { + /// Returns certified `(min, max)` timestamp values converted losslessly into + /// `target_unit`. Returns `None` when provenance is missing, row groups are + /// incomplete, bounds are non-exact, `timestamp_unit` is absent, bounds are + /// inverted, or unit conversion would overflow or truncate. + pub fn certified_timestamp_bounds( + &self, + target_unit: arrow_schema::TimeUnit, + ) -> Option<(i64, i64)> { + let prov = self.stats_provenance?; + if !(prov.complete_row_groups && prov.exact_min_max) { + return None; + } + let src_unit = prov.timestamp_unit?; + let TypedStatistics::Int(stats) = self.stats.as_ref()? else { + return None; + }; + if stats.min > stats.max { + return None; + } + let dst_unit = ManifestTimeUnit::from_arrow(target_unit); + let min = src_unit.convert_exact(stats.min, dst_unit)?; + let max = src_unit.convert_exact(stats.max, dst_unit)?; + if min > max { + return None; + } + Some((min, max)) + } + + /// Converts this column's manifest statistics into DataFusion `Precision::Exact` + /// `(min, max)` scalars ONLY when backed by complete, exact provenance. + /// + /// Floating-point columns (`Float32`, `Float64`) are always withheld (`None`): + /// Parquet omits `NaN` from min/max statistics, and DataFusion 55's Parquet + /// opener substitutes a constant literal when `min == max && null_count == 0` + /// are `Precision::Exact`, which would silently turn `[7.0, NaN]` into + /// `[7.0, 7.0]`. + pub fn certified_min_max_as_scalar( + &self, + data_type: &DataType, + ) -> Option<(ScalarValue, ScalarValue)> { + let prov = self.stats_provenance?; + if !(prov.complete_row_groups && prov.exact_min_max) { + return None; + } + let stats = self.stats.as_ref()?; + let (min, max) = match (stats, data_type) { + (TypedStatistics::Bool(s), DataType::Boolean) => { + if s.min && !s.max { + return None; + } + ( + ScalarValue::Boolean(Some(s.min)), + ScalarValue::Boolean(Some(s.max)), + ) + } + (TypedStatistics::Int(s), DataType::Int32) => { + if s.min > s.max { + return None; + } + let min = i32::try_from(s.min).ok()?; + let max = i32::try_from(s.max).ok()?; + (ScalarValue::Int32(Some(min)), ScalarValue::Int32(Some(max))) + } + (TypedStatistics::Int(s), DataType::Int64) => { + if s.min > s.max { + return None; + } + ( + ScalarValue::Int64(Some(s.min)), + ScalarValue::Int64(Some(s.max)), + ) + } + (TypedStatistics::Int(_), DataType::Timestamp(target_unit, tz)) => { + let (min, max) = self.certified_timestamp_bounds(*target_unit)?; + match target_unit { + arrow_schema::TimeUnit::Second => ( + ScalarValue::TimestampSecond(Some(min), tz.clone()), + ScalarValue::TimestampSecond(Some(max), tz.clone()), + ), + arrow_schema::TimeUnit::Millisecond => ( + ScalarValue::TimestampMillisecond(Some(min), tz.clone()), + ScalarValue::TimestampMillisecond(Some(max), tz.clone()), + ), + arrow_schema::TimeUnit::Microsecond => ( + ScalarValue::TimestampMicrosecond(Some(min), tz.clone()), + ScalarValue::TimestampMicrosecond(Some(max), tz.clone()), + ), + arrow_schema::TimeUnit::Nanosecond => ( + ScalarValue::TimestampNanosecond(Some(min), tz.clone()), + ScalarValue::TimestampNanosecond(Some(max), tz.clone()), + ), + } + } + (TypedStatistics::String(s), DataType::Utf8) => { + if s.min > s.max { + return None; + } + ( + ScalarValue::Utf8(Some(s.min.clone())), + ScalarValue::Utf8(Some(s.max.clone())), + ) + } + (_, DataType::Float32 | DataType::Float64) => return None, + _ => return None, + }; + Some((min, max)) + } } impl TryFrom<&Statistics> for TypedStatistics { @@ -229,10 +447,21 @@ impl TryFrom<&Statistics> for TypedStatistics { min: *stats.min_opt().expect("Int64 stats min not set"), max: *stats.max_opt().expect("Int64 stats max not set"), }), - Statistics::Int96(stats) => TypedStatistics::Int(Int64Type { - min: int96_to_i64_nanos(stats.min_opt().expect("Int96 stats min not set")), - max: int96_to_i64_nanos(stats.max_opt().expect("Int96 stats max not set")), - }), + Statistics::Int96(stats) => { + let min = int96_to_i64_nanos(stats.min_opt().expect("Int96 stats min not set")) + .ok_or_else(|| { + parquet::errors::ParquetError::General( + "Int96 stats min overflow".to_string(), + ) + })?; + let max = int96_to_i64_nanos(stats.max_opt().expect("Int96 stats max not set")) + .ok_or_else(|| { + parquet::errors::ParquetError::General( + "Int96 stats max overflow".to_string(), + ) + })?; + TypedStatistics::Int(Int64Type { min, max }) + } Statistics::Float(stats) => { let min = *stats.min_opt().expect("Float32 stats min not set") as f64; let max = *stats.max_opt().expect("Float32 stats max not set") as f64; @@ -285,20 +514,22 @@ impl TryFrom<&Statistics> for TypedStatistics { // Int96 is a deprecated timestamp format used by legacy Impala files // Convert to i64 nanoseconds since Unix epoch for statistics -fn int96_to_i64_nanos(int96: &parquet::data_type::Int96) -> i64 { +fn int96_to_i64_nanos(int96: &parquet::data_type::Int96) -> Option { const JULIAN_DAY_OF_EPOCH: i64 = 2_440_588; // Julian day for 1970-01-01 - const SECONDS_PER_DAY: i64 = 86_400; - const NANOS_PER_SECOND: i64 = 1_000_000_000; + const NANOS_PER_DAY: i64 = 86_400 * 1_000_000_000; // Extract nanoseconds from first 8 bytes (little-endian) - let nanos_of_day = int96.data()[0] as i64 | ((int96.data()[1] as i64) << 32); + let nanos_of_day_u64 = u64::from(int96.data()[0]) | (u64::from(int96.data()[1]) << 32); + let nanos_of_day = i64::try_from(nanos_of_day_u64).ok()?; // Extract Julian day from last 4 bytes - let julian_day = int96.data()[2] as i64; + let julian_day = i64::from(int96.data()[2]); - // Convert to nanoseconds since Unix epoch - let days_since_epoch = julian_day - JULIAN_DAY_OF_EPOCH; - days_since_epoch * SECONDS_PER_DAY * NANOS_PER_SECOND + nanos_of_day + // Convert to nanoseconds since Unix epoch with checked arithmetic + let days_since_epoch = julian_day.checked_sub(JULIAN_DAY_OF_EPOCH)?; + days_since_epoch + .checked_mul(NANOS_PER_DAY)? + .checked_add(nanos_of_day) } #[cfg(test)] @@ -461,4 +692,233 @@ mod tests { let result = stats.min_max_as_scalar(&DataType::Float64); assert!(result.is_some()); } + + #[test] + fn min_max_as_scalar_supports_timestamps_and_rejects_invalid_int_ranges() { + use arrow_schema::TimeUnit; + use std::sync::Arc; + + let stats = TypedStatistics::Int(Int64Type { + min: 1_700_000_000_000, + max: 1_700_000_060_000, + }); + assert_eq!( + stats + .clone() + .min_max_as_scalar(&DataType::Timestamp(TimeUnit::Millisecond, None)), + Some(( + ScalarValue::TimestampMillisecond(Some(1_700_000_000_000), None), + ScalarValue::TimestampMillisecond(Some(1_700_000_060_000), None), + )) + ); + let tz: Option> = Some(Arc::from("UTC")); + assert_eq!( + stats + .clone() + .min_max_as_scalar(&DataType::Timestamp(TimeUnit::Microsecond, tz.clone())), + Some(( + ScalarValue::TimestampMicrosecond(Some(1_700_000_000_000), tz.clone()), + ScalarValue::TimestampMicrosecond(Some(1_700_000_060_000), tz), + )) + ); + + let inverted = TypedStatistics::Int(Int64Type { min: 20, max: 10 }); + assert!( + inverted + .clone() + .min_max_as_scalar(&DataType::Timestamp(TimeUnit::Millisecond, None)) + .is_none() + ); + assert!(inverted.min_max_as_scalar(&DataType::Int64).is_none()); + + let out_of_i32 = TypedStatistics::Int(Int64Type { + min: 0, + max: i64::from(i32::MAX) + 1, + }); + assert!(out_of_i32.min_max_as_scalar(&DataType::Int32).is_none()); + } + + #[test] + fn column_stats_provenance_deserializes_legacy_json_and_round_trips() { + let legacy_json = r#"{ + "name": "p_timestamp", + "stats": { "Int": { "min": 1000, "max": 2000 } }, + "uncompressed_size": 100, + "compressed_size": 50 + }"#; + let legacy: Column = serde_json::from_str(legacy_json).unwrap(); + assert!(legacy.stats_provenance.is_none()); + assert!(legacy.null_count.is_none()); + assert!( + legacy + .certified_min_max_as_scalar(&DataType::Timestamp( + arrow_schema::TimeUnit::Millisecond, + None + )) + .is_none() + ); + // Omitted when None + let serialized_legacy = serde_json::to_string(&legacy).unwrap(); + assert!(!serialized_legacy.contains("stats_provenance")); + + let certified = Column { + name: "p_timestamp".to_owned(), + stats: Some(TypedStatistics::Int(Int64Type { + min: 1_000, + max: 2_000, + })), + null_count: Some(0), + uncompressed_size: 100, + compressed_size: 50, + stats_provenance: Some(StatsProvenance { + complete_row_groups: true, + exact_min_max: true, + timestamp_unit: Some(ManifestTimeUnit::Millisecond), + }), + }; + let json = serde_json::to_string(&certified).unwrap(); + let decoded: Column = serde_json::from_str(&json).unwrap(); + assert_eq!(decoded.stats_provenance, certified.stats_provenance); + } + + #[test] + fn certified_min_max_withholds_floats_and_enforces_provenance_and_timestamp_units() { + use arrow_schema::TimeUnit; + + let verified = |timestamp_unit: Option| { + Some(StatsProvenance { + complete_row_groups: true, + exact_min_max: true, + timestamp_unit, + }) + }; + let make_col = |stats, prov| Column { + name: "c".to_owned(), + stats: Some(stats), + null_count: Some(0), + uncompressed_size: 0, + compressed_size: 0, + stats_provenance: prov, + }; + + // Float32 and Float64 are ALWAYS withheld, even when complete & exact and min == max. + let float_col = make_col( + TypedStatistics::Float(Float64Type { min: 7.0, max: 7.0 }), + verified(None), + ); + assert!( + float_col + .certified_min_max_as_scalar(&DataType::Float64) + .is_none() + ); + assert!( + float_col + .certified_min_max_as_scalar(&DataType::Float32) + .is_none() + ); + + // Incomplete row groups or non-exact min/max are rejected. + let incomplete = make_col( + TypedStatistics::Int(Int64Type { min: 1, max: 10 }), + Some(StatsProvenance { + complete_row_groups: false, + exact_min_max: true, + timestamp_unit: None, + }), + ); + assert!( + incomplete + .certified_min_max_as_scalar(&DataType::Int64) + .is_none() + ); + + let truncated_str = make_col( + TypedStatistics::String(Utf8Type { + min: "aaa".to_owned(), + max: "zzz".to_owned(), + }), + Some(StatsProvenance { + complete_row_groups: true, + exact_min_max: false, + timestamp_unit: None, + }), + ); + assert!( + truncated_str + .certified_min_max_as_scalar(&DataType::Utf8) + .is_none() + ); + + // Timestamp requires verified timestamp_unit and lossless conversion. + let no_ts_unit = make_col( + TypedStatistics::Int(Int64Type { + min: 1_000, + max: 2_000, + }), + verified(None), + ); + assert!( + no_ts_unit + .certified_min_max_as_scalar(&DataType::Timestamp(TimeUnit::Millisecond, None)) + .is_none() + ); + + // Lossy Nanosecond -> Millisecond rejected. + let lossy_ns = make_col( + TypedStatistics::Int(Int64Type { + min: 1_700_000_000_000_000_001, + max: 1_700_000_060_000_000_000, + }), + verified(Some(ManifestTimeUnit::Nanosecond)), + ); + assert!( + lossy_ns + .certified_min_max_as_scalar(&DataType::Timestamp(TimeUnit::Millisecond, None)) + .is_none() + ); + + // Overflowing Second -> Nanosecond rejected. + let overflow_sec = make_col( + TypedStatistics::Int(Int64Type { + min: 0, + max: i64::MAX / 10, + }), + verified(Some(ManifestTimeUnit::Second)), + ); + assert!( + overflow_sec + .certified_min_max_as_scalar(&DataType::Timestamp(TimeUnit::Nanosecond, None)) + .is_none() + ); + + // Exact lossless Millisecond -> Microsecond succeeds. + let ms_col = make_col( + TypedStatistics::Int(Int64Type { + min: 1_000, + max: 2_000, + }), + verified(Some(ManifestTimeUnit::Millisecond)), + ); + assert_eq!( + ms_col.certified_min_max_as_scalar(&DataType::Timestamp(TimeUnit::Microsecond, None)), + Some(( + ScalarValue::TimestampMicrosecond(Some(1_000_000), None), + ScalarValue::TimestampMicrosecond(Some(2_000_000), None), + )) + ); + + // Inverted boolean/string/int rejected. + let inv_bool = make_col( + TypedStatistics::Bool(BoolType { + min: true, + max: false, + }), + verified(None), + ); + assert!( + inv_bool + .certified_min_max_as_scalar(&DataType::Boolean) + .is_none() + ); + } } diff --git a/src/catalog/manifest.rs b/src/catalog/manifest.rs index f8dd8ee92..34c89541d 100644 --- a/src/catalog/manifest.rs +++ b/src/catalog/manifest.rs @@ -24,15 +24,22 @@ use std::{ }; use dashmap::DashMap; -use parquet::file::{ - metadata::{ParquetMetaData, RowGroupMetaData, SortingColumn}, - reader::FileReader, - statistics::Statistics, +use parquet::{ + basic::{ + ConvertedType, LogicalType, SortOrder as ParquetSortOrder, TimeUnit as ParquetTimeUnit, + Type as PhysicalType, + }, + file::{ + metadata::{ParquetMetaData, RowGroupMetaData, SortingColumn}, + reader::FileReader, + statistics::Statistics, + }, + schema::types::ColumnDescriptor, }; use crate::metastore::metastore_traits::MetastoreObject; -use super::column::Column; +use super::column::{Column, ManifestTimeUnit, StatsProvenance, TypedStatistics}; #[derive( Debug, @@ -413,36 +420,165 @@ fn sort_order( sort_orders } +fn extract_timestamp_unit(descr: &ColumnDescriptor) -> Option { + if let Some(LogicalType::Timestamp(ts)) = descr.logical_type_ref() { + return Some(match ts.unit { + ParquetTimeUnit::MILLIS => ManifestTimeUnit::Millisecond, + ParquetTimeUnit::MICROS => ManifestTimeUnit::Microsecond, + ParquetTimeUnit::NANOS => ManifestTimeUnit::Nanosecond, + }); + } + match descr.converted_type() { + ConvertedType::TIMESTAMP_MILLIS => return Some(ManifestTimeUnit::Millisecond), + ConvertedType::TIMESTAMP_MICROS => return Some(ManifestTimeUnit::Microsecond), + _ => {} + } + if descr.physical_type() == PhysicalType::INT96 { + return Some(ManifestTimeUnit::Nanosecond); + } + None +} + +struct ColumnStatsAccumulator { + name: String, + stats: Option, + poisoned: bool, + complete_row_groups: bool, + exact_min_max: bool, + timestamp_unit: Option, + null_count: Option, + uncompressed_size: u64, + compressed_size: u64, + row_groups_seen: usize, +} + fn column_statistics(row_groups: &[RowGroupMetaData]) -> HashMap { - let mut columns: HashMap = HashMap::new(); + let mut accumulators: HashMap = HashMap::new(); + let total_row_groups = row_groups.len(); + for row_group in row_groups { + let rg_rows = u64::try_from(row_group.num_rows()).ok(); for col in row_group.columns() { - let col_name = col.column_descr().path().string(); - if let Some(entry) = columns.get_mut(&col_name) { - entry.compressed_size += col.compressed_size() as u64; - entry.uncompressed_size += col.uncompressed_size() as u64; - entry.null_count = entry - .null_count - .zip(col.statistics().and_then(Statistics::null_count_opt)) - .and_then(|(current, other)| current.checked_add(other)); - if let Some(other) = col.statistics().and_then(|stats| stats.try_into().ok()) { - entry.stats = entry.stats.clone().and_then(|this| this.update(other)); - } - } else { - columns.insert( - col_name.clone(), - Column { + let descr = col.column_descr(); + let col_name = descr.path().string(); + let col_ts_unit = extract_timestamp_unit(descr); + let is_defined_order = descr.physical_type() != PhysicalType::INT96 + && descr.sort_order() != ParquetSortOrder::UNDEFINED; + let col_null_count = col.statistics().and_then(Statistics::null_count_opt); + let uncompressed = u64::try_from(col.uncompressed_size()).unwrap_or(0); + let compressed = u64::try_from(col.compressed_size()).unwrap_or(0); + + let entry = + accumulators + .entry(col_name.clone()) + .or_insert_with(|| ColumnStatsAccumulator { name: col_name, - stats: col.statistics().and_then(|stats| stats.try_into().ok()), - null_count: col.statistics().and_then(Statistics::null_count_opt), - uncompressed_size: col.uncompressed_size() as u64, - compressed_size: col.compressed_size() as u64, - }, - ); + stats: None, + poisoned: false, + complete_row_groups: true, + exact_min_max: is_defined_order, + timestamp_unit: col_ts_unit, + null_count: Some(0), + uncompressed_size: 0, + compressed_size: 0, + row_groups_seen: 0, + }); + + entry.row_groups_seen += 1; + entry.uncompressed_size = entry.uncompressed_size.saturating_add(uncompressed); + entry.compressed_size = entry.compressed_size.saturating_add(compressed); + entry.null_count = entry + .null_count + .zip(col_null_count) + .and_then(|(current, other)| current.checked_add(other)); + + if entry.timestamp_unit != col_ts_unit { + entry.timestamp_unit = None; + entry.stats = None; + entry.poisoned = true; + entry.complete_row_groups = false; + entry.exact_min_max = false; + } + if !is_defined_order { + entry.exact_min_max = false; + } + + let Some(rg_rows) = rg_rows else { + entry.stats = None; + entry.poisoned = true; + entry.complete_row_groups = false; + continue; + }; + if rg_rows == 0 { + continue; + } + + // A non-empty row group that is provably all-null contributes no + // non-null values and preserves row-group completeness. + let provably_all_null = col_null_count == Some(rg_rows); + if provably_all_null { + continue; + } + + match col.statistics() { + Some(pq_stats) => match TypedStatistics::try_from(pq_stats) { + Ok(typed) => { + let rg_exact = + is_defined_order && pq_stats.min_is_exact() && pq_stats.max_is_exact(); + entry.exact_min_max &= rg_exact; + if !entry.poisoned { + match entry.stats.take() { + None => entry.stats = Some(typed), + Some(existing) => match existing.update(typed) { + Some(merged) => entry.stats = Some(merged), + None => { + entry.stats = None; + entry.poisoned = true; + entry.complete_row_groups = false; + } + }, + } + } + } + Err(_) => { + // Non-empty, not provably all-null, yet lacks usable min/max stats. + entry.stats = None; + entry.poisoned = true; + entry.complete_row_groups = false; + } + }, + None => { + entry.stats = None; + entry.poisoned = true; + entry.complete_row_groups = false; + } } } } - columns + + accumulators + .into_iter() + .map(|(name, mut acc)| { + if acc.row_groups_seen != total_row_groups { + acc.stats = None; + acc.null_count = None; + acc.complete_row_groups = false; + } + let col = Column { + name: acc.name, + stats: acc.stats, + null_count: acc.null_count, + uncompressed_size: acc.uncompressed_size, + compressed_size: acc.compressed_size, + stats_provenance: Some(StatsProvenance { + complete_row_groups: acc.complete_row_groups, + exact_min_max: acc.exact_min_max, + timestamp_unit: acc.timestamp_unit, + }), + }; + (name, col) + }) + .collect() } #[cfg(test)] @@ -463,6 +599,7 @@ mod codec_tests { null_count: None, uncompressed_size: 1024, compressed_size: 512, + stats_provenance: None, }) .collect(), sort_order_id: Vec::new(), @@ -929,4 +1066,239 @@ mod handoff_and_batch_tests { serde_json::to_value(&manifest).unwrap() ); } + + #[test] + fn multi_row_group_missing_stats_invalidates_column_and_complete_flag() { + use parquet::{ + data_type::Int64Type as ParquetInt64Type, + file::{ + metadata::ParquetMetaData, + properties::{EnabledStatistics, WriterProperties}, + writer::SerializedFileWriter, + }, + schema::parser::parse_message_type, + }; + + let write_single_rg = |vals: &[i64], stats: EnabledStatistics| -> ParquetMetaData { + let schema = + Arc::new(parse_message_type("message test { OPTIONAL INT64 val; }").unwrap()); + let mut bytes = Vec::new(); + let props = WriterProperties::builder() + .set_statistics_enabled(stats) + .build(); + let mut writer = + SerializedFileWriter::new(&mut bytes, schema, Arc::new(props)).unwrap(); + let mut rg = writer.next_row_group().unwrap(); + let mut col = rg.next_column().unwrap().unwrap(); + col.typed::() + .write_batch(vals, Some(&[1, 1]), None) + .unwrap(); + col.close().unwrap(); + rg.close().unwrap(); + writer.close().unwrap() + }; + + let rg1_meta = write_single_rg(&[10, 20], EnabledStatistics::Chunk); + let rg2_meta = write_single_rg(&[30, 40], EnabledStatistics::None); + assert!(rg1_meta.row_group(0).column(0).statistics().is_some()); + assert!(rg2_meta.row_group(0).column(0).statistics().is_none()); + + let combined = ParquetMetaData::new( + rg1_meta.file_metadata().clone(), + vec![rg1_meta.row_group(0).clone(), rg2_meta.row_group(0).clone()], + ); + + let manifest_file = + create_from_parquet_metadata("test.parquet".to_owned(), 1024, &combined); + let col = manifest_file + .columns + .iter() + .find(|c| c.name == "val") + .unwrap(); + assert!(col.stats.is_none(), "missing RG2 stats must poison stats"); + let prov = col.stats_provenance.expect("provenance set"); + assert!(!prov.complete_row_groups); + assert!(col.certified_min_max_as_scalar(&DataType::Int64).is_none()); + } + + #[test] + fn all_null_row_group_preserves_completeness_and_merges_other_row_group_stats() { + let schema = Arc::new(Schema::new(vec![ArrowField::new( + "val", + DataType::Int64, + true, + )])); + let all_null_batch = RecordBatch::try_new( + schema.clone(), + vec![Arc::new(Int64Array::from(vec![None, None, None]))], + ) + .unwrap(); + let non_null_batch = RecordBatch::try_new( + schema.clone(), + vec![Arc::new(Int64Array::from(vec![Some(10), Some(50), None]))], + ) + .unwrap(); + + let file = NamedTempFile::new().unwrap(); + let props = WriterProperties::builder() + .set_max_row_group_row_count(Some(3)) + .build(); + let mut writer = ArrowWriter::try_new(file.reopen().unwrap(), schema, Some(props)).unwrap(); + writer.write(&all_null_batch).unwrap(); + writer.write(&non_null_batch).unwrap(); + let metadata = writer.close().unwrap(); + assert_eq!(metadata.num_row_groups(), 2); + + let manifest_file = + create_from_parquet_metadata("all_null_rg.parquet".to_owned(), 512, &metadata); + let col = manifest_file + .columns + .iter() + .find(|c| c.name == "val") + .unwrap(); + let prov = col.stats_provenance.expect("provenance set"); + assert!(prov.complete_row_groups); + assert!(prov.exact_min_max); + assert_eq!(col.null_count, Some(4)); + assert_eq!( + col.certified_min_max_as_scalar(&DataType::Int64), + Some(( + datafusion::scalar::ScalarValue::Int64(Some(10)), + datafusion::scalar::ScalarValue::Int64(Some(50)), + )) + ); + } + + #[test] + fn truncated_parquet_string_stats_set_exact_min_max_false() { + let schema = Arc::new(Schema::new(vec![ArrowField::new( + "msg", + DataType::Utf8, + false, + )])); + let long_a = format!("{}_a", "x".repeat(80)); + let long_z = format!("{}_z", "x".repeat(80)); + let batch = RecordBatch::try_new( + schema.clone(), + vec![Arc::new(StringArray::from(vec![ + long_a.as_str(), + long_z.as_str(), + ]))], + ) + .unwrap(); + + let file = NamedTempFile::new().unwrap(); + let props = WriterProperties::builder() + .set_statistics_truncate_length(Some(16)) + .build(); + let mut writer = ArrowWriter::try_new(file.reopen().unwrap(), schema, Some(props)).unwrap(); + writer.write(&batch).unwrap(); + let metadata = writer.close().unwrap(); + + let manifest_file = + create_from_parquet_metadata("trunc.parquet".to_owned(), 512, &metadata); + let col = manifest_file + .columns + .iter() + .find(|c| c.name == "msg") + .unwrap(); + let prov = col.stats_provenance.expect("provenance set"); + assert!(prov.complete_row_groups); + assert!( + !prov.exact_min_max, + "truncated string stats must not be marked exact" + ); + assert!(col.certified_min_max_as_scalar(&DataType::Utf8).is_none()); + } + + #[test] + fn parquet_timestamp_units_and_int96_provenance() { + use arrow_array::{ + TimestampMicrosecondArray, TimestampMillisecondArray, TimestampNanosecondArray, + }; + use arrow_schema::TimeUnit; + use parquet::{ + data_type::{Int96, Int96Type}, + file::writer::SerializedFileWriter, + schema::parser::parse_message_type, + }; + + let schema = Arc::new(Schema::new(vec![ + ArrowField::new( + "ts_ms", + DataType::Timestamp(TimeUnit::Millisecond, None), + false, + ), + ArrowField::new( + "ts_us", + DataType::Timestamp(TimeUnit::Microsecond, None), + false, + ), + ArrowField::new( + "ts_ns", + DataType::Timestamp(TimeUnit::Nanosecond, None), + false, + ), + ])); + let batch = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(TimestampMillisecondArray::from(vec![1_000, 2_000])), + Arc::new(TimestampMicrosecondArray::from(vec![1_000_000, 2_000_000])), + Arc::new(TimestampNanosecondArray::from(vec![ + 1_000_000_000, + 2_000_000_000, + ])), + ], + ) + .unwrap(); + let file = NamedTempFile::new().unwrap(); + let mut writer = ArrowWriter::try_new(file.reopen().unwrap(), schema, None).unwrap(); + writer.write(&batch).unwrap(); + let metadata = writer.close().unwrap(); + let mf = create_from_parquet_metadata("ts.parquet".to_owned(), 512, &metadata); + for (name, expected_unit) in [ + ("ts_ms", ManifestTimeUnit::Millisecond), + ("ts_us", ManifestTimeUnit::Microsecond), + ("ts_ns", ManifestTimeUnit::Nanosecond), + ] { + let col = mf.columns.iter().find(|c| c.name == name).unwrap(); + let prov = col.stats_provenance.unwrap(); + assert!(prov.complete_row_groups); + assert!(prov.exact_min_max); + assert_eq!(prov.timestamp_unit, Some(expected_unit)); + } + + // INT96 physical type records Nanosecond unit and forces exact_min_max = false. + let int96_schema = + Arc::new(parse_message_type("message m { REQUIRED INT96 ts; }").unwrap()); + let mut bytes = Vec::new(); + let mut writer = SerializedFileWriter::new( + &mut bytes, + int96_schema, + Arc::new(WriterProperties::builder().build()), + ) + .unwrap(); + let mut rg = writer.next_row_group().unwrap(); + let mut col_writer = rg.next_column().unwrap().unwrap(); + let mut v = Int96::new(); + v.set_data(0, 0, 2_440_588); // 1970-01-01T00:00:00Z + col_writer + .typed::() + .write_batch(&[v], None, None) + .unwrap(); + col_writer.close().unwrap(); + rg.close().unwrap(); + let int96_meta = writer.close().unwrap(); + let int96_mf = create_from_parquet_metadata("int96.parquet".to_owned(), 256, &int96_meta); + let ts_col = int96_mf.columns.iter().find(|c| c.name == "ts").unwrap(); + let prov = ts_col.stats_provenance.unwrap(); + assert_eq!(prov.timestamp_unit, Some(ManifestTimeUnit::Nanosecond)); + assert!(!prov.exact_min_max); + assert!( + ts_col + .certified_min_max_as_scalar(&DataType::Timestamp(TimeUnit::Millisecond, None)) + .is_none() + ); + } } diff --git a/src/event/format/json.rs b/src/event/format/json.rs index 4236a6807..ba499e704 100644 --- a/src/event/format/json.rs +++ b/src/event/format/json.rs @@ -20,15 +20,23 @@ #![allow(deprecated)] use anyhow::anyhow; -use arrow_array::RecordBatch; +use arrow::compute::kernels::cast_utils::{Parser, string_to_datetime}; +use arrow_array::builder::{ + BooleanBuilder, Date32Builder, Float32Builder, Float64Builder, Int8Builder, Int16Builder, + Int32Builder, Int64Builder, StringBuilder, TimestampMillisecondBuilder, UInt8Builder, + UInt16Builder, UInt32Builder, UInt64Builder, +}; +use arrow_array::types::Date32Type; +use arrow_array::{ArrayRef, RecordBatch, RecordBatchOptions}; use arrow_json::reader::{ReaderBuilder, infer_json_schema_from_iterator}; -use arrow_schema::{DataType, Field, Fields, Schema}; +use arrow_schema::{DataType, Field, Fields, Schema, TimeUnit}; use chrono::{DateTime, NaiveDate, NaiveDateTime, Utc}; use datafusion::arrow::util::bit_util::round_upto_multiple_of_64; use itertools::Itertools; use rayon::prelude::*; use serde_json::Value; use std::{ + borrow::Borrow, collections::{HashMap, HashSet}, hash::{DefaultHasher, Hash, Hasher}, sync::Arc, @@ -37,6 +45,10 @@ use tracing::{error, info_span}; use super::EventFormat; use super::{detect_schema_conflicts, rename_conflicting_fields_in_json}; +use crate::utils::json::{ + flatten::{FlattenBudget, FlattenCost, string_json_len}, + strict::{FlatRowSink, parse_flat_rows}, +}; use crate::{handlers::TelemetryType, metadata::SchemaVersion, storage::StreamType}; pub struct Event { @@ -155,11 +167,28 @@ impl<'a> DateTotals<'a> { } } -fn decode_rows(data: &[impl serde::Serialize], schema: Arc) -> anyhow::Result { +fn decode_rows( + data: &[impl Borrow + serde::Serialize], + schema: Arc, +) -> anyhow::Result { let _span = info_span!("json_to_recordbatch", record_count = data.len()).entered(); if data.is_empty() { return Err(anyhow!("JSON batch must contain at least one event")); } + // Scalar columns are built straight from the values. Anything else, and + // every batch that does not decode, is left to Arrow's JSON decoder. + if let Some(rb) = decode_rows_direct(data, &schema) { + return Ok(rb); + } + decode_rows_arrow_json(data, schema) +} + +/// Decodes rows with Arrow's JSON decoder, which first copies every row onto +/// its tape. Handles every type and reports the decoding errors. +fn decode_rows_arrow_json( + data: &[impl serde::Serialize], + schema: Arc, +) -> anyhow::Result { let mut reader = ReaderBuilder::new(schema) .with_batch_size(round_upto_multiple_of_64(data.len())) .with_coerce_primitive(false) @@ -172,6 +201,528 @@ fn decode_rows(data: &[impl serde::Serialize], schema: Arc) -> anyhow::R } } +/// The Arrow builder of a scalar column that is built without Arrow's JSON +/// decoder. +/// +/// Every `append_*` takes a JSON scalar the way the decoder takes it for the +/// column's type (with `coerce_primitive` off), and returns `None` for +/// everything it does not take in exactly that way: a value the decoder +/// rejects, and one it converts by a rule not repeated here, such as a string +/// in a number column or a float in an integer one. The caller then gives the +/// whole batch to the decoder. +enum ColumnBuilder { + Boolean(BooleanBuilder), + Int8(Int8Builder), + Int16(Int16Builder), + Int32(Int32Builder), + Int64(Int64Builder), + UInt8(UInt8Builder), + UInt16(UInt16Builder), + UInt32(UInt32Builder), + UInt64(UInt64Builder), + Float32(Float32Builder), + Float64(Float64Builder), + Utf8(StringBuilder), + TimestampMillis(TimestampMillisecondBuilder), + Date32(Date32Builder), +} + +/// Runs `$body` with `$builder` bound to the builder of any variant +macro_rules! each_builder { + ($column:expr, $builder:ident => $body:expr) => { + match $column { + ColumnBuilder::Boolean($builder) => $body, + ColumnBuilder::Int8($builder) => $body, + ColumnBuilder::Int16($builder) => $body, + ColumnBuilder::Int32($builder) => $body, + ColumnBuilder::Int64($builder) => $body, + ColumnBuilder::UInt8($builder) => $body, + ColumnBuilder::UInt16($builder) => $body, + ColumnBuilder::UInt32($builder) => $body, + ColumnBuilder::UInt64($builder) => $body, + ColumnBuilder::Float32($builder) => $body, + ColumnBuilder::Float64($builder) => $body, + ColumnBuilder::Utf8($builder) => $body, + ColumnBuilder::TimestampMillis($builder) => $body, + ColumnBuilder::Date32($builder) => $body, + } + }; +} + +impl ColumnBuilder { + /// `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 { + Some(match data_type { + DataType::Boolean => Self::Boolean(BooleanBuilder::with_capacity(rows)), + DataType::Int8 => Self::Int8(Int8Builder::with_capacity(rows)), + DataType::Int16 => Self::Int16(Int16Builder::with_capacity(rows)), + DataType::Int32 => Self::Int32(Int32Builder::with_capacity(rows)), + DataType::Int64 => Self::Int64(Int64Builder::with_capacity(rows)), + DataType::UInt8 => Self::UInt8(UInt8Builder::with_capacity(rows)), + DataType::UInt16 => Self::UInt16(UInt16Builder::with_capacity(rows)), + DataType::UInt32 => Self::UInt32(UInt32Builder::with_capacity(rows)), + DataType::UInt64 => Self::UInt64(UInt64Builder::with_capacity(rows)), + DataType::Float32 => Self::Float32(Float32Builder::with_capacity(rows)), + DataType::Float64 => Self::Float64(Float64Builder::with_capacity(rows)), + DataType::Utf8 => Self::Utf8(StringBuilder::with_capacity(rows, rows * 16)), + DataType::Timestamp(TimeUnit::Millisecond, None) => { + Self::TimestampMillis(TimestampMillisecondBuilder::with_capacity(rows)) + } + DataType::Date32 => Self::Date32(Date32Builder::with_capacity(rows)), + _ => return None, + }) + } + + fn append_nulls(&mut self, rows: usize) { + each_builder!(self, builder => builder.append_nulls(rows)) + } + + fn append_bool(&mut self, value: bool) -> Option<()> { + match self { + Self::Boolean(builder) => builder.append_value(value), + _ => return None, + } + Some(()) + } + + /// A non-negative integer. An integer column takes it when it is in the + /// range of the column's type. + fn append_u64(&mut self, value: u64) -> Option<()> { + match self { + Self::Int8(builder) => builder.append_value(value.try_into().ok()?), + Self::Int16(builder) => builder.append_value(value.try_into().ok()?), + Self::Int32(builder) => builder.append_value(value.try_into().ok()?), + Self::Int64(builder) => builder.append_value(value.try_into().ok()?), + Self::UInt8(builder) => builder.append_value(value.try_into().ok()?), + Self::UInt16(builder) => builder.append_value(value.try_into().ok()?), + Self::UInt32(builder) => builder.append_value(value.try_into().ok()?), + Self::UInt64(builder) => builder.append_value(value), + Self::Float64(builder) => builder.append_value(value as f64), + _ => return None, + } + Some(()) + } + + /// A negative integer + fn append_i64(&mut self, value: i64) -> Option<()> { + match self { + Self::Int8(builder) => builder.append_value(value.try_into().ok()?), + Self::Int16(builder) => builder.append_value(value.try_into().ok()?), + Self::Int32(builder) => builder.append_value(value.try_into().ok()?), + Self::Int64(builder) => builder.append_value(value), + Self::Float64(builder) => builder.append_value(value as f64), + _ => return None, + } + Some(()) + } + + /// A number that is not an integer of 64 bits. The decoder truncates it + /// for an integer column, which is not repeated here. + fn append_f64(&mut self, value: f64) -> Option<()> { + match self { + Self::Float32(builder) => builder.append_value(value as f32), + Self::Float64(builder) => builder.append_value(value), + _ => return None, + } + Some(()) + } + + /// A string of rows that have been through `to_data` + fn append_str(&mut self, value: &str) -> Option<()> { + match self { + Self::Utf8(builder) => builder.append_value(value), + Self::TimestampMillis(builder) => { + builder.append_value(string_to_datetime(&Utc, value).ok()?.timestamp_millis()) + } + Self::Date32(builder) => builder.append_value(Date32Type::parse(value)?), + _ => return None, + } + Some(()) + } + + /// `append_str` for a string that has not been through `to_data`: taken + /// only when `known_scalar_schema` accepts it for an existing field of a + /// dynamic schema. That is narrower for a timestamp, and never holds for + /// a date. + fn append_known_str(&mut self, value: &str) -> Option<()> { + match self { + Self::Utf8(builder) => builder.append_value(value), + Self::TimestampMillis(builder) => { + builder.append_value(super::parse_compatible_timestamp(value)?.timestamp_millis()) + } + _ => return None, + } + Some(()) + } + + fn finish(&mut self) -> ArrayRef { + each_builder!(self, builder => Arc::new(builder.finish())) + } +} + +struct DirectColumn<'a> { + field: &'a Arc, + builder: ColumnBuilder, + /// 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 + key_len: usize, +} + +/// The columns of a batch that is built row by row +struct DirectColumns<'a> { + columns: Vec>, + by_name: rustc_hash::FxHashMap<&'a str, usize>, + /// The columns of the previous row's keys, in the order of the keys. Rows + /// of a batch mostly repeat their keys in order, which then resolves a key + /// by one comparison instead of a hash lookup. + order: Vec, + /// Keys of the current row resolved so far + position: usize, + /// Rows completed + row: usize, +} + +impl<'a> DirectColumns<'a> { + fn with_capacity(columns: usize) -> Self { + Self { + columns: Vec::with_capacity(columns), + by_name: rustc_hash::FxHashMap::with_capacity_and_hasher(columns, Default::default()), + order: Vec::with_capacity(columns), + position: 0, + row: 0, + } + } + + /// Adds a column for `field`, expected to hold `rows` rows. `None` when + /// its type is not built here or a column of its name exists. + fn add(&mut self, field: &'a Arc, rows: usize) -> Option { + let builder = ColumnBuilder::new(field.data_type(), rows)?; + let column = self.columns.len(); + if self.by_name.insert(field.name().as_str(), column).is_some() { + return None; + } + self.columns.push(DirectColumn { + field, + builder, + rows: 0, + key_len: string_json_len(field.name())?, + }); + Some(column) + } + + /// The column of the next key of the current row, if there is one + fn find(&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(), + } + } + + /// 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<()> { + if self.columns[column].rows > self.row { + return None; + } + match self.order.get_mut(self.position) { + Some(predicted) => *predicted = column, + None => self.order.push(column), + } + self.position += 1; + Some(()) + } + + /// The builder of `column`, for the value of the current row + fn value(&mut self, column: usize) -> &mut ColumnBuilder { + let row = self.row; + let column = &mut self.columns[column]; + if column.rows < row { + column.builder.append_nulls(row - column.rows); + } + column.rows = row + 1; + &mut column.builder + } + + fn end_row(&mut self) { + self.row += 1; + self.position = 0; + } + + /// 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()); + } + // 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() + } +} + +/// 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. +/// +/// `None` unless every field of `schema` is of a type `ColumnBuilder` builds +/// and every row is an object of the schema's fields with a scalar the +/// builder takes for each. This covers the batches `known_scalar_schema` +/// 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. +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())?; + } + 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)?; + 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()) +} + +/// A batch built from the bytes of a request body, and the length of its +/// rows as a compact JSON array, which is what the request is accounted as. +#[derive(Debug)] +pub(crate) struct FlatJsonBatch { + pub rb: RecordBatch, + pub origin_size: u64, +} + +/// Builds the record batch of a JSON body straight from its bytes, in one +/// pass and without a `serde_json::Value`, for the usual body: an object, or +/// an array of objects, whose keys are all existing scalar fields of the +/// stream with values of their types. +/// +/// `Some` is exactly what the general path produces for the body of a stream +/// without partitions, with `LogSource::Json` and a flatten level that leaves +/// flat rows alone, all of which the caller checks: +/// +/// - the body parses as a `StrictValue` (valid JSON, no duplicate keys), +/// - `flat_batch_len` takes it and charges `budget` the same, the batch's +/// `origin_size` being the length it returns, +/// - `known_scalar_schema` takes its rows, so no field is added, renamed or +/// retyped, and the batch has the fields the rows name, sorted by name, +/// - Arrow's JSON decoder decodes the rows to the same columns. +/// +/// The batch is the one before `add_parseable_fields`. `None`, with `budget` +/// as it was, for every other body, including every body the general path +/// rejects, such as one naming the reserved `p_timestamp`: it then decides. +/// Only streams of schema version 1 with a dynamic schema are taken, as the +/// other ones accept and convert values by rules of their own. +pub(crate) fn try_parse_flat_json_bytes_to_recordbatch( + bytes: &[u8], + stream_schema: &HashMap>, + schema_version: SchemaVersion, + static_schema_flag: bool, + budget: &mut FlattenBudget, +) -> Option { + if schema_version != SchemaVersion::V1 || static_schema_flag { + return None; + } + let first_non_ws = bytes + .iter() + .copied() + .find(|b| !matches!(b, b' ' | b'\t' | b'\r' | b'\n')); + let expected_rows = if first_non_ws == Some(b'{') { + 1 + } else { + // Bound aggregate initial builder capacity across wide schemas so + // wide arrays do not preallocate tens of megabytes up front. + let max_for_width = (65_536 / stream_schema.len().max(1)).clamp(1, 4096); + (bytes.len() / 128).clamp(1, max_for_width) + }; + let mut sink = FlatBatchSink { + stream_schema, + columns: DirectColumns::with_capacity(16), + expected_rows, + row_len: 0, + rows_len: 0, + budget: budget.clone(), + }; + parse_flat_rows(bytes, &mut sink)?; + let rows = sink.columns.row; + if rows == 0 { + return None; + } + // `[`, `]` and the commas between the rows + let origin_size = (2 + (rows - 1)).checked_add(sink.rows_len)?; + let mut fields: Vec> = sink + .columns + .columns + .iter() + .map(|column| column.field.clone()) + .collect(); + fields.sort_unstable_by(|a, b| a.name().cmp(b.name())); + let rb = sink.columns.finish(Arc::new(Schema::new(fields)))?; + *budget = sink.budget; + Some(FlatJsonBatch { + rb, + origin_size: origin_size as u64, + }) +} + +/// Builds the columns of `try_parse_flat_json_bytes_to_recordbatch`, adding +/// one for each field of the stream when a row first names it, and measures +/// the rows as `flat_batch_len` does. +struct FlatBatchSink<'a> { + stream_schema: &'a HashMap>, + columns: DirectColumns<'a>, + /// Rows to size a new column for + expected_rows: usize, + /// Length of the keys and values of the current row so far, as compact + /// JSON with the `:` of each key + row_len: usize, + /// Compact JSON length of all completed rows + rows_len: usize, + budget: FlattenBudget, +} + +impl FlatBatchSink<'_> { + /// The builder for the value of `column` in the current row, whose + /// compact JSON length is `len` + fn value(&mut self, column: usize, len: usize) -> Option<&mut ColumnBuilder> { + self.row_len = self.row_len.checked_add(len)?; + Some(self.columns.value(column)) + } +} + +/// Length of an integer written in decimal +fn decimal_len(value: u64) -> usize { + value.checked_ilog10().map_or(1, |log| log as usize + 1) +} + +/// Length of a finite float as serde_json writes it +fn float_json_len(value: f64) -> usize { + struct Counter(usize); + impl std::io::Write for Counter { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.0 += buf.len(); + Ok(buf.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + let mut counter = Counter(0); + // Writing a float to a counter cannot fail + let _ = serde_json::to_writer(&mut counter, &value); + counter.0 +} + +impl FlatRowSink for FlatBatchSink<'_> { + type Column = usize; + + fn key(&mut self, key: &str) -> Option { + let column = match self.columns.find(key) { + Some(column) => column, + None => { + // The checks `known_scalar_schema` makes of a key. A reserved + // key is left to the general path, which rejects it. + if key.starts_with('@') || key == crate::event::DEFAULT_TIMESTAMP_KEY { + return None; + } + let (name, field) = self.stream_schema.get_key_value(key)?; + if field.name() != name { + return None; + } + self.columns.add(field, self.expected_rows)? + } + }; + self.columns.take_key(column)?; + // `"key":` + self.row_len = self + .row_len + .checked_add(self.columns.columns[column].key_len)? + .checked_add(1)?; + Some(column) + } + + fn null(&mut self, column: usize) -> Option<()> { + self.value(column, "null".len())?.append_nulls(1); + Some(()) + } + + fn bool(&mut self, column: usize, value: bool) -> Option<()> { + let len = if value { "true".len() } else { "false".len() }; + self.value(column, len)?.append_bool(value) + } + + fn u64(&mut self, column: usize, value: u64) -> Option<()> { + self.value(column, decimal_len(value))?.append_u64(value) + } + + fn i64(&mut self, column: usize, value: i64) -> Option<()> { + let len = 1 + decimal_len(value.unsigned_abs()); + self.value(column, len)?.append_i64(value) + } + + fn f64(&mut self, column: usize, value: f64) -> Option<()> { + self.value(column, float_json_len(value))?.append_f64(value) + } + + fn str(&mut self, column: usize, value: &str) -> Option<()> { + self.value(column, string_json_len(value)?)? + .append_known_str(value) + } + + fn end_row(&mut self) -> Option<()> { + // `{`, `}` and the commas between the keys + let keys = self.columns.position; + let len = (2 + keys.saturating_sub(1)).checked_add(self.row_len)?; + // As `flat_batch_len` charges a row + if len > self.budget.limits().max_bytes_per_request { + return None; + } + self.budget + .charge_event(FlattenCost { + rows: 1, + bytes: len, + }) + .ok()?; + self.rows_len = self.rows_len.checked_add(len)?; + self.row_len = 0; + self.columns.end_row(); + Some(()) + } +} + impl Event { pub fn new(json: Value, p_timestamp: DateTime) -> Self { Self { json, p_timestamp } @@ -2434,3 +2985,1090 @@ mod partition_batching_tests { ); } } + +/// Differential tests of the batches built without Arrow's JSON decoder: +/// `decode_rows_direct` against the decoder on the same rows, and +/// `try_parse_flat_json_bytes_to_recordbatch` against what the general path +/// makes of the same body. +#[cfg(test)] +mod direct_batch_tests { + use arrow_array::{ + Array, BooleanArray, Float64Array, Int64Array, StringArray, TimestampMillisecondArray, + }; + use proptest::prelude::*; + use serde_json::json; + + use super::*; + use crate::utils::json::flatten::{FlattenLimits, pipeline_flattening_owned}; + use crate::utils::json::strict::{StrictValue, flat_batch_len}; + + const MILLIS: DataType = DataType::Timestamp(TimeUnit::Millisecond, None); + + /// A stream with a field of every type that is built directly, some that + /// are left to Arrow, the reserved field and a field that is not nullable + fn stream_schema() -> HashMap> { + let nullable = [ + ("s", DataType::Utf8), + ("s2", DataType::Utf8), + ("we\"ird\n", DataType::Utf8), + ("f", DataType::Float64), + ("f32", DataType::Float32), + ("i", DataType::Int64), + ("i32", DataType::Int32), + ("i16", DataType::Int16), + ("i8", DataType::Int8), + ("u", DataType::UInt64), + ("u32", DataType::UInt32), + ("u16", DataType::UInt16), + ("u8", DataType::UInt8), + ("b", DataType::Boolean), + ("ts", MILLIS), + ("d", DataType::Date32), + // Left to Arrow + ("f16", DataType::Float16), + ("ts_ns", DataType::Timestamp(TimeUnit::Nanosecond, None)), + ( + "ts_tz", + DataType::Timestamp(TimeUnit::Millisecond, Some("+05:30".into())), + ), + ( + "tags", + DataType::List(Arc::new(Field::new("item", DataType::Utf8, true))), + ), + (crate::event::DEFAULT_TIMESTAMP_KEY, MILLIS), + ] + .into_iter() + .map(|(name, data_type)| Field::new(name, data_type, true)); + nullable + .chain([Field::new("req", DataType::Utf8, false)]) + .map(|field| (field.name().clone(), Arc::new(field))) + .collect() + } + + fn direct(bytes: &[u8], schema: &HashMap>) -> Option { + try_parse_flat_json_bytes_to_recordbatch( + bytes, + schema, + SchemaVersion::V1, + false, + &mut FlattenBudget::new(FlattenLimits::DEFAULT), + ) + } + + /// What the general path makes of a body that is a flat batch, for a + /// stream of schema version 1 with a dynamic schema and no partitions, a + /// `LogSource::Json` and a flatten level of 2 or more: `stage_json` up to + /// the batch that `add_parseable_fields` extends, decoded by Arrow's JSON + /// decoder. The steps are taken one by one, as `stage_json` reads the + /// flatten level from the server's options, which tests share. + struct General { + rb: RecordBatch, + origin_size: u64, + charged: FlattenCost, + /// The body took every shortcut of the general path and has no field + /// of a type left to Arrow: the direct path has to take it + direct: bool, + } + + fn general_path( + bytes: &[u8], + schema: &HashMap>, + limits: FlattenLimits, + ) -> Result { + let json = serde_json::from_slice::(bytes) + .map_err(|e| e.to_string())? + .into_inner(); + let mut budget = FlattenBudget::new(limits); + // `process_non_partitioned`. A body that is not a flat batch within + // the limits is flattened, or refused, by a pipeline of no interest + // here: the direct path has to leave it alone. + let origin_size = flat_batch_len(&json, &mut budget) + .ok_or("not a flat batch within the flatten limits")?; + let rows = match json { + Value::Array(rows) => rows, + row => vec![row], + }; + let known = known_scalar_schema(&rows, schema, SchemaVersion::V1, false).is_some(); + let (data, fields, is_first) = Event::new(Value::Array(rows), Utc::now()) + .to_data(schema, None, SchemaVersion::V1, false, true) + .map_err(|e| e.to_string())?; + if fields + .iter() + .any(|field| field.name() == crate::event::DEFAULT_TIMESTAMP_KEY) + { + return Err("reserved field".to_owned()); + } + if data.is_empty() { + return Err("JSON batch must contain at least one event".to_owned()); + } + let built = fields + .iter() + .all(|field| ColumnBuilder::new(field.data_type(), 0).is_some()); + let rb = decode_rows_arrow_json(&data, Arc::new(Schema::new(fields))) + .map_err(|e| e.to_string())?; + Ok(General { + rb, + origin_size, + charged: budget.used(), + direct: known && !is_first && built, + }) + } + + /// Checks the direct path against the general one for a body, and returns + /// whether the direct path took it. + fn check_body( + bytes: &[u8], + schema: &HashMap>, + limits: FlattenLimits, + ) -> bool { + let body = String::from_utf8_lossy(bytes); + let mut budget = FlattenBudget::new(limits); + let direct = try_parse_flat_json_bytes_to_recordbatch( + bytes, + schema, + SchemaVersion::V1, + false, + &mut budget, + ); + match (direct, general_path(bytes, schema, limits)) { + (Some(direct), Ok(general)) => { + assert!(general.direct, "taken off the shortcuts: {body}"); + assert_eq!(direct.rb, general.rb, "{body}"); + assert_eq!(direct.origin_size, general.origin_size, "{body}"); + assert_eq!(budget.used(), general.charged, "{body}"); + true + } + (Some(_), Err(error)) => panic!("took a body that is rejected ({error}): {body}"), + (None, general) => { + if let Ok(general) = general { + assert!(!general.direct, "gave up on a body it takes: {body}"); + } + assert_eq!(budget.used(), FlattenCost::default(), "{body}"); + false + } + } + } + + /// Checks `decode_rows` and `decode_rows_direct` against Arrow's JSON + /// decoder for rows and a schema, and returns whether the rows were built + /// directly. + fn check_rows(rows: &[Value], schema: Arc) -> bool { + let arrow = decode_rows_arrow_json(rows, schema.clone()).map_err(|e| e.to_string()); + let direct = decode_rows_direct(rows, &schema); + if let Some(direct) = &direct { + assert_eq!(Ok(direct), arrow.as_ref(), "{rows:?}"); + } + if !rows.is_empty() { + assert_eq!( + decode_rows(rows, schema).map_err(|e| e.to_string()), + arrow, + "{rows:?}" + ); + } + direct.is_some() + } + + struct Rng(u64); + + impl Rng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + + fn below(&mut self, n: usize) -> usize { + (self.next() % n as u64) as usize + } + + fn one_in(&mut self, n: usize) -> bool { + self.below(n) == 0 + } + + fn pick<'a>(&mut self, items: &[&'a str]) -> &'a str { + items[self.below(items.len())] + } + } + + // JSON literals, as they are written in a body + const STRINGS: &[&str] = &[ + r#""""#, + r#""plain""#, + r#""with space and \"quotes\" and \\ and \/""#, + r#""雪 \n\t\r\b\f \u0000 \u001f \u00e9 \ud83d\ude00 é""#, + r#""12""#, + r#""true""#, + ]; + const TIMESTAMPS: &[&str] = &[ + r#""2025-01-02T03:04:05Z""#, + r#""2025-01-02T03:04:05.123Z""#, + r#""2025-01-02T03:04:05.123456789z""#, + r#""2025-01-02T03:04:05.1234567891234Z""#, + r#""2025-01-02 03:04:05""#, + r#""2025-01-02T03:04:05""#, + r#""2025-01-02T03:04:05.5""#, + r#""2025-01-02T03:04:05+05:30""#, + r#""2025-01-02T03:04:05.25-08:00""#, + r#""2025-01-02t03:04:05Z""#, + r#""1970-01-01T00:00:00Z""#, + r#""1969-12-31T23:59:59.999Z""#, + r#""9999-12-31T23:59:59Z""#, + r#""0000-01-01T00:00:00Z""#, + r#""2024-02-29T00:00:00Z""#, + r#""2025-02-29T00:00:00Z""#, + r#""2025-01-02T03:04:60Z""#, + r#""2025-01-02T24:00:00Z""#, + r#""2025-01-02T03:04:05+10:99""#, + r#""2025-01-02T03:04:05+0530""#, + r#""2025-01-02T03:04:05 +05:30""#, + r#""2025-01-02T03:04:05 UTC""#, + r#""2025-01-02T03:04:05 America/New_York""#, + r#""2025-01-02""#, + r#""2025-01-02T030405""#, + r#""2025-1-2""#, + r#""Thu, 02 Jan 2025 03:04:05 +0000""#, + r#""2025-01-02T03:04:05.Z""#, + r#""2025\u002d01-02T03:04:05Z""#, + r#""not a time""#, + ]; + const INTEGERS: &[&str] = &[ + "0", + "1", + "-1", + "7", + "127", + "128", + "-128", + "-129", + "255", + "256", + "32767", + "32768", + "-32768", + "-32769", + "65535", + "65536", + "2147483647", + "2147483648", + "-2147483648", + "-2147483649", + "4294967295", + "4294967296", + "9007199254740993", + "9223372036854775807", + "9223372036854775808", + "-9223372036854775808", + "-9223372036854775809", + "18446744073709551615", + "18446744073709551616", + "13835058055282163713", + "123456789012345678901234567890", + ]; + const FLOATS: &[&str] = &[ + "-0", + "0.0", + "-0.0", + "1.0", + "1.5", + "-2.25", + "0.1", + "0.30000000000000004", + "1e3", + "1E-3", + "100.0e-2", + "1.0E+2", + "3.4028235e38", + "3.5e38", + "1e39", + "1.7976931348623157e308", + "5e-324", + "1e-400", + "123456.789e3", + "16777217.0", + ]; + const BROKEN: &[&str] = &[ + "NaN", + "Infinity", + "-Infinity", + "1e400", + "01", + "1.", + "+1", + "tru", + "'s'", + "\"\\x\"", + "\"\\ud800\"", + "", + ]; + const NESTED: &[&str] = &["[]", "[1]", "{}", r#"{"a":1}"#, r#"["x"]"#]; + // Keys of `stream_schema`, the usual ones first + const KEYS: &[&str] = &[ + "s", + "s2", + "f", + "i", + "b", + "ts", + "u", + "f32", + "i8", + "i16", + "i32", + "u8", + "u16", + "u32", + "we\"ird\n", + "d", + "req", + "f16", + "ts_ns", + "ts_tz", + "tags", + "p_timestamp", + ]; + + /// A literal for a value of the field, mostly one of its type + fn literal(rng: &mut Rng, key: &str) -> &'static str { + if rng.one_in(12) { + return "null"; + } + if rng.one_in(25) { + let any = [STRINGS, TIMESTAMPS, INTEGERS, FLOATS, &["true", "false"]]; + let pool = any[rng.below(any.len())]; + return rng.pick(pool); + } + match key { + "s" | "s2" | "we\"ird\n" | "req" => { + if rng.one_in(4) { + rng.pick(TIMESTAMPS) + } else { + rng.pick(STRINGS) + } + } + "f" | "f32" | "f16" => { + if rng.one_in(2) { + rng.pick(FLOATS) + } else { + rng.pick(INTEGERS) + } + } + "b" => rng.pick(&["true", "false"]), + "ts" | "ts_ns" | "ts_tz" | "p_timestamp" => rng.pick(TIMESTAMPS), + "d" => rng.pick(&[ + r#""2025-01-02""#, + r#""2025-1-2""#, + r#""2025-01-02T03:04:05Z""#, + ]), + "tags" => rng.pick(NESTED), + _ => rng.pick(INTEGERS), + } + } + + /// A key as a JSON string, sometimes spelled with an escape + fn key_literal(rng: &mut Rng, key: &str) -> String { + if rng.one_in(15) { + let mut chars = key.chars(); + let first = chars.next().unwrap(); + return format!("\"\\u{:04x}{}\"", first as u32, json_tail(chars.as_str())); + } + serde_json::to_string(key).unwrap() + } + + fn json_tail(rest: &str) -> String { + let quoted = serde_json::to_string(rest).unwrap(); + quoted[1..quoted.len() - 1].to_owned() + } + + /// The text of a body: mostly flat rows of the usual fields, with the + /// faults that take a body off the direct path mixed in + fn body(rng: &mut Rng) -> String { + let space = |rng: &mut Rng| { + if rng.one_in(6) { + [" ", "\n", "\t", " \r\n "][rng.below(4)] + } else { + "" + } + }; + // Most bodies stay with the usual fields, to be taken directly + let usual = !rng.one_in(4); + let key_count = if usual { 7 } else { KEYS.len() }; + let faulty = rng.one_in(3); + let rows = if rng.one_in(30) { 0 } else { 1 + rng.below(5) }; + let single = rows == 1 && rng.one_in(3); + let mut text = String::new(); + text.push_str(space(rng)); + if !single { + text.push('['); + } + for row in 0..rows { + if row > 0 { + text.push(','); + } + text.push_str(space(rng)); + if faulty && rng.one_in(40) { + text.push_str(rng.pick(&["1", "null", "\"row\"", "[]", "[{}]"])); + continue; + } + text.push('{'); + let mut first = true; + let mut used: Vec<&str> = Vec::new(); + for _ in 0..rng.below(key_count + 2) { + let key = KEYS[rng.below(key_count)]; + // A repeated key only as a fault + if used.contains(&key) && !(faulty && rng.one_in(10)) { + continue; + } + used.push(key); + if !first { + text.push(','); + } + first = false; + text.push_str(space(rng)); + if faulty && rng.one_in(30) { + text.push_str(rng.pick(&[ + "\"unknown\"", + "\"@s\"", + "\"@timestamp\"", + "\"S\"", + "\"\"", + "\"p_timestamp\"", + ])); + } else { + text.push_str(&key_literal(rng, key)); + } + text.push_str(space(rng)); + text.push(':'); + text.push_str(space(rng)); + if faulty && rng.one_in(30) { + text.push_str(rng.pick(NESTED)); + } else if faulty && rng.one_in(60) { + text.push_str(rng.pick(BROKEN)); + } else { + text.push_str(literal(rng, key)); + } + text.push_str(space(rng)); + } + text.push('}'); + text.push_str(space(rng)); + } + if !single { + text.push(']'); + } + text.push_str(space(rng)); + if faulty && rng.one_in(25) { + text.push_str(rng.pick(&["x", "{}", "]", ",", "1", "\0"])); + } + if faulty && rng.one_in(25) && !text.is_empty() { + let mut end = rng.below(text.len()); + while !text.is_char_boundary(end) { + end -= 1; + } + text.truncate(end); + } + text + } + + #[test] + fn flat_bodies_match_the_general_path() { + let schema = stream_schema(); + let mut rng = Rng(0x9E37_79B9_7F4A_7C15); + let (mut taken, mut total) = (0, 0); + for _ in 0..30_000 { + let body = body(&mut rng); + total += 1; + taken += check_body(body.as_bytes(), &schema, FlattenLimits::DEFAULT) as usize; + } + // The generator is of no use if it rarely yields a body that is taken + assert!( + taken * 8 > total, + "{taken} of {total} bodies taken directly" + ); + } + + #[test] + fn flat_bodies_are_charged_to_the_budget_like_the_general_path() { + let schema = stream_schema(); + let mut rng = Rng(0xD1B5_4A32_D192_ED03); + let (mut taken, mut refused) = (0, 0); + for _ in 0..20_000 { + let body = body(&mut rng); + let limits = FlattenLimits { + max_rows_per_event: [0, 1, usize::MAX][rng.below(3).max(rng.below(3))], + max_rows_per_request: [0, 1, 2, 3, usize::MAX][rng.below(5)], + max_bytes_per_request: [0, 2, 20, 60, 150, usize::MAX][rng.below(6)], + }; + let unlimited = check_body(body.as_bytes(), &schema, FlattenLimits::DEFAULT); + let limited = check_body(body.as_bytes(), &schema, limits); + taken += limited as usize; + refused += (unlimited && !limited) as usize; + } + assert!( + taken > 500 && refused > 500, + "{taken} taken, {refused} refused" + ); + } + + #[test] + fn rows_are_decoded_like_arrow_decodes_them() { + let stream = stream_schema(); + let mut sorted: Vec<_> = stream.values().cloned().collect(); + sorted.sort_by(|a, b| a.name().cmp(b.name())); + // Every field that is built directly, nullable or not + let built: Vec<_> = sorted + .iter() + .filter(|field| ColumnBuilder::new(field.data_type(), 0).is_some()) + .cloned() + .collect(); + let nullable: Vec<_> = built + .iter() + .filter(|field| field.is_nullable()) + .cloned() + .collect(); + let mut rng = Rng(0x2545_F491_4F6C_DD1D); + let (mut direct, mut known_direct, mut total) = (0, 0, 0); + for _ in 0..30_000 { + let body = body(&mut rng); + let Ok(json) = serde_json::from_str::(&body) else { + continue; + }; + let rows = match json.into_inner() { + Value::Array(rows) => rows, + row => vec![row], + }; + total += 1; + direct += check_rows(&rows, Arc::new(Schema::new(nullable.clone()))) as usize; + check_rows(&rows, Arc::new(Schema::new(built.clone()))); + check_rows(&rows, Arc::new(Schema::new(sorted.clone()))); + // The schema the rows are decoded with on the known-schema path + for version in [SchemaVersion::V0, SchemaVersion::V1] { + for static_schema in [false, true] { + let Some(fields) = known_scalar_schema(&rows, &stream, version, static_schema) + else { + continue; + }; + let handled = fields + .iter() + .all(|field| ColumnBuilder::new(field.data_type(), 0).is_some()); + let schema = Arc::new(Schema::new(fields)); + let arrow = decode_rows_arrow_json(&rows, schema.clone()); + let is_direct = check_rows(&rows, schema); + known_direct += is_direct as usize; + // A static schema casts strings, which is left to Arrow + if handled && !static_schema && arrow.is_ok() { + assert!(is_direct, "left to Arrow: {body}"); + } + } + } + } + assert!(direct * 20 > total, "{direct} of {total} built directly"); + assert!(known_direct * 2 > total, "{known_direct} of {total}"); + } + + #[test] + fn every_scalar_type_is_built_from_bytes() { + let schema = stream_schema(); + let body = br#"[ + {"s": "a\n\u00e9", "f": 1.5, "f32": 0.1, "i": -9223372036854775808, "i32": -2147483648, + "i16": 32767, "i8": -128, "u": 18446744073709551615, "u32": 4294967295, "u16": 65535, + "u8": 255, "b": true, "ts": "2025-01-02T03:04:05.678Z"}, + {"ts": "2025-01-02 03:04:05", "b": false, "f": 3, "s": null}, + {}, + {"f": -7, "s2": "only here", "ts": "2025-01-02T03:04:05+05:30", "i": 12} + ]"#; + assert!(check_body(body, &schema, FlattenLimits::DEFAULT)); + let batch = direct(body, &schema).unwrap(); + let rb = &batch.rb; + assert_eq!(rb.num_rows(), 4); + // The fields the rows name, sorted, each the stream's own + let names: Vec<_> = rb + .schema() + .fields() + .iter() + .map(|f| f.name().clone()) + .collect(); + assert_eq!( + names, + [ + "b", "f", "f32", "i", "i16", "i32", "i8", "s", "s2", "ts", "u", "u16", "u32", "u8" + ] + ); + for field in rb.schema().fields() { + assert!(Arc::ptr_eq(field, &schema[field.name()])); + } + let column = |name: &str| rb.column_by_name(name).unwrap().clone(); + assert_eq!( + column("s").as_any().downcast_ref::().unwrap(), + &StringArray::from(vec![Some("a\n\u{e9}"), None, None, None]) + ); + assert_eq!( + column("s2").as_any().downcast_ref::().unwrap(), + &StringArray::from(vec![None, None, None, Some("only here")]) + ); + assert_eq!( + column("f").as_any().downcast_ref::().unwrap(), + &Float64Array::from(vec![Some(1.5), Some(3.0), None, Some(-7.0)]) + ); + assert_eq!( + column("i").as_any().downcast_ref::().unwrap(), + &Int64Array::from(vec![Some(i64::MIN), None, None, Some(12)]) + ); + assert_eq!( + column("b").as_any().downcast_ref::().unwrap(), + &BooleanArray::from(vec![Some(true), Some(false), None, None]) + ); + assert_eq!( + column("ts") + .as_any() + .downcast_ref::() + .unwrap(), + &TimestampMillisecondArray::from(vec![ + Some(1_735_787_045_678), + Some(1_735_787_045_000), + None, + Some(1_735_767_245_000), + ]) + ); + // The rows as a compact JSON array + let rows: Value = serde_json::from_slice(body).unwrap(); + assert_eq!( + batch.origin_size, + serde_json::to_vec(&rows).unwrap().len() as u64 + ); + } + + #[test] + fn a_single_object_is_a_batch_of_one_row() { + let schema = stream_schema(); + for (body, len) in [ + (&br#" {"s":"x","i":1} "#[..], r#"[{"s":"x","i":1}]"#.len()), + (b"{}", "[{}]".len()), + (b"[{},{}]", "[{},{}]".len()), + ] { + assert!(check_body(body, &schema, FlattenLimits::DEFAULT)); + assert_eq!(direct(body, &schema).unwrap().origin_size, len as u64); + } + // No columns, yet a row each + assert_eq!(direct(b"[{},{}]", &schema).unwrap().rb.num_rows(), 2); + assert_eq!(direct(b"[{},{}]", &schema).unwrap().rb.num_columns(), 0); + } + + #[test] + fn bodies_off_the_direct_path_are_left_to_the_general_path() { + let schema = stream_schema(); + for body in [ + // Not strict JSON + r#"[{"s":"a","s":"b"}]"#, + r#"[{"s":"a","\u0073":"b"}]"#, + r#"[{"s":"a"},{"i":1,"f":2,"i":3}]"#, + r#"[{"s":"a"}"#, + r#"[{"s":"a"}] x"#, + r#"[{"s":"a"}]{}"#, + r#"[{"s":"a",}]"#, + r#"[{"f":NaN}]"#, + r#"[{"f":Infinity}]"#, + r#"[{"f":1e400}]"#, + "", + // Not rows + "[]", + "1", + "null", + r#""s""#, + "[1]", + r#"[{"s":"a"},null]"#, + r#"[[{"s":"a"}]]"#, + // Keys that add, rename or are refused + r#"[{"new":1}]"#, + r#"[{"@s":"a"}]"#, + r#"[{"S":"a"}]"#, + r#"[{"p_timestamp":"2025-01-02T03:04:05Z"}]"#, + r#"[{"p_timestamp":null}]"#, + // Nested values + r#"[{"s":{"a":1}}]"#, + r#"[{"s":[]}]"#, + r#"[{"tags":["a"]}]"#, + r#"[{"s":"a","i":{}}]"#, + // Values that are not of the field's type + r#"[{"s":1}]"#, + r#"[{"s":true}]"#, + r#"[{"i":"1"}]"#, + r#"[{"i":1.5}]"#, + r#"[{"i":-0}]"#, + r#"[{"i":9223372036854775808}]"#, + r#"[{"u":-1}]"#, + r#"[{"b":"true"}]"#, + r#"[{"b":1}]"#, + r#"[{"f":"1.5"}]"#, + r#"[{"f32":1}]"#, + r#"[{"ts":1735787045678}]"#, + r#"[{"ts":"2025-01-02"}]"#, + r#"[{"ts":"Thu, 02 Jan 2025 03:04:05 +0000"}]"#, + r#"[{"ts":"2025-01-02T03:04:05+10:99"}]"#, + r#"[{"ts":"yesterday"}]"#, + r#"[{"d":"2025-01-02"}]"#, + // Values Arrow's decoder rejects for the field's type + r#"[{"i8":128}]"#, + r#"[{"i16":-32769}]"#, + r#"[{"i32":2147483648}]"#, + r#"[{"u8":256}]"#, + r#"[{"u16":65536}]"#, + r#"[{"u32":4294967296}]"#, + r#"[{"s":"a"},{"req":null}]"#, + r#"[{"req":"a"},{"s":"a"}]"#, + // Types left to Arrow, even for a null + r#"[{"f16":1.5}]"#, + r#"[{"f16":null}]"#, + r#"[{"ts_ns":"2025-01-02T03:04:05Z"}]"#, + r#"[{"ts_tz":"2025-01-02T03:04:05Z"}]"#, + ] { + assert!( + !check_body(body.as_bytes(), &schema, FlattenLimits::DEFAULT), + "{body}" + ); + } + // Not UTF-8 + assert!(!check_body( + b"[{\"s\":\"\xff\"}]", + &schema, + FlattenLimits::DEFAULT + )); + // Each of them only for the fault it has + for body in [ + r#"[{"s":"a","s2":"b"}]"#, + r#"[{"s":"a"},{"i":1,"f":2,"i8":3}]"#, + r#"[{"f":1e300}]"#, + r#"[{"i":0}]"#, + r#"[{"i":9223372036854775807}]"#, + r#"[{"u":0}]"#, + r#"[{"f32":1.0}]"#, + r#"[{"ts":"2025-01-02T03:04:05+10:59"}]"#, + r#"[{"d":null}]"#, + r#"[{"i8":127}]"#, + r#"[{"u32":4294967295}]"#, + r#"[{"s":"a","req":"b"},{"req":""}]"#, + ] { + assert!( + check_body(body.as_bytes(), &schema, FlattenLimits::DEFAULT), + "{body}" + ); + } + } + + #[test] + fn only_dynamic_streams_of_schema_version_1_are_taken() { + let schema = stream_schema(); + let body = br#"[{"s":"a","i":1}]"#; + for (version, static_schema, taken) in [ + (SchemaVersion::V1, false, true), + (SchemaVersion::V1, true, false), + (SchemaVersion::V0, false, false), + (SchemaVersion::V0, true, false), + ] { + let mut budget = FlattenBudget::new(FlattenLimits::DEFAULT); + let batch = try_parse_flat_json_bytes_to_recordbatch( + body, + &schema, + version, + static_schema, + &mut budget, + ); + assert_eq!(batch.is_some(), taken); + assert_eq!(budget.used().rows, taken as usize); + } + } + + #[test] + fn a_body_over_the_flatten_limits_is_left_to_the_general_path() { + let schema = stream_schema(); + let body = br#"[{"s":"a"},{"s":"b"},{"s":"c"}]"#; + let row = r#"{"s":"a"}"#.len(); + let limits = |rows_per_event, rows, bytes| FlattenLimits { + max_rows_per_event: rows_per_event, + max_rows_per_request: rows, + max_bytes_per_request: bytes, + }; + for (limits, taken) in [ + (limits(1, 3, 3 * row), true), + (limits(0, 3, 3 * row), false), + (limits(1, 2, 3 * row), false), + (limits(1, 3, 3 * row - 1), false), + (limits(1, 3, row - 1), false), + ] { + assert_eq!(check_body(body, &schema, limits), taken, "{limits:?}"); + // A request over a limit is refused by the general path, which + // charges its flattening to the same budget + if !taken { + let json: Value = serde_json::from_slice(body).unwrap(); + let error = + pipeline_flattening_owned(json, &mut FlattenBudget::new(limits)).unwrap_err(); + assert!(error.is_limit_exceeded(), "{error}"); + } + } + // What was charged before stays charged, and adds up + let mut budget = FlattenBudget::new(limits(1, 4, usize::MAX)); + for (taken, rows) in [(true, 3), (false, 3)] { + let batch = try_parse_flat_json_bytes_to_recordbatch( + body, + &schema, + SchemaVersion::V1, + false, + &mut budget, + ); + assert_eq!(batch.is_some(), taken); + assert_eq!(budget.used().rows, rows); + } + } + + #[test] + fn rows_of_every_scalar_type_are_decoded_directly() { + let fields: Vec<_> = stream_schema() + .into_values() + .filter(|field| ColumnBuilder::new(field.data_type(), 0).is_some()) + .filter(|field| field.is_nullable()) + .sorted_by(|a, b| a.name().cmp(b.name())) + .collect(); + let schema = Arc::new(Schema::new(fields)); + let rows = vec![ + json!({"s": "a", "f": 1.5, "f32": 0.1, "i": i64::MIN, "i32": i32::MIN, "i16": i16::MAX, + "i8": i8::MIN, "u": u64::MAX, "u32": u32::MAX, "u16": u16::MAX, "u8": u8::MAX, + "b": true, "ts": "2025-01-02T03:04:05.678Z", "d": "2025-01-02"}), + json!({"f": 3, "ts": "2025-01-02", "s": null}), + json!({}), + json!({"f": u64::MAX, "u": 0, "d": "1969-12-31"}), + ]; + assert!(check_rows(&rows, schema.clone())); + // References decode like values + let references: Vec<&Value> = rows.iter().collect(); + assert_eq!( + decode_rows_direct(&references, &schema), + decode_rows_direct(&rows, &schema) + ); + // What the builders do not repeat goes to Arrow, which may decode it + for (row, decodes) in [ + (json!({"i": 1.5}), true), + (json!({"i": "12"}), true), + (json!({"f": "1.5"}), true), + (json!({"f32": 1}), true), + (json!({"ts": 1_735_787_045_678_i64}), true), + (json!({"unknown": 1}), true), + (json!({"i8": 128}), false), + (json!({"u": -1}), false), + (json!({"s": 1}), false), + (json!({"b": "true"}), false), + (json!({"ts": "yesterday"}), false), + (json!({"d": "yesterday"}), false), + (json!({"s": {"nested": 1}}), false), + (json!("row"), false), + ] { + let rows = [rows[0].clone(), row]; + assert!(!check_rows(&rows, schema.clone()), "{rows:?}"); + assert_eq!( + decode_rows_arrow_json(&rows, schema.clone()).is_ok(), + decodes, + "{rows:?}" + ); + } + } + + /// 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 + /// (`values`), or built from the bytes (`new`). + #[ignore = "release-profile microbenchmark; select the section with HUNT_BENCH_SECTION"] + #[test] + fn bench_flat_json_body() { + let iters: usize = std::env::var("HUNT_BENCH_ITERS") + .ok() + .and_then(|value| value.parse().ok()) + .unwrap_or(200); + let section = std::env::var("HUNT_BENCH_SECTION").unwrap_or_else(|_| "old".to_owned()); + + let schema: HashMap> = [ + ("timestamp", MILLIS), + ("level", DataType::Utf8), + ("message", DataType::Utf8), + ("service", DataType::Utf8), + ("host", DataType::Utf8), + ("trace_id", DataType::Utf8), + ("path", DataType::Utf8), + ("method", DataType::Utf8), + ("status", DataType::Float64), + ("duration_ms", DataType::Float64), + ("bytes", DataType::Float64), + ("cached", DataType::Boolean), + ] + .into_iter() + .map(|(name, data_type)| (name.to_owned(), Arc::new(Field::new(name, data_type, true)))) + .collect(); + const LEVELS: [&str; 3] = ["info", "warn", "error"]; + let rows: Vec = (0..2000u32) + .map(|row| { + json!({ + "timestamp": format!("2025-01-02T03:{:02}:{:02}.{:03}Z", row / 60 % 60, row % 60, row % 1000), + "level": LEVELS[row as usize % 3], + "message": format!("request {row} served from the upstream pool without retries"), + "service": "checkout", + "host": format!("node-{}.internal", row % 17), + "trace_id": format!("{:032x}", u128::from(row) * 0x9E37_79B9_7F4A_7C15), + "path": format!("/api/v1/orders/{row}"), + "method": "GET", + "status": 200 + row % 5, + "duration_ms": f64::from(row) * 0.37, + "bytes": row * 13, + "cached": row % 2 == 0, + }) + }) + .collect(); + let body = serde_json::to_vec(&rows).unwrap(); + + let through_values = |decode: fn(&[Value], Arc) -> RecordBatch| { + let json = serde_json::from_slice::(&body) + .unwrap() + .into_inner(); + let mut budget = FlattenBudget::new(FlattenLimits::DEFAULT); + let origin_size = flat_batch_len(&json, &mut budget).unwrap(); + let Value::Array(rows) = json else { + unreachable!() + }; + let fields = known_scalar_schema(&rows, &schema, SchemaVersion::V1, false).unwrap(); + (decode(&rows, Arc::new(Schema::new(fields))), origin_size) + }; + let run = || match section.as_str() { + "old" => through_values(|rows, schema| decode_rows_arrow_json(rows, schema).unwrap()), + "values" => through_values(|rows, schema| decode_rows_direct(rows, &schema).unwrap()), + "new" => { + let batch = direct(&body, &schema).unwrap(); + (batch.rb, batch.origin_size) + } + section => panic!("no section {section}"), + }; + let expected = through_values(|rows, schema| decode_rows_arrow_json(rows, schema).unwrap()); + assert_eq!(run(), expected); + + let start = std::time::Instant::now(); + let mut checksum = 0; + for _ in 0..iters { + let (rb, origin_size) = std::hint::black_box(run()); + checksum += rb.num_rows() as u64 + origin_size; + } + let elapsed = start.elapsed(); + println!( + "bench_flat_json_body section={section} iters={iters} body_bytes={} checksum={checksum} total_ms={:.1} per_iter_us={:.1}", + body.len(), + elapsed.as_secs_f64() * 1e3, + elapsed.as_secs_f64() * 1e6 / iters as f64, + ); + } + + fn timestamp_text() -> impl Strategy { + prop_oneof![ + "20[0-9]{2}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])[T ]([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](\\.[0-9]{1,12})?(Z|[+-][01][0-9]:[0-5][0-9])?", + any::(), + ] + } + + /// A value for a field of the stream, mostly of its type + fn scalar(key: &'static str) -> BoxedStrategy { + let typed = match key { + "s" | "s2" => prop_oneof![ + any::().prop_map(Value::from), + timestamp_text().prop_map(Value::from) + ] + .boxed(), + "f" | "f32" => prop_oneof![ + any::() + .prop_filter("finite", |f| f.is_finite()) + .prop_map(Value::from), + any::().prop_map(Value::from), + any::().prop_map(Value::from), + ] + .boxed(), + "i" => any::().prop_map(Value::from).boxed(), + "i8" => (-200i64..200).prop_map(Value::from).boxed(), + "u" => any::().prop_map(Value::from).boxed(), + "u8" => (-10i64..300).prop_map(Value::from).boxed(), + "b" => any::().prop_map(Value::from).boxed(), + "ts" => timestamp_text().prop_map(Value::from).boxed(), + _ => unreachable!(), + }; + prop_oneof![ + 8 => typed, + 1 => Just(Value::Null), + 1 => prop_oneof![ + any::().prop_map(Value::from), + any::().prop_map(Value::from), + any::().prop_filter("finite", |f| f.is_finite()).prop_map(Value::from), + any::().prop_map(Value::from), + Just(json!([1])), + Just(json!({"a": 1})), + ], + ] + .boxed() + } + + fn row() -> impl Strategy { + const FIELDS: [&str; 10] = ["s", "s2", "f", "f32", "i", "i8", "u", "u8", "b", "ts"]; + let fields: Vec<_> = FIELDS + .into_iter() + .map(|key| proptest::option::weighted(0.7, scalar(key))) + .collect(); + ( + fields, + any::(), + proptest::option::weighted(0.03, "[a-z@_]{1,6}"), + ) + .prop_map(|(values, rotate, extra)| { + // Rows name their fields in different orders + let mut entries: Vec<_> = FIELDS + .into_iter() + .zip(values) + .filter_map(|(key, value)| Some((key.to_owned(), value?))) + .collect(); + if !entries.is_empty() { + let by = rotate.index(entries.len()); + entries.rotate_left(by); + } + if let Some(extra) = extra { + entries.push((extra, json!("extra"))); + } + Value::Object(entries.into_iter().collect()) + }) + } + + proptest! { + #![proptest_config(ProptestConfig::with_cases(2000))] + + #[test] + fn serialized_rows_match_the_general_path( + rows in proptest::collection::vec(row(), 1..8), + single in any::(), + pretty in any::(), + ) { + let schema = stream_schema(); + let body = if single { rows[0].clone() } else { Value::Array(rows.clone()) }; + let bytes = if pretty { + serde_json::to_vec_pretty(&body).unwrap() + } else { + serde_json::to_vec(&body).unwrap() + }; + check_body(&bytes, &schema, FlattenLimits::DEFAULT); + + // The same rows, decoded from their values + let fields: Vec<_> = schema + .values() + .filter(|field| ColumnBuilder::new(field.data_type(), 0).is_some()) + .filter(|field| field.is_nullable()) + .cloned() + .sorted_by(|a, b| a.name().cmp(b.name())) + .collect(); + check_rows(&rows, Arc::new(Schema::new(fields))); + for version in [SchemaVersion::V0, SchemaVersion::V1] { + if let Some(fields) = known_scalar_schema(&rows, &schema, version, false) { + let schema = Arc::new(Schema::new(fields)); + let decodes = decode_rows_arrow_json(&rows, schema.clone()).is_ok(); + prop_assert_eq!(check_rows(&rows, schema), decodes); + } + } + } + } +} diff --git a/src/event/format/mod.rs b/src/event/format/mod.rs index f12b00690..f26d7dd97 100644 --- a/src/event/format/mod.rs +++ b/src/event/format/mod.rs @@ -68,6 +68,83 @@ fn is_arrow_timestamp(value: &str) -> bool { string_to_datetime(&Utc, value).is_ok() } +/// The time a string stands for in an existing timestamp field, `None` when +/// the string is not accepted for one. +/// +/// A string is accepted when one of the chrono formats below parses it and +/// Arrow's JSON decoder, which produces the stored value, parses it too. The +/// two sets differ both ways: chrono takes RFC 2822, Arrow takes a bare date, +/// a compact time and named time zones. +/// +/// Arrow is asked first, as its result is the value. The usual shapes of a +/// timestamp are then known to be accepted by chrono whenever Arrow accepted +/// them (see `is_canonical_timestamp`), so only an unusual string is parsed +/// again, by up to six chrono parsers. +pub(crate) fn parse_compatible_timestamp(value: &str) -> Option> { + let parsed = string_to_datetime(&Utc, value).ok()?; + (is_canonical_timestamp(value) || chrono_accepts_timestamp(value)).then_some(parsed) +} + +fn chrono_accepts_timestamp(s: &str) -> bool { + chrono::DateTime::parse_from_rfc3339(s).is_ok() + || chrono::DateTime::parse_from_rfc2822(s).is_ok() + || chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%S%.f").is_ok() + || chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%S").is_ok() + || chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S%.f").is_ok() + || chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S").is_ok() +} + +/// Whether `s` has one of the shapes +/// +/// - `YYYY-MM-DD(T| )hh:mm:ss[.f]` +/// - `YYYY-MM-DD(T| )hh:mm:ss[.f](Z|z)` +/// - `YYYY-MM-DD(T| )hh:mm:ss[.f](+|-)hh:mm`, with offset minutes below 60 +/// +/// with seconds below 60 and `f` one or more digits. Only the shape is +/// checked, not that the date or the time exists. +/// +/// For a string of such a shape that Arrow parses, `chrono_accepts_timestamp` +/// holds: Arrow has then checked that the date and the time exist and that the +/// offset is less than a day, which is all chrono asks beyond the shape. The +/// first shape is one of the naive formats (whose `%.f` takes any number of +/// digits), the other two are RFC 3339. Offset minutes of 60 or more, which +/// Arrow takes and chrono refuses, are left out, as are leap seconds and the +/// separator `t`, which no naive format takes. +fn is_canonical_timestamp(s: &str) -> bool { + let bytes = s.as_bytes(); + let digits = |range: std::ops::Range| bytes[range].iter().all(u8::is_ascii_digit); + if bytes.len() < 19 + || !(digits(0..4) && digits(5..7) && digits(8..10)) + || !(digits(11..13) && digits(14..16) && digits(17..19)) + || bytes[4] != b'-' + || bytes[7] != b'-' + || !matches!(bytes[10], b'T' | b' ') + || bytes[13] != b':' + || bytes[16] != b':' + || bytes[17] > b'5' + { + return false; + } + let mut rest = &bytes[19..]; + if let [b'.', fraction @ ..] = rest { + let len = fraction.iter().take_while(|b| b.is_ascii_digit()).count(); + if len == 0 { + return false; + } + rest = &fraction[len..]; + } + match rest { + [] | [b'Z' | b'z'] => true, + [b'+' | b'-', h1, h2, b':', m1, m2] => { + h1.is_ascii_digit() + && h2.is_ascii_digit() + && matches!(m1, b'0'..=b'5') + && m2.is_ascii_digit() + } + _ => false, + } +} + type EventSchema = Vec>; /// Normalizes a field name by replacing leading '@' with '_'. @@ -550,15 +627,7 @@ fn value_compatible_with_type( DataType::Timestamp(_, _) => { // Timestamps can accept strings that parse as datetime or numbers match value { - Value::String(s) => { - (chrono::DateTime::parse_from_rfc3339(s).is_ok() - || chrono::DateTime::parse_from_rfc2822(s).is_ok() - || chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%S%.f").is_ok() - || chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%S").is_ok() - || chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S%.f").is_ok() - || chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S").is_ok()) - && is_arrow_timestamp(s) - } + Value::String(s) => parse_compatible_timestamp(s).is_some(), // Arrow JSON decoder with coerce_primitive(false) cannot decode // a JSON number into a Timestamp field — it expects a string. Value::Number(_) => false, @@ -811,6 +880,229 @@ mod tests { use super::*; use serde_json::json; + /// The check `value_compatible_with_type` made of a timestamp string + /// before it asked Arrow first: six chrono parsers, then Arrow's. + fn legacy_timestamp_compatible(s: &str) -> bool { + (chrono::DateTime::parse_from_rfc3339(s).is_ok() + || chrono::DateTime::parse_from_rfc2822(s).is_ok() + || chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%S%.f").is_ok() + || chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%S").is_ok() + || chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S%.f").is_ok() + || chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S").is_ok()) + && is_arrow_timestamp(s) + } + + /// Checks a string against the former check, and returns whether it has a + /// canonical shape that Arrow parses, for which chrono is no longer asked. + fn check_timestamp(s: &str) -> bool { + let parsed = parse_compatible_timestamp(s); + assert_eq!(parsed.is_some(), legacy_timestamp_compatible(s), "{s:?}"); + if let Some(parsed) = parsed { + assert_eq!(parsed, string_to_datetime(&Utc, s).unwrap(), "{s:?}"); + } + assert_eq!( + value_compatible_with_type( + &Value::String(s.to_owned()), + &DataType::Timestamp(TimeUnit::Millisecond, None), + SchemaVersion::V1, + ), + legacy_timestamp_compatible(s), + "{s:?}" + ); + let skipped = is_canonical_timestamp(s) && is_arrow_timestamp(s); + if skipped { + // What makes it safe not to ask chrono + assert!(chrono_accepts_timestamp(s), "{s:?}"); + } + skipped + } + + #[test] + fn timestamp_compatibility_matches_the_chrono_and_arrow_check() { + // The usual values first + const YEARS: [&str; 7] = ["0000", "0001", "1969", "2024", "2025", "9999", "20a5"]; + const MONTHS: [&str; 6] = ["01", "02", "12", "00", "13", "1"]; + const DAYS: [&str; 7] = ["01", "28", "29", "30", "31", "00", "32"]; + const SEPARATORS: [&str; 6] = ["T", " ", "t", "_", "", " "]; + const HOURS: [&str; 4] = ["00", "12", "23", "24"]; + const MINUTES: [&str; 3] = ["00", "59", "60"]; + const SECONDS: [&str; 5] = ["00", "30", "59", "60", "61"]; + const FRACTIONS: [&str; 9] = [ + "", + "", + ".5", + ".123", + ".123456789", + ".1234567890123", + ".12345678901234567890123", + ".", + ".12a", + ]; + const ZONES: [&str; 26] = [ + "", + "", + "Z", + "Z", + "z", + "+00:00", + "-00:00", + "+05:30", + "-08:00", + "+23:59", + "-23:59", + "+24:00", + "+99:00", + "+10:60", + "+10:99", + "+0530", + "+05", + " +05:30", + " Z", + "UTC", + " UTC", + " America/New_York", + "+5:30", + "+05:30 ", + "ZZ", + "\u{2212}05:30", + ]; + let mut seed = 0x9E37_79B9_7F4A_7C15_u64; + let mut pick = |n: usize| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed % n as u64) as usize + }; + let (mut skipped, mut accepted, mut total) = (0, 0, 0); + for _ in 0..60_000 { + // Mostly a time that exists, so that many strings are accepted + let usual = pick(3) != 0; + let mut part = |items: &[&'static str], usual_items: usize| { + items[pick(if usual { usual_items } else { items.len() })] + }; + let s = format!( + "{}-{}-{}{}{}:{}:{}{}{}", + part(&YEARS, 6), + part(&MONTHS, 3), + part(&DAYS, 3), + part(&SEPARATORS, 2), + part(&HOURS, 3), + part(&MINUTES, 2), + part(&SECONDS, 3), + part(&FRACTIONS, 7), + part(&ZONES, 11), + ); + total += 1; + accepted += legacy_timestamp_compatible(&s) as usize; + skipped += check_timestamp(&s) as usize; + // The same with a byte dropped or doubled + if !s.is_empty() && pick(4) == 0 { + let mut at = pick(s.len()); + while !s.is_char_boundary(at) { + at -= 1; + } + let mut dropped = s.clone(); + let removed = dropped.remove(at); + check_timestamp(&dropped); + let mut doubled = s.clone(); + doubled.insert(at, removed); + check_timestamp(&doubled); + } + } + // Most accepted strings are of a canonical shape + assert!(accepted * 3 > total, "{accepted} of {total} accepted"); + assert!(skipped * 10 > accepted * 9, "{skipped} of {accepted}"); + + for s in [ + "", + "2025", + "2025-01-02", + "2025-01-02T03:04", + "2025-01-02T030405", + "2025-01-02T030405Z", + "20250102T030405Z", + "2025-01-02T03:04:05", + "2025-01-02 03:04:05", + "2025-01-02 03:04:05", + "2025-01-02T03:04:05Z", + "2025-01-02T03:04:05.000000000000Z", + "2025-01-02T03:04:05,5Z", + " 2025-01-02T03:04:05Z", + "2025-01-02T03:04:05Z ", + "+2025-01-02T03:04:05", + "-2025-01-02T03:04:05Z", + "12025-01-02T03:04:05Z", + "2025-01-02T3:04:05Z", + "2025-01-02T03:04:05+05:30:00", + "Thu, 02 Jan 2025 03:04:05 +0000", + "Thu, 02 Jan 2025 03:04:05 GMT", + "2 Jan 2025 03:04:05 +0000", + "1735787045678", + "yesterday", + "2025-01-02T03:04:05Z", + ] { + check_timestamp(s); + } + } + + /// The check of a timestamp string for an existing timestamp field, over + /// the strings of a batch of 2,000 rows + #[ignore = "release-profile microbenchmark; select the section with HUNT_BENCH_SECTION"] + #[test] + fn bench_timestamp_compatibility() { + let iters: usize = std::env::var("HUNT_BENCH_ITERS") + .ok() + .and_then(|value| value.parse().ok()) + .unwrap_or(200); + let old = !matches!(std::env::var("HUNT_BENCH_SECTION").as_deref(), Ok("new")); + let strings: Vec = (0..2000u32) + .map(|row| { + format!( + "2025-01-02T03:{:02}:{:02}.{:03}Z", + row / 60 % 60, + row % 60, + row % 1000 + ) + }) + .collect(); + let start = std::time::Instant::now(); + let mut accepted = 0; + for _ in 0..iters { + for s in &strings { + let s = std::hint::black_box(s.as_str()); + accepted += if old { + legacy_timestamp_compatible(s) + } else { + parse_compatible_timestamp(s).is_some() + } as usize; + } + } + let elapsed = start.elapsed(); + assert_eq!(accepted, iters * strings.len()); + println!( + "bench_timestamp_compatibility section={} iters={iters} total_ms={:.1} per_string_ns={:.1}", + if old { "old" } else { "new" }, + elapsed.as_secs_f64() * 1e3, + elapsed.as_secs_f64() * 1e9 / (iters * strings.len()) as f64, + ); + } + + proptest::proptest! { + #![proptest_config(proptest::prelude::ProptestConfig::with_cases(4000))] + + #[test] + fn timestamp_compatibility_matches_for_any_string( + s in proptest::prop_oneof![ + "[0-9]{4}-[0-9]{2}-[0-9]{2}[Tt ][0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]{0,12})?(Z|z|[+-][0-9]{2}:?[0-9]{2}|[+-][0-9]{2})?", + "20[0-9]{2}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])[T ]([01][0-9]|2[0-3]):[0-5][0-9]:([0-5][0-9]|60)(\\.[0-9]{1,10})?(Z|[+-][0-2][0-9]:[0-9]{2})?", + "[0-9TtZz:.+ -]{0,32}", + proptest::prelude::any::(), + ], + ) { + check_timestamp(&s); + } + } + #[test] fn test_get_datatype_suffix() { assert_eq!(get_datatype_suffix(&DataType::Boolean), "bool"); diff --git a/src/event/mod.rs b/src/event/mod.rs index 26d953cd9..f9b0e819a 100644 --- a/src/event/mod.rs +++ b/src/event/mod.rs @@ -33,7 +33,7 @@ use crate::{ handlers::TelemetryType, metadata::{LogStreamMetadata, update_stats}, metrics::{increment_events_ingested_by_date, increment_events_ingested_size_by_date}, - parseable::{DEFAULT_TENANT, PARSEABLE, StagingError, StreamNotFound}, + parseable::{DEFAULT_TENANT, PARSEABLE, StagingError, StreamNotFound, StreamRef}, storage::StreamType, tenants::TenantNotFound, }; @@ -66,8 +66,16 @@ impl Event { /// Processes the event, holding user-defined streams to the configured /// dataset field limit. pub fn process(self) -> Result<(), EventError> { + let stream = PARSEABLE.get_or_create_stream(&self.stream_name, &self.tenant_id); + self.process_on_stream(&stream) + } + + /// Processes the event on an already-resolved stream handle, holding + /// user-defined streams to the configured dataset field limit without + /// re-looking up the stream in `PARSEABLE.streams`. + pub fn process_on_stream(self, stream: &StreamRef) -> Result<(), EventError> { let limit = PARSEABLE.options.dataset_fields_allowed_limit; - self.process_with_field_limit(limit, true) + self.process_with_field_limit_on_stream(stream, limit, true) } /// Processes the event without enforcing the dataset field limit. @@ -80,29 +88,25 @@ impl Event { /// together with `commit_ingested_schemas`, so that a request yielding /// several events cannot fail on the limit after some were staged. pub fn process_without_field_limit(self) -> Result<(), EventError> { - self.process_with_field_limit(usize::MAX, true) + let stream = PARSEABLE.get_or_create_stream(&self.stream_name, &self.tenant_id); + self.process_without_field_limit_on_stream(&stream) + } + + /// Like `process_without_field_limit`, using an already-resolved stream + /// handle instead of re-looking up `PARSEABLE.streams`. + pub fn process_without_field_limit_on_stream( + self, + stream: &StreamRef, + ) -> Result<(), EventError> { + self.process_with_field_limit_on_stream(stream, usize::MAX, true) } pub(crate) fn stage_without_observers(self) -> Result<(), EventError> { - self.process_with_field_limit(usize::MAX, false) + let stream = PARSEABLE.get_or_create_stream(&self.stream_name, &self.tenant_id); + self.process_with_field_limit_on_stream(&stream, usize::MAX, false) } - #[instrument( - name = "event_process", - level = "info", - skip_all, - fields( - stream_name = %self.stream_name, - num_rows = self.rb.num_rows(), - is_first_event = self.is_first_event - ) - )] - #[cfg_attr(feature = "hotpath", hotpath::measure)] - fn process_with_field_limit( - self, - field_limit: usize, - observers: bool, - ) -> Result<(), EventError> { + fn compute_push_key(&self) -> String { let mut key = get_schema_key(&self.rb.schema().fields); if self.time_partition.is_some() { let parsed_timestamp_to_min = self.parsed_timestamp.format("%Y%m%dT%H%M").to_string(); @@ -114,26 +118,97 @@ impl Event { key.push_str(&format!("&{k}={v}")); } } + key + } - let stream = PARSEABLE.get_or_create_stream(&self.stream_name, &self.tenant_id); - + fn commit_schema_on_stream( + &self, + stream: &StreamRef, + field_limit: usize, + ) -> Result { // User ingestion is held to the given field limit; internal // streams have fixed schemas and are exempt. - let schema_committed = if self.stream_type == StreamType::UserDefined { + if self.stream_type == StreamType::UserDefined { + // `commit_ingested_schema` already returns `false` for static + // schemas, so a `true` return implies `!static_schema_flag` + // without an extra `metadata.read()` lock. commit_ingested_schema( &self.stream_name, &stream.metadata, &self.rb.schema(), field_limit, self.is_first_event, - )? + ) } else if self.is_first_event { - commit_schema(&self.stream_name, self.rb.schema(), &self.tenant_id)?; - true + commit_schema_to_metadata(&stream.metadata, &self.rb.schema())?; + Ok(!stream.get_static_schema_flag()) } else { - false - }; - if schema_committed && !stream.get_static_schema_flag() { + Ok(false) + } + } + + /// Prepares `self` on a CPU thread for `PreparedEventPush::push_async`: + /// computes the push key, checks and commits schema updates, and + /// pre-encodes the IPC batch so the caller can release its Rayon worker + /// before entering the stream's `PushQueue`. + pub(crate) fn prepare_for_async_push_on_stream( + self, + stream: &StreamRef, + field_limit: usize, + ) -> Result { + let key = self.compute_push_key(); + let stage_schema = self.commit_schema_on_stream(stream, field_limit)?; + if stage_schema { + stream.stage_schema_file(stream.get_schema().as_ref().clone())?; + } + let preencoded = stream.preencode_for_push(&self.rb, self.stream_type); + Ok(PreparedEventPush { + event: self, + key, + preencoded, + needs_stage_schema_file: false, + }) + } + + /// Prepares an event whose schema key and IPC bytes were already computed + /// on a CPU thread, performing only in-memory schema checks on the caller + /// and deferring any rare `stage_schema_file` disk write to `push_async`. + pub(crate) fn prepare_preencoded_for_async_push_on_stream( + self, + stream: &StreamRef, + field_limit: usize, + key: String, + preencoded: Option, + ) -> Result { + let needs_stage_schema_file = self.commit_schema_on_stream(stream, field_limit)?; + Ok(PreparedEventPush { + event: self, + key, + preencoded, + needs_stage_schema_file, + }) + } + + #[instrument( + name = "event_process", + level = "info", + skip_all, + fields( + stream_name = %self.stream_name, + num_rows = self.rb.num_rows(), + is_first_event = self.is_first_event + ) + )] + #[cfg_attr(feature = "hotpath", hotpath::measure)] + pub fn process_with_field_limit_on_stream( + self, + stream: &StreamRef, + field_limit: usize, + observers: bool, + ) -> Result<(), EventError> { + let key = self.compute_push_key(); + let stage_schema = self.commit_schema_on_stream(stream, field_limit)?; + if stage_schema { stream.stage_schema_file(stream.get_schema().as_ref().clone())?; } @@ -170,18 +245,69 @@ impl Event { } pub fn process_unchecked(&self) -> Result<(), EventError> { + let stream = PARSEABLE.get_or_create_stream(&self.stream_name, &self.tenant_id); + self.process_unchecked_on_stream(&stream) + } + + pub fn process_unchecked_on_stream(&self, stream: &StreamRef) -> Result<(), EventError> { let key = get_schema_key(&self.rb.schema().fields); - PARSEABLE - .get_or_create_stream(&self.stream_name, &self.tenant_id) - .push( - &key, - &self.rb, - self.parsed_timestamp, - &self.custom_partition_values, - self.stream_type, - )?; + stream.push( + &key, + &self.rb, + self.parsed_timestamp, + &self.custom_partition_values, + self.stream_type, + )?; + + Ok(()) + } +} + +/// An ingested `Event` whose schema check and optional IPC pre-encoding have +/// completed on a CPU thread and is ready to be awaited on `Stream::push_async` +/// without holding a Rayon worker thread. +pub(crate) struct PreparedEventPush { + event: Event, + key: String, + preencoded: Option, + needs_stage_schema_file: bool, +} + +impl PreparedEventPush { + pub(crate) async fn push_async( + self, + stream: &StreamRef, + observers: bool, + ) -> Result<(), EventError> { + if self.needs_stage_schema_file { + let stream = stream.clone(); + tokio::task::spawn_blocking(move || { + stream.stage_schema_file(stream.get_schema().as_ref().clone()) + }) + .await + .map_err(|e| StagingError::ObjectStorage(std::io::Error::other(e.to_string())))??; + } + + stream + .push_async( + &self.key, + &self.event.rb, + self.preencoded, + self.event.parsed_timestamp, + &self.event.custom_partition_values, + self.event.stream_type, + ) + .await?; + if observers { + self.event.observe( + self.event.origin_size, + self.event.rb.num_rows(), + self.event.parsed_timestamp, + ); + crate::livetail::LIVETAIL.process(&self.event.stream_name, &self.event.rb); + } Ok(()) } } @@ -1252,4 +1378,287 @@ mod tests { }); assert_eq!(field_names(&stream).len(), LIMIT); } + + #[test] + fn process_on_stream_matches_process_including_field_limits_and_schema_staging() { + use crate::{ + cli::Options, + handlers::TelemetryType, + parseable::{PARSEABLE, Stream, install_default_test_parseable}, + storage::StreamType, + }; + + install_default_test_parseable(); + + let make_event = |stream_name: &str, + rb: arrow_array::RecordBatch, + is_first_event: bool, + stream_type: StreamType| super::Event { + stream_name: stream_name.to_owned(), + rb, + origin_format: "json", + origin_size: 42, + is_first_event, + parsed_timestamp: Utc::now().naive_utc(), + time_partition: None, + custom_partition_values: HashMap::new(), + stream_type, + telemetry_type: TelemetryType::Logs, + tenant_id: None, + }; + + // Part A: Parity between `Event::process` / `Event::process_without_field_limit` + // and their `_on_stream` counterparts on registered streams. + let suffix = ulid::Ulid::new().to_string().to_lowercase(); + let name_process = format!("evt_proc_{suffix}"); + let name_on_stream = format!("evt_on_stream_{suffix}"); + let dir_process = temp_dir::TempDir::new().unwrap(); + let dir_on_stream = temp_dir::TempDir::new().unwrap(); + let stream_process = Stream::new( + Arc::new(Options { + local_staging_path: dir_process.path().to_path_buf(), + ..Default::default() + }), + &name_process, + LogStreamMetadata { + schema_version: SchemaVersion::V1, + ..Default::default() + }, + None, + &None, + ); + let stream_on_stream = Stream::new( + Arc::new(Options { + local_staging_path: dir_on_stream.path().to_path_buf(), + ..Default::default() + }), + &name_on_stream, + LogStreamMetadata { + schema_version: SchemaVersion::V1, + ..Default::default() + }, + None, + &None, + ); + { + let mut map = PARSEABLE.streams.write().unwrap(); + let tenant_map = map + .entry(crate::parseable::DEFAULT_TENANT.to_owned()) + .or_default(); + tenant_map.insert(name_process.clone(), stream_process.clone()); + tenant_map.insert(name_on_stream.clone(), stream_on_stream.clone()); + } + + // `Event::process` and `Event::process_on_stream` must agree identically + // against `PARSEABLE.options.dataset_fields_allowed_limit`. + let initial_rb = event_batch(&stream_process.metadata, json!({"msg": "hello"}), &[]); + let res_process = make_event( + &name_process, + initial_rb.clone(), + true, + StreamType::UserDefined, + ) + .process(); + let res_on_stream = make_event( + &name_on_stream, + initial_rb.clone(), + true, + StreamType::UserDefined, + ) + .process_on_stream(&stream_on_stream); + match (&res_process, &res_on_stream) { + (Ok(()), Ok(())) => { + assert_eq!(stream_process.get_schema(), stream_on_stream.get_schema()); + assert_eq!( + stream_process.get_schemas_if_present().unwrap(), + stream_on_stream.get_schemas_if_present().unwrap() + ); + } + ( + Err(EventError::FieldsCountLimitExceeded(_, t1, l1)), + Err(EventError::FieldsCountLimitExceeded(_, t2, l2)), + ) => { + assert_eq!((t1, l1), (t2, l2)); + } + other => panic!("process vs process_on_stream diverged: {other:?}"), + } + + // `process_without_field_limit` vs `process_without_field_limit_on_stream` + // always commits, stages the schema file, and pushes rows identically. + make_event( + &name_process, + initial_rb.clone(), + true, + StreamType::UserDefined, + ) + .process_without_field_limit() + .unwrap(); + make_event(&name_on_stream, initial_rb, true, StreamType::UserDefined) + .process_without_field_limit_on_stream(&stream_on_stream) + .unwrap(); + + assert_eq!(stream_process.get_schema(), stream_on_stream.get_schema()); + assert_eq!( + stream_process.get_schemas_if_present().unwrap(), + stream_on_stream.get_schemas_if_present().unwrap() + ); + assert!( + !stream_on_stream + .get_schemas_if_present() + .unwrap() + .is_empty(), + "schema file must be staged after first-event commit" + ); + + // Second event with an additional header field (non-first event) + let second_rb = event_batch( + &stream_process.metadata, + json!({"msg": "world"}), + &[("env", "prod")], + ); + make_event( + &name_process, + second_rb.clone(), + false, + StreamType::UserDefined, + ) + .process_without_field_limit() + .unwrap(); + make_event(&name_on_stream, second_rb, false, StreamType::UserDefined) + .process_without_field_limit_on_stream(&stream_on_stream) + .unwrap(); + + assert_eq!(stream_process.get_schema(), stream_on_stream.get_schema()); + assert!(stream_on_stream.get_schema().field_with_name("env").is_ok()); + + PARSEABLE.streams.delete(&name_process, &None); + PARSEABLE.streams.delete(&name_on_stream, &None); + + // Part B: Standalone stream (never registered in PARSEABLE.streams) + // proves `process_with_field_limit_on_stream` skips PARSEABLE lookup, + // enforces field limits, respects static schema, and stages schema files. + let dir = temp_dir::TempDir::new().unwrap(); + let standalone = Stream::new( + Arc::new(Options { + local_staging_path: dir.path().to_path_buf(), + ..Default::default() + }), + "standalone_dynamic", + LogStreamMetadata { + schema_version: SchemaVersion::V1, + ..Default::default() + }, + None, + &None, + ); + + // 3 fields (p_timestamp + f0 + f1) fits within limit 3 + let rb3 = event_batch(&standalone.metadata, record("f", 2), &[]); + make_event("standalone_dynamic", rb3, true, StreamType::UserDefined) + .process_with_field_limit_on_stream(&standalone, 3, false) + .unwrap(); + assert_eq!(standalone.get_schema_len(), 3); + assert!( + !standalone.get_schemas_if_present().unwrap().is_empty(), + "dynamic schema commit must stage schema file" + ); + + // Adding a 4th field exceeds limit 3 and leaves schema unchanged + let rb4 = event_batch(&standalone.metadata, record("g", 1), &[]); + let err = make_event( + "standalone_dynamic", + rb4.clone(), + true, + StreamType::UserDefined, + ) + .process_with_field_limit_on_stream(&standalone, 3, false) + .unwrap_err(); + match err { + EventError::FieldsCountLimitExceeded(name, total, limit) => { + assert_eq!((name.as_str(), total, limit), ("standalone_dynamic", 4, 3)); + } + other => panic!("expected FieldsCountLimitExceeded, got {other:?}"), + } + assert_eq!(standalone.get_schema_len(), 3); + + // `process_without_field_limit_on_stream` bypasses the limit on the same stream + make_event("standalone_dynamic", rb4, true, StreamType::UserDefined) + .process_without_field_limit_on_stream(&standalone) + .unwrap(); + assert_eq!(standalone.get_schema_len(), 4); + + // Static schema stream: never grows or stages schema file, still checks stored len + let static_dir = temp_dir::TempDir::new().unwrap(); + let static_meta = metadata(vec![p_timestamp(), Field::new("msg", DataType::Utf8, true)]); + let static_stream = Stream::new( + Arc::new(Options { + local_staging_path: static_dir.path().to_path_buf(), + ..Default::default() + }), + "standalone_static", + LogStreamMetadata { + schema: static_meta.read().unwrap().schema.clone(), + static_schema_flag: true, + schema_version: SchemaVersion::V1, + ..Default::default() + }, + None, + &None, + ); + let static_rb = event_batch( + &static_stream.metadata, + json!({"msg": "ok"}), + &[("env", "prod")], + ); + make_event( + "standalone_static", + static_rb.clone(), + true, + StreamType::UserDefined, + ) + .process_with_field_limit_on_stream(&static_stream, 2, false) + .unwrap(); + assert_eq!(static_stream.get_schema_len(), 2); + assert!( + static_stream.get_schemas_if_present().unwrap().is_empty(), + "static schema stream must not stage a dynamic schema file" + ); + let err = make_event( + "standalone_static", + static_rb, + false, + StreamType::UserDefined, + ) + .process_with_field_limit_on_stream(&static_stream, 1, false) + .unwrap_err(); + assert!(matches!(err, EventError::FieldsCountLimitExceeded(_, 2, 1))); + + // Internal stream: exempt from field limit, commits without PARSEABLE.streams + let internal_dir = temp_dir::TempDir::new().unwrap(); + let internal_stream = Stream::new( + Arc::new(Options { + local_staging_path: internal_dir.path().to_path_buf(), + ..Default::default() + }), + "standalone_internal", + LogStreamMetadata { + stream_type: StreamType::Internal, + schema_version: SchemaVersion::V1, + ..Default::default() + }, + None, + &None, + ); + let internal_rb = event_batch(&internal_stream.metadata, json!({"msg": "meta"}), &[]); + make_event( + "standalone_internal", + internal_rb, + true, + StreamType::Internal, + ) + .process_with_field_limit_on_stream(&internal_stream, 0, false) + .unwrap(); + assert_eq!(internal_stream.get_schema_len(), 2); + assert!(!internal_stream.get_schemas_if_present().unwrap().is_empty()); + } } diff --git a/src/handlers/http/ingest.rs b/src/handlers/http/ingest.rs index 8d0b6ccd5..28f54a807 100644 --- a/src/handlers/http/ingest.rs +++ b/src/handlers/http/ingest.rs @@ -17,27 +17,35 @@ */ use std::collections::{HashMap, HashSet}; +use std::sync::Arc; +use actix_web::error::JsonPayloadError; use actix_web::http::StatusCode; use actix_web::web::{self, Json, Path}; use actix_web::{ - HttpRequest, HttpResponse, + HttpMessage, HttpRequest, HttpResponse, http::header::{ContentType, HeaderMap}, }; use arrow_array::RecordBatch; +use arrow_schema::Field; use bytes::Bytes; use chrono::Utc; use once_cell::sync::Lazy; use rayon::{ThreadPool, ThreadPoolBuilder}; +use serde_json::Value; use tokio::sync::oneshot; use tracing::error; use crate::event::error::EventError; +use crate::event::format::json::{FlatJsonBatch, try_parse_flat_json_bytes_to_recordbatch}; use crate::event::format::known_schema::{self, KNOWN_SCHEMA_LIST}; use crate::event::format::{self, EventFormat, LogSource, LogSourceEntry}; use crate::event::{self, FORMAT_KEY, USER_AGENT_KEY}; +#[cfg(test)] +use crate::handlers::http::modal::utils::ingest_utils::ingest_helper; use crate::handlers::http::modal::utils::ingest_utils::{ - ingest_helper, otel_response, process_otel_content, validate_stream_for_ingestion, + otel_response, prepare_json_push_with_stream, process_otel_content, + validate_stream_ref_for_ingestion, }; use crate::handlers::{ DATASET_TAGS_KEY, DatasetTag, EXTRACT_LOG_KEY, LOG_SOURCE_KEY, STREAM_NAME_HEADER_KEY, @@ -50,14 +58,18 @@ use crate::option::Mode; use crate::otel::logs::OTEL_LOG_KNOWN_FIELD_LIST; use crate::otel::metrics::OTEL_METRICS_KNOWN_FIELD_LIST; use crate::otel::traces::OTEL_TRACES_KNOWN_FIELD_LIST; -use crate::parseable::{PARSEABLE, StreamNotFound}; +use crate::parseable::{PARSEABLE, Stream, StreamNotFound, StreamRef}; use crate::storage::{ObjectStorageError, StreamType}; +use crate::utils::arrow::{add_parseable_fields, count_custom_fields_not_applied}; use crate::utils::get_tenant_id_from_request; use crate::utils::header_parsing::{ParseHeaderError, optional_header_str}; -use crate::utils::json::{flatten::JsonFlattenError, strict::StrictValue}; +use crate::utils::json::{ + flatten::{FlattenBudget, FlattenLimits, JsonFlattenError}, + strict::StrictValue, +}; use super::logstream::error::{CreateStreamError, StreamError}; -use super::modal::utils::ingest_utils::{flatten_and_push_logs, get_custom_fields_from_header}; +use super::modal::utils::ingest_utils::get_custom_fields_from_header; use super::users::dashboards::DashboardError; use super::users::filters::FiltersError; @@ -105,13 +117,411 @@ fn is_internal_stream(stream_name: &str, tenant_id: &Option) -> bool { .is_ok_and(|stream| stream.get_stream_type() == StreamType::Internal) } +/// A body no longer than this is parsed where the handler runs. Parsing it +/// takes less than handing it to another thread and waking up for the result, +/// so only larger bodies leave the worker. +const INLINE_PARSE_MAX_BYTES: usize = 4 * 1024; + +/// The parsed body of a request to `/api/v1/ingest` +enum IngestBody { + /// The JSON value, for the general path + Json(Value), + /// The record batch of its rows, built straight from the bytes + Flat(Box), +} + +struct FlatBody { + rb: RecordBatch, + origin_size: u64, + p_timestamp: chrono::DateTime, + schema_key: String, + preencoded: Option, + /// The stream's schema the batch was built for + schema: Arc>>, + /// The body, parsed again for the general path should the stream have + /// changed by the time the batch is staged + bytes: web::Bytes, +} + +/// Configuration for `JsonBytes`, matching `actix_web::web::JsonConfig`'s +/// payload limit while letting `/api/v1/ingest` parse JSON off the worker thread. +#[derive(Clone, Copy, Debug)] +pub struct JsonBytesConfig { + pub limit: usize, +} + +impl Default for JsonBytesConfig { + fn default() -> Self { + Self { + limit: crate::handlers::http::max_event_payload_size(), + } + } +} + +/// Raw JSON request body extractor that preserves Actix's exact `Json` +/// extraction precedence (`ContentType` checked before reading payload bytes, +/// then `OverflowKnownLength` / `Overflow` / `Payload`) without deserializing +/// JSON on the Actix worker thread. +pub struct JsonBytes(pub web::Bytes); + +impl From for JsonBytes { + fn from(bytes: web::Bytes) -> Self { + Self(bytes) + } +} + +impl actix_web::FromRequest for JsonBytes { + type Error = actix_web::Error; + type Future = std::pin::Pin>>>; + + fn from_request(req: &HttpRequest, payload: &mut actix_web::dev::Payload) -> Self::Future { + if !has_json_content_type(req) { + return Box::pin(async { Err(JsonPayloadError::ContentType.into()) }); + } + let limit = req + .app_data::() + .map_or_else(crate::handlers::http::max_event_payload_size, |cfg| { + cfg.limit + }); + if let Some(len) = req + .headers() + .get(actix_web::http::header::CONTENT_LENGTH) + .and_then(|v| v.to_str().ok()) + .and_then(|s| s.parse::().ok()) + && len > limit + { + return Box::pin(async move { + Err(JsonPayloadError::OverflowKnownLength { length: len, limit }.into()) + }); + } + let mut stream = payload.take(); + Box::pin(async move { + use futures_util::StreamExt; + let mut buf = actix_web::web::BytesMut::new(); + while let Some(chunk) = stream.next().await { + let chunk = chunk.map_err(JsonPayloadError::Payload)?; + if buf.len().saturating_add(chunk.len()) > limit { + return Err(JsonPayloadError::Overflow { limit }.into()); + } + buf.extend_from_slice(&chunk); + } + Ok(JsonBytes(buf.freeze())) + }) + } +} + +/// Whether the request has the content type the `Json` extractor asks for by +/// default: a JSON subtype or suffix. +fn has_json_content_type(req: &HttpRequest) -> bool { + matches!( + req.mime_type(), + Ok(Some(mime)) + if mime.subtype() == actix_web::mime::JSON + || mime.suffix() == Some(actix_web::mime::JSON) + ) +} + +/// The stream a request with `LogSource::Json` would be staged into, when it +/// is in memory and flat rows are not flattened further, for +/// `parse_flat_body`. Nothing is reported from here: every problem with the +/// request is left to the handler, which only loses the shorter path. +fn flat_ingest_stream(req: &HttpRequest) -> Option { + let stream_name = optional_header_str(req.headers(), STREAM_NAME_HEADER_KEY).ok()??; + let tenant_id = get_tenant_id_from_request(req).ok()?; + // As `process_non_partitioned` asks before it takes a batch as flat + if PARSEABLE.options.event_flatten_level < 2 { + return None; + } + let stream = PARSEABLE.get_stream(stream_name, &tenant_id).ok()?; + (stream.get_stream_type() != StreamType::Internal).then_some(stream) +} + +/// The stream's schema, when a flat batch of a `LogSource::Json` request is +/// staged into the stream as it is: the non-partitioned branch of +/// `stage_json`, for a stream `try_parse_flat_json_bytes_to_recordbatch` takes +/// (schema version 1, dynamic schema, already initialized) and that is within +/// its field limit (above it the general path refuses the request). +fn flat_staging_schema(stream: &Stream) -> Option>>> { + let snapshot = stream.ingest_snapshot(); + (!snapshot.schema.is_empty() + && snapshot.schema_version == SchemaVersion::V1 + && !snapshot.static_schema_flag + && snapshot.custom_partition.is_none() + && stream.get_time_partition().is_none() + && snapshot.schema.len() <= PARSEABLE.options.dataset_fields_allowed_limit) + .then_some(snapshot.schema) +} + +/// The batch of a body of flat rows of the stream's existing fields, with +/// Parseable metadata columns attached and IPC bytes pre-encoded on the CPU +/// thread so staging can await `Stream::push_async` directly without a second +/// Rayon hop. Returns `None` for any other body or stream. +fn parse_flat_body( + bytes: &web::Bytes, + stream: &Stream, + p_custom_fields: &HashMap, +) -> Option { + let schema = flat_staging_schema(stream)?; + // The request's budget, as `flatten_and_push_logs` creates it. Nothing + // else of the request is charged to it on this path. + let mut budget = FlattenBudget::new(FlattenLimits::from_config()); + let FlatJsonBatch { rb, origin_size } = try_parse_flat_json_bytes_to_recordbatch( + bytes, + &schema, + SchemaVersion::V1, + false, + &mut budget, + )?; + let p_timestamp = Utc::now(); + // If attaching custom fields fails, fall back to the general path so error + // precedence (validation before staging) is preserved identically. + let rb = add_parseable_fields(rb, p_timestamp, p_custom_fields, &schema).ok()?; + let schema_key = event::get_schema_key(&rb.schema().fields); + let preencoded = stream.preencode_for_push(&rb, StreamType::UserDefined); + Some(FlatBody { + rb, + origin_size, + p_timestamp, + schema_key, + preencoded, + schema, + bytes: bytes.clone(), + }) +} + +/// Parses a request body as the `Json` extractor did, failing +/// with the same error. With a `flat_stream` the body is first tried as a +/// batch of flat rows of that stream, which succeeds only for a body that is +/// strict JSON. +fn parse_body( + bytes: web::Bytes, + flat_stream: Option, + p_custom_fields: &HashMap, +) -> Result { + if let Some(stream) = flat_stream + && let Some(flat) = parse_flat_body(&bytes, &stream, p_custom_fields) + { + return Ok(IngestBody::Flat(Box::new(flat))); + } + serde_json::from_slice::(&bytes).map(|json| IngestBody::Json(json.into_inner())) +} + +/// `parse_body`, off the worker thread for all but small bodies +async fn parse_body_off_worker( + bytes: web::Bytes, + flat_stream: Option, + p_custom_fields: HashMap, +) -> Result< + ( + Result, + HashMap, + ), + PostError, +> { + if bytes.len() <= INLINE_PARSE_MAX_BYTES { + let parsed = parse_body(bytes, flat_stream, &p_custom_fields); + return Ok((parsed, p_custom_fields)); + } + let (s, r) = oneshot::channel(); + rayon::spawn(move || { + let parsed = parse_body(bytes, flat_stream, &p_custom_fields); + let _ = s.send((parsed, p_custom_fields)); + }); + r.await.map_err(|e| PostError::CustomError(e.to_string())) +} + +fn flat_body_matches_schema( + rb: &RecordBatch, + built_schema: &Arc>>, + current_schema: &Arc>>, + p_custom_fields: &HashMap, +) -> bool { + if Arc::ptr_eq(current_schema, built_schema) { + return true; + } + rb.schema_ref().fields().iter().all(|field| { + let name = field.name(); + match current_schema.get(name) { + Some(current_field) => current_field == field, + None => !built_schema.contains_key(name) && p_custom_fields.contains_key(name), + } + }) && p_custom_fields + .keys() + .all(|k| current_schema.get(k) == built_schema.get(k)) +} + +/// Runs `prepare_json_push_with_stream` on Rayon (freeing the CPU worker before +/// entering `PushQueue`) and awaits `PreparedEventPush::push_async`. +#[allow(clippy::too_many_arguments)] +async fn stage_json_body_async( + stream: StreamRef, + tenant_id: Option, + log_source: LogSource, + telemetry_type: TelemetryType, + p_custom_fields: HashMap, + json: Value, + time_partition: Option, +) -> Result<(), PostError> { + let stream_for_cpu = stream.clone(); + let (s, r) = oneshot::channel(); + rayon::spawn(move || { + let res = prepare_json_push_with_stream( + stream_for_cpu, + &tenant_id, + &log_source, + telemetry_type, + &p_custom_fields, + json, + time_partition, + ); + let _ = s.send(res); + }); + if let Some(prepared_events) = r + .await + .map_err(|e| PostError::CustomError(e.to_string()))?? + { + for prepared in prepared_events { + prepared.push_async(&stream, true).await.map_err(|e| { + let post_err: PostError = e.into(); + error!( + "Ingestion failed for stream {}: {post_err}", + stream.stream_name + ); + post_err + })?; + } + } + Ok(()) +} + +/// Stages the pre-built, pre-encoded batch of a flat body directly via +/// `Stream::push_async` without a second Rayon hop or blocking any Rayon +/// worker. Should the stream no longer be the one the batch was built for, the +/// body is re-parsed on Rayon and goes through the general path instead. +#[allow(clippy::too_many_arguments)] +async fn stage_flat_body_async( + flat: FlatBody, + stream: StreamRef, + tenant_id: Option, + log_source: LogSource, + telemetry_type: TelemetryType, + p_custom_fields: HashMap, + time_partition: Option, +) -> Result<(), PostError> { + let FlatBody { + rb, + origin_size, + p_timestamp, + schema_key, + preencoded, + schema, + bytes, + } = flat; + let still_valid = time_partition.is_none() + && flat_staging_schema(&stream).is_some_and(|current| { + flat_body_matches_schema(&rb, &schema, ¤t, &p_custom_fields) + }); + if !still_valid { + let stream_for_cpu = stream.clone(); + let (s, r) = oneshot::channel(); + rayon::spawn(move || { + let res = serde_json::from_slice::(&bytes) + .map_err(PostError::from) + .and_then(|json| { + prepare_json_push_with_stream( + stream_for_cpu, + &tenant_id, + &log_source, + telemetry_type, + &p_custom_fields, + json.into_inner(), + time_partition, + ) + }); + let _ = s.send(res); + }); + if let Some(prepared_events) = r + .await + .map_err(|e| PostError::CustomError(e.to_string()))?? + { + for prepared in prepared_events { + prepared.push_async(&stream, true).await.map_err(|e| { + let post_err: PostError = e.into(); + error!( + "Ingestion failed for stream {}: {post_err}", + stream.stream_name + ); + post_err + })?; + } + } + return Ok(()); + } + + let stream_name = stream.stream_name.clone(); + count_custom_fields_not_applied(&rb, &p_custom_fields, &stream_name, &tenant_id); + let event = event::Event { + rb, + stream_name: stream_name.clone(), + origin_format: "json", + origin_size, + is_first_event: false, + parsed_timestamp: p_timestamp.naive_utc(), + time_partition: None, + custom_partition_values: HashMap::new(), + stream_type: StreamType::UserDefined, + telemetry_type, + tenant_id, + }; + let prepared = event + .prepare_preencoded_for_async_push_on_stream( + &stream, + PARSEABLE.options.dataset_fields_allowed_limit, + schema_key, + preencoded, + ) + .map_err(PostError::from) + .inspect_err(|e| error!("Ingestion failed for stream {stream_name}: {e}"))?; + prepared + .push_async(&stream, true) + .await + .map_err(PostError::from) + .inspect_err(|e| error!("Ingestion failed for stream {stream_name}: {e}"))?; + Ok(()) +} + // Handler for POST /api/v1/ingest // ingests events by extracting stream name from header // creates if stream does not exist -pub async fn ingest( - req: HttpRequest, - Json(json): Json, -) -> Result { +// +// The body is taken as bytes and parsed off the worker thread. It used to be +// extracted as `Json`, which parsed it on the worker before the +// handler ran; a request that extractor refused is still refused first, with +// the response the extractor gave. +pub async fn ingest(req: HttpRequest, body: JsonBytes) -> Result { + let body = body.0; + if !has_json_content_type(&req) { + return Ok(HttpResponse::from_error(JsonPayloadError::ContentType)); + } + let log_source = req + .headers() + .get(LOG_SOURCE_KEY) + .and_then(|h| h.to_str().ok()) + .map_or(LogSource::default(), LogSource::from); + // Only a plain JSON body can be built into a batch without its value: + // a custom source extracts fields from the value, the others reshape it. + let flat_stream = (log_source == LogSource::Json) + .then(|| flat_ingest_stream(&req)) + .flatten(); + let had_non_internal_flat_stream = flat_stream.is_some(); + let p_custom_fields = get_custom_fields_from_header(&req); + let (parsed_body, mut p_custom_fields) = + parse_body_off_worker(body, flat_stream, p_custom_fields).await?; + let mut body = match parsed_body { + Ok(body) => body, + Err(e) => return Ok(HttpResponse::from_error(JsonPayloadError::Deserialize(e))), + }; + let Some(stream_name) = optional_header_str(req.headers(), STREAM_NAME_HEADER_KEY)? else { return Err(PostError::Header(ParseHeaderError::MissingStreamName)); }; @@ -119,17 +529,12 @@ pub async fn ingest( let tenant_id = get_tenant_id_from_request(&req)?; // One stream lookup answers the internal-stream question directly; building // the tenant's list of internal stream names would lock every stream's - // metadata on every request. - if is_internal_stream(&stream_name, &tenant_id) { + // metadata on every request. When `flat_ingest_stream` already verified a + // non-internal stream for these exact headers, skip the redundant lookup. + if !had_non_internal_flat_stream && is_internal_stream(&stream_name, &tenant_id) { return Err(PostError::InternalStream(stream_name)); } - let log_source = req - .headers() - .get(LOG_SOURCE_KEY) - .and_then(|h| h.to_str().ok()) - .map_or(LogSource::default(), LogSource::from); - let telemetry_type = req .headers() .get(TELEMETRY_TYPE_KEY) @@ -152,23 +557,17 @@ pub async fn ingest( return Err(PostError::OtelNotSupported(stream_name)); } - let mut p_custom_fields = get_custom_fields_from_header(&req); - let mut json = json.into_inner(); - - let fields = match &log_source { - LogSource::Custom(src) => KNOWN_SCHEMA_LIST.extract_from_inline_log( - &mut json, - &mut p_custom_fields, - src, - extract_log.as_deref(), - )?, + // A body of a custom source is always parsed to its value + let fields = match (&log_source, &mut body) { + (LogSource::Custom(src), IngestBody::Json(json)) => KNOWN_SCHEMA_LIST + .extract_from_inline_log(json, &mut p_custom_fields, src, extract_log.as_deref())?, _ => HashSet::new(), }; let log_source_entry = LogSourceEntry::new(log_source.clone(), fields); - PARSEABLE - .create_stream_if_not_exists_with( + let (stream, _existed) = PARSEABLE + .ensure_stream_with( &stream_name, StreamType::UserDefined, None, @@ -184,16 +583,15 @@ pub async fn ingest( e })?; - // if stream exists, fetch the stream log source + // if stream exists, validate the stream log source directly under one read lock // return error if the stream log source is otel traces or otel metrics - validate_stream_for_ingestion(&stream_name, &log_source, &tenant_id).map_err(|e| { + validate_stream_ref_for_ingestion(&stream, &log_source).map_err(|e| { error!("Ingestion failed for stream {stream_name}: {e}"); e })?; - let stream = PARSEABLE.get_stream(&stream_name, &tenant_id)?; PARSEABLE - .add_update_log_source(&stream_name, log_source_entry, &tenant_id) + .add_update_log_source_on_stream(&stream, log_source_entry, &tenant_id) .await .map_err(|e| { error!("Ingestion failed for stream {stream_name}: {e}"); @@ -202,25 +600,34 @@ pub async fn ingest( let time_partition = stream.get_time_partition(); - let (s, r) = oneshot::channel(); - rayon::spawn(move || { - let res = ingest_helper( - stream_name, - tenant_id, - log_source, - telemetry_type, - p_custom_fields, - json, - time_partition, - ); - let _ = s.send(res); - }); - - if let Err(e) = r.await.map_err(|e| PostError::CustomError(e.to_string()))? { - Err(e) - } else { - Ok(HttpResponse::Ok().finish()) + match body { + IngestBody::Json(json) => { + stage_json_body_async( + stream, + tenant_id, + log_source, + telemetry_type, + p_custom_fields, + json, + time_partition, + ) + .await?; + } + IngestBody::Flat(flat) => { + stage_flat_body_async( + *flat, + stream, + tenant_id, + log_source, + telemetry_type, + p_custom_fields, + time_partition, + ) + .await?; + } } + + Ok(HttpResponse::Ok().finish()) } pub async fn ingest_internal_stream( @@ -295,8 +702,8 @@ pub async fn setup_otel_stream( if is_internal_stream(&stream_name, &tenant_id) { return Err(PostError::InternalStream(stream_name)); } - PARSEABLE - .create_stream_if_not_exists_with( + let (stream, _existed) = PARSEABLE + .ensure_stream_with( &stream_name, StreamType::UserDefined, None, @@ -316,14 +723,14 @@ pub async fn setup_otel_stream( dataset_labels, ) .await?; - let mut time_partition = None; - // Validate stream compatibility - if let Ok(stream) = PARSEABLE.get_stream(&stream_name, &tenant_id) { + // Validate stream compatibility under a single metadata read lock (no clones). + let time_partition = { + let metadata = stream.metadata.read().expect(crate::LOCK_EXPECT); match log_source { LogSource::OtelLogs => { // For logs, reject if stream is metrics or traces - stream - .get_log_source() + metadata + .log_source .iter() .find(|&stream_log_source_entry| { stream_log_source_entry.log_source_format != LogSource::OtelTraces @@ -333,8 +740,8 @@ pub async fn setup_otel_stream( } LogSource::OtelMetrics | LogSource::OtelTraces => { // For metrics/traces, only allow same type - stream - .get_log_source() + metadata + .log_source .iter() .find(|&stream_log_source_entry| { stream_log_source_entry.log_source_format == log_source @@ -343,12 +750,11 @@ pub async fn setup_otel_stream( } _ => {} } - - time_partition = stream.get_time_partition(); - } + metadata.time_partition.clone() + }; PARSEABLE - .add_update_log_source(&stream_name, log_source_entry.clone(), &tenant_id) + .add_update_log_source_on_stream(&stream, log_source_entry.clone(), &tenant_id) .await?; Ok((stream_name, log_source, log_source_entry, time_partition)) @@ -509,23 +915,28 @@ pub async fn post_event( // if stream exists, fetch the stream log source // return error if the stream log source is otel traces or otel metrics or otel logs - if let Err(e) = validate_stream_for_ingestion(&stream_name, &log_source, &tenant_id) { + let stream = PARSEABLE + .get_stream(&stream_name, &tenant_id) + .map_err(|e| { + let post_err: PostError = e.into(); + error!("Ingestion failed for stream {stream_name}: {post_err}"); + post_err + })?; + if let Err(e) = validate_stream_ref_for_ingestion(&stream, &log_source) { error!("Ingestion failed for stream {stream_name}: {e}"); return Err(e); } - if let Err(e) = flatten_and_push_logs( + stage_json_body_async( + stream, + tenant_id, + log_source, + TelemetryType::Logs, + p_custom_fields, json, - &stream_name, - &log_source, - &p_custom_fields, None, - TelemetryType::Logs, - &tenant_id, - ) { - error!("Ingestion failed for stream {stream_name}: {e}"); - return Err(e); - } + ) + .await?; Ok(HttpResponse::Ok().finish()) } @@ -1291,7 +1702,10 @@ mod tests { mod header_error_tests { use actix_web::{ ResponseError, - http::{StatusCode, header::HeaderValue}, + http::{ + StatusCode, + header::{CONTENT_TYPE, HeaderValue}, + }, test::TestRequest, web::Json, }; @@ -1308,12 +1722,22 @@ mod header_error_tests { Json(serde_json::from_str("{}").expect("empty object is strict JSON")) } + /// The body `/api/v1/ingest` takes as bytes + fn empty_bytes() -> web::Bytes { + web::Bytes::from_static(b"{}") + } + + /// A request with the content type `/api/v1/ingest` asks for + fn json_request() -> TestRequest { + TestRequest::default().insert_header((CONTENT_TYPE, "application/json")) + } + #[actix_web::test] async fn ingest_rejects_non_ascii_stream_header_with_400() { - let req = TestRequest::default() + let req = json_request() .insert_header((STREAM_NAME_HEADER_KEY, non_ascii())) .to_http_request(); - let err = ingest(req, empty_body()).await.unwrap_err(); + let err = ingest(req, empty_bytes().into()).await.unwrap_err(); assert!(matches!( err, PostError::Header(ParseHeaderError::InvalidValue) @@ -1323,8 +1747,8 @@ mod header_error_tests { #[actix_web::test] async fn ingest_missing_stream_header_is_still_missing() { - let req = TestRequest::default().to_http_request(); - let err = ingest(req, empty_body()).await.unwrap_err(); + let req = json_request().to_http_request(); + let err = ingest(req, empty_bytes().into()).await.unwrap_err(); assert!(matches!( err, PostError::Header(ParseHeaderError::MissingStreamName) @@ -1333,11 +1757,11 @@ mod header_error_tests { #[actix_web::test] async fn ingest_rejects_malformed_tenant_with_400() { - let req = TestRequest::default() + let req = json_request() .insert_header((STREAM_NAME_HEADER_KEY, "app")) .insert_header((TENANT_ID, non_ascii())) .to_http_request(); - let err = ingest(req, empty_body()).await.unwrap_err(); + let err = ingest(req, empty_bytes().into()).await.unwrap_err(); assert!(matches!( err, PostError::Header(ParseHeaderError::InvalidTenantId) @@ -1895,9 +2319,10 @@ mod dataset_tag_tests { #[tokio::test] async fn header_named_ingest_creates_the_stream_with_the_tags_of_the_request() { crate::parseable::install_default_test_parseable(); - let body = || Json(serde_json::from_str::("{}").unwrap()); + let body = || JsonBytes::from(web::Bytes::from_static(b"{}")); let request = |stream: &str, tags: &'static str| { TestRequest::default() + .insert_header((CONTENT_TYPE, "application/json")) .insert_header((STREAM_NAME_HEADER_KEY, stream)) .insert_header((LOG_SOURCE_KEY, "kinesis")) .insert_header((DATASET_TAGS_KEY, tags)) @@ -1935,3 +2360,507 @@ mod dataset_tag_tests { ); } } + +/// `/api/v1/ingest` takes its body as bytes: it refuses what the +/// `Json` extractor refused, with the same response, and stages a +/// batch built from the bytes as the general path stages the same body. +#[cfg(test)] +mod ingest_body_tests { + use actix_web::http::header::CONTENT_TYPE; + use actix_web::test::TestRequest; + use actix_web::{FromRequest, ResponseError, body::to_bytes}; + use arrow_schema::Schema; + + use super::*; + + async fn parts(response: HttpResponse) -> (StatusCode, Option, Bytes) { + let content_type = response + .headers() + .get(CONTENT_TYPE) + .map(|value| value.to_str().unwrap().to_owned()); + let status = response.status(); + ( + status, + content_type, + to_bytes(response.into_body()).await.unwrap(), + ) + } + + fn request(content_type: Option<&'static str>, body: &[u8]) -> TestRequest { + let request = TestRequest::post() + .app_data(web::JsonConfig::default().limit(16 * 1024 * 1024)) + .set_payload(body.to_vec()); + match content_type { + Some(content_type) => request.insert_header((CONTENT_TYPE, content_type)), + None => request, + } + } + + #[actix_web::test] + async fn bodies_are_refused_as_the_json_extractor_refused_them() { + // Longer than a body that is parsed on the worker + let long = |tail: &str| { + let row = r#"{"message":"a row of a batch that is parsed off the worker","n":1},"#; + let text = format!( + "[{}{tail}", + row.repeat(INLINE_PARSE_MAX_BYTES / row.len() + 1) + ); + assert!(text.len() > INLINE_PARSE_MAX_BYTES); + text + }; + let bodies = [ + "".to_owned(), + " ".to_owned(), + "{".to_owned(), + "[1,]".to_owned(), + "{} trailing".to_owned(), + "{}{}".to_owned(), + "\u{feff}{}".to_owned(), + r#"{"a":1,"a":2}"#.to_owned(), + r#"{"a":1,"a":2}"#.to_owned(), + r#"[{"a":{"b":1,"b":2}}]"#.to_owned(), + r#"{"a":1e400}"#.to_owned(), + r#"{"a":NaN}"#.to_owned(), + r#"{"a":Infinity}"#.to_owned(), + r#"{"a":"\ud800"}"#.to_owned(), + long(r#"{"a":1,"a":2}]"#), + long(r#"{"a":1}"#), + long(r#"{"a":1e400}]"#), + // Bodies the extractor took + "{}".to_owned(), + "[]".to_owned(), + "1".to_owned(), + "null".to_owned(), + r#" [ {"a": 1, "b": [true, null, {"c": "d"}]} ] "#.to_owned(), + long(r#"{"a":1}]"#), + ]; + let content_types = [ + None, + Some("application/json"), + Some("application/json; charset=utf-8"), + Some("APPLICATION/JSON"), + Some("application/vnd.api+json"), + Some("text/json"), + Some("text/plain"), + Some("application/x-ndjson"), + Some("application/octet-stream"), + Some("json"), + Some(""), + ]; + let (mut refused, mut taken) = (0, 0); + for content_type in content_types { + for body in &bodies { + let (req, mut payload) = request(content_type, body.as_bytes()).to_http_parts(); + let extracted = Json::::from_request(&req, &mut payload).await; + let handled = ingest( + request(content_type, body.as_bytes()).to_http_request(), + JsonBytes::from(web::Bytes::from(body.clone())), + ) + .await; + match extracted { + Err(error) => { + let handled = handled.expect("a refused body is answered, not an error"); + assert_eq!( + parts(handled).await, + parts(error.error_response()).await, + "{content_type:?} {body}" + ); + refused += 1; + } + // The handler then gets as far as the stream header, of + // which the request has none + Ok(_) => { + assert!( + matches!( + handled, + Err(PostError::Header(ParseHeaderError::MissingStreamName)) + ), + "{content_type:?} {body}" + ); + taken += 1; + } + } + } + } + // Five content types are JSON, six bodies are strict JSON + assert_eq!(taken, 5 * 6); + assert_eq!(refused, content_types.len() * bodies.len() - taken); + } + + /// `JsonBytes` enforces the exact same content-type precedence, status code, + /// and response body text as Actix's `Json` extractor across both + /// valid and invalid content types and both declared and streaming limits. + #[actix_web::test] + async fn the_body_limit_refuses_what_the_json_limit_refused() { + const LIMIT: usize = 64; + for content_type in [Some("application/json"), Some("text/plain"), None] { + for len in [2, LIMIT - 1, LIMIT, LIMIT + 1, 4 * LIMIT] { + // A JSON document of that length + let body = format!("{:::from_request(&req, &mut payload).await { + Ok(_) => Ok(()), + Err(error) => Err(parts(error.error_response()).await), + }; + let (req, mut payload) = request().to_http_parts(); + let bytes = match JsonBytes::from_request(&req, &mut payload).await { + Ok(_) => Ok(()), + Err(error) => Err(parts(error.error_response()).await), + }; + assert_eq!( + bytes, json, + "content_type={content_type:?} len={len} declared={declared}" + ); + if content_type != Some("application/json") { + assert_eq!( + bytes.as_ref().unwrap_err().0, + StatusCode::BAD_REQUEST, + "wrong content-type must return 400 even when oversized" + ); + } else if len > LIMIT { + assert_eq!(bytes.as_ref().unwrap_err().0, StatusCode::PAYLOAD_TOO_LARGE); + } else { + assert!(bytes.is_ok()); + } + } + } + } + } + + /// What the extractor answered for the usual mistakes, which come before + /// anything the handler refuses + #[actix_web::test] + async fn refused_bodies_get_the_extractors_answer() { + for (content_type, body, message) in [ + (None, "{}", "Content type error"), + (Some("text/plain"), "{}", "Content type error"), + ( + Some("application/json"), + "", + "Json deserialize error: EOF while parsing a value", + ), + ( + Some("application/json"), + r#"{"a":1,"a":2}"#, + "Json deserialize error: duplicate key in JSON", + ), + ( + Some("application/json"), + r#"{"a":1e400}"#, + "Json deserialize error: number out of range", + ), + ] { + let response = ingest( + request(content_type, body.as_bytes()) + // Headers that are refused too, after the body + .insert_header((STREAM_NAME_HEADER_KEY, "pmeta")) + .insert_header((LOG_SOURCE_KEY, "otel-logs")) + .to_http_request(), + JsonBytes::from(web::Bytes::from(body)), + ) + .await + .unwrap(); + let (status, content_type, text) = parts(response).await; + assert_eq!(status, StatusCode::BAD_REQUEST); + assert_eq!(content_type.as_deref(), Some("text/plain; charset=utf-8")); + let text = String::from_utf8(text.to_vec()).unwrap(); + assert!(text.starts_with(message), "{text}"); + } + } + + /// A server with the options of a default deployment that staging depends + /// on. The one other tests install leaves them all at zero: rows are then + /// never taken as flat, and a stream with a field takes no second request. + fn deployed_parseable() -> crate::parseable::Parseable { + use crate::storage::object_storage::ObjectStorageProvider; + let root = tempfile::tempdir().expect("a temporary directory").keep(); + let provider = Arc::new(crate::storage::FSConfig { root }); + let storage = provider.construct_client(); + let metastore = Arc::new( + crate::metastore::metastores::object_store_metastore::ObjectStoreMetastore { + storage: storage.clone(), + }, + ); + let limits = FlattenLimits::DEFAULT; + let options = crate::cli::Options { + // Kept, like the store, for the life of the process + local_staging_path: tempfile::tempdir() + .expect("a temporary staging directory") + .keep(), + event_flatten_level: 10, + dataset_fields_allowed_limit: 1000, + max_flatten_rows_per_event: limits.max_rows_per_event, + max_flatten_rows_per_request: limits.max_rows_per_request, + max_flatten_bytes_per_request: limits.max_bytes_per_request, + ..Default::default() + }; + crate::parseable::Parseable::new( + options, + #[cfg(feature = "kafka")] + ::parse_from([ + "contract", + ]), + provider, + metastore, + storage, + ) + } + + /// Whether this process is the one that runs the body of `test`, with + /// `deployed_parseable` as its server. Otherwise the test is run again in + /// such a process, alone, as the server of a process is set only once. + fn in_deployed_process(test: &str) -> bool { + const CHILD: &str = "PARSEABLE_INGEST_BODY_TESTS_CHILD"; + if std::env::var_os(CHILD).is_some() { + let _ = crate::parseable::CONTRACT_PARSEABLE_FACTORY.set(deployed_parseable); + assert_eq!(PARSEABLE.options.event_flatten_level, 10); + return true; + } + let name = format!("{}::{test}", module_path!().split_once("::").unwrap().1); + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", &name, "--nocapture"]) + .env(CHILD, "1") + .output() + .unwrap(); + assert!( + output.status.success() && String::from_utf8_lossy(&output.stdout).contains("1 passed"), + "{test}\n{}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + false + } + + fn new_stream_name(prefix: &str) -> String { + format!("{prefix}{}", ulid::Ulid::new()).to_lowercase() + } + + fn ingest_request(stream: &str) -> HttpRequest { + TestRequest::post() + .insert_header((CONTENT_TYPE, "application/json")) + .insert_header((STREAM_NAME_HEADER_KEY, stream)) + .insert_header(("x-p-team", "search")) + .to_http_request() + } + + async fn post(stream: &str, body: &'static str) -> Result { + ingest( + ingest_request(stream), + JsonBytes::from(web::Bytes::from_static(body.as_bytes())), + ) + .await + } + + /// The general path for a body, as the handler took it before + fn general(stream: &str, body: &str) -> Result<(), PostError> { + ingest_helper( + stream.to_owned(), + None, + LogSource::Json, + TelemetryType::Logs, + get_custom_fields_from_header(&ingest_request(stream)), + serde_json::from_str::(body) + .unwrap() + .into_inner(), + None, + ) + } + + fn flat(stream: &str, body: &'static str) -> Option { + let p_custom_fields = get_custom_fields_from_header(&ingest_request(stream)); + let stream = PARSEABLE.get_stream(stream, &None).unwrap(); + match parse_body( + web::Bytes::from_static(body.as_bytes()), + Some(stream), + &p_custom_fields, + ) + .unwrap() + { + IngestBody::Flat(flat) => Some(*flat), + IngestBody::Json(_) => None, + } + } + + /// The stream's schema and staged rows, without the ingestion time. The + /// batches are ordered by their content, as staging keeps them by schema + /// in no particular order. + fn staged(stream: &str) -> (Arc, Vec) { + let stream = PARSEABLE.get_stream(stream, &None).unwrap(); + let schema = stream.get_schema(); + let mut batches: Vec = stream + .recordbatches_cloned(&schema) + .unwrap() + .into_iter() + .map(|batch| { + let timestamp = batch + .schema() + .index_of(crate::event::DEFAULT_TIMESTAMP_KEY) + .unwrap(); + let mut batch = batch; + batch.remove_column(timestamp); + batch + }) + .collect(); + batches.sort_by_cached_key(|batch| format!("{batch:?}")); + (schema, batches) + } + + const FIRST: &str = + r#"[{"msg":"first","n":1.5,"ok":true,"at":"2025-01-02T03:04:05Z","count":7}]"#; + const FLAT: &str = r#"[ + {"n": 2, "msg": "second"}, + {"ok": false, "at": "2025-01-02T03:04:06.5+05:30", "msg": "third\n", "count": -1e2}, + {}, + {"msg": null, "n": 18446744073709551615} + ]"#; + + #[tokio::test] + async fn a_flat_body_is_staged_like_the_general_path_stages_it() { + if !in_deployed_process("a_flat_body_is_staged_like_the_general_path_stages_it") { + return; + } + let (direct, twin) = (new_stream_name("flatdirect"), new_stream_name("flattwin")); + for stream in [&direct, &twin] { + // The stream is new: there is no schema to build a batch for + assert!(flat_ingest_stream(&ingest_request(stream)).is_none()); + assert_eq!(post(stream, FIRST).await.unwrap().status(), StatusCode::OK); + } + assert!(flat_ingest_stream(&ingest_request(&direct)).is_some()); + assert!(flat(&direct, FLAT).is_some()); + assert_eq!(post(&direct, FLAT).await.unwrap().status(), StatusCode::OK); + general(&twin, FLAT).unwrap(); + let (schema, batches) = staged(&direct); + assert_eq!((schema, batches.clone()), staged(&twin)); + assert_eq!( + batches.iter().map(RecordBatch::num_rows).sum::(), + 1 + 4 + ); + // The custom field of the request's header is on every row + assert!( + batches + .iter() + .all(|batch| batch.column_by_name("team").is_some()) + ); + + // Bodies that are not flat rows of the stream's fields take the + // general path, with the same outcome + for body in [ + r#"{"msg":"a new field","extra":1}"#, + r#"{"msg":"a conflict","n":"text"}"#, + r#"{"msg":"nested","at":{"day":2}}"#, + r#"[{"msg":"an array","tags":["a","b"]}]"#, + ] { + assert!(flat(&direct, body).is_none(), "{body}"); + assert_eq!(post(&direct, body).await.unwrap().status(), StatusCode::OK); + general(&twin, body).unwrap(); + assert_eq!(staged(&direct), staged(&twin), "{body}"); + } + // As do those it refuses + for body in [r#"{"p_timestamp":"2025-01-02T03:04:05Z"}"#, "[]", "1"] { + assert!(flat(&direct, body).is_none(), "{body}"); + let handled = post(&direct, body).await.unwrap_err(); + let expected = general(&twin, body).unwrap_err(); + assert_eq!(handled.to_string(), expected.to_string(), "{body}"); + assert_eq!(handled.status_code(), expected.status_code(), "{body}"); + } + assert_eq!(staged(&direct), staged(&twin)); + } + + #[tokio::test] + async fn a_refused_body_creates_no_stream() { + if !in_deployed_process("a_refused_body_creates_no_stream") { + return; + } + let stream = new_stream_name("refusedbody"); + let response = post(&stream, r#"[{"msg":"a","msg":"b"}]"#).await.unwrap(); + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + assert!(PARSEABLE.get_stream(&stream, &None).is_err()); + assert_eq!( + post(&stream, r#"[{"msg":"a"}]"#).await.unwrap().status(), + 200 + ); + assert!(PARSEABLE.get_stream(&stream, &None).is_ok()); + } + + #[tokio::test] + async fn a_batch_of_a_stream_that_changed_takes_the_general_path() { + if !in_deployed_process("a_batch_of_a_stream_that_changed_takes_the_general_path") { + return; + } + let built_for = new_stream_name("flatbuiltfor"); + assert_eq!( + post(&built_for, FIRST).await.unwrap().status(), + StatusCode::OK + ); + async fn stage(flat: FlatBody, stream: &str) -> Result<(), PostError> { + let stream_ref = PARSEABLE.get_stream(stream, &None)?; + stage_flat_body_async( + flat, + stream_ref, + None, + LogSource::Json, + TelemetryType::Logs, + get_custom_fields_from_header(&ingest_request(stream)), + None, + ) + .await + } + + // A stream that is gone + let gone = new_stream_name("flatgone"); + let error = stage(flat(&built_for, FLAT).unwrap(), &gone) + .await + .unwrap_err(); + assert!(matches!(error, PostError::StreamNotFound(_)), "{error}"); + + // A stream whose field is of another type than the batch's column: the + // batch is dropped, and the body is staged as the general path does + const OTHER: &str = r#"[{"msg":"first","n":"text","ok":true,"count":7}]"#; + let (changed, twin) = (new_stream_name("flatchanged"), new_stream_name("flattwin")); + for stream in [&changed, &twin] { + assert_eq!(post(stream, OTHER).await.unwrap().status(), StatusCode::OK); + } + stage(flat(&built_for, FLAT).unwrap(), &changed) + .await + .unwrap(); + general(&twin, FLAT).unwrap(); + assert_eq!(staged(&changed), staged(&twin)); + assert_ne!(staged(&changed).0, staged(&built_for).0); + + // A stream that gained fields still has those of the batch + let grown = flat(&built_for, FLAT).unwrap(); + assert_eq!( + post(&built_for, r#"{"msg":"grows","more":1}"#) + .await + .unwrap() + .status(), + StatusCode::OK + ); + let stream = PARSEABLE.get_stream(&built_for, &None).unwrap(); + assert!(!Arc::ptr_eq( + &grown.schema, + &stream.ingest_snapshot().schema + )); + let rows_before: usize = staged(&built_for).1.iter().map(RecordBatch::num_rows).sum(); + stage(grown, &built_for).await.unwrap(); + let (_, batches) = staged(&built_for); + let rows: usize = batches.iter().map(RecordBatch::num_rows).sum(); + assert_eq!(rows, rows_before + 4); + } +} diff --git a/src/handlers/http/modal/server.rs b/src/handlers/http/modal/server.rs index 78e498ebc..94152f823 100644 --- a/src/handlers/http/modal/server.rs +++ b/src/handlers/http/modal/server.rs @@ -706,7 +706,11 @@ impl Server { .to(ingest::ingest) .authorize_for_resource(Action::Ingest), ) - .app_data(web::JsonConfig::default().limit(max_event_payload_size())) + // Enforces Actix Json content-type precedence and exact payload-limit + // error variants while deferring JSON parsing off the Actix worker. + .app_data(ingest::JsonBytesConfig { + limit: max_event_payload_size(), + }) } // /v1/logs endpoint to be used for OTEL log ingestion only diff --git a/src/handlers/http/modal/utils/ingest_utils.rs b/src/handlers/http/modal/utils/ingest_utils.rs index 78379dc3b..e03047424 100644 --- a/src/handlers/http/modal/utils/ingest_utils.rs +++ b/src/handlers/http/modal/utils/ingest_utils.rs @@ -71,7 +71,7 @@ use crate::{ }, traces::flatten_traces_into, }, - parseable::{DEFAULT_TENANT, PARSEABLE, Stream}, + parseable::{DEFAULT_TENANT, IngestSnapshot, PARSEABLE, Stream, StreamRef}, storage::StreamType, utils::{ get_tenant_id_from_request, @@ -120,6 +120,93 @@ pub fn ingest_helper( Ok(()) } +/// Like `ingest_helper_with_stream`, preparing non-partitioned events (including +/// schema commit and parallel IPC pre-encoding) on the caller's CPU thread so +/// the async HTTP handler can await `Stream::push_async` without holding a Rayon +/// worker in `PushQueue`. Returns `Ok(None)` when the path already staged +/// synchronously (e.g. Kinesis, OTEL, or grouped custom-partitioned batches). +#[allow(clippy::too_many_arguments)] +pub(crate) fn prepare_json_push_with_stream( + stream: StreamRef, + tenant_id: &Option, + log_source: &LogSource, + telemetry_type: TelemetryType, + p_custom_fields: &HashMap, + json: Value, + time_partition: Option, +) -> Result>, PostError> { + let res = match log_source { + LogSource::Kinesis + | LogSource::OtelLogs + | LogSource::OtelTraces + | LogSource::OtelMetrics => { + flatten_and_push_logs_with_stream( + json, + stream.clone(), + log_source, + p_custom_fields, + time_partition, + telemetry_type, + tenant_id, + )?; + Ok(None) + } + _ => { + let snapshot = stream.ingest_snapshot(); + verify_dataset_fields_count_value(&stream.stream_name, snapshot.schema.len())?; + let mut budget = FlattenBudget::new(FlattenLimits::from_config()); + let staging = Staging::from_stream(stream.clone(), tenant_id); + let mut prepared = Vec::new(); + stage_json_with_snapshot( + StageInto { + tenant_id: staging.tenant_id, + stream: &staging.stream, + grouped: staging.grouped, + p_timestamp: staging.p_timestamp, + }, + snapshot, + json, + log_source, + p_custom_fields, + time_partition, + telemetry_type, + &mut budget, + StageOutput::PrepareAsync(&mut prepared), + )?; + Ok((!prepared.is_empty()).then_some(prepared)) + } + }; + res.inspect_err(|e| error!("Ingestion failed for stream {}: {e}", stream.stream_name)) +} + +/// Like `ingest_helper`, using an already-resolved stream handle instead of +/// re-looking up `PARSEABLE.streams`. +#[allow(clippy::too_many_arguments)] +pub fn ingest_helper_with_stream( + stream: StreamRef, + tenant_id: Option, + log_source: LogSource, + telemetry_type: TelemetryType, + p_custom_fields: HashMap, + json: Value, + time_partition: Option, +) -> Result<(), PostError> { + if let Err(e) = flatten_and_push_logs_with_stream( + json, + stream.clone(), + &log_source, + &p_custom_fields, + time_partition, + telemetry_type, + &tenant_id, + ) { + error!("Ingestion failed for stream {}: {e}", stream.stream_name); + return Err(e); + } + + Ok(()) +} + // Common content processing for OTEL ingestion pub async fn process_otel_content( req: &HttpRequest, @@ -572,6 +659,21 @@ fn ingest_otel_rows( &mut dyn RowSink, ) -> Result<(), PostError>, total: impl FnOnce() -> u64, +) -> Result { + ingest_otel_rows_with_stream(signal, target, None, body_len, records, flatten, total) +} + +fn ingest_otel_rows_with_stream( + signal: Signal, + target: &OtelTarget<'_>, + stream: Option, + body_len: usize, + records: u64, + flatten: impl FnOnce( + &mut FlattenBudget, + &mut dyn RowSink, + ) -> Result<(), PostError>, + total: impl FnOnce() -> u64, ) -> Result { if records == 0 { return Ok(OtelIngested::Full); @@ -582,7 +684,10 @@ fn ingest_otel_rows( max_event_payload_size(), FlattenLimits::from_config(), ); - let mut staging = Staging::new(target.stream_name, target.tenant_id)?; + let mut staging = match stream { + Some(stream) => Staging::from_stream(stream, target.tenant_id), + None => Staging::new(target.stream_name, target.tenant_id)?, + }; let (result, staged) = stage_otel_rows(limits, flatten, |rows| { staging.push( Value::Array(rows), @@ -599,15 +704,17 @@ fn ingest_otel_rows( } /// `ingest_otel_rows` for a request decoded whole (OTLP JSON) -fn ingest_otel_resources( +fn ingest_otel_resources_with_stream( resources: OtelResources<'_>, body_len: usize, target: &OtelTarget<'_>, + stream: Option, ) -> Result { let flatten_exemplars = PARSEABLE.options.otel_flatten_exemplars; - ingest_otel_rows( + ingest_otel_rows_with_stream( resources.signal(), target, + stream, body_len, resources.records(), |budget, sink| resources.flatten_into(budget, flatten_exemplars, sink), @@ -635,12 +742,25 @@ fn ingest_otel_json( json: Value, body_len: usize, target: &OtelTarget<'_>, +) -> Result { + ingest_otel_json_with_stream(json, body_len, target, None) +} + +fn ingest_otel_json_with_stream( + json: Value, + body_len: usize, + target: &OtelTarget<'_>, + stream: Option, ) -> Result { let normalise = PARSEABLE.options.normalise_otel_payload; // `{}` is the JSON encoding of an empty request, which the generated types // refuse for the collection it leaves out; it has no rows let empty = |json: &Value| -> Result { - verify_otel_fields_count(target.stream_name, target.tenant_id)?; + if let Some(stream) = &stream { + verify_dataset_fields_count_on_stream(stream)?; + } else { + verify_otel_fields_count(target.stream_name, target.tenant_id)?; + } Ok(json.as_object().is_some_and(|fields| fields.is_empty())) }; match target.log_source { @@ -649,22 +769,29 @@ fn ingest_otel_json( } LogSource::OtelLogs => { let logs: LogsData = deserialize_otel_json(json, normalise)?; - ingest_otel_resources(OtelResources::Logs(&logs.resource_logs), body_len, target) + ingest_otel_resources_with_stream( + OtelResources::Logs(&logs.resource_logs), + body_len, + target, + stream, + ) } LogSource::OtelMetrics => { let metrics: MetricsData = deserialize_otel_json(json, normalise)?; - ingest_otel_resources( + ingest_otel_resources_with_stream( OtelResources::Metrics(&metrics.resource_metrics), body_len, target, + stream, ) } LogSource::OtelTraces => { let traces: TracesData = deserialize_otel_json(json, normalise)?; - ingest_otel_resources( + ingest_otel_resources_with_stream( OtelResources::Traces(&traces.resource_spans), body_len, target, + stream, ) } other => Err(PostError::Invalid(anyhow::anyhow!( @@ -911,24 +1038,73 @@ pub fn flatten_and_push_logs( telemetry_type: TelemetryType, tenant_id: &Option, ) -> Result<(), PostError> { - if !matches!( + if matches!( log_source, LogSource::OtelLogs | LogSource::OtelTraces | LogSource::OtelMetrics ) { - // Verify the dataset fields count (the OTEL arms do it themselves) - verify_dataset_fields_count(stream_name, tenant_id)?; + let target = OtelTarget { + stream_name, + log_source, + p_custom_fields, + telemetry_type, + tenant_id, + }; + // The body's length, as the expansion cap counts it, is that of the + // JSON text of the value + let body_len = json_value_byte_size(&json) as usize; + if let OtelIngested::Partial { message, .. } = ingest_otel_json(json, body_len, &target)? { + return Err(PostError::Invalid(anyhow::Error::msg(message))); + } + return Ok(()); } - // Shared by every event of this request - let mut budget = FlattenBudget::new(FlattenLimits::from_config()); + let stream = PARSEABLE.get_stream(stream_name, tenant_id)?; + flatten_and_push_logs_with_stream( + json, + stream, + log_source, + p_custom_fields, + time_partition, + telemetry_type, + tenant_id, + ) +} + +#[instrument( + name = "flatten_and_push_logs", + level = "info", + skip( + json, + stream, + log_source, + p_custom_fields, + time_partition, + telemetry_type, + tenant_id + ), + fields(stream_name = %stream.stream_name) +)] +#[allow(clippy::too_many_arguments)] +pub fn flatten_and_push_logs_with_stream( + json: Value, + stream: StreamRef, + log_source: &LogSource, + p_custom_fields: &HashMap, + time_partition: Option, + telemetry_type: TelemetryType, + tenant_id: &Option, +) -> Result<(), PostError> { match log_source { LogSource::Kinesis => { + verify_dataset_fields_count_on_stream(&stream)?; + // Shared by every event of this request + let mut budget = FlattenBudget::new(FlattenLimits::from_config()); //custom flattening required for Amazon Kinesis let message: Message = serde_json::from_value(json)?; let flattened_kinesis_data = flatten_kinesis_logs(message, &mut budget)?; let record = convert_to_array(flattened_kinesis_data)?; - push_logs( - stream_name, + push_logs_with_stream( + stream, record, log_source, p_custom_fields, @@ -941,8 +1117,9 @@ pub fn flatten_and_push_logs( // Only reached through `handle_otel_ingestion`, which answers partial // successes itself; here they fail the request LogSource::OtelLogs | LogSource::OtelTraces | LogSource::OtelMetrics => { + let stream_name = stream.stream_name.clone(); let target = OtelTarget { - stream_name, + stream_name: &stream_name, log_source, p_custom_fields, telemetry_type, @@ -952,21 +1129,27 @@ pub fn flatten_and_push_logs( // JSON text of the value let body_len = json_value_byte_size(&json) as usize; if let OtelIngested::Partial { message, .. } = - ingest_otel_json(json, body_len, &target)? + ingest_otel_json_with_stream(json, body_len, &target, Some(stream))? { return Err(PostError::Invalid(anyhow::Error::msg(message))); } } - _ => push_logs( - stream_name, - json, - log_source, - p_custom_fields, - time_partition, - telemetry_type, - tenant_id, - &mut budget, - )?, + _ => { + // Take the ingest snapshot once and validate the dataset field count + // against it before flattening, avoiding a second metadata read lock. + let snapshot = stream.ingest_snapshot(); + verify_dataset_fields_count_value(&stream.stream_name, snapshot.schema.len())?; + let mut budget = FlattenBudget::new(FlattenLimits::from_config()); + Staging::from_stream(stream, tenant_id).push_with_budget_and_snapshot( + json, + log_source, + p_custom_fields, + time_partition, + telemetry_type, + &mut budget, + snapshot, + )?; + } } Ok(()) @@ -1009,15 +1192,51 @@ pub fn push_logs( ) } +#[instrument( + name = "push_logs", + level = "info", + skip( + stream, + json, + log_source, + p_custom_fields, + time_partition, + telemetry_type, + tenant_id, + budget + ), + fields(stream_name = %stream.stream_name, record_count = tracing::field::Empty) +)] +#[allow(clippy::too_many_arguments)] +#[cfg_attr(feature = "hotpath", hotpath::measure)] +pub fn push_logs_with_stream( + stream: StreamRef, + json: Value, + log_source: &LogSource, + p_custom_fields: &HashMap, + time_partition: Option, + telemetry_type: TelemetryType, + tenant_id: &Option, + budget: &mut FlattenBudget, +) -> Result<(), PostError> { + Staging::from_stream(stream, tenant_id).push_with_budget( + json, + log_source, + p_custom_fields, + time_partition, + telemetry_type, + budget, + ) +} + /// The stream one request is staged into, looked up once, and what every part of /// the request shares: its ingestion time (`p_timestamp`) and whether it uses the /// grouped path. A request can be staged in several parts (chunks); each part /// reads the stream's current schema, so it sees the fields the parts before it /// added, as a later request would. pub struct Staging<'a> { - stream_name: &'a str, tenant_id: &'a Option, - stream: std::sync::Arc, + stream: StreamRef, grouped: bool, p_timestamp: chrono::DateTime, /// Flattening budget of the parts, shared by all of them @@ -1025,24 +1244,27 @@ pub struct Staging<'a> { } impl<'a> Staging<'a> { - pub fn new(stream_name: &'a str, tenant_id: &'a Option) -> Result { + pub fn new(stream_name: &str, tenant_id: &'a Option) -> Result { + let stream = PARSEABLE.get_stream(stream_name, tenant_id)?; + Ok(Self::from_stream(stream, tenant_id)) + } + + pub fn from_stream(stream: StreamRef, tenant_id: &'a Option) -> Self { // Snapshot at request entry. A subscriber attaching later receives ordered // single-row slices from the grouped path. let grouped = use_partitioned_ingest_batching( PARSEABLE.options.partitioned_ingest_batching, PARSEABLE.options.mode, &crate::livetail::LIVETAIL, - stream_name, + &stream.stream_name, ); - let stream = PARSEABLE.get_stream(stream_name, tenant_id)?; - Ok(Self { - stream_name, + Self { tenant_id, stream, grouped, p_timestamp: Utc::now(), budget: FlattenBudget::new(FlattenLimits::from_config()), - }) + } } /// Stages one part of the request, charging its flattening to the budget @@ -1056,7 +1278,6 @@ impl<'a> Staging<'a> { telemetry_type: TelemetryType, ) -> Result<(), PostError> { let Self { - stream_name, tenant_id, stream, grouped, @@ -1065,7 +1286,6 @@ impl<'a> Staging<'a> { } = self; stage_json( StageInto { - stream_name, tenant_id, stream, grouped: *grouped, @@ -1091,7 +1311,6 @@ impl<'a> Staging<'a> { ) -> Result<(), PostError> { stage_json( StageInto { - stream_name: self.stream_name, tenant_id: self.tenant_id, stream: &self.stream, grouped: self.grouped, @@ -1105,17 +1324,50 @@ impl<'a> Staging<'a> { budget, ) } + + #[allow(clippy::too_many_arguments)] + fn push_with_budget_and_snapshot( + self, + json: Value, + log_source: &LogSource, + p_custom_fields: &HashMap, + time_partition: Option, + telemetry_type: TelemetryType, + budget: &mut FlattenBudget, + snapshot: IngestSnapshot, + ) -> Result<(), PostError> { + stage_json_with_snapshot( + StageInto { + tenant_id: self.tenant_id, + stream: &self.stream, + grouped: self.grouped, + p_timestamp: self.p_timestamp, + }, + snapshot, + json, + log_source, + p_custom_fields, + time_partition, + telemetry_type, + budget, + StageOutput::Sync, + ) + } } /// What `stage_json` takes from a `Staging` struct StageInto<'a> { - stream_name: &'a str, tenant_id: &'a Option, - stream: &'a Stream, + stream: &'a StreamRef, grouped: bool, p_timestamp: chrono::DateTime, } +enum StageOutput<'a> { + Sync, + PrepareAsync(&'a mut Vec), +} + /// Stages one part of a request fn stage_json( into: StageInto<'_>, @@ -1125,17 +1377,42 @@ fn stage_json( time_partition: Option, telemetry_type: TelemetryType, budget: &mut FlattenBudget, +) -> Result<(), PostError> { + // One metadata read lock for everything below; the schema map is shared + // with other requests while it is unchanged instead of deep-cloned. + let snapshot = into.stream.ingest_snapshot(); + stage_json_with_snapshot( + into, + snapshot, + json, + log_source, + p_custom_fields, + time_partition, + telemetry_type, + budget, + StageOutput::Sync, + ) +} + +#[allow(clippy::too_many_arguments)] +fn stage_json_with_snapshot( + into: StageInto<'_>, + snapshot: IngestSnapshot, + json: Value, + log_source: &LogSource, + p_custom_fields: &HashMap, + time_partition: Option, + telemetry_type: TelemetryType, + budget: &mut FlattenBudget, + output: StageOutput<'_>, ) -> Result<(), PostError> { let StageInto { - stream_name, tenant_id, stream, grouped, p_timestamp, } = into; - // One metadata read lock for everything below; the schema map is shared - // with other requests while it is unchanged instead of deep-cloned. - let snapshot = stream.ingest_snapshot(); + let stream_name = stream.stream_name.as_str(); let time_partition_limit = snapshot.time_partition_limit; let static_schema_flag = snapshot.static_schema_flag; let custom_partition = snapshot.custom_partition; @@ -1202,7 +1479,15 @@ fn stage_json( telemetry_type, tenant_id: tenant_id.to_owned(), }; - event.process()?; + match output { + StageOutput::Sync => event.process_on_stream(stream)?, + StageOutput::PrepareAsync(prepared) => { + prepared.push(event.prepare_for_async_push_on_stream( + stream, + PARSEABLE.options.dataset_fields_allowed_limit, + )?); + } + } } else if !grouped { // Per-record path for custom-partitioned streams let events: Result, _> = data @@ -1241,13 +1526,22 @@ fn stage_json( &schemas, PARSEABLE.options.dataset_fields_allowed_limit, )?; - if committed && !stream.get_static_schema_flag() { + if committed && !static_schema_flag { stream .stage_schema_file(stream.get_schema().as_ref().clone()) .map_err(EventError::from)?; } - for event in events { - event.process_without_field_limit()?; + match output { + StageOutput::Sync => { + for event in events { + event.process_without_field_limit_on_stream(stream)?; + } + } + StageOutput::PrepareAsync(prepared) => { + for event in events { + prepared.push(event.prepare_for_async_push_on_stream(stream, usize::MAX)?); + } + } } } else { let records = data @@ -1290,7 +1584,7 @@ fn stage_json( &schemas, PARSEABLE.options.dataset_fields_allowed_limit, )?; - if committed && !stream.get_static_schema_flag() { + if committed && !static_schema_flag { stream .stage_schema_file(stream.get_schema().as_ref().clone()) .map_err(EventError::from)?; @@ -1423,14 +1717,16 @@ fn verify_otel_fields_count( } } -fn verify_dataset_fields_count( +pub fn verify_dataset_fields_count_on_stream(stream: &Stream) -> Result<(), PostError> { + verify_dataset_fields_count_value(&stream.stream_name, stream.get_schema_len()) +} + +fn verify_dataset_fields_count_value( stream_name: &str, - tenant_id: &Option, + fields_count: usize, ) -> Result<(), PostError> { - let fields_count = PARSEABLE - .get_stream(stream_name, tenant_id)? - .get_schema_len(); - let dataset_fields_warn_threshold = 0.8 * PARSEABLE.options.dataset_fields_allowed_limit as f64; + let limit = PARSEABLE.options.dataset_fields_allowed_limit; + let dataset_fields_warn_threshold = 0.8 * limit as f64; // Check if the fields count exceeds the warn threshold if fields_count > dataset_fields_warn_threshold as usize { tracing::trace!( @@ -1438,17 +1734,14 @@ fn verify_dataset_fields_count( stream_name, fields_count, dataset_fields_warn_threshold as usize, - PARSEABLE.options.dataset_fields_allowed_limit + limit ); } // Check if the fields count exceeds the limit // Return an error if the fields count exceeds the limit - if fields_count > PARSEABLE.options.dataset_fields_allowed_limit { - let error = PostError::FieldsCountLimitExceeded( - stream_name.to_string(), - fields_count, - PARSEABLE.options.dataset_fields_allowed_limit, - ); + if fields_count > limit { + let error = + PostError::FieldsCountLimitExceeded(stream_name.to_string(), fields_count, limit); tracing::error!("{}", error); // Return an error if the fields count exceeds the limit return Err(error); @@ -1456,39 +1749,51 @@ fn verify_dataset_fields_count( Ok(()) } -pub fn validate_stream_for_ingestion( +fn verify_dataset_fields_count( stream_name: &str, - log_source: &LogSource, tenant_id: &Option, ) -> Result<(), PostError> { let stream = PARSEABLE.get_stream(stream_name, tenant_id)?; + verify_dataset_fields_count_on_stream(&stream) +} + +/// Validates a stream handle for ingestion under a single `metadata.read()` +/// lock with zero `Vec` or `String` clones on the happy path. +pub fn validate_stream_ref_for_ingestion( + stream: &Stream, + log_source: &LogSource, +) -> Result<(), PostError> { + let metadata = stream.metadata.read().expect(crate::LOCK_EXPECT); - if stream.is_deleting() { - return Err(PostError::StreamBeingDeleted(stream_name.to_string())); + if metadata.deleting { + return Err(PostError::StreamBeingDeleted(stream.stream_name.clone())); } // Validate that the stream's log source is compatible - stream - .get_log_source() - .iter() - .find(|&stream_log_source_entry| { - stream_log_source_entry.log_source_format != LogSource::OtelTraces - && stream_log_source_entry.log_source_format != LogSource::OtelMetrics - }) - .ok_or(PostError::IncorrectLogFormat(stream_name.to_string()))?; + let mut has_non_metric_trace = false; + let mut has_otel_logs = false; + for entry in &metadata.log_source { + if entry.log_source_format != LogSource::OtelTraces + && entry.log_source_format != LogSource::OtelMetrics + { + has_non_metric_trace = true; + } + if entry.log_source_format == LogSource::OtelLogs { + has_otel_logs = true; + } + } - // If stream has OtelLogs as log source, only allow OtelLogs ingestion - let has_otel_logs = stream - .get_log_source() - .iter() - .any(|entry| entry.log_source_format == LogSource::OtelLogs); + if !has_non_metric_trace { + return Err(PostError::IncorrectLogFormat(stream.stream_name.clone())); + } + // If stream has OtelLogs as log source, only allow OtelLogs ingestion if has_otel_logs && *log_source != LogSource::OtelLogs { - return Err(PostError::IncorrectLogFormat(stream_name.to_string())); + return Err(PostError::IncorrectLogFormat(stream.stream_name.clone())); } // Check for time partition - if stream.get_time_partition().is_some() { + if metadata.time_partition.is_some() { return Err(PostError::Invalid(anyhow::anyhow!( "Ingestion with time partition is not supported in Parseable OSS" ))); @@ -1497,6 +1802,15 @@ pub fn validate_stream_for_ingestion( Ok(()) } +pub fn validate_stream_for_ingestion( + stream_name: &str, + log_source: &LogSource, + tenant_id: &Option, +) -> Result<(), PostError> { + let stream = PARSEABLE.get_stream(stream_name, tenant_id)?; + validate_stream_ref_for_ingestion(&stream, log_source) +} + #[cfg(test)] mod tests { use super::*; @@ -2116,6 +2430,324 @@ mod tests { assert_eq!(custom_fields.get("team").unwrap(), "payments"); } + #[test] + fn validate_stream_ref_matches_validate_stream_for_ingestion() { + use crate::{ + event::format::LogSourceEntry, metadata::LogStreamMetadata, + parseable::install_default_test_parseable, + }; + use std::collections::HashSet; + + install_default_test_parseable(); + + fn verdict_key(res: Result<(), PostError>) -> (&'static str, String) { + match res { + Ok(()) => ("ok", String::new()), + Err(PostError::StreamBeingDeleted(s)) => { + ("deleting", PostError::StreamBeingDeleted(s).to_string()) + } + Err(PostError::IncorrectLogFormat(s)) => ( + "incorrect_format", + PostError::IncorrectLogFormat(s).to_string(), + ), + Err(PostError::Invalid(e)) => ("invalid", PostError::Invalid(e).to_string()), + Err(other) => ("other", other.to_string()), + } + } + + let entry = |fmt: LogSource| LogSourceEntry::new(fmt, HashSet::new()); + let cases: &[(&str, Vec, bool, Option<&str>)] = &[ + ("json_ok", vec![entry(LogSource::Json)], false, None), + ("otel_logs", vec![entry(LogSource::OtelLogs)], false, None), + ( + "otel_metrics", + vec![entry(LogSource::OtelMetrics)], + false, + None, + ), + ( + "otel_traces", + vec![entry(LogSource::OtelTraces)], + false, + None, + ), + ( + "otel_metrics_and_traces", + vec![entry(LogSource::OtelMetrics), entry(LogSource::OtelTraces)], + false, + None, + ), + ( + "json_and_otel_logs", + vec![entry(LogSource::Json), entry(LogSource::OtelLogs)], + false, + None, + ), + ("empty_sources", vec![], false, None), + ("deleting_json", vec![entry(LogSource::Json)], true, None), + ( + "deleting_metrics_timepart", + vec![entry(LogSource::OtelMetrics)], + true, + Some("ts"), + ), + ( + "time_partition_json", + vec![entry(LogSource::Json)], + false, + Some("ts"), + ), + ( + "time_partition_metrics", + vec![entry(LogSource::OtelMetrics)], + false, + Some("ts"), + ), + ( + "time_partition_otel_logs", + vec![entry(LogSource::OtelLogs)], + false, + Some("ts"), + ), + ]; + + let incoming_sources = [ + LogSource::Json, + LogSource::Kinesis, + LogSource::Custom("syslog".into()), + LogSource::OtelLogs, + LogSource::OtelMetrics, + LogSource::OtelTraces, + ]; + + let suffix = ulid::Ulid::new().to_string().to_lowercase(); + for tenant in [None, Some("tenant_val".to_string())] { + for (label, sources, deleting, time_partition) in cases { + let name = format!("val_{label}_{suffix}"); + let stream = PARSEABLE.streams.get_or_create( + PARSEABLE.options.clone(), + name.clone(), + LogStreamMetadata { + log_source: sources.clone(), + deleting: *deleting, + time_partition: time_partition.map(str::to_owned), + ..Default::default() + }, + None, + &tenant, + ); + + for incoming in &incoming_sources { + let via_ref = validate_stream_ref_for_ingestion(&stream, incoming); + let via_name = validate_stream_for_ingestion(&name, incoming, &tenant); + assert_eq!( + verdict_key(via_ref), + verdict_key(via_name), + "mismatch for case={label}, tenant={tenant:?}, incoming={incoming:?}" + ); + } + } + } + + // Spot-check expected error ordering explicitly: + // 1) StreamBeingDeleted wins over IncorrectLogFormat and time_partition + let deleting_stream = PARSEABLE + .get_stream(&format!("val_deleting_metrics_timepart_{suffix}"), &None) + .unwrap(); + assert!(matches!( + validate_stream_ref_for_ingestion(&deleting_stream, &LogSource::Json), + Err(PostError::StreamBeingDeleted(_)) + )); + // 2) IncorrectLogFormat wins over time_partition + let metrics_tp_stream = PARSEABLE + .get_stream(&format!("val_time_partition_metrics_{suffix}"), &None) + .unwrap(); + assert!(matches!( + validate_stream_ref_for_ingestion(&metrics_tp_stream, &LogSource::Json), + Err(PostError::IncorrectLogFormat(_)) + )); + // 3) OtelLogs stream rejects Json with IncorrectLogFormat, accepts OtelLogs + let otel_logs_stream = PARSEABLE + .get_stream(&format!("val_otel_logs_{suffix}"), &None) + .unwrap(); + assert!(matches!( + validate_stream_ref_for_ingestion(&otel_logs_stream, &LogSource::Json), + Err(PostError::IncorrectLogFormat(_)) + )); + assert!(validate_stream_ref_for_ingestion(&otel_logs_stream, &LogSource::OtelLogs).is_ok()); + // 4) Time partition returns exact Invalid message + let tp_stream = PARSEABLE + .get_stream(&format!("val_time_partition_json_{suffix}"), &None) + .unwrap(); + let err = validate_stream_ref_for_ingestion(&tp_stream, &LogSource::Json).unwrap_err(); + assert!(matches!(err, PostError::Invalid(_))); + assert_eq!( + err.to_string(), + "Invalid Request: Ingestion with time partition is not supported in Parseable OSS" + ); + } + + #[test] + fn ingest_helper_with_stream_and_verify_fields_count_on_stream_match_by_name() { + use crate::{ + cli::Options, + event::format::LogSourceEntry, + metadata::{LogStreamMetadata, SchemaVersion}, + parseable::install_default_test_parseable, + }; + use arrow_schema::{DataType, Field}; + use std::{collections::HashSet, sync::Arc}; + + install_default_test_parseable(); + let suffix = ulid::Ulid::new().to_string().to_lowercase(); + let name_a = format!("helper_by_name_{suffix}"); + let name_b = format!("helper_by_stream_{suffix}"); + let dir_a = temp_dir::TempDir::new().unwrap(); + let dir_b = temp_dir::TempDir::new().unwrap(); + + let register_stream = |name: &str, dir: &temp_dir::TempDir, metadata: LogStreamMetadata| { + let stream = Stream::new( + Arc::new(Options { + local_staging_path: dir.path().to_path_buf(), + ..Default::default() + }), + name, + metadata, + None, + &None, + ); + PARSEABLE + .streams + .write() + .unwrap() + .entry(DEFAULT_TENANT.to_owned()) + .or_default() + .insert(name.to_owned(), stream.clone()); + stream + }; + + let base_meta = || LogStreamMetadata { + schema_version: SchemaVersion::V1, + log_source: vec![LogSourceEntry::new(LogSource::Json, HashSet::new())], + ..Default::default() + }; + + let stream_a = register_stream(&name_a, &dir_a, base_meta()); + let stream_b = register_stream(&name_b, &dir_b, base_meta()); + let payload = serde_json::json!([ + {"msg": "hello", "code": 200}, + {"msg": "world", "code": 201} + ]); + let mut custom = HashMap::new(); + custom.insert("env".to_string(), "test".to_string()); + + let res_a = ingest_helper( + name_a.clone(), + None, + LogSource::Json, + TelemetryType::Logs, + custom.clone(), + payload.clone(), + None, + ); + let res_b = ingest_helper_with_stream( + stream_b.clone(), + None, + LogSource::Json, + TelemetryType::Logs, + custom.clone(), + payload, + None, + ); + + match (&res_a, &res_b) { + (Ok(()), Ok(())) => { + assert_eq!(stream_a.get_schema(), stream_b.get_schema()); + assert!(stream_b.get_schema().field_with_name("msg").is_ok()); + assert!(stream_b.get_schema().field_with_name("env").is_ok()); + } + ( + Err(PostError::FieldsCountLimitExceeded(_, c1, l1)), + Err(PostError::FieldsCountLimitExceeded(_, c2, l2)), + ) => { + assert_eq!((c1, l1), (c2, l2)); + } + other => panic!("ingest_helper vs ingest_helper_with_stream diverged: {other:?}"), + } + + // `Staging::from_stream` matches `Staging::new` on identical payloads. + let mut staging_a = Staging::new(&name_a, &None).unwrap(); + let mut staging_b = Staging::from_stream(stream_b.clone(), &None); + let stage_res_a = staging_a.push( + serde_json::json!([{"msg": "via_staging", "code": 202}]), + &LogSource::Json, + &custom, + None, + TelemetryType::Logs, + ); + let stage_res_b = staging_b.push( + serde_json::json!([{"msg": "via_staging", "code": 202}]), + &LogSource::Json, + &custom, + None, + TelemetryType::Logs, + ); + assert_eq!( + stage_res_a.is_ok(), + stage_res_b.is_ok(), + "Staging::new vs Staging::from_stream diverged: {stage_res_a:?} vs {stage_res_b:?}" + ); + assert_eq!(stream_a.get_schema(), stream_b.get_schema()); + + // `verify_dataset_fields_count_on_stream` matches `verify_dataset_fields_count` + assert!(verify_dataset_fields_count_on_stream(&stream_b).is_ok()); + let limit = PARSEABLE.options.dataset_fields_allowed_limit; + let over_name = format!("over_limit_{suffix}"); + let over_dir = temp_dir::TempDir::new().unwrap(); + let over_schema: HashMap> = (0..=limit) + .map(|i| { + let k = format!("f{i}"); + (k.clone(), Arc::new(Field::new(k, DataType::Utf8, true))) + }) + .collect(); + let over_stream = register_stream( + &over_name, + &over_dir, + LogStreamMetadata { + schema: over_schema, + schema_version: SchemaVersion::V1, + log_source: vec![LogSourceEntry::new(LogSource::Json, HashSet::new())], + ..Default::default() + }, + ); + let err_ref = verify_dataset_fields_count_on_stream(&over_stream).unwrap_err(); + let err_name = verify_dataset_fields_count(&over_name, &None).unwrap_err(); + assert_eq!(err_ref.to_string(), err_name.to_string()); + assert!(matches!( + err_ref, + PostError::FieldsCountLimitExceeded(_, count, lim) if count == limit + 1 && lim == limit + )); + // Over-limit stream also fails fast in `ingest_helper_with_stream` + let err_ingest = ingest_helper_with_stream( + over_stream, + None, + LogSource::Json, + TelemetryType::Logs, + HashMap::new(), + serde_json::json!({}), + None, + ) + .unwrap_err(); + assert!(matches!( + err_ingest, + PostError::FieldsCountLimitExceeded(_, count, lim) if count == limit + 1 && lim == limit + )); + + PARSEABLE.streams.delete(&name_a, &None); + PARSEABLE.streams.delete(&name_b, &None); + PARSEABLE.streams.delete(&over_name, &None); + } + // Micro-benchmarks and equivalence proofs for the shared ingest path. // The benches are `#[ignore]`d release-profile loops that // construct the objects the handlers read, so they never touch `PARSEABLE` diff --git a/src/main.rs b/src/main.rs index ee1e9d804..4469ca4a7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -54,11 +54,21 @@ unsafe impl Sync for MallocConf {} /// Compiled-in jemalloc defaults tuned for bounded RSS under bursty ingest and /// query workloads. Runtime `_RJEM_MALLOC_CONF` takes higher precedence and /// continues to override these defaults. +/// +/// `background_thread:true` has jemalloc's own threads do the decay purging +/// (returning freed pages to the OS), so a burst of frees, such as a staging +/// cache evicted at a minute rollover, is not purged by the next ingest +/// request on that arena. The `background_threads` feature of +/// `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. #[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".as_ptr()); +pub static MALLOC_CONF: MallocConf = MallocConf( + c"dirty_decay_ms:1000,muzzy_decay_ms:0,narenas:16,tcache_max:16384,background_thread:true" + .as_ptr(), +); #[actix_web::main] #[cfg_attr(feature = "hotpath", hotpath::main)] @@ -253,6 +263,23 @@ mod jemalloc_conf_tests { assert_eq!(narenas, 16); assert_eq!(tcache_max, 16384); + // Checked on Linux, where jemalloc always has background threads. + // Other platforms may be built without them; there is then nothing + // to check. + // SAFETY: `opt.background_thread` is a `bool` in jemalloc. + let requested = unsafe { tikv_jemalloc_ctl::raw::read::(b"opt.background_thread\0") }; + if cfg!(target_os = "linux") { + assert!( + requested.expect("opt.background_thread readable on linux"), + "compiled-in background_thread:true was not applied" + ); + // The option is the request; this is the state it results in. + assert!( + tikv_jemalloc_ctl::background_thread::read().expect("background_thread readable"), + "jemalloc background threads are not running" + ); + } + parseable::utils::allocator::purge_all_arenas().expect("purge_all_arenas succeeds"); let stats = parseable::utils::allocator::read_jemalloc_stats() .expect("read_jemalloc_stats returns live stats under jemalloc"); diff --git a/src/parseable/mod.rs b/src/parseable/mod.rs index b02b4ad1e..5f835c989 100644 --- a/src/parseable/mod.rs +++ b/src/parseable/mod.rs @@ -36,8 +36,8 @@ pub use staging::{ configure_memory_staging_budget, memory_staging_budget_bytes, set_memory_staging_external_pressure, total_memory_staging_bytes, }; -use streams::StreamRef; -pub use streams::{Stream, StreamNotFound, Streams}; +pub(crate) use streams::IngestSnapshot; +pub use streams::{Stream, StreamNotFound, StreamRef, Streams}; use tokio::try_join; use tracing::error; @@ -231,6 +231,8 @@ pub(crate) fn cold_load_attempted(stream_name: &str) -> bool { /// Serializes the creation of each stream on this node, see `create_stream`. static STREAM_CREATIONS: Lazy> = Lazy::new(Default::default); +static STREAM_LOG_SOURCE_UPDATES: Lazy> = + Lazy::new(Default::default); fn stream_creation_key(stream_name: &str, tenant_id: &Option) -> (String, String) { ( @@ -814,8 +816,39 @@ impl Parseable { dataset_tags: impl FnOnce() -> Result, PostError>, dataset_labels: Vec, ) -> Result { - if self.streams.contains(stream_name, tenant_id) { - return Ok(true); + let (_, existed) = self + .ensure_stream_with( + stream_name, + stream_type, + custom_partition, + log_source, + telemetry_type, + tenant_id, + dataset_tags, + dataset_labels, + ) + .await?; + Ok(existed) + } + + /// Like `create_stream_if_not_exists_with`, returning the resident + /// `StreamRef` alongside whether the stream already existed (`true`) or was + /// created by this call (`false`), so callers do not need a follow-up + /// `get_stream` lookup. + #[allow(clippy::too_many_arguments)] + pub async fn ensure_stream_with( + &self, + stream_name: &str, + stream_type: StreamType, + custom_partition: Option<&String>, + log_source: Vec, + telemetry_type: TelemetryType, + tenant_id: &Option, + dataset_tags: impl FnOnce() -> Result, PostError>, + dataset_labels: Vec, + ) -> Result<(StreamRef, bool), PostError> { + if let Ok(stream) = self.get_stream(stream_name, tenant_id) { + return Ok((stream, true)); } // validate custom partition if provided @@ -829,8 +862,8 @@ impl Parseable { let _creating = STREAM_CREATIONS .lock(stream_creation_key(stream_name, tenant_id)) .await; - if self.streams.contains(stream_name, tenant_id) { - return Ok(true); + if let Ok(stream) = self.get_stream(stream_name, tenant_id) { + return Ok((stream, true)); } // For distributed deployments, if the stream not found in memory map, @@ -841,29 +874,33 @@ impl Parseable { .load_stream_from_storage(stream_name, tenant_id) .await? { - return Ok(true); + let stream = self + .get_stream(stream_name, tenant_id) + .expect(STREAM_EXISTS); + return Ok((stream, true)); } // This request creates the stream: only now are its tags asked for let dataset_tags = dataset_tags()?; - self.write_new_stream( - stream_name.to_string(), - "", - None, - custom_partition, - false, - Arc::new(Schema::empty()), - stream_type, - log_source, - telemetry_type, - tenant_id, - dataset_tags, - dataset_labels, - true, - ) - .await?; + let stream = self + .write_new_stream( + stream_name.to_string(), + "", + None, + custom_partition, + false, + Arc::new(Schema::empty()), + stream_type, + log_source, + telemetry_type, + tenant_id, + dataset_tags, + dataset_labels, + true, + ) + .await?; - Ok(false) + Ok((stream, false)) } pub async fn add_update_log_source( @@ -875,46 +912,88 @@ impl Parseable { let stream = self .get_stream(stream_name, tenant_id) .expect(STREAM_EXISTS); - let mut log_sources = stream.get_log_source(); - let mut changed = false; + self.add_update_log_source_on_stream(&stream, log_source, tenant_id) + .await + } - // Try to find existing log source with the same format - if let Some(stream_log_source) = log_sources - .iter_mut() - .find(|source| source.log_source_format == log_source.log_source_format) + /// Updates the stream's recorded log sources and fields if `log_source` + /// introduces a new format or any new field, persisting only on change. + /// + /// Fast path: takes a single `stream.metadata.read()` lock and returns + /// `Ok(())` with zero clones and zero `HashSet` allocations when a matching + /// entry already exists and either `log_source.fields` is empty or every + /// field is already present. + pub async fn add_update_log_source_on_stream( + &self, + stream: &Stream, + log_source: LogSourceEntry, + tenant_id: &Option, + ) -> Result<(), StreamError> { + // Fast path: check under a read lock with zero clones or allocations. { - // Use a HashSet to efficiently track only new fields - let existing_fields: HashSet = - stream_log_source.fields.iter().cloned().collect(); - let new_fields: HashSet = log_source - .fields + let metadata = stream.metadata.read().expect(crate::LOCK_EXPECT); + if let Some(existing) = metadata + .log_source .iter() - .filter(|field| !existing_fields.contains(*field)) - .cloned() - .collect(); - - // Only update if there are new fields to add - if !new_fields.is_empty() { - stream_log_source.fields.extend(new_fields); - changed = true; + .find(|source| source.log_source_format == log_source.log_source_format) + && (log_source.fields.is_empty() + || log_source + .fields + .iter() + .all(|field| existing.fields.contains(field))) + { + return Ok(()); } - } else { - // If no matching log source found, add the new one - log_sources.push(log_source); - changed = true; } - // Only persist to storage if we made changes - if changed { - stream.set_log_source(log_sources.clone()); + // Slow path: serialize per-stream log_source updates so concurrent + // additions cannot clobber each other, persist BEFORE updating memory + // so failed storage writes remain retryable on the next request. + let _updating = STREAM_LOG_SOURCE_UPDATES + .lock(stream_creation_key(&stream.stream_name, tenant_id)) + .await; - let storage = self.storage.get_object_store(); - if let Err(err) = storage - .update_log_source_in_stream(stream_name, &log_sources, tenant_id) - .await + let updated_log_sources = { + let metadata = stream.metadata.read().expect(crate::LOCK_EXPECT); + if let Some(existing) = metadata + .log_source + .iter() + .find(|source| source.log_source_format == log_source.log_source_format) + && (log_source.fields.is_empty() + || log_source + .fields + .iter() + .all(|field| existing.fields.contains(field))) + { + return Ok(()); + } + + let mut candidate = metadata.log_source.clone(); + if let Some(existing) = candidate + .iter_mut() + .find(|source| source.log_source_format == log_source.log_source_format) { - return Err(StreamError::Storage(err)); + for field in log_source.fields { + existing.fields.insert(field); + } + } else { + candidate.push(log_source); } + candidate + }; + + let storage = self.storage.get_object_store(); + if let Err(err) = storage + .update_log_source_in_stream(&stream.stream_name, &updated_log_sources, tenant_id) + .await + { + return Err(StreamError::Storage(err)); + } + + // Only update in-memory metadata after storage persistence succeeded. + { + let mut metadata = stream.metadata.write().expect(crate::LOCK_EXPECT); + metadata.log_source = updated_log_sources; } Ok(()) @@ -1119,22 +1198,23 @@ impl Parseable { if self.streams.contains(&stream_name, tenant_id) { return Ok(false); } - self.write_new_stream( - stream_name, - time_partition, - time_partition_limit, - custom_partition, - static_schema_flag, - schema, - stream_type, - log_source, - telemetry_type, - tenant_id, - dataset_tags, - dataset_labels, - infer_timestamp, - ) - .await?; + let _ = self + .write_new_stream( + stream_name, + time_partition, + time_partition_limit, + custom_partition, + static_schema_flag, + schema, + stream_type, + log_source, + telemetry_type, + tenant_id, + dataset_tags, + dataset_labels, + infer_timestamp, + ) + .await?; Ok(true) } @@ -1156,7 +1236,7 @@ impl Parseable { dataset_tags: Vec, dataset_labels: Vec, infer_timestamp: bool, - ) -> Result<(), CreateStreamError> { + ) -> Result { // fail to proceed if invalid stream name if stream_type != StreamType::Internal { validator::new_stream_name(&stream_name, stream_type)?; @@ -1221,19 +1301,17 @@ impl Parseable { .map(|ingestor_metadata| ingestor_metadata.get_node_id()); // Gets write privileges only for creating the stream when it doesn't already exist. - self.streams.get_or_create( + let stream = self.streams.get_or_create( self.options.clone(), stream_name.to_owned(), metadata, ingestor_id, tenant_id, ); + Ok(stream) } - Err(err) => { - return Err(CreateStreamError::Storage { stream_name, err }); - } + Err(err) => Err(CreateStreamError::Storage { stream_name, err }), } - Ok(()) } async fn validate_and_update_custom_partition( @@ -2133,4 +2211,255 @@ mod tests { assert_eq!(resolved, TelemetryType::Logs); } } + + #[tokio::test] + async fn add_update_log_source_fast_path_skips_write_lock_and_persistence() { + use crate::storage::{FSConfig, LocalFS}; + + let dir = tempfile::tempdir().unwrap(); + // Absent backing directory: any persistence attempt would fail or create it. + let root = dir.path().join("absent-storage"); + let storage = Arc::new(LocalFS::new(root.clone())); + let server = Parseable::new( + Options::default(), + #[cfg(feature = "kafka")] + KafkaConfig::parse_from(["test"]), + Arc::new(FSConfig { root: root.clone() }), + Arc::new(ObjectStoreMetastore { + storage: storage.clone(), + }), + storage, + ); + + let name = new_stream_name("logsourcefast"); + let initial_sources = vec![ + LogSourceEntry::new(LogSource::Json, HashSet::new()), + LogSourceEntry::new( + LogSource::Custom("syslog".into()), + HashSet::from(["host".to_string(), "msg".to_string()]), + ), + ]; + let stream = server.streams.get_or_create( + server.options.clone(), + name.clone(), + LogStreamMetadata { + log_source: initial_sources.clone(), + ..Default::default() + }, + None, + &None, + ); + + // Hold a read lock while polling the fast path: any attempt to take a + // write lock would deadlock here. + { + let _read_guard = stream.metadata.read().unwrap(); + + // Matching format with empty fields -> immediate Ok(()) + let fut = server.add_update_log_source_on_stream( + &stream, + LogSourceEntry::new(LogSource::Json, HashSet::new()), + &None, + ); + tokio::pin!(fut); + assert!(matches!( + futures::poll!(fut), + std::task::Poll::Ready(Ok(())) + )); + + // Matching format with a subset of existing fields -> immediate Ok(()) + let fut = server.add_update_log_source_on_stream( + &stream, + LogSourceEntry::new( + LogSource::Custom("syslog".into()), + HashSet::from(["host".to_string()]), + ), + &None, + ); + tokio::pin!(fut); + assert!(matches!( + futures::poll!(fut), + std::task::Poll::Ready(Ok(())) + )); + + // Matching format with all existing fields -> immediate Ok(()) + let fut = server.add_update_log_source_on_stream( + &stream, + LogSourceEntry::new( + LogSource::Custom("syslog".into()), + HashSet::from(["host".to_string(), "msg".to_string()]), + ), + &None, + ); + tokio::pin!(fut); + assert!(matches!( + futures::poll!(fut), + std::task::Poll::Ready(Ok(())) + )); + } + + // Also exercise the by-name wrapper on the fast path. + server + .add_update_log_source( + &name, + LogSourceEntry::new(LogSource::Json, HashSet::new()), + &None, + ) + .await + .unwrap(); + + assert_eq!(stream.get_log_source(), initial_sources); + assert!( + !root.exists(), + "unchanged log source must never touch storage" + ); + } + + #[tokio::test] + async fn add_update_log_source_updates_and_persists_new_format_and_fields() { + install_default_test_parseable(); + let storage = PARSEABLE.storage.get_object_store(); + + for tenant in [None, Some("tenant1".to_string())] { + let name = new_stream_name("logsourcepersist"); + let initial = vec![LogSourceEntry::new(LogSource::Json, HashSet::new())]; + storage + .create_stream( + &name, + ObjectStoreFormat { + log_source: initial.clone(), + ..Default::default() + }, + Arc::new(Schema::empty()), + &tenant, + ) + .await + .unwrap(); + let stream = PARSEABLE.streams.get_or_create( + PARSEABLE.options.clone(), + name.clone(), + LogStreamMetadata { + log_source: initial, + ..Default::default() + }, + None, + &tenant, + ); + + // Adding a new log source format updates memory and persists. + PARSEABLE + .add_update_log_source_on_stream( + &stream, + LogSourceEntry::new( + LogSource::Custom("syslog".into()), + HashSet::from(["host".to_string()]), + ), + &tenant, + ) + .await + .unwrap(); + + let expected_after_format = vec![ + LogSourceEntry::new(LogSource::Json, HashSet::new()), + LogSourceEntry::new( + LogSource::Custom("syslog".into()), + HashSet::from(["host".to_string()]), + ), + ]; + assert_eq!(stream.get_log_source(), expected_after_format); + let stored: ObjectStoreFormat = serde_json::from_slice( + &PARSEABLE + .metastore + .get_stream_json(&name, false, &tenant, false) + .await + .unwrap(), + ) + .unwrap(); + assert_eq!(stored.log_source, expected_after_format); + + // Adding a new field to an existing format updates memory and persists. + PARSEABLE + .add_update_log_source_on_stream( + &stream, + LogSourceEntry::new( + LogSource::Custom("syslog".into()), + HashSet::from(["host".to_string(), "severity".to_string()]), + ), + &tenant, + ) + .await + .unwrap(); + + let expected_after_field = vec![ + LogSourceEntry::new(LogSource::Json, HashSet::new()), + LogSourceEntry::new( + LogSource::Custom("syslog".into()), + HashSet::from(["host".to_string(), "severity".to_string()]), + ), + ]; + assert_eq!(stream.get_log_source(), expected_after_field); + let stored: ObjectStoreFormat = serde_json::from_slice( + &PARSEABLE + .metastore + .get_stream_json(&name, false, &tenant, false) + .await + .unwrap(), + ) + .unwrap(); + assert_eq!(stored.log_source, expected_after_field); + + // Re-sending the same fields now hits the fast path cleanly. + PARSEABLE + .add_update_log_source( + &name, + LogSourceEntry::new( + LogSource::Custom("syslog".into()), + HashSet::from(["severity".to_string()]), + ), + &tenant, + ) + .await + .unwrap(); + assert_eq!(stream.get_log_source(), expected_after_field); + + PARSEABLE.streams.delete(&name, &tenant); + } + } + + #[tokio::test] + async fn ensure_stream_with_returns_stream_ref_and_existed_flag() { + install_default_test_parseable(); + let name = new_stream_name("ensurestream"); + + let (created_stream, existed) = PARSEABLE + .ensure_stream_with( + &name, + StreamType::UserDefined, + None, + vec![LogSourceEntry::new(LogSource::Json, HashSet::new())], + TelemetryType::Logs, + &None, + || Ok(vec![]), + vec![], + ) + .await + .unwrap(); + assert!(!existed); + + let (existing_stream, existed) = PARSEABLE + .ensure_stream_with( + &name, + StreamType::UserDefined, + None, + vec![LogSourceEntry::new(LogSource::Json, HashSet::new())], + TelemetryType::Logs, + &None, + || Err(PostError::Invalid(anyhow::anyhow!("must not be called"))), + vec![], + ) + .await + .unwrap(); + assert!(existed); + assert!(Arc::ptr_eq(&created_stream, &existing_stream)); + } } diff --git a/src/parseable/staging/disk_source.rs b/src/parseable/staging/disk_source.rs index 82a2cf61c..cefd5ba87 100644 --- a/src/parseable/staging/disk_source.rs +++ b/src/parseable/staging/disk_source.rs @@ -36,13 +36,17 @@ use std::{ sync::Arc, }; -use arrow_array::RecordBatch; +use arrow_array::{BooleanArray, RecordBatch}; use arrow_ipc::reader::StreamReader; use arrow_schema::{ArrowError, Schema}; use super::{ StagingError, - reader::{MessageRangeReader, exact_prefix_reader}, + reader::{ + DEFAULT_ADAPTIVE_FALLBACK_CONSECUTIVE_MATCHES, MessageRangeReader, TwoPhaseFilteredReader, + ValidatedPrefixPlan, exact_prefix_reader, plan_exact_prefix, stream_reader_for_ranges, + two_phase_filtered_reader, + }, }; use crate::utils::arrow::batch_adapter::BatchAdapter; @@ -118,6 +122,10 @@ pub struct StagingDiskSource { /// Forward or reverse record batches of a [`StagingDiskSource`]. pub(crate) type StagingDiskReader = StreamReader>>; +/// Two-phase filter-first record batch reader over a [`StagingDiskSource`]. +#[allow(dead_code)] // Wired into StagingDiskPartition during Q4 integration. +pub(crate) type StagingTwoPhaseDiskReader = TwoPhaseFilteredReader; + impl StagingDiskSource { /// Opens the first of `candidates` that exists. /// @@ -177,9 +185,7 @@ impl StagingDiskSource { self.len <= self.start } - /// Record batches of the prefix, in file order or newest first. Fails - /// unless the complete IPC messages end exactly at the recorded length. - pub(crate) fn reader(&self, reverse: bool) -> Result { + pub(crate) fn validate_file_len(&self) -> Result<(), StagingError> { let actual_len = self .file .metadata() @@ -199,6 +205,92 @@ impl StagingDiskSource { ), ))); } + Ok(()) + } + + /// Validates the file prefix `[start, len)` and returns its parsed schema + /// 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.validate_file_len()?; + plan_exact_prefix( + BoundedFile::new(Arc::clone(&self.file), self.len), + self.start, + self.len, + ) + .map_err(|err| { + StagingError::ObjectStorage(io::Error::new( + err.kind(), + format!("staging file {:?}: {err}", self.path), + )) + }) + } + + /// Builds a `StreamReader` over pre-validated IPC message ranges of this + /// file (starting with the schema message), re-checking file length at + /// execution time and reading only `projection` columns when specified. + pub(crate) fn reader_for_ranges( + &self, + ranges: Arc<[(u64, usize)]>, + projection: Option>, + buffer_bytes: usize, + ) -> Result { + self.validate_file_len()?; + stream_reader_for_ranges( + BoundedFile::new(Arc::clone(&self.file), self.len), + ranges, + projection, + buffer_bytes, + ) + .map_err(|err| { + StagingError::ObjectStorage(io::Error::new( + err.kind(), + format!("staging file {:?}: {err}", self.path), + )) + }) + } + + /// Builds a two-phase filter-first Arrow IPC reader over pre-validated + /// non-dictionary message ranges of this file (`ranges[0]` = schema, + /// `ranges[1..]` = record batches), re-checking file length at open time. + /// + /// For each message, decodes only `filter_indices`, evaluates `eval_filter` + /// on that narrow batch, and decodes `output_indices \ filter_indices` only + /// when at least one row matches. Defaults to adaptive fallback to + /// single-phase streaming [`StreamReader`] after + /// [`DEFAULT_ADAPTIVE_FALLBACK_CONSECUTIVE_MATCHES`] consecutive matching + /// batches with zero skipped batches. + pub(crate) fn two_phase_filtered_reader( + &self, + ranges: Arc<[(u64, usize)]>, + filter_indices: Vec, + output_indices: Vec, + eval_filter: F, + ) -> Result, StagingError> + where + F: FnMut(&RecordBatch) -> Result, + { + self.validate_file_len()?; + two_phase_filtered_reader( + BoundedFile::new(Arc::clone(&self.file), self.len), + ranges, + filter_indices, + output_indices, + eval_filter, + ) + .map(|reader| reader.with_adaptive_fallback(DEFAULT_ADAPTIVE_FALLBACK_CONSECUTIVE_MATCHES)) + .map_err(|err| { + StagingError::ObjectStorage(io::Error::new( + err.kind(), + format!("staging file {:?}: {err}", self.path), + )) + }) + } + + /// Record batches of the prefix, in file order or newest first. Fails + /// 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, @@ -266,3 +358,447 @@ impl StagingCapture { .sum() } } + +#[cfg(test)] +mod tests { + use std::{ + fs::OpenOptions, + io, + sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }, + }; + + use arrow_array::{ + BinaryArray, BooleanArray, Float64Array, Int64Array, RecordBatch, StringArray, + cast::AsArray, types::Int64Type, + }; + use arrow_ipc::{ + CompressionType, root_as_message, + writer::{IpcWriteOptions, StreamWriter}, + }; + use arrow_schema::{DataType, Field, Schema}; + use arrow_select::filter::filter_record_batch; + use temp_dir::TempDir; + + use super::StagingDiskSource; + use crate::parseable::staging::{ + StagingError, + reader::{TwoPhaseFallbackReason, TwoPhaseReadError, TwoPhaseStep}, + }; + + fn test_schema() -> Arc { + Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + Field::new("level", DataType::Utf8, true), + Field::new("score", DataType::Float64, true), + Field::new("payload", DataType::Binary, false), + Field::new("message", DataType::Utf8, true), + ])) + } + + fn make_batch(schema: &Arc, start_id: i64, rows: usize) -> RecordBatch { + let id = Int64Array::from_iter_values((0..rows).map(|i| start_id + i as i64)); + let level = StringArray::from_iter((0..rows).map(|i| match (start_id as usize + i) % 4 { + 0 => Some("error"), + 1 => Some("warn"), + 2 => Some("info"), + _ => None, + })); + let score = Float64Array::from_iter( + (0..rows).map(|i| (i % 5 != 0).then_some(start_id as f64 + i as f64 * 0.5)), + ); + let payload = BinaryArray::from_iter_values( + (0..rows) + .map(|i| format!("disk-payload-{start_id}-{i}-{}", "Z".repeat(96)).into_bytes()), + ); + let message = + StringArray::from_iter((0..rows).map(|i| { + (i % 6 != 0).then(|| format!("log-msg-{start_id}-{i}-{}", "M".repeat(64))) + })); + RecordBatch::try_new( + Arc::clone(schema), + vec![ + Arc::new(id), + Arc::new(level), + Arc::new(score), + Arc::new(payload), + Arc::new(message), + ], + ) + .unwrap() + } + + fn write_lz4_stream(schema: &Arc, batches: &[RecordBatch]) -> (Vec, Vec) { + let options = IpcWriteOptions::default() + .try_with_compression(Some(CompressionType::LZ4_FRAME)) + .unwrap(); + let mut writer = StreamWriter::try_new_with_options(Vec::new(), schema, options).unwrap(); + let mut batch_offsets = Vec::with_capacity(batches.len()); + for batch in batches { + batch_offsets.push(writer.get_ref().len() as u64); + writer.write(batch).unwrap(); + } + (writer.get_ref().clone(), batch_offsets) + } + + fn single_phase_disk_reference( + source: &StagingDiskSource, + ranges: Arc<[(u64, usize)]>, + output_indices: &[usize], + filter_positions_in_output: &[usize], + mut eval: impl FnMut(&RecordBatch) -> BooleanArray, + ) -> Vec { + let reader = source + .reader_for_ranges(ranges, Some(output_indices.to_vec()), 64 * 1024) + .unwrap(); + let mut out = Vec::new(); + for batch in reader { + let batch = batch.unwrap(); + if batch.num_rows() == 0 { + continue; + } + let filter_batch = batch.project(filter_positions_in_output).unwrap(); + let mask = eval(&filter_batch); + if mask.true_count() == 0 { + continue; + } + out.push(filter_record_batch(&batch, &mask).unwrap()); + } + out + } + + #[test] + fn disk_source_two_phase_matches_single_phase_forward_reverse_and_nonzero_start() { + let dir = TempDir::new().unwrap(); + let path = dir.path().join("wide_lz4.arrows"); + let schema = test_schema(); + let batches: Vec<_> = (0..5).map(|b| make_batch(&schema, b * 40, 40)).collect(); + let (bytes, batch_offsets) = write_lz4_stream(&schema, &batches); + std::fs::write(&path, &bytes).unwrap(); + + let filter_indices = vec![0usize, 1usize]; // id, level + let output_indices = vec![0usize, 1, 2, 3, 4]; + + // Test both start == 0 (full file) and start > 0 (slice from batch 2 onward) + for &start in &[0u64, batch_offsets[2]] { + let source = + StagingDiskSource::open_first(&[&path], start, bytes.len() as u64).unwrap(); + let plan = source.plan_prefix().unwrap(); + assert!(!plan.has_dictionaries); + if start == 0 { + assert_eq!(plan.messages.len(), 5); + } else { + assert_eq!(plan.messages.len(), 3); + } + + for reverse in [false, true] { + let mut messages = plan.messages.clone(); + if reverse { + messages.reverse(); + } + let mut ranges = Vec::with_capacity(messages.len() + 1); + ranges.push(plan.schema_range); + ranges.extend(messages.into_iter().map(|m| (m.offset, m.size))); + let ranges: Arc<[(u64, usize)]> = Arc::from(ranges); + + // 0% match + let eval_none = |fb: &RecordBatch| BooleanArray::from(vec![false; fb.num_rows()]); + let expected_none = single_phase_disk_reference( + &source, + Arc::clone(&ranges), + &output_indices, + &[0, 1], + eval_none, + ); + let mut reader_none = source + .two_phase_filtered_reader( + Arc::clone(&ranges), + filter_indices.clone(), + output_indices.clone(), + |fb| Ok::<_, io::Error>(eval_none(fb)), + ) + .unwrap(); + let actual_none: Vec<_> = + (&mut reader_none).collect::, _>>().unwrap(); + assert_eq!(actual_none, expected_none); + assert!(actual_none.is_empty()); + assert_eq!(reader_none.stats().phase2_decodes, 0); + + // Selective predicate with nulls (`level == "error" && id % 8 == 0`) + let eval_selective = |fb: &RecordBatch| { + let ids = fb.column(0).as_primitive::(); + let levels = fb.column(1).as_string::(); + BooleanArray::from_iter( + ids.values() + .iter() + .zip(levels.iter()) + .map(|(&id, level)| level.map(|lvl| lvl == "error" && id % 8 == 0)), + ) + }; + let expected_selective = single_phase_disk_reference( + &source, + Arc::clone(&ranges), + &output_indices, + &[0, 1], + eval_selective, + ); + let actual_selective: Vec<_> = source + .two_phase_filtered_reader( + Arc::clone(&ranges), + filter_indices.clone(), + output_indices.clone(), + |fb| Ok::<_, io::Error>(eval_selective(fb)), + ) + .unwrap() + .collect::, _>>() + .unwrap(); + assert_eq!(actual_selective, expected_selective); + assert!(!actual_selective.is_empty()); + + // 100% match + let eval_all = |fb: &RecordBatch| BooleanArray::from(vec![true; fb.num_rows()]); + let expected_all = single_phase_disk_reference( + &source, + Arc::clone(&ranges), + &output_indices, + &[0, 1], + eval_all, + ); + let mut reader_all = source + .two_phase_filtered_reader( + ranges, + filter_indices.clone(), + output_indices.clone(), + |fb| Ok::<_, io::Error>(eval_all(fb)), + ) + .unwrap(); + let actual_all: Vec<_> = (&mut reader_all).collect::, _>>().unwrap(); + assert_eq!(actual_all, expected_all); + assert_eq!(reader_all.stats().batches_partially_matched, 0); + } + } + } + + #[test] + fn disk_source_two_phase_fails_closed_on_post_plan_truncation() { + let dir = TempDir::new().unwrap(); + let path = dir.path().join("trunc.arrows"); + let schema = test_schema(); + let batches = vec![make_batch(&schema, 0, 20), make_batch(&schema, 20, 20)]; + let (bytes, _) = write_lz4_stream(&schema, &batches); + std::fs::write(&path, &bytes).unwrap(); + + let source = StagingDiskSource::open_first(&[&path], 0, bytes.len() as u64).unwrap(); + let plan = source.plan_prefix().unwrap(); + let mut ranges = Vec::with_capacity(plan.messages.len() + 1); + ranges.push(plan.schema_range); + ranges.extend(plan.messages.iter().map(|m| (m.offset, m.size))); + let ranges: Arc<[(u64, usize)]> = Arc::from(ranges); + + // Case B: Open reader while file is intact, read batch 0, then truncate + // the file mid-batch-1 before reading batch 1 -> fails closed with Io(InvalidData). + let mut live_reader = source + .two_phase_filtered_reader(Arc::clone(&ranges), vec![0], vec![0, 1, 2, 3, 4], |fb| { + Ok::<_, io::Error>(BooleanArray::from(vec![true; fb.num_rows()])) + }) + .unwrap(); + assert_eq!(live_reader.next().unwrap().unwrap().num_rows(), 20); + + let trunc_len = (plan.messages[1].offset as usize + plan.messages[1].size / 2) as u64; + OpenOptions::new() + .write(true) + .open(&path) + .unwrap() + .set_len(trunc_len) + .unwrap(); + + match live_reader.next().unwrap().unwrap_err() { + TwoPhaseReadError::Io(io_err) => { + assert_eq!(io_err.kind(), io::ErrorKind::InvalidData); + } + other => panic!("expected Io(InvalidData) on mid-scan truncation, got {other:?}"), + } + assert!(live_reader.next().is_none()); + + // Case A: Opening a new reader after truncation fails immediately at + // `validate_file_len()`. + let open_err = source + .two_phase_filtered_reader(ranges, vec![0], vec![0, 1, 2, 3, 4], |fb| { + Ok::<_, io::Error>(BooleanArray::from(vec![true; fb.num_rows()])) + }) + .unwrap_err(); + assert!( + matches!( + open_err, + StagingError::ObjectStorage(ref e) if e.kind() == io::ErrorKind::UnexpectedEof + ), + "expected UnexpectedEof from validate_file_len, got {open_err:?}" + ); + } + + #[test] + fn disk_source_two_phase_skips_non_filter_columns_on_zero_match_batch() { + let dir = TempDir::new().unwrap(); + let path = dir.path().join("skip_non_filter.arrows"); + let schema = test_schema(); + let batches = vec![make_batch(&schema, 0, 32), make_batch(&schema, 100, 32)]; + let (mut bytes, _) = write_lz4_stream(&schema, &batches); + std::fs::write(&path, &bytes).unwrap(); + + let source = StagingDiskSource::open_first(&[&path], 0, bytes.len() as u64).unwrap(); + let plan = source.plan_prefix().unwrap(); + let mut ranges = Vec::with_capacity(plan.messages.len() + 1); + ranges.push(plan.schema_range); + ranges.extend(plan.messages.iter().map(|m| (m.offset, m.size))); + let ranges: Arc<[(u64, usize)]> = Arc::from(ranges); + + // Corrupt the LZ4-compressed `payload` column (col 3 -> buffer index 9: + // col 0 Int64 = 2 bufs [0,1], col 1 Utf8 = 3 bufs [2,3,4], + // col 2 Float64 = 2 bufs [5,6], col 3 Binary = 3 bufs [7,8,9]) in batch 1. + let (rb1_off, rb1_size) = ranges[2]; + let rb1_slice = &bytes[rb1_off as usize..(rb1_off as usize + rb1_size)]; + let meta_len = i32::from_le_bytes(rb1_slice[4..8].try_into().unwrap()) as usize; + let msg = root_as_message(&rb1_slice[8..8 + meta_len]).unwrap(); + let rb_msg = msg.header_as_record_batch().unwrap(); + let payload_values_buf = rb_msg.buffers().unwrap().get(9); + let corrupt_start = rb1_off as usize + 8 + meta_len + payload_values_buf.offset() as usize; + let corrupt_end = corrupt_start + payload_values_buf.length() as usize; + for byte in &mut bytes[corrupt_start + 8..corrupt_end] { + *byte ^= 0xFF; + } + std::fs::write(&path, &bytes).unwrap(); + + let source = StagingDiskSource::open_first(&[&path], 0, bytes.len() as u64).unwrap(); + + // Predicate matches only rows in batch 0 (id < 10); batch 1 has 0 matches, + // so its corrupted `payload` column must NEVER be decompressed. + let mut reader = source + .two_phase_filtered_reader(Arc::clone(&ranges), vec![0], vec![0, 1, 2, 3, 4], |fb| { + let ids = fb.column(0).as_primitive::(); + Ok::<_, io::Error>(BooleanArray::from_iter( + ids.values().iter().map(|&id| Some(id < 10)), + )) + }) + .unwrap(); + let out: Vec<_> = (&mut reader).collect::, _>>().unwrap(); + assert_eq!(out.len(), 1); + assert_eq!(out[0].num_rows(), 10); + assert_eq!(reader.stats().messages_scanned, 2); + assert_eq!(reader.stats().batches_partially_matched, 1); + assert_eq!(reader.stats().batches_skipped_zero_matches, 1); + assert_eq!(reader.stats().phase2_decodes, 1); + + // Matching a row in batch 1 forces Phase 2 on batch 1 and fails closed. + let mut failing_reader = source + .two_phase_filtered_reader(ranges, vec![0], vec![0, 1, 2, 3, 4], |fb| { + let ids = fb.column(0).as_primitive::(); + Ok::<_, io::Error>(BooleanArray::from_iter( + ids.values().iter().map(|&id| Some(id == 105)), + )) + }) + .unwrap(); + assert!(matches!( + failing_reader.next().unwrap().unwrap_err(), + TwoPhaseReadError::Arrow(_) + )); + } + + #[test] + fn disk_source_two_phase_defaults_to_adaptive_fallback_and_supports_cancellation() { + let dir = TempDir::new().unwrap(); + let path = dir.path().join("adaptive_cancel.arrows"); + let schema = test_schema(); + let batches: Vec<_> = (0..6).map(|b| make_batch(&schema, b * 25, 25)).collect(); + let (bytes, _) = write_lz4_stream(&schema, &batches); + std::fs::write(&path, &bytes).unwrap(); + + let source = StagingDiskSource::open_first(&[&path], 0, bytes.len() as u64).unwrap(); + let plan = source.plan_prefix().unwrap(); + let mut ranges = Vec::with_capacity(plan.messages.len() + 1); + ranges.push(plan.schema_range); + ranges.extend(plan.messages.iter().map(|m| (m.offset, m.size))); + let ranges: Arc<[(u64, usize)]> = Arc::from(ranges); + + let eval_matching = |fb: &RecordBatch| { + let ids = fb.column(0).as_primitive::(); + BooleanArray::from_iter(ids.values().iter().map(|&id| Some(id % 2 == 0))) + }; + let expected = single_phase_disk_reference( + &source, + Arc::clone(&ranges), + &[0, 1, 2, 3, 4], + &[0], + eval_matching, + ); + + // Default adaptive fallback (4 consecutive matches) via explicit `next_step()`. + let mut step_reader = source + .two_phase_filtered_reader(Arc::clone(&ranges), vec![0], vec![0, 1, 2, 3, 4], |fb| { + Ok::<_, io::Error>(eval_matching(fb)) + }) + .unwrap(); + let mut combined = Vec::new(); + for _ in 0..4 { + match step_reader.next_step().unwrap() { + TwoPhaseStep::Batch(batch) => combined.push(batch), + other => panic!("expected batch, got {other:?}"), + } + } + let resume_idx = match step_reader.next_step().unwrap() { + TwoPhaseStep::FallbackToSinglePhase { + resume_range_index, + reason, + } => { + assert_eq!(resume_range_index, 5); + assert_eq!( + reason, + TwoPhaseFallbackReason::AdaptiveConsecutiveMatches { + consecutive_matches: 4, + } + ); + resume_range_index + } + other => panic!("expected adaptive fallback, got {other:?}"), + }; + let remaining = step_reader.remaining_ranges_with_schema(resume_idx); + let stream = source + .reader_for_ranges(remaining, None, 64 * 1024) + .unwrap(); + for batch in stream { + let batch = batch.unwrap(); + let filter_batch = batch.project(&[0]).unwrap(); + let mask = eval_matching(&filter_batch); + if mask.true_count() > 0 { + combined.push(filter_record_batch(&batch, &mask).unwrap()); + } + } + assert_eq!(combined, expected); + + // Seamless `Iterator` fallback via StagingDiskSource defaults. + let mut iter_reader = source + .two_phase_filtered_reader(Arc::clone(&ranges), vec![0], vec![0, 1, 2, 3, 4], |fb| { + Ok::<_, io::Error>(eval_matching(fb)) + }) + .unwrap(); + let iter_actual: Vec<_> = (&mut iter_reader).collect::, _>>().unwrap(); + assert_eq!(iter_actual, expected); + assert!(iter_reader.stats().fell_back_to_single_phase); + assert_eq!(iter_reader.stats().phase2_decodes, 4); + + // Cancellation stops zero-match disk scan after 1 message instead of all 6. + let cancelled = Arc::new(AtomicBool::new(false)); + let cancelled_in_cb = Arc::clone(&cancelled); + let mut cancel_reader = source + .two_phase_filtered_reader(ranges, vec![0], vec![0, 1, 2, 3, 4], move |fb| { + cancelled_in_cb.store(true, Ordering::Relaxed); + Ok::<_, io::Error>(BooleanArray::from(vec![false; fb.num_rows()])) + }) + .unwrap() + .with_cancel_flag(cancelled); + assert!(cancel_reader.next().is_none()); + assert_eq!(cancel_reader.stats().messages_scanned, 1); + assert_eq!(cancel_reader.stats().phase2_decodes, 0); + } +} diff --git a/src/parseable/staging/reader.rs b/src/parseable/staging/reader.rs index 9bbb07aef..ee6f40d61 100644 --- a/src/parseable/staging/reader.rs +++ b/src/parseable/staging/reader.rs @@ -18,19 +18,38 @@ */ use std::{ + collections::{HashMap, VecDeque}, + fmt, fs::File, io::{self, BufReader, Read, Seek, SeekFrom}, path::PathBuf, - sync::Arc, + ptr::NonNull, + sync::{ + Arc, + atomic::{AtomicBool, AtomicUsize, Ordering}, + }, vec::IntoIter, }; #[cfg(test)] use std::io::Take; -use arrow_array::{RecordBatch, TimestampMillisecondArray}; -use arrow_ipc::{MessageHeader, reader::StreamReader, root_as_message}; -use arrow_schema::{ArrowError, Schema}; +use arrow::{ + array::ArrayData, + buffer::{BooleanBuffer, Buffer, MutableBuffer, NullBuffer}, +}; +use arrow_array::{ + Array, ArrayRef, BooleanArray, RecordBatch, RecordBatchOptions, TimestampMillisecondArray, + make_array, +}; +use arrow_ipc::{ + MessageHeader, MetadataVersion, + convert::fb_to_schema, + reader::{StreamReader, read_record_batch}, + root_as_message, +}; +use arrow_schema::{ArrowError, DataType, Field, Schema, UnionMode}; +use arrow_select::filter::filter_record_batch; use byteorder::{LittleEndian, ReadBytesExt}; use itertools::kmerge_by; use tracing::{error, info_span}; @@ -40,6 +59,32 @@ use crate::{ utils::arrow::{batch_adapter::BatchAdapter, reverse}, }; +/// Buffer for scanning the IPC message headers of a staged file. Each message +/// costs two length reads, a metadata read and a skip over its body; 16 KiB +/// coalesces neighbouring small headers while bounding read-ahead discarded +/// when skipping large (~200–600 KiB) compressed record-batch bodies. +const MESSAGE_SCAN_BUFFER_BYTES: usize = 16 * 1024; + +/// Buffer between the Arrow stream decoder and a staged file. The decoder +/// reads a message in several small pieces before its body; the default +/// 8 KiB buffer turns those into extra system calls for every message. +const MESSAGE_READ_BUFFER_BYTES: usize = 256 * 1024; + +/// Total `BufReader` budget shared across all eagerly opened reverse readers in +/// a single `MergedReverseRecordReader` so wide multi-file schema-churn merges +/// do not allocate hundreds of megabytes of read buffers at once. +const MERGED_REVERSE_READ_BUFFER_BUDGET_BYTES: usize = 4 * 1024 * 1024; +const MIN_MESSAGE_READ_BUFFER_BYTES: usize = 8 * 1024; + +fn reverse_reader_buffer_bytes(file_count: usize) -> usize { + if file_count <= 1 { + MESSAGE_READ_BUFFER_BYTES + } else { + (MERGED_REVERSE_READ_BUFFER_BUDGET_BYTES / file_count) + .clamp(MIN_MESSAGE_READ_BUFFER_BYTES, MESSAGE_READ_BUFFER_BYTES) + } +} + #[derive(Debug)] /// Merges reverse readers while retaining the source-file validation result. pub struct MergedReverseRecordReader { @@ -120,7 +165,10 @@ impl ForwardFilePlan { .map(|(ranges, record_batches)| { let file = File::open(&self.path)?; let reader = StreamReader::try_new( - BufReader::new(MessageRangeReader::new(file, ranges)), + BufReader::with_capacity( + MESSAGE_READ_BUFFER_BYTES, + MessageRangeReader::new(file, ranges), + ), None, ) .map_err(|err| { @@ -231,6 +279,7 @@ impl MergedReverseRecordReader { let mut readers = Vec::with_capacity(file_paths.len()); let mut readable_files = Vec::with_capacity(file_paths.len()); let mut invalid_files = Vec::new(); + let read_buffer_bytes = reverse_reader_buffer_bytes(file_paths.len()); for path in file_paths { match File::open(path) { Err(err) => { @@ -238,14 +287,17 @@ impl MergedReverseRecordReader { continue; } Ok(file) => { - let reader = match get_reverse_reader(file) { - Ok(r) => r, - Err(err) => { - error!("Invalid file detected, ignoring it: {path:?}; error = {err}"); - invalid_files.push(path.clone()); - continue; - } - }; + let reader = + match get_reverse_reader_with_buffer_capacity(file, read_buffer_bytes) { + Ok(r) => r, + Err(err) => { + error!( + "Invalid file detected, ignoring it: {path:?}; error = {err}" + ); + invalid_files.push(path.clone()); + continue; + } + }; readers.push(reader); readable_files.push(path.clone()); } @@ -270,6 +322,26 @@ impl MergedReverseRecordReader { let mut adapters: Vec = (0..self.readers.len()) .map(|_| BatchAdapter::new(Arc::clone(&schema))) .collect(); + // A batch that cannot be presented under `schema` is an error for the + // conversion to handle, like a batch that cannot be decoded. + self.merged_decoded_iter(time_partition) + .map(move |(reader_idx, batch)| { + batch.and_then(|batch| { + let reversed = reverse(&batch); + adapters[reader_idx].adapt(&reversed) + }) + }) + } + + /// Merges all readers in reverse timestamp order, leaving each batch as + /// decoded: its rows oldest first, under the schema of its file. Each + /// batch comes with the index of its reader. A caller that reverses and + /// adapts the batches itself, as `merged_iter` does one at a time, can do + /// so for several batches at once. + pub(crate) fn merged_decoded_iter( + self, + time_partition: Option, + ) -> impl Iterator)> { let indexed_readers = self .readers .into_iter() @@ -283,23 +355,22 @@ impl MergedReverseRecordReader { (Ok(a), Ok(b)) => { let a_time = get_timestamp_millis(a, time_partition.as_deref()); let b_time = get_timestamp_millis(b, time_partition.as_deref()); - a_time > b_time + match (a_time, b_time) { + (Some(a_ts), Some(b_ts)) => a_ts > b_ts, + // Drain empty (0-row) or timestamp-less batches ahead of + // timestamped batches without accessing row 0 so schema + // validation and downstream error propagation are preserved. + (None, Some(_)) => true, + (Some(_), None) | (None, None) => false, + } } // Surface decoding errors through the iterator instead of silently // dropping them with Iterator::flatten. - (Err(_), _) => true, - (_, Err(_)) => false, + (Err(_), Ok(_)) => true, + (Ok(_), Err(_)) | (Err(_), Err(_)) => false, } }, ) - // A batch that cannot be presented under `schema` is an error for the - // conversion to handle, like a batch that cannot be decoded. - .map(move |(reader_idx, batch)| { - batch.and_then(|batch| { - let reversed = reverse(&batch); - adapters[reader_idx].adapt(&reversed) - }) - }) } /// Returns the union of schemas exposed by all readable Arrow streams, or @@ -318,35 +389,41 @@ impl MergedReverseRecordReader { } } -fn get_timestamp_millis(batch: &RecordBatch, time_partition: Option<&str>) -> i64 { +fn get_timestamp_millis(batch: &RecordBatch, time_partition: Option<&str>) -> Option { + if batch.num_rows() == 0 { + return None; + } match time_partition { Some(time_partition) => match batch.column_by_name(time_partition) { Some(column) => column .as_any() .downcast_ref::() - .unwrap() - .value(0), + .filter(|array| !array.is_empty()) + .map(|array| array.value(0)) + .or_else(|| get_default_timestamp_millis(batch)), None => get_default_timestamp_millis(batch), }, None => get_default_timestamp_millis(batch), } } -fn get_default_timestamp_millis(batch: &RecordBatch) -> i64 { + +fn get_default_timestamp_millis(batch: &RecordBatch) -> Option { + if batch.num_rows() == 0 || batch.num_columns() == 0 { + return None; + } match batch .column(0) .as_any() .downcast_ref::() { // Ideally we expect the first column to be a timestamp (because we add the timestamp column first in the writer) - Some(array) => array.value(0), + Some(array) if !array.is_empty() => Some(array.value(0)), // In case the first column is not a timestamp, we fallback to look for default timestamp column across all columns - None => batch + _ => batch .column_by_name(DEFAULT_TIMESTAMP_KEY) - .unwrap() - .as_any() - .downcast_ref::() - .unwrap() - .value(0), + .and_then(|column| column.as_any().downcast_ref::()) + .filter(|array| !array.is_empty()) + .map(|array| array.value(0)), } } @@ -356,7 +433,8 @@ fn get_default_timestamp_millis(batch: &RecordBatch) -> i64 { #[derive(Debug)] pub struct MessageRangeReader { reader: R, - ranges: IntoIter<(u64, usize)>, + ranges: Arc<[(u64, usize)]>, + next_index: usize, current_offset: u64, remaining: usize, positioned: bool, @@ -365,12 +443,16 @@ pub struct MessageRangeReader { impl MessageRangeReader { fn new(reader: R, ranges: Vec<(u64, usize)>) -> Self { - let mut ranges = ranges.into_iter(); - let first = ranges.next(); + Self::from_shared(reader, Arc::from(ranges)) + } + + fn from_shared(reader: R, ranges: Arc<[(u64, usize)]>) -> Self { + let first = ranges.first().copied(); let (current_offset, remaining) = first.unwrap_or_default(); Self { reader, ranges, + next_index: usize::from(first.is_some()), current_offset, remaining, positioned: false, @@ -379,8 +461,9 @@ impl MessageRangeReader { } fn advance(&mut self) { - match self.ranges.next() { + match self.ranges.get(self.next_index).copied() { Some((offset, size)) => { + self.next_index += 1; self.current_offset = offset; self.remaining = size; self.positioned = false; @@ -411,8 +494,12 @@ impl Read for MessageRangeReader { let max_read = self.remaining.min(buf.len()); let read = self.reader.read(&mut buf[..max_read])?; if read == 0 { + // Use `InvalidData` (not `UnexpectedEof`): `arrow-ipc`'s StreamReader + // interprets `UnexpectedEof` at a message header boundary as normal + // end-of-stream, which would turn a post-plan file truncation into a + // silent short scan. return Err(io::Error::new( - io::ErrorKind::UnexpectedEof, + io::ErrorKind::InvalidData, "Arrow IPC message ended before its declared boundary", )); } @@ -423,20 +510,62 @@ impl Read for MessageRangeReader { } } -/// Finds all complete IPC messages, excluding a crash-truncated tail. -fn complete_messages( +/// A single validated IPC message inside a staging file prefix. +#[derive(Debug, Clone, Copy)] +pub(crate) struct ValidatedIpcMessage { + pub(crate) offset: u64, + pub(crate) size: usize, + /// Row count declared in the FlatBuffer header for `RecordBatch` messages; + /// `None` for `DictionaryBatch` messages. + pub(crate) rows: Option, +} + +/// Validated message index and parsed schema for `[start, expected_len)` of a +/// staging IPC stream, enabling projected reads, parallel intra-file range +/// partitioning, and zero-body-read row counting. +#[derive(Debug, Clone)] +pub(crate) struct ValidatedPrefixPlan { + pub(crate) schema_range: (u64, usize), + pub(crate) schema: Arc, + pub(crate) messages: Vec, + pub(crate) has_dictionaries: bool, +} + +/// Raw scanned message metadata produced by `complete_messages_with_rows`. +struct ScannedIpcMessage { + header: MessageHeader, + offset: usize, + size: usize, + rows: Option, +} + +/// Finds all complete IPC messages and their declared row counts (for +/// `RecordBatch` messages), excluding a crash-truncated tail. When +/// `retain_from > 0`, non-dictionary record batches starting strictly before +/// `retain_from` are validated for boundary/EOF integrity and then discarded +/// on the fly instead of retained in memory. +fn scan_complete_messages( reader: &mut T, -) -> Result, io::Error> { + retain_from: u64, +) -> Result<(Vec, u64, bool), io::Error> { let file_len = reader.seek(SeekFrom::End(0))?; reader.rewind()?; + // The scan leaves `reader` at an arbitrary position: every caller seeks + // before it reads again. + let mut reader = BufReader::with_capacity(MESSAGE_SCAN_BUFFER_BYTES, reader); let mut offset: usize = 0; let mut messages = Vec::new(); + let mut saw_record_batch = false; + let mut saw_retain_boundary = retain_from == 0; + let mut message_count = 0usize; loop { let remaining = file_len.saturating_sub(offset as u64); - match find_limit_and_type(reader, remaining) { - Ok(Some((header, size))) => { + // A relative seek keeps the buffered bytes when the next header is + // already among them. + match scan_message_with_rows(&mut reader, remaining, BufReader::seek_relative) { + Ok(Some((header, size, rows))) => { let next_offset = offset.checked_add(size).ok_or_else(|| { io::Error::new(io::ErrorKind::InvalidData, "Arrow message size overflow") })?; @@ -447,11 +576,31 @@ fn complete_messages( if next_offset as u64 > file_len { break; } - messages.push((header, offset, size)); + if message_count > 0 && offset as u64 == retain_from { + saw_retain_boundary = true; + } + if header == MessageHeader::RecordBatch { + saw_record_batch = true; + } + // Always retain the schema message, any dictionary batch (which + // later batches may reference), and every message at or after + // `retain_from`. + if message_count == 0 + || header == MessageHeader::DictionaryBatch + || offset as u64 >= retain_from + { + messages.push(ScannedIpcMessage { + header, + offset, + size, + rows, + }); + } + message_count += 1; offset = next_offset; } Ok(None) => break, - Err(err) if err.kind() == io::ErrorKind::UnexpectedEof && !messages.is_empty() => { + Err(err) if err.kind() == io::ErrorKind::UnexpectedEof && message_count > 0 => { break; } Err(err) => return Err(err), @@ -460,7 +609,7 @@ fn complete_messages( if messages .first() - .is_none_or(|(header, _, _)| *header != MessageHeader::Schema) + .is_none_or(|msg| msg.header != MessageHeader::Schema) { return Err(io::Error::new( io::ErrorKind::InvalidData, @@ -468,40 +617,35 @@ fn complete_messages( )); } - if !messages - .iter() - .any(|(header, _, _)| *header == MessageHeader::RecordBatch) - { + if !saw_record_batch { return Err(io::Error::new( io::ErrorKind::InvalidData, "Arrow stream has no complete record batch", )); } - Ok(messages) + Ok((messages, offset as u64, saw_retain_boundary)) } -/// Builds an Arrow stream reader over exactly the IPC messages of -/// `[0, expected_len)` of `reader`, which must present no more than that -/// prefix (see `disk_source::BoundedFile`). With `start > 0`, only the -/// schema message and the messages from `start` on are read; `start` must be -/// a message boundary. -/// -/// The complete messages must end exactly at `expected_len`: the prefix is an -/// acknowledged length recorded on a message boundary, so anything shorter is -/// lost data, and the reader fails instead of silently returning fewer rows. -/// With `reverse`, record batches are returned newest first, unless the -/// stream has dictionary messages, whose order a reverse read would break. -pub(crate) fn exact_prefix_reader( +/// Finds all complete IPC messages, excluding a crash-truncated tail. +fn complete_messages( + reader: &mut T, +) -> Result, io::Error> { + let (messages, _, _) = scan_complete_messages(reader, 0)?; + Ok(messages + .into_iter() + .map(|msg| (msg.header, msg.offset, msg.size)) + .collect()) +} + +/// Validates `[0, expected_len)` of `reader` and returns the parsed file schema +/// plus the exact list of IPC message ranges covering `[start, expected_len)`. +pub(crate) fn plan_exact_prefix( mut reader: R, start: u64, expected_len: u64, - reverse: bool, -) -> Result>>, io::Error> { - let mut messages = complete_messages(&mut reader)?; - let end = messages - .last() - .map_or(0, |(_, offset, size)| (offset + size) as u64); +) -> Result { + let (messages, end, saw_start_boundary) = scan_complete_messages(&mut reader, start)?; if end != expected_len { return Err(io::Error::new( io::ErrorKind::InvalidData, @@ -510,39 +654,49 @@ pub(crate) fn exact_prefix_reader( ), )); } - if start > 0 { - let starts_at_boundary = messages - .iter() - .skip(1) - .any(|(_, offset, _)| *offset as u64 == start); - if !starts_at_boundary || start >= expected_len { - return Err(io::Error::new( - io::ErrorKind::InvalidData, - format!("Arrow stream has no message boundary at {start} below {expected_len}"), - )); - } - let mut index = 0; - messages.retain(|(header, offset, _)| { - index += 1; - // Preserve the schema message and any dictionary batches emitted - // before `start`, since subsequent record batches may reference them. - index == 1 || *header == MessageHeader::DictionaryBatch || *offset as u64 >= start - }); + if start > 0 && (!saw_start_boundary || start >= expected_len) { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("Arrow stream has no message boundary at {start} below {expected_len}"), + )); } - if reverse - && !messages - .iter() - .any(|(header, _, _)| *header == MessageHeader::DictionaryBatch) - { - messages[1..].reverse(); + + let schema_range = (messages[0].offset as u64, messages[0].size); + let schema_size = messages[0].size; + let mut has_dictionaries = false; + let mut planned = Vec::with_capacity(messages.len().saturating_sub(1)); + for msg in messages.into_iter().skip(1) { + match msg.header { + MessageHeader::RecordBatch => { + planned.push(ValidatedIpcMessage { + offset: msg.offset as u64, + size: msg.size, + rows: msg.rows, + }); + } + MessageHeader::DictionaryBatch => { + has_dictionaries = true; + planned.push(ValidatedIpcMessage { + offset: msg.offset as u64, + size: msg.size, + rows: None, + }); + } + other => { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("Unsupported Arrow IPC message header in staging file: {other:?}"), + )); + } + } } - let ranges = messages - .into_iter() - .map(|(_, offset, size)| (offset as u64, size)) - .collect(); + reader.rewind()?; - StreamReader::try_new( - BufReader::new(MessageRangeReader::new(reader, ranges)), + let schema = StreamReader::try_new( + BufReader::with_capacity( + schema_size.clamp(4096, MESSAGE_SCAN_BUFFER_BYTES), + MessageRangeReader::new(reader, vec![schema_range]), + ), None, ) .map_err(|e| { @@ -550,22 +704,35 @@ pub(crate) fn exact_prefix_reader( io::ErrorKind::InvalidData, format!("Invalid arrow stream: {e}"), ) + })? + .schema(); + + Ok(ValidatedPrefixPlan { + schema_range, + schema, + messages: planned, + has_dictionaries, }) } -/// Builds a forward Arrow stream reader over only complete IPC messages. -#[cfg(test)] -pub fn get_forward_reader( - mut reader: T, -) -> Result>>, io::Error> { - let messages = complete_messages(&mut reader)?; - let complete_len = messages - .last() - .map(|(_, offset, size)| offset + size) - .expect("complete_messages requires a schema and record batch"); +/// Builds an Arrow `StreamReader` over a pre-validated sequence of IPC message +/// ranges (starting with the schema message), applying an optional column +/// projection so unprojected buffers are skipped without decompression. +pub(crate) fn stream_reader_for_ranges( + mut reader: R, + ranges: Arc<[(u64, usize)]>, + projection: Option>, + buffer_bytes: usize, +) -> Result>>, io::Error> { reader.rewind()?; - - StreamReader::try_new(BufReader::new(reader.take(complete_len as u64)), None).map_err(|e| { + StreamReader::try_new( + BufReader::with_capacity( + buffer_bytes, + MessageRangeReader::from_shared(reader, ranges), + ), + projection, + ) + .map_err(|e| { io::Error::new( io::ErrorKind::InvalidData, format!("Invalid arrow stream: {e}"), @@ -573,976 +740,4904 @@ pub fn get_forward_reader( }) } -/// Builds a reverse Arrow stream reader from complete IPC messages. -/// Preserves forward order when dictionary messages are present so batches do -/// not arrive before the dictionaries they reference. -pub fn get_reverse_reader( - mut reader: T, -) -> Result>>, io::Error> { - let mut messages = complete_messages(&mut reader)?; +/// Arrow IPC streaming continuation marker (`0xFFFFFFFF`). +const IPC_CONTINUATION_MARKER: [u8; 4] = [0xFF; 4]; - // Reverse everything leaving the first because it has schema message, - // unless dictionary messages require original IPC order. - if !messages - .iter() - .any(|(header, _, _)| *header == MessageHeader::DictionaryBatch) - { - messages[1..].reverse(); - } - let messages = messages - .into_iter() - .map(|(_, offset, size)| (offset as u64, size)) - .collect(); +/// Maximum byte length of a single IPC schema message (8-byte prefix + bounded +/// metadata + up to 7 bytes of alignment padding). +const MAX_IPC_SCHEMA_MESSAGE_BYTES: usize = 8 + MAX_IPC_METADATA_BYTES + 7; - // reset reader - reader.rewind()?; +/// Maximum recursion depth accepted when pre-validating nested Arrow IPC schema +/// FlatBuffers before invoking `arrow_ipc::convert::fb_to_schema`. +const MAX_IPC_SCHEMA_DEPTH: usize = 64; - StreamReader::try_new( - BufReader::new(MessageRangeReader::new(reader, messages)), - None, - ) - .map_err(|e| { - io::Error::new( - io::ErrorKind::InvalidData, - format!("Invalid arrow stream: {e}"), - ) - }) -} +/// Maximum byte size of a single IPC `RecordBatch` message buffered in memory +/// by [`TwoPhaseFilteredReader`]. Larger messages fall back to streaming +/// single-phase [`StreamReader`] without allocating a whole-message buffer. +pub(crate) const STAGING_TWO_PHASE_MAX_MESSAGE_BYTES: usize = 16 * 1024 * 1024; -/// Hard upper bound on a single IPC FlatBuffer metadata payload to prevent -/// corrupt length fields from triggering multi-GiB allocations. -const MAX_IPC_METADATA_BYTES: usize = 64 * 1024 * 1024; +/// Process-wide shared byte budget across all concurrent two-phase IPC readers +/// (all queries and all partitions). When acquiring `msg_size` bytes would +/// exceed this cap, the reader falls back to streaming single-phase +/// [`StreamReader`] instead of over-allocating. +#[allow(dead_code)] // Exposed for StagingDiskPartition diagnostics and tests. +pub(crate) const STAGING_TWO_PHASE_SHARED_BUDGET_BYTES: usize = 64 * 1024 * 1024; -/// Returns the IPC message type and its padded byte length. -fn find_limit_and_type( - reader: &mut (impl Read + Seek), - remaining_bytes: u64, -) -> Result, io::Error> { - let mut size = 0; - let marker = reader.read_u32::()?; - size += 4; +/// Default consecutive matching batch threshold before [`TwoPhaseFilteredReader`] +/// adaptively switches remaining ranges to single-phase [`StreamReader`]. +pub(crate) const DEFAULT_ADAPTIVE_FALLBACK_CONSECUTIVE_MATCHES: usize = 4; - if marker != 0xFFFFFFFF { - return Err(io::Error::new( - io::ErrorKind::InvalidData, - "Invalid Continuation Marker", - )); - } +/// Lightweight non-blocking shared byte budget with RAII permits. +#[derive(Debug)] +pub(crate) struct SharedByteBudget { + in_use: AtomicUsize, + limit: usize, +} - let metadata_size = reader.read_u32::()? as usize; - size += 4; +impl SharedByteBudget { + pub(crate) const fn new(limit: usize) -> Self { + Self { + in_use: AtomicUsize::new(0), + limit, + } + } - if metadata_size == 0x00000000 { - return Ok(None); + #[cfg(test)] + pub(crate) fn limit(&self) -> usize { + self.limit } - if metadata_size > MAX_IPC_METADATA_BYTES { - return Err(io::Error::new( - io::ErrorKind::InvalidData, - format!("Arrow IPC metadata length {metadata_size} exceeds maximum"), - )); + pub(crate) fn in_use(&self) -> usize { + self.in_use.load(Ordering::Acquire) } - if (metadata_size as u64) > remaining_bytes.saturating_sub(size as u64) { - return Err(io::Error::new( - io::ErrorKind::UnexpectedEof, - "Arrow IPC metadata truncated before end of file", - )); + + /// Attempts to reserve `bytes` from the shared budget without blocking. + /// Returns `None` if `in_use + bytes > limit`. + pub(crate) fn try_acquire(&self, bytes: usize) -> Option> { + let mut current = self.in_use.load(Ordering::Acquire); + loop { + let next = current.checked_add(bytes)?; + if next > self.limit { + return None; + } + match self.in_use.compare_exchange_weak( + current, + next, + Ordering::AcqRel, + Ordering::Acquire, + ) { + Ok(_) => { + return Some(SharedBytePermit { + budget: self, + bytes, + }); + } + Err(actual) => current = actual, + } + } } +} - let mut message = vec![0u8; metadata_size]; - reader.read_exact(&mut message)?; - size += metadata_size; +/// RAII permit releasing reserved bytes back to a [`SharedByteBudget`] on drop. +#[derive(Debug)] +pub(crate) struct SharedBytePermit<'a> { + budget: &'a SharedByteBudget, + bytes: usize, +} - let message = root_as_message(&message).map_err(|err| { - io::Error::new( - io::ErrorKind::InvalidData, - format!("Invalid Arrow IPC message: {err}"), - ) - })?; - let header = message.header_type(); - let message_size = usize::try_from(message.bodyLength()) - .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "Invalid Arrow IPC body length"))?; - size = size - .checked_add(message_size) - .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "Arrow message size overflow"))?; +impl Drop for SharedBytePermit<'_> { + fn drop(&mut self) { + if self.bytes > 0 { + self.budget.in_use.fetch_sub(self.bytes, Ordering::Release); + } + } +} - let padding = (8 - (size % 8)) % 8; - let seek_by = message_size - .checked_add(padding) - .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "Arrow message size overflow"))?; - reader.seek(SeekFrom::Current(seek_by as i64))?; - size = size - .checked_add(padding) - .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "Arrow message size overflow"))?; +static STAGING_TWO_PHASE_SHARED_BUDGET: SharedByteBudget = + SharedByteBudget::new(STAGING_TWO_PHASE_SHARED_BUDGET_BYTES); - Ok(Some((header, size))) +/// Returns bytes currently reserved in the process-wide two-phase IPC buffer +/// budget. +#[allow(dead_code)] // Exposed for diagnostics and tests. +pub(crate) fn staging_two_phase_shared_budget_in_use() -> usize { + STAGING_TWO_PHASE_SHARED_BUDGET.in_use() } -#[cfg(test)] -mod tests { - mod track_e { - include!("reader/track_e.rs"); +#[derive(Debug, Clone)] +enum BudgetHandle { + Static(&'static SharedByteBudget), + #[cfg(test)] + Shared(Arc), +} + +impl BudgetHandle { + fn try_acquire(&self, bytes: usize) -> Option> { + match self { + Self::Static(budget) => budget.try_acquire(bytes), + #[cfg(test)] + Self::Shared(budget) => budget.try_acquire(bytes), + } } +} - use std::{ - collections::VecDeque, - io::{self, Cursor, Read}, - path::Path, - sync::Arc, - }; +/// Reason [`TwoPhaseFilteredReader`] switched (or requested switching) to +/// single-phase streaming [`StreamReader`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum TwoPhaseFallbackReason { + /// A single IPC message exceeded the per-message buffer cap. + MessageTooLarge { + message_bytes: usize, + limit_bytes: usize, + }, + /// The process-wide shared two-phase message buffer budget was exhausted. + SharedBudgetExhausted { message_bytes: usize }, + /// Too many consecutive batches matched with zero skipped batches + /// (non-selective / scattered-match query). + AdaptiveConsecutiveMatches { consecutive_matches: usize }, +} - use arrow_array::{ - Array, DictionaryArray, Float64Array, Int32Array, Int64Array, RecordBatch, StringArray, - cast::AsArray, - types::{Int32Type, Int64Type}, - }; - use arrow_ipc::{ - MessageHeader, - writer::{ - DictionaryTracker, IpcDataGenerator, IpcWriteContext, IpcWriteOptions, StreamWriter, - write_message, - }, - }; - use arrow_schema::{DataType, Field, Schema}; - use chrono::Utc; - use temp_dir::TempDir; +/// Explicit step outcome from [`TwoPhaseFilteredReader::next_step`]. +#[derive(Debug)] +#[allow(dead_code)] // Wired into StagingDiskPartition explicit fallback path and tests. +pub(crate) enum TwoPhaseStep { + /// A filtered output batch ready to emit. + Batch(RecordBatch), + /// Two-phase reading stopped before `ranges[resume_range_index]`. The caller + /// can hand [`TwoPhaseFilteredReader::remaining_ranges_with_schema`] directly + /// to streaming [`StreamReader`] with zero dropped or duplicated rows. + FallbackToSinglePhase { + resume_range_index: usize, + reason: TwoPhaseFallbackReason, + }, + /// Stream exhausted or cancelled. + Finished, +} - use crate::{ - OBJECT_STORE_DATA_GRANULARITY, - parseable::staging::{ - reader::{MergedForwardRecordReader, MergedReverseRecordReader, MessageRangeReader}, - writer::DiskWriter, - }, - utils::time::TimeRange, - }; +/// Error returned while iterating a [`TwoPhaseFilteredReader`]. +#[derive(Debug)] +pub(crate) enum TwoPhaseReadError { + /// Physical I/O, short-read truncation, or IPC message framing/validation error. + Io(io::Error), + /// Arrow IPC decode, schema/layout validation, or row-filtering error. + Arrow(ArrowError), + /// Error returned by the caller's predicate callback. + Filter(E), +} - use super::{find_limit_and_type, get_forward_reader, get_reverse_reader}; - - fn rb(rows: usize) -> RecordBatch { - let array1: Arc = Arc::new(Int64Array::from_iter(0..(rows as i64))); - let array2: Arc = Arc::new(Float64Array::from_iter((0..rows).map(|x| x as f64))); - let array3: Arc = Arc::new(StringArray::from_iter( - (0..rows).map(|x| Some(format!("str {}", x))), - )); - - RecordBatch::try_from_iter_with_nullable([ - ("a", array1, true), - ("b", array2, true), - ("c", array3, true), - ]) - .unwrap() +impl fmt::Display for TwoPhaseReadError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Io(err) => write!(f, "{err}"), + Self::Arrow(err) => write!(f, "{err}"), + Self::Filter(err) => write!(f, "{err}"), + } } +} - fn write_mem(rbs: &[RecordBatch]) -> Vec { - let buf = Vec::new(); - let mut writer = StreamWriter::try_new(buf, &rbs[0].schema()).unwrap(); - - for rb in rbs { - writer.write(rb).unwrap() +impl std::error::Error for TwoPhaseReadError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Io(err) => Some(err), + Self::Arrow(err) => Some(err), + Self::Filter(err) => Some(err), } - - writer.into_inner().unwrap() } +} - fn truncate_last_record_batch(bytes: &mut Vec) { - let mut cursor = Cursor::new(bytes.as_slice()); - let mut offset = 0usize; - let mut last_record_batch = None; - let total = bytes.len() as u64; - while let Some((header, size)) = - find_limit_and_type(&mut cursor, total.saturating_sub(offset as u64)).unwrap() - { - if header == MessageHeader::RecordBatch { - last_record_batch = Some((offset, size)); - } - offset += size; - } +/// Per-reader execution statistics for [`TwoPhaseFilteredReader`]. +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +pub(crate) struct TwoPhaseReadStats { + pub(crate) messages_scanned: usize, + pub(crate) batches_skipped_empty: usize, + pub(crate) batches_skipped_zero_matches: usize, + pub(crate) batches_all_matched: usize, + pub(crate) batches_partially_matched: usize, + pub(crate) phase2_decodes: usize, + pub(crate) fell_back_to_single_phase: bool, + pub(crate) fallback_reason: Option, +} - let (offset, size) = last_record_batch.expect("record batch message"); - bytes.truncate(offset + size / 2); - } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum ColumnSource { + Filter(usize), + Extra(usize), +} - #[test] - fn mixed_compression_includes_dictionary_message_metadata() { - use arrow_ipc::{CompressionType, reader::StreamReader}; - let raw = IpcWriteOptions::default(); - let compressed = IpcWriteOptions::default() - .try_with_compression(Some(CompressionType::LZ4_FRAME)) - .unwrap(); - let batches = [1, 1000, 10] - .into_iter() - .enumerate() - .map(|(i, n)| { - let value = if i % 2 == 0 { "alpha" } else { "beta" }; - RecordBatch::try_from_iter([( - "dict", - Arc::new(DictionaryArray::::from_iter( - (0..n).map(|_| value), - )) as Arc, - )]) - .unwrap() - }) - .collect::>(); - let mut tracker = DictionaryTracker::new(false); - let generator = IpcDataGenerator::default(); - let mut context = IpcWriteContext::default(); - let mut bytes = Vec::new(); - let schema = generator.schema_to_bytes_with_dictionary_tracker( - &batches[0].schema(), - &mut tracker, - &compressed, - ); - write_message(&mut bytes, schema, &compressed).unwrap(); - for (i, batch) in batches.iter().enumerate() { - let options = if i % 2 == 0 { &raw } else { &compressed }; - let (dicts, message) = generator - .encode(batch, &mut tracker, options, &mut context) - .unwrap(); - assert_eq!(dicts.len(), 1); - for dict in dicts { - write_message(&mut bytes, dict, options).unwrap(); - } - write_message(&mut bytes, message, options).unwrap(); +enum TwoPhaseReaderSource { + TwoPhase(R), + SinglePhase(Box>>>), + Exhausted, +} + +impl fmt::Debug for TwoPhaseReaderSource { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::TwoPhase(reader) => f.debug_tuple("TwoPhase").field(reader).finish(), + Self::SinglePhase(reader) => f.debug_tuple("SinglePhase").field(reader).finish(), + Self::Exhausted => f.write_str("Exhausted"), } - bytes.extend_from_slice(&[255, 255, 255, 255, 0, 0, 0, 0]); - assert_eq!( - StreamReader::try_new(Cursor::new(&bytes), None) - .unwrap() - .collect::, _>>() - .unwrap(), - batches - ); - assert_eq!( - get_forward_reader(Cursor::new(&bytes)) - .unwrap() - .collect::, _>>() - .unwrap(), - batches - ); - // Reverse staging readers preserve forward order when dictionary - // messages are present so valid dictionary-encoded files decode cleanly. - assert_eq!( - get_reverse_reader(Cursor::new(&bytes)) - .unwrap() - .collect::, _>>() - .unwrap(), - batches - ); } +} - #[test] - fn reverse_reader_recovers_complete_batches_before_truncated_tail() { - let mut bytes = write_mem(&[rb(2), rb(3)]); - truncate_last_record_batch(&mut bytes); +type CancelCheck = Arc bool + Send + Sync>; - let reader = get_reverse_reader(Cursor::new(bytes)).unwrap(); - let batches = reader.collect::, _>>().unwrap(); +/// Two-phase filter-first Arrow IPC batch reader over pre-validated +/// non-dictionary `RecordBatch` message ranges. +/// +/// `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: +/// 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. +/// 3. If all rows match, only `extra_indices = output_indices \ filter_indices` +/// are decoded and stitched in `output_indices` order, detaching any +/// uncompressed slices so the raw IPC message buffer is freed immediately. +/// 4. If a strict subset of rows match, only `extra_indices` are decoded, +/// columns are stitched in `output_indices` order, and +/// `arrow_select::filter::filter_record_batch` is applied. +/// +/// If a message exceeds `max_message_bytes`, the process-wide shared budget is +/// exhausted, or `max_consecutive_matches_before_fallback` consecutive batches +/// match with zero skipped batches: +/// - [`Self::next_step`] yields [`TwoPhaseStep::FallbackToSinglePhase`] with the +/// exact `resume_range_index` so the caller can resume via `StreamReader`. +/// - [`Iterator::next`] seamlessly switches internally to streaming +/// [`StreamReader`] over `[schema_range, ranges[resume_range_index..]]` with +/// zero dropped or duplicated rows. +pub(crate) struct TwoPhaseFilteredReader { + source: TwoPhaseReaderSource, + ranges: Arc<[(u64, usize)]>, + next_range_idx: usize, + file_schema: Arc, + filter_schema: Arc, + output_schema: Arc, + filter_indices: Vec, + output_indices: Vec, + extra_indices: Vec, + stitch_plan: Vec, + single_phase_indices: Vec, + single_phase_filter_positions: Vec, + single_phase_output_positions: Vec, + empty_dictionaries: HashMap, + eval_filter: F, + max_message_bytes: usize, + shared_budget: BudgetHandle, + max_consecutive_matches_before_fallback: Option, + consecutive_matching_batches: usize, + pending_fallback: Option<(usize, TwoPhaseFallbackReason)>, + is_cancelled: Option, + failed: bool, + handed_off: bool, + cancelled: bool, + stats: TwoPhaseReadStats, +} - assert_eq!(batches.len(), 1); - assert_eq!(batches[0].num_rows(), 2); +impl fmt::Debug for TwoPhaseFilteredReader { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("TwoPhaseFilteredReader") + .field("source", &self.source) + .field("range_count", &self.ranges.len()) + .field("next_range_idx", &self.next_range_idx) + .field("file_schema", &self.file_schema) + .field("output_schema", &self.output_schema) + .field("filter_indices", &self.filter_indices) + .field("output_indices", &self.output_indices) + .field("extra_indices", &self.extra_indices) + .field("max_message_bytes", &self.max_message_bytes) + .field( + "max_consecutive_matches_before_fallback", + &self.max_consecutive_matches_before_fallback, + ) + .field( + "consecutive_matching_batches", + &self.consecutive_matching_batches, + ) + .field("has_cancel_check", &self.is_cancelled.is_some()) + .field("failed", &self.failed) + .field("handed_off", &self.handed_off) + .field("cancelled", &self.cancelled) + .field("stats", &self.stats) + .finish() } +} - #[test] - fn forward_reader_recovers_complete_batches_before_truncated_tail() { - let mut bytes = write_mem(&[rb(2), rb(3)]); - truncate_last_record_batch(&mut bytes); - - let reader = get_forward_reader(Cursor::new(bytes)).unwrap(); - let batches = reader.collect::, _>>().unwrap(); +#[allow(dead_code)] // Accessors and builders used by StagingDiskPartition and tests. +impl TwoPhaseFilteredReader { + /// Returns the full file schema parsed once from `ranges[0]`. + pub(crate) fn file_schema(&self) -> Arc { + Arc::clone(&self.file_schema) + } - assert_eq!(batches.len(), 1); - assert_eq!(batches[0].num_rows(), 2); + /// Returns the projected schema passed to `eval_filter`. + pub(crate) fn filter_schema(&self) -> Arc { + Arc::clone(&self.filter_schema) } - #[test] - fn forward_reader_preserves_batch_order() { - let bytes = write_mem(&[rb(1), rb(2), rb(3)]); + /// Returns the projected schema of yielded output batches. + pub(crate) fn output_schema(&self) -> Arc { + Arc::clone(&self.output_schema) + } - let reader = get_forward_reader(Cursor::new(bytes)).unwrap(); - let rows = reader - .map(|batch| batch.unwrap().num_rows()) - .collect::>(); + /// Returns per-reader execution statistics. + pub(crate) fn stats(&self) -> TwoPhaseReadStats { + self.stats + } - assert_eq!(rows, vec![1, 2, 3]); + /// Configures adaptive fallback after `max_consecutive_matches` consecutive + /// matching batches (with zero skipped zero-match batches). Pass `None` or + /// `0` to disable adaptive fallback. + pub(crate) fn with_adaptive_fallback( + mut self, + max_consecutive_matches: impl Into>, + ) -> Self { + self.max_consecutive_matches_before_fallback = + max_consecutive_matches.into().filter(|&n| n > 0); + self } - #[test] - fn reverse_reader_rejects_stream_without_complete_batch() { - let mut bytes = write_mem(&[rb(2)]); - truncate_last_record_batch(&mut bytes); + /// Overrides the per-message buffer byte limit before falling back to + /// streaming single-phase [`StreamReader`]. + pub(crate) fn with_max_message_bytes(mut self, max_message_bytes: usize) -> Self { + self.max_message_bytes = max_message_bytes; + self + } - let err = get_reverse_reader(Cursor::new(bytes)).unwrap_err(); - assert!(err.to_string().contains("no complete record batch")); + /// Configures a cancellation predicate checked before reading each IPC + /// message so zero-match runs stop immediately when cancelled. + pub(crate) fn with_cancel_check(mut self, is_cancelled: C) -> Self + where + C: Fn() -> bool + Send + Sync + 'static, + { + self.is_cancelled = Some(Arc::new(is_cancelled)); + self } - #[test] - fn reverse_reader_accepts_complete_batches_without_eos() { - let mut bytes = write_mem(&[rb(2)]); - bytes.truncate(bytes.len() - 8); + /// Convenience wrapper around [`Self::with_cancel_check`] backed by an + /// [`AtomicBool`]. + pub(crate) fn with_cancel_flag(self, cancelled: Arc) -> Self { + self.with_cancel_check(move || cancelled.load(Ordering::Relaxed)) + } - let reader = get_reverse_reader(Cursor::new(bytes)).unwrap(); - let batches = reader.collect::, _>>().unwrap(); + #[cfg(test)] + pub(crate) fn with_shared_budget(mut self, budget: Arc) -> Self { + self.shared_budget = BudgetHandle::Shared(budget); + self + } - assert_eq!(batches.len(), 1); - assert_eq!(batches[0].num_rows(), 2); + /// Builds `[schema_range, ranges[resume_range_index..]]` so a caller + /// handling [`TwoPhaseStep::FallbackToSinglePhase`] can hand the unread + /// messages directly to streaming [`StreamReader`]. + pub(crate) fn remaining_ranges_with_schema( + &self, + resume_range_index: usize, + ) -> Arc<[(u64, usize)]> { + let start = resume_range_index.max(1).min(self.ranges.len()); + let tail = &self.ranges[start..]; + let mut remaining = Vec::with_capacity(1 + tail.len()); + remaining.push(self.ranges[0]); + remaining.extend_from_slice(tail); + Arc::from(remaining) } - #[test] - fn test_empty_row() { - let rb = rb(0); - let buf = write_mem(&[rb]); - let reader = Cursor::new(buf); - let mut reader = get_reverse_reader(reader).unwrap(); - let rb = reader.next().unwrap().unwrap(); - assert_eq!(rb.num_rows(), 0); + fn check_cancelled(&mut self) -> bool { + if self.cancelled { + return true; + } + if let Some(check) = &self.is_cancelled + && check() + { + self.cancelled = true; + return true; + } + false } - #[test] - fn test_one_row() { - let rb = rb(1); - let buf = write_mem(&[rb]); - let reader = Cursor::new(buf); - let mut reader = get_reverse_reader(reader).unwrap(); - let rb = reader.next().unwrap().unwrap(); - assert_eq!(rb.num_rows(), 1); + fn record_matching_batch(&mut self) { + self.consecutive_matching_batches += 1; + if let Some(threshold) = self.max_consecutive_matches_before_fallback + && threshold > 0 + && self.stats.batches_skipped_zero_matches == 0 + && self.consecutive_matching_batches >= threshold + && self.next_range_idx < self.ranges.len() + { + self.pending_fallback = Some(( + self.next_range_idx, + TwoPhaseFallbackReason::AdaptiveConsecutiveMatches { + consecutive_matches: self.consecutive_matching_batches, + }, + )); + } } +} - #[test] - fn test_multiple_row_multiple_rbs() { - let buf = write_mem(&[rb(1), rb(2), rb(3)]); - let reader = Cursor::new(buf); - let mut reader = get_reverse_reader(reader).unwrap(); - let rb = reader.next().unwrap().unwrap(); - assert_eq!(rb.num_rows(), 3); - let col1_val: Vec = rb - .column(0) - .as_primitive::() - .iter() - .flatten() - .collect(); - assert_eq!(col1_val, vec![0, 1, 2]); +impl TwoPhaseFilteredReader +where + R: Read + Seek, + F: FnMut(&RecordBatch) -> Result, +{ + /// Opens a two-phase filter-first IPC reader, parsing the schema message + /// once from `ranges[0]` and validating `filter_indices` and + /// `output_indices`. + pub(crate) fn try_new( + mut reader: R, + ranges: Arc<[(u64, usize)]>, + filter_indices: Vec, + output_indices: Vec, + eval_filter: F, + ) -> Result { + let Some(&(schema_offset, schema_size)) = ranges.first() else { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "Arrow IPC ranges missing schema message", + )); + }; + if schema_size > MAX_IPC_SCHEMA_MESSAGE_BYTES { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("Arrow IPC schema message length {schema_size} exceeds maximum"), + )); + } - let rb = reader.next().unwrap().unwrap(); - assert_eq!(rb.num_rows(), 2); + let schema_buf = read_exact_range(&mut reader, schema_offset, schema_size)?; + let file_schema = parse_schema_message(schema_buf.as_slice())?; + let num_fields = file_schema.fields().len(); - let rb = reader.next().unwrap().unwrap(); - assert_eq!(rb.num_rows(), 1); + if filter_indices.is_empty() { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "Two-phase IPC reader requires at least one filter column index", + )); + } + validate_sorted_unique_indices(&filter_indices, num_fields, "filter_indices")?; + validate_sorted_unique_indices(&output_indices, num_fields, "output_indices")?; + + let filter_schema = Arc::new(file_schema.project(&filter_indices).map_err(|err| { + io::Error::new( + io::ErrorKind::InvalidInput, + format!("Invalid filter_indices projection: {err}"), + ) + })?); + let output_schema = Arc::new(file_schema.project(&output_indices).map_err(|err| { + io::Error::new( + io::ErrorKind::InvalidInput, + format!("Invalid output_indices projection: {err}"), + ) + })?); + let (extra_indices, stitch_plan) = build_stitch_plan(&filter_indices, &output_indices); + let (single_phase_indices, single_phase_filter_positions, single_phase_output_positions) = + build_single_phase_plan(&filter_indices, &output_indices); + + Ok(Self { + source: TwoPhaseReaderSource::TwoPhase(reader), + ranges, + next_range_idx: 1, + file_schema, + filter_schema, + output_schema, + filter_indices, + output_indices, + extra_indices, + stitch_plan, + 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), + max_consecutive_matches_before_fallback: None, + consecutive_matching_batches: 0, + pending_fallback: None, + is_cancelled: None, + failed: false, + handed_off: false, + cancelled: false, + stats: TwoPhaseReadStats::default(), + }) } - #[test] - fn manual_write() { - let error_on_replacement = true; - let options = IpcWriteOptions::default(); - let mut dictionary_tracker = DictionaryTracker::new(error_on_replacement); - let data_gen = IpcDataGenerator {}; - let mut compression_context = IpcWriteContext::default(); + /// Advances the reader by one step, returning + /// [`TwoPhaseStep::FallbackToSinglePhase`] if a message exceeds the buffer + /// budget or adaptive fallback triggers so the caller can explicitly switch + /// remaining ranges to [`StreamReader`]. + #[allow(dead_code)] // Explicit fallback API for StagingDiskPartition and tests. + pub(crate) fn next_step(&mut self) -> Result> { + if self.failed || self.handed_off || self.cancelled { + return Ok(TwoPhaseStep::Finished); + } + match self.next_step_internal() { + Ok(step @ TwoPhaseStep::FallbackToSinglePhase { .. }) => { + self.handed_off = true; + Ok(step) + } + Ok(step) => Ok(step), + Err(err) => { + self.failed = true; + Err(err) + } + } + } - let mut buf = Vec::new(); - let rb1 = rb(1); + fn next_step_internal(&mut self) -> Result> { + if matches!(self.source, TwoPhaseReaderSource::SinglePhase(_)) { + return match self.next_single_phase_batch()? { + Some(batch) => Ok(TwoPhaseStep::Batch(batch)), + None => Ok(TwoPhaseStep::Finished), + }; + } - let schema = data_gen.schema_to_bytes_with_dictionary_tracker( - &rb1.schema(), - &mut dictionary_tracker, - &options, - ); - write_message(&mut buf, schema, &options).unwrap(); + if self.check_cancelled() { + return Ok(TwoPhaseStep::Finished); + } - for i in (1..=3).cycle().skip(1).take(10000) { - let (_, encoded_message) = data_gen - .encode( - &rb(i), - &mut dictionary_tracker, - &options, - &mut compression_context, - ) - .unwrap(); - write_message(&mut buf, encoded_message, &options).unwrap(); + if let Some((resume_range_index, reason)) = self.pending_fallback.take() { + self.stats.fell_back_to_single_phase = true; + self.stats.fallback_reason = Some(reason); + return Ok(TwoPhaseStep::FallbackToSinglePhase { + resume_range_index, + reason, + }); } - let schema = data_gen.schema_to_bytes_with_dictionary_tracker( - &rb1.schema(), - &mut dictionary_tracker, - &options, - ); - write_message(&mut buf, schema, &options).unwrap(); + while let Some(&(offset, size)) = self.ranges.get(self.next_range_idx) { + if self.check_cancelled() { + return Ok(TwoPhaseStep::Finished); + } - let buf = Cursor::new(buf); - let reader = get_reverse_reader(buf).unwrap().flatten(); + let current_range_idx = self.next_range_idx; + + if size > self.max_message_bytes { + let reason = TwoPhaseFallbackReason::MessageTooLarge { + message_bytes: size, + limit_bytes: self.max_message_bytes, + }; + self.stats.fell_back_to_single_phase = true; + self.stats.fallback_reason = Some(reason); + return Ok(TwoPhaseStep::FallbackToSinglePhase { + resume_range_index: current_range_idx, + reason, + }); + } - let mut sum = 0; - for rb in reader { - sum += 1; - assert!(rb.num_rows() > 0); - } + // 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. + let Some(_budget_permit) = self.shared_budget.try_acquire(size) else { + let reason = TwoPhaseFallbackReason::SharedBudgetExhausted { + message_bytes: size, + }; + self.stats.fell_back_to_single_phase = true; + self.stats.fallback_reason = Some(reason); + return Ok(TwoPhaseStep::FallbackToSinglePhase { + resume_range_index: current_range_idx, + reason, + }); + }; + + self.next_range_idx += 1; + self.stats.messages_scanned += 1; + + let (output_batch, true_count, num_rows) = { + 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, + ) + .map_err(TwoPhaseReadError::Arrow)?; - assert_eq!(sum, 10000); - } + let num_rows = filter_batch.num_rows(); + if num_rows == 0 { + self.stats.batches_skipped_empty += 1; + continue; + } - // Helper function to create test record batches - fn create_test_batches(schema: &Arc, count: usize) -> Vec { - let mut batches = Vec::with_capacity(count); + let mask = (self.eval_filter)(&filter_batch).map_err(TwoPhaseReadError::Filter)?; + if mask.len() != num_rows { + return Err(TwoPhaseReadError::Arrow(ArrowError::InvalidArgumentError( + format!( + "Filter mask length {} does not match batch row count {num_rows}", + mask.len() + ), + ))); + } - for batch_num in 1..=count as i32 { - let id_array = Int32Array::from_iter(batch_num * 10..=batch_num * 10 + 1); - let name_array = StringArray::from(vec![ - format!("Name {batch_num}-1"), - format!("Name {batch_num}-2"), - ]); + let true_count = mask.true_count(); + 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. + continue; + } - let batch = RecordBatch::try_new( - schema.clone(), - vec![Arc::new(id_array), Arc::new(name_array)], - ) - .expect("Failed to create test batch"); + let batch = if self.stitch_plan.is_empty() { + let options = RecordBatchOptions::new().with_row_count(Some(true_count)); + RecordBatch::try_new_with_options( + Arc::clone(&self.output_schema), + Vec::new(), + &options, + ) + .map_err(TwoPhaseReadError::Arrow)? + } else { + // Phase 2: decompress and decode ONLY `extra_indices`. + let extra_batch = if self.extra_indices.is_empty() { + None + } 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)?, + ) + }; - batches.push(batch); - } + let mut columns = Vec::with_capacity(self.stitch_plan.len()); + for source in &self.stitch_plan { + match *source { + ColumnSource::Filter(idx) => { + columns.push(Arc::clone(filter_batch.column(idx))); + } + ColumnSource::Extra(idx) => { + columns.push(Arc::clone( + extra_batch + .as_ref() + .expect( + "extra_batch decoded whenever stitch_plan references Extra", + ) + .column(idx), + )); + } + } + } - batches - } + let combined = RecordBatch::try_new_with_options( + Arc::clone(&self.output_schema), + columns, + &RecordBatchOptions::new().with_row_count(Some(num_rows)), + ) + .map_err(TwoPhaseReadError::Arrow)?; + + // 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)? + } else { + let filtered = filter_record_batch(&combined, &mask) + .map_err(TwoPhaseReadError::Arrow)?; + detach_batch_from_raw(filtered, raw_data_ptr) + .map_err(TwoPhaseReadError::Arrow)? + } + }; - // Helper function to write batches to a file - fn write_test_batches( - path: &Path, - schema: &Arc, - batches: &[RecordBatch], - ) -> io::Result<()> { - let range = TimeRange::granularity_range(Utc::now(), OBJECT_STORE_DATA_GRANULARITY); - let mut writer = - DiskWriter::try_new(path, schema, range).expect("Failed to create StreamWriter"); + (batch, true_count, num_rows) + }; + drop(_budget_permit); - for batch in batches { - writer.write(batch).expect("Failed to write batch"); + if true_count == num_rows { + self.stats.batches_all_matched += 1; + } else { + self.stats.batches_partially_matched += 1; + } + self.record_matching_batch(); + return Ok(TwoPhaseStep::Batch(output_batch)); } - Ok(()) + Ok(TwoPhaseStep::Finished) } - /// Two sealed files giving one field incompatible types must be reported, - /// not panic the conversion that merges them. - #[test] - fn merged_schema_reports_incompatible_files() -> io::Result<()> { - let dir = TempDir::new().unwrap(); - let schema_of = |value: DataType| { - Arc::new(Schema::new(vec![ - Field::new("id", DataType::Int32, false), - Field::new("value", value, false), - ])) + fn switch_to_single_phase( + &mut self, + resume_range_index: usize, + ) -> Result<(), TwoPhaseReadError> { + let remaining_ranges = self.remaining_ranges_with_schema(resume_range_index); + let projection = if self.single_phase_indices.len() == self.file_schema.fields().len() { + // Full schema needed (e.g., SELECT *): pass `projection = None` to + // avoid projection overhead in Arrow's streaming reader. + None + } else { + Some(self.single_phase_indices.clone()) }; - let numbers = schema_of(DataType::Int64); - let text = schema_of(DataType::Utf8); - let numbers_path = dir.path().join("numbers.data.arrows"); - let text_path = dir.path().join("text.data.arrows"); - write_test_batches( - &numbers_path, - &numbers, - &[RecordBatch::try_new( - numbers.clone(), - vec![ - Arc::new(Int32Array::from(vec![1])), - Arc::new(Int64Array::from(vec![10])), - ], - ) - .unwrap()], - )?; - write_test_batches( - &text_path, - &text, - &[RecordBatch::try_new( - text.clone(), - vec![ - Arc::new(Int32Array::from(vec![2])), - Arc::new(StringArray::from(vec!["ten"])), - ], - ) - .unwrap()], - )?; - let files = [numbers_path, text_path]; - let reverse = MergedReverseRecordReader::try_new(&files); - assert_eq!(reverse.readable_files.len(), 2); - assert!(reverse.merged_schema().is_err()); - let forward = MergedForwardRecordReader::try_new(&files); - assert_eq!(forward.readable_files.len(), 2); - assert!(forward.merged_schema().is_err()); - // Each file alone still merges. - let alone = MergedReverseRecordReader::try_new(&files[..1]); - assert_eq!(alone.merged_schema().unwrap(), *numbers); + let raw_reader = match std::mem::replace(&mut self.source, TwoPhaseReaderSource::Exhausted) + { + TwoPhaseReaderSource::TwoPhase(reader) => reader, + other => { + self.source = other; + return Ok(()); + } + }; + + let stream_reader = stream_reader_for_ranges( + raw_reader, + remaining_ranges, + projection, + MESSAGE_READ_BUFFER_BYTES, + ) + .map_err(TwoPhaseReadError::Io)?; + self.source = TwoPhaseReaderSource::SinglePhase(Box::new(stream_reader)); Ok(()) } - #[test] - fn test_message_range_reader() { - // Create a simple binary file in memory - let data = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; - let cursor = Cursor::new(data); + fn next_single_phase_batch(&mut self) -> Result, TwoPhaseReadError> { + loop { + if self.check_cancelled() { + return Ok(None); + } + let next = match &mut self.source { + TwoPhaseReaderSource::SinglePhase(reader) => reader.next(), + _ => return Ok(None), + }; + let Some(batch_res) = next else { + self.source = TwoPhaseReaderSource::Exhausted; + 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 num_rows = batch.num_rows(); + if num_rows == 0 { + self.stats.batches_skipped_empty += 1; + continue; + } - // Define offset list: (offset, size) - let offsets = vec![(2, 3), (7, 2)]; // Read bytes 2-4 (3, 4, 5) and then 7-8 (8, 9) + let mask = if self.single_phase_filter_positions.len() == batch.num_columns() + && self + .single_phase_filter_positions + .iter() + .enumerate() + .all(|(i, &pos)| i == pos) + { + (self.eval_filter)(&batch).map_err(TwoPhaseReadError::Filter)? + } else { + let filter_batch = batch + .project(&self.single_phase_filter_positions) + .map_err(TwoPhaseReadError::Arrow)?; + (self.eval_filter)(&filter_batch).map_err(TwoPhaseReadError::Filter)? + }; + + if mask.len() != num_rows { + return Err(TwoPhaseReadError::Arrow(ArrowError::InvalidArgumentError( + format!( + "Filter mask length {} does not match batch row count {num_rows}", + mask.len() + ), + ))); + } - let mut reader = MessageRangeReader::new(cursor, offsets); - let mut buffer = [0u8; 10]; + let true_count = mask.true_count(); + if true_count == 0 { + self.stats.batches_skipped_zero_matches += 1; + continue; + } - // First read should get bytes 3, 4, 5 - let read_bytes = reader.read(&mut buffer).unwrap(); - assert_eq!(read_bytes, 3); - assert_eq!(&buffer[..read_bytes], &[3, 4, 5]); + if self.output_indices.is_empty() { + if true_count == num_rows { + self.stats.batches_all_matched += 1; + } else { + self.stats.batches_partially_matched += 1; + } + let options = RecordBatchOptions::new().with_row_count(Some(true_count)); + let empty_out = RecordBatch::try_new_with_options( + Arc::clone(&self.output_schema), + Vec::new(), + &options, + ) + .map_err(TwoPhaseReadError::Arrow)?; + return Ok(Some(empty_out)); + } - // Second read should get bytes 8, 9 - let read_bytes = reader.read(&mut buffer).unwrap(); - assert_eq!(read_bytes, 2); - assert_eq!(&buffer[..read_bytes], &[8, 9]); + let out_batch = if self.single_phase_output_positions.len() == batch.num_columns() + && self + .single_phase_output_positions + .iter() + .enumerate() + .all(|(i, &pos)| i == pos) + { + batch + } else { + batch + .project(&self.single_phase_output_positions) + .map_err(TwoPhaseReadError::Arrow)? + }; - // No more data - let read_bytes = reader.read(&mut buffer).unwrap(); - assert_eq!(read_bytes, 0); - } + if true_count == num_rows { + self.stats.batches_all_matched += 1; + return Ok(Some(out_batch)); + } - #[test] - fn test_merged_reverse_record_reader() -> io::Result<()> { - let dir = TempDir::new().unwrap(); - let file_path = dir.path().join("test.data.arrows"); + self.stats.batches_partially_matched += 1; + let filtered = + filter_record_batch(&out_batch, &mask).map_err(TwoPhaseReadError::Arrow)?; + return Ok(Some(filtered)); + } + } +} - // Create a schema - let schema = Arc::new(Schema::new(vec![ - Field::new("id", DataType::Int32, false), - Field::new("name", DataType::Utf8, false), - ])); +impl Iterator for TwoPhaseFilteredReader +where + R: Read + Seek, + F: FnMut(&RecordBatch) -> Result, +{ + type Item = Result>; - // Create test batches (3 batches) - let batches = create_test_batches(&schema, 3); + fn next(&mut self) -> Option { + if self.failed || self.handed_off || self.cancelled { + return None; + } + loop { + match self.next_step_internal() { + Ok(TwoPhaseStep::Batch(batch)) => return Some(Ok(batch)), + Ok(TwoPhaseStep::Finished) => return None, + Ok(TwoPhaseStep::FallbackToSinglePhase { + resume_range_index, .. + }) => { + if let Err(err) = self.switch_to_single_phase(resume_range_index) { + self.failed = true; + return Some(Err(err)); + } + } + Err(err) => { + self.failed = true; + return Some(Err(err)); + } + } + } + } +} - // Write batches to file - write_test_batches(&file_path, &schema, &batches)?; +/// Builds a two-phase filter-first Arrow IPC reader over pre-validated +/// non-dictionary message ranges (`ranges[0]` = schema, `ranges[1..]` = record +/// batches). +pub(crate) fn two_phase_filtered_reader( + reader: R, + ranges: Arc<[(u64, usize)]>, + filter_indices: Vec, + output_indices: Vec, + eval_filter: F, +) -> Result, io::Error> +where + R: Read + Seek, + F: FnMut(&RecordBatch) -> Result, +{ + TwoPhaseFilteredReader::try_new(reader, ranges, filter_indices, output_indices, eval_filter) +} - // Now read them back in reverse order - let mut reader = - MergedReverseRecordReader::try_new(&[file_path.into()]).merged_iter(schema, None); +/// Copies any buffer in `batch` whose underlying allocation is `raw_data_ptr` +/// (e.g., uncompressed IPC slices or empty slices pinning the raw message +/// allocation) so the whole raw IPC message buffer can be freed immediately. +fn detach_batch_from_raw( + batch: RecordBatch, + raw_data_ptr: NonNull, +) -> Result { + if batch.num_columns() == 0 { + return Ok(batch); + } + let needs_detach = batch + .columns() + .iter() + .any(|col| array_data_references_raw(&col.to_data(), raw_data_ptr)); + if !needs_detach { + return Ok(batch); + } - // We should get batches in reverse order: 3, 2, 1 - // But first message should be schema, so we'll still read them in order + let schema = batch.schema(); + let num_rows = batch.num_rows(); + let mut columns = Vec::with_capacity(batch.num_columns()); + for col in batch.columns() { + let data = col.to_data(); + if array_data_references_raw(&data, raw_data_ptr) { + columns.push(make_array(detach_array_data(data, raw_data_ptr)?)); + } else { + columns.push(Arc::clone(col)); + } + } + RecordBatch::try_new_with_options( + schema, + columns, + &RecordBatchOptions::new().with_row_count(Some(num_rows)), + ) +} - // Read batch 3 - let batch = reader - .next() - .expect("Failed to read batch") - .expect("Invalid batch"); - assert_eq!(batch.num_rows(), 2); - let id_array = batch - .column(0) - .as_any() - .downcast_ref::() - .unwrap(); - assert_eq!(id_array.value(0), 31); // affect of reverse on each recordbatch - assert_eq!(id_array.value(1), 30); +fn array_data_references_raw(data: &ArrayData, raw_data_ptr: NonNull) -> bool { + if data + .buffers() + .iter() + .any(|buf| buf.data_ptr() == raw_data_ptr) + { + return true; + } + if let Some(nulls) = data.nulls() + && nulls.buffer().data_ptr() == raw_data_ptr + { + return true; + } + data.child_data() + .iter() + .any(|child| array_data_references_raw(child, raw_data_ptr)) +} - // Read batch 2 - let batch = reader - .next() - .expect("Failed to read batch") - .expect("Invalid batch"); - assert_eq!(batch.num_rows(), 2); - let id_array = batch - .column(0) - .as_any() - .downcast_ref::() - .unwrap(); - assert_eq!(id_array.value(0), 21); - assert_eq!(id_array.value(1), 20); +fn detach_buffer(buf: &Buffer, raw_data_ptr: NonNull) -> Buffer { + if buf.data_ptr() != raw_data_ptr { + buf.clone() + } else if buf.is_empty() { + Buffer::from(&[] as &[u8]) + } else { + Buffer::from_slice_ref(buf.as_slice()) + } +} - // Read batch 1 - let batch = reader - .next() - .expect("Failed to read batch") - .expect("Invalid batch"); - assert_eq!(batch.num_rows(), 2); - let id_array = batch - .column(0) - .as_any() - .downcast_ref::() - .unwrap(); - assert_eq!(id_array.value(0), 11); - assert_eq!(id_array.value(1), 10); +fn detach_array_data(data: ArrayData, raw_data_ptr: NonNull) -> Result { + let buffers: Vec = data + .buffers() + .iter() + .map(|buf| detach_buffer(buf, raw_data_ptr)) + .collect(); + let nulls = data.nulls().map(|nulls| { + if nulls.buffer().data_ptr() == raw_data_ptr { + let detached = detach_buffer(nulls.buffer(), raw_data_ptr); + NullBuffer::new(BooleanBuffer::new(detached, nulls.offset(), nulls.len())) + } else { + nulls.clone() + } + }); + let children = data + .child_data() + .iter() + .map(|child| { + if array_data_references_raw(child, raw_data_ptr) { + detach_array_data(child.clone(), raw_data_ptr) + } else { + Ok(child.clone()) + } + }) + .collect::, _>>()?; - // No more batches - assert!(reader.next().is_none()); + data.into_builder() + .buffers(buffers) + .nulls(nulls) + .child_data(children) + .build() +} - Ok(()) +/// Computes the sorted union `filter_indices U output_indices` along with the +/// positions of `filter_indices` and `output_indices` inside that union for +/// single-phase streaming fallback. +fn build_single_phase_plan( + filter_indices: &[usize], + output_indices: &[usize], +) -> (Vec, Vec, Vec) { + let mut union = Vec::with_capacity(filter_indices.len() + output_indices.len()); + let mut filter_pos = Vec::with_capacity(filter_indices.len()); + let mut output_pos = Vec::with_capacity(output_indices.len()); + let (mut fi, mut oi) = (0usize, 0usize); + + while fi < filter_indices.len() || oi < output_indices.len() { + let next_pos = union.len(); + match (filter_indices.get(fi), output_indices.get(oi)) { + (Some(&f), Some(&o)) if f == o => { + union.push(f); + filter_pos.push(next_pos); + output_pos.push(next_pos); + fi += 1; + oi += 1; + } + (Some(&f), Some(&o)) if f < o => { + union.push(f); + filter_pos.push(next_pos); + fi += 1; + } + (Some(_), Some(&o)) => { + union.push(o); + output_pos.push(next_pos); + oi += 1; + } + (Some(&f), None) => { + union.push(f); + filter_pos.push(next_pos); + fi += 1; + } + (None, Some(&o)) => { + union.push(o); + output_pos.push(next_pos); + oi += 1; + } + (None, None) => break, + } } - #[test] + (union, filter_pos, output_pos) +} + +/// Reads an exact `[offset, offset + size)` byte range into a single aligned +/// Arrow `Buffer`. Any physical short read fails closed with +/// `io::ErrorKind::InvalidData` (never silent EOF). +fn read_exact_range( + reader: &mut R, + offset: u64, + size: usize, +) -> io::Result { + reader.seek(SeekFrom::Start(offset))?; + let mut buf = MutableBuffer::from_len_zeroed(size); + let slice = buf.as_slice_mut(); + let mut read_total = 0; + while read_total < size { + match reader.read(&mut slice[read_total..]) { + Ok(0) => { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "Arrow IPC message ended before its declared boundary", + )); + } + Ok(n) => read_total += n, + Err(err) if err.kind() == io::ErrorKind::Interrupted => continue, + Err(err) => return Err(err), + } + } + Ok(Buffer::from(buf)) +} + +/// 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)> { + if bytes.len() < 4 { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "Arrow IPC message shorter than 4-byte length prefix", + )); + } + + let (meta_start, raw_len) = if bytes[..4] == IPC_CONTINUATION_MARKER { + if bytes.len() < 8 { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "Arrow IPC message truncated after continuation marker", + )); + } + (8usize, i32::from_le_bytes(bytes[4..8].try_into().unwrap())) + } else { + (4usize, i32::from_le_bytes(bytes[..4].try_into().unwrap())) + }; + + if raw_len <= 0 { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("Invalid Arrow IPC metadata length: {raw_len}"), + )); + } + let meta_len = raw_len as usize; + if meta_len > MAX_IPC_METADATA_BYTES { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("Arrow IPC metadata length {meta_len} exceeds maximum"), + )); + } + let meta_end = meta_start.checked_add(meta_len).ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidData, + "Arrow IPC metadata length overflow", + ) + })?; + if meta_end > bytes.len() { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!( + "Arrow IPC metadata boundary {meta_end} exceeds declared message range length {}", + bytes.len() + ), + )); + } + + Ok((meta_start, meta_len)) +} + +/// Parses a single framed IPC `Schema` message from raw bytes. +fn parse_schema_message(raw: &[u8]) -> io::Result> { + let (meta_start, meta_len) = parse_ipc_message_prefix(raw)?; + let meta_end = meta_start + meta_len; + let message = root_as_message(&raw[meta_start..meta_end]).map_err(|err| { + io::Error::new( + io::ErrorKind::InvalidData, + format!("Invalid Arrow IPC schema message: {err}"), + ) + })?; + if message.header_type() != MessageHeader::Schema { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!( + "Expected Arrow IPC Schema message at ranges[0], got {:?}", + message.header_type() + ), + )); + } + let body_len = usize::try_from(message.bodyLength()).map_err(|_| { + io::Error::new( + io::ErrorKind::InvalidData, + "Invalid Arrow IPC schema body length", + ) + })?; + let body_end = meta_end.checked_add(body_len).ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidData, + "Arrow IPC schema message length overflow", + ) + })?; + if body_end > raw.len() || raw.len() - body_end > 7 { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!( + "Arrow IPC schema boundary {body_end} does not match declared range length {}", + raw.len() + ), + )); + } + let ipc_schema = message.header_as_schema().ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidData, + "Failed to parse Arrow IPC schema header", + ) + })?; + validate_ipc_schema(ipc_schema)?; + Ok(Arc::new(fb_to_schema(ipc_schema))) +} + +/// Validates an Arrow IPC FlatBuffer `Schema` header (endianness, field types, +/// metadata ranges, and child cardinalities) before passing it to +/// `arrow_ipc::convert::fb_to_schema`, preventing panics on corrupt schemas. +fn validate_ipc_schema(ipc_schema: arrow_ipc::Schema<'_>) -> io::Result<()> { + let fields = ipc_schema.fields().ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidData, + "Arrow IPC schema header missing fields vector", + ) + })?; + if !ipc_schema.endianness().equals_to_target_endianness() { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "Arrow IPC schema endianness does not match target platform", + )); + } + let is_big_endian = ipc_schema.endianness() == arrow_ipc::Endianness::Big; + for i in 0..fields.len() { + validate_ipc_field(fields.get(i), is_big_endian, 0)?; + } + Ok(()) +} + +fn validate_ipc_int(int: arrow_ipc::Int<'_>, context: &str) -> io::Result<()> { + match (int.bitWidth(), int.is_signed()) { + (8 | 16 | 32 | 64, true | false) => Ok(()), + (width, signed) => Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("Unsupported Arrow IPC {context} int width={width} signed={signed}"), + )), + } +} + +fn validate_ipc_field( + field: arrow_ipc::Field<'_>, + is_big_endian: bool, + depth: usize, +) -> io::Result<()> { + if depth > MAX_IPC_SCHEMA_DEPTH { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("Arrow IPC schema nesting depth exceeds maximum {MAX_IPC_SCHEMA_DEPTH}"), + )); + } + + if let Some(dict) = field.dictionary() { + let index_type = dict.indexType().ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidData, + "Arrow IPC dictionary field missing indexType", + ) + })?; + validate_ipc_int(index_type, "dictionary index")?; + } + + match field.type_type() { + arrow_ipc::Type::Null + | arrow_ipc::Type::Bool + | arrow_ipc::Type::Binary + | arrow_ipc::Type::BinaryView + | arrow_ipc::Type::LargeBinary + | arrow_ipc::Type::Utf8 + | arrow_ipc::Type::Utf8View + | arrow_ipc::Type::LargeUtf8 => Ok(()), + arrow_ipc::Type::Int => { + let int = field.type_as_int().ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidData, + "Arrow IPC Int field missing Int metadata", + ) + })?; + validate_ipc_int(int, "field") + } + arrow_ipc::Type::FixedSizeBinary => { + let fsb = field.type_as_fixed_size_binary().ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidData, + "Arrow IPC FixedSizeBinary field missing metadata", + ) + })?; + if fsb.byteWidth() < 0 { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!( + "Arrow IPC FixedSizeBinary has negative byteWidth {}", + fsb.byteWidth() + ), + )); + } + Ok(()) + } + arrow_ipc::Type::FloatingPoint => { + let fp = field.type_as_floating_point().ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidData, + "Arrow IPC FloatingPoint field missing metadata", + ) + })?; + match fp.precision() { + arrow_ipc::Precision::HALF + | arrow_ipc::Precision::SINGLE + | arrow_ipc::Precision::DOUBLE => Ok(()), + other => Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("Unsupported Arrow IPC FloatingPoint precision {other:?}"), + )), + } + } + arrow_ipc::Type::Date => { + let date = field.type_as_date().ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidData, + "Arrow IPC Date field missing metadata", + ) + })?; + match date.unit() { + arrow_ipc::DateUnit::DAY | arrow_ipc::DateUnit::MILLISECOND => Ok(()), + other => Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("Unsupported Arrow IPC Date unit {other:?}"), + )), + } + } + arrow_ipc::Type::Time => { + let time = field.type_as_time().ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidData, + "Arrow IPC Time field missing metadata", + ) + })?; + match (time.bitWidth(), time.unit()) { + (32, arrow_ipc::TimeUnit::SECOND | arrow_ipc::TimeUnit::MILLISECOND) + | (64, arrow_ipc::TimeUnit::MICROSECOND | arrow_ipc::TimeUnit::NANOSECOND) => { + Ok(()) + } + (width, unit) => Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("Unsupported Arrow IPC Time bitWidth={width} unit={unit:?}"), + )), + } + } + arrow_ipc::Type::Timestamp => { + let ts = field.type_as_timestamp().ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidData, + "Arrow IPC Timestamp field missing metadata", + ) + })?; + match ts.unit() { + arrow_ipc::TimeUnit::SECOND + | arrow_ipc::TimeUnit::MILLISECOND + | arrow_ipc::TimeUnit::MICROSECOND + | arrow_ipc::TimeUnit::NANOSECOND => Ok(()), + other => Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("Unsupported Arrow IPC Timestamp unit {other:?}"), + )), + } + } + arrow_ipc::Type::Interval => { + let interval = field.type_as_interval().ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidData, + "Arrow IPC Interval field missing metadata", + ) + })?; + match interval.unit() { + arrow_ipc::IntervalUnit::YEAR_MONTH + | arrow_ipc::IntervalUnit::DAY_TIME + | arrow_ipc::IntervalUnit::MONTH_DAY_NANO => Ok(()), + other => Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("Unsupported Arrow IPC Interval unit {other:?}"), + )), + } + } + arrow_ipc::Type::Duration => { + let duration = field.type_as_duration().ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidData, + "Arrow IPC Duration field missing metadata", + ) + })?; + match duration.unit() { + arrow_ipc::TimeUnit::SECOND + | arrow_ipc::TimeUnit::MILLISECOND + | arrow_ipc::TimeUnit::MICROSECOND + | arrow_ipc::TimeUnit::NANOSECOND => Ok(()), + other => Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("Unsupported Arrow IPC Duration unit {other:?}"), + )), + } + } + arrow_ipc::Type::Decimal => { + if is_big_endian { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "Big-endian Arrow IPC Decimal fields are unsupported", + )); + } + let dec = field.type_as_decimal().ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidData, + "Arrow IPC Decimal field missing metadata", + ) + })?; + if !matches!(dec.bitWidth(), 32 | 64 | 128 | 256) { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("Unsupported Arrow IPC Decimal bitWidth {}", dec.bitWidth()), + )); + } + if u8::try_from(dec.precision()).is_err() || i8::try_from(dec.scale()).is_err() { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!( + "Arrow IPC Decimal precision={} scale={} out of range", + dec.precision(), + dec.scale() + ), + )); + } + Ok(()) + } + arrow_ipc::Type::List + | arrow_ipc::Type::LargeList + | arrow_ipc::Type::ListView + | arrow_ipc::Type::LargeListView => { + let children = field.children().ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidData, + format!("Arrow IPC {:?} field missing children", field.type_type()), + ) + })?; + if children.len() != 1 { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!( + "Arrow IPC {:?} field must have exactly 1 child, found {}", + field.type_type(), + children.len() + ), + )); + } + validate_ipc_field(children.get(0), is_big_endian, depth + 1) + } + arrow_ipc::Type::FixedSizeList => { + let fsl = field.type_as_fixed_size_list().ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidData, + "Arrow IPC FixedSizeList field missing metadata", + ) + })?; + if fsl.listSize() < 0 { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!( + "Arrow IPC FixedSizeList has negative listSize {}", + fsl.listSize() + ), + )); + } + let children = field.children().ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidData, + "Arrow IPC FixedSizeList field missing children", + ) + })?; + if children.len() != 1 { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!( + "Arrow IPC FixedSizeList must have exactly 1 child, found {}", + children.len() + ), + )); + } + validate_ipc_field(children.get(0), is_big_endian, depth + 1) + } + arrow_ipc::Type::Struct_ => { + if let Some(children) = field.children() { + for i in 0..children.len() { + validate_ipc_field(children.get(i), is_big_endian, depth + 1)?; + } + } + Ok(()) + } + arrow_ipc::Type::RunEndEncoded => { + let children = field.children().ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidData, + "Arrow IPC RunEndEncoded field missing children", + ) + })?; + if children.len() != 2 { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!( + "Arrow IPC RunEndEncoded must have exactly 2 children, found {}", + children.len() + ), + )); + } + validate_ipc_field(children.get(0), is_big_endian, depth + 1)?; + validate_ipc_field(children.get(1), is_big_endian, depth + 1) + } + arrow_ipc::Type::Map => { + if field.type_as_map().is_none() { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "Arrow IPC Map field missing metadata", + )); + } + let children = field.children().ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidData, + "Arrow IPC Map field missing children", + ) + })?; + if children.len() != 1 { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!( + "Arrow IPC Map must have exactly 1 child, found {}", + children.len() + ), + )); + } + validate_ipc_field(children.get(0), is_big_endian, depth + 1) + } + arrow_ipc::Type::Union => { + let union = field.type_as_union().ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidData, + "Arrow IPC Union field missing metadata", + ) + })?; + if !matches!( + union.mode(), + arrow_ipc::UnionMode::Dense | arrow_ipc::UnionMode::Sparse + ) { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("Unsupported Arrow IPC Union mode {:?}", union.mode()), + )); + } + let child_count = field.children().map_or(0, |children| children.len()); + if let Some(children) = field.children() { + for i in 0..children.len() { + validate_ipc_field(children.get(i), is_big_endian, depth + 1)?; + } + } + match union.typeIds() { + None => { + if child_count > 128 { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!( + "Arrow IPC Union has {child_count} children, exceeding max 128" + ), + )); + } + } + Some(ids) => { + if ids.len() != child_count { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!( + "Arrow IPC Union typeIds length {} != children length {child_count}", + ids.len() + ), + )); + } + let mut seen = 0u128; + for raw_id in ids.iter() { + let Ok(type_id) = i8::try_from(raw_id) else { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("Arrow IPC Union typeId {raw_id} out of i8 range"), + )); + }; + if type_id < 0 { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("Arrow IPC Union typeId {type_id} must be non-negative"), + )); + } + let mask = 1u128 << (type_id as u32); + if seen & mask != 0 { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("Duplicate Arrow IPC Union typeId {type_id}"), + )); + } + seen |= mask; + } + } + } + Ok(()) + } + other => Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("Unsupported Arrow IPC field type {other:?}"), + )), + } +} + +fn validate_sorted_unique_indices( + indices: &[usize], + num_fields: usize, + label: &str, +) -> io::Result<()> { + for (pos, &idx) in indices.iter().enumerate() { + if idx >= num_fields { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + format!("{label}[{pos}] = {idx} out of bounds for schema with {num_fields} fields"), + )); + } + if pos > 0 && indices[pos - 1] >= idx { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + format!("{label} must be strictly sorted and unique"), + )); + } + } + Ok(()) +} + +/// Computes `extra_indices = output_indices \ filter_indices` and the ordered +/// stitch plan mapping each output column to either Phase 1 (`Filter`) or +/// Phase 2 (`Extra`). Both input slices must be strictly sorted. +fn build_stitch_plan( + filter_indices: &[usize], + output_indices: &[usize], +) -> (Vec, Vec) { + let mut extra_indices = Vec::with_capacity(output_indices.len()); + let mut stitch_plan = Vec::with_capacity(output_indices.len()); + let mut filter_pos = 0usize; + + for &out_col in output_indices { + while filter_pos < filter_indices.len() && filter_indices[filter_pos] < out_col { + filter_pos += 1; + } + if filter_pos < filter_indices.len() && filter_indices[filter_pos] == out_col { + stitch_plan.push(ColumnSource::Filter(filter_pos)); + } else { + let extra_pos = extra_indices.len(); + extra_indices.push(out_col); + stitch_plan.push(ColumnSource::Extra(extra_pos)); + } + } + + (extra_indices, stitch_plan) +} + +/// Pre-validates a FlatBuffer `RecordBatch` header's field-node descriptors, +/// buffer bounds against `body_len`, and variadic/layout counts against +/// `schema` BEFORE calling `arrow_ipc::reader::read_record_batch`. +/// +/// Any descriptor or layout violation fails closed with +/// `io::ErrorKind::InvalidData` instead of panicking inside Arrow IPC decoding. +pub(crate) fn pre_validate_record_batch( + schema: &Schema, + rb: arrow_ipc::RecordBatch<'_>, + version: MetadataVersion, + body_len: usize, +) -> io::Result<()> { + if usize::try_from(rb.length()).is_err() { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("Invalid Arrow IPC record batch row count {}", rb.length()), + )); + } + let nodes = rb.nodes().ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidData, + "Unable to get field nodes from IPC RecordBatch", + ) + })?; + let buffers = rb.buffers().ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidData, + "Unable to get buffers from IPC RecordBatch", + ) + })?; + + for (idx, node) in nodes.iter().enumerate() { + let length = node.length(); + let null_count = node.null_count(); + if length < 0 || usize::try_from(length).is_err() { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("IPC RecordBatch FieldNode[{idx}] has invalid length {length}"), + )); + } + if null_count < 0 || usize::try_from(null_count).is_err() { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("IPC RecordBatch FieldNode[{idx}] has invalid null_count {null_count}"), + )); + } + if null_count > length { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!( + "IPC RecordBatch FieldNode[{idx}] has null_count {null_count} > length {length}" + ), + )); + } + } + + let body_len_u64 = body_len as u64; + for (idx, buf) in buffers.iter().enumerate() { + let offset = buf.offset(); + let length = buf.length(); + if offset < 0 || usize::try_from(offset).is_err() { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("IPC RecordBatch Buffer[{idx}] has invalid offset {offset}"), + )); + } + if length < 0 || usize::try_from(length).is_err() { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("IPC RecordBatch Buffer[{idx}] has invalid length {length}"), + )); + } + let end = (offset as u64).checked_add(length as u64).ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidData, + format!("IPC RecordBatch Buffer[{idx}] offset + length overflow"), + ) + })?; + if end > body_len_u64 { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!( + "IPC RecordBatch Buffer[{idx}] range {offset}..{end} exceeds body length {body_len}" + ), + )); + } + } + + let mut validator = RecordBatchLayoutValidator { + rb, + version, + uncompressed: rb.compression().is_none(), + variadic_counts: rb.variadicBufferCounts().into_iter().flatten().collect(), + node_idx: 0, + buffer_idx: 0, + }; + for field in schema.fields() { + validator.validate_field(field)?; + } + if !validator.variadic_counts.is_empty() { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "Unexpected extra variadicBufferCounts entries in IPC RecordBatch", + )); + } + Ok(()) +} + +struct RecordBatchLayoutValidator<'a> { + rb: arrow_ipc::RecordBatch<'a>, + version: MetadataVersion, + uncompressed: bool, + variadic_counts: VecDeque, + node_idx: usize, + buffer_idx: usize, +} + +impl<'a> RecordBatchLayoutValidator<'a> { + fn take_node(&mut self) -> io::Result<(usize, usize)> { + let nodes = self.rb.nodes().ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidData, + "Unable to get field nodes from IPC RecordBatch", + ) + })?; + let pos = self.node_idx; + if pos >= nodes.len() { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!( + "IPC RecordBatch has {} field nodes, expected at least {}", + nodes.len(), + pos + 1 + ), + )); + } + self.node_idx = pos + .checked_add(1) + .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "IPC node count overflow"))?; + let node = nodes.get(pos); + Ok((node.length() as usize, node.null_count() as usize)) + } + + fn take_buffers(&mut self, count: usize) -> io::Result { + let buffers = self.rb.buffers().ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidData, + "Unable to get buffers from IPC RecordBatch", + ) + })?; + let start = self.buffer_idx; + let end = start.checked_add(count).ok_or_else(|| { + io::Error::new(io::ErrorKind::InvalidData, "IPC buffer count overflow") + })?; + if end > buffers.len() { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!( + "IPC RecordBatch has {} buffers, expected at least {end}", + buffers.len() + ), + )); + } + self.buffer_idx = end; + Ok(start) + } + + fn buffer_len(&self, idx: usize) -> usize { + self.rb + .buffers() + .expect("buffers validated in pre_validate_record_batch") + .get(idx) + .length() as usize + } + + fn validate_field(&mut self, field: &Field) -> io::Result<()> { + let (node_len, node_nulls) = self.take_node()?; + + match field.data_type() { + DataType::Utf8 | DataType::Binary | DataType::LargeBinary | DataType::LargeUtf8 => { + self.take_buffers(3)?; + } + DataType::Utf8View | DataType::BinaryView => { + let count = self.variadic_counts.pop_front().ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidData, + format!("Missing variadic count for {} column", field.data_type()), + ) + })?; + let count = usize::try_from(count).map_err(|_| { + io::Error::new( + io::ErrorKind::InvalidData, + format!( + "Invalid negative variadic count {count} for {} column", + field.data_type() + ), + ) + })?; + let total = count.checked_add(2).ok_or_else(|| { + io::Error::new(io::ErrorKind::InvalidData, "IPC variadic count overflow") + })?; + self.take_buffers(total)?; + } + DataType::FixedSizeBinary(_) | DataType::Dictionary(_, _) => { + self.take_buffers(2)?; + } + DataType::List(list_field) + | DataType::LargeList(list_field) + | DataType::Map(list_field, _) => { + self.take_buffers(2)?; + self.validate_field(list_field)?; + } + DataType::ListView(list_field) | DataType::LargeListView(list_field) => { + self.take_buffers(3)?; + self.validate_field(list_field)?; + } + DataType::FixedSizeList(list_field, _) => { + self.take_buffers(1)?; + self.validate_field(list_field)?; + } + DataType::Struct(struct_fields) => { + let null_buf_idx = self.take_buffers(1)?; + if self.uncompressed && node_nulls > 0 { + let needed_bytes = node_len.div_ceil(8); + let actual_bytes = self.buffer_len(null_buf_idx); + if actual_bytes < needed_bytes { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!( + "IPC Struct validity buffer length {actual_bytes} < required {needed_bytes} bytes" + ), + )); + } + } + for struct_field in struct_fields { + self.validate_field(struct_field)?; + } + } + DataType::RunEndEncoded(run_ends_field, values_field) => { + self.validate_field(run_ends_field)?; + self.validate_field(values_field)?; + } + DataType::Union(fields, mode) => { + if self.version < MetadataVersion::V5 { + self.take_buffers(1)?; + } + let type_ids_buf_idx = self.take_buffers(1)?; + if self.uncompressed && self.buffer_len(type_ids_buf_idx) < node_len { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!( + "IPC Union type_ids buffer length {} < required {node_len}", + self.buffer_len(type_ids_buf_idx) + ), + )); + } + if matches!(mode, UnionMode::Dense) { + let offsets_buf_idx = self.take_buffers(1)?; + let needed = node_len.checked_mul(4).ok_or_else(|| { + io::Error::new(io::ErrorKind::InvalidData, "IPC Union offsets overflow") + })?; + if self.uncompressed && self.buffer_len(offsets_buf_idx) < needed { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!( + "IPC Dense Union offsets buffer length {} < required {needed}", + self.buffer_len(offsets_buf_idx) + ), + )); + } + } + for (_, child_field) in fields.iter() { + self.validate_field(child_field)?; + } + } + DataType::Null => {} + DataType::Boolean + | DataType::Int8 + | DataType::Int16 + | DataType::Int32 + | DataType::Int64 + | DataType::UInt8 + | DataType::UInt16 + | DataType::UInt32 + | DataType::UInt64 + | DataType::Float16 + | DataType::Float32 + | DataType::Float64 + | DataType::Timestamp(_, _) + | DataType::Date32 + | DataType::Date64 + | DataType::Time32(_) + | DataType::Time64(_) + | DataType::Duration(_) + | DataType::Interval(_) + | DataType::Decimal32(_, _) + | DataType::Decimal64(_, _) + | DataType::Decimal128(_, _) + | DataType::Decimal256(_, _) => { + self.take_buffers(2)?; + } + } + Ok(()) + } +} + +/// Builds an Arrow stream reader over exactly the IPC messages of +/// `[0, expected_len)` of `reader`, which must present no more than that +/// prefix (see `disk_source::BoundedFile`). With `start > 0`, only the +/// schema message and the messages from `start` on are read; `start` must be +/// a message boundary. +/// +/// The complete messages must end exactly at `expected_len`: the prefix is an +/// acknowledged length recorded on a message boundary, so anything shorter is +/// lost data, and the reader fails instead of silently returning fewer rows. +/// With `reverse`, record batches are returned newest first, unless the +/// stream has dictionary messages, whose order a reverse read would break. +pub(crate) fn exact_prefix_reader( + mut reader: R, + start: u64, + expected_len: u64, + reverse: bool, +) -> Result>>, io::Error> { + let mut plan = plan_exact_prefix(&mut reader, start, expected_len)?; + if reverse && !plan.has_dictionaries { + plan.messages.reverse(); + } + let mut ranges = Vec::with_capacity(plan.messages.len() + 1); + ranges.push(plan.schema_range); + ranges.extend(plan.messages.into_iter().map(|m| (m.offset, m.size))); + stream_reader_for_ranges(reader, Arc::from(ranges), None, MESSAGE_READ_BUFFER_BYTES) +} + +/// Builds a forward Arrow stream reader over only complete IPC messages. +#[cfg(test)] +pub fn get_forward_reader( + mut reader: T, +) -> Result>>, io::Error> { + let messages = complete_messages(&mut reader)?; + let complete_len = messages + .last() + .map(|(_, offset, size)| offset + size) + .expect("complete_messages requires a schema and record batch"); + reader.rewind()?; + + StreamReader::try_new(BufReader::new(reader.take(complete_len as u64)), None).map_err(|e| { + io::Error::new( + io::ErrorKind::InvalidData, + format!("Invalid arrow stream: {e}"), + ) + }) +} + +/// Builds a reverse Arrow stream reader from complete IPC messages. +/// Preserves forward order when dictionary messages are present so batches do +/// not arrive before the dictionaries they reference. +pub fn get_reverse_reader( + reader: T, +) -> Result>>, io::Error> { + get_reverse_reader_with_buffer_capacity(reader, MESSAGE_READ_BUFFER_BYTES) +} + +fn get_reverse_reader_with_buffer_capacity( + mut reader: T, + buffer_bytes: usize, +) -> Result>>, io::Error> { + let mut messages = complete_messages(&mut reader)?; + + // Reverse everything leaving the first because it has schema message, + // unless dictionary messages require original IPC order. + if !messages + .iter() + .any(|(header, _, _)| *header == MessageHeader::DictionaryBatch) + { + messages[1..].reverse(); + } + let messages = messages + .into_iter() + .map(|(_, offset, size)| (offset as u64, size)) + .collect(); + + // reset reader + reader.rewind()?; + + StreamReader::try_new( + BufReader::with_capacity(buffer_bytes, MessageRangeReader::new(reader, messages)), + None, + ) + .map_err(|e| { + io::Error::new( + io::ErrorKind::InvalidData, + format!("Invalid arrow stream: {e}"), + ) + }) +} + +/// Hard upper bound on a single IPC FlatBuffer metadata payload to prevent +/// corrupt length fields from triggering multi-GiB allocations. +const MAX_IPC_METADATA_BYTES: usize = 64 * 1024 * 1024; + +/// Returns the IPC message type and its padded byte length. +#[cfg(test)] +fn find_limit_and_type( + reader: &mut (impl Read + Seek), + remaining_bytes: u64, +) -> Result, io::Error> { + scan_message_with_rows(reader, remaining_bytes, |reader, by| { + reader.seek(SeekFrom::Current(by)).map(drop) + }) + .map(|opt| opt.map(|(header, size, _)| (header, size))) +} + +/// Reads one IPC message header and skips its body with `skip`. Returns the +/// message type, its padded byte length, and (for `RecordBatch`) its declared +/// row count. +fn scan_message_with_rows( + reader: &mut R, + remaining_bytes: u64, + skip: impl FnOnce(&mut R, i64) -> io::Result<()>, +) -> Result)>, io::Error> { + let mut size = 0; + let marker = reader.read_u32::()?; + size += 4; + + if marker != 0xFFFFFFFF { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "Invalid Continuation Marker", + )); + } + + let metadata_size = reader.read_u32::()? as usize; + size += 4; + + if metadata_size == 0x00000000 { + return Ok(None); + } + + if metadata_size > MAX_IPC_METADATA_BYTES { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("Arrow IPC metadata length {metadata_size} exceeds maximum"), + )); + } + if (metadata_size as u64) > remaining_bytes.saturating_sub(size as u64) { + return Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + "Arrow IPC metadata truncated before end of file", + )); + } + + let mut message = vec![0u8; metadata_size]; + reader.read_exact(&mut message)?; + size += metadata_size; + + let message = root_as_message(&message).map_err(|err| { + io::Error::new( + io::ErrorKind::InvalidData, + format!("Invalid Arrow IPC message: {err}"), + ) + })?; + let header = message.header_type(); + if header == MessageHeader::Schema { + let ipc_schema = message.header_as_schema().ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidData, + "Invalid Arrow IPC schema header", + ) + })?; + validate_ipc_schema(ipc_schema)?; + } + let rows = if header == MessageHeader::RecordBatch { + let rb = message.header_as_record_batch().ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidData, + "Invalid Arrow IPC record batch header", + ) + })?; + let count = usize::try_from(rb.length()).map_err(|_| { + io::Error::new( + io::ErrorKind::InvalidData, + "Invalid Arrow IPC record batch row count", + ) + })?; + Some(count) + } else { + None + }; + let message_size = usize::try_from(message.bodyLength()) + .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "Invalid Arrow IPC body length"))?; + size = size + .checked_add(message_size) + .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "Arrow message size overflow"))?; + + let padding = (8 - (size % 8)) % 8; + let seek_by = message_size + .checked_add(padding) + .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "Arrow message size overflow"))?; + skip(reader, seek_by as i64)?; + size = size + .checked_add(padding) + .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "Arrow message size overflow"))?; + + Ok(Some((header, size, rows))) +} + +#[cfg(test)] +mod tests { + mod track_e { + include!("reader/track_e.rs"); + } + + use std::{ + collections::VecDeque, + io::{self, Cursor, Read}, + path::Path, + sync::Arc, + }; + + use arrow_array::{ + Array, DictionaryArray, Float64Array, Int32Array, Int64Array, RecordBatch, StringArray, + cast::AsArray, + types::{Int32Type, Int64Type}, + }; + use arrow_ipc::{ + MessageHeader, + writer::{ + DictionaryTracker, IpcDataGenerator, IpcWriteContext, IpcWriteOptions, StreamWriter, + write_message, + }, + }; + use arrow_schema::{DataType, Field, Schema}; + use chrono::Utc; + use temp_dir::TempDir; + + use crate::{ + OBJECT_STORE_DATA_GRANULARITY, + parseable::staging::{ + reader::{MergedForwardRecordReader, MergedReverseRecordReader, MessageRangeReader}, + writer::DiskWriter, + }, + utils::time::TimeRange, + }; + + use super::{find_limit_and_type, get_forward_reader, get_reverse_reader}; + + fn rb(rows: usize) -> RecordBatch { + let array1: Arc = Arc::new(Int64Array::from_iter(0..(rows as i64))); + let array2: Arc = Arc::new(Float64Array::from_iter((0..rows).map(|x| x as f64))); + let array3: Arc = Arc::new(StringArray::from_iter( + (0..rows).map(|x| Some(format!("str {}", x))), + )); + + RecordBatch::try_from_iter_with_nullable([ + ("a", array1, true), + ("b", array2, true), + ("c", array3, true), + ]) + .unwrap() + } + + fn write_mem(rbs: &[RecordBatch]) -> Vec { + let buf = Vec::new(); + let mut writer = StreamWriter::try_new(buf, &rbs[0].schema()).unwrap(); + + for rb in rbs { + writer.write(rb).unwrap() + } + + writer.into_inner().unwrap() + } + + fn truncate_last_record_batch(bytes: &mut Vec) { + let mut cursor = Cursor::new(bytes.as_slice()); + let mut offset = 0usize; + let mut last_record_batch = None; + let total = bytes.len() as u64; + while let Some((header, size)) = + find_limit_and_type(&mut cursor, total.saturating_sub(offset as u64)).unwrap() + { + if header == MessageHeader::RecordBatch { + last_record_batch = Some((offset, size)); + } + offset += size; + } + + let (offset, size) = last_record_batch.expect("record batch message"); + bytes.truncate(offset + size / 2); + } + + #[test] + fn mixed_compression_includes_dictionary_message_metadata() { + use arrow_ipc::{CompressionType, reader::StreamReader}; + let raw = IpcWriteOptions::default(); + let compressed = IpcWriteOptions::default() + .try_with_compression(Some(CompressionType::LZ4_FRAME)) + .unwrap(); + let batches = [1, 1000, 10] + .into_iter() + .enumerate() + .map(|(i, n)| { + let value = if i % 2 == 0 { "alpha" } else { "beta" }; + RecordBatch::try_from_iter([( + "dict", + Arc::new(DictionaryArray::::from_iter( + (0..n).map(|_| value), + )) as Arc, + )]) + .unwrap() + }) + .collect::>(); + let mut tracker = DictionaryTracker::new(false); + let generator = IpcDataGenerator::default(); + let mut context = IpcWriteContext::default(); + let mut bytes = Vec::new(); + let schema = generator.schema_to_bytes_with_dictionary_tracker( + &batches[0].schema(), + &mut tracker, + &compressed, + ); + write_message(&mut bytes, schema, &compressed).unwrap(); + for (i, batch) in batches.iter().enumerate() { + let options = if i % 2 == 0 { &raw } else { &compressed }; + let (dicts, message) = generator + .encode(batch, &mut tracker, options, &mut context) + .unwrap(); + assert_eq!(dicts.len(), 1); + for dict in dicts { + write_message(&mut bytes, dict, options).unwrap(); + } + write_message(&mut bytes, message, options).unwrap(); + } + bytes.extend_from_slice(&[255, 255, 255, 255, 0, 0, 0, 0]); + assert_eq!( + StreamReader::try_new(Cursor::new(&bytes), None) + .unwrap() + .collect::, _>>() + .unwrap(), + batches + ); + assert_eq!( + get_forward_reader(Cursor::new(&bytes)) + .unwrap() + .collect::, _>>() + .unwrap(), + batches + ); + // Reverse staging readers preserve forward order when dictionary + // messages are present so valid dictionary-encoded files decode cleanly. + assert_eq!( + get_reverse_reader(Cursor::new(&bytes)) + .unwrap() + .collect::, _>>() + .unwrap(), + batches + ); + } + + /// Counts the calls that reach the underlying file. + struct CountingReader { + inner: R, + reads: usize, + seeks: usize, + } + + impl Read for CountingReader { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + self.reads += 1; + self.inner.read(buf) + } + } + + impl io::Seek for CountingReader { + fn seek(&mut self, pos: io::SeekFrom) -> io::Result { + self.seeks += 1; + self.inner.seek(pos) + } + } + + /// The message boundaries found by reading every header unbuffered. + fn scan_unbuffered(bytes: &[u8]) -> Vec<(MessageHeader, usize, usize)> { + let mut cursor = Cursor::new(bytes); + let mut offset = 0usize; + let mut messages = Vec::new(); + let total = bytes.len() as u64; + while let Ok(Some((header, size))) = + find_limit_and_type(&mut cursor, total.saturating_sub(offset as u64)) + { + if (offset + size) as u64 > total { + break; + } + messages.push((header, offset, size)); + offset += size; + } + messages + } + + #[test] + fn message_scan_reads_neighbouring_headers_from_one_buffer() { + // Many small messages: their headers come out of a few buffer fills + // instead of three reads and a seek each. + let small = write_mem(&(0..500).map(|_| rb(2)).collect::>()); + let mut reader = CountingReader { + inner: Cursor::new(small.as_slice()), + reads: 0, + seeks: 0, + }; + let messages = super::complete_messages(&mut reader).unwrap(); + assert_eq!(messages.len(), 501); + assert_eq!(messages, scan_unbuffered(&small)); + // A buffer is refilled, after one seek, only when a message body runs + // past its end: a few times for the file, not for each message. + let fills = small.len().div_ceil(super::MESSAGE_SCAN_BUFFER_BYTES); + assert!(fills < 20, "{fills} fills"); + assert!(reader.reads <= 2 * fills + 1, "{} reads", reader.reads); + // Two more for the length probe and the rewind. + assert!(reader.seeks <= 2 * fills + 2, "{} seeks", reader.seeks); + + // Messages larger than the buffer: one seek and one fill per message, + // and the same boundaries. + let large = write_mem(&(0..6).map(|_| rb(20_000)).collect::>()); + assert!(large.len() / 6 > 2 * super::MESSAGE_SCAN_BUFFER_BYTES); + let mut reader = CountingReader { + inner: Cursor::new(large.as_slice()), + reads: 0, + seeks: 0, + }; + let messages = super::complete_messages(&mut reader).unwrap(); + assert_eq!(messages.len(), 7); + assert_eq!(messages, scan_unbuffered(&large)); + assert!(reader.reads <= 9, "{} reads", reader.reads); + assert!(reader.seeks <= 9, "{} seeks", reader.seeks); + + // The scan leaves the reader wherever its buffer ended; the readers + // built on it still decode every batch, newest first. + let batches = get_reverse_reader(Cursor::new(large)) + .unwrap() + .collect::, _>>() + .unwrap(); + assert_eq!(batches.len(), 6); + assert!(batches.iter().all(|batch| *batch == rb(20_000))); + } + + #[test] + fn buffered_message_scan_stops_at_truncated_tail_like_unbuffered() { + let complete = write_mem(&[rb(3), rb(700), rb(5)]); + let boundaries = scan_unbuffered(&complete); + assert_eq!(boundaries.len(), 4); + // Cut the stream at every length inside the last two messages. + let (_, second_offset, _) = boundaries[2]; + for len in (second_offset..complete.len()).step_by(37) { + let truncated = &complete[..len]; + let expected = scan_unbuffered(truncated); + let messages = super::complete_messages(&mut Cursor::new(truncated)).unwrap(); + assert_eq!(messages, expected, "length {len}"); + } + } + + #[test] + fn reverse_reader_recovers_complete_batches_before_truncated_tail() { + let mut bytes = write_mem(&[rb(2), rb(3)]); + truncate_last_record_batch(&mut bytes); + + let reader = get_reverse_reader(Cursor::new(bytes)).unwrap(); + let batches = reader.collect::, _>>().unwrap(); + + assert_eq!(batches.len(), 1); + assert_eq!(batches[0].num_rows(), 2); + } + + #[test] + fn forward_reader_recovers_complete_batches_before_truncated_tail() { + let mut bytes = write_mem(&[rb(2), rb(3)]); + truncate_last_record_batch(&mut bytes); + + let reader = get_forward_reader(Cursor::new(bytes)).unwrap(); + let batches = reader.collect::, _>>().unwrap(); + + assert_eq!(batches.len(), 1); + assert_eq!(batches[0].num_rows(), 2); + } + + #[test] + fn forward_reader_preserves_batch_order() { + let bytes = write_mem(&[rb(1), rb(2), rb(3)]); + + let reader = get_forward_reader(Cursor::new(bytes)).unwrap(); + let rows = reader + .map(|batch| batch.unwrap().num_rows()) + .collect::>(); + + assert_eq!(rows, vec![1, 2, 3]); + } + + #[test] + fn reverse_reader_rejects_stream_without_complete_batch() { + let mut bytes = write_mem(&[rb(2)]); + truncate_last_record_batch(&mut bytes); + + let err = get_reverse_reader(Cursor::new(bytes)).unwrap_err(); + assert!(err.to_string().contains("no complete record batch")); + } + + #[test] + fn reverse_reader_accepts_complete_batches_without_eos() { + let mut bytes = write_mem(&[rb(2)]); + bytes.truncate(bytes.len() - 8); + + let reader = get_reverse_reader(Cursor::new(bytes)).unwrap(); + let batches = reader.collect::, _>>().unwrap(); + + assert_eq!(batches.len(), 1); + assert_eq!(batches[0].num_rows(), 2); + } + + #[test] + fn test_empty_row() { + let rb = rb(0); + let buf = write_mem(&[rb]); + let reader = Cursor::new(buf); + let mut reader = get_reverse_reader(reader).unwrap(); + let rb = reader.next().unwrap().unwrap(); + assert_eq!(rb.num_rows(), 0); + } + + #[test] + fn test_one_row() { + let rb = rb(1); + let buf = write_mem(&[rb]); + let reader = Cursor::new(buf); + let mut reader = get_reverse_reader(reader).unwrap(); + let rb = reader.next().unwrap().unwrap(); + assert_eq!(rb.num_rows(), 1); + } + + #[test] + fn test_multiple_row_multiple_rbs() { + let buf = write_mem(&[rb(1), rb(2), rb(3)]); + let reader = Cursor::new(buf); + let mut reader = get_reverse_reader(reader).unwrap(); + let rb = reader.next().unwrap().unwrap(); + assert_eq!(rb.num_rows(), 3); + let col1_val: Vec = rb + .column(0) + .as_primitive::() + .iter() + .flatten() + .collect(); + assert_eq!(col1_val, vec![0, 1, 2]); + + let rb = reader.next().unwrap().unwrap(); + assert_eq!(rb.num_rows(), 2); + + let rb = reader.next().unwrap().unwrap(); + assert_eq!(rb.num_rows(), 1); + } + + #[test] + fn manual_write() { + let error_on_replacement = true; + let options = IpcWriteOptions::default(); + let mut dictionary_tracker = DictionaryTracker::new(error_on_replacement); + let data_gen = IpcDataGenerator {}; + let mut compression_context = IpcWriteContext::default(); + + let mut buf = Vec::new(); + let rb1 = rb(1); + + let schema = data_gen.schema_to_bytes_with_dictionary_tracker( + &rb1.schema(), + &mut dictionary_tracker, + &options, + ); + write_message(&mut buf, schema, &options).unwrap(); + + for i in (1..=3).cycle().skip(1).take(10000) { + let (_, encoded_message) = data_gen + .encode( + &rb(i), + &mut dictionary_tracker, + &options, + &mut compression_context, + ) + .unwrap(); + write_message(&mut buf, encoded_message, &options).unwrap(); + } + + let schema = data_gen.schema_to_bytes_with_dictionary_tracker( + &rb1.schema(), + &mut dictionary_tracker, + &options, + ); + write_message(&mut buf, schema, &options).unwrap(); + + let buf = Cursor::new(buf); + let reader = get_reverse_reader(buf).unwrap().flatten(); + + let mut sum = 0; + for rb in reader { + sum += 1; + assert!(rb.num_rows() > 0); + } + + assert_eq!(sum, 10000); + } + + // Helper function to create test record batches + fn create_test_batches(schema: &Arc, count: usize) -> Vec { + let mut batches = Vec::with_capacity(count); + + for batch_num in 1..=count as i32 { + let id_array = Int32Array::from_iter(batch_num * 10..=batch_num * 10 + 1); + let name_array = StringArray::from(vec![ + format!("Name {batch_num}-1"), + format!("Name {batch_num}-2"), + ]); + + let batch = RecordBatch::try_new( + schema.clone(), + vec![Arc::new(id_array), Arc::new(name_array)], + ) + .expect("Failed to create test batch"); + + batches.push(batch); + } + + batches + } + + // Helper function to write batches to a file + fn write_test_batches( + path: &Path, + schema: &Arc, + batches: &[RecordBatch], + ) -> io::Result<()> { + let range = TimeRange::granularity_range(Utc::now(), OBJECT_STORE_DATA_GRANULARITY); + let mut writer = + DiskWriter::try_new(path, schema, range).expect("Failed to create StreamWriter"); + + for batch in batches { + writer.write(batch).expect("Failed to write batch"); + } + + Ok(()) + } + + /// Two sealed files giving one field incompatible types must be reported, + /// not panic the conversion that merges them. + #[test] + fn merged_schema_reports_incompatible_files() -> io::Result<()> { + let dir = TempDir::new().unwrap(); + let schema_of = |value: DataType| { + Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new("value", value, false), + ])) + }; + let numbers = schema_of(DataType::Int64); + let text = schema_of(DataType::Utf8); + let numbers_path = dir.path().join("numbers.data.arrows"); + let text_path = dir.path().join("text.data.arrows"); + write_test_batches( + &numbers_path, + &numbers, + &[RecordBatch::try_new( + numbers.clone(), + vec![ + Arc::new(Int32Array::from(vec![1])), + Arc::new(Int64Array::from(vec![10])), + ], + ) + .unwrap()], + )?; + write_test_batches( + &text_path, + &text, + &[RecordBatch::try_new( + text.clone(), + vec![ + Arc::new(Int32Array::from(vec![2])), + Arc::new(StringArray::from(vec!["ten"])), + ], + ) + .unwrap()], + )?; + let files = [numbers_path, text_path]; + let reverse = MergedReverseRecordReader::try_new(&files); + assert_eq!(reverse.readable_files.len(), 2); + assert!(reverse.merged_schema().is_err()); + let forward = MergedForwardRecordReader::try_new(&files); + assert_eq!(forward.readable_files.len(), 2); + assert!(forward.merged_schema().is_err()); + + // Each file alone still merges. + let alone = MergedReverseRecordReader::try_new(&files[..1]); + assert_eq!(alone.merged_schema().unwrap(), *numbers); + Ok(()) + } + + #[test] + fn test_message_range_reader() { + // Create a simple binary file in memory + let data = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; + let cursor = Cursor::new(data); + + // Define offset list: (offset, size) + let offsets = vec![(2, 3), (7, 2)]; // Read bytes 2-4 (3, 4, 5) and then 7-8 (8, 9) + + let mut reader = MessageRangeReader::new(cursor, offsets); + let mut buffer = [0u8; 10]; + + // First read should get bytes 3, 4, 5 + let read_bytes = reader.read(&mut buffer).unwrap(); + assert_eq!(read_bytes, 3); + assert_eq!(&buffer[..read_bytes], &[3, 4, 5]); + + // Second read should get bytes 8, 9 + let read_bytes = reader.read(&mut buffer).unwrap(); + assert_eq!(read_bytes, 2); + assert_eq!(&buffer[..read_bytes], &[8, 9]); + + // No more data + let read_bytes = reader.read(&mut buffer).unwrap(); + assert_eq!(read_bytes, 0); + } + + #[test] + fn test_merged_reverse_record_reader() -> io::Result<()> { + let dir = TempDir::new().unwrap(); + let file_path = dir.path().join("test.data.arrows"); + + // Create a schema + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new("name", DataType::Utf8, false), + ])); + + // Create test batches (3 batches) + let batches = create_test_batches(&schema, 3); + + // Write batches to file + write_test_batches(&file_path, &schema, &batches)?; + + // Now read them back in reverse order + let mut reader = + MergedReverseRecordReader::try_new(&[file_path.into()]).merged_iter(schema, None); + + // We should get batches in reverse order: 3, 2, 1 + // But first message should be schema, so we'll still read them in order + + // Read batch 3 + let batch = reader + .next() + .expect("Failed to read batch") + .expect("Invalid batch"); + assert_eq!(batch.num_rows(), 2); + let id_array = batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(id_array.value(0), 31); // affect of reverse on each recordbatch + assert_eq!(id_array.value(1), 30); + + // Read batch 2 + let batch = reader + .next() + .expect("Failed to read batch") + .expect("Invalid batch"); + assert_eq!(batch.num_rows(), 2); + let id_array = batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(id_array.value(0), 21); + assert_eq!(id_array.value(1), 20); + + // Read batch 1 + let batch = reader + .next() + .expect("Failed to read batch") + .expect("Invalid batch"); + assert_eq!(batch.num_rows(), 2); + let id_array = batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(id_array.value(0), 11); + assert_eq!(id_array.value(1), 10); + + // No more batches + assert!(reader.next().is_none()); + + Ok(()) + } + + #[test] fn forward_reader_lanes_preserve_original_batch_order() -> io::Result<()> { let dir = TempDir::new().unwrap(); - let file_path = dir.path().join("striped.data.arrows"); - let schema = Arc::new(Schema::new(vec![ - Field::new("id", DataType::Int32, false), - Field::new("name", DataType::Utf8, false), + let file_path = dir.path().join("striped.data.arrows"); + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new("name", DataType::Utf8, false), + ])); + write_test_batches(&file_path, &schema, &create_test_batches(&schema, 10))?; + + let plan = MergedForwardRecordReader::try_new(&[file_path]) + .into_file_plans() + .next() + .unwrap(); + let lanes = plan.open_lanes(4)?; + assert_eq!( + lanes + .iter() + .map(|lane| lane.record_batches) + .collect::>(), + vec![3, 3, 2, 2] + ); + + let mut batches_by_lane = lanes + .into_iter() + .map(|lane| lane.reader.collect::, _>>().unwrap()) + .collect::>(); + let first_ids = (0..10) + .map(|batch_index| { + let batch = batches_by_lane[batch_index % 4].pop_front().unwrap(); + batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .value(0) + }) + .collect::>(); + assert_eq!(first_ids, vec![10, 20, 30, 40, 50, 60, 70, 80, 90, 100]); + + Ok(()) + } + + #[test] + fn forward_reader_lanes_receive_dictionary_messages() -> io::Result<()> { + let dir = TempDir::new().unwrap(); + let file_path = dir.path().join("dictionary.data.arrows"); + let dictionary = DictionaryArray::::from_iter(["alpha", "beta"]); + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new("name", dictionary.data_type().clone(), false), + ])); + let batches = (0..8) + .map(|batch| { + RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(Int32Array::from(vec![batch * 2, batch * 2 + 1])), + Arc::new(DictionaryArray::::from_iter(["alpha", "beta"])), + ], + ) + .unwrap() + }) + .collect::>(); + write_test_batches(&file_path, &schema, &batches)?; + + let plan = MergedForwardRecordReader::try_new(&[file_path]) + .into_file_plans() + .next() + .unwrap(); + let decoded_batches = plan + .open_lanes(4)? + .into_iter() + .map(|lane| lane.reader.collect::, _>>().unwrap().len()) + .sum::(); + assert_eq!(decoded_batches, 8); + + Ok(()) + } + + #[test] + fn test_empty_range_list() { + // Test with empty range list + let data = vec![1, 2, 3, 4, 5]; + let cursor = Cursor::new(data); + + let mut reader = MessageRangeReader::new(cursor, vec![]); + let mut buffer = [0u8; 10]; + + // Should return 0 bytes read + let read_bytes = reader.read(&mut buffer).unwrap(); + assert_eq!(read_bytes, 0); + } + + #[test] + fn test_partial_reads() { + // Test reading with a buffer smaller than the section size + let data = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; + let cursor = Cursor::new(data); + + // One offset of 5 bytes + let offsets = vec![(2, 5)]; // Read bytes 2-6 (3, 4, 5, 6, 7) + + let mut reader = MessageRangeReader::new(cursor, offsets); + let mut buffer = [0u8; 3]; // Buffer smaller than the 5 bytes we want to read + + // First read should get first 3 bytes: 3, 4, 5 + let read_bytes = reader.read(&mut buffer).unwrap(); + assert_eq!(read_bytes, 3); + assert_eq!(&buffer[..read_bytes], &[3, 4, 5]); + + // Second read should get remaining 2 bytes: 6, 7 + let read_bytes = reader.read(&mut buffer).unwrap(); + assert_eq!(read_bytes, 2); + assert_eq!(&buffer[..read_bytes], &[6, 7]); + + // No more data + let read_bytes = reader.read(&mut buffer).unwrap(); + assert_eq!(read_bytes, 0); + } + + #[test] + fn testget_reverse_reader_single_message() -> io::Result<()> { + let dir = TempDir::new().unwrap(); + let file_path = dir.path().join("test_single.data.arrows"); + + // Create a schema + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); + + // Create a single batch + let batch = + RecordBatch::try_new(schema.clone(), vec![Arc::new(Int32Array::from(vec![42]))]) + .expect("Failed to create batch"); + + // Write batch to file + write_test_batches(&file_path, &schema, &[batch])?; + + let mut reader = + MergedReverseRecordReader::try_new(&[file_path.into()]).merged_iter(schema, None); + + // Should get the batch + let result_batch = reader + .next() + .expect("Failed to read batch") + .expect("Invalid batch"); + let id_array = result_batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(id_array.value(0), 42); + + // No more batches + assert!(reader.next().is_none()); + + Ok(()) + } + + #[test] + fn test_large_range_direct_read() { + // Test reading a large section directly into caller's buffer without an + // intermediate MessageRangeReader buffer. + let data = vec![1; 10000]; // 10KB of data + let cursor = Cursor::new(data); + + // One large offset (8KB) + let offsets = vec![(1000, 8000)]; + + let mut reader = MessageRangeReader::new(cursor, offsets); + let mut buffer = [0u8; 10000]; + + // Should read 8KB + let read_bytes = reader.read(&mut buffer).unwrap(); + assert_eq!(read_bytes, 8000); + + // All bytes should be 1 + for &byte in &buffer[..read_bytes] { + assert_eq!(byte, 1); + } + } + + #[test] + fn merged_reverse_reader_orders_multifile_timestamps_and_evolves_schema() -> io::Result<()> { + use arrow_array::TimestampMillisecondArray; + use arrow_schema::TimeUnit; + + let dir = TempDir::new().unwrap(); + let file_a = dir.path().join("a.data.arrows"); + let file_b = dir.path().join("b.data.arrows"); + + // File A has (p_timestamp, msg); File B evolves schema with extra nullable column `extra` + // and widens `code` from Int32 (missing in A) to Int64 (in target merged schema). + let schema_a = Arc::new(Schema::new(vec![ + Field::new( + crate::event::DEFAULT_TIMESTAMP_KEY, + DataType::Timestamp(TimeUnit::Millisecond, None), + false, + ), + Field::new("msg", DataType::Utf8, true), + ])); + let schema_b = Arc::new(Schema::new(vec![ + Field::new( + crate::event::DEFAULT_TIMESTAMP_KEY, + DataType::Timestamp(TimeUnit::Millisecond, None), + false, + ), + Field::new("msg", DataType::Utf8, true), + Field::new("extra", DataType::Int64, true), ])); - write_test_batches(&file_path, &schema, &create_test_batches(&schema, 10))?; - let plan = MergedForwardRecordReader::try_new(&[file_path]) - .into_file_plans() - .next() + // Interleaved batch timestamps: + // File A batches: [100, 101], [300, 301] + // File B batches: [200, 201], [400, 401] + let batches_a = vec![ + RecordBatch::try_new( + schema_a.clone(), + vec![ + Arc::new(TimestampMillisecondArray::from(vec![100, 101])), + Arc::new(StringArray::from(vec![Some("a1"), Some("a2")])), + ], + ) + .unwrap(), + RecordBatch::try_new( + schema_a.clone(), + vec![ + Arc::new(TimestampMillisecondArray::from(vec![300, 301])), + Arc::new(StringArray::from(vec![Some("a3"), Some("a4")])), + ], + ) + .unwrap(), + ]; + let batches_b = vec![ + RecordBatch::try_new( + schema_b.clone(), + vec![ + Arc::new(TimestampMillisecondArray::from(vec![200, 201])), + Arc::new(StringArray::from(vec![Some("b1"), Some("b2")])), + Arc::new(Int64Array::from(vec![Some(20), Some(21)])), + ], + ) + .unwrap(), + RecordBatch::try_new( + schema_b.clone(), + vec![ + Arc::new(TimestampMillisecondArray::from(vec![400, 401])), + Arc::new(StringArray::from(vec![Some("b3"), Some("b4")])), + Arc::new(Int64Array::from(vec![Some(40), Some(41)])), + ], + ) + .unwrap(), + ]; + + write_test_batches(&file_a, &schema_a, &batches_a)?; + write_test_batches(&file_b, &schema_b, &batches_b)?; + + let merged = MergedReverseRecordReader::try_new(&[file_a.clone(), file_b.clone()]); + assert_eq!(merged.readable_files, vec![file_a, file_b]); + assert!(merged.invalid_files.is_empty()); + + let target_schema = Arc::new(merged.merged_schema().unwrap()); + let results = merged + .merged_iter(target_schema.clone(), None) + .collect::, _>>() .unwrap(); - let lanes = plan.open_lanes(4)?; + assert_eq!(results.len(), 4); + + let all_timestamps: Vec = results + .iter() + .flat_map(|batch| { + assert_eq!(batch.schema(), target_schema); + batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .values() + .iter() + .copied() + }) + .collect(); + // Reverse batch order (400s, 300s, 200s, 100s) and reversed rows inside each batch + assert_eq!(all_timestamps, vec![401, 400, 301, 300, 201, 200, 101, 100]); + + // Verify schema evolution filled `extra` with nulls for File A batches and preserved values for File B + let extras: Vec> = results + .iter() + .flat_map(|batch| { + batch + .column_by_name("extra") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap() + .iter() + }) + .collect(); assert_eq!( - lanes + extras, + vec![ + Some(41), + Some(40), + None, + None, + Some(21), + Some(20), + None, + None + ] + ); + Ok(()) + } + + #[test] + fn merged_reverse_reader_attributes_invalid_and_truncated_files() -> io::Result<()> { + use arrow_array::TimestampMillisecondArray; + use arrow_schema::TimeUnit; + + let dir = TempDir::new().unwrap(); + let valid_path = dir.path().join("valid.data.arrows"); + let truncated_tail_path = dir.path().join("truncated_tail.data.arrows"); + let corrupt_path = dir.path().join("corrupt.data.arrows"); + + let schema = Arc::new(Schema::new(vec![ + Field::new( + crate::event::DEFAULT_TIMESTAMP_KEY, + DataType::Timestamp(TimeUnit::Millisecond, None), + false, + ), + Field::new("id", DataType::Int32, false), + ])); + let make_batch = |ts: i64, id: i32| { + RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(TimestampMillisecondArray::from(vec![ts])), + Arc::new(Int32Array::from(vec![id])), + ], + ) + .unwrap() + }; + + write_test_batches(&valid_path, &schema, &[make_batch(10, 1)])?; + + // A file with 2 batches whose second batch is crash-truncated recovers the first batch + let mut truncated_bytes = write_mem(&[make_batch(20, 2), make_batch(30, 3)]); + truncate_last_record_batch(&mut truncated_bytes); + std::fs::write(&truncated_tail_path, &truncated_bytes)?; + + // A file with garbage bytes is attributed to invalid_files + std::fs::write(&corrupt_path, b"not an arrow ipc stream")?; + + let merged = MergedReverseRecordReader::try_new(&[ + valid_path.clone(), + truncated_tail_path.clone(), + corrupt_path.clone(), + ]); + assert_eq!(merged.readable_files, vec![valid_path, truncated_tail_path]); + assert_eq!(merged.invalid_files, vec![corrupt_path]); + + let ids: Vec = merged + .merged_iter(schema, None) + .map(|batch| { + batch + .unwrap() + .column_by_name("id") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap() + .value(0) + }) + .collect(); + assert_eq!(ids, vec![2, 1]); + Ok(()) + } + + #[test] + fn merged_reverse_reader_handles_zero_row_batches_and_preserves_validation() -> io::Result<()> { + use arrow_array::TimestampMillisecondArray; + use arrow_schema::TimeUnit; + + let dir = TempDir::new().unwrap(); + let file_a = dir.path().join("a_empty.data.arrows"); + let file_b = dir.path().join("b_empty.data.arrows"); + + let schema = Arc::new(Schema::new(vec![ + Field::new( + crate::event::DEFAULT_TIMESTAMP_KEY, + DataType::Timestamp(TimeUnit::Millisecond, None), + false, + ), + Field::new( + "custom_ts", + DataType::Timestamp(TimeUnit::Millisecond, None), + false, + ), + Field::new("id", DataType::Int32, false), + ])); + let make_batch = |rows: &[(i64, i64, i32)]| { + RecordBatch::try_new( + Arc::clone(&schema), + vec![ + Arc::new(TimestampMillisecondArray::from_iter_values( + rows.iter().map(|&(ts, _, _)| ts), + )), + Arc::new(TimestampMillisecondArray::from_iter_values( + rows.iter().map(|&(_, cts, _)| cts), + )), + Arc::new(Int32Array::from_iter_values( + rows.iter().map(|&(_, _, id)| id), + )), + ], + ) + .unwrap() + }; + + // Interleave 0-row batches at start, middle, and end across two files so + // kmerge_by compares empty batches against both empty and non-empty batches. + write_test_batches( + &file_a, + &schema, + &[ + make_batch(&[(100, 1000, 1), (101, 1001, 2)]), + make_batch(&[]), + make_batch(&[(300, 3000, 5), (301, 3001, 6)]), + ], + )?; + write_test_batches( + &file_b, + &schema, + &[ + make_batch(&[]), + make_batch(&[(200, 2000, 3), (201, 2001, 4)]), + make_batch(&[]), + ], + )?; + + for time_partition in [None, Some("custom_ts".to_string())] { + let merged = MergedReverseRecordReader::try_new(&[file_a.clone(), file_b.clone()]); + let batches = merged + .merged_iter(Arc::clone(&schema), time_partition) + .collect::, _>>() + .unwrap(); + let timestamps: Vec = batches .iter() - .map(|lane| lane.record_batches) - .collect::>(), - vec![3, 3, 2, 2] + .flat_map(|batch| { + batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .values() + .iter() + .copied() + }) + .collect(); + assert_eq!(timestamps, vec![301, 300, 201, 200, 101, 100]); + } + + // Schema validation is preserved even when a file starts with a 0-row batch. + let incompatible_schema = Arc::new(Schema::new(vec![ + Field::new( + crate::event::DEFAULT_TIMESTAMP_KEY, + DataType::Timestamp(TimeUnit::Millisecond, None), + false, + ), + Field::new( + "custom_ts", + DataType::Timestamp(TimeUnit::Millisecond, None), + false, + ), + Field::new("id", DataType::Utf8, false), + ])); + let merged = MergedReverseRecordReader::try_new(&[file_a, file_b]); + let results: Vec<_> = merged.merged_iter(incompatible_schema, None).collect(); + assert!( + results.iter().any(Result::is_err), + "incompatible schema must still error on streams containing 0-row batches" ); - let mut batches_by_lane = lanes - .into_iter() - .map(|lane| lane.reader.collect::, _>>().unwrap()) - .collect::>(); - let first_ids = (0..10) - .map(|batch_index| { - let batch = batches_by_lane[batch_index % 4].pop_front().unwrap(); - batch - .column(0) - .as_any() - .downcast_ref::() - .unwrap() - .value(0) - }) - .collect::>(); - assert_eq!(first_ids, vec![10, 20, 30, 40, 50, 60, 70, 80, 90, 100]); - Ok(()) } - #[test] - fn forward_reader_lanes_receive_dictionary_messages() -> io::Result<()> { - let dir = TempDir::new().unwrap(); - let file_path = dir.path().join("dictionary.data.arrows"); - let dictionary = DictionaryArray::::from_iter(["alpha", "beta"]); - let schema = Arc::new(Schema::new(vec![ - Field::new("id", DataType::Int32, false), - Field::new("name", dictionary.data_type().clone(), false), - ])); - let batches = (0..8) - .map(|batch| { - RecordBatch::try_new( - schema.clone(), - vec![ - Arc::new(Int32Array::from(vec![batch * 2, batch * 2 + 1])), - Arc::new(DictionaryArray::::from_iter(["alpha", "beta"])), - ], - ) - .unwrap() - }) - .collect::>(); - write_test_batches(&file_path, &schema, &batches)?; + mod two_phase_tests { + use std::collections::HashMap; + use std::io::{self, Cursor}; + use std::sync::{ + Arc, + atomic::{AtomicBool, AtomicUsize, Ordering}, + }; - let plan = MergedForwardRecordReader::try_new(&[file_path]) - .into_file_plans() - .next() - .unwrap(); - let decoded_batches = plan - .open_lanes(4)? - .into_iter() - .map(|lane| lane.reader.collect::, _>>().unwrap().len()) - .sum::(); - assert_eq!(decoded_batches, 8); + use arrow_array::{ + Array, ArrayRef, BinaryArray, BooleanArray, Float64Array, Int64Array, LargeStringArray, + ListArray, RecordBatch, StringArray, StructArray, TimestampMillisecondArray, + builder::{Int32Builder, ListBuilder}, + cast::AsArray, + types::Int64Type, + }; + use arrow_ipc::{ + CompressionType, MetadataVersion, root_as_message, + writer::{IpcWriteOptions, StreamWriter}, + }; + use arrow_schema::{DataType, Field, Fields, Schema, TimeUnit}; + use arrow_select::filter::filter_record_batch; + + use super::super::{ + DEFAULT_ADAPTIVE_FALLBACK_CONSECUTIVE_MATCHES, MESSAGE_READ_BUFFER_BYTES, + STAGING_TWO_PHASE_MAX_MESSAGE_BYTES, STAGING_TWO_PHASE_SHARED_BUDGET_BYTES, + SharedByteBudget, TwoPhaseFallbackReason, TwoPhaseReadError, TwoPhaseStep, + plan_exact_prefix, staging_two_phase_shared_budget_in_use, stream_reader_for_ranges, + two_phase_filtered_reader, + }; - Ok(()) - } + fn wide_schema_with_metadata() -> Arc { + let mut schema_meta = HashMap::new(); + schema_meta.insert("stream".to_string(), "wide_test".to_string()); - #[test] - fn test_empty_range_list() { - // Test with empty range list - let data = vec![1, 2, 3, 4, 5]; - let cursor = Cursor::new(data); + let mut level_meta = HashMap::new(); + level_meta.insert("indexed".to_string(), "true".to_string()); - let mut reader = MessageRangeReader::new(cursor, vec![]); - let mut buffer = [0u8; 10]; + let struct_fields = Fields::from(vec![ + Field::new("k", DataType::Utf8, true), + Field::new("v", DataType::Int64, true), + ]); - // Should return 0 bytes read - let read_bytes = reader.read(&mut buffer).unwrap(); - assert_eq!(read_bytes, 0); - } + Arc::new(Schema::new_with_metadata( + vec![ + Field::new( + "ts", + DataType::Timestamp(TimeUnit::Millisecond, None), + false, + ), + Field::new("id", DataType::Int64, false), + Field::new("level", DataType::Utf8, true).with_metadata(level_meta), + Field::new("score", DataType::Float64, true), + Field::new("flag", DataType::Boolean, true), + Field::new("payload_bin", DataType::Binary, true), + Field::new("payload_large", DataType::LargeUtf8, true), + Field::new( + "tags", + DataType::List(Arc::new(Field::new("item", DataType::Int32, true))), + true, + ), + Field::new("meta", DataType::Struct(struct_fields), true), + ], + schema_meta, + )) + } - #[test] - fn test_partial_reads() { - // Test reading with a buffer smaller than the section size - let data = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; - let cursor = Cursor::new(data); + fn make_wide_batch(schema: &Arc, start_id: i64, rows: usize) -> RecordBatch { + let ts = TimestampMillisecondArray::from_iter_values( + (0..rows).map(|i| 1_700_000_000_000 + start_id + i as i64), + ); + let id = Int64Array::from_iter_values((0..rows).map(|i| start_id + i as i64)); + let level = + StringArray::from_iter((0..rows).map(|i| match (start_id as usize + i) % 5 { + 0 => Some("error"), + 1 => Some("warn"), + 2 => Some("info"), + 3 => Some("debug"), + _ => None, + })); + let score = Float64Array::from_iter( + (0..rows).map(|i| (i % 7 != 0).then_some((start_id as f64) + (i as f64) * 0.25)), + ); + let flag = BooleanArray::from_iter((0..rows).map(|i| match i % 3 { + 0 => Some(true), + 1 => Some(false), + _ => None, + })); + let payload_bin = BinaryArray::from_iter((0..rows).map(|i| { + Some(format!("binary-payload-{start_id}-{i}-{}", "x".repeat(64)).into_bytes()) + })); + let payload_large = LargeStringArray::from_iter((0..rows).map(|i| { + (i % 11 != 0).then(|| format!("large-payload-{start_id}-{i}-{}", "y".repeat(80))) + })); + + let mut list_builder = ListBuilder::new(Int32Builder::new()); + for i in 0..rows { + if i % 4 == 0 { + list_builder.append_null(); + } else { + list_builder + .values() + .append_value((start_id + i as i64) as i32); + list_builder.values().append_value(i as i32); + list_builder.append(true); + } + } + let tags: ListArray = list_builder.finish(); + + let struct_fields = match schema.field(8).data_type() { + DataType::Struct(fields) => fields.clone(), + other => panic!("expected struct, got {other:?}"), + }; + let meta_k: ArrayRef = Arc::new(StringArray::from_iter( + (0..rows).map(|i| Some(format!("key-{}", i % 9))), + )); + let meta_v: ArrayRef = Arc::new(Int64Array::from_iter( + (0..rows).map(|i| (i % 5 != 0).then_some(start_id + i as i64)), + )); + let meta = StructArray::try_new(struct_fields, vec![meta_k, meta_v], None).unwrap(); - // One offset of 5 bytes - let offsets = vec![(2, 5)]; // Read bytes 2-6 (3, 4, 5, 6, 7) + RecordBatch::try_new( + Arc::clone(schema), + vec![ + Arc::new(ts), + Arc::new(id), + Arc::new(level), + Arc::new(score), + Arc::new(flag), + Arc::new(payload_bin), + Arc::new(payload_large), + Arc::new(tags), + Arc::new(meta), + ], + ) + .unwrap() + } - let mut reader = MessageRangeReader::new(cursor, offsets); - let mut buffer = [0u8; 3]; // Buffer smaller than the 5 bytes we want to read + fn write_ipc_with_options( + schema: &Arc, + batches: &[RecordBatch], + options: IpcWriteOptions, + ) -> Vec { + let mut writer = + StreamWriter::try_new_with_options(Vec::new(), schema, options).unwrap(); + for batch in batches { + writer.write(batch).unwrap(); + } + // Match Parseable staging files (no EOS required, exact complete prefix). + writer.get_ref().clone() + } - // First read should get first 3 bytes: 3, 4, 5 - let read_bytes = reader.read(&mut buffer).unwrap(); - assert_eq!(read_bytes, 3); - assert_eq!(&buffer[..read_bytes], &[3, 4, 5]); + fn single_phase_reference( + bytes: &[u8], + ranges: Arc<[(u64, usize)]>, + output_indices: &[usize], + filter_positions_in_output: &[usize], + mut eval: impl FnMut(&RecordBatch) -> BooleanArray, + ) -> Vec { + let reader = stream_reader_for_ranges( + Cursor::new(bytes), + ranges, + Some(output_indices.to_vec()), + MESSAGE_READ_BUFFER_BYTES, + ) + .unwrap(); + let mut out = Vec::new(); + for batch in reader { + let batch = batch.unwrap(); + if batch.num_rows() == 0 { + continue; + } + let filter_batch = batch.project(filter_positions_in_output).unwrap(); + let mask = eval(&filter_batch); + if mask.true_count() == 0 { + continue; + } + let filtered = filter_record_batch(&batch, &mask).unwrap(); + out.push(filtered); + } + out + } - // Second read should get remaining 2 bytes: 6, 7 - let read_bytes = reader.read(&mut buffer).unwrap(); - assert_eq!(read_bytes, 2); - assert_eq!(&buffer[..read_bytes], &[6, 7]); + fn build_ranges(bytes: &[u8], reverse: bool) -> Arc<[(u64, usize)]> { + let mut plan = plan_exact_prefix(Cursor::new(bytes), 0, bytes.len() as u64).unwrap(); + assert!(!plan.has_dictionaries); + if reverse { + plan.messages.reverse(); + } + let mut ranges = Vec::with_capacity(plan.messages.len() + 1); + ranges.push(plan.schema_range); + ranges.extend(plan.messages.into_iter().map(|m| (m.offset, m.size))); + Arc::from(ranges) + } - // No more data - let read_bytes = reader.read(&mut buffer).unwrap(); - assert_eq!(read_bytes, 0); - } + #[test] + fn two_phase_matches_single_phase_across_selectivities_and_compressions() { + let schema = wide_schema_with_metadata(); + let batches = vec![ + make_wide_batch(&schema, 0, 100), + make_wide_batch(&schema, 100, 0), // zero-row batch in the middle + make_wide_batch(&schema, 100, 100), + make_wide_batch(&schema, 200, 100), + ]; + + let filter_indices = vec![1usize, 2usize]; // id, level + let output_indices: Vec = (0..schema.fields().len()).collect(); + let filter_positions_in_output = vec![1usize, 2usize]; + + let options_list = [ + IpcWriteOptions::default(), + IpcWriteOptions::default() + .try_with_compression(Some(CompressionType::LZ4_FRAME)) + .unwrap(), + IpcWriteOptions::default() + .try_with_compression(Some(CompressionType::ZSTD)) + .unwrap(), + ]; + + for options in options_list { + let bytes = write_ipc_with_options(&schema, &batches, options); + for reverse in [false, true] { + let ranges = build_ranges(&bytes, reverse); + + // 1. 0% match (all-false) + { + let eval = + |fb: &RecordBatch| BooleanArray::from(vec![false; fb.num_rows()]); + let expected = single_phase_reference( + &bytes, + Arc::clone(&ranges), + &output_indices, + &filter_positions_in_output, + eval, + ); + let mut reader = two_phase_filtered_reader( + Cursor::new(bytes.as_slice()), + Arc::clone(&ranges), + filter_indices.clone(), + output_indices.clone(), + |fb| Ok::<_, io::Error>(eval(fb)), + ) + .unwrap(); + let actual: Vec<_> = (&mut reader).collect::, _>>().unwrap(); + assert!(actual.is_empty()); + assert_eq!(actual, expected); + assert_eq!(reader.stats().phase2_decodes, 0); + assert_eq!(reader.stats().batches_skipped_empty, 1); + assert_eq!(reader.stats().batches_skipped_zero_matches, 3); + } - #[test] - fn testget_reverse_reader_single_message() -> io::Result<()> { - let dir = TempDir::new().unwrap(); - let file_path = dir.path().join("test_single.data.arrows"); + // 2. 1% match (1 row per 100-row batch) + { + let eval = |fb: &RecordBatch| { + let ids = fb.column(0).as_primitive::(); + BooleanArray::from_iter( + ids.values().iter().map(|&v| Some(v % 100 == 42)), + ) + }; + let expected = single_phase_reference( + &bytes, + Arc::clone(&ranges), + &output_indices, + &filter_positions_in_output, + eval, + ); + let mut reader = two_phase_filtered_reader( + Cursor::new(bytes.as_slice()), + Arc::clone(&ranges), + filter_indices.clone(), + output_indices.clone(), + |fb| Ok::<_, io::Error>(eval(fb)), + ) + .unwrap(); + let actual: Vec<_> = (&mut reader).collect::, _>>().unwrap(); + assert_eq!(actual.len(), 3); + assert_eq!(actual.iter().map(RecordBatch::num_rows).sum::(), 3); + assert_eq!(actual, expected); + assert_eq!(reader.stats().phase2_decodes, 3); + assert_eq!(reader.stats().batches_partially_matched, 3); + } - // Create a schema - let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); + // 3. 50% match + { + let eval = |fb: &RecordBatch| { + let ids = fb.column(0).as_primitive::(); + BooleanArray::from_iter(ids.values().iter().map(|&v| Some(v % 2 == 0))) + }; + let expected = single_phase_reference( + &bytes, + Arc::clone(&ranges), + &output_indices, + &filter_positions_in_output, + eval, + ); + let actual: Vec<_> = two_phase_filtered_reader( + Cursor::new(bytes.as_slice()), + Arc::clone(&ranges), + filter_indices.clone(), + output_indices.clone(), + |fb| Ok::<_, io::Error>(eval(fb)), + ) + .unwrap() + .collect::, _>>() + .unwrap(); + assert_eq!(actual.iter().map(RecordBatch::num_rows).sum::(), 150); + assert_eq!(actual, expected); + } - // Create a single batch - let batch = - RecordBatch::try_new(schema.clone(), vec![Arc::new(Int32Array::from(vec![42]))]) - .expect("Failed to create batch"); + // 4. 100% match (all-true fast path without filter_record_batch copy) + { + let eval = |fb: &RecordBatch| BooleanArray::from(vec![true; fb.num_rows()]); + let expected = single_phase_reference( + &bytes, + Arc::clone(&ranges), + &output_indices, + &filter_positions_in_output, + eval, + ); + let mut reader = two_phase_filtered_reader( + Cursor::new(bytes.as_slice()), + Arc::clone(&ranges), + filter_indices.clone(), + output_indices.clone(), + |fb| Ok::<_, io::Error>(eval(fb)), + ) + .unwrap(); + let actual: Vec<_> = (&mut reader).collect::, _>>().unwrap(); + assert_eq!(actual, expected); + assert_eq!(reader.stats().batches_all_matched, 3); + assert_eq!(reader.stats().batches_partially_matched, 0); + assert_eq!(reader.stats().phase2_decodes, 3); + assert_eq!(reader.output_schema(), schema); + } - // Write batch to file - write_test_batches(&file_path, &schema, &[batch])?; + // 5. All-null predicate mask + { + let eval = |fb: &RecordBatch| BooleanArray::from(vec![None; fb.num_rows()]); + let expected = single_phase_reference( + &bytes, + Arc::clone(&ranges), + &output_indices, + &filter_positions_in_output, + eval, + ); + let mut reader = two_phase_filtered_reader( + Cursor::new(bytes.as_slice()), + Arc::clone(&ranges), + filter_indices.clone(), + output_indices.clone(), + |fb| Ok::<_, io::Error>(eval(fb)), + ) + .unwrap(); + let actual: Vec<_> = (&mut reader).collect::, _>>().unwrap(); + assert!(actual.is_empty()); + assert_eq!(actual, expected); + assert_eq!(reader.stats().phase2_decodes, 0); + assert_eq!(reader.stats().batches_skipped_zero_matches, 3); + } - let mut reader = - MergedReverseRecordReader::try_new(&[file_path.into()]).merged_iter(schema, None); + // 6. Mixed null + true + false predicate (including null level values) + { + let eval = |fb: &RecordBatch| { + let levels = fb.column(1).as_string::(); + BooleanArray::from_iter( + levels.iter().map(|opt| opt.map(|v| v == "error")), + ) + }; + let expected = single_phase_reference( + &bytes, + Arc::clone(&ranges), + &output_indices, + &filter_positions_in_output, + eval, + ); + let actual: Vec<_> = two_phase_filtered_reader( + Cursor::new(bytes.as_slice()), + Arc::clone(&ranges), + filter_indices.clone(), + output_indices.clone(), + |fb| Ok::<_, io::Error>(eval(fb)), + ) + .unwrap() + .collect::, _>>() + .unwrap(); + assert_eq!(actual, expected); + } - // Should get the batch - let result_batch = reader - .next() - .expect("Failed to read batch") - .expect("Invalid batch"); - let id_array = result_batch - .column(0) - .as_any() - .downcast_ref::() - .unwrap(); - assert_eq!(id_array.value(0), 42); + // 7. Mixed per-batch selectivity: batch 0 = 0%, batch 1 = 100%, batch 2 = 10% + { + let eval = |fb: &RecordBatch| { + let ids = fb.column(0).as_primitive::(); + BooleanArray::from_iter(ids.values().iter().map(|&v| { + if v < 100 { + Some(false) + } else if v < 200 { + Some(true) + } else { + (v % 10 == 0).then_some(true) + } + })) + }; + let expected = single_phase_reference( + &bytes, + Arc::clone(&ranges), + &output_indices, + &filter_positions_in_output, + eval, + ); + let mut reader = two_phase_filtered_reader( + Cursor::new(bytes.as_slice()), + Arc::clone(&ranges), + filter_indices.clone(), + output_indices.clone(), + |fb| Ok::<_, io::Error>(eval(fb)), + ) + .unwrap(); + let actual: Vec<_> = (&mut reader).collect::, _>>().unwrap(); + assert_eq!(actual, expected); + assert_eq!(reader.stats().batches_skipped_empty, 1); + assert_eq!(reader.stats().batches_skipped_zero_matches, 1); + assert_eq!(reader.stats().batches_all_matched, 1); + assert_eq!(reader.stats().batches_partially_matched, 1); + assert_eq!(reader.stats().phase2_decodes, 2); + } + } + } + } - // No more batches - assert!(reader.next().is_none()); + #[test] + fn two_phase_skips_non_filter_column_decompression_on_zero_matches() { + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + Field::new("payload_a", DataType::Utf8, false), + Field::new("payload_b", DataType::Binary, false), + ])); + let rows = 64usize; + let batch = RecordBatch::try_new( + Arc::clone(&schema), + vec![ + Arc::new(Int64Array::from_iter_values(0..rows as i64)), + Arc::new(StringArray::from_iter_values( + (0..rows).map(|i| format!("payload-a-{i}-{}", "A".repeat(128))), + )), + Arc::new(BinaryArray::from_iter_values((0..rows).map(|i| { + format!("payload-b-{i}-{}", "B".repeat(128)).into_bytes() + }))), + ], + ) + .unwrap(); - Ok(()) - } + let options = IpcWriteOptions::default() + .try_with_compression(Some(CompressionType::LZ4_FRAME)) + .unwrap(); + let mut bytes = write_ipc_with_options(&schema, &[batch], options); + let ranges = build_ranges(&bytes, false); + + // Locate the compressed values buffer of `payload_a` (buffer index 4: + // col 0 has buffers [0, 1]; col 1 Utf8 has buffers [2 (nulls), 3 (offsets), 4 (values)]) + // and corrupt its LZ4 frame bytes in place. + let (rb_offset, rb_size) = ranges[1]; + let rb_slice = &bytes[rb_offset as usize..(rb_offset as usize + rb_size)]; + let meta_len = i32::from_le_bytes(rb_slice[4..8].try_into().unwrap()) as usize; + let message = root_as_message(&rb_slice[8..8 + meta_len]).unwrap(); + let rb_msg = message.header_as_record_batch().unwrap(); + let payload_buf = rb_msg.buffers().unwrap().get(4); + assert!(payload_buf.length() > 16); + let corrupt_start = rb_offset as usize + 8 + meta_len + payload_buf.offset() as usize; + let corrupt_end = corrupt_start + payload_buf.length() as usize; + for byte in &mut bytes[corrupt_start + 8..corrupt_end] { + *byte ^= 0xFF; + } - #[test] - fn test_large_range_direct_read() { - // Test reading a large section directly into caller's buffer without an - // intermediate MessageRangeReader buffer. - let data = vec![1; 10000]; // 10KB of data - let cursor = Cursor::new(data); + // 0 matching rows: Phase 1 decodes only column 0 (`id`), drops the + // buffer, and never touches or LZ4-decompresses corrupted column 1. + let mut zero_match_reader = two_phase_filtered_reader( + Cursor::new(bytes.as_slice()), + Arc::clone(&ranges), + vec![0], + vec![0, 1, 2], + |fb| Ok::<_, io::Error>(BooleanArray::from(vec![false; fb.num_rows()])), + ) + .unwrap(); + let zero_results: Vec<_> = (&mut zero_match_reader) + .collect::, _>>() + .unwrap(); + assert!(zero_results.is_empty()); + assert_eq!(zero_match_reader.stats().messages_scanned, 1); + assert_eq!(zero_match_reader.stats().batches_skipped_zero_matches, 1); + assert_eq!(zero_match_reader.stats().phase2_decodes, 0); + + // 1 matching row on the exact same corrupted bytes: Phase 2 must + // attempt to LZ4-decompress column 1 and fail closed! + let mut match_reader = two_phase_filtered_reader( + Cursor::new(bytes.as_slice()), + ranges, + vec![0], + vec![0, 1, 2], + |fb| { + let mut mask = vec![false; fb.num_rows()]; + mask[0] = true; + Ok::<_, io::Error>(BooleanArray::from(mask)) + }, + ) + .unwrap(); + let err = match_reader.next().unwrap().unwrap_err(); + assert!( + matches!(err, TwoPhaseReadError::Arrow(_)), + "expected Arrow decompression error, got {err:?}" + ); + assert!(match_reader.next().is_none()); + } - // One large offset (8KB) - let offsets = vec![(1000, 8000)]; + #[test] + fn two_phase_interleaved_equal_disjoint_and_empty_output_projections() { + let schema = wide_schema_with_metadata(); + let batches = vec![make_wide_batch(&schema, 10, 40)]; + let options = IpcWriteOptions::default() + .try_with_compression(Some(CompressionType::LZ4_FRAME)) + .unwrap(); + let bytes = write_ipc_with_options(&schema, &batches, options); + let ranges = build_ranges(&bytes, false); + + // Interleaved non-contiguous filter and output indices + let filter_indices = vec![1, 4]; // id, flag + let output_indices = vec![0, 1, 3, 4, 7]; + let eval = |fb: &RecordBatch| { + let ids = fb.column(0).as_primitive::(); + let flags = fb.column(1).as_boolean(); + BooleanArray::from_iter( + ids.values() + .iter() + .zip(flags.iter()) + .map(|(&id, flag)| Some(id % 2 == 0 && flag == Some(true))), + ) + }; + let expected = single_phase_reference( + &bytes, + Arc::clone(&ranges), + &output_indices, + &[1, 3], // positions of cols 1 and 4 within output_indices + eval, + ); + let actual: Vec<_> = two_phase_filtered_reader( + Cursor::new(bytes.as_slice()), + Arc::clone(&ranges), + filter_indices.clone(), + output_indices, + |fb| Ok::<_, io::Error>(eval(fb)), + ) + .unwrap() + .collect::, _>>() + .unwrap(); + assert_eq!(actual, expected); + + // output_indices == filter_indices -> Phase 2 is skipped completely + let mut equal_reader = two_phase_filtered_reader( + Cursor::new(bytes.as_slice()), + Arc::clone(&ranges), + filter_indices.clone(), + filter_indices.clone(), + |fb| Ok::<_, io::Error>(eval(fb)), + ) + .unwrap(); + let equal_actual: Vec<_> = (&mut equal_reader).collect::, _>>().unwrap(); + let equal_expected = + single_phase_reference(&bytes, Arc::clone(&ranges), &filter_indices, &[0, 1], eval); + assert_eq!(equal_actual, equal_expected); + assert_eq!(equal_reader.stats().phase2_decodes, 0); + + // Disjoint output_indices (filter column omitted from output) + let disjoint_actual: Vec<_> = two_phase_filtered_reader( + Cursor::new(bytes.as_slice()), + Arc::clone(&ranges), + vec![1], + vec![0, 3], + |fb| { + let ids = fb.column(0).as_primitive::(); + Ok::<_, io::Error>(BooleanArray::from_iter( + ids.values().iter().map(|&id| Some(id >= 30)), + )) + }, + ) + .unwrap() + .collect::, _>>() + .unwrap(); + assert_eq!(disjoint_actual.len(), 1); + assert_eq!(disjoint_actual[0].num_columns(), 2); + assert_eq!(disjoint_actual[0].num_rows(), 20); + assert_eq!( + disjoint_actual[0].schema(), + Arc::new(schema.project(&[0, 3]).unwrap()) + ); + + // Empty output_indices (e.g., filtered COUNT(*)): 0 columns, exact row count + let mut empty_out_reader = two_phase_filtered_reader( + Cursor::new(bytes.as_slice()), + ranges, + vec![1], + vec![], + |fb| { + let ids = fb.column(0).as_primitive::(); + Ok::<_, io::Error>(BooleanArray::from_iter( + ids.values().iter().map(|&id| Some(id < 25)), + )) + }, + ) + .unwrap(); + let empty_out_batches: Vec<_> = (&mut empty_out_reader) + .collect::, _>>() + .unwrap(); + assert_eq!(empty_out_batches.len(), 1); + assert_eq!(empty_out_batches[0].num_columns(), 0); + assert_eq!(empty_out_batches[0].num_rows(), 15); + assert_eq!(empty_out_reader.stats().phase2_decodes, 0); + } - let mut reader = MessageRangeReader::new(cursor, offsets); - let mut buffer = [0u8; 10000]; + #[test] + fn two_phase_supports_legacy_ipc_format() { + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + Field::new("name", DataType::Utf8, true), + Field::new("val", DataType::Float64, true), + ])); + let batch1 = RecordBatch::try_new( + Arc::clone(&schema), + vec![ + Arc::new(Int64Array::from(vec![1, 2, 3, 4])), + Arc::new(StringArray::from(vec![ + Some("a"), + None, + Some("c"), + Some("d"), + ])), + Arc::new(Float64Array::from(vec![ + Some(1.0), + Some(2.0), + None, + Some(4.0), + ])), + ], + ) + .unwrap(); + let batch2 = RecordBatch::try_new( + Arc::clone(&schema), + vec![ + Arc::new(Int64Array::from(vec![5, 6, 7])), + Arc::new(StringArray::from(vec![Some("e"), Some("f"), Some("g")])), + Arc::new(Float64Array::from(vec![Some(5.0), Some(6.0), Some(7.0)])), + ], + ) + .unwrap(); - // Should read 8KB - let read_bytes = reader.read(&mut buffer).unwrap(); - assert_eq!(read_bytes, 8000); + let legacy_options = IpcWriteOptions::try_new(8, true, MetadataVersion::V4).unwrap(); + let bytes = write_ipc_with_options(&schema, &[batch1, batch2], legacy_options); + assert_ne!(&bytes[..4], &[0xFF, 0xFF, 0xFF, 0xFF]); + + // Walk legacy 4-byte length-prefixed messages to build ranges. + let mut offset = 0usize; + let mut ranges = Vec::new(); + while offset < bytes.len() { + let meta_len = + i32::from_le_bytes(bytes[offset..offset + 4].try_into().unwrap()) as usize; + let msg = root_as_message(&bytes[offset + 4..offset + 4 + meta_len]).unwrap(); + let body_len = msg.bodyLength() as usize; + let size = 4 + meta_len + body_len; + ranges.push((offset as u64, size)); + offset += size; + } + assert_eq!(ranges.len(), 3); + let ranges: Arc<[(u64, usize)]> = Arc::from(ranges); + + let eval = |fb: &RecordBatch| { + let ids = fb.column(0).as_primitive::(); + BooleanArray::from_iter(ids.values().iter().map(|&id| Some(id % 2 == 1))) + }; + let expected = + single_phase_reference(&bytes, Arc::clone(&ranges), &[0, 1, 2], &[0], eval); + let actual: Vec<_> = two_phase_filtered_reader( + Cursor::new(bytes.as_slice()), + ranges, + vec![0], + vec![0, 1, 2], + |fb| Ok::<_, io::Error>(eval(fb)), + ) + .unwrap() + .collect::, _>>() + .unwrap(); + assert_eq!(actual, expected); + } - // All bytes should be 1 - for &byte in &buffer[..read_bytes] { - assert_eq!(byte, 1); + #[test] + fn two_phase_handles_zero_row_batches_and_schema_only_ranges() { + let schema = wide_schema_with_metadata(); + let batches = vec![ + make_wide_batch(&schema, 0, 0), + make_wide_batch(&schema, 0, 0), + ]; + let bytes = write_ipc_with_options(&schema, &batches, IpcWriteOptions::default()); + let ranges = build_ranges(&bytes, false); + + // Schema-only ranges (no record batches) + let schema_only: Arc<[(u64, usize)]> = Arc::from(vec![ranges[0]]); + let mut empty_reader = two_phase_filtered_reader( + Cursor::new(bytes.as_slice()), + schema_only, + vec![0], + vec![0, 1], + |_| -> Result { + panic!("eval_filter must not be called with zero record batches") + }, + ) + .unwrap(); + assert!(empty_reader.next().is_none()); + assert_eq!(empty_reader.stats().messages_scanned, 0); + + // Stream containing only 0-row batches + let mut zero_rows_reader = two_phase_filtered_reader( + Cursor::new(bytes.as_slice()), + ranges, + vec![1], + vec![0, 1, 2], + |_| -> Result { + panic!("eval_filter must not be called on 0-row batches") + }, + ) + .unwrap(); + assert!(zero_rows_reader.next().is_none()); + assert_eq!(zero_rows_reader.stats().messages_scanned, 2); + assert_eq!(zero_rows_reader.stats().batches_skipped_empty, 2); + assert_eq!(zero_rows_reader.stats().phase2_decodes, 0); } - } - #[test] - fn merged_reverse_reader_orders_multifile_timestamps_and_evolves_schema() -> io::Result<()> { - use arrow_array::TimestampMillisecondArray; - use arrow_schema::TimeUnit; + #[test] + fn two_phase_fails_closed_on_short_reads_corrupt_bytes_and_bad_args() { + let schema = wide_schema_with_metadata(); + let batches = vec![ + make_wide_batch(&schema, 0, 10), + make_wide_batch(&schema, 10, 10), + ]; + let bytes = write_ipc_with_options(&schema, &batches, IpcWriteOptions::default()); + let ranges = build_ranges(&bytes, false); + + // 1. Short read inside promised record batch range -> Io(InvalidData), never silent EOF + let truncated = &bytes[..bytes.len() - 5]; + let mut reader = two_phase_filtered_reader( + Cursor::new(truncated), + Arc::clone(&ranges), + vec![1], + vec![0, 1, 2], + |fb| Ok::<_, io::Error>(BooleanArray::from(vec![true; fb.num_rows()])), + ) + .unwrap(); + assert!(reader.next().unwrap().is_ok()); // batch 0 intact + let err = reader.next().unwrap().unwrap_err(); // batch 1 truncated + match err { + TwoPhaseReadError::Io(io_err) => { + assert_eq!(io_err.kind(), io::ErrorKind::InvalidData); + } + other => panic!("expected Io(InvalidData), got {other:?}"), + } + // Fused after error + assert!(reader.next().is_none()); + + // 2. Short read inside schema range -> InvalidData at try_new + let truncated_schema = &bytes[..ranges[0].1 / 2]; + let err = two_phase_filtered_reader( + Cursor::new(truncated_schema), + Arc::clone(&ranges), + vec![1], + vec![0, 1], + |fb| Ok::<_, io::Error>(BooleanArray::from(vec![true; fb.num_rows()])), + ) + .unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::InvalidData); + + // 3. Corrupt record batch message bytes -> fails closed + let mut corrupt_rb = bytes.clone(); + let (rb_off, rb_size) = ranges[1]; + for b in &mut corrupt_rb[rb_off as usize + 8..rb_off as usize + 32.min(rb_size)] { + *b ^= 0xAA; + } + let mut corrupt_reader = two_phase_filtered_reader( + Cursor::new(corrupt_rb.as_slice()), + Arc::clone(&ranges), + vec![1], + vec![0, 1, 2], + |fb| Ok::<_, io::Error>(BooleanArray::from(vec![true; fb.num_rows()])), + ) + .unwrap(); + assert!(corrupt_reader.next().unwrap().is_err()); + assert!(corrupt_reader.next().is_none()); + + // 4. Schema message placed where RecordBatch is expected -> fails closed + let wrong_header_ranges: Arc<[(u64, usize)]> = Arc::from(vec![ranges[0], ranges[0]]); + let mut wrong_header_reader = two_phase_filtered_reader( + Cursor::new(bytes.as_slice()), + wrong_header_ranges, + vec![1], + vec![0, 1], + |fb| Ok::<_, io::Error>(BooleanArray::from(vec![true; fb.num_rows()])), + ) + .unwrap(); + assert!(matches!( + wrong_header_reader.next().unwrap().unwrap_err(), + TwoPhaseReadError::Arrow(_) + )); - let dir = TempDir::new().unwrap(); - let file_a = dir.path().join("a.data.arrows"); - let file_b = dir.path().join("b.data.arrows"); + // 5. Merged range with >7 trailing bytes -> fails closed with Io(InvalidData) + let merged_ranges: Arc<[(u64, usize)]> = + Arc::from(vec![ranges[0], (ranges[1].0, ranges[1].1 + ranges[2].1)]); + let mut merged_reader = two_phase_filtered_reader( + Cursor::new(bytes.as_slice()), + merged_ranges, + vec![1], + vec![0, 1], + |fb| Ok::<_, io::Error>(BooleanArray::from(vec![true; fb.num_rows()])), + ) + .unwrap(); + assert!(matches!( + merged_reader.next().unwrap().unwrap_err(), + TwoPhaseReadError::Io(ref e) if e.kind() == io::ErrorKind::InvalidData + )); + + // 6. Mismatched mask length -> Arrow error + let mut bad_mask_reader = two_phase_filtered_reader( + Cursor::new(bytes.as_slice()), + Arc::clone(&ranges), + vec![1], + vec![0, 1, 2], + |_| Ok::<_, io::Error>(BooleanArray::from(vec![true, false])), + ) + .unwrap(); + assert!(matches!( + bad_mask_reader.next().unwrap().unwrap_err(), + TwoPhaseReadError::Arrow(_) + )); + assert_eq!(bad_mask_reader.stats().phase2_decodes, 0); + + // 7. Predicate error propagates as Filter(E) without Phase 2 decode + let mut filter_err_reader = two_phase_filtered_reader( + Cursor::new(bytes.as_slice()), + Arc::clone(&ranges), + vec![1], + vec![0, 1, 2], + |_| Err::("predicate boom"), + ) + .unwrap(); + match filter_err_reader.next().unwrap().unwrap_err() { + TwoPhaseReadError::Filter(msg) => assert_eq!(msg, "predicate boom"), + other => panic!("expected Filter error, got {other:?}"), + } + assert_eq!(filter_err_reader.stats().phase2_decodes, 0); + assert!(filter_err_reader.next().is_none()); + + // 8. Invalid arguments rejected at open time + let dummy = |fb: &RecordBatch| { + Ok::<_, io::Error>(BooleanArray::from(vec![true; fb.num_rows()])) + }; + assert_eq!( + two_phase_filtered_reader( + Cursor::new(bytes.as_slice()), + Arc::from(vec![]), + vec![0], + vec![0], + dummy + ) + .unwrap_err() + .kind(), + io::ErrorKind::InvalidData + ); + assert_eq!( + two_phase_filtered_reader( + Cursor::new(bytes.as_slice()), + Arc::clone(&ranges), + vec![], + vec![0], + dummy + ) + .unwrap_err() + .kind(), + io::ErrorKind::InvalidInput + ); + assert_eq!( + two_phase_filtered_reader( + Cursor::new(bytes.as_slice()), + Arc::clone(&ranges), + vec![2, 1], + vec![0, 1, 2], + dummy + ) + .unwrap_err() + .kind(), + io::ErrorKind::InvalidInput + ); + assert_eq!( + two_phase_filtered_reader( + Cursor::new(bytes.as_slice()), + Arc::clone(&ranges), + vec![1, 1], + vec![0, 1, 2], + dummy + ) + .unwrap_err() + .kind(), + io::ErrorKind::InvalidInput + ); + assert_eq!( + two_phase_filtered_reader( + Cursor::new(bytes.as_slice()), + Arc::clone(&ranges), + vec![99], + vec![0, 1], + dummy + ) + .unwrap_err() + .kind(), + io::ErrorKind::InvalidInput + ); + assert_eq!( + two_phase_filtered_reader( + Cursor::new(bytes.as_slice()), + Arc::clone(&ranges), + vec![0], + vec![2, 0], + dummy + ) + .unwrap_err() + .kind(), + io::ErrorKind::InvalidInput + ); + assert_eq!( + two_phase_filtered_reader( + Cursor::new(bytes.as_slice()), + ranges, + vec![0], + vec![0, 99], + dummy + ) + .unwrap_err() + .kind(), + io::ErrorKind::InvalidInput + ); + } - // File A has (p_timestamp, msg); File B evolves schema with extra nullable column `extra` - // and widens `code` from Int32 (missing in A) to Int64 (in target merged schema). - let schema_a = Arc::new(Schema::new(vec![ - Field::new( - crate::event::DEFAULT_TIMESTAMP_KEY, - DataType::Timestamp(TimeUnit::Millisecond, None), - false, - ), - Field::new("msg", DataType::Utf8, true), - ])); - let schema_b = Arc::new(Schema::new(vec![ - Field::new( - crate::event::DEFAULT_TIMESTAMP_KEY, - DataType::Timestamp(TimeUnit::Millisecond, None), - false, - ), - Field::new("msg", DataType::Utf8, true), - Field::new("extra", DataType::Int64, true), - ])); + #[test] + fn two_phase_oversized_message_falls_back_without_allocating_and_resumes_cleanly() { + assert_eq!(STAGING_TWO_PHASE_MAX_MESSAGE_BYTES, 16 * 1024 * 1024); + assert_eq!(STAGING_TWO_PHASE_SHARED_BUDGET_BYTES, 64 * 1024 * 1024); + + let schema = wide_schema_with_metadata(); + let batches = vec![ + make_wide_batch(&schema, 0, 12), + make_wide_batch(&schema, 12, 12), + make_wide_batch(&schema, 24, 240), // oversized relative to cap + make_wide_batch(&schema, 264, 12), + ]; + let options = IpcWriteOptions::default() + .try_with_compression(Some(CompressionType::LZ4_FRAME)) + .unwrap(); + let bytes = write_ipc_with_options(&schema, &batches, options); + let ranges = build_ranges(&bytes, false); + + // Set cap between small messages (ranges[1], ranges[2]) and large message (ranges[3]). + let cap = ranges[1].1.max(ranges[2].1); + assert!(ranges[3].1 > cap); + + let filter_indices = vec![1usize, 2usize]; + let output_indices: Vec = (0..schema.fields().len()).collect(); + let eval = |fb: &RecordBatch| { + let ids = fb.column(0).as_primitive::(); + BooleanArray::from_iter(ids.values().iter().map(|&id| Some(id % 3 == 0))) + }; + let expected = + single_phase_reference(&bytes, Arc::clone(&ranges), &output_indices, &[1, 2], eval); + + // 1. Explicit `next_step()` returns FallbackToSinglePhase at exact index 3 + // without reading/allocating ranges[3], and resuming via StreamReader yields + // identical rows with zero drops or duplicates. + let mut reader = two_phase_filtered_reader( + Cursor::new(bytes.as_slice()), + Arc::clone(&ranges), + filter_indices.clone(), + output_indices.clone(), + |fb| Ok::<_, io::Error>(eval(fb)), + ) + .unwrap() + .with_max_message_bytes(cap); + + let mut combined = Vec::new(); + let resume_idx = loop { + match reader.next_step().unwrap() { + TwoPhaseStep::Batch(batch) => combined.push(batch), + TwoPhaseStep::FallbackToSinglePhase { + resume_range_index, + reason, + } => { + assert_eq!(resume_range_index, 3); + assert_eq!( + reason, + TwoPhaseFallbackReason::MessageTooLarge { + message_bytes: ranges[3].1, + limit_bytes: cap, + } + ); + break resume_range_index; + } + TwoPhaseStep::Finished => panic!("expected FallbackToSinglePhase"), + } + }; + assert_eq!(reader.stats().messages_scanned, 2); + assert!(matches!( + reader.next_step().unwrap(), + TwoPhaseStep::Finished + )); - // Interleaved batch timestamps: - // File A batches: [100, 101], [300, 301] - // File B batches: [200, 201], [400, 401] - let batches_a = vec![ - RecordBatch::try_new( - schema_a.clone(), - vec![ - Arc::new(TimestampMillisecondArray::from(vec![100, 101])), - Arc::new(StringArray::from(vec![Some("a1"), Some("a2")])), - ], + let remaining = reader.remaining_ranges_with_schema(resume_idx); + assert_eq!(remaining.len(), 3); // schema + ranges[3] + ranges[4] + assert_eq!(remaining[0], ranges[0]); + assert_eq!(remaining[1], ranges[3]); + assert_eq!(remaining[2], ranges[4]); + combined.extend(single_phase_reference( + &bytes, + remaining, + &output_indices, + &[1, 2], + eval, + )); + assert_eq!(combined, expected); + + // 2. Seamless `Iterator` fallback completes the whole stream with exact parity. + let large_msg_bytes = ranges[3].1; + let mut iter_reader = two_phase_filtered_reader( + Cursor::new(bytes.as_slice()), + ranges, + filter_indices, + output_indices, + |fb| Ok::<_, io::Error>(eval(fb)), ) - .unwrap(), - RecordBatch::try_new( - schema_a.clone(), - vec![ - Arc::new(TimestampMillisecondArray::from(vec![300, 301])), - Arc::new(StringArray::from(vec![Some("a3"), Some("a4")])), - ], + .unwrap() + .with_max_message_bytes(cap); + let iter_actual: Vec<_> = (&mut iter_reader).collect::, _>>().unwrap(); + assert_eq!(iter_actual, expected); + assert!(iter_reader.stats().fell_back_to_single_phase); + assert_eq!( + iter_reader.stats().fallback_reason, + Some(TwoPhaseFallbackReason::MessageTooLarge { + message_bytes: large_msg_bytes, + limit_bytes: cap, + }) + ); + } + + #[test] + fn two_phase_shared_budget_exhaustion_falls_back_and_releases_permits() { + let schema = wide_schema_with_metadata(); + let batches = vec![ + make_wide_batch(&schema, 0, 20), + make_wide_batch(&schema, 20, 80), + make_wide_batch(&schema, 100, 20), + ]; + let options = IpcWriteOptions::default() + .try_with_compression(Some(CompressionType::LZ4_FRAME)) + .unwrap(); + let bytes = write_ipc_with_options(&schema, &batches, options); + let ranges = build_ranges(&bytes, false); + assert!(ranges[2].1 > ranges[1].1); + + let filter_indices = vec![1usize]; + let output_indices = vec![0usize, 1, 2, 5]; + let eval = |fb: &RecordBatch| { + let ids = fb.column(0).as_primitive::(); + BooleanArray::from_iter(ids.values().iter().map(|&id| Some(id % 2 == 0))) + }; + let expected = + single_phase_reference(&bytes, Arc::clone(&ranges), &output_indices, &[1], eval); + + // Budget holds ranges[1] plus a concurrent reservation, leaving too little + // headroom for ranges[2]. + let reserved = 1024usize; + let budget_limit = reserved + ranges[1].1; + assert!(budget_limit < reserved + ranges[2].1); + let budget = Arc::new(SharedByteBudget::new(budget_limit)); + assert_eq!(budget.limit(), budget_limit); + let concurrent_permit = budget.try_acquire(reserved).unwrap(); + + let mut reader = two_phase_filtered_reader( + Cursor::new(bytes.as_slice()), + Arc::clone(&ranges), + filter_indices.clone(), + output_indices.clone(), + |fb| Ok::<_, io::Error>(eval(fb)), ) - .unwrap(), - ]; - let batches_b = vec![ - RecordBatch::try_new( - schema_b.clone(), + .unwrap() + .with_shared_budget(Arc::clone(&budget)); + + // First batch fits; its permit must be released immediately after emission. + let first_batch = match reader.next_step().unwrap() { + TwoPhaseStep::Batch(batch) => batch, + other => panic!("expected first batch, got {other:?}"), + }; + assert_eq!(budget.in_use(), reserved); + + // Second batch exceeds remaining shared budget -> FallbackToSinglePhase at index 2. + let resume_idx = match reader.next_step().unwrap() { + TwoPhaseStep::FallbackToSinglePhase { + resume_range_index, + reason, + } => { + assert_eq!(resume_range_index, 2); + assert_eq!( + reason, + TwoPhaseFallbackReason::SharedBudgetExhausted { + message_bytes: ranges[2].1, + } + ); + resume_range_index + } + other => panic!("expected SharedBudgetExhausted fallback, got {other:?}"), + }; + assert_eq!(reader.stats().messages_scanned, 1); + assert_eq!(budget.in_use(), reserved); + + let mut combined = vec![first_batch]; + combined.extend(single_phase_reference( + &bytes, + reader.remaining_ranges_with_schema(resume_idx), + &output_indices, + &[1], + eval, + )); + assert_eq!(combined, expected); + + // Seamless `Iterator` fallback while budget stays full produces identical rows. + let mut iter_reader = two_phase_filtered_reader( + Cursor::new(bytes.as_slice()), + ranges, + filter_indices, + output_indices, + |fb| Ok::<_, io::Error>(eval(fb)), + ) + .unwrap() + .with_shared_budget(Arc::clone(&budget)); + let iter_actual: Vec<_> = (&mut iter_reader).collect::, _>>().unwrap(); + assert_eq!(iter_actual, expected); + assert!(iter_reader.stats().fell_back_to_single_phase); + assert_eq!(budget.in_use(), reserved); + + drop(concurrent_permit); + assert_eq!(budget.in_use(), 0); + } + + #[test] + fn two_phase_uncompressed_output_detaches_from_raw_message_buffer() { + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + Field::new("big_payload", DataType::Binary, false), + ])); + let rows = 32usize; + let batch = RecordBatch::try_new( + Arc::clone(&schema), vec![ - Arc::new(TimestampMillisecondArray::from(vec![200, 201])), - Arc::new(StringArray::from(vec![Some("b1"), Some("b2")])), - Arc::new(Int64Array::from(vec![Some(20), Some(21)])), + Arc::new(Int64Array::from_iter_values(0..rows as i64)), + Arc::new(BinaryArray::from_iter_values( + (0..rows).map(|_| vec![b'X'; 4096]), + )), ], ) - .unwrap(), - RecordBatch::try_new( - schema_b.clone(), + .unwrap(); + let bytes = write_ipc_with_options(&schema, &[batch], IpcWriteOptions::default()); + let ranges = build_ranges(&bytes, false); + let raw_msg_len = ranges[1].1; + assert!(raw_msg_len > 128 * 1024); + + let budget = Arc::new(SharedByteBudget::new(STAGING_TWO_PHASE_SHARED_BUDGET_BYTES)); + let mut reader = two_phase_filtered_reader( + Cursor::new(bytes.as_slice()), + ranges, + vec![0], + vec![0], + |fb| Ok::<_, io::Error>(BooleanArray::from(vec![true; fb.num_rows()])), + ) + .unwrap() + .with_shared_budget(Arc::clone(&budget)); + let out = reader.next().unwrap().unwrap(); + assert_eq!(out.num_rows(), rows); + assert_eq!(reader.stats().batches_all_matched, 1); + + // The 32 * 8 = 256-byte `id` column must NOT pin the >128 KiB raw IPC buffer. + let id_data = out.column(0).to_data(); + for buf in id_data.buffers() { + assert!( + buf.capacity() < raw_msg_len / 4, + "uncompressed output buffer retained raw IPC message capacity {} (raw_msg_len={raw_msg_len})", + buf.capacity() + ); + } + assert_eq!(budget.in_use(), 0); + let _ = staging_two_phase_shared_budget_in_use(); + } + + #[test] + fn two_phase_pre_validate_rejects_corrupt_buffer_and_field_node_descriptors() { + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + Field::new("msg", DataType::Utf8, true), + ])); + let batch = RecordBatch::try_new( + Arc::clone(&schema), vec![ - Arc::new(TimestampMillisecondArray::from(vec![400, 401])), - Arc::new(StringArray::from(vec![Some("b3"), Some("b4")])), - Arc::new(Int64Array::from(vec![Some(40), Some(41)])), + Arc::new(Int64Array::from(vec![1, 2, 3, 4])), + Arc::new(StringArray::from(vec![ + Some("a"), + None, + Some("c"), + Some("d"), + ])), ], ) - .unwrap(), - ]; + .unwrap(); + let bytes = write_ipc_with_options(&schema, &[batch], IpcWriteOptions::default()); + let ranges = build_ranges(&bytes, false); + let (rb_off, rb_size) = ranges[1]; + let rb_start = rb_off as usize; + let meta_len = + i32::from_le_bytes(bytes[rb_start + 4..rb_start + 8].try_into().unwrap()) as usize; + let meta_start = rb_start + 8; + let meta_slice = &bytes[meta_start..meta_start + meta_len]; + let msg = root_as_message(meta_slice).unwrap(); + let body_len = msg.bodyLength(); + let rb_msg = msg.header_as_record_batch().unwrap(); + + // Compute exact byte offsets of FieldNode[0] and Buffer[1] inside `bytes`. + let node0 = rb_msg.nodes().unwrap().get(0); + let node0_off = + meta_start + ((node0 as *const _ as usize) - (meta_slice.as_ptr() as usize)); + assert_eq!( + i64::from_le_bytes(bytes[node0_off..node0_off + 8].try_into().unwrap()), + node0.length() + ); + assert_eq!( + i64::from_le_bytes(bytes[node0_off + 8..node0_off + 16].try_into().unwrap()), + node0.null_count() + ); + + let buf1 = rb_msg.buffers().unwrap().get(1); + let buf1_off = + meta_start + ((buf1 as *const _ as usize) - (meta_slice.as_ptr() as usize)); + assert_eq!( + i64::from_le_bytes(bytes[buf1_off..buf1_off + 8].try_into().unwrap()), + buf1.offset() + ); + assert_eq!( + i64::from_le_bytes(bytes[buf1_off + 8..buf1_off + 16].try_into().unwrap()), + buf1.length() + ); + + let assert_invalid_data = |mutated: Vec, label: &str| { + let mut reader = two_phase_filtered_reader( + Cursor::new(mutated.as_slice()), + Arc::clone(&ranges), + vec![0], + vec![0, 1], + |fb| Ok::<_, io::Error>(BooleanArray::from(vec![true; fb.num_rows()])), + ) + .unwrap(); + match reader.next().unwrap() { + Err(TwoPhaseReadError::Io(err)) => { + assert_eq!( + err.kind(), + io::ErrorKind::InvalidData, + "{label}: expected InvalidData, got {err:?}" + ); + } + other => panic!("{label}: expected Io(InvalidData), got {other:?}"), + } + }; - write_test_batches(&file_a, &schema_a, &batches_a)?; - write_test_batches(&file_b, &schema_b, &batches_b)?; + // 1. Buffer offset out of bounds (offset + length > body_len) + { + let mut mutated = bytes.clone(); + mutated[buf1_off..buf1_off + 8].copy_from_slice(&(body_len + 8).to_le_bytes()); + assert_invalid_data(mutated, "buffer offset past body_len"); + } - let merged = MergedReverseRecordReader::try_new(&[file_a.clone(), file_b.clone()]); - assert_eq!(merged.readable_files, vec![file_a, file_b]); - assert!(merged.invalid_files.is_empty()); + // 2. Buffer length exceeds body_len + { + let mut mutated = bytes.clone(); + mutated[buf1_off + 8..buf1_off + 16] + .copy_from_slice(&(body_len + 64).to_le_bytes()); + assert_invalid_data(mutated, "buffer length past body_len"); + } - let target_schema = Arc::new(merged.merged_schema().unwrap()); - let results = merged - .merged_iter(target_schema.clone(), None) - .collect::, _>>() - .unwrap(); - assert_eq!(results.len(), 4); + // 3. Negative buffer offset + { + let mut mutated = bytes.clone(); + mutated[buf1_off..buf1_off + 8].copy_from_slice(&(-8i64).to_le_bytes()); + assert_invalid_data(mutated, "negative buffer offset"); + } - let all_timestamps: Vec = results - .iter() - .flat_map(|batch| { - assert_eq!(batch.schema(), target_schema); - batch - .column(0) - .as_any() - .downcast_ref::() - .unwrap() - .values() - .iter() - .copied() - }) - .collect(); - // Reverse batch order (400s, 300s, 200s, 100s) and reversed rows inside each batch - assert_eq!(all_timestamps, vec![401, 400, 301, 300, 201, 200, 101, 100]); + // 4. Negative buffer length + { + let mut mutated = bytes.clone(); + mutated[buf1_off + 8..buf1_off + 16].copy_from_slice(&(-1i64).to_le_bytes()); + assert_invalid_data(mutated, "negative buffer length"); + } - // Verify schema evolution filled `extra` with nulls for File A batches and preserved values for File B - let extras: Vec> = results - .iter() - .flat_map(|batch| { - batch - .column_by_name("extra") - .unwrap() - .as_any() - .downcast_ref::() - .unwrap() - .iter() - }) - .collect(); - assert_eq!( - extras, - vec![ - Some(41), - Some(40), - None, - None, - Some(21), - Some(20), - None, - None - ] - ); - Ok(()) - } + // 5. Buffer offset + length i64/u64 overflow + { + let mut mutated = bytes.clone(); + mutated[buf1_off..buf1_off + 8].copy_from_slice(&i64::MAX.to_le_bytes()); + mutated[buf1_off + 8..buf1_off + 16].copy_from_slice(&i64::MAX.to_le_bytes()); + assert_invalid_data(mutated, "buffer offset+length overflow"); + } - #[test] - fn merged_reverse_reader_attributes_invalid_and_truncated_files() -> io::Result<()> { - use arrow_array::TimestampMillisecondArray; - use arrow_schema::TimeUnit; + // 6. FieldNode null_count > length + { + let mut mutated = bytes.clone(); + let bad_nulls = node0.length() + 1; + mutated[node0_off + 8..node0_off + 16].copy_from_slice(&bad_nulls.to_le_bytes()); + assert_invalid_data(mutated, "FieldNode null_count > length"); + } - let dir = TempDir::new().unwrap(); - let valid_path = dir.path().join("valid.data.arrows"); - let truncated_tail_path = dir.path().join("truncated_tail.data.arrows"); - let corrupt_path = dir.path().join("corrupt.data.arrows"); + // 7. Negative FieldNode length + { + let mut mutated = bytes.clone(); + mutated[node0_off..node0_off + 8].copy_from_slice(&(-4i64).to_le_bytes()); + assert_invalid_data(mutated, "negative FieldNode length"); + } - let schema = Arc::new(Schema::new(vec![ - Field::new( - crate::event::DEFAULT_TIMESTAMP_KEY, - DataType::Timestamp(TimeUnit::Millisecond, None), - false, - ), - Field::new("id", DataType::Int32, false), - ])); - let make_batch = |ts: i64, id: i32| { - RecordBatch::try_new( - schema.clone(), - vec![ - Arc::new(TimestampMillisecondArray::from(vec![ts])), - Arc::new(Int32Array::from(vec![id])), - ], - ) - .unwrap() - }; + // 8. Negative FieldNode null_count + { + let mut mutated = bytes.clone(); + mutated[node0_off + 8..node0_off + 16].copy_from_slice(&(-1i64).to_le_bytes()); + assert_invalid_data(mutated, "negative FieldNode null_count"); + } - write_test_batches(&valid_path, &schema, &[make_batch(10, 1)])?; + assert!(rb_size > meta_len); + } - // A file with 2 batches whose second batch is crash-truncated recovers the first batch - let mut truncated_bytes = write_mem(&[make_batch(20, 2), make_batch(30, 3)]); - truncate_last_record_batch(&mut truncated_bytes); - std::fs::write(&truncated_tail_path, &truncated_bytes)?; + #[test] + fn two_phase_rejects_corrupt_ipc_schema_field_shapes_without_panicking() { + // Case 1: List field with 0 children (would panic in arrow_ipc::convert::fb_to_schema). + let list_schema = Arc::new(Schema::new(vec![Field::new( + "tags", + DataType::List(Arc::new(Field::new("item", DataType::Int32, true))), + true, + )])); + let mut list_builder = ListBuilder::new(Int32Builder::new()); + list_builder.values().append_value(1); + list_builder.append(true); + let batch = RecordBatch::try_new( + Arc::clone(&list_schema), + vec![Arc::new(list_builder.finish())], + ) + .unwrap(); + let mut bytes = + write_ipc_with_options(&list_schema, &[batch], IpcWriteOptions::default()); + let ranges = build_ranges(&bytes, false); + + let meta_len = i32::from_le_bytes(bytes[4..8].try_into().unwrap()) as usize; + let meta_start = 8usize; + // Locate the `u32` length == 1 of the List field's `children` vector and set it to 0. + let mut patched_children = false; + for pos in (meta_start..meta_start + meta_len - 4).step_by(4) { + if u32::from_le_bytes(bytes[pos..pos + 4].try_into().unwrap()) != 1 { + continue; + } + let mut candidate = bytes.clone(); + candidate[pos..pos + 4].copy_from_slice(&0u32.to_le_bytes()); + if let Ok(msg) = root_as_message(&candidate[meta_start..meta_start + meta_len]) + && let Some(ipc_schema) = msg.header_as_schema() + && let Some(fields) = ipc_schema.fields() + && fields.len() == 1 + && let Some(children) = fields.get(0).children() + && children.is_empty() + { + bytes = candidate; + patched_children = true; + break; + } + } + assert!(patched_children, "failed to patch List children count to 0"); + + let err = two_phase_filtered_reader( + Cursor::new(bytes.as_slice()), + ranges, + vec![0], + vec![0], + |fb| Ok::<_, io::Error>(BooleanArray::from(vec![true; fb.num_rows()])), + ) + .unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::InvalidData); + + let plan_err = plan_exact_prefix(Cursor::new(bytes.as_slice()), 0, bytes.len() as u64) + .unwrap_err(); + assert_eq!(plan_err.kind(), io::ErrorKind::InvalidData); + + // Case 2: Int field with invalid bitWidth (24) fails with InvalidData instead of panicking. + let int_schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int64, false)])); + let int_batch = RecordBatch::try_new( + Arc::clone(&int_schema), + vec![Arc::new(Int64Array::from(vec![1, 2]))], + ) + .unwrap(); + let mut int_bytes = + write_ipc_with_options(&int_schema, &[int_batch], IpcWriteOptions::default()); + let int_ranges = build_ranges(&int_bytes, false); + let int_meta_len = i32::from_le_bytes(int_bytes[4..8].try_into().unwrap()) as usize; + let mut patched_width = false; + for pos in (8..8 + int_meta_len - 4).step_by(4) { + if i32::from_le_bytes(int_bytes[pos..pos + 4].try_into().unwrap()) != 64 { + continue; + } + let mut candidate = int_bytes.clone(); + candidate[pos..pos + 4].copy_from_slice(&24i32.to_le_bytes()); + if let Ok(msg) = root_as_message(&candidate[8..8 + int_meta_len]) + && let Some(ipc_schema) = msg.header_as_schema() + && let Some(fields) = ipc_schema.fields() + && fields.len() == 1 + && let Some(int_ty) = fields.get(0).type_as_int() + && int_ty.bitWidth() == 24 + { + int_bytes = candidate; + patched_width = true; + break; + } + } + assert!(patched_width, "failed to patch Int bitWidth to 24"); + + let width_err = two_phase_filtered_reader( + Cursor::new(int_bytes.as_slice()), + int_ranges, + vec![0], + vec![0], + |fb| Ok::<_, io::Error>(BooleanArray::from(vec![true; fb.num_rows()])), + ) + .unwrap_err(); + assert_eq!(width_err.kind(), io::ErrorKind::InvalidData); + } - // A file with garbage bytes is attributed to invalid_files - std::fs::write(&corrupt_path, b"not an arrow ipc stream")?; + #[test] + fn two_phase_adaptive_fallback_triggers_after_consecutive_matches_with_zero_row_loss() { + assert_eq!(DEFAULT_ADAPTIVE_FALLBACK_CONSECUTIVE_MATCHES, 4); - let merged = MergedReverseRecordReader::try_new(&[ - valid_path.clone(), - truncated_tail_path.clone(), - corrupt_path.clone(), - ]); - assert_eq!(merged.readable_files, vec![valid_path, truncated_tail_path]); - assert_eq!(merged.invalid_files, vec![corrupt_path]); + let schema = wide_schema_with_metadata(); + let batches: Vec<_> = (0..7) + .map(|b| make_wide_batch(&schema, b * 20, 20)) + .collect(); + let options = IpcWriteOptions::default() + .try_with_compression(Some(CompressionType::LZ4_FRAME)) + .unwrap(); + let bytes = write_ipc_with_options(&schema, &batches, options); + let ranges = build_ranges(&bytes, false); + + let filter_indices = vec![1usize]; + let output_indices: Vec = (0..schema.fields().len()).collect(); + let eval = |fb: &RecordBatch| { + let ids = fb.column(0).as_primitive::(); + BooleanArray::from_iter(ids.values().iter().map(|&id| Some(id % 5 == 0))) + }; + let expected = + single_phase_reference(&bytes, Arc::clone(&ranges), &output_indices, &[1], eval); + + // 1. Explicit `next_step()`: emits 4 matching batches, then returns + // FallbackToSinglePhase { resume_range_index: 5 } on the 5th step without reading range 5. + let mut reader = two_phase_filtered_reader( + Cursor::new(bytes.as_slice()), + Arc::clone(&ranges), + filter_indices.clone(), + output_indices.clone(), + |fb| Ok::<_, io::Error>(eval(fb)), + ) + .unwrap() + .with_adaptive_fallback(4); - let ids: Vec = merged - .merged_iter(schema, None) - .map(|batch| { - batch - .unwrap() - .column_by_name("id") - .unwrap() - .as_any() - .downcast_ref::() - .unwrap() - .value(0) - }) - .collect(); - assert_eq!(ids, vec![2, 1]); - Ok(()) + let mut combined = Vec::new(); + for _ in 0..4 { + match reader.next_step().unwrap() { + TwoPhaseStep::Batch(batch) => combined.push(batch), + other => panic!("expected batch during first 4 steps, got {other:?}"), + } + } + let resume_idx = match reader.next_step().unwrap() { + TwoPhaseStep::FallbackToSinglePhase { + resume_range_index, + reason, + } => { + assert_eq!(resume_range_index, 5); + assert_eq!( + reason, + TwoPhaseFallbackReason::AdaptiveConsecutiveMatches { + consecutive_matches: 4, + } + ); + resume_range_index + } + other => panic!("expected AdaptiveConsecutiveMatches fallback, got {other:?}"), + }; + assert_eq!(reader.stats().messages_scanned, 4); + assert_eq!(reader.stats().phase2_decodes, 4); + + let remaining = reader.remaining_ranges_with_schema(resume_idx); + assert_eq!(remaining.len(), 4); // schema + 3 remaining batches + // Resume with `projection = None` (SELECT *) to verify full-stream parity. + let stream = stream_reader_for_ranges( + Cursor::new(bytes.as_slice()), + remaining, + None, + MESSAGE_READ_BUFFER_BYTES, + ) + .unwrap(); + for batch in stream { + let batch = batch.unwrap(); + let filter_batch = batch.project(&[1]).unwrap(); + let mask = eval(&filter_batch); + if mask.true_count() > 0 { + combined.push(filter_record_batch(&batch, &mask).unwrap()); + } + } + assert_eq!(combined, expected); + + // 2. Seamless `Iterator`: switches internally after 4 consecutive matches and + // yields all 7 batches with zero row loss. + let mut iter_reader = two_phase_filtered_reader( + Cursor::new(bytes.as_slice()), + Arc::clone(&ranges), + filter_indices.clone(), + output_indices.clone(), + |fb| Ok::<_, io::Error>(eval(fb)), + ) + .unwrap() + .with_adaptive_fallback(4); + let iter_actual: Vec<_> = (&mut iter_reader).collect::, _>>().unwrap(); + assert_eq!(iter_actual, expected); + assert!(iter_reader.stats().fell_back_to_single_phase); + assert_eq!(iter_reader.stats().phase2_decodes, 4); + assert_eq!( + iter_reader.stats().fallback_reason, + Some(TwoPhaseFallbackReason::AdaptiveConsecutiveMatches { + consecutive_matches: 4, + }) + ); + + // 3. When a zero-match batch occurs before the threshold, two-phase proved + // selective and must NOT trigger adaptive fallback. + let mut selective_reader = two_phase_filtered_reader( + Cursor::new(bytes.as_slice()), + Arc::clone(&ranges), + filter_indices.clone(), + output_indices.clone(), + |fb| { + let ids = fb.column(0).as_primitive::(); + Ok::<_, io::Error>(BooleanArray::from_iter( + ids.values().iter().map(|&id| Some(id >= 20)), + )) + }, + ) + .unwrap() + .with_adaptive_fallback(4); + let selective_batches: Vec<_> = (&mut selective_reader) + .collect::, _>>() + .unwrap(); + assert_eq!(selective_batches.len(), 6); + assert!(!selective_reader.stats().fell_back_to_single_phase); + assert_eq!(selective_reader.stats().batches_skipped_zero_matches, 1); + assert_eq!(selective_reader.stats().phase2_decodes, 6); + + // 4. Exactly 4 batches total: no remaining ranges after the 4th batch, so + // adaptive fallback must NOT fire spuriously. + let four_ranges: Arc<[(u64, usize)]> = Arc::from(&ranges[..5]); + let mut exact_four = two_phase_filtered_reader( + Cursor::new(bytes.as_slice()), + four_ranges, + filter_indices, + output_indices, + |fb| Ok::<_, io::Error>(eval(fb)), + ) + .unwrap() + .with_adaptive_fallback(4); + for _ in 0..4 { + assert!(matches!( + exact_four.next_step().unwrap(), + TwoPhaseStep::Batch(_) + )); + } + assert!(matches!( + exact_four.next_step().unwrap(), + TwoPhaseStep::Finished + )); + assert!(!exact_four.stats().fell_back_to_single_phase); + } + + #[test] + fn two_phase_cancellation_stops_zero_match_scan_early() { + let schema = wide_schema_with_metadata(); + let batches: Vec<_> = (0..10) + .map(|b| make_wide_batch(&schema, b * 16, 16)) + .collect(); + let options = IpcWriteOptions::default() + .try_with_compression(Some(CompressionType::LZ4_FRAME)) + .unwrap(); + let bytes = write_ipc_with_options(&schema, &batches, options); + let ranges = build_ranges(&bytes, false); + + // 1. Pre-cancelled before first message: 0 messages read, 0 predicate calls. + let pre_cancelled = Arc::new(AtomicBool::new(true)); + let eval_calls = Arc::new(AtomicUsize::new(0)); + let eval_calls_clone = Arc::clone(&eval_calls); + let mut pre_reader = two_phase_filtered_reader( + Cursor::new(bytes.as_slice()), + Arc::clone(&ranges), + vec![1], + vec![0, 1, 2, 5], + move |fb| { + eval_calls_clone.fetch_add(1, Ordering::Relaxed); + Ok::<_, io::Error>(BooleanArray::from(vec![false; fb.num_rows()])) + }, + ) + .unwrap() + .with_cancel_flag(pre_cancelled); + assert!(pre_reader.next().is_none()); + assert_eq!(pre_reader.stats().messages_scanned, 0); + assert_eq!(eval_calls.load(Ordering::Relaxed), 0); + + // 2. Cancelled during message 0 on an all-zero-match stream: stops after + // 1 message instead of scanning all 10 messages. + let cancelled = Arc::new(AtomicBool::new(false)); + let cancelled_in_filter = Arc::clone(&cancelled); + let mut reader = two_phase_filtered_reader( + Cursor::new(bytes.as_slice()), + ranges, + vec![1], + vec![0, 1, 2, 5], + move |fb| { + cancelled_in_filter.store(true, Ordering::Relaxed); + Ok::<_, io::Error>(BooleanArray::from(vec![false; fb.num_rows()])) + }, + ) + .unwrap() + .with_cancel_flag(cancelled); + assert!(reader.next().is_none()); + assert_eq!(reader.stats().messages_scanned, 1); + assert_eq!(reader.stats().batches_skipped_zero_matches, 1); + assert_eq!(reader.stats().phase2_decodes, 0); + // Fused after cancellation + assert!(matches!( + reader.next_step().unwrap(), + TwoPhaseStep::Finished + )); + } } } diff --git a/src/parseable/staging/writer.rs b/src/parseable/staging/writer.rs index 9da1b79b2..0619bb90b 100644 --- a/src/parseable/staging/writer.rs +++ b/src/parseable/staging/writer.rs @@ -19,11 +19,13 @@ use std::{ borrow::Cow, + cell::RefCell, collections::{HashMap, HashSet}, fs::{self, File, OpenOptions}, io::{BufWriter, Write}, path::{Path, PathBuf}, - sync::Arc, + str::FromStr, + sync::{Arc, mpsc}, }; use arrow_array::RecordBatch; @@ -34,7 +36,7 @@ use arrow_ipc::{ write_message, }, }; -use arrow_schema::{Schema, SchemaRef}; +use arrow_schema::{ArrowError, Schema, SchemaRef}; use arrow_select::concat::concat_batches; use chrono::{DateTime, Utc}; use once_cell::sync::Lazy; @@ -70,6 +72,253 @@ const MIN_COMPRESSED_BATCH_ROWS: usize = 100; // rows are about 123 KiB. const MAX_UNCOMPRESSED_BATCH_BYTES: usize = 256 * 1024; +// 32 KiB coalesces small metadata/headers cleanly while keeping cold open +// writers compact (1,000 idle writers = ~32 MiB instead of 250 MiB). Large +// pre-encoded IPC batches (>32 KiB) bypass `BufWriter`'s internal copy and +// issue a single direct `write(2)` syscall. +const DISK_WRITER_BUFFER_BYTES: usize = 32 * 1024; + +// Cached batches below this size are freed by the thread that evicted them, +// 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; + +pub const STAGING_IPC_COMPRESSION_VAR: &str = "P_STAGING_IPC_COMPRESSION"; + +/// Codec of the compressed record batch messages in staging files. +/// +/// Every message names its own codec, so files written with either setting, +/// and files mixing them with the uncompressed small batches, are read by the +/// same readers. Changing the setting needs no migration. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum StagingIpcCompression { + #[default] + Lz4, + Zstd, +} + +impl StagingIpcCompression { + pub const ALL: [Self; 2] = [Self::Lz4, Self::Zstd]; + + fn codec(self) -> CompressionType { + match self { + Self::Lz4 => CompressionType::LZ4_FRAME, + Self::Zstd => CompressionType::ZSTD, + } + } + + 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 { + type Err = String; + + fn from_str(value: &str) -> Result { + match value.trim().to_ascii_lowercase().as_str() { + "" | "lz4" | "lz4_frame" => Ok(Self::Lz4), + "zstd" => Ok(Self::Zstd), + other => Err(format!( + "unknown staging IPC compression {other:?}: expected \"lz4\" or \"zstd\"" + )), + } + } +} + +/// `P_STAGING_IPC_COMPRESSION`: `lz4` (default) or `zstd`. +pub static STAGING_IPC_COMPRESSION: Lazy = + Lazy::new(|| match std::env::var(STAGING_IPC_COMPRESSION_VAR) { + Ok(value) => value.parse().unwrap_or_else(|err| { + tracing::warn!("{STAGING_IPC_COMPRESSION_VAR}: {err}; using lz4"); + StagingIpcCompression::default() + }), + Err(_) => StagingIpcCompression::default(), + }); + +/// Whether `rb` is written as a compressed message; see the two cutoffs above. +pub(crate) fn is_compressed_batch(rb: &RecordBatch) -> bool { + rb.num_rows() >= MIN_COMPRESSED_BATCH_ROWS + || rb.get_array_memory_size() >= MAX_UNCOMPRESSED_BATCH_BYTES +} + +fn has_dictionary(schema: &Schema) -> bool { + schema + .flattened_fields() + .iter() + .any(|field| matches!(field.data_type(), arrow_schema::DataType::Dictionary(_, _))) +} + +thread_local! { + // Reuses the flatbuffer builder and the zstd context between the batches + // a thread encodes. + static PREENCODE_CONTEXT: RefCell = RefCell::default(); +} + +/// The IPC stream message of one record batch, encoded and compressed ahead +/// of the staging writer: the bytes `DiskWriter::write` would append for it. +/// +/// Encoding is most of the cost of an append, and a message without +/// dictionaries depends only on its batch. Callers encode on their own +/// threads and the writer, which serializes them, only copies the bytes. +#[derive(Debug, Clone)] +pub struct PreEncodedBatch { + // The exact schema of the encoded batch; a writer takes the bytes only + // into a stream opened with it. + schema: SchemaRef, + rows: usize, + bytes: Vec, +} + +impl PreEncodedBatch { + /// Encodes a batch that takes the compressed path, with the configured + /// codec. `None` leaves the batch to its writer: small batches, which are + /// cheap to encode and are combined with their queue neighbours, schemas + /// with dictionaries, whose messages depend on what the stream already + /// holds, and batches that fail to encode, so that the writer reports + /// the error. + pub fn for_push(rb: &RecordBatch) -> Option { + if !is_compressed_batch(rb) { + return None; + } + Self::encode_with(rb, *STAGING_IPC_COMPRESSION) + .ok() + .flatten() + } + + /// Encodes `rb` as its writer would: compressed with `compression`, or + /// uncompressed when it is a small batch. `None` for a schema with + /// dictionaries. + pub fn encode_with( + rb: &RecordBatch, + compression: StagingIpcCompression, + ) -> Result, ArrowError> { + if has_dictionary(rb.schema_ref()) { + return Ok(None); + } + let options = if is_compressed_batch(rb) { + compression.write_options() + } else { + IpcWriteOptions::default() + }; + let bytes = PREENCODE_CONTEXT.with(|context| { + let mut dictionaries = DictionaryTracker::new(false); + let (dictionary_messages, message) = IpcDataGenerator::default().encode( + rb, + &mut dictionaries, + &options, + &mut context.borrow_mut(), + )?; + if !dictionary_messages.is_empty() { + return Err(ArrowError::IpcError( + "unexpected dictionary in a pre-encoded staging batch".to_owned(), + )); + } + let mut bytes = + Vec::with_capacity(message.ipc_message.len() + message.arrow_data.len() + 128); + write_message(&mut bytes, message, &options)?; + Ok(bytes) + })?; + Ok(Some(Self { + schema: rb.schema(), + rows: rb.num_rows(), + bytes, + })) + } + + /// Encoded length: the bytes this batch adds to its staging file. + pub fn len(&self) -> usize { + self.bytes.len() + } + + pub fn is_empty(&self) -> bool { + self.bytes.is_empty() + } + + fn is_for(&self, rb: &RecordBatch) -> bool { + self.rows == rb.num_rows() + && (Arc::ptr_eq(&self.schema, rb.schema_ref()) || self.schema == *rb.schema_ref()) + } +} + +/// Batches leaving the memory cache, kept alive until their holder is dropped. +/// +/// Freeing a large cache takes long, and the paths that empty one hold the +/// stream's writer lock: rollover, budget eviction, a failed write. They move +/// the batches here instead and the caller drops this after releasing its +/// locks. The bytes are subtracted from the staging budget when the batches +/// are moved, not when they are freed, so the budget never waits for the +/// allocator; batches of `BACKGROUND_DROP_MIN_BYTES` or more are freed by a +/// dedicated thread. +#[derive(Debug, Default)] +pub struct DeferredDrop { + batches: Vec, + // Budget bytes the batches were charged with. + bytes: usize, + // Free on the dropping thread whatever the size. + inline: bool, +} + +impl DeferredDrop { + /// A holder that frees its batches where it is dropped: for callers that + /// free under their own lock, as before deferral existed. + fn inline() -> Self { + Self { + batches: Vec::new(), + bytes: 0, + inline: true, + } + } + + /// Budget bytes of the batches held. + pub fn bytes(&self) -> usize { + self.bytes + } + + pub fn is_empty(&self) -> bool { + self.batches.is_empty() + } + + fn take(&mut self, batches: &mut Vec, bytes: usize) { + self.batches.append(batches); + self.bytes = self.bytes.saturating_add(bytes); + } +} + +impl Drop for DeferredDrop { + fn drop(&mut self) { + if self.inline || self.bytes < BACKGROUND_DROP_MIN_BYTES || self.batches.is_empty() { + return; + } + if let Some(thread) = DROP_THREAD.as_ref() { + // 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)); + } + } +} + +// Bounded so concurrent multi-stream rollovers cannot accumulate unbounded +// 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); + std::thread::Builder::new() + .name("staging-drop".to_owned()) + .spawn(move || { + for batches in receiver { + drop(batches); + } + }) + .map_err(|err| error!("Couldn't start the staging drop thread: {err}")) + .ok() + .map(|_| sender) +}); + const ENABLE_MEMORY_STAGING_VAR: &str = "ENABLE_MEMORY_STAGING"; pub static ENABLE_MEMORY_STAGING: Lazy = Lazy::new(|| { if let Ok(var) = std::env::var(ENABLE_MEMORY_STAGING_VAR) @@ -92,6 +341,23 @@ static ONE_PARQUET_PER_ARROW: Lazy = Lazy::new(|| { } }); +/// One batch of a group written under a single hold of the writer lock. +pub(crate) struct StagedPush<'a> { + /// The staging file of the batch. `None` only caches it in memory, for + /// streams that stage nothing on disk. + pub(crate) file: Option>, + pub(crate) schema_key: &'a str, + pub(crate) batch: &'a RecordBatch, + /// `batch` already encoded, when its caller did that ahead of the lock. + pub(crate) preencoded: Option<&'a PreEncodedBatch>, +} + +pub(crate) struct StagedFile<'a> { + pub(crate) name: &'a str, + pub(crate) path: PathBuf, + pub(crate) range: TimeRange, +} + // #[derive(Default)] pub struct Writer { pub mem: Option>, @@ -147,45 +413,112 @@ impl Writer { /// The returned key is the sibling's when one took the batch, and memory /// segments must be keyed by it as well: a segment follows the file of the /// writer with its key. - fn write_or_retire(&mut self, key: &str, rb: &RecordBatch) -> Result<(), StagingError> { - let res = self + #[cfg_attr(feature = "hotpath", hotpath::measure)] + pub(crate) fn push_disk_ref<'a>( + &mut self, + filename: &'a str, + rb: &RecordBatch, + file_path: PathBuf, + range: TimeRange, + ) -> Result, StagingError> { + self.append_disk( + filename, + rb, + None, + file_path, + range, + true, + &mut DeferredDrop::inline(), + ) + } + + /// Appends `rb` to the writer `key`. With `flush` the batch is flushed + /// and acknowledged before this returns; without, it stays staged in the + /// writer until `flush_or_retire`. + fn write_or_retire( + &mut self, + key: &str, + rb: &RecordBatch, + preencoded: Option<&PreEncodedBatch>, + flush: bool, + deferred: &mut DeferredDrop, + ) -> Result<(), StagingError> { + let writer = self .disk .get_mut(key) - .expect("caller verified writer presence") - .write(rb); + .expect("caller verified writer presence"); + let mut res = writer.append(rb, preencoded); + if res.is_ok() && flush { + res = writer.flush_staged(); + } if res.is_err() { - // Retire a writer on its first write/flush error so no later append - // can drain partial bytes from the failed call into an acknowledged - // prefix. Preserve any already-acknowledged prefix in `pending` so - // earlier rows stay queryable until recovery/conversion. - if let Some(writer) = self.disk.remove(key) { - let acknowledged = writer.acknowledged_len(); - let path = writer.path().to_path_buf(); - if let Some(mem) = self.mem.as_mut() - && let Some(mut segment) = mem.segments.remove(key) - { - let start = segment.disk.as_ref().map_or(0, |d| d.start); - segment.drop_cached(); - if acknowledged > start { - mem.pending.entry(path).or_default().push(PendingSource { - start, - len: acknowledged, - previous: None, - }); - } + self.retire(key, deferred); + } + res + } + + /// Flushes the batches staged in the writer `key`, acknowledging them. + fn flush_or_retire( + &mut self, + key: &str, + deferred: &mut DeferredDrop, + ) -> Result<(), StagingError> { + let Some(writer) = self.disk.get_mut(key) else { + return Ok(()); + }; + let res = writer.flush_staged(); + if res.is_err() { + self.retire(key, deferred); + } + res + } + + /// Retires a writer on its first write/flush error so no later append + /// can drain partial bytes from the failed call into an acknowledged + /// prefix. Preserves any already-acknowledged prefix in `pending` so + /// earlier rows stay queryable until recovery/conversion. Batches staged + /// in the writer but not flushed are lost with it: their callers must be + /// told the error. + fn retire(&mut self, key: &str, deferred: &mut DeferredDrop) { + if let Some(mut writer) = self.disk.remove(key) { + let acknowledged = writer.acknowledged_len(); + let path = writer.path().to_path_buf(); + // Prevent DiskWriter::drop from renaming the `.part` file behind + // `mem.pending`'s back and truncate any unflushed/partial tail back + // to the last acknowledged message boundary. + writer.retire_failed(); + if let Some(mem) = self.mem.as_mut() + && let Some(mut segment) = mem.segments.remove(key) + { + let start = segment + .disk + .as_ref() + .filter(|d| d.path == path) + .map_or(0, |d| d.start); + segment.take_cached(deferred); + if acknowledged > start { + mem.pending.entry(path).or_default().push(PendingSource { + start, + len: acknowledged, + previous: None, + }); } } } - res } - #[cfg_attr(feature = "hotpath", hotpath::measure)] - pub(crate) fn push_disk_ref<'a>( + /// `push_disk_ref` with the batch optionally pre-encoded, and optionally + /// left staged instead of flushed. + #[allow(clippy::too_many_arguments)] + fn append_disk<'a>( &mut self, filename: &'a str, rb: &RecordBatch, + preencoded: Option<&PreEncodedBatch>, file_path: PathBuf, range: TimeRange, + flush: bool, + deferred: &mut DeferredDrop, ) -> Result, StagingError> { enum Action { WriteExisting, @@ -206,15 +539,24 @@ impl Writer { }; let sibling = match action { Action::WriteExisting => { - self.write_or_retire(filename, rb)?; + self.write_or_retire(filename, rb, preencoded, flush, deferred)?; return Ok(Cow::Borrowed(filename)); } Action::WriteReordered(reordered) => { - self.write_or_retire(filename, &reordered)?; + // Bytes encoded in the batch's own column order do not fit + // this stream: encode the reordered batch here. + self.write_or_retire(filename, &reordered, None, flush, deferred)?; return Ok(Cow::Borrowed(filename)); } Action::OpenNew => { - self.open_disk_writer(filename.to_owned(), rb, file_path, range)?; + self.open_disk_writer( + filename.to_owned(), + rb, + preencoded, + file_path, + range, + flush, + )?; return Ok(Cow::Borrowed(filename)); } Action::TrySibling(sibling) => sibling, @@ -227,7 +569,7 @@ impl Writer { .get(&key) .is_some_and(|writer| writer.has_schema(rb.schema_ref())) { - self.write_or_retire(&key, rb)?; + self.write_or_retire(&key, rb, preencoded, flush, deferred)?; return Ok(Cow::Owned(key)); } // Open a new sibling under the first free key. This walks the keys in @@ -240,7 +582,7 @@ impl Writer { } let mut path = file_path; path.set_file_name(&key); - self.open_disk_writer(key.clone(), rb, path, range)?; + self.open_disk_writer(key.clone(), rb, preencoded, path, range, flush)?; if let Some(writer) = self.disk.get_mut(filename) { writer.siblings.insert(rb.schema(), key.clone()); } @@ -251,6 +593,10 @@ impl Writer { /// tail of that file's rows, while the memory staging budget allows. /// The disk write comes first: a cached row is always already durable, /// so the cache can drop it at any time and serve the file instead. + /// + /// Ingestion writes through `push_group`; this is its one-batch form, + /// flushing the batch and freeing evicted batches in place. + #[cfg_attr(not(test), allow(dead_code))] pub(crate) fn push_disk_and_memory( &mut self, filename: &str, @@ -259,29 +605,147 @@ impl Writer { file_path: PathBuf, range: TimeRange, ) -> Result<(), StagingError> { - let key = self.push_disk_ref(filename, rb, file_path, range)?; + self.push_staged( + filename, + schema_key, + rb, + None, + file_path, + range, + true, + &mut DeferredDrop::inline(), + ) + .map(|_| ()) + } + + /// Appends `rb` to its staging file and caches it, returning the key of + /// the writer that took it. Without `flush` the batch is only staged: + /// the cache then runs ahead of the file until the caller flushes the + /// writer, which it must do, or retire it, before releasing the writer + /// lock. Batches the cache gives up go to `deferred`. + #[allow(clippy::too_many_arguments)] + fn push_staged<'a>( + &mut self, + filename: &'a str, + schema_key: &str, + rb: &RecordBatch, + preencoded: Option<&PreEncodedBatch>, + file_path: PathBuf, + range: TimeRange, + flush: bool, + deferred: &mut DeferredDrop, + ) -> Result, StagingError> { + 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.push_for_disk_file( - &key, + Some(writer) => mem.segment(&key).push_disk_backed( schema_key, rb, writer.path(), writer.last_batch_start(), - writer.acknowledged_len(), + writer.staged_len(), + deferred, )?, None => mem.push_for_file(&key, schema_key, rb)?, } } - Ok(()) + Ok(key) + } + + /// Writes a group of batches and flushes each staging file it touched + /// once, after the last batch, instead of once per batch. Returns one + /// result per push, in order. A batch is acknowledged (`Ok`) only when + /// the flush that covers it succeeded, so every acknowledged row has + /// reached the file, exactly as with one flush per batch. + /// + /// A failed append or flush retires its writer. Every batch still staged + /// in that writer then fails with the same error, while batches flushed + /// by earlier groups stay acknowledged and queryable. Later batches of + /// the group open a new file and are unaffected. + /// + /// Batches the memory cache gives up, by eviction or a retired writer, + /// are moved to `deferred`: drop it after releasing the writer lock. + pub(crate) fn push_group( + &mut self, + pushes: Vec>, + deferred: &mut DeferredDrop, + ) -> Vec> { + let mut results: Vec> = Vec::with_capacity(pushes.len()); + // Pushes staged in a writer and not flushed yet, by writer key. A + // group rarely touches more than one file. + let mut staged: Vec<(String, Vec)> = Vec::new(); + for (index, push) in pushes.into_iter().enumerate() { + let Some(file) = push.file else { + results.push(match self.mem.as_mut() { + Some(mem) => mem.push(push.schema_key, push.batch), + None => Ok(()), + }); + continue; + }; + match self.push_staged( + file.name, + push.schema_key, + push.batch, + push.preencoded, + file.path, + file.range, + false, + deferred, + ) { + Ok(key) => { + match staged.iter_mut().find(|(staged_key, _)| *staged_key == key) { + Some((_, indexes)) => indexes.push(index), + None => staged.push((key.into_owned(), vec![index])), + } + results.push(Ok(())); + } + Err(err) => { + // The failed append retired its writer, if it had one: + // what was staged in it is gone too. + let mut lost = Vec::new(); + staged.retain_mut(|(key, indexes)| { + let open = self.disk.contains_key(key); + if !open { + lost.append(indexes); + } + open + }); + if lost.is_empty() { + results.push(Err(err)); + } else { + let err = Arc::new(err); + for index in lost { + results[index] = Err(StagingError::CombinedPush(Arc::clone(&err))); + } + results.push(Err(StagingError::CombinedPush(err))); + } + } + } + } + for (key, indexes) in staged { + if let Err(err) = self.flush_or_retire(&key, deferred) { + let err = Arc::new(err); + for index in indexes { + results[index] = Err(StagingError::CombinedPush(Arc::clone(&err))); + } + } + } + results } /// Drops every cached batch whose rows are on disk, keeping them /// queryable from their staging files. Returns the bytes released. pub fn evict_pending_or_segments(&mut self) -> usize { + self.evict_pending_or_segments_deferred(&mut DeferredDrop::inline()) + } + + /// `evict_pending_or_segments`, moving the batches to `deferred` instead + /// of freeing them: the bytes are released from the budget here, and the + /// caller drops `deferred` after releasing the writer lock. + pub fn evict_pending_or_segments_deferred(&mut self, deferred: &mut DeferredDrop) -> usize { self.mem .as_mut() - .map_or(0, MemWriter::evict_pending_or_segments) + .map_or(0, |mem| mem.evict_pending_or_segments_deferred(deferred)) } /// Captures the staged rows for a query: cached batches and the staging @@ -298,14 +762,19 @@ impl Writer { &mut self, key: String, rb: &RecordBatch, + preencoded: Option<&PreEncodedBatch>, file_path: PathBuf, range: TimeRange, + flush: bool, ) -> Result<(), StagingError> { if let Some(parent) = file_path.parent() { fs::create_dir_all(parent)?; } let mut writer = DiskWriter::try_new_shared(file_path, rb.schema(), range)?; - writer.write(rb)?; + writer.append(rb, preencoded)?; + if flush { + writer.flush_staged()?; + } self.disk.insert(key, writer); Ok(()) } @@ -322,7 +791,7 @@ impl Writer { now: DateTime, ) -> HashMap { let flushable_disk = self.split_flushable_disk(forced, now); - self.compact_memory(); + self.compact_memory(&mut DeferredDrop::inline()); flushable_disk } @@ -332,15 +801,30 @@ impl Writer { /// batches of its segment are dropped. The caller must seal the writers /// and follow their files with `MemWriter::rekey_pending` until their rows /// are published in Parquet or discarded. + #[cfg_attr(not(test), allow(dead_code))] pub(crate) fn detach_flushable_disk_at( &mut self, forced: bool, now: DateTime, + ) -> Vec { + self.detach_flushable_disk_deferred_at(forced, now, &mut DeferredDrop::inline()) + } + + /// `detach_flushable_disk_at`, moving the cached batches of the detached + /// segments to `deferred` instead of freeing them. A minute's cache can + /// hold gigabytes: its bytes are released from the budget here, and the + /// caller drops `deferred` after releasing the writer lock, so pushes do + /// not wait for the allocator at every rollover. + pub(crate) fn detach_flushable_disk_deferred_at( + &mut self, + forced: bool, + now: DateTime, + deferred: &mut DeferredDrop, ) -> Vec { let flushable_disk = self.split_flushable_disk(forced, now); if let Some(mem) = self.mem.as_mut() { for (filename, writer) in &flushable_disk { - if let Some(segment) = mem.segments.remove(filename) { + if let Some(mut segment) = mem.segments.remove(filename) { // The file holds every row of the segment from its start, // cached or not: serve the file from now on. let start = segment @@ -348,6 +832,7 @@ impl Writer { .as_ref() .filter(|disk| disk.path == writer.path) .map_or(0, |disk| disk.start); + segment.take_cached(deferred); drop(segment); let len = writer.acknowledged_len(); if len > start { @@ -363,7 +848,7 @@ impl Writer { } } } - self.compact_memory(); + self.compact_memory(deferred); flushable_disk.into_values().collect() } @@ -375,6 +860,27 @@ impl Writer { .collect() } + /// Whether `mem.pending` currently tracks any detached/retired `.part` + /// files awaiting recovery (O(pending) in-memory check, zero disk I/O). + pub(crate) fn has_pending_part_files(&self) -> bool { + self.mem.as_ref().is_some_and(|mem| { + mem.pending.keys().any(|path| { + path.extension() + .is_some_and(|ext| ext == PART_FILE_EXTENSION) + }) + }) + } + + #[cfg(test)] + pub(crate) fn disk_keys_for_test(&self) -> Vec { + self.disk.keys().cloned().collect() + } + + #[cfg(test)] + pub(crate) fn retire_for_test(&mut self, key: &str, deferred: &mut DeferredDrop) { + self.retire(key, deferred); + } + fn split_flushable_disk( &mut self, forced: bool, @@ -392,13 +898,19 @@ impl Writer { flushable_disk } - fn compact_memory(&mut self) { + fn compact_memory(&mut self, deferred: &mut DeferredDrop) { if let Some(mem) = self.mem.as_mut() { // Use the selected writer keys, not a second clock/range check. // Query-only segments have no disk owner and expire at each flush. - mem.clear_unsegmented(); - mem.segments - .retain(|filename, _| self.disk.contains_key(filename)); + mem.take_cached(deferred); + let disk = &self.disk; + mem.segments.retain(|filename, segment| { + let owned = disk.contains_key(filename); + if !owned { + segment.take_cached(deferred); + } + owned + }); if mem.segments.is_empty() { // clear/retain alone keep the burst's bucket allocation alive. mem.segments = HashMap::new(); @@ -436,16 +948,26 @@ pub(crate) struct SealedPart { struct CountingFile { file: File, written: u64, + // Set when the writer is retired after an append/flush failure so + // `BufWriter::drop` cannot flush stale unacknowledged bytes back onto the + // truncated file. + retired: bool, } impl Write for CountingFile { fn write(&mut self, buf: &[u8]) -> std::io::Result { + if self.retired { + return Ok(buf.len()); + } let written = self.file.write(buf)?; self.written = self.written.saturating_add(written as u64); Ok(written) } fn flush(&mut self) -> std::io::Result<()> { + if self.retired { + return Ok(()); + } self.file.flush() } } @@ -466,9 +988,17 @@ pub struct DiskWriter { // a batch is written and flushed, so it always ends on an IPC message // boundary, and a failed write leaves it at the last complete batch. acknowledged: u64, - // `acknowledged` before the last successful write: where that batch's + // End of the last batch appended, counting bytes still in the buffer. + // Ahead of `acknowledged` only between an `append` and the flush that + // acknowledges it, within one hold of the stream's writer lock. + staged: u64, + // `staged` before the last successful append: where that batch's // messages begin. last_batch_start: u64, + // Codec of this stream's compressed messages. + compression: StagingIpcCompression, + #[cfg(test)] + flushes: usize, // Set once `seal` has taken over finishing and renaming from Drop. sealed: bool, } @@ -504,11 +1034,7 @@ impl SmallBatchEncoder { } fn for_schema(schema: &Schema) -> Option { - if schema - .flattened_fields() - .iter() - .any(|field| matches!(field.data_type(), arrow_schema::DataType::Dictionary(_, _))) - { + if has_dictionary(schema) { return None; } let options = IpcWriteOptions::default(); @@ -541,16 +1067,31 @@ impl DiskWriter { path: impl Into, schema: SchemaRef, range: TimeRange, + ) -> Result { + Self::try_new_with_compression(path, schema, range, *STAGING_IPC_COMPRESSION) + } + + /// `try_new_shared` with an explicit codec instead of the configured one. + pub(crate) fn try_new_with_compression( + path: impl Into, + schema: SchemaRef, + range: TimeRange, + compression: StagingIpcCompression, ) -> Result { let base = path.into(); // ONE_PARQUET_PER_ARROW is a rudimentary way to ensure one parquet per arrow file let (file, path) = Self::create_part_file(&base, *ONE_PARQUET_PER_ARROW)?; let inner = StreamWriter::try_new_with_options( - BufWriter::new(CountingFile { file, written: 0 }), + BufWriter::with_capacity( + DISK_WRITER_BUFFER_BYTES, + CountingFile { + file, + written: 0, + retired: false, + }, + ), &schema, - IpcWriteOptions::default() - .try_with_compression(Some(CompressionType::LZ4_FRAME)) - .unwrap(), + compression.write_options(), )?; Ok(Self { @@ -561,7 +1102,11 @@ impl DiskWriter { path, range, acknowledged: 0, + staged: 0, last_batch_start: 0, + compression, + #[cfg(test)] + flushes: 0, sealed: false, }) } @@ -641,6 +1186,24 @@ impl DiskWriter { } } + /// Retires a writer after an append/flush failure: suppresses `Drop`'s + /// automatic finish/rename (which would move the `.part` file away from + /// `mem.pending`'s recorded key), prevents `BufWriter::drop` from draining + /// unflushed bytes, and truncates any partial tail back to + /// `self.acknowledged` so neither queries nor recovery see unacknowledged + /// bytes. + pub(crate) fn retire_failed(&mut self) { + self.sealed = true; + let counting = self.inner.get_mut().get_mut(); + counting.retired = true; + if let Err(err) = counting.file.set_len(self.acknowledged) { + error!( + "Failed to truncate retired staging part {:?} back to {} acknowledged bytes: {err}", + self.path, self.acknowledged + ); + } + } + /// Finishes the IPC stream and chooses its `.arrows` name without renaming, /// so callers can move memory ownership to that name before conversion can /// see it. On error the part file is left for startup recovery. @@ -665,12 +1228,45 @@ impl DiskWriter { self.acknowledged } - /// Where the messages of the last acknowledged batch begin; `0` for the + /// Where the messages of the last appended batch begin; `0` for the /// first batch, whose bytes follow the schema message. pub(crate) fn last_batch_start(&self) -> u64 { self.last_batch_start } + /// Length of the IPC stream up to and including the last appended batch. + /// Equal to `acknowledged_len` except while a group of batches is staged + /// and not flushed yet. + pub(crate) fn staged_len(&self) -> u64 { + self.staged + } + + /// The codec of this file's compressed messages. + pub fn compression(&self) -> StagingIpcCompression { + self.compression + } + + /// Flushes of this file so far. + #[cfg(test)] + pub(crate) fn flush_count(&self) -> usize { + self.flushes + } + + /// Bytes handed to the stream so far, in the file or still buffered. + fn position(&self) -> u64 { + let sink = self.inner.get_ref(); + sink.get_ref() + .written + .saturating_add(sink.buffer().len() as u64) + } + + /// Whether `preencoded` can be appended to this stream as the bytes of + /// `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) + } + /// Returns whether this writer belongs to the current time range. pub fn is_current(&self) -> bool { self.range.contains(Utc::now()) @@ -679,20 +1275,60 @@ impl DiskWriter { /// Write a single recordbatch into file #[cfg_attr(feature = "hotpath", hotpath::measure)] pub fn write(&mut self, rb: &RecordBatch) -> Result<(), StagingError> { - if let Some(small) = self.small.as_mut().filter(|_| { - rb.num_rows() < MIN_COMPRESSED_BATCH_ROWS - && rb.get_array_memory_size() < MAX_UNCOMPRESSED_BATCH_BYTES - }) { + self.write_preencoded(rb, None) + } + + /// `write`, taking the batch's message from `preencoded` when that was + /// encoded from a batch of this file's exact schema: its bytes are then + /// copied into the stream without encoding `rb` again. Otherwise (no + /// bytes, another schema or column order, a schema with dictionaries) + /// `rb` is encoded here, as by `write`. + pub fn write_preencoded( + &mut self, + rb: &RecordBatch, + preencoded: Option<&PreEncodedBatch>, + ) -> Result<(), StagingError> { + self.append(rb, preencoded)?; + self.flush_staged() + } + + /// Appends `rb` to the stream without flushing or acknowledging it. The + /// batch may sit in the userspace buffer: call `flush_staged` before + /// acknowledging it to anyone. A writer whose append failed may hold + /// partial bytes and must not be written to again. + #[cfg_attr(feature = "hotpath", hotpath::measure)] + fn append( + &mut self, + rb: &RecordBatch, + preencoded: Option<&PreEncodedBatch>, + ) -> Result<(), StagingError> { + if let Some(preencoded) = preencoded.filter(|preencoded| self.accepts(preencoded, rb)) { + 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)?; } + self.last_batch_start = self.staged; + self.staged = self.position(); + Ok(()) + } + + /// Flushes every appended batch to the file and acknowledges them. + fn flush_staged(&mut self) -> Result<(), StagingError> { // A process crash does not run Drop, so do not leave the tail of an // acknowledged record batch only in BufWriter's userspace buffer. // The EOS marker can be recovered, but missing batch bytes cannot. self.inner.flush().map_err(StagingError::Arrow)?; - self.last_batch_start = self.acknowledged; self.acknowledged = self.inner.get_ref().get_ref().written; + self.staged = self.acknowledged; + #[cfg(test)] + { + self.flushes += 1; + } Ok(()) } } @@ -875,24 +1511,6 @@ impl MemWriter { self.segment(filename).push(schema_key, rb) } - /// Caches `rb`, just written to `path` whose acknowledged length is now - /// `acknowledged`, as the tail of segment `filename` if the budget allows. - /// Otherwise the segment drops its cached batches and serves the file's - /// whole acknowledged prefix from disk; it caches again once the budget - /// has room, as the tail after that prefix. - pub(crate) fn push_for_disk_file( - &mut self, - filename: &str, - schema_key: &str, - rb: &RecordBatch, - path: &Path, - batch_start: u64, - acknowledged: u64, - ) -> Result<(), StagingError> { - self.segment(filename) - .push_disk_backed(schema_key, rb, path, batch_start, acknowledged) - } - fn segment(&mut self, filename: &str) -> &mut Self { if !self.segments.contains_key(filename) { let segment = Self::with_budget(Arc::clone(&self.budget)); @@ -903,6 +1521,11 @@ impl MemWriter { .expect("segment was just inserted") } + /// 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. fn push_disk_backed( &mut self, schema_key: &str, @@ -910,6 +1533,7 @@ impl MemWriter { path: &Path, batch_start: u64, acknowledged: u64, + deferred: &mut DeferredDrop, ) -> Result<(), StagingError> { match self.disk.as_mut() { Some(disk) if disk.path == path => disk.acknowledged = acknowledged, @@ -919,7 +1543,7 @@ impl MemWriter { // alongside this one. // The segment covers its file from this batch on: a segment // created after `clear` must not resurrect cleared rows. - self.drop_cached(); + self.take_cached(deferred); let start = batch_start; self.disk = Some(SegmentDisk { path: path.to_path_buf(), @@ -941,27 +1565,34 @@ impl MemWriter { %err, "In-memory staging cache update failed after disk append; falling back to disk reads" ); - self.evict_to_disk(); + self.evict_to_disk(deferred); } Ok(()) } else { - self.evict_to_disk(); + self.evict_to_disk(deferred); Ok(()) } } /// Serves every acknowledged row of this segment's file from disk and - /// drops its cached batches. Returns the bytes released. - fn evict_to_disk(&mut self) -> usize { + /// moves its cached batches to `deferred`. Returns the bytes released. + fn evict_to_disk(&mut self, deferred: &mut DeferredDrop) -> usize { let Some(disk) = self.disk.as_mut() else { return 0; }; disk.evicted = disk.acknowledged; - self.drop_cached() + self.take_cached(deferred) } - fn drop_cached(&mut self) -> usize { + /// Empties this writer's own buffers into `deferred` and releases their + /// bytes from the budget at once. The batches are freed whenever + /// `deferred` is dropped; nothing is left for this writer's own `Drop` to + /// subtract, so the bytes are never released twice. Returns the bytes + /// released. + fn take_cached(&mut self, deferred: &mut DeferredDrop) -> usize { let released = self.accounted; + deferred.take(&mut self.read_buffer, released); + deferred.take(&mut self.mutable_buffer.inner, 0); self.clear_unsegmented(); released } @@ -970,9 +1601,15 @@ impl MemWriter { /// rows hold no batches; memory-only rows (query mode) stay. Returns the /// bytes released. pub fn evict_pending_or_segments(&mut self) -> usize { + self.evict_pending_or_segments_deferred(&mut DeferredDrop::inline()) + } + + /// `evict_pending_or_segments`, moving the batches to `deferred` instead + /// of freeing them here. + pub fn evict_pending_or_segments_deferred(&mut self, deferred: &mut DeferredDrop) -> usize { self.segments .values_mut() - .map(MemWriter::evict_to_disk) + .map(|segment| segment.evict_to_disk(deferred)) .sum() } @@ -2917,3 +3554,1063 @@ mod track_e { assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 33); } } + +#[cfg(test)] +mod staged_group_tests { + use std::{ + fs::File, + io::Cursor, + sync::Arc, + time::{Duration, Instant}, + }; + + use arrow_array::{Array, ArrayRef, Int32Array, RecordBatch, StringArray}; + use arrow_ipc::reader::StreamReader; + use arrow_schema::{DataType, Field, Schema}; + use chrono::Utc; + use temp_dir::TempDir; + + use super::*; + use crate::{ + OBJECT_STORE_DATA_GRANULARITY, + parseable::staging::reader::{ + MergedForwardRecordReader, get_forward_reader, get_reverse_reader, + }, + }; + + const FILE: &str = "ids.date=2020-01-02.data.arrows"; + + fn current() -> TimeRange { + TimeRange::granularity_range(Utc::now(), OBJECT_STORE_DATA_GRANULARITY) + } + + fn id_schema() -> Arc { + Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])) + } + + fn ids_batch(ids: std::ops::Range) -> RecordBatch { + RecordBatch::try_new( + id_schema(), + vec![Arc::new(Int32Array::from_iter_values(ids))], + ) + .unwrap() + } + + fn ids_of(batches: &[RecordBatch]) -> Vec { + batches + .iter() + .flat_map(|batch| { + let index = batch.schema().index_of("id").unwrap(); + batch + .column(index) + .as_any() + .downcast_ref::() + .unwrap() + .values() + .to_vec() + }) + .collect() + } + + fn writer(budget: &Arc) -> Writer { + Writer { + mem: Some(MemWriter::with_budget(Arc::clone(budget))), + disk: Default::default(), + } + } + + fn staged<'a>( + dir: &TempDir, + batch: &'a RecordBatch, + preencoded: Option<&'a PreEncodedBatch>, + ) -> StagedPush<'a> { + StagedPush { + file: Some(StagedFile { + name: FILE, + path: dir.path().join(FILE), + range: current(), + }), + schema_key: "id", + batch, + preencoded, + } + } + + fn captured(writer: &Writer) -> Vec { + let schema = id_schema(); + let mut ids = ids_of( + &writer + .capture(&schema) + .unwrap() + .into_record_batches(&schema) + .unwrap(), + ); + ids.sort_unstable(); + ids + } + + fn read_all(bytes: &[u8]) -> Vec { + StreamReader::try_new(Cursor::new(bytes), None) + .unwrap() + .collect::, _>>() + .unwrap() + } + + /// Offsets at which each record batch message of `bytes` ends. + fn batch_ends(bytes: &[u8], batches: usize) -> Vec { + let mut cursor = Cursor::new(bytes); + let mut ends = Vec::new(); + let mut reader = StreamReader::try_new(&mut cursor, None).unwrap(); + for _ in 0..batches { + reader.next().unwrap().unwrap(); + ends.push(reader.get_ref().position() as usize); + } + ends + } + + /// Batches on both sides of the compression cutoffs, with nulls and + /// slices: uncompressed small ones between compressed large ones. + fn mixed_batches() -> Vec { + let strings = (0..6000) + .map(|i| (i % 3 != 0).then(|| format!("value {i}"))) + .collect::>(); + let wide = RecordBatch::try_from_iter([ + ( + "text", + Arc::new(StringArray::from(strings)) as Arc, + ), + ( + "id", + Arc::new(Int32Array::from_iter( + (0..6000).map(|i| (i % 7 != 0).then_some(i)), + )) as Arc, + ), + ]) + .unwrap(); + vec![ + wide.slice(1, 1), + wide.slice(3, 1000), + wide.slice(7, 10), + wide.slice(9, 100), + wide.slice(0, 99), + wide.slice(500, 5000), + wide.slice(5999, 1), + ] + } + + #[test] + fn staging_ipc_compression_parses_lz4_and_zstd() { + for (value, expected) in [ + ("lz4", StagingIpcCompression::Lz4), + (" LZ4 ", StagingIpcCompression::Lz4), + ("lz4_frame", StagingIpcCompression::Lz4), + ("", StagingIpcCompression::Lz4), + ("zstd", StagingIpcCompression::Zstd), + ("ZSTD", StagingIpcCompression::Zstd), + ] { + assert_eq!(value.parse::().unwrap(), expected); + } + 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. + if std::env::var_os(STAGING_IPC_COMPRESSION_VAR).is_none() { + assert_eq!(*STAGING_IPC_COMPRESSION, StagingIpcCompression::Lz4); + } + } + + #[test] + fn preencoded_messages_are_the_bytes_the_writer_encodes() { + let batches = mixed_batches(); + let schema = batches[0].schema(); + let mut sizes = Vec::new(); + for compression in StagingIpcCompression::ALL { + let dir = TempDir::new().unwrap(); + let mut encoded_here = DiskWriter::try_new_with_compression( + dir.path().join("inline.data.arrows"), + schema.clone(), + current(), + compression, + ) + .unwrap(); + let mut encoded_ahead = DiskWriter::try_new_with_compression( + dir.path().join("ahead.data.arrows"), + schema.clone(), + current(), + compression, + ) + .unwrap(); + assert_eq!(encoded_ahead.compression(), compression); + let mut offsets = vec![]; + for batch in &batches { + encoded_here.write(batch).unwrap(); + let preencoded = PreEncodedBatch::encode_with(batch, compression) + .unwrap() + .expect("no dictionaries"); + assert!(!preencoded.is_empty()); + let before = encoded_ahead.acknowledged_len(); + encoded_ahead + .write_preencoded(batch, Some(&preencoded)) + .unwrap(); + // The message, and nothing else, was appended. (The first + // batch's range also covers the schema message.) + if before > 0 { + assert_eq!(encoded_ahead.last_batch_start(), before); + assert_eq!( + encoded_ahead.acknowledged_len() - before, + preencoded.len() as u64 + ); + } + offsets.push(( + encoded_ahead.last_batch_start(), + encoded_ahead.acknowledged_len(), + )); + assert_eq!( + encoded_ahead.acknowledged_len(), + encoded_here.acknowledged_len() + ); + } + let part = encoded_ahead.path().to_path_buf(); + // Sources over acknowledged prefixes of the open file: all rows, + // then the rows from every later batch on. + for (index, (start, _)) in offsets.iter().enumerate() { + let (_, len) = offsets[offsets.len() - 1]; + let source = StagingDiskSource::open_first(&[part.as_path()], *start, len).unwrap(); + for reverse in [false, true] { + let mut expected = batches[index..].to_vec(); + if reverse { + expected.reverse(); + } + assert_eq!( + source + .reader(reverse) + .unwrap() + .collect::, _>>() + .unwrap(), + expected, + "{compression:?} from batch {index}, reverse {reverse}" + ); + } + } + let inline_part = encoded_here.seal().unwrap_or_else(|(_, e)| panic!("{e}")); + let ahead_part = encoded_ahead.seal().unwrap_or_else(|(_, e)| panic!("{e}")); + let bytes = std::fs::read(&ahead_part.part).unwrap(); + assert_eq!( + bytes, + std::fs::read(&inline_part.part).unwrap(), + "{compression:?}: pre-encoded bytes differ from the writer's" + ); + assert_eq!(read_all(&bytes), batches); + assert_eq!( + get_forward_reader(Cursor::new(&bytes)) + .unwrap() + .collect::, _>>() + .unwrap(), + batches + ); + // The reader Parquet conversion uses on the sealed file. + std::fs::rename(&ahead_part.part, &ahead_part.arrow).unwrap(); + let plan = MergedForwardRecordReader::try_new(std::slice::from_ref(&ahead_part.arrow)) + .into_file_plans() + .next() + .unwrap(); + assert_eq!( + plan.open_lanes(1) + .unwrap() + .pop() + .unwrap() + .reader + .collect::, _>>() + .unwrap(), + batches + ); + let mut reversed = batches.clone(); + reversed.reverse(); + assert_eq!( + get_reverse_reader(Cursor::new(&bytes)) + .unwrap() + .collect::, _>>() + .unwrap(), + reversed + ); + // A crash anywhere inside the last messages recovers the batches + // before them, in both directions: at a message boundary, inside + // the metadata, inside a compressed body, and short of the end. + let ends = batch_ends(&bytes, batches.len()); + for kept in [batches.len() - 1, batches.len() - 2] { + let boundary = ends[kept - 1]; + let inside_body = (boundary + ends[kept]) / 2; + for cut in [boundary, boundary + 4, inside_body, ends[kept] - 9] { + let truncated = &bytes[..cut]; + assert_eq!( + get_forward_reader(Cursor::new(truncated)) + .unwrap() + .collect::, _>>() + .unwrap(), + batches[..kept], + "{compression:?} cut at {cut}" + ); + let mut expected = batches[..kept].to_vec(); + expected.reverse(); + assert_eq!( + get_reverse_reader(Cursor::new(truncated)) + .unwrap() + .collect::, _>>() + .unwrap(), + expected, + "{compression:?} cut at {cut}" + ); + } + } + sizes.push((compression, bytes)); + } + // The codecs really differ on disk, and each file names its own. + let (_, lz4) = &sizes[0]; + let (_, zstd) = &sizes[1]; + assert_ne!(lz4, zstd); + const LZ4_FRAME_MAGIC: [u8; 4] = [0x04, 0x22, 0x4D, 0x18]; + const ZSTD_MAGIC: [u8; 4] = [0x28, 0xB5, 0x2F, 0xFD]; + let has = |bytes: &[u8], magic: [u8; 4]| bytes.windows(4).any(|window| window == magic); + assert!(has(lz4, LZ4_FRAME_MAGIC) && !has(lz4, ZSTD_MAGIC)); + assert!(has(zstd, ZSTD_MAGIC) && !has(zstd, LZ4_FRAME_MAGIC)); + } + + #[test] + fn one_file_may_mix_codecs_and_uncompressed_batches() { + // A restart with another `P_STAGING_IPC_COMPRESSION` appends to no + // old file, but one stream of messages may still carry every codec: + // each message names its own. + let batches = mixed_batches(); + let dir = TempDir::new().unwrap(); + let mut writer = DiskWriter::try_new_with_compression( + dir.path().join("mixed.data.arrows"), + batches[0].schema(), + current(), + StagingIpcCompression::Lz4, + ) + .unwrap(); + for (index, batch) in batches.iter().enumerate() { + let compression = StagingIpcCompression::ALL[index % 2]; + let preencoded = PreEncodedBatch::encode_with(batch, compression) + .unwrap() + .unwrap(); + if index % 3 == 0 { + writer.write(batch).unwrap(); + } else { + writer.write_preencoded(batch, Some(&preencoded)).unwrap(); + } + } + let len = writer.acknowledged_len(); + let source = StagingDiskSource::open_first(&[writer.path()], 0, len).unwrap(); + assert_eq!( + source + .reader(false) + .unwrap() + .collect::, _>>() + .unwrap(), + batches + ); + let sealed = writer.seal().unwrap_or_else(|(_, e)| panic!("{e}")); + let bytes = std::fs::read(sealed.part).unwrap(); + assert_eq!(read_all(&bytes), batches); + let mut reversed = batches.clone(); + reversed.reverse(); + assert_eq!( + get_reverse_reader(Cursor::new(&bytes)) + .unwrap() + .collect::, _>>() + .unwrap(), + reversed + ); + } + + #[test] + fn preencoding_leaves_small_and_dictionary_batches_to_the_writer() { + use arrow_array::{DictionaryArray, types::Int32Type}; + // Small batches are cheap to encode and are combined in the queue. + assert!(PreEncodedBatch::for_push(&ids_batch(0..99)).is_none()); + assert!(PreEncodedBatch::for_push(&ids_batch(0..100)).is_some()); + // The explicit helper encodes them too, uncompressed like the writer. + let small = PreEncodedBatch::encode_with(&ids_batch(0..3), StagingIpcCompression::Zstd) + .unwrap() + .unwrap(); + let large = PreEncodedBatch::encode_with(&ids_batch(0..3000), StagingIpcCompression::Zstd) + .unwrap() + .unwrap(); + assert!(small.len() < large.len()); + + let dictionary = RecordBatch::try_from_iter([( + "dict", + Arc::new(DictionaryArray::::from_iter( + (0..1000).map(|_| "same"), + )) as ArrayRef, + )]) + .unwrap(); + for compression in StagingIpcCompression::ALL { + assert!( + PreEncodedBatch::encode_with(&dictionary, compression) + .unwrap() + .is_none() + ); + } + assert!(PreEncodedBatch::for_push(&dictionary).is_none()); + + // A dictionary stream ignores bytes offered to it and encodes the + // batch itself, keeping its dictionary messages in order. + let dir = TempDir::new().unwrap(); + let path = dir.path().join("dictionary.data.arrows"); + let mut writer = DiskWriter::try_new(&path, &dictionary.schema(), current()).unwrap(); + let foreign = PreEncodedBatch { + schema: dictionary.schema(), + rows: dictionary.num_rows(), + bytes: b"not an IPC message".to_vec(), + }; + writer + .write_preencoded(&dictionary, Some(&foreign)) + .unwrap(); + writer.write_preencoded(&dictionary, None).unwrap(); + drop(writer); + assert_eq!( + read_all(&std::fs::read(path).unwrap()), + vec![dictionary.clone(), dictionary] + ); + } + + #[test] + fn preencoded_bytes_of_another_schema_or_column_order_are_not_written() { + let dir = TempDir::new().unwrap(); + let fields = [ + Field::new("a", DataType::Int32, false), + Field::new("b", DataType::Utf8, true), + ]; + let columns: [ArrayRef; 2] = [ + Arc::new(Int32Array::from_iter_values(0..500)), + Arc::new(StringArray::from_iter_values( + (0..500).map(|i| format!("row {i}")), + )), + ]; + let ordered = + RecordBatch::try_new(Arc::new(Schema::new(fields.to_vec())), columns.to_vec()).unwrap(); + let reordered = RecordBatch::try_new( + Arc::new(Schema::new(vec![fields[1].clone(), fields[0].clone()])), + vec![columns[1].clone(), columns[0].clone()], + ) + .unwrap(); + let nullable = RecordBatch::try_new( + Arc::new(Schema::new(vec![ + Field::new("a", DataType::Int32, true), + fields[1].clone(), + ])), + columns.to_vec(), + ) + .unwrap(); + let encode = |batch: &RecordBatch| PreEncodedBatch::for_push(batch).unwrap(); + + // DiskWriter: bytes for another schema, or for other rows, are + // ignored and the batch given is the one encoded. + let mut direct = DiskWriter::try_new( + dir.path().join("direct.data.arrows"), + &ordered.schema(), + current(), + ) + .unwrap(); + direct + .write_preencoded(&ordered, Some(&encode(&reordered))) + .unwrap(); + direct + .write_preencoded(&ordered, Some(&encode(&ordered.slice(0, 200)))) + .unwrap(); + direct + .write_preencoded(&ordered, Some(&encode(&ordered))) + .unwrap(); + let sealed = direct.seal().unwrap_or_else(|(_, e)| panic!("{e}")); + assert_eq!( + read_all(&std::fs::read(sealed.part).unwrap()), + vec![ordered.clone(), ordered.clone(), ordered.clone()] + ); + + // Writer: a reordered batch joins the file in the file's column + // order, re-encoded; another nullability goes to a sibling file, + // where its own bytes fit as they are. + let budget = StagingMemoryBudget::new(0); + let mut writer = writer(&budget); + let (first, second, third) = (encode(&ordered), encode(&reordered), encode(&nullable)); + let name = "k.date=2020-01-02.data.arrows"; + let push = |batch, preencoded| StagedPush { + file: Some(StagedFile { + name, + path: dir.path().join(name), + range: current(), + }), + schema_key: "k", + batch, + preencoded: Some(preencoded), + }; + let results = writer.push_group( + vec![ + push(&ordered, &first), + push(&reordered, &second), + push(&nullable, &third), + push(&reordered, &second), + ], + &mut DeferredDrop::default(), + ); + assert!(results.iter().all(Result::is_ok), "{results:?}"); + assert_eq!(writer.disk.len(), 2); + let paths = writer + .disk + .iter() + .map(|(key, disk)| (key.clone(), disk.path().to_path_buf())) + .collect::>(); + drop(writer); + // Dropping the writers finished their parts as `.arrows` files. + let read = |key: &str| read_all(&std::fs::read(paths[key].with_extension("")).unwrap()); + assert_eq!( + read(name), + vec![ordered.clone(), ordered.clone(), ordered.clone()] + ); + assert_eq!(read("k-1.date=2020-01-02.data.arrows"), vec![nullable]); + } + + #[test] + fn group_is_flushed_once_and_acknowledged_exactly() { + let dir = TempDir::new().unwrap(); + let budget = StagingMemoryBudget::new(1 << 30); + let mut writer = writer(&budget); + let batches = [0..2500, 2500..2501, 2501..9000, 9000..9099] + .map(ids_batch) + .to_vec(); + let encoded = batches + .iter() + .map(PreEncodedBatch::for_push) + .collect::>(); + assert_eq!( + encoded.iter().map(Option::is_some).collect::>(), + [true, false, true, false] + ); + let results = writer.push_group( + batches + .iter() + .zip(&encoded) + .map(|(batch, preencoded)| staged(&dir, batch, preencoded.as_ref())) + .collect(), + &mut DeferredDrop::default(), + ); + assert!(results.iter().all(Result::is_ok), "{results:?}"); + let disk = &writer.disk[FILE]; + assert_eq!(disk.flush_count(), 1); + // Everything acknowledged is in the file, with nothing left behind + // in the buffer. + let on_disk = std::fs::metadata(disk.path()).unwrap().len(); + assert_eq!(disk.acknowledged_len(), on_disk); + assert_eq!(disk.staged_len(), on_disk); + let file = read_all(&std::fs::read(disk.path()).unwrap()[..on_disk as usize]); + // One message per batch: nothing was concatenated. + assert_eq!(file, batches); + assert_eq!(captured(&writer), (0..9099).collect::>()); + + // A second group appends after the first, again with one flush, and + // the cache follows the file exactly: evicted, every row is read back + // from the acknowledged prefix. + let more = [9099..9100, 9100..12000].map(ids_batch); + let results = writer.push_group( + more.iter().map(|batch| staged(&dir, batch, None)).collect(), + &mut DeferredDrop::default(), + ); + assert!(results.iter().all(Result::is_ok)); + assert_eq!(writer.disk[FILE].flush_count(), 2); + let mut deferred = DeferredDrop::default(); + assert!(writer.evict_pending_or_segments_deferred(&mut deferred) > 0); + assert_eq!(budget.used(), 0); + let capture = writer.capture(&id_schema()).unwrap(); + assert!(capture.memory.is_empty()); + assert_eq!( + (capture.disk[0].start(), capture.disk[0].len()), + (0, writer.disk[FILE].acknowledged_len()) + ); + assert_eq!(captured(&writer), (0..12000).collect::>()); + } + + #[test] + fn cache_evicted_inside_a_group_is_served_from_the_flushed_file() { + let dir = TempDir::new().unwrap(); + let first = ids_batch(0..1000); + // Room for the first batch only: the second evicts mid-group, while + // both are still in the write buffer. + let budget = StagingMemoryBudget::new(first.get_array_memory_size() + 16); + let mut writer = writer(&budget); + let batches = [first, ids_batch(1000..2000), ids_batch(2000..3000)]; + let mut deferred = DeferredDrop::default(); + let results = writer.push_group( + batches + .iter() + .map(|batch| staged(&dir, batch, None)) + .collect(), + &mut deferred, + ); + assert!(results.iter().all(Result::is_ok)); + assert!(deferred.bytes() > 0 && !deferred.is_empty()); + assert_eq!(budget.used(), writer.mem.as_ref().unwrap().memory_bytes()); + let capture = writer.capture(&id_schema()).unwrap(); + assert_eq!(capture.disk.len(), 1); + assert!(capture.disk[0].len() <= writer.disk[FILE].acknowledged_len()); + assert_eq!(captured(&writer), (0..3000).collect::>()); + } + + fn full_device() -> File { + std::fs::OpenOptions::new() + .write(true) + .open("/dev/full") + .unwrap() + } + + #[test] + fn failed_group_flush_fails_every_staged_batch_and_keeps_the_acknowledged_prefix() { + let dir = TempDir::new().unwrap(); + let budget = StagingMemoryBudget::new(1 << 30); + let mut writer = writer(&budget); + let acknowledged = ids_batch(0..500); + writer + .push_group( + vec![staged(&dir, &acknowledged, None)], + &mut DeferredDrop::default(), + ) + .pop() + .unwrap() + .unwrap(); + let prefix = writer.disk[FILE].acknowledged_len(); + let part = writer.disk[FILE].path().to_path_buf(); + // Appends now stay in the buffer and the group's one flush fails. + writer + .disk + .get_mut(FILE) + .unwrap() + .inner + .get_mut() + .get_mut() + .file = full_device(); + let group = [ + ids_batch(500..501), + ids_batch(501..900), + ids_batch(900..901), + ]; + let mut deferred = DeferredDrop::default(); + let results = writer.push_group( + group + .iter() + .map(|batch| staged(&dir, batch, None)) + .collect(), + &mut deferred, + ); + assert_eq!(results.len(), 3); + for result in &results { + assert!( + matches!(result, Err(StagingError::CombinedPush(_))), + "{result:?}" + ); + } + // The writer is retired; rows acknowledged before the group are + // still served, from exactly their prefix of the file, and nothing + // of the failed group is. + assert!(writer.disk.is_empty()); + assert_eq!(budget.used(), 0); + assert!(deferred.bytes() > 0); + let capture = writer.capture(&id_schema()).unwrap(); + assert!(capture.memory.is_empty()); + assert_eq!( + (capture.disk[0].start(), capture.disk[0].len()), + (0, prefix) + ); + assert_eq!(capture.disk[0].path(), part.as_path()); + assert_eq!(captured(&writer), (0..500).collect::>()); + + // The next push opens a fresh part and the stream carries on. + let next = ids_batch(2000..2100); + writer + .push_group( + vec![staged(&dir, &next, None)], + &mut DeferredDrop::default(), + ) + .pop() + .unwrap() + .unwrap(); + assert_ne!(writer.disk[FILE].path(), part.as_path()); + assert_eq!( + captured(&writer), + (0..500).chain(2000..2100).collect::>() + ); + drop(deferred); + drop(writer); + assert_eq!(budget.used(), 0); + } + + #[test] + fn failed_append_fails_the_batches_staged_before_it_and_spares_the_ones_after() { + let dir = TempDir::new().unwrap(); + let budget = StagingMemoryBudget::new(1 << 30); + let mut writer = writer(&budget); + let acknowledged = ids_batch(0..10); + writer + .push_group( + vec![staged(&dir, &acknowledged, None)], + &mut DeferredDrop::default(), + ) + .pop() + .unwrap() + .unwrap(); + writer + .disk + .get_mut(FILE) + .unwrap() + .inner + .get_mut() + .get_mut() + .file = full_device(); + // Incompressible and larger than the write buffer: it reaches the + // file, and fails, in its own append rather than in the flush. + let noise = (0..200_000i32) + .map(|i| i.wrapping_mul(-1640531527) ^ (i << 13)) + .collect::>(); + let big = + RecordBatch::try_new(id_schema(), vec![Arc::new(Int32Array::from(noise))]).unwrap(); + let group = [ids_batch(10..20), big, ids_batch(30..40), ids_batch(40..45)]; + let results = writer.push_group( + group + .iter() + .map(|batch| staged(&dir, batch, None)) + .collect(), + &mut DeferredDrop::default(), + ); + assert!(matches!(results[0], Err(StagingError::CombinedPush(_)))); + assert!(matches!(results[1], Err(StagingError::CombinedPush(_)))); + // Written to a new part after the failure, flushed, acknowledged. + assert!(results[2].is_ok() && results[3].is_ok(), "{results:?}"); + assert_eq!(writer.disk[FILE].flush_count(), 1); + assert_eq!(captured(&writer), (0..10).chain(30..45).collect::>()); + drop(writer); + assert_eq!(budget.used(), 0); + } + + #[test] + fn lone_failure_keeps_its_own_error() { + // No directory can be created under a file: the open fails, nothing + // else is staged, and the caller sees the error itself. + let dir = TempDir::new().unwrap(); + let blocker = dir.path().join("blocker"); + std::fs::write(&blocker, b"").unwrap(); + let mut writer = writer(&StagingMemoryBudget::new(0)); + let batch = ids_batch(0..5); + let results = writer.push_group( + vec![StagedPush { + file: Some(StagedFile { + name: FILE, + path: blocker.join(FILE), + range: current(), + }), + schema_key: "id", + batch: &batch, + preencoded: None, + }], + &mut DeferredDrop::default(), + ); + assert!(matches!(results[0], Err(StagingError::ObjectStorage(_)))); + } + + #[test] + fn memory_only_pushes_join_a_group() { + let budget = StagingMemoryBudget::new(1 << 20); + let mut writer = writer(&budget); + let batch = ids_batch(0..7); + let results = writer.push_group( + vec![StagedPush { + file: None, + schema_key: "id", + batch: &batch, + preencoded: None, + }], + &mut DeferredDrop::default(), + ); + assert!(results[0].is_ok()); + assert!(writer.disk.is_empty()); + assert_eq!(captured(&writer), (0..7).collect::>()); + } + + /// Strong count of the batch's only column: `1` when nothing else holds + /// its data. + fn holders(batch: &RecordBatch) -> usize { + Arc::strong_count(batch.column(0)) + } + + #[test] + fn detach_moves_the_cache_out_and_settles_the_budget_at_once() { + let dir = TempDir::new().unwrap(); + let budget = StagingMemoryBudget::new(1 << 30); + let mut writer = writer(&budget); + let batch = ids_batch(0..1000); + // Query-only rows without a file expire at the same flush. + let ownerless = ids_batch(5000..5010); + writer + .push_group( + vec![staged(&dir, &batch, None)], + &mut DeferredDrop::default(), + ) + .pop() + .unwrap() + .unwrap(); + writer.mem.as_mut().unwrap().push("id", &ownerless).unwrap(); + let cached = budget.used(); + assert!(cached > 0); + assert_eq!((holders(&batch), holders(&ownerless)), (2, 2)); + + let mut deferred = DeferredDrop::default(); + let detached = writer.detach_flushable_disk_deferred_at(true, Utc::now(), &mut deferred); + assert_eq!(detached.len(), 1); + // Released from the budget while the batches are still alive... + assert_eq!(budget.used(), 0); + assert_eq!(writer.mem.as_ref().unwrap().memory_bytes(), 0); + assert_eq!(deferred.bytes(), cached); + assert_eq!((holders(&batch), holders(&ownerless)), (2, 2)); + // ...and their rows are served from the detached file meanwhile. + assert_eq!(captured(&writer), (0..1000).collect::>()); + // Freed only when the holder goes, with nothing subtracted twice. + drop(deferred); + assert_eq!((holders(&batch), holders(&ownerless)), (1, 1)); + assert_eq!(budget.used(), 0); + drop(detached); + drop(writer); + assert_eq!(budget.used(), 0); + } + + #[test] + fn eviction_moves_the_cache_out_and_settles_the_budget_at_once() { + let dir = TempDir::new().unwrap(); + let first = ids_batch(0..1000); + let budget = StagingMemoryBudget::new(first.get_array_memory_size() + 16); + let mut writer = writer(&budget); + let mut deferred = DeferredDrop::default(); + writer + .push_group(vec![staged(&dir, &first, None)], &mut deferred) + .pop() + .unwrap() + .unwrap(); + assert!(deferred.is_empty()); + assert_eq!(holders(&first), 2); + assert_eq!(budget.used(), first.get_array_memory_size()); + + // Over budget: the push evicts the segment into the holder. + let second = ids_batch(1000..2000); + writer + .push_group(vec![staged(&dir, &second, None)], &mut deferred) + .pop() + .unwrap() + .unwrap(); + assert_eq!(budget.used(), 0); + assert_eq!(deferred.bytes(), first.get_array_memory_size()); + assert_eq!((holders(&first), holders(&second)), (2, 1)); + assert_eq!(captured(&writer), (0..2000).collect::>()); + drop(deferred); + assert_eq!(holders(&first), 1); + + // Explicit eviction, as under memory pressure. + budget.set_limit(1 << 30); + let third = ids_batch(2000..3000); + writer + .push_group( + vec![staged(&dir, &third, None)], + &mut DeferredDrop::default(), + ) + .pop() + .unwrap() + .unwrap(); + assert_eq!(holders(&third), 2); + let mut deferred = DeferredDrop::default(); + let released = writer.evict_pending_or_segments_deferred(&mut deferred); + assert_eq!(released, third.get_array_memory_size()); + assert_eq!(deferred.bytes(), released); + assert_eq!(budget.used(), 0); + assert_eq!(holders(&third), 2); + drop(deferred); + assert_eq!(holders(&third), 1); + assert_eq!(captured(&writer), (0..3000).collect::>()); + drop(writer); + assert_eq!(budget.used(), 0); + } + + #[test] + fn large_evictions_are_freed_by_the_drop_thread() { + let batch = ids_batch(0..1000); + let mut holder = DeferredDrop::default(); + holder.take(&mut vec![batch.clone()], BACKGROUND_DROP_MIN_BYTES); + assert_eq!(holders(&batch), 2); + drop(holder); + // Handed over, not freed here: wait for the thread. + let deadline = Instant::now() + Duration::from_secs(30); + while holders(&batch) != 1 { + assert!(Instant::now() < deadline, "the drop thread freed nothing"); + std::thread::sleep(Duration::from_millis(1)); + } + + // Below the cutoff, and for callers that free in place, the batches + // are gone when the holder is. + let mut small = DeferredDrop::default(); + small.take(&mut vec![batch.clone()], BACKGROUND_DROP_MIN_BYTES - 1); + drop(small); + assert_eq!(holders(&batch), 1); + let mut inline = DeferredDrop::inline(); + inline.take(&mut vec![batch.clone()], usize::MAX); + drop(inline); + assert_eq!(holders(&batch), 1); + } + + #[test] + fn budget_matches_the_cache_through_every_deferred_path_and_returns_to_zero() { + let dir = TempDir::new().unwrap(); + // Tight enough that pushes evict, loose enough that some are cached. + let budget = StagingMemoryBudget::new(40_000); + let mut writer = writer(&budget); + let mut holders = Vec::new(); + let mut next = 0; + let mut expected = Vec::new(); + // A fixed pseudo-random walk over pushes, groups, evictions, detaches + // and clears, some dropping their holder at once and some keeping it. + let mut seed = 0x9E37_79B9_7F4A_7C15u64; + let mut roll = |bound: u64| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed % bound + }; + for step in 0..400 { + let mut deferred = DeferredDrop::default(); + match roll(10) { + 0..=4 => { + let batches = (0..1 + roll(4)) + .map(|_| { + let rows = [1, 50, 100, 700, 5000][roll(5) as usize]; + let batch = ids_batch(next..next + rows); + expected.extend(next..next + rows); + next += rows; + batch + }) + .collect::>(); + let encoded = batches + .iter() + .map(PreEncodedBatch::for_push) + .collect::>(); + let results = writer.push_group( + batches + .iter() + .zip(&encoded) + .map(|(batch, preencoded)| staged(&dir, batch, preencoded.as_ref())) + .collect(), + &mut deferred, + ); + assert!( + results.iter().all(Result::is_ok), + "step {step}: {results:?}" + ); + } + 5 => { + let batch = ids_batch(next..next + 30); + expected.extend(next..next + 30); + next += 30; + writer + .push_disk_and_memory(FILE, "id", &batch, dir.path().join(FILE), current()) + .unwrap(); + } + 6 | 7 => { + writer.evict_pending_or_segments_deferred(&mut deferred); + } + 8 => { + // Detached rows stay queryable as pending sources; keep + // the writers alive so their files stay in place. + let detached = + writer.detach_flushable_disk_deferred_at(true, Utc::now(), &mut deferred); + std::mem::forget(detached); + } + _ => { + writer.mem.as_mut().unwrap().clear(); + expected.clear(); + } + } + // Exact at every step, whether or not the evicted batches have + // been freed yet. + assert_eq!( + budget.used(), + writer.mem.as_ref().unwrap().memory_bytes(), + "step {step}" + ); + if step % 3 == 0 { + holders.push(deferred); + } + if step % 40 == 0 { + assert_eq!(captured(&writer), expected, "step {step}"); + } + } + assert_eq!(captured(&writer), expected); + drop(holders); + assert_eq!(budget.used(), writer.mem.as_ref().unwrap().memory_bytes()); + let mut deferred = DeferredDrop::default(); + writer.evict_pending_or_segments_deferred(&mut deferred); + assert_eq!(budget.used(), 0); + drop(writer); + assert_eq!(budget.used(), 0); + drop(deferred); + assert_eq!(budget.used(), 0); + } + + #[test] + fn retired_writer_keeps_part_path_truncates_unacked_tail_and_preserves_pending_rows() { + let dir = TempDir::new().unwrap(); + let budget = StagingMemoryBudget::new(1024 * 1024); + let mut writer = writer(&budget); + let first = ids_batch(0..10); + writer + .push_disk_and_memory(FILE, "id", &first, dir.path().join(FILE), current()) + .unwrap(); + + let (part_path, ack_len) = { + let disk = writer.disk.get_mut(FILE).unwrap(); + let part_path = disk.path().to_path_buf(); + let ack_len = disk.acknowledged_len(); + assert!(ack_len > 0); + // Stage an unacknowledged batch in BufWriter and also append trailing + // garbage past `ack_len` on disk to simulate a partial/failed flush. + let unacked = ids_batch(10..20); + disk.append(&unacked, None).unwrap(); + { + use std::io::Write; + let mut f = std::fs::OpenOptions::new() + .append(true) + .open(&part_path) + .unwrap(); + f.write_all(b"partial-unacked-tail").unwrap(); + } + (part_path, ack_len) + }; + + let mut deferred = DeferredDrop::default(); + writer.retire(FILE, &mut deferred); + drop(deferred); + + // The retired `.part` file must stay at its exact path (not renamed to `.arrows` + // by Drop) and be truncated to the last acknowledged message boundary (with no + // stale bytes flushed by `BufWriter::drop`). + assert!( + part_path.exists(), + "retired .part file must remain in place" + ); + assert!( + !sealed_arrow_path(&part_path).exists(), + "retired writer must not rename .part to .arrows on Drop" + ); + assert_eq!( + std::fs::metadata(&part_path).unwrap().len(), + ack_len, + "retired .part file must be truncated to acknowledged length" + ); + // Only the 10 acknowledged rows are queryable from `mem.pending`. + assert_eq!(captured(&writer), (0..10).collect::>()); + assert_eq!(budget.used(), 0); + } +} diff --git a/src/parseable/streams.rs b/src/parseable/streams.rs index ef2fc8dc2..a63731010 100644 --- a/src/parseable/streams.rs +++ b/src/parseable/streams.rs @@ -30,7 +30,9 @@ use once_cell::sync::{Lazy, OnceCell}; use parquet::{ arrow::{ ArrowWriter, - arrow_writer::{ArrowColumnChunk, ArrowRowGroupWriterFactory, compute_leaves}, + arrow_writer::{ + ArrowColumnChunk, ArrowColumnWriter, ArrowRowGroupWriterFactory, compute_leaves, + }, }, basic::Encoding, errors::ParquetError, @@ -215,6 +217,41 @@ static METRIC_ROW_GROUP_ENCODE_IN_FLIGHT: Lazy = Lazy::new(|| { } }); +const LOG_ROW_GROUP_ENCODE_IN_FLIGHT_VAR: &str = "LOG_ROW_GROUP_ENCODE_IN_FLIGHT"; +/// Caps the row groups of one log Parquet file that are encoded at the same +/// time. The same number of row groups is read ahead while those are encoded, +/// so one log conversion holds the decoded rows of at most twice this many +/// row groups, and for a moment a second copy of those being read while +/// their rows are reversed. Row groups reach the file in source order +/// whatever this is. +static LOG_ROW_GROUP_ENCODE_IN_FLIGHT: Lazy = Lazy::new(|| { + log_row_group_encode_in_flight( + std::env::var(LOG_ROW_GROUP_ENCODE_IN_FLIGHT_VAR) + .ok() + .as_deref(), + ) +}); + +/// Row groups of one log Parquet file encoded at once: a positive override, +/// else two. +fn log_row_group_encode_in_flight(var: Option<&str>) -> usize { + var.and_then(|var| var.trim().parse::().ok()) + .filter(|&in_flight| in_flight > 0) + .unwrap_or(2) +} + +/// Fewest columns one Rayon task encodes for a log row group. A log stream +/// has few columns compared to a metric one, so a fixed share of eight would +/// leave most of the conversion pool idle: with no more columns than threads +/// every column is its own task. +fn log_columns_per_rayon_task(columns: usize, threads: usize) -> usize { + (columns / threads.max(1)).clamp(1, 8) +} + +/// Row groups with fewer rows are encoded by the thread that prepared them: +/// their columns are encoded sooner than tasks for them are scheduled. +const LOG_PARALLEL_ENCODE_MIN_ROWS: usize = 1024; + const MAX_ARROW_FILES_PER_PARQUET_VAR: &str = "MAX_ARROW_FILES_PER_PARQUET"; /// Caps how many arrow files feed a single parquet conversion group. A /// minute with heavy schema-key churn can stage thousands of small arrow @@ -426,12 +463,673 @@ struct SchemaSnapshot { fields: Arc>>, } +/// Consecutive rows of a log conversion that form one Parquet row group, as +/// the batches, or parts of batches, the reader produced them in. +struct LogRowGroup { + batches: Vec, + rows: usize, + /// Bytes of the allocations the finished rows keep alive, see + /// [`log_batch_retained_bytes`]; a batch split between row groups is + /// charged to each in proportion to its rows. Zero unless the source + /// measures them (`LogRowGroupSource::measuring_retained_bytes`). + retained_bytes: usize, +} + +/// Bytes of Arrow data in the rows of `batch`, which is what a row group's +/// byte limit is counted in. +/// +/// This is the size of the data itself, not of the allocations behind it. +/// `RecordBatch::get_array_memory_size` reports the latter, and is many times +/// too large for the batches a conversion reads: all the arrays of a batch +/// decoded from a staged file share the buffer of one IPC message, which it +/// counts in full once per array buffer, and every buffer of a small batch +/// counts as its 64-byte allocation. Row groups cut by it would be a +/// fraction of the configured size for streams ingested in small batches. +fn log_batch_data_bytes(batch: &RecordBatch) -> usize { + batch + .columns() + .iter() + .map(|column| { + column + .to_data() + .get_slice_memory_size() + .unwrap_or_else(|_| column.get_array_memory_size()) + }) + .sum() +} + +/// Bytes of the allocations the arrays of `batch` keep alive, each counted +/// once: what holding the batch actually retains. +/// +/// `RecordBatch::get_array_memory_size` counts the capacity of every buffer +/// behind the batch, which is the retained memory of a batch whose buffers +/// are separate allocations (as reversed and adapted batches are), but +/// counts a shared allocation once per buffer that points into it, as every +/// buffer of a batch decoded from one IPC message does. This sums the same +/// capacities with each allocation counted once. Unlike +/// [`log_batch_data_bytes`], a slice is charged for the whole allocation it +/// keeps alive. +fn log_batch_retained_bytes(batch: &RecordBatch) -> usize { + fn collect(data: &arrow::array::ArrayData, allocations: &mut Vec<(usize, usize)>) { + let nulls = data.nulls().map(|nulls| nulls.buffer()); + for buffer in data.buffers().iter().chain(nulls) { + // Externally owned buffers report no capacity: count the bytes + // reachable from the start of their allocation. + let size = buffer + .capacity() + .max(buffer.ptr_offset().saturating_add(buffer.len())); + allocations.push((buffer.data_ptr().as_ptr() as usize, size)); + } + for child in data.child_data() { + collect(child, allocations); + } + } + let mut allocations = Vec::new(); + for column in batch.columns() { + collect(&column.to_data(), &mut allocations); + } + allocations.sort_unstable(); + // Of the buffers into one allocation, the largest size reached counts. + let mut total = 0usize; + let mut current: Option<(usize, usize)> = None; + for (pointer, size) in allocations { + match current.as_mut() { + Some((current_pointer, current_size)) if *current_pointer == pointer => { + *current_size = (*current_size).max(size); + } + _ => { + if let Some((_, size)) = current { + total = total.saturating_add(size); + } + current = Some((pointer, size)); + } + } + } + if let Some((_, size)) = current { + total = total.saturating_add(size); + } + total +} + +/// Estimated bytes per row a decoded `batch` contributes to a row group's +/// byte limit: its Arrow data per row and, for a batch narrower than the +/// `merged_columns` of the merged schema, at least the `merged_row_bytes` +/// floor its typed null arrays take once `BatchAdapter::adapt` adds them. +fn log_batch_bytes_per_row( + batch: &RecordBatch, + merged_columns: usize, + merged_row_bytes: usize, +) -> usize { + let raw_bytes_per_row = log_batch_data_bytes(batch) + .div_ceil(batch.num_rows().max(1)) + .max(1); + if batch.num_columns() < merged_columns { + raw_bytes_per_row.max(merged_row_bytes).max(1) + } else { + raw_bytes_per_row + } +} + +/// Maximum estimated adapted Arrow memory for a single parallel log row group +/// when no explicit `row_group_bytes` cap is configured. Above this ceiling +/// (e.g., wide 900-column schema-churn merges at default `row_group_size`), +/// log conversion streams batches one at a time through `ArrowWriter` so peak +/// memory stays bounded to a single adapted batch instead of a full row group. +const LOG_PARALLEL_ROW_GROUP_MAX_ADAPTED_BYTES: usize = 128 * 1024 * 1024; + +/// Soft wave memory target for pipelining multiple log row groups concurrently. +/// Once a wave reaches this adapted size, `next_row_groups` stops accumulating +/// additional row groups in the same wave so large rows pipeline one group at +/// a time. +const LOG_PARALLEL_WAVE_SOFT_BYTES: usize = 64 * 1024 * 1024; + +/// Minimum per-row Arrow buffer bytes `BatchAdapter` allocates for one field +/// when materializing a typed null column under the merged schema. +fn adapted_field_row_bytes_floor(data_type: &arrow_schema::DataType) -> usize { + use arrow_schema::DataType; + match data_type { + DataType::Null => 0, + DataType::Boolean | DataType::Int8 | DataType::UInt8 => 1, + DataType::Int16 | DataType::UInt16 | DataType::Float16 => 2, + DataType::Int32 + | DataType::UInt32 + | DataType::Float32 + | DataType::Date32 + | DataType::Time32(_) + | DataType::Utf8 + | DataType::Binary => 4, + DataType::Int64 + | DataType::UInt64 + | DataType::Float64 + | DataType::Date64 + | DataType::Time64(_) + | DataType::Timestamp(_, _) + | DataType::Duration(_) + | DataType::LargeUtf8 + | DataType::LargeBinary + | DataType::Interval(_) => 8, + DataType::Decimal128(_, _) | DataType::Utf8View | DataType::BinaryView => 16, + DataType::Decimal256(_, _) => 32, + DataType::FixedSizeBinary(width) => (*width).max(0) as usize, + DataType::Struct(fields) => fields + .iter() + .map(|f| adapted_field_row_bytes_floor(f.data_type())) + .sum::() + .max(1), + DataType::List(_) | DataType::Map(_, _) => 4, + DataType::LargeList(_) => 8, + DataType::FixedSizeList(field, len) => { + adapted_field_row_bytes_floor(field.data_type()).saturating_mul((*len).max(1) as usize) + } + DataType::Dictionary(key, _) => adapted_field_row_bytes_floor(key), + _ => 8, + } +} + +/// Minimum per-row Arrow memory for a batch once adapted to `schema` +/// (including typed null arrays synthesized for missing columns). +fn merged_schema_adapted_row_bytes(schema: &Schema) -> usize { + schema + .fields() + .iter() + .map(|field| adapted_field_row_bytes_floor(field.data_type())) + .sum() +} + +/// The decoded batches of a log conversion in the order their rows are +/// written, each with the index of the reader it came from. +type DecodedLogBatches = Box)> + Send>; + +/// Turns the decoded batches of a log conversion into the batches that are +/// written: rows newest first, under the schema of the Parquet file. +struct LogBatchFinisher { + /// One adapter per reader, so that files with different schemas do not + /// invalidate each other's cached column mapping. Empty when the batches + /// arrive in their final form. + adapters: Vec, + #[cfg(test)] + part_path: Option, +} + +impl LogBatchFinisher { + /// For batches from `readers` reverse readers. + fn reversing(schema: &Arc, readers: usize) -> Self { + Self { + adapters: (0..readers) + .map(|_| crate::utils::arrow::batch_adapter::BatchAdapter::new(schema.clone())) + .collect(), + #[cfg(test)] + part_path: None, + } + } + + /// For batches that are written as they are read. + fn finished() -> Self { + Self { + adapters: Vec::new(), + #[cfg(test)] + part_path: None, + } + } + + /// Finishes `batches` and returns them in their order. Reversing copies + /// every row and is what reading a log conversion spends most time in, + /// so the batches are reversed in parallel, on the pool of the caller. + /// They are then adapted one by one in their order, as a sequential + /// reader would, which is cheap and keeps the first error the same. + fn finish( + &mut self, + batches: Vec<(usize, RecordBatch)>, + ) -> Result, ArrowError> { + if self.adapters.is_empty() { + return Ok(batches.into_iter().map(|(_, batch)| batch).collect()); + } + #[cfg(test)] + let part_path = self.part_path.as_deref(); + let reverse_batch = |(reader, batch): (usize, RecordBatch)| { + #[cfg(test)] + if let Some(part_path) = part_path { + record_log_pipeline_thread(part_path, LogPipelineStage::Reverse); + } + (reader, crate::utils::arrow::reverse(&batch)) + }; + let reversed: Vec<(usize, RecordBatch)> = if batches.len() < 2 { + batches.into_iter().map(reverse_batch).collect() + } else { + batches.into_par_iter().map(reverse_batch).collect() + }; + reversed + .into_iter() + .map(|(reader, batch)| self.adapters[reader].adapt(&batch)) + .collect() + } +} + +/// Where the rows of a planned row group come from: `rows` rows from row +/// `offset` of the batch in `slot`. +struct LogRowGroupPiece { + slot: usize, + offset: usize, + rows: usize, +} + +/// A batch that a row group is being cut from, and the rows of it that no +/// row group has taken yet. +struct LogBatchCursor { + slot: usize, + offset: usize, + rows: usize, + bytes_per_row: usize, +} + +/// Cuts the batches of a log conversion into row groups without reordering +/// or copying rows. +/// +/// A row group is closed when it has `max_rows` rows or when the Arrow data +/// of its rows reaches `max_bytes`, whichever comes first, so the rows held +/// for one row group are bounded however large the source batches are. A +/// batch that crosses a limit is split by row, each row counted at the +/// average size of the batch it came from. +/// +/// Row groups are read several at a time. The batches are first decoded and +/// assigned to row groups one after the other, which needs only their row +/// counts and sizes; the batches of all those row groups are then finished +/// together, in parallel. +struct LogRowGroupSource { + /// Decoded batches in the order their rows are written, each with the + /// index of its reader. + batches: I, + finisher: LogBatchFinisher, + /// Finished rows of a batch left over by the previous row group, and + /// their estimated size per row. + carry: Option<(RecordBatch, usize)>, + max_rows: usize, + max_bytes: Option, + /// Number of columns in the target merged schema. + merged_columns: usize, + /// Minimum adapted bytes per row under the target merged schema so narrow + /// 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, + /// Whether row groups report the bytes their rows retain. + measure_retained_bytes: bool, + exhausted: bool, +} + +impl)>> LogRowGroupSource { + fn new( + batches: I, + finisher: LogBatchFinisher, + max_rows: usize, + max_bytes: Option, + stats: Option, + ) -> Self { + Self { + batches, + finisher, + carry: None, + max_rows, + max_bytes, + merged_columns: 0, + merged_row_bytes: 0, + stats, + inline_stats_max_bytes: None, + measure_retained_bytes: false, + exhausted: false, + } + } + + /// Measures the bytes the rows of every row group retain, see + /// [`LogRowGroup::retained_bytes`]. + fn measuring_retained_bytes(mut self) -> Self { + self.measure_retained_bytes = true; + 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); + self + } + + fn with_merged_schema(mut self, merged_columns: usize, merged_row_bytes: usize) -> Self { + self.merged_columns = merged_columns; + self.merged_row_bytes = merged_row_bytes; + self + } + + /// Reads up to `row_groups` consecutive row groups. Fewer, or none, are + /// returned only when the source has no more rows. + fn next_row_groups(&mut self, row_groups: usize) -> Result, StagingError> { + // Batches the row groups are cut from: at most one finished batch + // left over by the previous call, then batches decoded by this one. + let mut finished = Vec::new(); + let mut decoded = Vec::new(); + let mut cursor = None; + if let Some((batch, bytes_per_row)) = self.carry.take() { + cursor = Some(LogBatchCursor { + slot: 0, + offset: 0, + rows: batch.num_rows(), + bytes_per_row, + }); + finished.push(batch); + } + let carried = finished.len(); + + let mut plan: Vec> = Vec::new(); + let mut wave_bytes = 0usize; + while plan.len() < row_groups { + if !plan.is_empty() && wave_bytes >= LOG_PARALLEL_WAVE_SOFT_BYTES { + break; + } + let mut pieces = Vec::new(); + let mut rows = 0usize; + let mut bytes = 0usize; + loop { + let batch = match cursor.take() { + Some(batch) => batch, + None if self.exhausted => break, + None => { + let Some((reader, batch)) = self.batches.next() else { + self.exhausted = true; + break; + }; + let batch = batch?; + let bytes_per_row = log_batch_bytes_per_row( + &batch, + self.merged_columns, + self.merged_row_bytes, + ); + let cursor = LogBatchCursor { + slot: carried + decoded.len(), + offset: 0, + rows: batch.num_rows(), + bytes_per_row, + }; + // A batch with no rows is still finished, so that + // one that does not fit the schema is still an error. + decoded.push((reader, batch)); + if cursor.rows == 0 { + continue; + } + cursor + } + }; + let rows_within_count = self.max_rows - rows; + let rows_within_bytes = match self.max_bytes { + // An empty row group takes a row whatever its size, so a + // row larger than the limit still gets written. + Some(max_bytes) => (max_bytes.saturating_sub(bytes) / batch.bytes_per_row) + .max(usize::from(rows == 0)), + None => usize::MAX, + }; + let taken = batch.rows.min(rows_within_count).min(rows_within_bytes); + if taken > 0 { + pieces.push(LogRowGroupPiece { + slot: batch.slot, + offset: batch.offset, + rows: taken, + }); + rows += taken; + bytes = bytes.saturating_add(taken.saturating_mul(batch.bytes_per_row)); + } + let full = taken < batch.rows; + if full { + cursor = Some(LogBatchCursor { + offset: batch.offset + taken, + rows: batch.rows - taken, + ..batch + }); + } + if full + || rows >= self.max_rows + || self.max_bytes.is_some_and(|max_bytes| bytes >= max_bytes) + { + break; + } + } + if pieces.is_empty() { + break; + } + wave_bytes = wave_bytes.saturating_add(bytes); + plan.push(pieces); + } + + let newly_finished = self.finisher.finish(decoded)?; + // Statistics see every batch whole and in source order, whatever row + // groups its rows end up in. + 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)) + { + self.stats = None; + break; + } + } + } + finished.extend(newly_finished); + + let cut = |piece: &LogRowGroupPiece| { + let batch = &finished[piece.slot]; + if piece.offset == 0 && piece.rows == batch.num_rows() { + batch.clone() + } else { + batch.slice(piece.offset, piece.rows) + } + }; + // Retained bytes of each finished batch that a row group takes rows of. + let mut retained = vec![None; finished.len()]; + let measure = self.measure_retained_bytes; + let mut retained_of = |piece: &LogRowGroupPiece| { + if !measure { + return 0; + } + let batch = &finished[piece.slot]; + let bytes = + *retained[piece.slot].get_or_insert_with(|| log_batch_retained_bytes(batch)); + let rows = batch.num_rows().max(1); + ((bytes as u128 * piece.rows as u128).div_ceil(rows as u128)) as usize + }; + let row_groups = plan + .iter() + .map(|pieces| LogRowGroup { + batches: pieces.iter().map(cut).collect(), + rows: pieces.iter().map(|piece| piece.rows).sum(), + retained_bytes: pieces + .iter() + .map(&mut retained_of) + .fold(0, usize::saturating_add), + }) + .collect(); + self.carry = cursor.map(|batch| { + ( + finished[batch.slot].slice(batch.offset, batch.rows), + batch.bytes_per_row, + ) + }); + Ok(row_groups) + } + + fn is_exhausted(&self) -> bool { + self.exhausted && self.carry.is_none() + } +} + +/// The column chunks of one encoded log row group, in Parquet column order. +struct EncodedLogRowGroup { + row_group_index: usize, + chunks: Vec, +} + +/// Encodes the row groups of one log Parquet file. Shared by the tasks of a +/// conversion; every one of them runs on the Rayon pool of its caller. +struct LogRowGroupEncoder<'a> { + factory: &'a ArrowRowGroupWriterFactory, + schema: &'a Schema, + /// Parquet leaf columns under each Arrow field, in field order. + leaves_per_field: &'a [usize], + columns_per_task: usize, + #[cfg(test)] + part_path: &'a Path, +} + +impl LogRowGroupEncoder<'_> { + /// Encodes consecutive row groups at the same time and returns them in + /// their order. `first_index` is the file position of the first one. + fn encode_row_groups( + &self, + row_groups: Vec, + first_index: usize, + ) -> Result, StagingError> { + if row_groups.len() < 2 { + return row_groups + .into_iter() + .map(|row_group| self.encode_row_group(row_group, first_index)) + .collect(); + } + row_groups + .into_par_iter() + .enumerate() + .map(|(offset, row_group)| self.encode_row_group(row_group, first_index + offset)) + .collect() + } + + /// Encodes one row group, its columns in parallel. The decoded rows are + /// released when this returns. + fn encode_row_group( + &self, + row_group: LogRowGroup, + row_group_index: usize, + ) -> Result { + #[cfg(test)] + record_log_pipeline_thread(self.part_path, LogPipelineStage::EncodeRowGroup); + let writers = self.factory.create_column_writers(row_group_index)?; + let leaves = self.leaves_per_field.iter().sum::(); + if writers.len() != leaves { + return Err(ParquetError::General(format!( + "Parquet column writer count {} does not match schema leaf count {leaves}", + writers.len(), + )) + .into()); + } + let mut writers = writers.into_iter(); + let fields = self + .leaves_per_field + .iter() + .enumerate() + .map(|(field_index, leaves)| (field_index, writers.by_ref().take(*leaves).collect())) + .collect::)>>(); + + // Each batch is written to the column writers in turn, as + // `ArrowWriter` does, so the pages match those of a sequential write + // and the batches are never concatenated. + let batches = row_group.batches.as_slice(); + let encode_field = |(field_index, mut writers): (usize, Vec)| { + #[cfg(test)] + record_log_pipeline_thread(self.part_path, LogPipelineStage::EncodeColumn); + let field = self.schema.field(field_index); + for batch in batches { + let leaves = compute_leaves(field, batch.column(field_index))?; + if leaves.len() != writers.len() { + return Err(ParquetError::General(format!( + "Arrow field {} has {} leaves for {} Parquet column writers", + field.name(), + leaves.len(), + writers.len() + ))); + } + for (writer, leaf) in writers.iter_mut().zip(&leaves) { + writer.write(leaf)?; + } + } + writers + .into_iter() + .map(ArrowColumnWriter::close) + .collect::, ParquetError>>() + }; + let chunks: Vec> = + if row_group.rows < LOG_PARALLEL_ENCODE_MIN_ROWS || fields.len() < 2 { + fields + .into_iter() + .map(encode_field) + .collect::>()? + } else { + fields + .into_par_iter() + .with_min_len(self.columns_per_task) + .map(encode_field) + .collect::>()? + }; + Ok(EncodedLogRowGroup { + row_group_index, + chunks: chunks.into_iter().flatten().collect(), + }) + } +} + +/// Where the threads of a log conversion are recorded, for tests that check +/// which pool its work ran on. Only registered part files are recorded. +#[cfg(test)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +enum LogPipelineStage { + /// Reading and decoding the rows of row groups. + Prepare, + /// Reversing one decoded batch. + Reverse, + /// Encoding one row group. + EncodeRowGroup, + /// Encoding the leaves of one field of a row group. + EncodeColumn, + /// Appending encoded row groups to the file. + Append, +} + +/// The stage and thread name of every recorded step, by part file. +#[cfg(test)] +type LogPipelineThreads = HashMap>; + +#[cfg(test)] +static LOG_PIPELINE_THREADS: Lazy> = Lazy::new(Default::default); + +#[cfg(test)] +fn record_log_pipeline_thread(part_path: &Path, stage: LogPipelineStage) { + if let Some(threads) = LOG_PIPELINE_THREADS.lock().unwrap().get_mut(part_path) { + threads.push(( + stage, + std::thread::current().name().unwrap_or_default().to_owned(), + )); + } +} + #[derive(Default)] struct WrittenParquetArtifacts { parquet_metadata: Option>, field_stats: Option<(usize, Vec)>, } +/// Time one log conversion spent in each step of its pipeline. The steps +/// overlap, so they add up to more than the conversion took. +#[derive(Default)] +struct LogParquetPhaseTimings { + rows: usize, + row_groups: usize, + columns_per_task: usize, + prepare_duration: Duration, + encode_duration: Duration, + append_duration: Duration, + close_duration: Duration, +} + /// All state associated with a single logstream in Parseable. pub struct Stream { pub stream_name: String, @@ -976,6 +1674,29 @@ impl ConversionRecordReader { Self::Reverse(reader) => Box::new(reader.merged_iter(schema, time_partition)), } } + + /// The batches `merged_iter` yields, in its order, before they are + /// finished, and what finishes them. The log writer finishes the batches + /// of several row groups at once instead of one batch at a time. + fn into_log_batches( + self, + schema: Arc, + time_partition: Option, + ) -> (DecodedLogBatches, LogBatchFinisher) { + match self { + Self::Forward(reader) => ( + Box::new(MetricForwardRecordIterator::new(reader, schema).map(|batch| (0, batch))), + LogBatchFinisher::finished(), + ), + Self::Reverse(reader) => { + let finisher = LogBatchFinisher::reversing(&schema, reader.readers.len()); + ( + Box::new(reader.merged_decoded_iter(time_partition)), + finisher, + ) + } + } + } } impl ArrowFileConversionOutcome { @@ -1097,7 +1818,64 @@ impl Stream { (self.options.mode != Mode::Query || stream_type == StreamType::Internal).then(|| { self.filename_by_partition(schema_key, parsed_timestamp, custom_partition_values) }); - self.combined_push(disk, schema_key, record, parsed_timestamp) + // Encode and compress on the caller's thread, before queueing for the + // stream's writer: the callers of a busy stream then encode in + // parallel and the writer only copies their bytes. + let preencoded = disk + .as_ref() + .and_then(|_| super::staging::writer::PreEncodedBatch::for_push(record)); + self.combined_push(disk, schema_key, record, preencoded, parsed_timestamp) + } + + /// Encodes `record` for `push_async`, as `push` does for itself: call it + /// on a CPU thread, not on the async executor. `None` when the batch is + /// left to the writer (small batches, dictionary schemas) or the stream + /// stages nothing on disk. + pub fn preencode_for_push( + &self, + record: &RecordBatch, + stream_type: StreamType, + ) -> Option { + (self.options.mode != Mode::Query || stream_type == StreamType::Internal) + .then(|| super::staging::writer::PreEncodedBatch::for_push(record)) + .flatten() + } + + /// `push` for async callers. While another caller holds the stream's + /// writer this awaits instead of blocking a thread, and the write itself + /// runs on the runtime's blocking pool, never on the calling task. + /// + /// Nothing is encoded here: pass the result of `preencode_for_push`, + /// computed on a CPU thread. Without it the writer encodes the batch + /// itself, one batch at a time. + /// + /// Resolves once the rows are flushed to their staging file, like `push`. + /// Once the batch is admitted to the queue it is written even if this + /// future is dropped. + pub async fn push_async( + self: &Arc, + schema_key: &str, + record: &RecordBatch, + preencoded: Option, + parsed_timestamp: NaiveDateTime, + custom_partition_values: &HashMap, + stream_type: StreamType, + ) -> Result<(), StagingError> { + let span = info_span!( + "stream_push", + stream_name = %self.stream_name, + num_rows = record.num_rows(), + ); + let disk = + (self.options.mode != Mode::Query || stream_type == StreamType::Internal).then(|| { + self.filename_by_partition(schema_key, parsed_timestamp, custom_partition_values) + }); + let preencoded = preencoded.filter(|_| disk.is_some()); + tracing::Instrument::instrument( + self.combined_push_async(disk, schema_key, record, preencoded, parsed_timestamp), + span, + ) + .await } fn write_push( @@ -1105,8 +1883,52 @@ impl Stream { disk: Option<&str>, schema_key: &str, record: &RecordBatch, + preencoded: Option<&super::staging::writer::PreEncodedBatch>, parsed_timestamp: NaiveDateTime, + deferred: &mut super::staging::writer::DeferredDrop, ) -> Result<(), StagingError> { + self.write_pushes( + &[push_queue::PendingPush { + disk, + key: schema_key, + record, + preencoded, + timestamp: parsed_timestamp, + }], + deferred, + ) + .pop() + .unwrap_or(Ok(())) + } + + /// Writes the batches of one queue turn under a single hold of the + /// writer lock, flushing each staging file once, and returns one result + /// per batch. Cached batches the writes evict are moved to `deferred`, + /// already released from the memory staging budget: the caller drops it + /// after this returns, and after ending its turn, so neither the writer + /// lock nor the queue waits for the allocator. + fn write_pushes( + &self, + pushes: &[push_queue::PendingPush<'_>], + deferred: &mut super::staging::writer::DeferredDrop, + ) -> Vec> { + use super::staging::writer::{StagedFile, StagedPush}; + let staged = pushes + .iter() + .map(|push| StagedPush { + file: push.disk.map(|filename| StagedFile { + name: filename, + path: self.data_path.join(filename), + range: TimeRange::granularity_range( + push.timestamp.and_local_timezone(Utc).unwrap(), + OBJECT_STORE_DATA_GRANULARITY, + ), + }), + schema_key: push.key, + batch: push.record, + preencoded: push.preencoded, + }) + .collect::>(); let mut guard = { let _lock_span = info_span!("acquire_writer_lock").entered(); match self.writer.lock() { @@ -1116,31 +1938,22 @@ impl Stream { "Writer lock poisoned while ingesting data for stream {}", self.stream_name ); - - return Err(StagingError::PoisonError(PoisonError::new(format!( + let message = format!( "Writer lock poisoned while ingesting data for stream {} - {}", self.stream_name, poisoned - )))); + ); + return pushes + .iter() + .map(|_| Err(StagingError::PoisonError(PoisonError::new(message.clone())))) + .collect(); } } }; - if let Some(filename) = disk { - let range = TimeRange::granularity_range( - parsed_timestamp.and_local_timezone(Utc).unwrap(), - OBJECT_STORE_DATA_GRANULARITY, - ); - let file_path = self.data_path.join(filename); - - // The writer may route the batch to a sibling file; its rows in - // memory then belong to that file, not to `filename`. Rows are - // cached only while the memory staging budget allows; the rest - // are served from the staging file by queries. - guard.push_disk_and_memory(filename, schema_key, record, file_path, range)?; - } else if let Some(mem) = guard.mem.as_mut() { - mem.push(schema_key, record)?; - } - - Ok(()) + // The writer may route a batch to a sibling file; its rows in memory + // then belong to that file, not to the push's own. Rows are cached + // only while the memory staging budget allows; the rest are served + // from the staging file by queries. + guard.push_group(staged, deferred) } pub fn filename_by_partition( @@ -1911,9 +2724,12 @@ impl Stream { /// queries then read those rows from the staging files. Returns the /// bytes released from the memory staging budget. pub fn evict_staging_memory(&self) -> usize { + // The bytes leave the budget under the lock; the batches are freed + // after it, when `deferred` goes out of scope. + let mut deferred = super::staging::writer::DeferredDrop::default(); self.writer .lock() - .map(|mut writer| writer.evict_pending_or_segments()) + .map(|mut writer| writer.evict_pending_or_segments_deferred(&mut deferred)) .unwrap_or(0) } @@ -2031,15 +2847,17 @@ impl Stream { .part_lifecycle .read() .unwrap_or_else(PoisonError::into_inner); + // The cached batches of the detached writers: a minute of them can be + // gigabytes. Detaching releases their bytes from the memory staging + // budget and moves them here; they are freed below, after both locks. + let mut detached_cache = super::staging::writer::DeferredDrop::default(); // Swap out stale writers under the lock, seal them after releasing it. // Sealing does I/O (IPC finish + file rename) so sealing // outside the lock avoids blocking concurrent push() calls. let stale_writers = { - let _admission = self - .push_queue - .lifecycle - .write() - .unwrap_or_else(PoisonError::into_inner); + // Admits no push and waits for the admitted ones, so the writers + // detached hold every row accepted before this flush. + let _admission = self.push_queue.pause(); let mut writer = self.writer.lock().map_err(|poisoned| { StagingError::PoisonError(PoisonError::new(format!( "Writer lock poisoned while flushing data for stream {} - {}", @@ -2047,8 +2865,9 @@ impl Stream { ))) })?; - writer.detach_flushable_disk_at(forced, clock()) + writer.detach_flushable_disk_deferred_at(forced, clock(), &mut detached_cache) }; + drop(detached_cache); #[cfg(test)] self.lifecycle_phase(LifecyclePhase::FlushDetached); // Sealing I/O happens here, outside the lock @@ -3171,51 +3990,40 @@ impl Stream { collect_stats.then_some(max_field_statistics), )? } else if let Some(key) = cluster_key { - let stats = log_clustering::write_clustered_log_parquet( + self.write_clustered_log_parquet_part_file( + part_path, &mut part_file, - record_reader.merged_iter(schema.clone(), time_partition.cloned()), + record_reader, schema, props, - self.options.row_group_size, + time_partition, key, - )?; - debug!( - stream_name = %self.stream_name, - parquet_path = %part_path.display(), - rows = stats.rows, - row_groups = stats.row_groups, - cluster_ms = stats.cluster_duration.as_secs_f64() * 1000.0, - "Clustered log Arrow-to-Parquet conversion" - ); - WrittenParquetArtifacts::default() + collect_stats.then_some(max_field_statistics), + *LOG_ROW_GROUP_ENCODE_IN_FLIGHT, + )? } else { - let mut stats_acc = collect_stats.then(|| { - crate::storage::field_stats::FieldStatsAccumulator::new( - &self.stream_name, - schema.as_ref(), - max_field_statistics, - ) - }); - let mut writer = - ArrowWriter::try_new(&mut part_file, schema.clone(), Some(props.clone()))?; - for record in record_reader.merged_iter(schema.clone(), time_partition.cloned()) { - let batch = record?; - if let Some(acc) = stats_acc.as_mut() { - acc.update(&batch); - } - writer.write(&batch)?; - } - let parquet_metadata = Arc::new(writer.close()?); - WrittenParquetArtifacts { - parquet_metadata: Some(parquet_metadata), - field_stats: stats_acc.map(|acc| (max_field_statistics, acc.finish())), - } + self.write_log_parquet_part_file( + part_path, + &mut part_file, + record_reader, + schema, + props, + time_partition, + collect_stats.then_some(max_field_statistics), + *LOG_ROW_GROUP_ENCODE_IN_FLIGHT, + )? }; + // Flush the buffered writer before validating on disk so every byte is + // visible to the footer check and failed writes on drop cannot go unnoticed. + part_file.flush()?; drop(part_file); #[cfg(test)] self.lifecycle_phase(LifecyclePhase::ParquetPartClosed(part_path.to_path_buf())); + // Always validate the written Parquet file's on-disk footer before + // publishing or retiring source Arrow files so production and tests + // share the exact same verification path. if !Self::is_valid_parquet_file(part_path, &self.stream_name) { error!( "Invalid parquet file {part_path:?} detected for stream {stream_name}, removing it", @@ -3228,6 +4036,367 @@ impl Stream { Ok(Some(artifacts)) } + /// Writes a log conversion group with every row group clustered by `key`, + /// on the conversion pool: row groups are read, clustered and encoded as + /// a pipeline, as the unclustered log writer does, with the bytes of the + /// sequential clustered writer. Field statistics are collected from the + /// rows as they are read, so the file need not be read back for them. + #[allow(clippy::too_many_arguments)] + fn write_clustered_log_parquet_part_file( + &self, + part_path: &Path, + part_file: &mut (impl Write + Send), + record_reader: ConversionRecordReader, + schema: &Arc, + props: &WriterProperties, + time_partition: Option<&String>, + key: LogClusterKey, + collect_stats_max: Option, + in_flight: usize, + ) -> Result { + self.write_clustered_log_parquet_part_file_on_pool( + &LOG_CONVERSION_THREADPOOL, + part_path, + part_file, + record_reader, + schema, + props, + time_partition, + key, + collect_stats_max, + in_flight, + ) + } + + #[allow(clippy::too_many_arguments)] + fn write_clustered_log_parquet_part_file_on_pool( + &self, + pool: &rayon::ThreadPool, + part_path: &Path, + part_file: &mut (impl Write + Send), + record_reader: ConversionRecordReader, + schema: &Arc, + props: &WriterProperties, + time_partition: Option<&String>, + key: LogClusterKey, + collect_stats_max: Option, + in_flight: usize, + ) -> Result { + let conversion_started = Instant::now(); + let stats = collect_stats_max.map(|max_stats| { + crate::storage::field_stats::FieldStatsAccumulator::new( + &self.stream_name, + schema.as_ref(), + max_stats, + ) + }); + #[cfg_attr(not(test), allow(unused_mut))] + let (batches, mut finisher) = + record_reader.into_log_batches(schema.clone(), time_partition.cloned()); + #[cfg(test)] + { + finisher.part_path = Some(part_path.to_path_buf()); + } + let output = log_clustering::write_clustered_log_parquet_on_pool( + pool, + part_file, + batches, + finisher, + schema, + props, + self.options.row_group_size, + key, + in_flight, + stats, + part_path, + )?; + let timings = output.write_stats; + // Statistics over the inline budget, or approximate, were dropped + // during the write; the upload path computes them from the file. + let inline_stats_dropped = collect_stats_max.is_some() && output.stats.is_none(); + debug!( + stream_name = %self.stream_name, + parquet_path = %part_path.display(), + rows = timings.rows, + row_groups = timings.row_groups, + split_row_groups = timings.split_row_groups, + reencoded_row_groups = timings.reencoded_row_groups, + sequential = timings.sequential, + serial = timings.serial, + inline_stats_dropped, + row_group_encode_in_flight = in_flight, + columns_per_rayon_task = timings.columns_per_task, + conversion_threads = pool.current_num_threads(), + total_ms = conversion_started.elapsed().as_secs_f64() * 1000.0, + cluster_ms = timings.cluster_duration.as_secs_f64() * 1000.0, + prepare_ms = timings.prepare_duration.as_secs_f64() * 1000.0, + encode_ms = timings.encode_duration.as_secs_f64() * 1000.0, + append_ms = timings.append_duration.as_secs_f64() * 1000.0, + close_ms = timings.close_duration.as_secs_f64() * 1000.0, + "Clustered log Arrow-to-Parquet conversion" + ); + Ok(WrittenParquetArtifacts { + parquet_metadata: Some(Arc::new(output.metadata)), + field_stats: output + .stats + .zip(collect_stats_max) + .map(|(stats, max_stats)| (max_stats, stats.finish())), + }) + } + + /// Writes a log conversion group with its row groups prepared, encoded + /// and appended as a pipeline, on the conversion pool. + /// + /// Rows keep the order of the merged reader. Each step works on a wave of + /// up to `in_flight` consecutive row groups: while + /// one wave is encoded, columns and row groups in parallel, the previous + /// wave is appended to the file and the next one is read. The steps are + /// joined on the pool rather than passed between threads over channels: + /// a pool thread that waits for a step runs other pool work meanwhile, + /// so a pool whose every thread is converting a stream cannot deadlock. + #[allow(clippy::too_many_arguments)] + fn write_log_parquet_part_file( + &self, + part_path: &Path, + part_file: &mut (impl Write + Send), + record_reader: ConversionRecordReader, + schema: &Arc, + props: &WriterProperties, + time_partition: Option<&String>, + collect_stats_max: Option, + in_flight: usize, + ) -> Result { + self.write_log_parquet_part_file_on_pool( + &LOG_CONVERSION_THREADPOOL, + part_path, + part_file, + record_reader, + schema, + props, + time_partition, + collect_stats_max, + in_flight, + ) + } + + #[allow(clippy::too_many_arguments)] + fn write_log_parquet_part_file_on_pool( + &self, + pool: &rayon::ThreadPool, + part_path: &Path, + part_file: &mut (impl Write + Send), + record_reader: ConversionRecordReader, + schema: &Arc, + props: &WriterProperties, + time_partition: Option<&String>, + collect_stats_max: Option, + in_flight: usize, + ) -> Result { + let in_flight = in_flight.max(1); + let max_rows = self.options.row_group_size; + if max_rows == 0 { + return Err(ParquetError::General( + "Parquet row-group target must be greater than zero".to_string(), + ) + .into()); + } + let max_bytes = (self.options.row_group_bytes > 0).then_some(self.options.row_group_bytes); + let merged_columns = schema.fields().len(); + let merged_row_bytes = merged_schema_adapted_row_bytes(schema.as_ref()); + let estimated_rg_bytes = max_rows.saturating_mul(merged_row_bytes); + let effective_in_flight = if estimated_rg_bytes > LOG_PARALLEL_WAVE_SOFT_BYTES { + 1 + } else { + in_flight + }; + let stats = collect_stats_max.map(|max_stats| { + crate::storage::field_stats::FieldStatsAccumulator::new( + &self.stream_name, + schema.as_ref(), + max_stats, + ) + }); + let conversion_started = Instant::now(); + + // Startup conversion calls this from outside the pool. `install` runs + // the pipeline on a pool thread either way, so none of its parallel + // work can land on the global Rayon pool that HTTP ingest uses. + let (parquet_metadata, stats, timings) = pool.install(|| { + // Wide merged schemas without an explicit byte cap (e.g., 900+ + // columns under schema churn at default `row_group_size`) would + // materialize gigabytes of padded null arrays if a whole row group + // were retained in RAM at once. Stream one adapted batch at a time + // through `ArrowWriter` so peak memory stays bounded to one batch + // while producing byte-identical Parquet output. + if max_bytes.is_none() && estimated_rg_bytes > LOG_PARALLEL_ROW_GROUP_MAX_ADAPTED_BYTES + { + let mut writer = + ArrowWriter::try_new(&mut *part_file, schema.clone(), Some(props.clone()))?; + let mut stats = stats; + 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); + } + timings.rows += batch.num_rows(); + writer.write(&batch)?; + } + let close_started = Instant::now(); + let parquet_metadata = writer.close()?; + timings.close_duration = close_started.elapsed(); + timings.row_groups = parquet_metadata.num_row_groups(); + return Ok::<_, StagingError>((parquet_metadata, stats, timings)); + } + + let arrow_writer = + ArrowWriter::try_new(&mut *part_file, schema.clone(), Some(props.clone()))?; + let (mut writer, factory) = arrow_writer.into_serialized_writer()?; + let mut leaves_per_field = vec![0usize; schema.fields().len()]; + let parquet_schema = writer.schema_descr(); + for leaf in 0..parquet_schema.num_columns() { + leaves_per_field[parquet_schema.get_column_root_idx(leaf)] += 1; + } + let encoder = LogRowGroupEncoder { + factory: &factory, + schema: schema.as_ref(), + leaves_per_field: &leaves_per_field, + columns_per_task: log_columns_per_rayon_task( + schema.fields().len(), + rayon::current_num_threads(), + ), + #[cfg(test)] + part_path, + }; + #[cfg_attr(not(test), allow(unused_mut))] + let (batches, mut finisher) = + record_reader.into_log_batches(schema.clone(), time_partition.cloned()); + #[cfg(test)] + { + 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); + let mut timings = LogParquetPhaseTimings::default(); + let prepare = |source: &mut LogRowGroupSource<_>, + timings: &mut LogParquetPhaseTimings| { + #[cfg(test)] + record_log_pipeline_thread(part_path, LogPipelineStage::Prepare); + let started = Instant::now(); + let row_groups = source.next_row_groups(effective_in_flight); + timings.prepare_duration += started.elapsed(); + row_groups + }; + let append = |writer: &mut SerializedFileWriter<_>, + encoded: Vec, + timings: &mut LogParquetPhaseTimings| { + #[cfg(test)] + record_log_pipeline_thread(part_path, LogPipelineStage::Append); + let started = Instant::now(); + let appended = Self::append_encoded_log_row_groups(writer, encoded); + timings.append_duration += started.elapsed(); + appended + }; + + let mut next_row_group_index = writer.flushed_row_groups().len(); + let mut row_groups = prepare(&mut source, &mut timings)?; + let mut encoded = Vec::new(); + while !row_groups.is_empty() { + let first_index = next_row_group_index; + next_row_group_index += row_groups.len(); + timings.row_groups += row_groups.len(); + timings.rows += row_groups.iter().map(|group| group.rows).sum::(); + // Most conversions are a single wave: with nothing to append + // or read meanwhile, it is encoded without a join. + let overlap = !encoded.is_empty() || !source.is_exhausted(); + let file_side = || { + let appended = append(&mut writer, std::mem::take(&mut encoded), &mut timings); + // Nothing more is read for a file that cannot be written. + let prepared = if appended.is_ok() && !source.is_exhausted() { + prepare(&mut source, &mut timings) + } else { + Ok(Vec::new()) + }; + (appended, prepared) + }; + let encode_side = || { + let started = Instant::now(); + let encoded = encoder.encode_row_groups(row_groups, first_index); + (encoded, started.elapsed()) + }; + // The side that owns the file and the readers runs here; the + // encoding side is taken by another pool thread when one is + // free, and otherwise runs here afterwards. + let ((appended, prepared), encoded_row_groups) = if overlap { + rayon::join(file_side, encode_side) + } else { + ((Ok(()), Ok(Vec::new())), encode_side()) + }; + appended?; + let (encoded_row_groups, encode_duration) = encoded_row_groups; + timings.encode_duration += encode_duration; + encoded = encoded_row_groups?; + row_groups = prepared?; + } + append(&mut writer, encoded, &mut timings)?; + // Release the Arrow readers before the file is finished, as the + // metric writer does. + let stats = source.stats.take(); + drop(source); + + let close_started = Instant::now(); + let parquet_metadata = writer.close()?; + timings.close_duration = close_started.elapsed(); + timings.columns_per_task = encoder.columns_per_task; + Ok::<_, StagingError>((parquet_metadata, stats, timings)) + })?; + + debug!( + stream_name = %self.stream_name, + parquet_path = %part_path.display(), + rows = timings.rows, + row_groups = timings.row_groups, + row_group_encode_in_flight = in_flight, + columns_per_rayon_task = timings.columns_per_task, + conversion_threads = LOG_CONVERSION_THREADPOOL.current_num_threads(), + total_ms = conversion_started.elapsed().as_secs_f64() * 1000.0, + prepare_ms = timings.prepare_duration.as_secs_f64() * 1000.0, + encode_ms = timings.encode_duration.as_secs_f64() * 1000.0, + append_ms = timings.append_duration.as_secs_f64() * 1000.0, + close_ms = timings.close_duration.as_secs_f64() * 1000.0, + "Log Arrow-to-Parquet phase timings" + ); + Ok(WrittenParquetArtifacts { + parquet_metadata: Some(Arc::new(parquet_metadata)), + field_stats: stats + .zip(collect_stats_max) + .map(|(stats, max_stats)| (max_stats, stats.finish())), + }) + } + + /// Appends encoded log row groups to the file in their order. + fn append_encoded_log_row_groups( + writer: &mut SerializedFileWriter, + encoded: Vec, + ) -> Result<(), StagingError> { + for row_group in encoded { + let expected_row_group_index = writer.flushed_row_groups().len(); + if row_group.row_group_index != expected_row_group_index { + return Err(ParquetError::General(format!( + "Encoded Parquet row group {} cannot be appended at position {}", + row_group.row_group_index, expected_row_group_index + )) + .into()); + } + let mut row_group_writer = writer.next_row_group()?; + for chunk in row_group.chunks { + chunk.append_to_row_group(&mut row_group_writer)?; + } + row_group_writer.close()?; + } + Ok(()) + } + /// Writes a metric conversion group with pipelined row-group preparation /// and encoding while preserving row-group output order. #[allow(clippy::too_many_arguments)] @@ -4244,6 +5413,17 @@ impl Stream { self.recover_orphan_part_files(); Some(recovery) } else { + // If a prior transient write/seal failure retired a `.part` file + // into `mem.pending`, recover it on the next periodic cycle so + // acknowledged rows reach object storage without waiting for restart. + let has_stranded_parts = self + .writer + .lock() + .map(|writer| writer.has_pending_part_files()) + .unwrap_or(false); + if has_stranded_parts { + self.recover_orphan_part_files(); + } None }; @@ -4586,6 +5766,1255 @@ fn lexsort_to_indices_rows( )) } +#[cfg(test)] +mod log_parquet_pipeline_tests { + use std::fs::File; + + use arrow::compute::concat_batches; + use arrow_array::{ + Array, Int32Array, Int64Array, StringArray, StructArray, TimestampMillisecondArray, + builder::{ListBuilder, StringBuilder}, + }; + use arrow_ipc::writer::StreamWriter as ArrowStreamWriter; + use arrow_schema::{DataType, TimeUnit}; + use parquet::{ + arrow::arrow_reader::ParquetRecordBatchReaderBuilder, + file::{ + properties::ReaderProperties, + serialized_reader::{ReadOptionsBuilder, SerializedFileReader}, + }, + }; + use temp_dir::TempDir; + + use super::*; + + const FIXTURE_FIELDS: usize = 7; + + fn log_stream(dir: &TempDir, name: &str, options: Options) -> StreamRef { + Stream::new( + Arc::new(Options { + local_staging_path: dir.path().to_path_buf(), + ..options + }), + name, + LogStreamMetadata::default(), + None, + &None, + ) + } + + /// A log schema with scalar, struct and list columns, so that Arrow + /// fields and Parquet leaf columns do not line up one to one. `status` + /// can be left out to make the files of a group disagree. + fn log_schema(with_status: bool) -> Arc { + let mut fields = vec![ + Field::new( + DEFAULT_TIMESTAMP_KEY, + DataType::Timestamp(TimeUnit::Millisecond, None), + true, + ), + Field::new("host", DataType::Utf8, true), + Field::new("region", DataType::Utf8, true), + Field::new("message", DataType::Utf8, true), + ]; + if with_status { + fields.push(Field::new("status", DataType::Int64, true)); + } + fields.push(Field::new( + "attrs", + DataType::Struct(Fields::from(vec![ + Field::new("code", DataType::Int32, true), + Field::new("label", DataType::Utf8, true), + ])), + true, + )); + fields.push(Field::new( + "tags", + DataType::List(Arc::new(Field::new_list_field(DataType::Utf8, true))), + true, + )); + Arc::new(Schema::new(fields)) + } + + fn log_batch(schema: &Arc, first_timestamp: i64, rows: usize) -> RecordBatch { + let row_ids = || (0..rows).map(|row| first_timestamp as usize + row); + let mut tags = ListBuilder::new(StringBuilder::new()); + for id in row_ids() { + if id % 9 == 0 { + tags.append_null(); + continue; + } + for tag in 0..id % 3 { + tags.values().append_value(format!("tag-{id}-{tag}")); + } + tags.append(true); + } + let mut columns: Vec = vec![ + Arc::new(TimestampMillisecondArray::from_iter_values( + row_ids().map(|id| id as i64), + )), + Arc::new(StringArray::from_iter( + row_ids().map(|id| (id % 11 != 0).then(|| format!("host-{}", id % 7))), + )), + Arc::new(StringArray::from_iter_values( + row_ids().map(|id| ["ap", "eu", "us"][id % 3]), + )), + Arc::new(StringArray::from_iter_values( + row_ids().map(|id| format!("request {id} {}", "x".repeat((id % 13) * 5))), + )), + ]; + if schema.index_of("status").is_ok() { + columns.push(Arc::new(Int64Array::from_iter( + row_ids().map(|id| (id % 5 != 0).then_some(200 + (id % 4) as i64)), + ))); + } + let DataType::Struct(attr_fields) = schema.field_with_name("attrs").unwrap().data_type() + else { + unreachable!() + }; + columns.push(Arc::new(StructArray::new( + attr_fields.clone(), + vec![ + Arc::new(Int32Array::from_iter( + row_ids().map(|id| (id % 4 != 0).then_some(id as i32)), + )), + Arc::new(StringArray::from_iter_values( + row_ids().map(|id| format!("label-{}", id % 17)), + )), + ], + None, + ))); + columns.push(Arc::new(tags.finish())); + RecordBatch::try_new(schema.clone(), columns).unwrap() + } + + /// Stages `files` Arrow files of `batches` batches of `rows` rows. Time + /// increases within a file, as staged, and no two batches share a + /// timestamp, so the conversion output is strictly newest first. Odd + /// files have no `status` column. + fn stage_arrow_files(dir: &TempDir, files: usize, batches: usize, rows: usize) -> Vec { + (0..files) + .map(|file| { + let schema = log_schema(file % 2 == 0); + let path = dir.path().join(format!("{file}.data.arrows")); + let mut writer = + ArrowStreamWriter::try_new(File::create(&path).unwrap(), &schema).unwrap(); + for batch in 0..batches { + let first_timestamp = ((batch * files + file) * rows) as i64; + writer + .write(&log_batch(&schema, first_timestamp, rows)) + .unwrap(); + } + writer.finish().unwrap(); + path + }) + .collect() + } + + fn reader(files: &[PathBuf]) -> ConversionRecordReader { + ConversionRecordReader::for_stream(files, false) + } + + /// The rows a conversion of `files` must write, in order: what the + /// merged reverse reader yields. + fn merged_batches(files: &[PathBuf], schema: &Arc) -> Vec { + reader(files) + .merged_iter(schema.clone(), None) + .collect::>() + .unwrap() + } + + /// The writer this pipeline replaced: one `ArrowWriter` fed batch by batch. + fn write_sequential( + path: &Path, + files: &[PathBuf], + schema: &Arc, + props: &WriterProperties, + ) { + let mut writer = ArrowWriter::try_new( + File::create(path).unwrap(), + schema.clone(), + Some(props.clone()), + ) + .unwrap(); + for batch in merged_batches(files, schema) { + writer.write(&batch).unwrap(); + } + writer.close().unwrap(); + } + + fn read_parquet(path: &Path) -> RecordBatch { + let reader = ParquetRecordBatchReaderBuilder::try_new(File::open(path).unwrap()) + .unwrap() + .with_batch_size(777) + .build() + .unwrap(); + let batches = reader.collect::, _>>().unwrap(); + concat_batches(&batches[0].schema(), &batches).unwrap() + } + + fn row_group_rows(path: &Path) -> Vec { + let reader = SerializedFileReader::new(File::open(path).unwrap()).unwrap(); + reader + .metadata() + .row_groups() + .iter() + .map(|row_group| row_group.num_rows() as usize) + .collect() + } + + fn assert_same_rows(actual: &RecordBatch, expected: &RecordBatch) { + assert_eq!(actual.num_rows(), expected.num_rows()); + assert_eq!(actual.num_columns(), expected.num_columns()); + for (index, field) in expected.schema().fields().iter().enumerate() { + assert_eq!(actual.schema().field(index).name(), field.name()); + assert_eq!( + actual.column(index).as_ref(), + expected.column(index).as_ref(), + "column {}", + field.name() + ); + } + } + + fn assert_newest_first(rows: &RecordBatch) { + let timestamps = rows + .column_by_name(DEFAULT_TIMESTAMP_KEY) + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + assert!(timestamps.values().windows(2).all(|pair| pair[0] > pair[1])); + } + + #[test] + fn log_pipeline_knobs_have_bounded_defaults() { + assert_eq!(log_row_group_encode_in_flight(None), 2); + assert_eq!(log_row_group_encode_in_flight(Some("1")), 1); + assert_eq!(log_row_group_encode_in_flight(Some(" 5 ")), 5); + assert_eq!(log_row_group_encode_in_flight(Some("0")), 2); + assert_eq!(log_row_group_encode_in_flight(Some("many")), 2); + + // Ten to sixteen columns on an eight-thread pool: one column per task. + for columns in 1..=16 { + assert_eq!(log_columns_per_rayon_task(columns, 8), (columns / 8).max(1)); + } + assert_eq!(log_columns_per_rayon_task(12, 8), 1); + assert_eq!(log_columns_per_rayon_task(12, 2), 6); + assert_eq!(log_columns_per_rayon_task(40, 8), 5); + assert_eq!(log_columns_per_rayon_task(400, 8), 8); + assert_eq!(log_columns_per_rayon_task(3, 0), 3); + } + + fn int_batch(values: std::ops::Range) -> RecordBatch { + RecordBatch::try_from_iter([( + "value", + Arc::new(Int64Array::from_iter_values(values)) as ArrayRef, + )]) + .unwrap() + } + + /// Reads every row group of `source`, `wave` at a time. + fn drain)>>( + mut source: LogRowGroupSource, + wave: usize, + ) -> Vec { + let mut row_groups = Vec::new(); + loop { + let next = source.next_row_groups(wave).unwrap(); + assert!(next.len() <= wave); + if next.is_empty() { + break; + } + // Only the last read may come back short. + assert!(next.len() == wave || source.is_exhausted()); + row_groups.extend(next); + } + // The end is reported again, not an empty row group. + assert!(source.next_row_groups(wave).unwrap().is_empty()); + assert!(source.is_exhausted()); + for row_group in &row_groups { + assert_eq!( + row_group.rows, + row_group + .batches + .iter() + .map(RecordBatch::num_rows) + .sum::() + ); + assert!(row_group.batches.iter().all(|batch| batch.num_rows() > 0)); + } + row_groups + } + + /// Cuts batches that are written as they are into row groups. The cut + /// must not depend on how many row groups are read at a time. + fn cut(batches: &[RecordBatch], max_rows: usize, max_bytes: Option) -> Vec { + let cut_in_waves = |wave| { + drain( + LogRowGroupSource::new( + batches.iter().cloned().map(|batch| (0, Ok(batch))), + LogBatchFinisher::finished(), + max_rows, + max_bytes, + None, + ), + wave, + ) + }; + let pieces = |row_groups: &[LogRowGroup]| { + row_groups + .iter() + .map(|row_group| row_group.batches.clone()) + .collect::>() + }; + let row_groups = cut_in_waves(1); + for wave in [2, 3, 7, 1000] { + assert_eq!( + pieces(&cut_in_waves(wave)), + pieces(&row_groups), + "wave {wave}" + ); + } + row_groups + } + + fn rows_of(row_groups: &[LogRowGroup]) -> Vec { + row_groups.iter().map(|row_group| row_group.rows).collect() + } + + fn values(row_groups: &[LogRowGroup]) -> Vec { + row_groups + .iter() + .flat_map(|row_group| &row_group.batches) + .flat_map(|batch| { + batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .values() + .to_vec() + }) + .collect() + } + + #[test] + fn row_group_source_splits_by_row_count_across_batches() { + let batches = (0..5) + .map(|batch| int_batch(batch * 7..batch * 7 + 7)) + .collect::>(); + let row_groups = cut(&batches, 10, None); + assert_eq!(rows_of(&row_groups), vec![10, 10, 10, 5]); + // 7+3, 4+6, 1+7+2, 5: batches are split, never merged or reordered. + assert_eq!( + row_groups + .iter() + .map(|group| group.batches.len()) + .collect::>(), + vec![2, 2, 3, 1] + ); + assert_eq!(values(&row_groups), (0..35).collect::>()); + + // A batch that fills a row group exactly leaves nothing behind. + let batches = (0..3) + .map(|batch| int_batch(batch * 4..batch * 4 + 4)) + .collect::>(); + let row_groups = cut(&batches, 4, None); + assert_eq!(rows_of(&row_groups), vec![4, 4, 4]); + assert!(row_groups.iter().all(|group| group.batches.len() == 1)); + } + + #[test] + fn row_group_source_splits_by_bytes_before_row_count() { + let batch = int_batch(0..100); + let bytes_per_row = log_batch_data_bytes(&batch).div_ceil(100); + assert_eq!(bytes_per_row, 8); + + // Twenty-five rows of this batch reach the byte limit long before + // the row limit, also inside one batch and across batches. + let row_groups = cut( + &[batch.clone(), int_batch(100..200)], + 1_000_000, + Some(bytes_per_row * 25), + ); + assert_eq!(rows_of(&row_groups), vec![25; 8]); + assert_eq!(values(&row_groups), (0..200).collect::>()); + + // Whichever limit is reached first closes the row group. + let row_groups = cut(std::slice::from_ref(&batch), 10, Some(bytes_per_row * 25)); + assert_eq!(rows_of(&row_groups), vec![10; 10]); + let row_groups = cut(std::slice::from_ref(&batch), 40, Some(bytes_per_row * 25)); + assert_eq!(rows_of(&row_groups), vec![25; 4]); + + // A limit smaller than one row still makes progress, a row at a time. + let row_groups = cut(std::slice::from_ref(&batch), 1_000, Some(1)); + assert_eq!(rows_of(&row_groups), vec![1; 100]); + assert_eq!(values(&row_groups), (0..100).collect::>()); + + // No limit on bytes: only the row count splits. + assert_eq!(rows_of(&cut(&[batch], 1_000, None)), vec![100]); + } + + #[test] + fn row_group_bytes_count_data_not_shared_allocations() { + // Rows staged one batch at a time, as single events are ingested. + let dir = TempDir::new().unwrap(); + let schema = log_schema(true); + let path = dir.path().join("single-rows.data.arrows"); + let mut writer = ArrowStreamWriter::try_new(File::create(&path).unwrap(), &schema).unwrap(); + for row in 0..200 { + writer.write(&log_batch(&schema, row, 1)).unwrap(); + } + writer.finish().unwrap(); + let single_rows = merged_batches(&[path], &schema); + assert_eq!(single_rows.len(), 200); + let whole = log_batch(&schema, 0, 200); + + // The same rows are the same number of bytes however they are + // batched, give or take the per-batch offsets and validity bytes. + let data = log_batch_data_bytes(&whole); + let batched = single_rows.iter().map(log_batch_data_bytes).sum::(); + assert!(batched >= data && batched < 2 * data, "{batched} vs {data}"); + // The allocations behind the decoded batches are many times that: + // a limit counted in them would cut row groups far too small. + let allocated = single_rows + .iter() + .map(RecordBatch::get_array_memory_size) + .sum::(); + assert!(allocated > 5 * data, "{allocated} vs {data}"); + + // A slice counts only its own rows. + let half = log_batch_data_bytes(&whole.slice(50, 100)); + assert!(half > data / 3 && half < 2 * data / 3, "{half} vs {data}"); + + // A limit of a quarter of the data cuts about four row groups. + let row_groups = cut(&single_rows, 1_000_000, Some(batched / 4)); + assert!((4..=5).contains(&row_groups.len()), "{}", row_groups.len()); + } + + #[test] + fn row_group_source_skips_empty_batches_and_surfaces_errors() { + let row_groups = cut( + &[int_batch(0..0), int_batch(0..3), int_batch(3..3)], + 10, + Some(1 << 20), + ); + assert_eq!(rows_of(&row_groups), vec![3]); + assert_eq!(values(&row_groups), vec![0, 1, 2]); + assert!(cut(&[int_batch(0..0), int_batch(0..0)], 10, None).is_empty()); + assert!(cut(&[], 10, None).is_empty()); + + // A row group is not returned short when its source fails. + let failing = [ + Ok(int_batch(0..4)), + Err(ArrowError::IpcError("truncated".into())), + Ok(int_batch(4..8)), + ] + .into_iter() + .map(|batch| (0, batch)); + let mut source = + LogRowGroupSource::new(failing, LogBatchFinisher::finished(), 10, None, None); + assert!(matches!( + source.next_row_groups(2), + Err(StagingError::Arrow(_)) + )); + } + + #[test] + fn log_batches_are_finished_like_the_sequential_reader() { + // Files with different schemas, read in waves of every size: the + // rows handed to the encoder are those of the merged reader, batch + // for batch, and so are the statistics collected on the way. + let dir = TempDir::new().unwrap(); + let files = stage_arrow_files(&dir, 3, 5, 300); + let schema = Arc::new(reader(&files).merged_schema().unwrap()); + let expected = merged_batches(&files, &schema); + assert_eq!(expected.len(), 15); + let expected_stats = crate::storage::field_stats::compute_field_stats_from_batches( + &expected, + "log-pipeline-finish", + &schema, + 5, + ); + for wave in [1, 2, 4, 100] { + let (batches, finisher) = reader(&files).into_log_batches(schema.clone(), None); + let mut source = LogRowGroupSource::new( + batches, + finisher, + 300, + None, + Some(crate::storage::field_stats::FieldStatsAccumulator::new( + "log-pipeline-finish", + &schema, + 5, + )), + ); + let mut finished = Vec::new(); + // Inside the pool, where batches are reversed in parallel. + LOG_CONVERSION_THREADPOOL.install(|| { + loop { + let row_groups = source.next_row_groups(wave).unwrap(); + if row_groups.is_empty() { + break; + } + finished.extend(row_groups.into_iter().flat_map(|group| group.batches)); + } + }); + assert_eq!(finished, expected, "wave {wave}"); + assert_eq!(source.stats.take().unwrap().finish(), expected_stats); + } + + // A file whose column cannot stand for the stream's is an error of + // the read, as it is for the sequential reader. + let conflicting = Arc::new(Schema::new(vec![ + Field::new( + DEFAULT_TIMESTAMP_KEY, + DataType::Timestamp(TimeUnit::Millisecond, None), + true, + ), + Field::new("host", DataType::Int64, true), + ])); + assert!( + reader(&files) + .merged_iter(conflicting.clone(), None) + .any(|batch| batch.is_err()) + ); + let (batches, finisher) = reader(&files).into_log_batches(conflicting, None); + let mut source = LogRowGroupSource::new(batches, finisher, 300, None, None); + assert!(matches!( + source.next_row_groups(2), + Err(StagingError::Arrow(_)) + )); + } + + #[test] + fn parallel_log_writer_is_byte_identical_to_sequential_writer() { + // Row groups cut by row count alone fall where `ArrowWriter` cuts + // them, so the whole file must come out the same: pages, statistics, + // encodings and footer included. Wave sizes around the number of row + // groups cover a last wave that is full, short and absent. + let dir = TempDir::new().unwrap(); + let files = stage_arrow_files(&dir, 3, 4, 700); + let staging = log_stream( + &dir, + "log-pipeline-identical", + Options { + row_group_size: 1500, + row_group_bytes: 0, + collect_dataset_stats: false, + ..Default::default() + }, + ); + let schema = Arc::new(reader(&files).merged_schema().unwrap()); + assert_eq!(schema.fields().len(), FIXTURE_FIELDS); + let props = staging.parquet_writer_props(&schema, None, None, false); + let reference_path = dir.path().join("reference.parquet"); + write_sequential(&reference_path, &files, &schema, &props); + let reference = std::fs::read(&reference_path).unwrap(); + let expected = concat_batches(&schema, &merged_batches(&files, &schema)).unwrap(); + assert_eq!(expected.num_rows(), 3 * 4 * 700); + assert_newest_first(&expected); + assert_eq!( + row_group_rows(&reference_path), + vec![1500, 1500, 1500, 1500, 1500, 900] + ); + + for in_flight in [1, 2, 3, 6, 7, 64] { + let path = dir.path().join(format!("in-flight-{in_flight}.parquet")); + let mut file = File::create(&path).unwrap(); + let artifacts = staging + .write_log_parquet_part_file( + &path, + &mut file, + reader(&files), + &schema, + &props, + None, + None, + in_flight, + ) + .unwrap(); + drop(file); + assert!( + std::fs::read(&path).unwrap() == reference, + "in_flight {in_flight} differs from the sequential writer" + ); + let metadata = artifacts.parquet_metadata.unwrap(); + assert_eq!(metadata.file_metadata().num_rows(), 8400); + assert_eq!(metadata.num_row_groups(), 6); + assert!(artifacts.field_stats.is_none()); + let rows = read_parquet(&path); + assert_same_rows(&rows, &expected); + assert_newest_first(&rows); + } + } + + #[test] + fn log_conversion_preserves_rows_sorting_and_cached_footer() { + let dir = TempDir::new().unwrap(); + let files = stage_arrow_files(&dir, 4, 3, 500); + let staging = log_stream( + &dir, + "log-pipeline-rows", + Options { + row_group_size: 1024, + row_group_bytes: 0, + ..Default::default() + }, + ); + let schema = Arc::new(reader(&files).merged_schema().unwrap()); + let props = staging.parquet_writer_props(&schema, None, None, false); + let path = dir.path().join("rows.parquet.part"); + let artifacts = staging + .write_parquet_part_file(&path, reader(&files), &schema, &props, None, None) + .unwrap() + .unwrap(); + + let expected = concat_batches(&schema, &merged_batches(&files, &schema)).unwrap(); + let rows = read_parquet(&path); + assert_same_rows(&rows, &expected); + assert_newest_first(&rows); + // The file with no `status` column reads back as nulls in its rows. + assert!(rows.column_by_name("status").unwrap().null_count() >= 3000); + assert_eq!( + row_group_rows(&path), + vec![1024, 1024, 1024, 1024, 1024, 880] + ); + + // The footer handed back for the metadata cache is the one on disk, + // and the file passes the validation that is no longer run on it. + assert!(Stream::validate_parquet_file(&path, &staging.stream_name).unwrap()); + let on_disk = SerializedFileReader::new(File::open(&path).unwrap()).unwrap(); + let cached = artifacts.parquet_metadata.unwrap(); + assert_eq!(cached.file_metadata().num_rows(), 6000); + assert_eq!(cached.num_row_groups(), on_disk.metadata().num_row_groups()); + let timestamp_index = schema.index_of(DEFAULT_TIMESTAMP_KEY).unwrap() as i32; + for (cached, on_disk) in cached + .row_groups() + .iter() + .zip(on_disk.metadata().row_groups()) + { + assert_eq!(cached.num_rows(), on_disk.num_rows()); + assert_eq!(cached.total_byte_size(), on_disk.total_byte_size()); + assert_eq!(cached.sorting_columns(), on_disk.sorting_columns()); + assert_eq!( + on_disk.sorting_columns().unwrap(), + &vec![SortingColumn { + column_idx: timestamp_index, + descending: true, + nulls_first: false, + }] + ); + for (cached, on_disk) in cached.columns().iter().zip(on_disk.columns()) { + assert_eq!(cached.file_offset(), on_disk.file_offset()); + assert_eq!(cached.compressed_size(), on_disk.compressed_size()); + } + } + } + + #[test] + fn log_conversion_splits_row_groups_by_bytes() { + let dir = TempDir::new().unwrap(); + let files = stage_arrow_files(&dir, 2, 3, 2000); + let row_group_bytes = 256 * 1024; + let staging = log_stream( + &dir, + "log-pipeline-bytes", + Options { + row_group_size: 1_000_000, + row_group_bytes, + ..Default::default() + }, + ); + let schema = Arc::new(reader(&files).merged_schema().unwrap()); + let props = staging.parquet_writer_props(&schema, None, None, false); + let path = dir.path().join("bytes.parquet.part"); + staging + .write_parquet_part_file(&path, reader(&files), &schema, &props, None, None) + .unwrap() + .unwrap(); + + // The row count alone would give one row group of 12000 rows. The + // row groups in the file are those the byte limit cuts. + let batches = merged_batches(&files, &schema); + let memory = batches.iter().map(log_batch_data_bytes).sum::(); + let (decoded, finisher) = reader(&files).into_log_batches(schema.clone(), None); + let expected_row_groups = rows_of(&drain( + LogRowGroupSource::new(decoded, finisher, 1_000_000, Some(row_group_bytes), None), + 1, + )); + let written = row_group_rows(&path); + assert_eq!(written, expected_row_groups); + assert_eq!(written.iter().sum::(), 12_000); + assert!(written.len() >= memory / row_group_bytes, "{written:?}"); + assert!(written.len() > 4, "{written:?}"); + // No row group holds much more than its share of the rows: none was + // left to grow without bound. + let average_row = memory.div_ceil(12_000); + assert!( + written + .iter() + .all(|rows| rows * average_row <= 2 * row_group_bytes), + "{written:?}" + ); + + let rows = read_parquet(&path); + assert_same_rows(&rows, &concat_batches(&schema, &batches).unwrap()); + assert_newest_first(&rows); + } + + #[test] + fn log_conversion_keeps_bloom_filters_and_custom_partition_encoding() { + let dir = TempDir::new().unwrap(); + let files = stage_arrow_files(&dir, 2, 3, 1200); + let staging = log_stream( + &dir, + "log-pipeline-bloom", + Options { + row_group_size: 2048, + row_group_bytes: 0, + parquet_bloom_filter_columns: vec!["host".into(), "missing".into()], + ..Default::default() + }, + ); + let schema = Arc::new(reader(&files).merged_schema().unwrap()); + let custom_partition = "region".to_string(); + let props = staging.parquet_writer_props(&schema, None, Some(&custom_partition), false); + let path = dir.path().join("bloom.parquet.part"); + staging + .write_parquet_part_file(&path, reader(&files), &schema, &props, None, None) + .unwrap() + .unwrap(); + + // Same bytes as the sequential writer: filters, encodings and + // sorting metadata are those it would have written. + let reference_path = dir.path().join("bloom-reference.parquet"); + write_sequential(&reference_path, &files, &schema, &props); + assert!(std::fs::read(&path).unwrap() == std::fs::read(&reference_path).unwrap()); + + let read_options = ReadOptionsBuilder::new() + .with_reader_properties( + ReaderProperties::builder() + .set_read_bloom_filter(true) + .build(), + ) + .build(); + let reader = + SerializedFileReader::new_with_options(File::open(&path).unwrap(), read_options) + .unwrap(); + let timestamp_index = schema.index_of(DEFAULT_TIMESTAMP_KEY).unwrap(); + let host_index = schema.index_of("host").unwrap(); + let region_index = schema.index_of("region").unwrap(); + assert_eq!(reader.num_row_groups(), 4); + for index in 0..reader.num_row_groups() { + let row_group = reader.get_row_group(index).unwrap(); + let metadata = row_group.metadata(); + assert_eq!( + metadata.sorting_columns().unwrap(), + &vec![ + SortingColumn { + column_idx: timestamp_index as i32, + descending: true, + nulls_first: false, + }, + SortingColumn { + column_idx: region_index as i32, + descending: true, + nulls_first: true, + }, + ] + ); + for column in 0..metadata.num_columns() { + assert_eq!( + metadata.column(column).bloom_filter_offset().is_some(), + column == host_index, + "column {column}" + ); + } + let filter = row_group.get_column_bloom_filter(host_index).unwrap(); + for host in 0..7 { + assert!(filter.check(&format!("host-{host}").as_str())); + } + assert!(!filter.check(&"host-absent")); + } + // The encodings asked for the partition and time columns are those + // of the properties the row groups were encoded with. + assert_eq!( + props.encoding(&ColumnPath::new(vec!["region".into()])), + Some(Encoding::DELTA_BYTE_ARRAY) + ); + assert_eq!( + props.encoding(&ColumnPath::new(vec![DEFAULT_TIMESTAMP_KEY.into()])), + Some(Encoding::DELTA_BINARY_PACKED) + ); + let rows = read_parquet(&path); + assert_same_rows( + &rows, + &concat_batches(&schema, &merged_batches(&files, &schema)).unwrap(), + ); + } + + #[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 staging = log_stream( + &dir, + "log-pipeline-stats", + Options { + // Row groups cut batches apart; statistics must not notice. + row_group_size: 1100, + row_group_bytes: 96 * 1024, + collect_dataset_stats: true, + max_field_statistics: 5, + ..Default::default() + }, + ); + let schema = Arc::new(reader(&files).merged_schema().unwrap()); + let props = staging.parquet_writer_props(&schema, None, None, false); + let path = dir.path().join("stats.parquet.part"); + let artifacts = staging + .write_parquet_part_file(&path, reader(&files), &schema, &props, None, None) + .unwrap() + .unwrap(); + assert!(row_group_rows(&path).len() > 9); + + let (max_field_statistics, stats) = artifacts.field_stats.unwrap(); + assert_eq!(max_field_statistics, 5); + let expected = crate::storage::field_stats::compute_field_stats_from_batches( + &merged_batches(&files, &schema), + &staging.stream_name, + &schema, + 5, + ); + assert_eq!(stats, expected); + let host = stats.iter().find(|stat| stat.field_name == "host").unwrap(); + assert!(host.count > 0 && host.distinct_count >= 7, "{host:?}"); + + // Statistics are not collected when the stream does not ask for them. + let quiet = log_stream( + &dir, + "log-pipeline-no-stats", + Options { + row_group_size: 1100, + collect_dataset_stats: false, + ..Default::default() + }, + ); + let quiet_path = dir.path().join("no-stats.parquet.part"); + let artifacts = quiet + .write_parquet_part_file(&quiet_path, reader(&files), &schema, &props, None, None) + .unwrap() + .unwrap(); + assert!(artifacts.field_stats.is_none()); + } + + #[test] + fn log_conversion_of_no_rows_writes_no_file() { + let dir = TempDir::new().unwrap(); + let schema = log_schema(true); + // A readable file whose batches have no rows: one batch, then several. + for batches in [1, 3] { + let arrow_path = dir.path().join(format!("empty-{batches}.data.arrows")); + let mut writer = + ArrowStreamWriter::try_new(File::create(&arrow_path).unwrap(), &schema).unwrap(); + for _ in 0..batches { + writer.write(&log_batch(&schema, 0, 0)).unwrap(); + } + writer.finish().unwrap(); + + let staging = log_stream( + &dir, + "log-pipeline-empty", + Options { + row_group_size: 1024, + ..Default::default() + }, + ); + let props = staging.parquet_writer_props(&schema, None, None, false); + let record_reader = reader(&[arrow_path]); + assert_eq!(record_reader.reader_count(), 1); + let path = dir.path().join(format!("empty-{batches}.parquet.part")); + let written = staging + .write_parquet_part_file(&path, record_reader, &schema, &props, None, None) + .unwrap(); + assert!(written.is_none()); + assert!(!path.exists()); + } + } + + fn pipeline_threads(path: &Path, convert: impl FnOnce()) -> Vec<(LogPipelineStage, String)> { + LOG_PIPELINE_THREADS + .lock() + .unwrap() + .insert(path.to_path_buf(), Vec::new()); + convert(); + LOG_PIPELINE_THREADS.lock().unwrap().remove(path).unwrap() + } + + #[test] + fn log_conversion_work_stays_on_the_conversion_pool() { + let dir = TempDir::new().unwrap(); + // Batches large enough for the reader to reverse their columns in + // parallel, row groups large enough to encode theirs in parallel. + let files = stage_arrow_files(&dir, 2, 3, 2000); + let staging = log_stream( + &dir, + "log-pipeline-threads", + Options { + row_group_size: 2048, + row_group_bytes: 0, + ..Default::default() + }, + ); + let schema = Arc::new(reader(&files).merged_schema().unwrap()); + let props = staging.parquet_writer_props(&schema, None, None, false); + let expected = concat_batches(&schema, &merged_batches(&files, &schema)).unwrap(); + let convert = |path: &Path| { + staging + .write_parquet_part_file(path, reader(&files), &schema, &props, None, None) + .unwrap() + .unwrap(); + }; + let foreign_pool = rayon::ThreadPoolBuilder::new() + .num_threads(3) + .thread_name(|index| format!("foreign-pool-{index}")) + .build() + .unwrap(); + + // The caller may be a plain thread (startup conversion, this test), + // a conversion worker (periodic conversion), or a worker of another + // Rayon pool. The work of the conversion never follows it there. + type Caller<'a> = &'a (dyn Fn(&Path) + Sync); + let callers: [(&str, Caller); 4] = [ + ("plain", &|path| convert(path)), + ("conversion", &|path| { + LOG_CONVERSION_THREADPOOL.install(|| convert(path)) + }), + ("foreign", &|path| foreign_pool.install(|| convert(path))), + ("global", &|path| { + rayon::scope(|scope| scope.spawn(|_| convert(path))) + }), + ]; + for (caller, run) in callers { + let path = dir.path().join(format!("threads-{caller}.parquet.part")); + let threads = pipeline_threads(&path, || run(&path)); + let stage_count = |stage| { + threads + .iter() + .filter(|(recorded, _)| *recorded == stage) + .count() + }; + let row_groups = row_group_rows(&path).len(); + assert_eq!(row_groups, 6, "{caller}"); + assert_eq!(stage_count(LogPipelineStage::EncodeRowGroup), row_groups); + assert_eq!( + stage_count(LogPipelineStage::EncodeColumn), + row_groups * FIXTURE_FIELDS + ); + // Six staged batches, each reversed once. + assert_eq!(stage_count(LogPipelineStage::Reverse), 6, "{caller}"); + assert!(stage_count(LogPipelineStage::Prepare) >= 1, "{caller}"); + assert!(stage_count(LogPipelineStage::Append) >= 1, "{caller}"); + assert!( + threads + .iter() + .all(|(_, thread)| thread.starts_with("log-conversion-")), + "{caller}: {threads:?}" + ); + assert_same_rows(&read_parquet(&path), &expected); + } + } + + #[test] + fn log_conversion_through_staging_keeps_newest_first_across_row_groups() { + let dir = TempDir::new().unwrap(); + let staging = log_stream( + &dir, + "log-pipeline-staged", + Options { + row_group_size: 2500, + ..Default::default() + }, + ); + let schema = log_schema(true); + let event_time = (Utc::now() - chrono::TimeDelta::minutes(2)).naive_utc(); + for batch in 0..3 { + staging + .push( + "log-pipeline-schema", + &log_batch(&schema, batch * 2000, 2000), + event_time, + &HashMap::new(), + StreamType::UserDefined, + ) + .unwrap(); + } + staging.flush(true).unwrap(); + staging + .convert_disk_files_to_parquet(None, None, false, true, &None) + .unwrap(); + + let parquet_files = staging.parquet_files(); + assert_eq!(parquet_files.len(), 1); + assert_eq!(row_group_rows(&parquet_files[0]), vec![2500, 2500, 1000]); + let rows = read_parquet(&parquet_files[0]); + assert_eq!(rows.num_rows(), 6000); + assert_newest_first(&rows); + let expected = (0..3) + .rev() + .map(|batch| crate::utils::arrow::reverse(&log_batch(&schema, batch * 2000, 2000))) + .collect::>(); + assert_same_rows(&rows, &concat_batches(&schema, &expected).unwrap()); + assert!(staging.arrow_files().is_empty()); + } + + #[test] + fn log_conversion_completes_without_deadlock_on_one_and_two_worker_pools() { + let dir = TempDir::new().unwrap(); + let files = stage_arrow_files(&dir, 2, 4, 300); + let schema = Arc::new(reader(&files).merged_schema().unwrap()); + let stream = log_stream( + &dir, + "log-small-pool", + Options { + row_group_size: 400, + ..Default::default() + }, + ); + let props = stream.parquet_writer_props(&schema, None, None, false); + let expected_path = dir.path().join("expected.parquet"); + write_sequential(&expected_path, &files, &schema, &props); + let expected_bytes = fs::read(&expected_path).unwrap(); + + for num_threads in [1usize, 2usize] { + let pool = rayon::ThreadPoolBuilder::new() + .num_threads(num_threads) + .build() + .unwrap(); + let outputs: Vec = (0..6) + .map(|idx| { + dir.path() + .join(format!("pool-{num_threads}-out-{idx}.parquet")) + }) + .collect(); + pool.install(|| { + outputs.par_iter().for_each(|out_path| { + let mut out_file = fs::File::create(out_path).unwrap(); + stream + .write_log_parquet_part_file_on_pool( + &pool, + out_path, + &mut out_file, + reader(&files), + &schema, + &props, + None, + Some(1000), + 2, + ) + .unwrap(); + }); + }); + for out_path in &outputs { + assert_eq!( + fs::read(out_path).unwrap(), + expected_bytes, + "pool with {num_threads} thread(s) produced divergent Parquet output" + ); + } + } + } + + #[test] + fn wide_schema_churn_conversion_stays_bounded_and_byte_identical() { + let dir = TempDir::new().unwrap(); + // One wide file (900 nullable Int64 fields + p_timestamp) mixed with narrow + // 2-column batches: adapted narrow rows allocate ~7.2 KiB/row of null arrays. + let mut wide_fields = vec![Field::new( + DEFAULT_TIMESTAMP_KEY, + DataType::Timestamp(TimeUnit::Millisecond, None), + false, + )]; + for idx in 0..900 { + wide_fields.push(Field::new(format!("c{idx:03}"), DataType::Int64, true)); + } + let wide_schema = Arc::new(Schema::new(wide_fields)); + let narrow_schema = Arc::new(Schema::new(vec![ + Field::new( + DEFAULT_TIMESTAMP_KEY, + DataType::Timestamp(TimeUnit::Millisecond, None), + false, + ), + Field::new("c000", DataType::Int64, true), + ])); + + let wide_path = dir.path().join("wide.arrows"); + { + let mut cols: Vec = + vec![Arc::new(TimestampMillisecondArray::from(vec![ + 1_000_000i64, + ]))]; + for idx in 0..900i64 { + cols.push(Arc::new(Int64Array::from(vec![Some(idx)]))); + } + let wide_batch = RecordBatch::try_new(wide_schema.clone(), cols).unwrap(); + let mut writer = + ArrowStreamWriter::try_new(fs::File::create(&wide_path).unwrap(), &wide_schema) + .unwrap(); + writer.write(&wide_batch).unwrap(); + writer.finish().unwrap(); + } + let narrow_path = dir.path().join("narrow.arrows"); + { + let mut writer = + ArrowStreamWriter::try_new(fs::File::create(&narrow_path).unwrap(), &narrow_schema) + .unwrap(); + for b in 0..5i64 { + let ts: Vec = (0..10).map(|i| 1_000_100 + b * 10 + i).collect(); + let vals: Vec> = (0..10).map(|i| Some(b * 10 + i)).collect(); + let batch = RecordBatch::try_new( + narrow_schema.clone(), + vec![ + Arc::new(TimestampMillisecondArray::from(ts)), + Arc::new(Int64Array::from(vals)), + ], + ) + .unwrap(); + writer.write(&batch).unwrap(); + } + writer.finish().unwrap(); + } + + let files = vec![wide_path, narrow_path]; + let merged_schema = Arc::new(reader(&files).merged_schema().unwrap()); + let row_floor = merged_schema_adapted_row_bytes(&merged_schema); + assert!(row_floor >= 900 * 8, "row floor was {row_floor}"); + assert!( + 262_144usize.saturating_mul(row_floor) > LOG_PARALLEL_ROW_GROUP_MAX_ADAPTED_BYTES, + "default 262k rows * 900 Int64 columns must trigger streaming fallback" + ); + + // Case 1: default row_group_bytes = 0 takes streaming fallback and matches sequential bytes. + let stream_default = log_stream( + &dir, + "wide-churn-default", + Options { + row_group_size: 262_144, + row_group_bytes: 0, + ..Default::default() + }, + ); + let props = stream_default.parquet_writer_props(&merged_schema, None, None, false); + let expected_path = dir.path().join("wide-expected.parquet"); + write_sequential(&expected_path, &files, &merged_schema, &props); + let actual_path = dir.path().join("wide-actual.parquet"); + let mut actual_file = fs::File::create(&actual_path).unwrap(); + stream_default + .write_log_parquet_part_file( + &actual_path, + &mut actual_file, + reader(&files), + &merged_schema, + &props, + None, + None, + 2, + ) + .unwrap(); + assert_eq!( + fs::read(&actual_path).unwrap(), + fs::read(&expected_path).unwrap() + ); + + // Case 2: explicit row_group_bytes budgets narrow rows by merged-schema footprint. + let stream_capped = log_stream( + &dir, + "wide-churn-capped", + Options { + row_group_size: 262_144, + row_group_bytes: 64 * 1024, + ..Default::default() + }, + ); + let capped_path = dir.path().join("wide-capped.parquet"); + let mut capped_file = fs::File::create(&capped_path).unwrap(); + stream_capped + .write_log_parquet_part_file( + &capped_path, + &mut capped_file, + reader(&files), + &merged_schema, + &props, + None, + None, + 2, + ) + .unwrap(); + let rg_rows = row_group_rows(&capped_path); + assert_eq!(rg_rows.iter().sum::(), 51); + assert!( + rg_rows.iter().all(|&rows| rows <= 10), + "narrow batches under 900-col merged schema should be cut to <= 10 rows per 64 KiB RG, got {rg_rows:?}" + ); + } + + #[test] + fn periodic_flush_recovers_retired_part_file_without_restart() { + let dir = TempDir::new().unwrap(); + let staging = log_stream( + &dir, + "retired-part-periodic-recovery", + Options { + row_group_size: 1000, + ..Default::default() + }, + ); + let schema = log_schema(true); + let event_time = (Utc::now() - chrono::TimeDelta::minutes(2)).naive_utc(); + staging + .push( + "retired-part-schema", + &log_batch(&schema, 1000, 12), + event_time, + &HashMap::new(), + StreamType::UserDefined, + ) + .unwrap(); + + // Simulate a write/flush failure retiring the active `.part` writer into `mem.pending`. + let part_path = { + let mut guard = staging.writer.lock().unwrap(); + let active = guard.active_part_paths(); + assert_eq!(active.len(), 1); + let part_path = active.into_iter().next().unwrap(); + let mut deferred = crate::parseable::staging::writer::DeferredDrop::default(); + let key = guard + .disk_keys_for_test() + .into_iter() + .next() + .expect("attached disk key"); + guard.retire_for_test(&key, &mut deferred); + assert!(guard.has_pending_part_files()); + part_path + }; + assert!(part_path.exists()); + + // Advance the conversion clock past the current minute (simulating the next + // periodic sync tick) so non-init, non-shutdown conversion claims the + // recovered `.arrows` file and converts it to Parquet without a restart. + *staging.conversion_clock.lock().unwrap() = + Some(SystemTime::now() + std::time::Duration::from_secs(120)); + staging.flush_and_convert(false, false, &None).unwrap(); + assert!(!part_path.exists(), "retired .part should be recovered"); + let parquet_files = staging.parquet_files(); + assert_eq!(parquet_files.len(), 1); + assert_eq!(read_parquet(&parquet_files[0]).num_rows(), 12); + assert!(!staging.writer.lock().unwrap().has_pending_part_files()); + } +} + #[cfg(test)] mod crash_recovery_tests; diff --git a/src/parseable/streams/conversion_journal.rs b/src/parseable/streams/conversion_journal.rs index 524e31b4d..6d3a53229 100644 --- a/src/parseable/streams/conversion_journal.rs +++ b/src/parseable/streams/conversion_journal.rs @@ -391,6 +391,7 @@ impl Stream { .open(&tmp)?; file.write_all(&bytes)?; file.sync_all()?; + drop(file); self.conversion_phase(ConversionPhase::JournalTmpSynced); // Output claims protect tmp writes/cleanup. Keep only conflict check, // install rename and reservations atomic under the registry lock. @@ -413,6 +414,7 @@ impl Stream { } } drop(registry); + drop(_inventory); sync_directory(&self.data_path)?; Ok(()) } diff --git a/src/parseable/streams/log_clustering.rs b/src/parseable/streams/log_clustering.rs index 51e7b58e4..4aea587db 100644 --- a/src/parseable/streams/log_clustering.rs +++ b/src/parseable/streams/log_clustering.rs @@ -29,8 +29,29 @@ //! //! Clustered files declare no `sorting_columns`: per-row-group order is not //! a file-level timestamp order, and Parseable never trusts footer ordering. +//! +//! Conversion runs [`write_clustered_log_parquet_on_pool`]: the row groups of +//! a file are read, clustered and encoded as a pipeline on the log conversion +//! pool, each row group's columns in parallel, with the same bytes as the +//! sequential [`write_clustered_log_parquet`], which remains the +//! memory-bounded fallback for row groups too large to pipeline. +//! +//! Memory is bounded by the rows themselves, not only by the schema: rows stop +//! accumulating into a clustered row group once their Arrow data reaches +//! [`CLUSTER_ROW_GROUP_MAX_BYTES`] (so a row group of large string payloads +//! has fewer rows than the target), and once a row group's finished rows +//! retain more than [`CLUSTER_OVERLAP_MAX_RETAINED_BYTES`], the rest of the +//! file is read and encoded one row group at a time. -use std::{io::Write, sync::Arc, time::Duration, time::Instant}; +use std::{ + io::Write, + sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }, + time::Duration, + time::Instant, +}; use arrow::{ compute::{concat, interleave}, @@ -38,19 +59,84 @@ use arrow::{ }; use arrow_array::{Array, ArrayRef, RecordBatch}; use arrow_schema::{ArrowError, DataType, Schema, SortOptions}; -use parquet::{arrow::ArrowWriter, errors::ParquetError, file::properties::WriterProperties}; +use parquet::{ + arrow::{ + ArrowWriter, + arrow_writer::{ + ArrowColumnChunk, ArrowColumnWriter, ArrowRowGroupWriterFactory, compute_leaves, + }, + }, + errors::ParquetError, + file::{metadata::ParquetMetaData, properties::WriterProperties, writer::SerializedFileWriter}, +}; use rayon::{ - iter::{IntoParallelIterator, ParallelIterator}, + iter::{ + IndexedParallelIterator, IntoParallelIterator, IntoParallelRefIterator, ParallelIterator, + }, slice::ParallelSliceMut, }; +use super::{ + DecodedLogBatches, LOG_PARALLEL_ENCODE_MIN_ROWS, LOG_PARALLEL_ROW_GROUP_MAX_ADAPTED_BYTES, + LOG_PARALLEL_WAVE_SOFT_BYTES, LogBatchFinisher, LogRowGroup, LogRowGroupSource, + log_batch_bytes_per_row, log_batch_data_bytes, log_columns_per_rayon_task, + merged_schema_adapted_row_bytes, +}; +#[cfg(test)] +use super::{LogPipelineStage, record_log_pipeline_thread}; use crate::{ event::{DEFAULT_TIMESTAMP_KEY, format::LogSource}, handlers::TelemetryType, parseable::staging::StagingError, - storage::StreamType, + storage::{ + StreamType, + field_stats::{FieldStatsAccumulator, MAX_INLINE_FIELD_STATS_BYTES}, + }, }; +/// Arrow data at which rows stop accumulating into a clustered row group. +/// +/// A clustered row group is buffered whole before it is ordered, so its rows +/// must be bounded in bytes as well as in count: at 2 KiB per row, a group of +/// the default 262,144 rows would hold 512 MiB. A group closes at the row +/// target or once its rows reach this many bytes, whichever comes first, so +/// row groups of ordinary rows keep exactly the rows the unclustered writer +/// gives them, and only groups of large rows are cut short. Rows are counted +/// at the data size per row of the batch they come from, as the unclustered +/// writer counts them against `row_group_bytes`. +pub(super) const CLUSTER_ROW_GROUP_MAX_BYTES: usize = LOG_PARALLEL_ROW_GROUP_MAX_ADAPTED_BYTES; + +/// Retained memory of one clustered row group's finished rows above which +/// the rest of a file is written without overlap: one row group is read, +/// then clustered and encoded, then appended, and no other is read while it +/// is held. Measured from the allocations the finished rows keep alive, so +/// string payloads, adapter padding and shared buffers all count. +pub(super) const CLUSTER_OVERLAP_MAX_RETAINED_BYTES: usize = LOG_PARALLEL_WAVE_SOFT_BYTES; + +/// Memory limits of one clustered conversion. Tests lower them to exercise +/// the large-row paths with small inputs. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) struct ClusterMemoryLimits { + /// See [`CLUSTER_ROW_GROUP_MAX_BYTES`]. + pub(super) row_group_max_bytes: usize, + /// See [`CLUSTER_OVERLAP_MAX_RETAINED_BYTES`]. + pub(super) overlap_max_retained_bytes: usize, + /// Inline field statistics are dropped, and left to the post-write + /// reread of the file, once they retain more than this or become + /// approximate: see `FieldStatsAccumulator::exceeds_inline_budget`. + pub(super) inline_stats_max_bytes: usize, +} + +impl Default for ClusterMemoryLimits { + fn default() -> Self { + Self { + row_group_max_bytes: CLUSTER_ROW_GROUP_MAX_BYTES, + overlap_max_retained_bytes: CLUSTER_OVERLAP_MAX_RETAINED_BYTES, + inline_stats_max_bytes: MAX_INLINE_FIELD_STATS_BYTES, + } + } +} + /// Column positions in the merged conversion schema used to cluster one file. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(super) struct LogClusterKey { @@ -306,13 +392,45 @@ pub(super) fn cluster_row_group( #[derive(Debug, Default, Clone, Copy)] pub(super) struct LogClusterWriteStats { pub(super) rows: usize, + /// Clustered row groups: groups of `target_rows` rows, or fewer for the + /// last one and for groups cut at [`CLUSTER_ROW_GROUP_MAX_BYTES`]. The + /// writer's own limits may split one into several Parquet row groups, as + /// `ArrowWriter` would. pub(super) row_groups: usize, + /// Time spent ordering rows, and in the sequential writer gathering them; + /// the parallel writer gathers each column as it encodes it. pub(super) cluster_duration: Duration, + /// Clustered row groups the writer's limits split into several Parquet + /// row groups. + pub(super) split_row_groups: usize, + /// Clustered row groups the parallel writer encoded twice: column by + /// column, then again batch by batch because the writer's byte limit + /// split them. After the first, the rest of the file's row groups are + /// encoded batch by batch straight away. + pub(super) reencoded_row_groups: usize, + /// Whether the file was written by the sequential writer because one of + /// its row groups was estimated too large to pipeline. + pub(super) sequential: bool, + /// Whether the parallel writer stopped overlapping reading, encoding and + /// appending because a row group's rows retained more than + /// [`CLUSTER_OVERLAP_MAX_RETAINED_BYTES`]. + pub(super) serial: bool, + pub(super) columns_per_task: usize, + pub(super) prepare_duration: Duration, + pub(super) encode_duration: Duration, + pub(super) append_duration: Duration, + pub(super) close_duration: Duration, } /// Writes log batches to `file`, clustering each row group of exactly /// `target_rows` rows (the final group may be partial). Row-group membership /// matches what `ArrowWriter` would produce for the same input sequence. +/// +/// This is the sequential writer: one row group is buffered and written at a +/// time. [`write_clustered_log_parquet_on_pool`] writes the same bytes and +/// falls back to it for row groups too large to pipeline; tests use it as +/// the reference. +#[cfg(test)] pub(super) fn write_clustered_log_parquet( file: &mut W, records: impl Iterator>, @@ -321,16 +439,47 @@ pub(super) fn write_clustered_log_parquet( target_rows: usize, key: LogClusterKey, ) -> Result { + // Finished batches have every column of the merged schema. + let records = records.map(|record| { + record.map(|batch| { + let bytes_per_row = log_batch_bytes_per_row(&batch, 0, 0); + (batch, bytes_per_row) + }) + }); + write_clustered_log_parquet_sequential( + file, + records, + schema, + props, + target_rows, + CLUSTER_ROW_GROUP_MAX_BYTES, + key, + ) + .map(|(_, stats)| stats) +} + +/// Writes `records`, each finished batch with the bytes per row its rows +/// count against `max_bytes` (see `log_batch_bytes_per_row`), one clustered +/// row group at a time. A row group closes at `target_rows` rows or once its +/// rows reach `max_bytes`, as [`LogRowGroupSource`] cuts them for the +/// parallel writer. +fn write_clustered_log_parquet_sequential( + file: &mut W, + records: impl Iterator>, + schema: &Arc, + props: &WriterProperties, + target_rows: usize, + max_bytes: usize, + key: LogClusterKey, +) -> Result<(ParquetMetaData, LogClusterWriteStats), StagingError> { if target_rows == 0 { - return Err(ParquetError::General( - "Parquet row-group target must be greater than zero".to_string(), - ) - .into()); + return Err(zero_target_error()); } let mut writer = ArrowWriter::try_new(file, schema.clone(), Some(props.clone()))?; let mut stats = LogClusterWriteStats::default(); let mut buffer: Vec = Vec::new(); let mut buffered_rows = 0; + let mut buffered_bytes = 0usize; let emit = |buffer: Vec, writer: &mut ArrowWriter<&mut W>, @@ -352,23 +501,871 @@ pub(super) fn write_clustered_log_parquet( }; for record in records { - let record = record?; + let (record, bytes_per_row) = record?; + let bytes_per_row = bytes_per_row.max(1); let record_rows = record.num_rows(); let mut offset = 0; while offset < record_rows { - let rows = (target_rows - buffered_rows).min(record_rows - offset); - buffer.push(record.slice(offset, rows)); - buffered_rows += rows; - offset += rows; - if buffered_rows == target_rows { + // An empty row group takes a row whatever its size, so a row + // larger than the limit is still written. + let rows_within_bytes = (max_bytes.saturating_sub(buffered_bytes) / bytes_per_row) + .max(usize::from(buffered_rows == 0)); + let rows = (target_rows - buffered_rows) + .min(record_rows - offset) + .min(rows_within_bytes); + if rows > 0 { + buffer.push(record.slice(offset, rows)); + buffered_rows += rows; + buffered_bytes = buffered_bytes.saturating_add(rows.saturating_mul(bytes_per_row)); + offset += rows; + } + // A batch whose rows do not all fit closes the row group. + if offset < record_rows || buffered_rows == target_rows || buffered_bytes >= max_bytes { emit(std::mem::take(&mut buffer), &mut writer, &mut stats)?; buffered_rows = 0; + buffered_bytes = 0; } } } if buffered_rows > 0 { emit(buffer, &mut writer, &mut stats)?; } - writer.close()?; - Ok(stats) + let close_started = Instant::now(); + let metadata = writer.close()?; + stats.close_duration = close_started.elapsed(); + Ok((metadata, stats)) +} + +fn zero_target_error() -> StagingError { + ParquetError::General("Parquet row-group target must be greater than zero".to_string()).into() +} + +/// Decoded rows a wave of row groups may hold while the next wave is read. +/// A larger wave is encoded before more rows are read, so a conversion of +/// large rows holds one wave of decoded rows at a time, as the sequential +/// writer holds one row group. +const CLUSTER_READ_AHEAD_MAX_BYTES: usize = LOG_PARALLEL_WAVE_SOFT_BYTES; + +/// What a clustered conversion wrote. +pub(super) struct ClusteredParquetOutput { + pub(super) metadata: ParquetMetaData, + /// The statistics passed in, updated with every row in source order. + pub(super) stats: Option, + pub(super) write_stats: LogClusterWriteStats, +} + +/// Writes a clustered log conversion on `pool`, with the bytes +/// [`write_clustered_log_parquet`] writes for the finished `batches`. +/// +/// Row groups are cut from the batches at exactly `target_rows` rows, as the +/// sequential writer cuts them, and read, clustered and encoded in waves of +/// up to `in_flight` row groups: while one wave is clustered and encoded, +/// each row group's columns in parallel, the previous wave is appended and +/// the next one read. As in the unclustered log writer, the steps are joined +/// on the pool rather than passed between threads, so a pool whose every +/// thread converts a stream cannot deadlock. +/// +/// Each column of a row group is given to its column writer in the batches +/// the sequential writer gives `ArrowWriter`: the buffered slices when they +/// are already in cluster order, else gathers of +/// [`CLUSTER_OUTPUT_BATCH_ROWS`] rows. Its pages are therefore the same, and +/// a gather of one column is all a column task holds beyond the buffered +/// rows. When `ArrowWriter` would split the row group by the writer's row or +/// byte limits, the row group is encoded again batch by batch, as it would. +/// +/// Once the writer's limits split one row group, the rest are encoded batch +/// by batch straight away rather than encoded twice. +/// +/// Memory: rows stop accumulating into a row group once their Arrow data +/// reaches [`CLUSTER_ROW_GROUP_MAX_BYTES`], in both writers. A row group +/// estimated larger than the unclustered writer's parallel ceiling under the +/// merged schema is written by the sequential writer, which holds one row +/// group at a time (as are files written with content-defined chunking); +/// above the wave target, waves hold one row group; a wave whose decoded +/// rows exceed the read-ahead budget is encoded before the next one is read; +/// and once a row group's finished rows retain more than +/// [`CLUSTER_OVERLAP_MAX_RETAINED_BYTES`], the rest of the file is read, +/// encoded and appended one row group at a time. +/// +/// `stats`, when given, sees every finished batch whole and in source order. +/// It is dropped, releasing its values, as soon as it exceeds the inline +/// budget or becomes approximate (its top values could then differ from a +/// count of the clustered file); the caller then computes the statistics +/// from the written file. +#[allow(clippy::too_many_arguments)] +pub(super) fn write_clustered_log_parquet_on_pool( + pool: &rayon::ThreadPool, + file: &mut W, + batches: DecodedLogBatches, + finisher: LogBatchFinisher, + schema: &Arc, + props: &WriterProperties, + target_rows: usize, + key: LogClusterKey, + in_flight: usize, + stats: Option, + part_path: &std::path::Path, +) -> Result { + write_clustered_log_parquet_on_pool_with_limits( + pool, + file, + batches, + finisher, + schema, + props, + target_rows, + key, + in_flight, + stats, + part_path, + ClusterMemoryLimits::default(), + ) +} + +/// [`write_clustered_log_parquet_on_pool`] under `limits`. +#[allow(clippy::too_many_arguments)] +pub(super) fn write_clustered_log_parquet_on_pool_with_limits( + pool: &rayon::ThreadPool, + file: &mut W, + batches: DecodedLogBatches, + finisher: LogBatchFinisher, + schema: &Arc, + props: &WriterProperties, + target_rows: usize, + key: LogClusterKey, + in_flight: usize, + stats: Option, + part_path: &std::path::Path, + limits: ClusterMemoryLimits, +) -> Result { + #[cfg(not(test))] + let _ = part_path; + if target_rows == 0 { + return Err(zero_target_error()); + } + let merged_columns = schema.fields().len(); + let merged_row_bytes = merged_schema_adapted_row_bytes(schema.as_ref()); + let estimated_rg_bytes = target_rows.saturating_mul(merged_row_bytes); + + // `install` keeps every parallel step, including sorting and gathering + // in the sequential writer, on the conversion pool. + pool.install(|| { + // Content-defined chunking keeps per-column chunker state inside + // `ArrowWriter` that column writers alone do not reproduce. + if estimated_rg_bytes > LOG_PARALLEL_ROW_GROUP_MAX_ADAPTED_BYTES + || props.content_defined_chunking().is_some() + { + return write_clustered_decoded_sequential( + file, + batches, + finisher, + schema, + props, + target_rows, + key, + stats, + limits, + ); + } + + let mut in_flight = if estimated_rg_bytes > LOG_PARALLEL_WAVE_SOFT_BYTES { + 1 + } else { + in_flight.max(1) + }; + let arrow_writer = ArrowWriter::try_new(&mut *file, schema.clone(), Some(props.clone()))?; + let (mut writer, factory) = arrow_writer.into_serialized_writer()?; + let mut leaves_per_field = vec![0usize; schema.fields().len()]; + let parquet_schema = writer.schema_descr(); + for leaf in 0..parquet_schema.num_columns() { + leaves_per_field[parquet_schema.get_column_root_idx(leaf)] += 1; + } + let encoder = ClusteredRowGroupEncoder { + factory: &factory, + schema, + leaves_per_field: &leaves_per_field, + columns_per_task: log_columns_per_rayon_task( + schema.fields().len(), + rayon::current_num_threads(), + ), + key, + max_rows: props.max_row_group_row_count(), + max_bytes: props.max_row_group_bytes(), + split_fallback: AtomicBool::new(false), + #[cfg(test)] + part_path, + }; + // Row groups are cut at the sequential writer's boundaries: by row + // count, or by the clustered row-group byte cap for large rows. The + // writer's own byte limit applies after clustering. + let mut source = LogRowGroupSource::new( + batches, + finisher, + target_rows, + Some(limits.row_group_max_bytes), + stats, + ) + .with_merged_schema(merged_columns, merged_row_bytes) + .with_inline_stats_budget(limits.inline_stats_max_bytes) + .measuring_retained_bytes(); + let mut write_stats = LogClusterWriteStats { + columns_per_task: encoder.columns_per_task, + ..Default::default() + }; + let prepare = |source: &mut LogRowGroupSource, + in_flight: usize, + write_stats: &mut LogClusterWriteStats| { + #[cfg(test)] + record_log_pipeline_thread(part_path, LogPipelineStage::Prepare); + let started = Instant::now(); + let row_groups = source.next_row_groups(in_flight); + write_stats.prepare_duration += started.elapsed(); + row_groups + }; + let mut next_append_index = 0; + let mut append = |writer: &mut SerializedFileWriter<_>, + encoded: Vec, + write_stats: &mut LogClusterWriteStats| { + #[cfg(test)] + record_log_pipeline_thread(part_path, LogPipelineStage::Append); + let started = Instant::now(); + let appended = + append_clustered_row_groups(writer, encoded, &mut next_append_index, write_stats); + write_stats.append_duration += started.elapsed(); + appended + }; + + let mut next_index = 0; + let mut row_groups = prepare(&mut source, in_flight, &mut write_stats)?; + let mut encoded = Vec::new(); + while !row_groups.is_empty() { + let first_index = next_index; + next_index += row_groups.len(); + if !write_stats.serial + && row_groups + .iter() + .any(|row_group| row_group.retained_bytes > limits.overlap_max_retained_bytes) + { + // Large rows: from here on, hold one row group at a time. + write_stats.serial = true; + in_flight = 1; + } + if write_stats.serial { + append(&mut writer, std::mem::take(&mut encoded), &mut write_stats)?; + for (offset, row_group) in row_groups.into_iter().enumerate() { + let started = Instant::now(); + let encoded_row_group = + encoder.encode_row_group(row_group, first_index + offset); + write_stats.encode_duration += started.elapsed(); + append(&mut writer, vec![encoded_row_group?], &mut write_stats)?; + } + row_groups = if source.is_exhausted() { + Vec::new() + } else { + prepare(&mut source, in_flight, &mut write_stats)? + }; + continue; + } + let read_ahead = wave_data_bytes(&row_groups).max(wave_retained_bytes(&row_groups)) + <= CLUSTER_READ_AHEAD_MAX_BYTES; + let overlap = !encoded.is_empty() || (read_ahead && !source.is_exhausted()); + let file_side = || { + let appended = append(&mut writer, std::mem::take(&mut encoded), &mut write_stats); + // Nothing more is read for a file that cannot be written. + let prepared = if read_ahead && appended.is_ok() && !source.is_exhausted() { + prepare(&mut source, in_flight, &mut write_stats) + } else { + Ok(Vec::new()) + }; + (appended, prepared) + }; + let encode_side = || { + let started = Instant::now(); + let encoded = encoder.encode_row_groups(row_groups, first_index); + (encoded, started.elapsed()) + }; + // The side that owns the file and the readers runs here; the + // encoding side is taken by another pool thread when one is + // free, and otherwise runs here afterwards. + let ((appended, prepared), (encoded_row_groups, encode_duration)) = if overlap { + rayon::join(file_side, encode_side) + } else { + ((Ok(()), Ok(Vec::new())), encode_side()) + }; + appended?; + write_stats.encode_duration += encode_duration; + encoded = encoded_row_groups?; + row_groups = prepared?; + if !read_ahead && !source.is_exhausted() { + // The rows of a large wave are released before more are read. + row_groups = prepare(&mut source, in_flight, &mut write_stats)?; + } + } + append(&mut writer, encoded, &mut write_stats)?; + let stats = source.stats.take(); + drop(source); + + let close_started = Instant::now(); + let metadata = writer.close()?; + write_stats.close_duration = close_started.elapsed(); + Ok(ClusteredParquetOutput { + metadata, + stats, + write_stats, + }) + }) +} + +/// Writes decoded log batches with the sequential writer, one clustered row +/// group at a time, finishing each batch as it is read: the fallback of +/// [`write_clustered_log_parquet_on_pool_with_limits`], with its row groups +/// and bytes. Run it on the conversion pool. +#[allow(clippy::too_many_arguments)] +pub(super) fn write_clustered_decoded_sequential( + file: &mut W, + batches: DecodedLogBatches, + mut finisher: LogBatchFinisher, + schema: &Arc, + props: &WriterProperties, + target_rows: usize, + key: LogClusterKey, + stats: Option, + limits: ClusterMemoryLimits, +) -> Result { + let merged_columns = schema.fields().len(); + let merged_row_bytes = merged_schema_adapted_row_bytes(schema.as_ref()); + let mut stats = stats; + let stats_ref = &mut stats; + let records = batches.map(|(reader, batch)| { + let batch = batch?; + // Counted as the parallel writer's source counts it, from the + // decoded batch, so both writers cut the same row groups. + let bytes_per_row = log_batch_bytes_per_row(&batch, merged_columns, merged_row_bytes); + let mut finished = finisher.finish(vec![(reader, batch)])?; + let batch = finished.pop().ok_or_else(|| { + ArrowError::ComputeError("Finishing a log batch returned no batch".into()) + })?; + let over_budget = stats_ref.as_mut().is_some_and(|stats| { + stats.update(&batch); + stats.exceeds_inline_budget(limits.inline_stats_max_bytes) + }); + if over_budget { + // Releases the tracked values now, not at the end of the file. + *stats_ref = None; + } + Ok((batch, bytes_per_row)) + }); + let (metadata, mut write_stats) = write_clustered_log_parquet_sequential( + file, + records, + schema, + props, + target_rows, + limits.row_group_max_bytes, + key, + )?; + write_stats.sequential = true; + Ok(ClusteredParquetOutput { + metadata, + stats, + write_stats, + }) +} + +/// Bytes of Arrow data in the decoded rows of a wave. +fn wave_data_bytes(row_groups: &[LogRowGroup]) -> usize { + row_groups + .iter() + .flat_map(|row_group| &row_group.batches) + .map(log_batch_data_bytes) + .fold(0, usize::saturating_add) +} + +/// Bytes of the allocations the decoded rows of a wave keep alive. +fn wave_retained_bytes(row_groups: &[LogRowGroup]) -> usize { + row_groups + .iter() + .map(|row_group| row_group.retained_bytes) + .fold(0, usize::saturating_add) +} + +/// Appends encoded clustered row groups to the file in their order. +fn append_clustered_row_groups( + writer: &mut SerializedFileWriter, + encoded: Vec, + next_index: &mut usize, + write_stats: &mut LogClusterWriteStats, +) -> Result<(), StagingError> { + for row_group in encoded { + if row_group.index != *next_index { + return Err(ParquetError::General(format!( + "Clustered row group {} cannot be appended in place of {}", + row_group.index, next_index + )) + .into()); + } + *next_index += 1; + write_stats.rows += row_group.rows; + write_stats.row_groups += 1; + write_stats.split_row_groups += usize::from(row_group.parts.len() > 1); + write_stats.reencoded_row_groups += usize::from(row_group.reencoded); + write_stats.cluster_duration += row_group.cluster_duration; + for chunks in row_group.parts { + let mut row_group_writer = writer.next_row_group()?; + for chunk in chunks { + chunk.append_to_row_group(&mut row_group_writer)?; + } + row_group_writer.close()?; + } + } + Ok(()) +} + +/// The order in which the buffered rows of one row group are written. +enum ClusteredOrder { + /// Already in cluster order: the buffered slices are written as they are. + Unchanged, + /// The (buffered slice, row) of every output row, in output order. Rows + /// are gathered [`CLUSTER_OUTPUT_BATCH_ROWS`] at a time. + Gathered(Vec<(usize, usize)>), +} + +/// One buffered row group and the batches its clustered rows are written in: +/// those [`cluster_row_group_into`] emits for the same buffer. +struct ClusteredRowGroupPlan { + buffer: Vec, + order: ClusteredOrder, + batch_rows: Vec, +} + +impl ClusteredRowGroupPlan { + fn new( + mut buffer: Vec, + rows: usize, + key: LogClusterKey, + ) -> Result { + buffer.retain(|batch| batch.num_rows() > 0); + let Some(indices) = cluster_indices(&buffer, rows, key)? else { + let batch_rows = buffer.iter().map(RecordBatch::num_rows).collect(); + return Ok(Self { + buffer, + order: ClusteredOrder::Unchanged, + batch_rows, + }); + }; + let starts: Vec = buffer + .iter() + .scan(0, |next, batch| { + let start = *next; + *next += batch.num_rows(); + Some(start) + }) + .collect(); + let positions: Vec<(usize, usize)> = indices + .par_iter() + .with_min_len(CLUSTER_OUTPUT_BATCH_ROWS) + .map(|index| { + let index = *index as usize; + let slice = starts.partition_point(|start| *start <= index) - 1; + (slice, index - starts[slice]) + }) + .collect(); + let batch_rows = positions + .chunks(CLUSTER_OUTPUT_BATCH_ROWS) + .map(<[_]>::len) + .collect(); + Ok(Self { + buffer, + order: ClusteredOrder::Gathered(positions), + batch_rows, + }) + } + + /// Column `field` of output batch `batch`. + fn column(&self, field: usize, batch: usize) -> Result { + match &self.order { + ClusteredOrder::Unchanged => Ok(self.buffer[batch].column(field).clone()), + ClusteredOrder::Gathered(positions) => { + let start = batch * CLUSTER_OUTPUT_BATCH_ROWS; + let end = (start + CLUSTER_OUTPUT_BATCH_ROWS).min(positions.len()); + let values: Vec<&dyn Array> = self + .buffer + .iter() + .map(|buffered| buffered.column(field).as_ref()) + .collect(); + interleave(&values, &positions[start..end]) + } + } + } + + /// Output batch `batch` with all its columns. + fn batch(&self, batch: usize) -> Result { + if let ClusteredOrder::Unchanged = self.order { + return Ok(self.buffer[batch].clone()); + } + let schema = self.buffer[0].schema(); + let columns = (0..schema.fields().len()) + .into_par_iter() + .map(|field| self.column(field, batch)) + .collect::, _>>()?; + RecordBatch::try_new(schema, columns) + } +} + +/// The column chunks of one clustered row group, in Parquet column order: +/// one part, or several when the writer's limits split it. +struct EncodedClusteredRowGroup { + /// Position of the row group among the clustered row groups of the file. + index: usize, + parts: Vec>, + rows: usize, + cluster_duration: Duration, + /// Whether the row group was encoded twice, see + /// [`LogClusterWriteStats::reencoded_row_groups`]. + reencoded: bool, +} + +/// Clusters and encodes the row groups of one log Parquet file. +struct ClusteredRowGroupEncoder<'a> { + factory: &'a ArrowRowGroupWriterFactory, + schema: &'a Arc, + /// Parquet leaf columns under each Arrow field, in field order. + leaves_per_field: &'a [usize], + columns_per_task: usize, + key: LogClusterKey, + /// The writer's limits, which `ArrowWriter` applies to every batch. + max_rows: Option, + max_bytes: Option, + /// Set once the writer's limits split a row group: every later row group + /// of the file is encoded batch by batch straight away, once, instead of + /// column by column and then again. + split_fallback: AtomicBool, + #[cfg(test)] + part_path: &'a std::path::Path, +} + +impl ClusteredRowGroupEncoder<'_> { + /// Encodes consecutive row groups at the same time and returns them in + /// their order. `first_index` is the position of the first one. + fn encode_row_groups( + &self, + row_groups: Vec, + first_index: usize, + ) -> Result, StagingError> { + if row_groups.len() < 2 { + return row_groups + .into_iter() + .map(|row_group| self.encode_row_group(row_group, first_index)) + .collect(); + } + row_groups + .into_par_iter() + .enumerate() + .map(|(offset, row_group)| self.encode_row_group(row_group, first_index + offset)) + .collect() + } + + /// Clusters one row group and encodes it, its columns in parallel. The + /// buffered rows are released when this returns. + fn encode_row_group( + &self, + row_group: LogRowGroup, + index: usize, + ) -> Result { + #[cfg(test)] + record_log_pipeline_thread(self.part_path, LogPipelineStage::EncodeRowGroup); + let started = Instant::now(); + let rows = row_group.rows; + let plan = ClusteredRowGroupPlan::new(row_group.batches, rows, self.key)?; + let cluster_duration = started.elapsed(); + + // The row limit splits exactly the row groups with more rows; after + // a split by the byte limit, later row groups likely split too. + if self.max_rows.is_some_and(|max_rows| rows > max_rows) + || self.split_fallback.load(Ordering::Relaxed) + { + return self.encode_split(&plan, index, rows, cluster_duration, false); + } + + // The row-group ordinal only matters to Parquet modular encryption, + // which conversion never enables; without splits it is the position + // of the row group in the file. + let writers = self.factory.create_column_writers(index)?; + let leaves = self.leaves_per_field.iter().sum::(); + if writers.len() != leaves { + return Err(ParquetError::General(format!( + "Parquet column writer count {} does not match schema leaf count {leaves}", + writers.len(), + )) + .into()); + } + let mut writers = writers.into_iter(); + let fields = self + .leaves_per_field + .iter() + .enumerate() + .map(|(field_index, leaves)| (field_index, writers.by_ref().take(*leaves).collect())) + .collect::)>>(); + + let track_bytes = self.max_bytes.is_some(); + // Encodes one field from the output batches in order and returns its + // chunks with its estimated encoded size after each batch. + let encode_field = |(field_index, mut writers): (usize, Vec)| { + #[cfg(test)] + record_log_pipeline_thread(self.part_path, LogPipelineStage::EncodeColumn); + let field = self.schema.field(field_index); + let mut estimates = Vec::new(); + for batch in 0..plan.batch_rows.len() { + let column = plan.column(field_index, batch)?; + let leaves = compute_leaves(field, &column)?; + if leaves.len() != writers.len() { + return Err(ParquetError::General(format!( + "Arrow field {} has {} leaves for {} Parquet column writers", + field.name(), + leaves.len(), + writers.len() + )) + .into()); + } + for (writer, leaf) in writers.iter_mut().zip(&leaves) { + writer.write(leaf)?; + } + if track_bytes { + estimates.push( + writers + .iter() + .map(ArrowColumnWriter::get_estimated_total_bytes) + .sum::(), + ); + } + } + let chunks = writers + .into_iter() + .map(ArrowColumnWriter::close) + .collect::, ParquetError>>()?; + Ok::<_, StagingError>((chunks, estimates)) + }; + let encoded: Vec<(Vec, Vec)> = + if rows < LOG_PARALLEL_ENCODE_MIN_ROWS || fields.len() < 2 { + fields + .into_iter() + .map(encode_field) + .collect::>()? + } else { + fields + .into_par_iter() + .with_min_len(self.columns_per_task) + .map(encode_field) + .collect::>()? + }; + + // `ArrowWriter` sums the estimates of all column writers. + let mut estimates = vec![ + 0usize; + if track_bytes { + plan.batch_rows.len() + } else { + 0 + } + ]; + for (_, field_estimates) in &encoded { + for (total, estimate) in estimates.iter_mut().zip(field_estimates) { + *total = total.saturating_add(*estimate); + } + } + if !arrow_writer_splits(&plan.batch_rows, &estimates, self.max_rows, self.max_bytes) { + return Ok(EncodedClusteredRowGroup { + index, + parts: vec![encoded.into_iter().flat_map(|(chunks, _)| chunks).collect()], + rows, + cluster_duration, + reencoded: false, + }); + } + drop(encoded); + self.split_fallback.store(true, Ordering::Relaxed); + self.encode_split(&plan, index, rows, cluster_duration, true) + } + + /// Encodes the output batches of `plan` in order as `ArrowWriter` would, + /// closing a Parquet row group wherever the writer's limits do. The + /// bytes are those of [`Self::encode_row_group`]'s column-parallel + /// encoding when no limit is reached. + fn encode_split( + &self, + plan: &ClusteredRowGroupPlan, + index: usize, + rows: usize, + cluster_duration: Duration, + reencoded: bool, + ) -> Result { + let mut writer = SplitRowGroupWriter { + factory: self.factory, + schema: self.schema, + next_index: index, + max_rows: self.max_rows, + max_bytes: self.max_bytes, + writers: None, + buffered_rows: 0, + parts: Vec::new(), + }; + for batch in 0..plan.batch_rows.len() { + writer.write(&plan.batch(batch)?)?; + } + writer.flush()?; + Ok(EncodedClusteredRowGroup { + index, + parts: writer.parts, + rows, + cluster_duration, + reencoded, + }) + } +} + +/// Whether `ArrowWriter::write`, given batches of `batch_rows` rows that make +/// one row group, would close a row group before the last batch: by the row +/// limit, or by the byte limit with `estimates[b]` its estimated encoded size +/// after batch `b`. Mirrors the checks `ArrowWriter::write` makes. +fn arrow_writer_splits( + batch_rows: &[usize], + estimates: &[usize], + max_rows: Option, + max_bytes: Option, +) -> bool { + let last = batch_rows.len().saturating_sub(1); + let mut buffered = 0usize; + for (batch, &rows) in batch_rows.iter().enumerate() { + if max_rows.is_some_and(|max_rows| buffered + rows > max_rows) { + return true; + } + if let Some(max_bytes) = max_bytes + && buffered > 0 + { + let current = estimates[batch - 1]; + if current >= max_bytes { + return true; + } + if let Some(average) = current.checked_div(buffered).filter(|average| *average > 0) + && rows > (max_bytes - current) / average + { + return true; + } + } + buffered += rows; + let flush = max_rows.is_some_and(|max_rows| buffered >= max_rows) + || max_bytes.is_some_and(|max_bytes| estimates[batch] >= max_bytes); + if flush && batch != last { + return true; + } + } + false +} + +/// Encodes the batches of one row group as `ArrowWriter::write` and +/// `ArrowWriter::flush` would, closing a row group wherever its limits do. +struct SplitRowGroupWriter<'a> { + factory: &'a ArrowRowGroupWriterFactory, + schema: &'a Arc, + next_index: usize, + max_rows: Option, + max_bytes: Option, + writers: Option>, + buffered_rows: usize, + parts: Vec>, +} + +impl SplitRowGroupWriter<'_> { + fn estimated_bytes(&self) -> usize { + self.writers + .iter() + .flatten() + .map(ArrowColumnWriter::get_estimated_total_bytes) + .sum() + } + + fn write(&mut self, batch: &RecordBatch) -> Result<(), ParquetError> { + let rows = batch.num_rows(); + if rows == 0 { + return Ok(()); + } + if self.writers.is_none() { + self.writers = Some(self.factory.create_column_writers(self.next_index)?); + self.buffered_rows = 0; + } + if let Some(max_rows) = self.max_rows + && self.buffered_rows + rows > max_rows + { + let to_write = max_rows - self.buffered_rows; + self.write(&batch.slice(0, to_write))?; + return self.write(&batch.slice(to_write, rows - to_write)); + } + if let Some(max_bytes) = self.max_bytes + && self.buffered_rows > 0 + { + let current = self.estimated_bytes(); + if current >= max_bytes { + self.flush()?; + return self.write(batch); + } + if let Some(average) = current + .checked_div(self.buffered_rows) + .filter(|average| *average > 0) + { + let fit = (max_bytes - current) / average; + if rows > fit { + if fit > 0 { + self.write(&batch.slice(0, fit))?; + return self.write(&batch.slice(fit, rows - fit)); + } + self.flush()?; + return self.write(batch); + } + } + } + + self.buffered_rows += rows; + let Some(writers) = self.writers.as_mut() else { + return Err(ParquetError::General( + "Clustered row group has no column writers".to_string(), + )); + }; + let mut writers = writers.iter_mut(); + for (field, column) in self.schema.fields().iter().zip(batch.columns()) { + for leaf in compute_leaves(field.as_ref(), column)? { + let Some(writer) = writers.next() else { + return Err(ParquetError::General(format!( + "Arrow field {} has more leaves than Parquet column writers", + field.name() + ))); + }; + writer.write(&leaf)?; + } + } + let flush = self + .max_rows + .is_some_and(|max_rows| self.buffered_rows >= max_rows) + || self + .max_bytes + .is_some_and(|max_bytes| self.estimated_bytes() >= max_bytes); + if flush { + self.flush()?; + } + Ok(()) + } + + fn flush(&mut self) -> Result<(), ParquetError> { + let Some(writers) = self.writers.take() else { + return Ok(()); + }; + self.buffered_rows = 0; + self.next_index += 1; + self.parts.push( + writers + .into_iter() + .map(ArrowColumnWriter::close) + .collect::>()?, + ); + Ok(()) + } } diff --git a/src/parseable/streams/log_clustering_tests.rs b/src/parseable/streams/log_clustering_tests.rs index 71e331fe9..289ba450f 100644 --- a/src/parseable/streams/log_clustering_tests.rs +++ b/src/parseable/streams/log_clustering_tests.rs @@ -26,11 +26,13 @@ use std::collections::BTreeMap; use arrow::util::display::{ArrayFormatter, FormatOptions}; +use arrow_array::builder::{ListBuilder, StringBuilder}; use arrow_array::{ Array, BooleanArray, DictionaryArray, Float64Array, Int32Array, Int64Array, StringArray, TimestampMillisecondArray, types::Int32Type, }; -use arrow_schema::{DataType, Field, TimeUnit}; +use arrow_ipc::writer::StreamWriter as ArrowStreamWriter; +use arrow_schema::{DataType, Field, Fields, TimeUnit}; use chrono::NaiveDate; use clap::Parser; use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder; @@ -1216,3 +1218,1133 @@ fn chunked_writer_matches_single_batch_write_bytes() { vec![TARGET, BIG_ROWS - TARGET] ); } + +// --------------------------------------------------------------------------- +// Parallel clustered writer: the conversion path writes the bytes of the +// sequential clustered writer, on the conversion pool. +// --------------------------------------------------------------------------- + +/// Staged severities: unordered with NULLs, or one value, which leaves the +/// reverse reader's newest-first rows already in cluster order. +#[derive(Clone, Copy)] +enum Severities { + Mixed, + Constant, +} + +/// A staged log schema with scalar, struct and list columns, so Arrow fields +/// and Parquet leaves do not line up one to one. Odd files have no `message`, +/// so their batches are adapted to the merged schema. +fn staged_schema(with_message: bool) -> Arc { + let mut fields = vec![ + Field::new( + DEFAULT_TIMESTAMP_KEY, + DataType::Timestamp(TimeUnit::Millisecond, None), + true, + ), + Field::new("id", DataType::Int64, false), + Field::new(SEVERITY, DataType::Utf8, true), + ]; + if with_message { + fields.push(Field::new("message", DataType::Utf8, true)); + } + fields.push(Field::new( + "attrs", + DataType::Struct(Fields::from(vec![ + Field::new("code", DataType::Int32, true), + Field::new("label", DataType::Utf8, true), + ])), + true, + )); + fields.push(Field::new( + "tags", + DataType::List(Arc::new(Field::new_list_field(DataType::Utf8, true))), + true, + )); + Arc::new(Schema::new(fields)) +} + +fn staged_batch( + schema: &Arc, + first: usize, + rows: usize, + severities: Severities, +) -> RecordBatch { + let ids = || first..first + rows; + let mut tags = ListBuilder::new(StringBuilder::new()); + for id in ids() { + if id % 9 == 0 { + tags.append_null(); + continue; + } + for tag in 0..id % 3 { + tags.values().append_value(format!("tag-{}-{tag}", id % 50)); + } + tags.append(true); + } + let mut columns: Vec = vec![ + Arc::new(TimestampMillisecondArray::from_iter_values( + ids().map(|id| 1_760_000_000_000 + id as i64), + )), + Arc::new(Int64Array::from_iter_values(ids().map(|id| id as i64))), + Arc::new(StringArray::from_iter(ids().map(|id| match severities { + Severities::Mixed => severity(id), + Severities::Constant => Some("INFO"), + }))), + ]; + if schema.index_of("message").is_ok() { + columns.push(Arc::new(StringArray::from_iter(ids().map(|id| { + (id % 11 != 0).then(|| format!("message {} {}", id % 23, "x".repeat(id % 7))) + })))); + } + let DataType::Struct(attr_fields) = schema.field_with_name("attrs").unwrap().data_type() else { + unreachable!() + }; + columns.push(Arc::new(arrow_array::StructArray::new( + attr_fields.clone(), + vec![ + Arc::new(Int32Array::from_iter( + ids().map(|id| (id % 4 != 0).then_some((id % 300) as i32)), + )), + Arc::new(StringArray::from_iter_values( + ids().map(|id| format!("label-{}", id % 17)), + )), + ], + None, + ))); + columns.push(Arc::new(tags.finish())); + RecordBatch::try_new(schema.clone(), columns).unwrap() +} + +/// Stages `files` Arrow files of `batches` batches of `rows` rows, time +/// increasing within a file and no timestamp shared, as ingestion stages them. +fn stage_files( + dir: &TempDir, + files: usize, + batches: usize, + rows: usize, + severities: Severities, +) -> Vec { + (0..files) + .map(|file| { + let schema = staged_schema(file % 2 == 0); + let path = dir.path().join(format!("{file}.data.arrows")); + let mut writer = + ArrowStreamWriter::try_new(File::create(&path).unwrap(), &schema).unwrap(); + for batch in 0..batches { + let first = (batch * files + file) * rows; + writer + .write(&staged_batch(&schema, first, rows, severities)) + .unwrap(); + } + writer.finish().unwrap(); + path + }) + .collect() +} + +fn conversion_reader(files: &[PathBuf]) -> ConversionRecordReader { + ConversionRecordReader::for_stream(files, false) +} + +fn merged_schema_of(files: &[PathBuf]) -> Arc { + Arc::new(conversion_reader(files).merged_schema().unwrap()) +} + +/// The finished batches the conversion of `files` writes, in order. +fn finished_batches(files: &[PathBuf], schema: &Arc) -> Vec { + conversion_reader(files) + .merged_iter(schema.clone(), None) + .collect::>() + .unwrap() +} + +fn severity_key(schema: &Schema) -> LogClusterKey { + resolve_cluster_key(Some(SEVERITY), true, schema, None).unwrap() +} + +/// The previous, sequential clustered writer's bytes for `files`. +fn sequential_clustered_bytes( + files: &[PathBuf], + schema: &Arc, + props: &WriterProperties, + target_rows: usize, +) -> Vec { + let mut out = Vec::new(); + log_clustering::write_clustered_log_parquet( + &mut out, + conversion_reader(files).merged_iter(schema.clone(), None), + schema, + props, + target_rows, + severity_key(schema), + ) + .unwrap(); + out +} + +#[allow(clippy::too_many_arguments)] +fn parallel_clustered( + pool: &rayon::ThreadPool, + files: &[PathBuf], + schema: &Arc, + props: &WriterProperties, + target_rows: usize, + in_flight: usize, + stats: Option, +) -> (Vec, log_clustering::ClusteredParquetOutput) { + let (batches, finisher) = conversion_reader(files).into_log_batches(schema.clone(), None); + let mut out = Vec::new(); + let output = log_clustering::write_clustered_log_parquet_on_pool( + pool, + &mut out, + batches, + finisher, + schema, + props, + target_rows, + severity_key(schema), + in_flight, + stats, + Path::new("unregistered-clustered-part"), + ) + .unwrap(); + (out, output) +} + +/// Field statistics as the post-write fallback computes them: the written +/// file read back in its physical (clustered) order. +fn reread_field_stats( + bytes: Vec, + stream_name: &str, + schema: &Schema, + max_field_statistics: usize, +) -> Vec { + let reader = ParquetRecordBatchReaderBuilder::try_new(bytes::Bytes::from(bytes)) + .unwrap() + .with_batch_size(32 * 1024) + .build() + .unwrap(); + let mut accumulator = crate::storage::field_stats::FieldStatsAccumulator::new( + stream_name, + schema, + max_field_statistics, + ); + for batch in reader { + accumulator.update(&batch.unwrap()); + } + accumulator.finish() +} + +fn row_groups_of_bytes(dir: &TempDir, name: &str, bytes: &[u8]) -> Vec> { + let path = dir.path().join(name); + std::fs::write(&path, bytes).unwrap(); + row_groups(&path) +} + +#[test] +fn parallel_clustered_writer_matches_sequential_bytes() { + let dir = TempDir::new().unwrap(); + // 18,000 rows: groups of 10,000 hold two 8,192-row gathers, and groups + // past 1,024 rows encode their columns in parallel. + let files = stage_files(&dir, 3, 4, 1500, Severities::Mixed); + let schema = merged_schema_of(&files); + let total = 18_000; + let severity_idx = schema.index_of(SEVERITY).unwrap(); + let time_idx = schema.index_of(DEFAULT_TIMESTAMP_KEY).unwrap(); + let pool = &*LOG_CONVERSION_THREADPOOL; + + for target in [97usize, 1000, 10_000, 50_000] { + let stream = Stream::new( + Arc::new(Options { + local_staging_path: dir.path().to_path_buf(), + row_group_size: target, + log_severity_cluster_column: Some(SEVERITY.into()), + parquet_bloom_filter_columns: vec![SEVERITY.into()], + ..Default::default() + }), + "parallel-clustering", + LogStreamMetadata::default(), + None, + &None, + ); + let production = stream.parquet_writer_props(&schema, None, None, true); + // A byte limit that `ArrowWriter` reaches inside clustered groups, + // and a row limit below the clustering target: both split groups. + let byte_limited = WriterProperties::builder() + .set_max_row_group_row_count(Some(target)) + .set_max_row_group_bytes(Some(24 * 1024)) + .build(); + let row_limited = WriterProperties::builder() + .set_max_row_group_row_count(Some(target / 3 + 1)) + .set_max_row_group_bytes(None) + .build(); + let cases = [ + ("production", &production, vec![1usize, 2, 4]), + ("byte-limited", &byte_limited, vec![2]), + ("row-limited", &row_limited, vec![2]), + ]; + for (name, props, in_flights) in cases { + let expected = sequential_clustered_bytes(&files, &schema, props, target); + for in_flight in in_flights { + let (actual, output) = + parallel_clustered(pool, &files, &schema, props, target, in_flight, None); + assert!( + actual == expected, + "{name}, target {target}, in_flight {in_flight}: bytes differ" + ); + let stats = output.write_stats; + assert_eq!(stats.rows, total); + assert_eq!(stats.row_groups, total.div_ceil(target)); + assert!(!stats.sequential); + assert_eq!( + output.metadata.file_metadata().num_rows() as usize, + total, + "{name}" + ); + // Groups the writer's limits split are those encoded again. + assert_eq!( + stats.split_row_groups > 0, + output.metadata.num_row_groups() > stats.row_groups, + "{name}, target {target}" + ); + match name { + "production" => assert_eq!(stats.split_row_groups, 0), + _ if target >= 10_000 => { + assert!(stats.split_row_groups > 0, "{name}, target {target}") + } + _ => {} + } + } + if name == "production" { + let (actual, output) = + parallel_clustered(pool, &files, &schema, props, target, 2, None); + assert!( + output + .metadata + .row_groups() + .iter() + .all(|group| group.sorting_columns().is_none()) + ); + let groups = + row_groups_of_bytes(&dir, &format!("parallel-{target}.parquet"), &actual); + assert_eq!( + groups.iter().map(Vec::len).collect_vec(), + (0..total.div_ceil(target)) + .map(|group| target.min(total - group * target)) + .collect_vec() + ); + for rows in &groups { + assert_clustered(rows, severity_idx, time_idx); + } + } + } + } + + // Rows already in cluster order are written as the buffered slices. + let ordered_dir = TempDir::new().unwrap(); + let ordered = stage_files(&ordered_dir, 2, 3, 1700, Severities::Constant); + let schema = merged_schema_of(&ordered); + for target in [500usize, 4096, 20_000] { + let props = WriterProperties::builder() + .set_max_row_group_row_count(Some(target)) + .build(); + let expected = sequential_clustered_bytes(&ordered, &schema, &props, target); + let (actual, output) = parallel_clustered(pool, &ordered, &schema, &props, target, 2, None); + assert!(actual == expected, "ordered input, target {target}"); + assert_eq!(output.write_stats.rows, 10_200); + } + + // The zero row-group target is rejected as by the sequential writer. + let (batches, finisher) = conversion_reader(&ordered).into_log_batches(schema.clone(), None); + let error = log_clustering::write_clustered_log_parquet_on_pool( + pool, + &mut Vec::new(), + batches, + finisher, + &schema, + &WriterProperties::builder().build(), + 0, + severity_key(&schema), + 2, + None, + Path::new("unregistered-clustered-part"), + ) + .err() + .unwrap(); + assert!( + matches!(&error, StagingError::Parquet(inner) if inner.to_string().contains("greater than zero")), + "{error:?}" + ); +} + +#[test] +fn parallel_clustered_writer_completes_on_one_and_two_thread_pools() { + let dir = TempDir::new().unwrap(); + let files = stage_files(&dir, 2, 4, 300, Severities::Mixed); + let schema = merged_schema_of(&files); + let key = severity_key(&schema); + // Row groups of 128 rows: many waves, so reading, encoding and appending + // overlap in every conversion. + let stream = stream_with( + &dir, + Some(SEVERITY), + LogStreamMetadata::default(), + "small-pool", + ); + let props = stream.parquet_writer_props(&schema, None, None, true); + let expected = sequential_clustered_bytes(&files, &schema, &props, ROW_GROUP); + + for threads in [1usize, 2] { + let pool = rayon::ThreadPoolBuilder::new() + .num_threads(threads) + .build() + .unwrap(); + let outputs = (0..6) + .map(|index| { + dir.path() + .join(format!("pool-{threads}-{index}.parquet.part")) + }) + .collect_vec(); + // Every thread of the pool converts a stream; none may wait on work + // that only a busy thread could run. + pool.install(|| { + outputs.par_iter().for_each(|path| { + let mut file = File::create(path).unwrap(); + let artifacts = stream + .write_clustered_log_parquet_part_file_on_pool( + &pool, + path, + &mut file, + conversion_reader(&files), + &schema, + &props, + None, + key, + // Tracks every one of the 2,400 values of a field, so + // the counts stay exact and are kept. + Some(10_000), + 2, + ) + .unwrap(); + assert!(artifacts.field_stats.is_some()); + }); + }); + for path in &outputs { + assert!( + std::fs::read(path).unwrap() == expected, + "a {threads}-thread pool wrote different bytes" + ); + } + } +} + +#[test] +fn clustered_conversion_collects_field_stats_inline() { + let dir = TempDir::new().unwrap(); + // At most 1,000 values per field: below the tracked-value limit, so + // statistics do not depend on the order rows are counted in. + let files = stage_files(&dir, 2, 2, 250, Severities::Mixed); + let schema = merged_schema_of(&files); + let key = severity_key(&schema); + let stream = Stream::new( + Arc::new(Options { + local_staging_path: dir.path().to_path_buf(), + row_group_size: ROW_GROUP, + log_severity_cluster_column: Some(SEVERITY.into()), + collect_dataset_stats: true, + max_field_statistics: 5, + ..Default::default() + }), + "clustered-stats", + LogStreamMetadata::default(), + None, + &None, + ); + let props = stream.parquet_writer_props(&schema, None, None, true); + let path = dir.path().join("stats.parquet.part"); + let threads = LOG_PIPELINE_THREADS + .lock() + .unwrap() + .insert(path.clone(), Vec::new()); + assert!(threads.is_none()); + let artifacts = stream + .write_parquet_part_file( + &path, + conversion_reader(&files), + &schema, + &props, + None, + Some(key), + ) + .unwrap() + .unwrap(); + let threads = LOG_PIPELINE_THREADS.lock().unwrap().remove(&path).unwrap(); + // The clustered conversion ran its pipeline on the conversion pool. + for stage in [ + LogPipelineStage::Prepare, + LogPipelineStage::EncodeRowGroup, + LogPipelineStage::EncodeColumn, + LogPipelineStage::Append, + ] { + assert!( + threads.iter().any(|(recorded, _)| *recorded == stage), + "{stage:?}" + ); + } + assert!( + threads + .iter() + .all(|(_, thread)| thread.starts_with("log-conversion-")), + "{threads:?}" + ); + + let bytes = std::fs::read(&path).unwrap(); + let (max_field_statistics, stats) = artifacts.field_stats.unwrap(); + assert_eq!(max_field_statistics, 5); + let source_order = crate::storage::field_stats::compute_field_stats_from_batches( + &finished_batches(&files, &schema), + &stream.stream_name, + &schema, + 5, + ); + assert_eq!(stats, source_order); + assert_eq!( + stats, + reread_field_stats(bytes.clone(), &stream.stream_name, &schema, 5) + ); + assert!( + stats + .iter() + .any(|stat| stat.field_name == SEVERITY && stat.distinct_count >= 5) + ); + + // The footer handed on is the written file's. + let metadata = artifacts.parquet_metadata.unwrap(); + let written = ParquetRecordBatchReaderBuilder::try_new(bytes::Bytes::from(bytes)) + .unwrap() + .metadata() + .clone(); + assert_eq!(metadata.num_row_groups(), written.num_row_groups()); + assert_eq!(metadata.num_row_groups(), 1000usize.div_ceil(ROW_GROUP)); + assert_eq!(metadata.file_metadata().num_rows(), 1000); + for (group, written_group) in metadata.row_groups().iter().zip(written.row_groups()) { + assert_eq!(group.num_rows(), written_group.num_rows()); + assert_eq!(group.total_byte_size(), written_group.total_byte_size()); + assert!(group.sorting_columns().is_none()); + } + let severity_idx = schema.index_of(SEVERITY).unwrap(); + let time_idx = schema.index_of(DEFAULT_TIMESTAMP_KEY).unwrap(); + for rows in row_groups(&path) { + assert_clustered(&rows, severity_idx, time_idx); + } + + // Larger groups and more values: statistics still see the rows in + // source order, as the unclustered writer's do, while every value of a + // field is tracked. + let many = TempDir::new().unwrap(); + let many_files = stage_files(&many, 3, 2, 1500, Severities::Mixed); + let many_schema = merged_schema_of(&many_files); + let stats = crate::storage::field_stats::FieldStatsAccumulator::new( + &stream.stream_name, + &many_schema, + 10_000, + ); + let (many_bytes, output) = parallel_clustered( + &LOG_CONVERSION_THREADPOOL, + &many_files, + &many_schema, + &props, + 4000, + 2, + Some(stats), + ); + let inline = output.stats.unwrap().finish(); + assert_eq!( + inline, + crate::storage::field_stats::compute_field_stats_from_batches( + &finished_batches(&many_files, &many_schema), + &stream.stream_name, + &many_schema, + 10_000, + ) + ); + assert_eq!( + inline, + reread_field_stats(many_bytes, &stream.stream_name, &many_schema, 10_000) + ); + + // No statistics are collected when the stream does not ask for them. + let quiet = stream_with(&dir, Some(SEVERITY), LogStreamMetadata::default(), "quiet"); + let quiet_path = dir.path().join("quiet.parquet.part"); + let artifacts = quiet + .write_parquet_part_file( + &quiet_path, + conversion_reader(&files), + &schema, + &props, + None, + Some(key), + ) + .unwrap() + .unwrap(); + assert!(artifacts.field_stats.is_none()); + assert!(artifacts.parquet_metadata.is_some()); +} + +/// Files of a wide schema and narrow files of a few of its columns, as +/// schema churn stages them. +fn stage_wide_files(dir: &TempDir, columns: usize) -> Vec { + let schema_of = |columns: usize| { + let mut fields = vec![ + Field::new( + DEFAULT_TIMESTAMP_KEY, + DataType::Timestamp(TimeUnit::Millisecond, None), + true, + ), + Field::new(SEVERITY, DataType::Utf8, true), + ]; + fields.extend((0..columns).map(|c| Field::new(format!("c{c:03}"), DataType::Int64, true))); + Arc::new(Schema::new(fields)) + }; + [columns, 1] + .into_iter() + .enumerate() + .map(|(file, columns)| { + let schema = schema_of(columns); + let path = dir.path().join(format!("wide-{file}.data.arrows")); + let mut writer = + ArrowStreamWriter::try_new(File::create(&path).unwrap(), &schema).unwrap(); + for batch in 0..3 { + let first = (batch * 2 + file) * 400; + let ids = first..first + 400; + let mut arrays: Vec = vec![ + Arc::new(TimestampMillisecondArray::from_iter_values( + ids.clone().map(|id| 1_760_000_000_000 + id as i64), + )), + Arc::new(StringArray::from_iter(ids.clone().map(severity))), + ]; + arrays.extend((0..columns).map(|c| { + Arc::new(Int64Array::from_iter( + ids.clone() + .map(|id| ((id + c) % 5 != 0).then_some((id * c) as i64)), + )) as ArrayRef + })); + writer + .write(&RecordBatch::try_new(schema.clone(), arrays).unwrap()) + .unwrap(); + } + writer.finish().unwrap(); + path + }) + .collect() +} + +#[test] +fn wide_clustered_row_groups_fall_back_to_the_sequential_writer() { + // At the default 262,144-row target, 70 Int64 columns estimate a row + // group above the parallel ceiling: the sequential writer, which holds one + // row group at a time, writes it. 40 columns pipeline one group per wave. + for (columns, sequential) in [(70usize, true), (40, false)] { + let dir = TempDir::new().unwrap(); + let files = stage_wide_files(&dir, columns); + let schema = merged_schema_of(&files); + let target = 262_144; + let estimated = target * merged_schema_adapted_row_bytes(&schema); + assert_eq!( + estimated > LOG_PARALLEL_ROW_GROUP_MAX_ADAPTED_BYTES, + sequential + ); + assert!(estimated > LOG_PARALLEL_WAVE_SOFT_BYTES); + let props = WriterProperties::builder() + .set_max_row_group_row_count(Some(target)) + .build(); + let expected = sequential_clustered_bytes(&files, &schema, &props, target); + // Every value tracked, so the exact counts are kept. + let stats = + crate::storage::field_stats::FieldStatsAccumulator::new("wide", &schema, 10_000); + let (actual, output) = parallel_clustered( + &LOG_CONVERSION_THREADPOOL, + &files, + &schema, + &props, + target, + 4, + Some(stats), + ); + assert!(actual == expected, "{columns} columns: bytes differ"); + assert_eq!(output.write_stats.sequential, sequential); + assert_eq!(output.write_stats.rows, 2400); + assert_eq!(output.metadata.num_row_groups(), 1); + // Statistics are collected inline whichever writer runs. + assert_eq!( + output.stats.unwrap().finish(), + crate::storage::field_stats::compute_field_stats_from_batches( + &finished_batches(&files, &schema), + "wide", + &schema, + 10_000, + ) + ); + let rows = row_groups_of_bytes(&dir, "wide.parquet", &actual); + assert_clustered( + &rows[0], + schema.index_of(SEVERITY).unwrap(), + schema.index_of(DEFAULT_TIMESTAMP_KEY).unwrap(), + ); + } +} + +// --------------------------------------------------------------------------- +// Memory bounds: large rows, byte-limit splits and inline statistics. + +/// Stages two files of `batches` batches of `rows` rows each, every row with +/// a `message` of about `message_bytes` bytes, under one schema. +fn stage_large_rows( + dir: &TempDir, + batches: usize, + rows: usize, + message_bytes: usize, +) -> Vec { + let schema = Arc::new(Schema::new(vec![ + Field::new( + DEFAULT_TIMESTAMP_KEY, + DataType::Timestamp(TimeUnit::Millisecond, None), + true, + ), + Field::new(SEVERITY, DataType::Utf8, true), + Field::new("message", DataType::Utf8, true), + ])); + (0..2) + .map(|file| { + let path = dir.path().join(format!("large-{file}.data.arrows")); + let mut writer = + ArrowStreamWriter::try_new(File::create(&path).unwrap(), &schema).unwrap(); + for batch in 0..batches { + let first = (batch * 2 + file) * rows; + let ids = first..first + rows; + let columns: Vec = vec![ + Arc::new(TimestampMillisecondArray::from_iter_values( + ids.clone().map(|id| 1_760_000_000_000 + id as i64), + )), + Arc::new(StringArray::from_iter(ids.clone().map(severity))), + Arc::new(StringArray::from_iter_values( + ids.map(|id| format!("{id:08}-{}", "m".repeat(message_bytes))), + )), + ]; + writer + .write(&RecordBatch::try_new(schema.clone(), columns).unwrap()) + .unwrap(); + } + writer.finish().unwrap(); + path + }) + .collect() +} + +#[allow(clippy::too_many_arguments)] +fn parallel_clustered_with_limits( + files: &[PathBuf], + schema: &Arc, + props: &WriterProperties, + target_rows: usize, + in_flight: usize, + stats: Option, + limits: log_clustering::ClusterMemoryLimits, +) -> (Vec, log_clustering::ClusteredParquetOutput) { + let (batches, finisher) = conversion_reader(files).into_log_batches(schema.clone(), None); + let mut out = Vec::new(); + let output = log_clustering::write_clustered_log_parquet_on_pool_with_limits( + &LOG_CONVERSION_THREADPOOL, + &mut out, + batches, + finisher, + schema, + props, + target_rows, + severity_key(schema), + in_flight, + stats, + Path::new("unregistered-clustered-part"), + limits, + ) + .unwrap(); + (out, output) +} + +/// The sequential fallback writer's output for `files` under `limits`. +fn sequential_decoded_with_limits( + files: &[PathBuf], + schema: &Arc, + props: &WriterProperties, + target_rows: usize, + stats: Option, + limits: log_clustering::ClusterMemoryLimits, +) -> (Vec, log_clustering::ClusteredParquetOutput) { + let (batches, finisher) = conversion_reader(files).into_log_batches(schema.clone(), None); + let mut out = Vec::new(); + let output = LOG_CONVERSION_THREADPOOL.install(|| { + log_clustering::write_clustered_decoded_sequential( + &mut out, + batches, + finisher, + schema, + props, + target_rows, + severity_key(schema), + stats, + limits, + ) + .unwrap() + }); + (out, output) +} + +#[test] +fn retained_bytes_count_each_allocation_once() { + // Separate allocations, as reversed and adapted batches have: the + // retained bytes are those `get_array_memory_size` counts. + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + Field::new("message", DataType::Utf8, true), + ])); + let rows = 100; + let batch = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(Int64Array::from_iter_values(0..rows as i64)), + Arc::new(StringArray::from_iter_values( + (0..rows).map(|_| "x".repeat(2048)), + )), + ], + ) + .unwrap(); + let retained = log_batch_retained_bytes(&batch); + assert!(retained >= rows * 2048, "{retained}"); + // Less only by the array structs `get_array_memory_size` adds. + assert!(retained <= batch.get_array_memory_size()); + assert!(batch.get_array_memory_size() - retained < 1024); + // A slice keeps the whole allocation alive. + assert_eq!(log_batch_retained_bytes(&batch.slice(10, 5)), retained); + + // A batch decoded from one IPC message shares one allocation, which + // `get_array_memory_size` counts once per buffer. + let mut ipc = Vec::new(); + { + let mut writer = ArrowStreamWriter::try_new(&mut ipc, &schema).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + } + let decoded = arrow_ipc::reader::StreamReader::try_new(std::io::Cursor::new(ipc), None) + .unwrap() + .next() + .unwrap() + .unwrap(); + let decoded_retained = log_batch_retained_bytes(&decoded); + assert!(decoded_retained >= log_batch_data_bytes(&decoded)); + assert!(decoded_retained <= decoded.get_array_memory_size()); +} + +#[test] +fn large_rows_cut_clustered_row_groups_and_write_one_group_at_a_time() { + let dir = TempDir::new().unwrap(); + // 1,600 rows of about 2 KiB: the schema floor estimates a few bytes per + // row, while each 1,000-row group holds about 2 MiB of strings. + let files = stage_large_rows(&dir, 4, 200, 2048); + let schema = merged_schema_of(&files); + let total = 1600; + let target = 1000; + assert!(target * merged_schema_adapted_row_bytes(&schema) < 64 * 1024); + let props = WriterProperties::builder() + .set_max_row_group_row_count(Some(target)) + .build(); + let severity_idx = schema.index_of(SEVERITY).unwrap(); + let time_idx = schema.index_of(DEFAULT_TIMESTAMP_KEY).unwrap(); + let default_limits = log_clustering::ClusterMemoryLimits::default(); + let reference = sequential_clustered_bytes(&files, &schema, &props, target); + + // Ordinary limits: the groups keep their rows, and the bytes are those + // the sequential writer always wrote. + for in_flight in [1, 4] { + let (actual, output) = parallel_clustered_with_limits( + &files, + &schema, + &props, + target, + in_flight, + None, + default_limits, + ); + assert!(actual == reference, "in_flight {in_flight}: bytes differ"); + assert!(!output.write_stats.serial); + assert_eq!(output.write_stats.row_groups, 2); + } + + // Groups retaining more than the overlap limit are read, encoded and + // appended one at a time, with the same bytes. + let serial_limits = log_clustering::ClusterMemoryLimits { + overlap_max_retained_bytes: 128 * 1024, + ..default_limits + }; + for in_flight in [1, 4] { + let (actual, output) = parallel_clustered_with_limits( + &files, + &schema, + &props, + target, + in_flight, + None, + serial_limits, + ); + assert!(actual == reference, "serial, in_flight {in_flight}"); + assert!(output.write_stats.serial); + assert!(!output.write_stats.sequential); + assert_eq!(output.write_stats.row_groups, 2); + assert_eq!(output.write_stats.rows, total); + } + + // Rows stop accumulating into a group at the row-group byte cap: groups + // of about 128 rows, written alike by both writers. + let capped_limits = log_clustering::ClusterMemoryLimits { + row_group_max_bytes: 256 * 1024, + overlap_max_retained_bytes: 128 * 1024, + ..default_limits + }; + let (expected, sequential) = + sequential_decoded_with_limits(&files, &schema, &props, target, None, capped_limits); + assert!(sequential.write_stats.sequential); + for in_flight in [1, 4] { + let (actual, output) = parallel_clustered_with_limits( + &files, + &schema, + &props, + target, + in_flight, + None, + capped_limits, + ); + assert!(actual == expected, "capped, in_flight {in_flight}"); + let stats = output.write_stats; + assert!(stats.serial); + assert_eq!(stats.rows, total); + assert_eq!(stats.row_groups, sequential.write_stats.row_groups); + assert!(stats.row_groups >= total / 130, "{}", stats.row_groups); + let groups = row_groups_of_bytes(&dir, &format!("capped-{in_flight}.parquet"), &actual); + assert_eq!(groups.len(), stats.row_groups); + for rows in &groups { + // About 2 KiB a row: never more rows than fit the cap, plus one. + assert!(rows.len() <= 256 * 1024 / 2048 + 1, "{}", rows.len()); + assert_clustered(rows, severity_idx, time_idx); + } + // The same rows as the uncapped file, in more, smaller groups. + assert_eq!( + sorted(groups.into_iter().flatten().collect()), + sorted( + row_groups_of_bytes(&dir, "reference.parquet", &reference) + .into_iter() + .flatten() + .collect() + ) + ); + } + + // A cap only above the rows of a group changes nothing. + let (actual, output) = parallel_clustered_with_limits( + &files, + &schema, + &props, + target, + 4, + None, + log_clustering::ClusterMemoryLimits { + row_group_max_bytes: 64 * 1024 * 1024, + ..default_limits + }, + ); + assert!(actual == reference); + assert_eq!(output.write_stats.row_groups, 2); +} + +#[test] +fn byte_limit_split_encodes_later_row_groups_once() { + let dir = TempDir::new().unwrap(); + // 36,000 rows in groups of 9,000: two output batches per group, between + // which `ArrowWriter` checks its limits. + let files = stage_files(&dir, 3, 8, 1500, Severities::Mixed); + let schema = merged_schema_of(&files); + let target = 9000; + // Small pages, so the writer's size estimate grows as rows are written + // and reaches the limit inside every group. + let byte_limited = WriterProperties::builder() + .set_max_row_group_row_count(Some(target)) + .set_max_row_group_bytes(Some(16 * 1024)) + .set_data_page_size_limit(1024) + .set_dictionary_enabled(false) + .build(); + let expected = sequential_clustered_bytes(&files, &schema, &byte_limited, target); + let parallel = |props: &WriterProperties, in_flight: usize| { + parallel_clustered( + &LOG_CONVERSION_THREADPOOL, + &files, + &schema, + props, + target, + in_flight, + None, + ) + }; + + let (actual, output) = parallel(&byte_limited, 1); + assert!(actual == expected); + let stats = output.write_stats; + assert_eq!(stats.row_groups, 4); + // Every group splits, but only the first is encoded twice. + assert_eq!(stats.split_row_groups, 4, "{stats:?}"); + assert_eq!(stats.reencoded_row_groups, 1, "{stats:?}"); + + // Groups encoded together may each find the split; later waves do not. + let (actual, output) = parallel(&byte_limited, 2); + assert!(actual == expected); + let stats = output.write_stats; + assert_eq!(stats.split_row_groups, 4, "{stats:?}"); + assert!((1..=2).contains(&stats.reencoded_row_groups), "{stats:?}"); + + // A row limit below the group size is known before encoding: no group + // is encoded twice. + let row_limited = WriterProperties::builder() + .set_max_row_group_row_count(Some(target / 3 + 1)) + .set_max_row_group_bytes(None) + .build(); + let (actual, output) = parallel(&row_limited, 2); + assert!(actual == sequential_clustered_bytes(&files, &schema, &row_limited, target)); + assert_eq!(output.write_stats.split_row_groups, 4); + assert_eq!(output.write_stats.reencoded_row_groups, 0); +} + +#[test] +fn inline_clustered_stats_are_dropped_when_approximate_or_over_budget() { + use crate::storage::field_stats::FieldStatsAccumulator; + + let default_limits = log_clustering::ClusterMemoryLimits::default(); + let props = WriterProperties::builder() + .set_max_row_group_row_count(Some(ROW_GROUP)) + .build(); + + // 18,000 distinct ids: more than a field tracks, so its top values would + // depend on whether rows are counted in source or clustered order. + let many = TempDir::new().unwrap(); + let many_files = stage_files(&many, 3, 4, 1500, Severities::Mixed); + let many_schema = merged_schema_of(&many_files); + let (_, output) = parallel_clustered_with_limits( + &many_files, + &many_schema, + &props, + ROW_GROUP, + 2, + Some(FieldStatsAccumulator::new("approx", &many_schema, 5)), + default_limits, + ); + assert!(output.stats.is_none()); + let (_, output) = sequential_decoded_with_limits( + &many_files, + &many_schema, + &props, + ROW_GROUP, + Some(FieldStatsAccumulator::new("approx", &many_schema, 5)), + default_limits, + ); + assert!(output.stats.is_none()); + // The accumulator itself reports it. + let mut accumulator = FieldStatsAccumulator::new("approx", &many_schema, 5); + for batch in finished_batches(&many_files, &many_schema) { + accumulator.update(&batch); + } + assert!(accumulator.is_approximate()); + + // A conversion hands on no statistics, so the upload path rereads the + // file for them. + let stream = Stream::new( + Arc::new(Options { + local_staging_path: many.path().to_path_buf(), + row_group_size: ROW_GROUP, + log_severity_cluster_column: Some(SEVERITY.into()), + collect_dataset_stats: true, + max_field_statistics: 5, + ..Default::default() + }), + "approximate-stats", + LogStreamMetadata::default(), + None, + &None, + ); + let path = many.path().join("approximate.parquet.part"); + let artifacts = stream + .write_parquet_part_file( + &path, + conversion_reader(&many_files), + &many_schema, + &stream.parquet_writer_props(&many_schema, None, None, true), + None, + Some(severity_key(&many_schema)), + ) + .unwrap() + .unwrap(); + assert!(artifacts.field_stats.is_none()); + assert!(artifacts.parquet_metadata.is_some()); + + // 1,000 rows: exact counts, but more tracked bytes than a small budget. + let few = TempDir::new().unwrap(); + let files = stage_files(&few, 2, 2, 250, Severities::Mixed); + let schema = merged_schema_of(&files); + let mut accumulator = FieldStatsAccumulator::new("budget", &schema, 5); + for batch in finished_batches(&files, &schema) { + accumulator.update(&batch); + } + assert!(!accumulator.is_approximate()); + assert!(accumulator.retained_bytes() > 1024); + let small_budget = log_clustering::ClusterMemoryLimits { + inline_stats_max_bytes: 1024, + ..default_limits + }; + let (_, output) = parallel_clustered_with_limits( + &files, + &schema, + &props, + ROW_GROUP, + 2, + Some(FieldStatsAccumulator::new("budget", &schema, 5)), + small_budget, + ); + assert!(output.stats.is_none()); + let (_, output) = sequential_decoded_with_limits( + &files, + &schema, + &props, + ROW_GROUP, + Some(FieldStatsAccumulator::new("budget", &schema, 5)), + small_budget, + ); + assert!(output.stats.is_none()); + + // Within the budget, both writers keep the exact statistics. + let expected = accumulator.finish(); + let (_, output) = parallel_clustered_with_limits( + &files, + &schema, + &props, + ROW_GROUP, + 2, + Some(FieldStatsAccumulator::new("budget", &schema, 5)), + default_limits, + ); + assert_eq!(output.stats.unwrap().finish(), expected); + let (_, output) = sequential_decoded_with_limits( + &files, + &schema, + &props, + ROW_GROUP, + Some(FieldStatsAccumulator::new("budget", &schema, 5)), + default_limits, + ); + assert_eq!(output.stats.unwrap().finish(), expected); +} diff --git a/src/parseable/streams/push_queue.rs b/src/parseable/streams/push_queue.rs index eba06957d..a5c43b9e7 100644 --- a/src/parseable/streams/push_queue.rs +++ b/src/parseable/streams/push_queue.rs @@ -1,5 +1,25 @@ +//! Serializes a stream's staging writes without parking its callers. +//! +//! One caller at a time leads: it holds the stream's writer for a bounded +//! turn and writes what queued up behind it. Callers of `Stream::push` block +//! until their rows are flushed, as before. Callers of `Stream::push_async` +//! await instead, and their turns run on a blocking-pool thread, so a busy +//! stream costs the ingest thread pool nothing but the encoding each caller +//! does for itself before it queues. +//! +//! Admission is one FIFO line for both kinds of caller, bounded by count and +//! by bytes. `pause` closes it for a flush and waits for the admitted pushes, +//! so a flush detaches writers that hold every row accepted before it. +//! +//! No step waits for an async caller's task to be polled: a waiting async +//! job sits in the line itself and is moved on by whichever thread makes +//! room. A blocked thread or a flush therefore never depends on an executor +//! that it may itself be blocking. + use super::*; -use std::sync::{Condvar, mpsc}; +use crate::parseable::staging::writer::{DeferredDrop, PreEncodedBatch, is_compressed_batch}; +use std::sync::{Condvar, MutexGuard, Weak, mpsc}; +use tokio::{runtime::Handle, sync::oneshot}; const MAX_JOBS: usize = 64; const MAX_BYTES: usize = 64 << 20; @@ -9,10 +29,10 @@ const TURN_BYTES: usize = 16 << 20; #[derive(Default)] pub(super) struct PushQueue { state: Mutex, + // Blocked callers waiting in line. space: Condvar, - // Flush takes the exclusive guard up through detachment. Existing callers - // keep a shared guard until their disk and memory publication completes. - pub(super) lifecycle: RwLock<()>, + // Flushes waiting for the admitted pushes to finish. + idle: Condvar, } #[derive(Default)] @@ -20,13 +40,93 @@ struct State { busy: bool, bytes: usize, jobs: VecDeque, - next_ticket: u64, - serving: u64, + // Callers the queue has no room for yet, oldest first. + line: VecDeque, + next_waiter: u64, + // Admitted pushes whose turn has not ended: the leader's own batch and + // every job queued or being written. + active: usize, + // Flushes waiting for `active` to reach zero or detaching writers. No + // push is admitted meanwhile. + flushes: usize, +} + +/// A caller waiting for admission. +enum Waiter { + /// A thread blocked in `Stream::push`; it admits itself when it reaches + /// the head of the line. + Blocking(u64), + /// The job of a task awaiting `Stream::push_async`, admitted by + /// `PushQueue::advance`. + Async(u64, Job), } impl State { fn has_capacity(&self, bytes: usize) -> bool { - self.jobs.len() < MAX_JOBS && bytes <= MAX_BYTES - self.bytes + self.jobs.len() < MAX_JOBS && bytes <= MAX_BYTES.saturating_sub(self.bytes) + } + + /// Whether the caller at the head of the line may go ahead. An input + /// larger than the entire byte budget is admitted once the queue is idle. + fn admits(&self, bytes: usize) -> bool { + self.flushes == 0 && ((!self.busy && self.jobs.is_empty()) || self.has_capacity(bytes)) + } + + fn enqueue(&mut self, job: Job) { + self.active += 1; + self.bytes += job.bytes; + self.jobs.push_back(job); + } + + fn next_waiter(&mut self) -> u64 { + let id = self.next_waiter; + self.next_waiter = id.wrapping_add(1); + id + } + + /// Whether the blocked caller `id` is at the head of the line. + fn is_next(&self, id: u64) -> bool { + matches!(self.line.front(), Some(Waiter::Blocking(head)) if *head == id) + } + + /// Admits the async jobs at the head of the line while there is room. + /// Stops at a blocked caller, who admits itself. Whoever calls this + /// makes sure the queue has a leader afterwards. + fn advance(&mut self) { + while let Some(Waiter::Async(_, job)) = self.line.front() { + if !self.admits(job.bytes) { + return; + } + if let Some(Waiter::Async(_, job)) = self.line.pop_front() { + self.enqueue(job); + } + } + } + + /// Takes the lead of an idle queue for the async job at its head and + /// returns what its drainer needs. `None` when the queue has a leader + /// or nothing to write. + fn take_lead(&mut self, dead: &mut Vec) -> Option<(Arc, Handle)> { + if self.busy { + return None; + } + while let Some(job) = self.jobs.front() { + if let Some(lead) = job.reply.lead() { + self.busy = true; + return Some(lead); + } + dead.extend(self.pop_dead()); + self.advance(); + } + None + } + + /// Removes the job at the head of the queue, which nobody can lead for. + fn pop_dead(&mut self) -> Option { + let job = self.jobs.pop_front()?; + self.bytes -= job.bytes; + self.active = self.active.saturating_sub(1); + Some(job) } } @@ -35,87 +135,323 @@ enum Signal { Done(Result<(), StagingError>), } +/// How a queued caller hears about its batch. +enum Reply { + /// A thread blocked in `Stream::push`. It also leads the turn that + /// starts with its job. + Blocking(mpsc::Sender), + /// A task awaiting `Stream::push_async`. Its turn is led by a drainer + /// on the blocking pool of `lead`'s runtime. + Async { + done: oneshot::Sender>, + lead: Lead, + }, +} + +impl Reply { + fn done(self, result: Result<(), StagingError>) { + match self { + Reply::Blocking(reply) => { + let _ = reply.send(Signal::Done(result)); + } + Reply::Async { done, .. } => { + let _ = done.send(result); + } + } + } + + /// The stream and runtime of a drainer for this job, when it is async + /// and its stream is still alive. + fn lead(&self) -> Option<(Arc, Handle)> { + match self { + Reply::Blocking(_) => None, + Reply::Async { lead, .. } => lead + .stream + .upgrade() + .map(|stream| (stream, lead.runtime.clone())), + } + } +} + +/// What a leader needs to start a drainer for an async job: the queue holds +/// no reference to its own stream. +struct Lead { + stream: Weak, + runtime: Handle, +} + struct Job { disk: Option, key: String, record: RecordBatch, + preencoded: Option, timestamp: NaiveDateTime, bytes: usize, - reply: mpsc::Sender, + // Written uncompressed, where the message framing outweighs the rows: + // such jobs share one message with their neighbours. + small: bool, + reply: Reply, +} + +impl Job { + fn new( + disk: Option, + key: &str, + record: &RecordBatch, + preencoded: Option, + timestamp: NaiveDateTime, + bytes: usize, + reply: Reply, + ) -> Self { + Self { + disk, + key: key.to_owned(), + small: preencoded.is_none() && !is_compressed_batch(record), + record: record.clone(), + preencoded, + timestamp, + bytes, + reply, + } + } + + fn compatible(&self, next: &Self) -> bool { + self.disk == next.disk + && self.key == next.key + && self.record.schema_ref() == next.record.schema_ref() + } + + /// Whether `next` is written in the same message as this job. Only small + /// batches are copied together; a compressed batch is its own message, + /// usually encoded by its caller already. + fn combines_with(&self, next: &Self) -> bool { + self.small && next.small && self.compatible(next) + } +} + +/// Queue memory held by a job: its arrays and its encoded message. +fn job_bytes(record: &RecordBatch, preencoded: Option<&PreEncodedBatch>) -> usize { + record + .get_array_memory_size() + .saturating_add(preencoded.map_or(0, PreEncodedBatch::len)) +} + +/// A batch of a turn, as `Stream::write_pushes` takes it. +pub(super) struct PendingPush<'a> { + pub(super) disk: Option<&'a str>, + pub(super) key: &'a str, + pub(super) record: &'a RecordBatch, + pub(super) preencoded: Option<&'a PreEncodedBatch>, + pub(super) timestamp: NaiveDateTime, } // Hand off to a queued caller after every bounded turn, including on unwind. -struct Turn<'a>(&'a PushQueue); +struct Turn<'a> { + queue: &'a PushQueue, + // Admitted pushes this turn finishes. + taken: usize, + released: bool, +} + +impl<'a> Turn<'a> { + fn new(queue: &'a PushQueue, taken: usize) -> Self { + Self { + queue, + taken, + released: false, + } + } + + /// Ends the turn and passes the lead to whoever queued first: a blocked + /// caller leads its own turn, an async job gets a drainer. Returns `true` + /// when the caller is a drainer and keeps the lead for the next turn. + fn release(&mut self, drainer: bool) -> bool { + enum Next { + Handed, + Kept, + Drainer(Arc, Handle), + Idle, + } + if std::mem::replace(&mut self.released, true) { + return false; + } + let queue = self.queue; + // Jobs nobody can answer or lead for; freed after the lock. + let mut dead = Vec::new(); + let mut state = queue.lock(); + state.active = state.active.saturating_sub(self.taken); + let next = loop { + // An empty queue is idle for the waiter at the head of the line, + // which lets an input over the byte budget in. + state.busy = !state.jobs.is_empty(); + state.advance(); + let lead = match state.jobs.front().map(|job| &job.reply) { + None => break Next::Idle, + Some(Reply::Blocking(reply)) => { + if reply.send(Signal::Lead).is_ok() { + break Next::Handed; + } + None + } + Some(Reply::Async { .. }) if drainer => break Next::Kept, + Some(reply) => reply.lead(), + }; + if let Some((stream, runtime)) = lead { + break Next::Drainer(stream, runtime); + } + dead.extend(state.pop_dead()); + }; + state.busy = !matches!(next, Next::Idle); + let idle = state.active == 0; + drop(state); + queue.space.notify_all(); + if idle { + queue.idle.notify_all(); + } + drop(dead); + match next { + Next::Kept => true, + Next::Drainer(stream, runtime) => { + spawn_drainer(stream, &runtime); + false + } + Next::Handed | Next::Idle => false, + } + } +} impl Drop for Turn<'_> { fn drop(&mut self) { - let mut state = self.0.state.lock().unwrap_or_else(PoisonError::into_inner); - while let Some(next) = state.jobs.front() { - if next.reply.send(Signal::Lead).is_ok() { - return; - } - state.bytes -= state.jobs.pop_front().unwrap().bytes; + self.release(false); + } +} + +/// An async caller's place in the line. Dropped while still waiting, when +/// its future is cancelled, it takes its job out of the line: the batch is +/// not written and the callers behind it move up. +struct Parked<'a> { + queue: &'a PushQueue, + id: u64, +} + +impl Drop for Parked<'_> { + fn drop(&mut self) { + let mut state = self.queue.lock(); + let position = state + .line + .iter() + .position(|waiter| matches!(waiter, Waiter::Async(id, _) if *id == self.id)); + // Already admitted, or answered: nothing to take back. + let Some(waiter) = position.and_then(|position| state.line.remove(position)) else { + return; + }; + self.queue.admit_waiters(state); + drop(waiter); + } +} + +/// The lead of the queue, on its way to a blocking-pool thread. +struct Drainer(Option>); + +impl Drainer { + fn run(mut self) { + if let Some(stream) = self.0.take() { + stream.drain_turns(); } - state.busy = false; - let has_waiters = state.next_ticket != state.serving; - drop(state); - if has_waiters { - self.0.space.notify_all(); + } +} + +impl Drop for Drainer { + fn drop(&mut self) { + // A runtime that is shutting down drops the task without running it. + // The lead must not be lost with it: drain on the dropping thread. + if let Some(stream) = self.0.take() { + stream.drain_turns(); } } } +/// Starts leading turns for the async jobs at the head of the queue. The +/// caller must have set `busy` for it and must not hold the queue's state. +fn spawn_drainer(stream: Arc, runtime: &Handle) { + let drainer = Drainer(Some(stream)); + drop(runtime.spawn_blocking(move || drainer.run())); +} + +/// Holds admission closed for a flush. See `PushQueue::pause`. +pub(super) struct Paused<'a>(&'a PushQueue); + +impl Drop for Paused<'_> { + fn drop(&mut self) { + let mut state = self.0.lock(); + state.flushes -= 1; + self.0.admit_waiters(state); + } +} + impl Stream { pub(super) fn combined_push( &self, disk: Option, key: &str, record: &RecordBatch, + preencoded: Option, timestamp: NaiveDateTime, ) -> Result<(), StagingError> { let queue = &self.push_queue; - let _admission = queue - .lifecycle - .read() - .unwrap_or_else(PoisonError::into_inner); - let mut state = queue.state.lock().unwrap_or_else(PoisonError::into_inner); - let waiting = state.next_ticket != state.serving; - let bytes = if state.busy || waiting { - record.get_array_memory_size() + // Declared before any turn, so that cached batches a write evicts are + // freed after the turn has passed the writer on. + let mut deferred = DeferredDrop::default(); + let mut state = queue.lock(); + let waiting = !state.line.is_empty(); + let bytes = if state.busy || waiting || state.flushes > 0 { + job_bytes(record, preencoded.as_ref()) } else { 0 }; - if waiting || (state.busy && !state.has_capacity(bytes)) { + if waiting || !state.admits(bytes) { // Admit backpressured callers in order. An input larger than the // entire byte budget must eventually get an idle, direct turn. - let ticket = state.next_ticket; - state.next_ticket = ticket.wrapping_add(1); - while ticket != state.serving || (state.busy && !state.has_capacity(bytes)) { + let id = state.next_waiter(); + state.line.push_back(Waiter::Blocking(id)); + while !(state.is_next(id) && state.admits(bytes)) { state = queue .space .wait(state) .unwrap_or_else(PoisonError::into_inner); } - state.serving = ticket.wrapping_add(1); - queue.space.notify_all(); + state.line.pop_front(); } if !state.busy { state.busy = true; + state.active += 1; + // Whoever waited behind this caller queues behind its turn. + state.advance(); drop(state); - let _turn = Turn(queue); - return self.write_push(disk.as_deref(), key, record, timestamp); + queue.space.notify_all(); + let _turn = Turn::new(queue, 1); + return self.write_push( + disk.as_deref(), + key, + record, + preencoded.as_ref(), + timestamp, + &mut deferred, + ); } let (reply, result) = mpsc::channel(); - state.jobs.push_back(Job { + state.enqueue(Job::new( disk, - key: key.to_owned(), - record: record.clone(), + key, + record, + preencoded, timestamp, bytes, - reply, - }); - state.bytes += bytes; + Reply::Blocking(reply), + )); + state.advance(); drop(state); + queue.space.notify_all(); loop { match result .recv() @@ -123,60 +459,199 @@ impl Stream { { Signal::Done(result) => return result, Signal::Lead => { - let _turn = Turn(queue); - let jobs = queue.take_turn(); - for group in jobs.chunk_by(Job::compatible) { - self.write_group(group); - } + let mut turn = Turn::new(queue, 0); + let jobs = queue.take_turn(&mut turn); + self.write_turn(jobs, &mut deferred); } } } } - fn write_group(&self, group: &[Job]) { - let first = &group[0]; - let write = |batch: &RecordBatch| { - self.write_push(first.disk.as_deref(), &first.key, batch, first.timestamp) - }; - if group.len() == 1 { - let _ = first.reply.send(Signal::Done(write(&first.record))); - return; - } - let combined = match arrow::compute::concat_batches( - first.record.schema_ref(), - group.iter().map(|job| &job.record), - ) { - Ok(batch) => batch, - Err(_) => { - // Fall back to individual writes if concatenation fails (e.g. - // dictionary key or offset overflow) so innocent callers succeed. - for job in group { - let res = - self.write_push(job.disk.as_deref(), &job.key, &job.record, job.timestamp); - let _ = job.reply.send(Signal::Done(res)); + /// `combined_push` for async callers: waits for admission and for the + /// write without blocking a thread. The batch is always queued, and + /// written by a drainer on the blocking pool. + /// + /// Dropping the future while its job still waits in line takes the job + /// back: nothing is written. Once admitted to the queue the batch is + /// written whether or not anyone still awaits it. + pub(super) async fn combined_push_async( + self: &Arc, + disk: Option, + key: &str, + record: &RecordBatch, + preencoded: Option, + timestamp: NaiveDateTime, + ) -> Result<(), StagingError> { + let queue = &self.push_queue; + let bytes = job_bytes(record, preencoded.as_ref()); + let runtime = + Handle::try_current().unwrap_or_else(|_| FLUSH_AND_CONVERT_RUNTIME.handle().clone()); + let (reply, result) = oneshot::channel(); + let job = Job::new( + disk, + key, + record, + preencoded, + timestamp, + bytes, + Reply::Async { + done: reply, + lead: Lead { + stream: Arc::downgrade(self), + runtime: runtime.clone(), + }, + }, + ); + let parked = { + let mut state = queue.lock(); + if state.line.is_empty() && state.admits(bytes) { + // Queueing and taking the lead are one step: from here the + // batch is written without this task. + state.enqueue(job); + let lead = !std::mem::replace(&mut state.busy, true); + drop(state); + if lead { + spawn_drainer(Arc::clone(self), &runtime); } - return; + None + } else { + // 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)); + Some(Parked { queue, id }) } }; - let result = write(&combined).map_err(Arc::new); - for job in group { - let status = result.clone().map_err(StagingError::CombinedPush); - let _ = job.reply.send(Signal::Done(status)); + let result = result.await; + // Answered, so no longer in line: nothing to take back. + std::mem::forget(parked); + result.map_err(|_| std::io::Error::other("push worker terminated"))? + } + + /// Leads turns while async jobs head the queue. Runs on a blocking-pool + /// thread; ends when the queue is empty or a blocked caller takes over. + fn drain_turns(&self) { + let queue = &self.push_queue; + loop { + let mut deferred = DeferredDrop::default(); + let mut turn = Turn::new(queue, 0); + let jobs = queue.take_turn(&mut turn); + self.write_turn(jobs, &mut deferred); + if !turn.release(true) { + return; + } } } -} -impl Job { - fn compatible(&self, next: &Self) -> bool { - self.disk == next.disk - && self.key == next.key - && self.record.schema_ref() == next.record.schema_ref() + /// Writes a turn's jobs under one hold of the writer lock, each staging + /// file flushed once, and answers every caller after that flush. + fn write_turn(&self, jobs: Vec, deferred: &mut DeferredDrop) { + // Runs of small jobs for the same file and schema become one batch. + let mut units: Vec<(std::ops::Range, Option)> = + Vec::with_capacity(jobs.len()); + let mut start = 0; + for run in jobs.chunk_by(Job::combines_with) { + let end = start + run.len(); + let combined = (run.len() > 1) + .then(|| { + arrow::compute::concat_batches( + run[0].record.schema_ref(), + run.iter().map(|job| &job.record), + ) + .ok() + }) + .flatten(); + if combined.is_some() || run.len() == 1 { + units.push((start..end, combined)); + } else { + // Concatenation failed (e.g. dictionary key or offset + // overflow): write each batch on its own so innocent callers + // succeed. + units.extend((start..end).map(|index| (index..index + 1, None))); + } + start = end; + } + let pushes = units + .iter() + .map(|(range, combined)| { + let first = &jobs[range.start]; + PendingPush { + disk: first.disk.as_deref(), + key: &first.key, + record: combined.as_ref().unwrap_or(&first.record), + preencoded: match combined { + Some(_) => None, + None => first.preencoded.as_ref(), + }, + timestamp: first.timestamp, + } + }) + .collect::>(); + let results = self.write_pushes(&pushes, deferred); + drop(pushes); + let mut jobs = jobs.into_iter(); + for ((range, _), result) in units.into_iter().zip(results) { + if range.len() == 1 { + if let Some(job) = jobs.next() { + job.reply.done(result); + } + continue; + } + let result = result.map_err(Arc::new); + for job in jobs.by_ref().take(range.len()) { + job.reply + .done(result.clone().map_err(StagingError::CombinedPush)); + } + } } } impl PushQueue { - fn take_turn(&self) -> Vec { - let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner); + fn lock(&self) -> MutexGuard<'_, State> { + self.state.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// Lets the line move after a change that may have made room: admits + /// async jobs, starts a drainer if the queue was idle, and wakes the + /// blocked callers to look for themselves. + fn admit_waiters(&self, mut state: MutexGuard<'_, State>) { + let mut dead = Vec::new(); + state.advance(); + let lead = state.take_lead(&mut dead); + let idle = state.active == 0; + drop(state); + self.space.notify_all(); + if idle { + self.idle.notify_all(); + } + drop(dead); + if let Some((stream, runtime)) = lead { + spawn_drainer(stream, &runtime); + } + } + + /// Closes admission and waits until every admitted push has been written + /// and flushed, for a flush to detach writers. Pushes arriving meanwhile + /// wait in line and are admitted, in order, when the guard is dropped. + /// + /// Waiting never depends on a push's own thread or task making progress: + /// blocked callers lead their turns themselves and async jobs are written + /// by drainers, so a flush may run on any thread, including one that + /// polls the futures of pending async pushes. + pub(super) fn pause(&self) -> Paused<'_> { + let mut state = self.lock(); + state.flushes += 1; + while state.active > 0 { + state = self + .idle + .wait(state) + .unwrap_or_else(PoisonError::into_inner); + } + Paused(self) + } + + fn take_turn(&self, turn: &mut Turn<'_>) -> Vec { + let mut state = self.lock(); let mut jobs = Vec::with_capacity(TURN_JOBS); let mut bytes = 0; while let Some(next) = state.jobs.front() { @@ -188,7 +663,10 @@ impl PushQueue { jobs.push(job); } state.bytes -= bytes; - let has_waiters = state.next_ticket != state.serving; + turn.taken += jobs.len(); + // The turn made room: let the line move up behind it. + state.advance(); + let has_waiters = !state.line.is_empty(); drop(state); if has_waiters { self.space.notify_all(); @@ -200,13 +678,23 @@ impl PushQueue { #[cfg(test)] impl PushQueue { pub(super) fn queued(&self) -> usize { - self.state.lock().unwrap().jobs.len() + self.lock().jobs.len() } } #[cfg(test)] mod tests { use super::*; + use crate::parseable::staging::{StagingMemoryBudget, writer::MemWriter}; + use arrow_array::Int32Array; + use arrow_schema::{DataType, Field}; + use std::{ + future::Future, + pin::Pin, + sync::atomic::{AtomicBool, AtomicUsize, Ordering}, + }; + + const WAIT: Duration = Duration::from_secs(60); fn job(bytes: usize) -> Job { Job { @@ -214,11 +702,21 @@ mod tests { disk: None, key: String::new(), record: RecordBatch::new_empty(Arc::new(Schema::empty())), + preencoded: None, + small: true, timestamp: DateTime::::UNIX_EPOCH.naive_utc(), - reply: mpsc::channel().0, + reply: Reply::Blocking(mpsc::channel().0), } } + /// One turn's jobs, leaving the queue as the turn found it otherwise. + fn take(queue: &PushQueue) -> Vec { + let mut turn = Turn::new(queue, 0); + let jobs = queue.take_turn(&mut turn); + turn.released = true; + jobs + } + #[test] fn admission_and_turns_bound_count_and_bytes_independently() { let queue = PushQueue::default(); @@ -230,7 +728,7 @@ mod tests { } assert!(!state.has_capacity(1)); drop(state); - assert_eq!(queue.take_turn().len(), TURN_JOBS); + assert_eq!(take(&queue).len(), TURN_JOBS); let mut state = queue.state.lock().unwrap(); assert!(state.has_capacity(1)); assert_eq!(state.bytes, MAX_JOBS - TURN_JOBS); @@ -241,11 +739,665 @@ mod tests { .extend([job(TURN_BYTES - 1), job(2), job(MAX_BYTES - TURN_BYTES - 1)]); assert!(!state.has_capacity(1)); drop(state); - assert_eq!(queue.take_turn().len(), 1); - assert_eq!(queue.take_turn().len(), 1); - assert_eq!(queue.take_turn().len(), 1); + assert_eq!(take(&queue).len(), 1); + assert_eq!(take(&queue).len(), 1); + assert_eq!(take(&queue).len(), 1); assert_eq!(queue.state.lock().unwrap().bytes, 0); } + + #[test] + fn admission_is_closed_while_a_flush_waits_and_oversized_input_needs_an_idle_queue() { + let mut state = State::default(); + assert!(state.admits(MAX_BYTES * 2)); + state.busy = true; + assert!(state.admits(MAX_BYTES)); + assert!(!state.admits(MAX_BYTES + 1)); + // An oversized job admitted to an idle queue leaves no room, and no + // underflow, for the next. + state.bytes = MAX_BYTES * 2; + assert!(!state.admits(1)); + state.bytes = 0; + state.flushes = 1; + assert!(!state.admits(0)); + state.busy = false; + assert!(!state.admits(0)); + } + + #[test] + fn the_line_admits_async_jobs_in_order_and_stops_at_a_blocked_caller() { + let mut state = State { + busy: true, + ..Default::default() + }; + let first = state.next_waiter(); + state.line.push_back(Waiter::Async(first, job(1))); + let second = state.next_waiter(); + state.line.push_back(Waiter::Async(second, 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))); + + // The second job does not fit behind the first: nobody overtakes it. + state.advance(); + assert_eq!((state.jobs.len(), state.line.len()), (1, 3)); + assert_eq!((state.active, state.bytes), (1, 1)); + assert!(!state.is_next(blocked)); + // Room again: it goes in, and the blocked caller is next. + state.bytes = 0; + state.advance(); + assert_eq!((state.jobs.len(), state.line.len()), (2, 2)); + assert!(state.is_next(blocked)); + // Async jobs behind a blocked caller wait for it to admit itself. + state.bytes = 0; + state.advance(); + assert_eq!(state.line.len(), 2); + state.line.pop_front(); + state.advance(); + assert!(state.line.is_empty()); + assert_eq!((state.jobs.len(), state.active), (3, 3)); + } + + fn stream(dir: &tempfile::TempDir, name: &str) -> StreamRef { + Stream::new( + Arc::new(Options { + local_staging_path: dir.path().to_owned(), + ..Default::default() + }), + name, + LogStreamMetadata::default(), + None, + &None, + ) + } + + /// Gives the stream its own memory staging budget. + fn budgeted(stream: &Stream, limit: usize) -> Arc { + let budget = StagingMemoryBudget::new(limit); + stream.writer.lock().unwrap().mem = Some(MemWriter::with_budget(Arc::clone(&budget))); + budget + } + + fn id_schema() -> Arc { + Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])) + } + + fn ids(schema: &Arc, ids: std::ops::Range) -> RecordBatch { + RecordBatch::try_new( + schema.clone(), + vec![Arc::new(Int32Array::from_iter_values(ids))], + ) + .unwrap() + } + + /// One minute for every push, so they share a staging file. + fn minute() -> NaiveDateTime { + DateTime::parse_from_rfc3339("2020-01-02T12:34:30Z") + .unwrap() + .naive_utc() + } + + fn ids_of(batch: &RecordBatch) -> Vec { + batch + .column(batch.schema().index_of("id").unwrap()) + .as_any() + .downcast_ref::() + .unwrap() + .values() + .to_vec() + } + + /// The record batch messages of the stream's sealed staging files. + fn sealed_frames(stream: &Stream) -> Vec { + // Oldest first. + stream + .arrow_files() + .into_iter() + .flat_map(|path| { + arrow_ipc::reader::StreamReader::try_new(File::open(path).unwrap(), None) + .unwrap() + .collect::, _>>() + .unwrap() + }) + .collect() + } + + fn sealed_ids(stream: &Stream) -> Vec { + sealed_frames(stream).iter().flat_map(ids_of).collect() + } + + fn until(what: &str, mut done: impl FnMut() -> bool) { + let deadline = Instant::now() + WAIT; + while !done() { + assert!(Instant::now() < deadline, "timed out waiting for {what}"); + std::thread::sleep(Duration::from_millis(1)); + } + } + + type Push<'a> = Pin> + 'a>>; + + /// An async push of `batch`, encoded ahead as an ingest handler would. + fn push_async<'a>(stream: &'a StreamRef, batch: &'a RecordBatch) -> Push<'a> { + static NO_PARTITION: Lazy> = Lazy::new(HashMap::new); + let preencoded = stream.preencode_for_push(batch, StreamType::UserDefined); + Box::pin(stream.push_async( + "key", + batch, + preencoded, + minute(), + &NO_PARTITION, + StreamType::UserDefined, + )) + } + + /// Polls a push once, as an executor with nothing else to do would. + fn is_pending(push: &mut Push<'_>) -> bool { + let mut context = std::task::Context::from_waker(futures::task::noop_waker_ref()); + push.as_mut().poll(&mut context).is_pending() + } + + fn push_blocking(stream: &Stream, batch: &RecordBatch) -> Result<(), StagingError> { + stream.push( + "key", + batch, + minute(), + &HashMap::new(), + StreamType::UserDefined, + ) + } + + #[tokio::test(flavor = "current_thread")] + async fn async_pushes_wait_as_futures_and_large_batches_are_written_as_encoded() { + let dir = tempfile::tempdir().unwrap(); + let stream = stream(&dir, "async-queue"); + let schema = id_schema(); + let batches = (0..32) + .map(|i| ids(&schema, i * 200..(i + 1) * 200)) + .collect::>(); + // With the writer held, the one drainer blocks on it and every other + // push is a queued job: 32 callers, one executor thread, none parked. + let writer = stream.writer.lock().unwrap(); + let mut pushes = batches + .iter() + .map(|batch| push_async(&stream, batch)) + .collect::>(); + for push in &mut pushes { + assert!(is_pending(push)); + } + until("the drainer's first turn", || { + let state = stream.push_queue.lock(); + state.busy && state.active == 32 && state.jobs.len() < 32 + }); + // A second look changes nothing: they are waiting, not spinning. + for push in &mut pushes { + assert!(is_pending(push)); + } + drop(writer); + for push in pushes { + tokio::time::timeout(WAIT, push).await.unwrap().unwrap(); + } + // Answers go out before the last turn ends. + until("an idle queue", || !stream.push_queue.lock().busy); + { + let state = stream.push_queue.lock(); + assert_eq!((state.active, state.bytes, state.jobs.len()), (0, 0, 0)); + } + // A handful of turns flushed the file, not one flush per push. + let flushes = stream + .writer + .lock() + .unwrap() + .disk + .values() + .map(|disk| disk.flush_count()) + .sum::(); + assert!( + (2..=1 + 32usize.div_ceil(TURN_JOBS)).contains(&flushes), + "{flushes}" + ); + + stream.flush(true).unwrap(); + // In admission order, and one message per push: batches this size + // arrive encoded and are never concatenated. + assert_eq!(sealed_frames(&stream), batches); + } + + #[tokio::test(flavor = "current_thread")] + async fn async_backpressure_is_bounded_and_fifo_and_survives_cancelled_waiters() { + let dir = tempfile::tempdir().unwrap(); + let stream = stream(&dir, "async-backpressure"); + let schema = id_schema(); + let batches = (0..200).map(|i| ids(&schema, i..i + 1)).collect::>(); + let writer = stream.writer.lock().unwrap(); + let mut pushes = batches + .iter() + .map(|batch| Some(push_async(&stream, batch))) + .collect::>(); + let poll_all = |pushes: &mut Vec>>| { + for push in pushes.iter_mut().flatten() { + assert!(is_pending(push)); + assert!(stream.push_queue.queued() <= MAX_JOBS); + } + }; + poll_all(&mut pushes); + // The drainer takes one turn and blocks on the writer. The queue + // refills to its bound from the line, with no task polled for it, + // and everyone else keeps waiting. + until("a full queue behind the drainer", || { + let state = stream.push_queue.lock(); + assert!(state.jobs.len() <= MAX_JOBS); + state.jobs.len() == MAX_JOBS && state.active > MAX_JOBS + }); + poll_all(&mut pushes); + let admitted = { + let state = stream.push_queue.lock(); + assert!(state.active <= MAX_JOBS + TURN_JOBS); + assert!(state.bytes <= MAX_BYTES); + assert_eq!(state.line.len(), batches.len() - state.active); + state.active + }; + // Cancel every other waiter, including the head of the line. + let mut expected = Vec::new(); + for (index, push) in pushes.iter_mut().enumerate() { + if index >= admitted && (index - admitted) % 2 == 0 { + *push = None; + } else { + expected.push(index as i32); + } + } + drop(writer); + for push in pushes.into_iter().flatten() { + tokio::time::timeout(WAIT, push).await.unwrap().unwrap(); + } + until("an idle queue", || !stream.push_queue.lock().busy); + { + let state = stream.push_queue.lock(); + assert_eq!((state.active, state.bytes, state.jobs.len()), (0, 0, 0)); + assert!(state.line.is_empty()); + } + stream.flush(true).unwrap(); + // Every push that stayed was written exactly once, in line order; + // small batches shared messages along the way. + assert_eq!(sealed_ids(&stream), expected); + assert!(sealed_frames(&stream).len() < expected.len()); + } + + #[tokio::test(flavor = "current_thread")] + async fn flush_waits_for_admitted_pushes_and_holds_back_later_ones() { + let dir = tempfile::tempdir().unwrap(); + let stream = stream(&dir, "flush-gate"); + let schema = id_schema(); + let (first, second, third) = ( + ids(&schema, 0..300), + ids(&schema, 300..600), + ids(&schema, 600..900), + ); + let writer = stream.writer.lock().unwrap(); + let mut admitted = push_async(&stream, &first); + assert!(is_pending(&mut admitted)); + until("the drainer", || stream.push_queue.queued() == 0); + + // The flush runs on its own thread and must wait for `first`. This + // thread, the only one that polls the pushes, polls none of them + // again until the flush is through. + let flushed = Arc::new(AtomicBool::new(false)); + let flusher = { + let (stream, flushed) = (stream.clone(), flushed.clone()); + std::thread::spawn(move || { + stream.flush(true).unwrap(); + flushed.store(true, Ordering::Release); + sealed_ids(&stream) + }) + }; + until("the flush to close admission", || { + stream.push_queue.lock().flushes == 1 + }); + // Pushes arriving now, async and blocking, line up behind it. + let mut later = push_async(&stream, &second); + assert!(is_pending(&mut later)); + let blocked = { + let (stream, third) = (stream.clone(), third.clone()); + std::thread::spawn(move || push_blocking(&stream, &third)) + }; + until("both later pushes in line", || { + stream.push_queue.lock().line.len() == 2 + }); + { + let state = stream.push_queue.lock(); + assert_eq!((state.active, state.jobs.len()), (1, 0)); + } + assert!(!flushed.load(Ordering::Acquire)); + + drop(writer); + // The detached file holds exactly what was admitted before the flush. + assert_eq!(flusher.join().unwrap(), (0..300).collect::>()); + // Both later pushes get through with no task polled: the blocked + // caller stood behind the async one in line. + blocked.join().unwrap().unwrap(); + tokio::time::timeout(WAIT, admitted).await.unwrap().unwrap(); + tokio::time::timeout(WAIT, later).await.unwrap().unwrap(); + stream.flush(true).unwrap(); + // Two files now, listed by modification time: compare the rows. + assert_eq!(stream.arrow_files().len(), 2); + let mut sealed = sealed_ids(&stream); + sealed.sort_unstable(); + assert!(sealed == (0..900).collect::>()); + } + + #[tokio::test(flavor = "current_thread")] + async fn the_lead_passes_between_blocked_callers_and_drainers() { + let dir = tempfile::tempdir().unwrap(); + let stream = stream(&dir, "handoff"); + let schema = id_schema(); + let batches = (0..5) + .map(|i| ids(&schema, i * 150..(i + 1) * 150)) + .collect::>(); + let blocking = |index: usize| { + let (stream, batch) = (stream.clone(), batches[index].clone()); + std::thread::spawn(move || push_blocking(&stream, &batch)) + }; + + // A blocked caller leads with an async job queued behind it: when + // its turn ends the lead goes to a drainer it starts. + let writer = stream.writer.lock().unwrap(); + let leader = blocking(0); + until("the direct leader", || stream.push_queue.lock().busy); + let mut behind_leader = push_async(&stream, &batches[1]); + assert!(is_pending(&mut behind_leader)); + assert_eq!(stream.push_queue.queued(), 1); + drop(writer); + leader.join().unwrap().unwrap(); + tokio::time::timeout(WAIT, behind_leader) + .await + .unwrap() + .unwrap(); + until("an idle queue", || !stream.push_queue.lock().busy); + + // A drainer leads with a blocked caller queued behind it, and async + // jobs behind that: the drainer hands over and the blocked caller + // writes the async jobs of its turn. + let writer = stream.writer.lock().unwrap(); + let mut ahead = push_async(&stream, &batches[2]); + assert!(is_pending(&mut ahead)); + until("the drainer's turn", || stream.push_queue.queued() == 0); + let follower = blocking(3); + until("the blocked follower", || stream.push_queue.queued() == 1); + let mut behind_follower = push_async(&stream, &batches[4]); + assert!(is_pending(&mut behind_follower)); + assert_eq!(stream.push_queue.queued(), 2); + drop(writer); + follower.join().unwrap().unwrap(); + tokio::time::timeout(WAIT, ahead).await.unwrap().unwrap(); + tokio::time::timeout(WAIT, behind_follower) + .await + .unwrap() + .unwrap(); + until("an idle queue", || !stream.push_queue.lock().busy); + + stream.flush(true).unwrap(); + assert_eq!(sealed_frames(&stream), batches); + } + + #[tokio::test(flavor = "current_thread")] + async fn a_drainer_dropped_unrun_still_drains() { + // A runtime that is shutting down drops blocking tasks unrun. The + // lead they carry must not be lost with them. + let dir = tempfile::tempdir().unwrap(); + let stream = stream(&dir, "dropped-drainer"); + let schema = id_schema(); + let batch = ids(&schema, 0..120); + let (reply, result) = oneshot::channel(); + { + let mut state = stream.push_queue.lock(); + state.busy = true; + state.active += 1; + state.jobs.push_back(Job::new( + Some(stream.filename_by_partition("key", minute(), &HashMap::new())), + "key", + &batch, + None, + minute(), + 0, + Reply::Async { + done: reply, + lead: Lead { + stream: Arc::downgrade(&stream), + runtime: Handle::current(), + }, + }, + )); + } + drop(Drainer(Some(stream.clone()))); + result.await.unwrap().unwrap(); + assert!(!stream.push_queue.lock().busy); + stream.flush(true).unwrap(); + assert_eq!(sealed_ids(&stream), (0..120).collect::>()); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn concurrent_async_and_blocking_pushes_with_flushes_keep_every_row_once() { + const ASYNC_TASKS: i32 = 8; + const BLOCKING_THREADS: i32 = 6; + const PUSHES: i32 = 60; + const SPAN: i32 = 1000; + let dir = tempfile::tempdir().unwrap(); + let stream = stream(&dir, "stress"); + // Small enough that the cache keeps evicting under the pushes. + let budget = budgeted(&stream, 48 * 1024); + let schema = id_schema(); + // Pusher `p` owns ids [p * PUSHES * SPAN ..): small batches that are + // combined and large ones that arrive encoded, interleaved. + let batch = move |schema: &Arc, pusher: i32, push: i32| { + let start = (pusher * PUSHES + push) * SPAN; + let rows = [1, 150, 7, 900, 99, 100][(push % 6) as usize]; + ids(schema, start..start + rows) + }; + let mut expected = (0..ASYNC_TASKS + BLOCKING_THREADS) + .flat_map(|pusher| (0..PUSHES).map(move |push| (pusher, push))) + .flat_map(|(pusher, push)| ids_of(&batch(&schema, pusher, push))) + .collect::>(); + expected.sort_unstable(); + + let done = Arc::new(AtomicBool::new(false)); + let flushes = Arc::new(AtomicUsize::new(0)); + let background = [true, false].map(|flusher| { + let (stream, done, flushes) = (stream.clone(), done.clone(), flushes.clone()); + std::thread::spawn(move || { + while !done.load(Ordering::Acquire) { + if flusher { + stream.flush(true).unwrap(); + flushes.fetch_add(1, Ordering::AcqRel); + } else { + stream.evict_staging_memory(); + } + std::thread::sleep(Duration::from_micros(300)); + } + }) + }); + // Spawned tasks: the futures are `Send`, and polled on any worker. + let tasks = (0..ASYNC_TASKS) + .map(|pusher| { + let (stream, schema) = (stream.clone(), schema.clone()); + tokio::spawn(async move { + for push in 0..PUSHES { + let record = batch(&schema, pusher, push); + let preencoded = + stream.preencode_for_push(&record, StreamType::UserDefined); + stream + .push_async( + "key", + &record, + preencoded, + minute(), + &HashMap::new(), + StreamType::UserDefined, + ) + .await + .unwrap(); + } + }) + }) + .collect::>(); + let threads = (ASYNC_TASKS..ASYNC_TASKS + BLOCKING_THREADS) + .map(|pusher| { + let (stream, schema) = (stream.clone(), schema.clone()); + std::thread::spawn(move || { + for push in 0..PUSHES { + push_blocking(&stream, &batch(&schema, pusher, push)).unwrap(); + } + }) + }) + .collect::>(); + tokio::time::timeout(WAIT, async { + for task in tasks { + task.await.unwrap(); + } + }) + .await + .expect("async pushes deadlocked"); + tokio::task::spawn_blocking(move || { + for thread in threads { + thread.join().unwrap(); + } + }) + .await + .unwrap(); + done.store(true, Ordering::Release); + for thread in background { + thread.join().unwrap(); + } + assert!(flushes.load(Ordering::Acquire) > 0); + + // Queryable before the last flush: cached, evicted and detached rows + // together are every row, once. + let mut staged = stream + .recordbatches_cloned(&schema) + .unwrap() + .iter() + .flat_map(ids_of) + .collect::>(); + staged.sort_unstable(); + assert_eq!(staged.len(), expected.len()); + assert!(staged == expected, "staged rows differ from pushed rows"); + + stream.flush(true).unwrap(); + let mut sealed = sealed_ids(&stream); + sealed.sort_unstable(); + assert!(sealed == expected, "sealed rows differ from pushed rows"); + { + let state = stream.push_queue.lock(); + assert_eq!((state.active, state.bytes, state.flushes), (0, 0, 0)); + assert!(!state.busy && state.jobs.is_empty() && state.line.is_empty()); + } + // Every writer is detached, so nothing is cached, and the budget + // agrees to the byte however the evictions interleaved. + assert_eq!(budget.used(), 0); + drop(stream); + assert_eq!(budget.used(), 0); + } + + /// An Int32 batch whose buffer reports, when freed, whether the stream's + /// writer lock and queue were free at that moment. + fn probed_batch( + stream: &StreamRef, + schema: &Arc, + ids: std::ops::Range, + freed_outside_locks: &Arc>>, + ) -> RecordBatch { + struct Probe { + values: Vec, + stream: std::panic::AssertUnwindSafe>, + freed_outside_locks: Arc>>, + } + impl Drop for Probe { + fn drop(&mut self) { + let outside = self.stream.upgrade().is_none_or(|stream| { + stream.writer.try_lock().is_ok() + && stream + .push_queue + .state + .try_lock() + .is_ok_and(|state| !state.busy && state.flushes == 0) + }); + self.freed_outside_locks.lock().unwrap().push(outside); + } + } + let probe = Arc::new(Probe { + values: ids.collect(), + stream: std::panic::AssertUnwindSafe(Arc::downgrade(stream)), + freed_outside_locks: freed_outside_locks.clone(), + }); + let rows = probe.values.len(); + let pointer = std::ptr::NonNull::new(probe.values.as_ptr() as *mut u8).unwrap(); + // SAFETY: the buffer covers exactly `probe.values`, which lives, + // unmoved and unmodified, as long as the buffer's owner `probe`. + let buffer = unsafe { + arrow::buffer::Buffer::from_custom_allocation( + pointer, + rows * std::mem::size_of::(), + probe, + ) + }; + RecordBatch::try_new( + schema.clone(), + vec![Arc::new(Int32Array::new( + arrow::buffer::ScalarBuffer::new(buffer, 0, rows), + None, + ))], + ) + .unwrap() + } + + #[test] + fn evicted_and_rolled_over_caches_are_freed_after_the_locks_are_released() { + let dir = tempfile::tempdir().unwrap(); + let stream = stream(&dir, "deferred-drop"); + let schema = id_schema(); + let freed = Arc::new(Mutex::new(Vec::new())); + let probed = |ids| probed_batch(&stream, &schema, ids, &freed); + let first = probed(0..1000); + let budget = budgeted(&stream, first.get_array_memory_size() + 16); + let pushed = |batch: RecordBatch| { + push_blocking(&stream, &batch).unwrap(); + // The cache now holds the only reference to the data. + drop(batch); + }; + let frees = || freed.lock().unwrap().clone(); + + // Budget eviction inside a push: the cached batch outlives the write + // and the turn. + pushed(first); + assert!(budget.used() > 0 && frees().is_empty()); + // Not cached itself (the budget is shedding): freed by its caller. + pushed(probed(1000..2000)); + assert_eq!(budget.used(), 0); + assert_eq!(frees(), [true, true]); + + // Eviction under memory pressure. + budget.set_limit(1 << 30); + pushed(probed(2000..3000)); + assert!(budget.used() > 0); + assert!(stream.evict_staging_memory() > 0); + assert_eq!(budget.used(), 0); + assert_eq!(frees(), [true; 3]); + + // Rollover: the flush detaches the segment under both locks. + pushed(probed(3000..4000)); + assert!(budget.used() > 0); + stream.flush(true).unwrap(); + assert_eq!(budget.used(), 0); + assert_eq!(frees(), [true; 4]); + + // Nothing was lost on the way. + let mut staged = stream + .recordbatches_cloned(&schema) + .unwrap() + .iter() + .flat_map(ids_of) + .collect::>(); + staged.sort_unstable(); + assert_eq!(staged, (0..4000).collect::>()); + } } #[cfg(test)] @@ -283,32 +1435,32 @@ mod track_e { .unwrap(); let (reply, result) = mpsc::channel(); ( - Job { - disk: Some("dict.arrows".into()), - key: "dict".into(), - record, - timestamp: Utc::now().naive_utc(), - bytes: 0, - reply, - }, + Job::new( + Some("dict.arrows".into()), + "dict", + &record, + None, + Utc::now().naive_utc(), + 0, + Reply::Blocking(reply), + ), result, ) }) .unzip(); - assert!(jobs[0].compatible(&jobs[1])); + assert!(jobs[0].combines_with(&jobs[1])); let schema = jobs[0].record.schema(); - assert!( - arrow::compute::concat_batches(&schema, jobs.iter().map(|job| &job.record)).is_err() - ); + let records = jobs + .iter() + .map(|job| job.record.clone()) + .collect::>(); + assert!(arrow::compute::concat_batches(&schema, &records).is_err()); - stream.write_group(&jobs); + stream.write_turn(jobs, &mut DeferredDrop::default()); for reply in replies { assert!(matches!(reply.try_recv().unwrap(), Signal::Done(Ok(())))); } let (capture, ()) = stream.capture_staging_sources(&schema, |_| ()).unwrap(); - assert_eq!( - capture.into_record_batches(&schema).unwrap(), - jobs.into_iter().map(|job| job.record).collect::>() - ); + assert_eq!(capture.into_record_batches(&schema).unwrap(), records); } } diff --git a/src/parseable/streams/writeback.rs b/src/parseable/streams/writeback.rs index e7129ff86..4ac756a58 100644 --- a/src/parseable/streams/writeback.rs +++ b/src/parseable/streams/writeback.rs @@ -1,38 +1,59 @@ -#[cfg(not(target_os = "linux"))] -pub(super) type Output = std::fs::File; +use std::{fs::File, io::BufWriter}; +/// Bytes gathered before one `write(2)` to the Parquet part file. The Parquet +/// writer hands over pages through its own small buffer, so without this each +/// 8 KiB of a part file costs a system call. +const OUTPUT_BUFFER_BYTES: usize = 256 * 1024; + +/// Bytes of written output after which the kernel is asked to start writing +/// them back, so a part file does not sit entirely in dirty page cache until +/// it is synced. #[cfg(target_os = "linux")] +const WRITEBACK_HINT_BYTES: i64 = 32 << 20; + +/// Buffered Parquet part file. Buffered bytes reach the file on `flush`, when +/// the writeback hint is due, and when the value is dropped. A caller that +/// must know the bytes were written calls `flush`, since drop cannot report a +/// failure. pub(super) struct Output { - file: std::fs::File, + file: BufWriter, + #[cfg(target_os = "linux")] written: i64, + #[cfg(target_os = "linux")] hinted: i64, + #[cfg(target_os = "linux")] enabled: bool, } -#[cfg(target_os = "linux")] -impl From for Output { - fn from(file: std::fs::File) -> Self { +impl From for Output { + fn from(file: File) -> Self { Self { - file, + file: BufWriter::with_capacity(OUTPUT_BUFFER_BYTES, file), + #[cfg(target_os = "linux")] written: 0, + #[cfg(target_os = "linux")] hinted: 0, + #[cfg(target_os = "linux")] enabled: true, } } } -#[cfg(target_os = "linux")] impl std::io::Write for Output { + #[cfg(target_os = "linux")] fn write(&mut self, buf: &[u8]) -> std::io::Result { use std::os::fd::AsRawFd; let n = self.file.write(buf)?; self.written += n as i64; let pending = self.written - self.hinted; - if self.enabled && pending >= 32 << 20 { + if self.enabled && pending >= WRITEBACK_HINT_BYTES { + // The hint covers bytes the file already has, so the buffered + // tail of the range is written first. + self.file.flush()?; // SAFETY: the borrowed file owns this fd throughout the call. let rc = unsafe { libc::sync_file_range( - self.file.as_raw_fd(), + self.file.get_ref().as_raw_fd(), self.hinted, pending, libc::SYNC_FILE_RANGE_WRITE, @@ -44,6 +65,11 @@ impl std::io::Write for Output { Ok(n) } + #[cfg(not(target_os = "linux"))] + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.file.write(buf) + } + fn flush(&mut self) -> std::io::Result<()> { self.file.flush() } @@ -88,4 +114,52 @@ mod tests { encode(Output::from(std::fs::File::create(&path).unwrap()), &batch); assert_eq!(std::fs::read(path).unwrap(), expected); } + + #[test] + fn small_writes_are_buffered_until_flush_or_drop() { + let dir = temp_dir::TempDir::new().unwrap(); + let path = dir.path().join("buffered"); + let mut output = Output::from(std::fs::File::create(&path).unwrap()); + // Many small writes stay in the buffer: nothing reaches the file. + for _ in 0..1000 { + output.write_all(b"0123456789").unwrap(); + } + assert_eq!(output.written, 10_000); + assert_eq!(std::fs::metadata(&path).unwrap().len(), 0); + output.flush().unwrap(); + assert_eq!(std::fs::metadata(&path).unwrap().len(), 10_000); + + // More than one buffer of small writes spills in buffer-sized writes, + // and the tail reaches the file when the output is dropped. + let chunk = [7u8; 1000]; + for _ in 0..600 { + output.write_all(&chunk).unwrap(); + } + let on_disk = std::fs::metadata(&path).unwrap().len(); + assert!(on_disk > 10_000 && on_disk < 610_000, "{on_disk}"); + assert_eq!((on_disk - 10_000) % 1000, 0); + drop(output); + let bytes = std::fs::read(&path).unwrap(); + assert_eq!(bytes.len(), 610_000); + assert!(bytes[10_000..].iter().all(|byte| *byte == 7)); + } + + #[test] + fn hint_is_issued_once_buffered_writes_reach_the_threshold() { + let dir = temp_dir::TempDir::new().unwrap(); + let path = dir.path().join("hint-small-writes"); + let mut output = Output::from(std::fs::File::create(&path).unwrap()); + let chunk = vec![3u8; 100_000]; + let mut written = 0i64; + while written + (chunk.len() as i64) < WRITEBACK_HINT_BYTES { + output.write_all(&chunk).unwrap(); + written += chunk.len() as i64; + } + assert_eq!(output.hinted, 0); + output.write_all(&chunk).unwrap(); + written += chunk.len() as i64; + // The hint flushed the buffer first: every byte it covers is in the file. + assert_eq!(output.hinted, written); + assert_eq!(std::fs::metadata(&path).unwrap().len() as i64, written); + } } diff --git a/src/query/mod.rs b/src/query/mod.rs index f13a2c3ef..514823f40 100644 --- a/src/query/mod.rs +++ b/src/query/mod.rs @@ -19,6 +19,7 @@ mod filter_optimizer; mod latest_n; mod listing_table_builder; +mod ordered_topk; pub mod read_only; pub mod stream_schema_provider; @@ -480,7 +481,8 @@ impl Query { let mut builder = SessionStateBuilder::new() .with_default_features() .with_config(config) - .with_runtime_env(runtime); + .with_runtime_env(runtime) + .with_physical_optimizer_rule(Arc::new(ordered_topk::ProgressiveTopKRule)); // Append any additional physical optimizer rules (e.g., enterprise partial agg pushdown) if let Ok(rules) = ADDITIONAL_PHYSICAL_OPTIMIZER_RULES.read() { @@ -1626,6 +1628,7 @@ mod tests { null_count: None, uncompressed_size: 0, compressed_size: 0, + stats_provenance: None, }; let int_stats = |minute| { Some(TypedStatistics::Int(Int64Type { @@ -2092,9 +2095,9 @@ mod tests { let query = stream.query(&limited, "5m", "now").await; assert_eq!(row_count(&stream.run(&query).await), 1); - // An end that is not on a minute boundary is what the parser must never - // produce: the bound is then not exact, a filter stays above the scan - // and the limit does not reach it. + // Mid-minute time bounds on the partition column are now also handled + // as `Exact` (enforced on boundary/staging scans while interior files + // skip decoding the time column), so `LIMIT 1` reaches the scan here too. let unaligned = stream .query_over( &limited, @@ -2103,6 +2106,16 @@ mod tests { .await; assert_eq!( filter_and_fetch_at_scan(&stream.ctx, &unaligned), + (false, Some(1)) + ); + assert_eq!(row_count(&stream.run(&unaligned).await), 1); + + // Non-partition predicates remain `Inexact`, so a `Filter` stays above + // the scan and `LIMIT` is not pushed into `TableScan`. + let filtered = format!("SELECT * FROM {} WHERE id > 0 LIMIT 1", stream.name); + let filtered_query = stream.query(&filtered, "5m", "now").await; + assert_eq!( + filter_and_fetch_at_scan(&stream.ctx, &filtered_query), (true, None) ); diff --git a/src/query/ordered_topk.rs b/src/query/ordered_topk.rs new file mode 100644 index 000000000..aa39a2cc8 --- /dev/null +++ b/src/query/ordered_topk.rs @@ -0,0 +1,3246 @@ +/* + * Parseable Server (C) 2022 - 2025 Parseable, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +//! Progressive, certified-bounds TopK execution. +//! +//! Parseable never advertises a physical row order for its scans (see +//! `docs/query-ordering-performance.md`), so `ORDER BY LIMIT n` always +//! plans a TopK `SortExec` over a `UnionExec` of staging and Parquet sources. +//! DataFusion starts every union input at once, so old Parquet files are opened +//! and decoded before the TopK has learned a useful threshold. +//! +//! [`ProgressiveTopKRule`] replaces such a TopK with [`ProgressiveTopKExec`], +//! which runs the sources ("units") in best-bound order and stops once the +//! remaining units provably cannot contribute: +//! +//! * A unit's bound is taken only from `Precision::Exact` min/max column +//! statistics of a file scan (table level, or per file when every +//! `PartitionedFile` carries statistics). Row order inside files is never +//! trusted. Everything else (memory staging, staging files, sources without +//! exact statistics, scans with a pushed-down `limit`) is *unbounded* and is +//! always executed. +//! * After at least `fetch` rows are held, the `fetch`-th row's primary key is +//! the threshold `t`. A unit is prunable when, for `DESC`, its exact +//! `max < t` (for `ASC`, `min > t`), and, under `NULLS FIRST`, it provably +//! holds no `NULL` keys. Ties never prune, so secondary sort keys stay exact. +//! More rows can only move the `fetch`-th row earlier in the sort order, so a +//! threshold learned from completed units is final-safe even while other +//! (unbounded) units still run; the query itself only finishes once every +//! unbounded unit has completed. +//! * Each unit is reduced with DataFusion's own TopK (`SortExec` with `fetch`), +//! and the per-unit results are merged into at most `fetch` rows. Held rows +//! and merge buffers are reserved in the query's memory pool. +//! * Every unit counts its output partitions against one shared budget of +//! `target_partitions` running partitions. Unbounded units start first; +//! bounded units start in best-bound order once the unbounded units finish +//! or have run for [`OVERLAP_DELAY`] (so slow unbounded work does not +//! serialize sparse queries), ramping 1, 2, then the full budget. +//! * Each execution drives its own fresh copy of the scans' TopK dynamic filter +//! (pushed down by DataFusion for the original `SortExec`) from the global +//! threshold, so in-flight scans keep pruning row groups, and marks it +//! complete when the execution ends. +//! +//! Dropping the output stream aborts every running unit task. + +use std::cmp::Ordering; +use std::collections::{HashMap, HashSet, VecDeque}; +use std::fmt; +use std::sync::Arc; +use std::time::Duration; + +use datafusion::arrow::array::Array; +use datafusion::arrow::compute::{concat_batches, lexsort_to_indices, take_record_batch}; +use datafusion::arrow::datatypes::{DataType, SchemaRef}; +use datafusion::arrow::record_batch::RecordBatch; +use datafusion::common::config::ConfigOptions; +use datafusion::common::runtime::JoinSet; +use datafusion::common::stats::Precision; +use datafusion::common::tree_node::{Transformed, TreeNode, TreeNodeRecursion}; +use datafusion::common::{ColumnStatistics, DataFusionError, Result, ScalarValue, Statistics}; +use datafusion::datasource::listing::PartitionedFile; +use datafusion::datasource::physical_plan::{ + FileGroup, FileScanConfig, FileScanConfigBuilder, ParquetSource, +}; +use datafusion::datasource::source::DataSourceExec; +use datafusion::execution::TaskContext; +use datafusion::execution::memory_pool::{MemoryConsumer, MemoryPool, MemoryReservation}; +use datafusion::logical_expr::Operator; +use datafusion::physical_expr::expressions::{ + BinaryExpr, Column, DynamicFilterPhysicalExpr, IsNotNullExpr, IsNullExpr, Literal, lit, +}; +use datafusion::physical_expr::{ + EquivalenceProperties, LexOrdering, PhysicalExpr, PhysicalSortExpr, split_conjunction, +}; +use datafusion::physical_optimizer::PhysicalOptimizerRule; +use datafusion::physical_plan::coalesce_partitions::CoalescePartitionsExec; +use datafusion::physical_plan::coop::CooperativeExec; +use datafusion::physical_plan::execution_plan::{Boundedness, CardinalityEffect, EmissionType}; +use datafusion::physical_plan::filter::FilterExec; +use datafusion::physical_plan::metrics::{ExecutionPlanMetricsSet, MetricBuilder, MetricsSet}; +use datafusion::physical_plan::projection::ProjectionExec; +use datafusion::physical_plan::repartition::RepartitionExec; +use datafusion::physical_plan::sorts::sort::SortExec; +use datafusion::physical_plan::sorts::sort_preserving_merge::SortPreservingMergeExec; +use datafusion::physical_plan::stream::RecordBatchStreamAdapter; +use datafusion::physical_plan::union::UnionExec; +use datafusion::physical_plan::{ + DisplayAs, DisplayFormatType, ExecutionPlan, ExecutionPlanProperties, Partitioning, + PlanProperties, SendableRecordBatchStream, replace_children_if_necessary, +}; +use futures::{StreamExt, TryStreamExt}; + +/// 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. +pub(crate) const MAX_PROGRESSIVE_FETCH: usize = 1_000; + +/// How long unbounded units run alone before bounded units may use the spare +/// partition budget. Fast unbounded units (memory staging) usually fill the +/// limit within this window and prune every bounded unit unopened. +pub(crate) const OVERLAP_DELAY: Duration = Duration::from_millis(100); + +/// Replaces bounded TopK sorts over multi-source scans with +/// [`ProgressiveTopKExec`] when at least one source has a certified bound. +#[derive(Debug, Default)] +pub struct ProgressiveTopKRule; + +impl PhysicalOptimizerRule for ProgressiveTopKRule { + fn optimize( + &self, + plan: Arc, + config: &ConfigOptions, + ) -> Result> { + let max_concurrency = config.execution.target_partitions.max(1); + plan.transform_down(|node| { + Ok(match rewrite_topk(&node, max_concurrency)? { + Some(rewritten) => Transformed::new(rewritten, true, TreeNodeRecursion::Jump), + None => Transformed::no(node), + }) + }) + .map(|transformed| transformed.data) + } + + fn name(&self) -> &str { + "progressive_certified_topk" + } + + fn schema_check(&self) -> bool { + true + } +} + +/// Matches `SortPreservingMergeExec(fetch) -> SortExec(fetch, preserve_partitioning)` +/// or a single-partition `SortExec(fetch)`. +fn rewrite_topk( + node: &Arc, + max_concurrency: usize, +) -> Result>> { + let (sort, fetch) = if let Some(merge) = node.downcast_ref::() { + let Some(fetch) = merge.fetch() else { + return Ok(None); + }; + let Some(sort) = merge.input().downcast_ref::() else { + return Ok(None); + }; + if sort.fetch().is_none_or(|sort_fetch| sort_fetch < fetch) || sort.expr() != merge.expr() { + return Ok(None); + } + (sort, fetch) + } else if let Some(sort) = node.downcast_ref::() { + let Some(fetch) = sort.fetch() else { + return Ok(None); + }; + if sort.preserve_partitioning() && sort.input().output_partitioning().partition_count() > 1 + { + return Ok(None); + } + (sort, fetch) + } else { + return Ok(None); + }; + if fetch == 0 || fetch > MAX_PROGRESSIVE_FETCH { + return Ok(None); + } + let input = sort.input(); + if input.boundedness().is_unbounded() { + return Ok(None); + } + let schema = input.schema(); + for sort_expr in sort.expr().iter() { + if !lexsort_supported(&sort_expr.expr.data_type(&schema)?) { + return Ok(None); + } + } + if PrimaryKey::try_new(sort.expr(), &schema)?.is_none() { + return Ok(None); + } + let Some(sources) = distribute_over_union(input)? else { + return Ok(None); + }; + let dynamic_filter = sort + .dynamic_expressions_produced() + .into_iter() + .find(|expr| expr.downcast_ref::().is_some()); + let exec = ProgressiveTopKExec::try_new( + sort.expr().clone(), + fetch, + schema, + sources, + dynamic_filter, + max_concurrency, + )?; + if exec.units.len() < 2 || exec.bounded_units() == 0 || !exec.has_prunable_unit() { + return Ok(None); + } + Ok(Some(Arc::new(exec))) +} + +/// Types `lexsort_to_indices` sorts with the same semantics as DataFusion's +/// row-format TopK. +fn lexsort_supported(data_type: &DataType) -> bool { + data_type.is_primitive() + || matches!( + data_type, + DataType::Boolean + | DataType::Utf8 + | DataType::LargeUtf8 + | DataType::Utf8View + | DataType::Binary + | DataType::LargeBinary + | DataType::BinaryView + ) +} + +/// Types whose Parquet/manifest min/max statistics are total-order bounds that +/// `ScalarValue` compares exactly as Arrow sorts them. Floating point is +/// excluded: footer statistics omit `NaN`, which sorts greatest. +fn bound_supported(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::Decimal32(_, _) + | DataType::Decimal64(_, _) + | DataType::Decimal128(_, _) + | DataType::Decimal256(_, _) + | DataType::Date32 + | DataType::Date64 + | DataType::Time32(_) + | DataType::Time64(_) + | DataType::Timestamp(_, _) + | DataType::Duration(_) + | DataType::Utf8 + | DataType::LargeUtf8 + | DataType::Utf8View + ) +} + +/// The primary (first) sort key, which must be a plain column. +#[derive(Debug, Clone, Copy)] +struct PrimaryKey { + index: usize, + descending: bool, + nulls_first: bool, +} + +impl PrimaryKey { + fn try_new(expr: &LexOrdering, schema: &SchemaRef) -> Result> { + let first = expr.first(); + let Some(column) = first.expr.downcast_ref::() else { + return Ok(None); + }; + if column.index() >= schema.fields().len() + || schema.field(column.index()).name() != column.name() + || !bound_supported(schema.field(column.index()).data_type()) + { + return Ok(None); + } + Ok(Some(Self { + index: column.index(), + descending: first.options.descending, + nulls_first: first.options.nulls_first, + })) + } +} + +/// Operators that pass each input row through unchanged (or drop it) and whose +/// output partitioning is irrelevant once every partition is drained. +fn is_repartitioning(node: &Arc) -> bool { + (node.is::() || node.is::()) && node.fetch().is_none() +} + +fn is_row_preserving(node: &Arc) -> bool { + (node.is::() || node.is::() || node.is::()) + && node.fetch().is_none() +} + +/// Splits `input` into per-source plans: the row-preserving chain above a +/// `UnionExec` is re-applied on top of each union input. Repartitioning nodes +/// are dropped since the progressive executor drains every partition. +fn distribute_over_union( + input: &Arc, +) -> Result>>> { + let mut chain = Vec::new(); + let mut node = Arc::clone(input); + let leaves = loop { + if let Some(union) = node.downcast_ref::() { + let mut leaves = Vec::new(); + flatten_union(union, &mut leaves); + break leaves; + } + if is_repartitioning(&node) { + node = Arc::clone(node.children()[0]); + } else if is_row_preserving(&node) { + chain.push(Arc::clone(&node)); + node = Arc::clone(node.children()[0]); + } else { + // A single source: worthwhile only when it splits per file. + break vec![node]; + } + }; + let expected = input.schema(); + let mut sources = Vec::with_capacity(leaves.len()); + for leaf in leaves { + let mut plan = leaf; + for op in chain.iter().rev() { + plan = replace_children_if_necessary(Arc::clone(op), vec![plan])?; + } + let schema = plan.schema(); + if schema.fields().len() != expected.fields().len() + || schema + .fields() + .iter() + .zip(expected.fields().iter()) + .any(|(a, b)| a.data_type() != b.data_type()) + || plan.boundedness().is_unbounded() + { + return Ok(None); + } + sources.push(plan); + } + Ok(Some(sources)) +} + +fn flatten_union(union: &UnionExec, out: &mut Vec>) { + for child in union.inputs() { + match child.downcast_ref::() { + Some(nested) => flatten_union(nested, out), + None => out.push(Arc::clone(child)), + } + } +} + +/// A certified bound on a unit's primary key: `max` for descending order, +/// `min` for ascending order. +#[derive(Debug, Clone)] +struct UnitBound { + value: ScalarValue, + /// The unit provably produces no `NULL` primary keys. + no_nulls: bool, +} + +/// One independently executed piece of the input. +#[derive(Debug, Clone)] +struct Unit { + plan: Arc, + bound: Option, +} + +/// The primary column traced from a source's top down to its file scan. +struct Traced { + /// Nodes from the source top down to and including the `DataSourceExec`. + path: Vec>, + /// Column index in the `DataSourceExec` output. + leaf_index: usize, + /// A filter on the path rejects rows whose key is `NULL`. + null_rejected: bool, +} + +fn trace_primary(source: &Arc, mut index: usize) -> Option { + let mut path = Vec::new(); + let mut null_rejected = false; + let mut node = Arc::clone(source); + loop { + path.push(Arc::clone(&node)); + if node.is::() { + return Some(Traced { + path, + leaf_index: index, + null_rejected, + }); + } + if let Some(filter) = node.downcast_ref::() { + if filter.fetch().is_some() { + return None; + } + if let Some(projection) = filter.projection() { + index = *projection.get(index)?; + } + let input_schema = filter.input().schema(); + let name = input_schema.fields().get(index)?.name().clone(); + null_rejected |= rejects_nulls(filter.predicate(), index, &name); + } else if let Some(projection) = node.downcast_ref::() { + let column = projection + .expr() + .get(index)? + .expr + .downcast_ref::()?; + index = column.index(); + } else if !(is_repartitioning(&node) || is_row_preserving(&node)) { + return None; + } + let child = Arc::clone(node.children().first()?); + node = child; + } +} + +/// Whether `predicate` evaluates to `NULL`/`false` whenever column `index` is +/// `NULL`, using only conjuncts of the form `col literal` or +/// `col IS NOT NULL`. +fn rejects_nulls(predicate: &Arc, index: usize, name: &str) -> bool { + let is_key = |expr: &Arc| { + expr.downcast_ref::() + .is_some_and(|column| column.index() == index && column.name() == name) + }; + let is_value = |expr: &Arc| { + expr.downcast_ref::() + .is_some_and(|literal| !literal.value().is_null()) + }; + split_conjunction(predicate).into_iter().any(|conjunct| { + if let Some(binary) = conjunct.downcast_ref::() { + matches!( + binary.op(), + Operator::Eq + | Operator::NotEq + | Operator::Lt + | Operator::LtEq + | Operator::Gt + | Operator::GtEq + ) && ((is_key(binary.left()) && is_value(binary.right())) + || (is_value(binary.left()) && is_key(binary.right()))) + } else if let Some(not_null) = conjunct.downcast_ref::() { + is_key(not_null.arg()) + } else { + false + } + }) +} + +/// Compares two bound/threshold values with Arrow's sort semantics, or `None` +/// when they are not comparable (different types, or a `NULL`). +fn compare_values(a: &ScalarValue, b: &ScalarValue) -> Option { + if a.is_null() || b.is_null() { + return None; + } + let as_str = |value: &ScalarValue| match value { + ScalarValue::Utf8(Some(s)) + | ScalarValue::LargeUtf8(Some(s)) + | ScalarValue::Utf8View(Some(s)) => Some(s.clone()), + _ => None, + }; + if let (Some(a), Some(b)) = (as_str(a), as_str(b)) { + return Some(a.as_bytes().cmp(b.as_bytes())); + } + if a.data_type() != b.data_type() || !bound_supported(&a.data_type()) { + return None; + } + a.partial_cmp(b) +} + +/// Whether a unit with `bound` provably holds no row that sorts before or ties +/// the current `fetch`-th row (whose primary key is `threshold`). +fn prunable(bound: &UnitBound, threshold: &ScalarValue, key: PrimaryKey) -> bool { + if threshold.is_null() { + // Every held row has a NULL key. Under NULLS FIRST only NULL keys can + // tie or win; under NULLS LAST every non-NULL key wins. + return key.nulls_first && bound.no_nulls; + } + if key.nulls_first && !bound.no_nulls { + return false; + } + match compare_values(&bound.value, threshold) { + Some(Ordering::Less) => key.descending, + Some(Ordering::Greater) => !key.descending, + _ => false, + } +} + +fn exact_bound(stats: Option<&ColumnStatistics>, key: PrimaryKey) -> Option { + let stats = stats?; + let value = if key.descending { + &stats.max_value + } else { + &stats.min_value + }; + match value { + Precision::Exact(value) if !value.is_null() => Some(value.clone()), + _ => None, + } +} + +fn exact_no_nulls(stats: Option<&ColumnStatistics>) -> bool { + stats.is_some_and(|stats| stats.null_count == Precision::Exact(0)) +} + +/// Rebuilds `path` (top to leaf) over a replacement leaf. +fn rebuild_path( + path: &[Arc], + leaf: Arc, +) -> Result> { + let mut plan = leaf; + for node in path.iter().rev().skip(1) { + 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 { + Some(range) => u64::try_from(range.end - range.start).unwrap_or(0), + None => file.object_meta.size, + } +} + +/// Spreads `pieces` over at most `groups` file groups with similar byte sizes +/// (largest piece first onto the lightest group). +fn balanced_groups(mut pieces: Vec, groups: usize) -> Vec { + let groups = groups.clamp(1, pieces.len().max(1)); + if groups == 1 { + return vec![FileGroup::new(pieces)]; + } + pieces.sort_by_key(|piece| std::cmp::Reverse(piece_size(piece))); + let mut buckets = vec![(0_u64, Vec::new()); groups]; + for piece in pieces { + let lightest = buckets + .iter_mut() + .min_by_key(|(bytes, _)| *bytes) + .expect("at least one group"); + lightest.0 += piece_size(&piece); + lightest.1.push(piece); + } + buckets + .into_iter() + .filter(|(_, files)| !files.is_empty()) + .map(|(_, files)| FileGroup::new(files)) + .collect() +} + +/// Splits a source into units, attaching certified bounds where available. +/// +/// Certified files become one unit each. Uncertified files of a split scan +/// stay together in one unit with at most `min(target_partitions, original +/// group count)` balanced file groups, so splitting never raises the scan's +/// partition count for files that cannot be pruned. +fn analyze_source( + source: &Arc, + key: PrimaryKey, + target_partitions: usize, +) -> Result> { + let unbounded = || { + vec![Unit { + plan: Arc::clone(source), + bound: None, + }] + }; + let Some(traced) = trace_primary(source, key.index) else { + return Ok(unbounded()); + }; + let leaf = traced.path.last().expect("path ends at the scan"); + let exec = leaf + .downcast_ref::() + .expect("trace ends at DataSourceExec"); + let Some(config) = exec.data_source().downcast_ref::() else { + return Ok(unbounded()); + }; + let output_schema = leaf.schema(); + let Some(output_field) = output_schema.fields().get(traced.leaf_index) else { + return Ok(unbounded()); + }; + let table_schema = Arc::clone(config.file_source().table_schema().table_schema()); + let table_index = match config.file_source().projection() { + Some(projection) => { + let Some(column) = projection + .iter() + .nth(traced.leaf_index) + .and_then(|projected| projected.expr.downcast_ref::()) + else { + return Ok(unbounded()); + }; + column.index() + } + None => traced.leaf_index, + }; + let Some(table_field) = table_schema.fields().get(table_index) else { + return Ok(unbounded()); + }; + if !bound_supported(table_field.data_type()) { + return Ok(unbounded()); + } + + // NULL keys are impossible when the scan's schema forbids them, a filter + // above the scan rejects them, or the Parquet scan enforces a NULL-rejecting + // row filter (`pushdown_filters`), as Parseable relies on for `Exact` + // time-range filters. + let scan_rejects_nulls = config + .file_source() + .downcast_ref::() + .is_some_and(|parquet| parquet.table_parquet_options().global.pushdown_filters) + && config + .file_source() + .filter() + .is_some_and(|predicate| rejects_nulls(&predicate, table_index, table_field.name())); + let path_no_nulls = traced.null_rejected || scan_rejects_nulls || !output_field.is_nullable(); + + // Per-file units, when the files carry their own statistics. A scan with a + // pushed-down `limit` stays whole: every per-file copy would apply the + // limit again and return up to `units * limit` rows. + let mut locations: Vec<(String, Vec)> = Vec::new(); + let mut positions = HashMap::new(); + if config.limit.is_none() && config.output_partitioning.is_none() { + for file in config.file_groups.iter().flat_map(|group| group.iter()) { + let location = file.object_meta.location.to_string(); + let position = *positions.entry(location.clone()).or_insert_with(|| { + locations.push((location, Vec::new())); + locations.len() - 1 + }); + locations[position].1.push(file.clone()); + } + } + let file_bound = |pieces: &[PartitionedFile]| -> Option { + let stats = pieces.first()?.statistics.as_ref()?; + let value = exact_bound(stats.column_statistics.get(table_index), key)?; + // Every byte-range piece of a file must carry the same certificate. + let mut no_nulls = true; + for piece in pieces { + let column = piece + .statistics + .as_ref()? + .column_statistics + .get(table_index); + if exact_bound(column, key).as_ref() != Some(&value) { + return None; + } + // The NULL certificate must hold for every piece, not just the + // first one. + no_nulls &= exact_no_nulls(column); + } + Some(UnitBound { + value, + no_nulls: path_no_nulls || no_nulls, + }) + }; + let split = locations.len() >= 2 + && locations + .iter() + .any(|(_, pieces)| file_bound(pieces).is_some()); + if split { + // One template without files, cloned per unit: cloning `config` itself + // would copy every file of the scan for every unit (quadratic). + let mut template = config.clone(); + template.file_groups = Vec::new(); + let file_unit = |groups: Vec, stats: Statistics| -> Result<_> { + let scan = FileScanConfigBuilder::from(template.clone()) + .with_file_groups(groups) + .with_statistics(stats) + .build(); + let leaf: Arc = + Arc::new(exec.clone().with_data_source(Arc::new(scan))); + rebuild_path(&traced.path, leaf) + }; + let original_groups = config.file_groups.len().max(1); + let mut units = Vec::new(); + let mut uncertified = Vec::new(); + for (_, pieces) in locations { + match file_bound(&pieces) { + Some(bound) => { + let stats = pieces[0] + .statistics + .as_deref() + .cloned() + .unwrap_or_else(|| Statistics::new_unknown(&table_schema)); + let groups = pieces + .into_iter() + .map(|piece| FileGroup::new(vec![piece])) + .collect(); + units.push(Unit { + plan: file_unit(groups, stats)?, + bound: Some(bound), + }); + } + None => uncertified.extend(pieces), + } + } + if !uncertified.is_empty() { + let groups = + balanced_groups(uncertified, target_partitions.max(1).min(original_groups)); + units.push(Unit { + plan: file_unit(groups, Statistics::new_unknown(&table_schema))?, + bound: None, + }); + } + return Ok(units); + } + + // One unit for the whole scan. `FileScanConfig::statistics` marks every + // statistic inexact once a predicate is pushed into the scan, although a + // filter (or a limit) can only narrow the true range; read the unfiltered + // table statistics through a predicate-free copy of the scan. + let raw = FileScanConfigBuilder::from(config.clone()) + .with_source(Arc::new(ParquetSource::new( + config.file_source().table_schema().clone(), + ))) + .with_limit(None) + .build() + .statistics(); + let column = raw.column_statistics.get(table_index); + let bound = exact_bound(column, key).map(|value| UnitBound { + value, + no_nulls: path_no_nulls || exact_no_nulls(column), + }); + Ok(vec![Unit { + plan: Arc::clone(source), + bound, + }]) +} + +/// Executes a TopK in waves over sources ordered by certified bounds; see the +/// module documentation. +#[derive(Debug)] +pub struct ProgressiveTopKExec { + expr: LexOrdering, + fetch: usize, + key: PrimaryKey, + schema: SchemaRef, + sources: Vec>, + /// Unbounded units first (in source order), then bounded units best-first. + units: Arc>, + /// The `SortExec`'s TopK dynamic filter as pushed into the scans. It is a + /// template only: every execution rebinds the scans to a fresh copy. + dynamic_filter: Option>, + /// Shared budget of concurrently running unit partitions. + max_concurrency: usize, + overlap_delay: Duration, + cache: Arc, + metrics: ExecutionPlanMetricsSet, + /// The per-execution dynamic filters, for tests. + #[cfg(test)] + run_filters: Arc>>>, +} + +impl ProgressiveTopKExec { + fn try_new( + expr: LexOrdering, + fetch: usize, + schema: SchemaRef, + sources: Vec>, + dynamic_filter: Option>, + max_concurrency: usize, + ) -> Result { + let key = PrimaryKey::try_new(&expr, &schema)?; + let mut unbounded = Vec::new(); + let mut bounded = Vec::new(); + for source in &sources { + let units = match key { + Some(key) => analyze_source(source, key, max_concurrency)?, + None => vec![Unit { + plan: Arc::clone(source), + bound: None, + }], + }; + for unit in units { + if unit.bound.is_some() { + bounded.push(unit); + } else { + unbounded.push(unit); + } + } + } + // Keep only bounds comparable with each other so the ordering is total. + let reference = bounded + .first() + .and_then(|unit: &Unit| unit.bound.as_ref()) + .map(|bound| bound.value.clone()); + if let Some(reference) = reference { + for unit in &mut bounded { + let comparable = unit + .bound + .as_ref() + .is_some_and(|bound| compare_values(&bound.value, &reference).is_some()); + if !comparable { + unit.bound = None; + } + } + } + let (still_bounded, demoted): (Vec<_>, Vec<_>) = + bounded.into_iter().partition(|unit| unit.bound.is_some()); + unbounded.extend(demoted); + let mut bounded = still_bounded; + let descending = key.is_some_and(|key| key.descending); + bounded.sort_by(|a, b| { + let (a, b) = ( + &a.bound.as_ref().expect("bounded").value, + &b.bound.as_ref().expect("bounded").value, + ); + let ordering = compare_values(a, b).unwrap_or(Ordering::Equal); + if descending { + ordering.reverse() + } else { + ordering + } + }); + unbounded.extend(bounded); + let units = unbounded; + + let eq_properties = EquivalenceProperties::new_with_orderings( + Arc::clone(&schema), + [expr.iter().cloned().collect::>()], + ); + let cache = PlanProperties::new( + eq_properties, + Partitioning::UnknownPartitioning(1), + EmissionType::Final, + Boundedness::Bounded, + ); + Ok(Self { + expr, + fetch, + key: key.unwrap_or(PrimaryKey { + index: 0, + descending: false, + nulls_first: false, + }), + schema, + sources, + units: Arc::new(units), + dynamic_filter, + max_concurrency: max_concurrency.max(1), + overlap_delay: OVERLAP_DELAY, + cache: Arc::new(cache), + metrics: ExecutionPlanMetricsSet::new(), + #[cfg(test)] + run_filters: Arc::default(), + }) + } + + fn bounded_units(&self) -> usize { + self.units + .iter() + .filter(|unit| unit.bound.is_some()) + .count() + } + + /// Returns `true` when at least one bounded unit can theoretically be + /// pruned by an earlier unit. When every unit is guaranteed to be scanned + /// (e.g. all files share identical `min`/`max` sort bounds with no + /// unbounded source, or `NULLS FIRST` has no NULL-free bounded unit), + /// progressive waves add overhead with zero pruning upside. + fn has_prunable_unit(&self) -> bool { + let mut has_unbounded = false; + let mut best_bound: Option<&ScalarValue> = None; + let mut any_earlier_nullable = false; + for unit in self.units.iter() { + match &unit.bound { + None => { + has_unbounded = true; + } + Some(bound) => { + if self.key.nulls_first && !bound.no_nulls { + any_earlier_nullable = true; + if best_bound.is_none() { + best_bound = Some(&bound.value); + } + continue; + } + if has_unbounded + || (self.key.nulls_first && any_earlier_nullable) + || best_bound.is_some_and(|best| prunable(bound, best, self.key)) + { + return true; + } + if best_bound.is_none() { + best_bound = Some(&bound.value); + } + } + } + } + false + } +} + +impl DisplayAs for ProgressiveTopKExec { + fn fmt_as(&self, t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result { + let expr = self + .expr + .iter() + .map(|e| e.to_string()) + .collect::>() + .join(", "); + match t { + DisplayFormatType::Default | DisplayFormatType::Verbose => write!( + f, + "ProgressiveTopKExec: fetch={}, expr=[{}], units={}, bounded_units={}", + self.fetch, + expr, + self.units.len(), + self.bounded_units() + ), + DisplayFormatType::TreeRender => { + writeln!(f, "fetch={}", self.fetch)?; + writeln!(f, "expr=[{expr}]")?; + write!( + f, + "units={} bounded={}", + self.units.len(), + self.bounded_units() + ) + } + } + } +} + +impl ExecutionPlan for ProgressiveTopKExec { + fn name(&self) -> &str { + "ProgressiveTopKExec" + } + + fn properties(&self) -> &Arc { + &self.cache + } + + fn children(&self) -> Vec<&Arc> { + self.sources.iter().collect() + } + + fn apply_expressions( + &self, + f: &mut dyn FnMut(&Arc) -> Result, + ) -> Result { + let mut recursion = TreeNodeRecursion::Continue; + for expr in self + .expr + .iter() + .map(|sort_expr| &sort_expr.expr) + .chain(self.dynamic_filter.iter()) + { + recursion = f(expr)?; + if recursion == TreeNodeRecursion::Stop { + break; + } + } + Ok(recursion) + } + + fn dynamic_expressions_produced(&self) -> Vec> { + self.dynamic_filter.iter().cloned().collect() + } + + fn maintains_input_order(&self) -> Vec { + vec![false; self.sources.len()] + } + + fn benefits_from_input_partitioning(&self) -> Vec { + vec![false; self.sources.len()] + } + + fn with_new_children( + self: Arc, + children: Vec>, + ) -> Result> { + let mut exec = Self::try_new( + self.expr.clone(), + self.fetch, + Arc::clone(&self.schema), + children, + self.dynamic_filter.clone(), + self.max_concurrency, + )?; + exec.overlap_delay = self.overlap_delay; + Ok(Arc::new(exec)) + } + + fn execute( + &self, + partition: usize, + context: Arc, + ) -> Result { + if partition != 0 { + return Err(DataFusionError::Internal(format!( + "ProgressiveTopKExec has a single partition, got {partition}" + ))); + } + // Every execution gets its own dynamic filter, bound into the units' + // scans as they launch, so concurrent or repeated executions never + // share (or reset) each other's thresholds. + let filter = self + .dynamic_filter + .as_ref() + .filter(|filter| filter.downcast_ref::().is_some()) + .and_then(|template| { + let template_id = template.expression_id()?; + let children = template.children().into_iter().cloned().collect(); + Some(RunFilter { + template_id, + filter: Arc::new(DynamicFilterPhysicalExpr::new(children, lit(true))), + }) + }); + #[cfg(test)] + if let Some(filter) = &filter { + self.run_filters + .lock() + .expect("run filters") + .push(Arc::clone(&filter.filter)); + } + let run = ProgressiveRun { + expr: self.expr.clone(), + fetch: self.fetch, + key: self.key, + schema: Arc::clone(&self.schema), + units: Arc::clone(&self.units), + filter: CompleteOnDrop(filter), + max_concurrency: self.max_concurrency, + overlap_delay: self.overlap_delay, + executed: MetricBuilder::new(&self.metrics).counter("units_executed", partition), + pruned: MetricBuilder::new(&self.metrics).counter("units_pruned", partition), + }; + let batch_size = context.session_config().batch_size().max(1); + let stream = futures::stream::once(run.run(context)) + .map_ok(move |batch| { + let chunks = (0..batch.num_rows()) + .step_by(batch_size) + .map( + |offset| Ok(batch.slice(offset, batch_size.min(batch.num_rows() - offset))), + ) + .collect::>(); + futures::stream::iter(chunks) + }) + .try_flatten(); + Ok(Box::pin(RecordBatchStreamAdapter::new( + Arc::clone(&self.schema), + stream, + ))) + } + + fn metrics(&self) -> Option { + Some(self.metrics.clone_inner()) + } + + fn fetch(&self) -> Option { + Some(self.fetch) + } + + fn cardinality_effect(&self) -> CardinalityEffect { + CardinalityEffect::LowerEqual + } +} + +/// One execution's dynamic filter. The scans' copies of the template filter +/// (`template_id`) are rebound to `filter` when a unit launches. +struct RunFilter { + template_id: u64, + filter: Arc, +} + +/// Marks the execution's dynamic filter complete however the run ends: +/// finished, failed or dropped. +struct CompleteOnDrop(Option); + +impl Drop for CompleteOnDrop { + fn drop(&mut self) { + if let Some(run) = &self.0 { + run.filter.mark_complete(); + } + } +} + +/// Rebinds every copy of the template dynamic filter in `predicate` to the +/// execution's filter, keeping each copy's column remapping. +fn rebind_predicate( + predicate: &Arc, + filter: &RunFilter, +) -> Result>> { + let fresh: Arc = Arc::clone(&filter.filter) 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)) + } else { + Ok(Transformed::no(node)) + } + }) +} + +/// Rebinds a Parquet scan's copy of the template dynamic filter. +fn rebind_scan( + node: &Arc, + filter: &RunFilter, +) -> Result>> { + let Some(exec) = node.downcast_ref::() else { + return Ok(None); + }; + let Some(config) = exec.data_source().downcast_ref::() else { + return Ok(None); + }; + let Some(parquet) = config.file_source().downcast_ref::() else { + return Ok(None); + }; + let Some(predicate) = config.file_source().filter() else { + return Ok(None); + }; + let rebound = rebind_predicate(&predicate, filter)?; + if !rebound.transformed { + return Ok(None); + } + let scan = FileScanConfigBuilder::from(config.clone()) + .with_source(Arc::new(parquet.with_predicate(rebound.data))) + .build(); + Ok(Some(Arc::new( + exec.clone().with_data_source(Arc::new(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. +fn prepare_unit( + plan: &Arc, + filter: Option<&RunFilter>, +) -> Result> { + Arc::clone(plan) + .transform_up(|node| { + let node = node.reset_state()?; + let node = match filter { + Some(filter) => rebind_scan(&node, filter)?.unwrap_or(node), + None => node, + }; + Ok(Transformed::yes(node)) + }) + .map(|transformed| transformed.data) +} + +/// At most `fetch` sorted rows, with their memory (and the merge buffers +/// needed to combine them with a new batch) reserved in the query's pool. +struct HeldRows { + schema: SchemaRef, + expr: LexOrdering, + fetch: usize, + rows: Option, + reservation: MemoryReservation, +} + +impl HeldRows { + fn new( + name: &str, + schema: SchemaRef, + expr: LexOrdering, + fetch: usize, + pool: &Arc, + ) -> Self { + Self { + schema, + expr, + fetch, + rows: None, + reservation: MemoryConsumer::new(name).register(pool), + } + } + + fn rows(&self) -> Option<&RecordBatch> { + self.rows.as_ref() + } + + fn push(&mut self, batch: RecordBatch) -> Result<()> { + if batch.num_rows() == 0 { + return Ok(()); + } + let held = self + .rows + .as_ref() + .map_or(0, RecordBatch::get_array_memory_size); + // Both inputs plus their concatenation, which the merge sorts. + self.reservation + .try_resize(2 * (held + batch.get_array_memory_size()))?; + let merged = merge_topk( + &self.schema, + &self.expr, + self.fetch, + self.rows.take(), + batch, + )?; + self.reservation + .try_resize(merged.get_array_memory_size())?; + self.rows = Some(merged); + Ok(()) + } + + fn into_rows(self) -> Option { + self.rows + } +} + +struct ProgressiveRun { + expr: LexOrdering, + fetch: usize, + key: PrimaryKey, + schema: SchemaRef, + units: Arc>, + filter: CompleteOnDrop, + max_concurrency: usize, + overlap_delay: Duration, + executed: datafusion::physical_plan::metrics::Count, + pruned: datafusion::physical_plan::metrics::Count, +} + +impl ProgressiveRun { + fn publish_filter(&self, predicate: Arc) -> Result<()> { + if let Some(run) = &self.filter.0 { + run.filter.update(predicate)?; + } + Ok(()) + } + + /// A sound scan filter for rows that may still enter the TopK: rows tying + /// the threshold are kept so secondary keys decide. + fn threshold_filter(&self, threshold: &ScalarValue) -> Option> { + let column = Arc::clone(&self.expr.first().expr); + let is_null = || Arc::new(IsNullExpr::new(Arc::clone(&column))) as Arc; + if threshold.is_null() { + return self.key.nulls_first.then(is_null); + } + let op = if self.key.descending { + Operator::GtEq + } else { + Operator::LtEq + }; + let compare = Arc::new(BinaryExpr::new( + Arc::clone(&column), + op, + lit(threshold.clone()), + )) as Arc; + Some(if self.key.nulls_first { + Arc::new(BinaryExpr::new(is_null(), Operator::Or, compare)) + } else { + compare + }) + } + + fn bound(&self, index: usize) -> &UnitBound { + self.units[index].bound.as_ref().expect("bounded unit") + } + + /// Whether bounded unit `a` has a strictly better bound than `b`. + fn better(&self, a: usize, b: usize) -> bool { + match compare_values(&self.bound(a).value, &self.bound(b).value) { + Some(Ordering::Greater) => self.key.descending, + Some(Ordering::Less) => !self.key.descending, + _ => false, + } + } + + fn partitions(&self, index: usize) -> usize { + self.units[index] + .plan + .output_partitioning() + .partition_count() + .max(1) + } + + async fn run(self, context: Arc) -> Result { + let mut unbounded = VecDeque::new(); + // Pending bounded units, best bound first. Under NULLS FIRST a unit + // without a no-NULL certificate can never be pruned, so those wait in + // `pinned`: the prunable units of `pending` then always form a suffix + // (bounds only get worse towards the back), removed from the back. + let mut pending = VecDeque::new(); + let mut pinned = VecDeque::new(); + for (index, unit) in self.units.iter().enumerate() { + match &unit.bound { + None => unbounded.push_back(index), + Some(bound) if self.key.nulls_first && !bound.no_nulls => pinned.push_back(index), + Some(_) => pending.push_back(index), + } + } + let mut tasks = JoinSet::new(); + let mut running: HashMap = + HashMap::new(); + let mut aborted = HashSet::new(); + let mut running_unbounded = 0; + // Every unit counts its partitions against one budget of + // `max_concurrency` (`target_partitions`) running partitions. A unit + // larger than the budget runs alone. Bounded units additionally ramp + // 1, 2, then the full budget, so a query that cannot prune still + // reaches full parallelism after two completions. + let mut running_partitions = 0; + let mut bounded_partitions = 0; + let mut ramp = 1; + // Bounded units may overlap still-running unbounded units once those + // have had `overlap_delay` to fill the limit on their own. + let overlap_at = tokio::time::Instant::now() + self.overlap_delay; + let mut overlap = self.overlap_delay.is_zero(); + let mut held = HeldRows::new( + "ProgressiveTopKExec", + Arc::clone(&self.schema), + self.expr.clone(), + self.fetch, + context.memory_pool(), + ); + let mut threshold: Option = None; + + let spawn = |tasks: &mut JoinSet>>, + running: &mut HashMap<_, _>, + index: usize| + -> Result<()> { + self.executed.add(1); + let plan = prepare_unit(&self.units[index].plan, self.filter.0.as_ref())?; + let handle = tasks.spawn(run_unit( + plan, + self.expr.clone(), + self.fetch, + Arc::clone(&self.schema), + Arc::clone(&context), + )); + running.insert(handle.id(), (index, handle)); + Ok(()) + }; + + loop { + // Unbounded units can never be pruned and their rows may prune + // every bounded unit, so they take the budget first. + while let Some(&index) = unbounded.front() { + let needed = self.partitions(index); + if running_partitions > 0 && running_partitions + needed > self.max_concurrency { + break; + } + unbounded.pop_front(); + spawn(&mut tasks, &mut running, index)?; + running_unbounded += 1; + running_partitions += needed; + } + if unbounded.is_empty() && (running_unbounded == 0 || overlap) { + loop { + let from_pinned = match (pending.front(), pinned.front()) { + (Some(&best), Some(&other)) => self.better(other, best), + (None, Some(_)) => true, + (Some(_), None) => false, + (None, None) => break, + }; + let index = if from_pinned { pinned[0] } else { pending[0] }; + let needed = self.partitions(index); + let fits = running_partitions == 0 + || (running_partitions + needed <= self.max_concurrency + && (bounded_partitions == 0 || bounded_partitions + needed <= ramp)); + if !fits { + break; + } + if from_pinned { + pinned.pop_front(); + } else { + pending.pop_front(); + } + spawn(&mut tasks, &mut running, index)?; + running_partitions += needed; + bounded_partitions += needed; + } + } + let await_overlap = !overlap + && running_unbounded > 0 + && unbounded.is_empty() + && !(pending.is_empty() && pinned.is_empty()); + let joined = if await_overlap { + tokio::select! { + joined = tasks.join_next_with_id() => joined, + () = tokio::time::sleep_until(overlap_at) => { + overlap = true; + continue; + } + } + } else { + tasks.join_next_with_id().await + }; + let Some(joined) = joined else { + if !(unbounded.is_empty() && pending.is_empty() && pinned.is_empty()) { + return Err(DataFusionError::Internal( + "progressive TopK stopped with pending units".to_owned(), + )); + } + break; + }; + let (id, result) = match joined { + Ok(joined) => joined, + Err(error) => { + if error.is_panic() { + std::panic::resume_unwind(error.into_panic()); + } + if aborted.remove(&error.id()) { + continue; + } + return Err(DataFusionError::Execution(format!( + "progressive TopK unit failed: {error}" + ))); + } + }; + aborted.remove(&id); + let Some((index, _)) = running.remove(&id) else { + continue; + }; + let needed = self.partitions(index); + running_partitions -= needed; + if self.units[index].bound.is_some() { + bounded_partitions -= needed; + ramp = if ramp < 2 { + 2 + } else { + self.max_concurrency.max(2) + }; + } else { + running_unbounded -= 1; + } + if let Some(batch) = result? { + held.push(batch)?; + } + + let Some(rows) = held.rows().filter(|rows| rows.num_rows() >= self.fetch) else { + continue; + }; + let column = self.expr.first().evaluate_to_sort_column(rows)?.values; + let current = ScalarValue::try_from_array(&column, self.fetch - 1)?; + // Pending units were already checked against an unchanged + // threshold. The threshold only ever moves earlier in the sort + // order (more rows can only improve the `fetch`-th row), so a unit + // prunable now stays prunable whatever the running units return. + if threshold.as_ref() == Some(¤t) { + continue; + } + if let Some(predicate) = self.threshold_filter(¤t) { + self.publish_filter(predicate)?; + } + while let Some(&index) = pending.back() { + if !prunable(self.bound(index), ¤t, self.key) { + break; + } + pending.pop_back(); + self.pruned.add(1); + } + let prunable_running = running + .iter() + .filter(|(_, (index, _))| { + self.units[*index] + .bound + .as_ref() + .is_some_and(|bound| prunable(bound, ¤t, self.key)) + }) + .map(|(id, _)| *id) + .collect::>(); + for id in prunable_running { + if let Some((index, handle)) = running.remove(&id) { + handle.abort(); + aborted.insert(id); + let needed = self.partitions(index); + running_partitions -= needed; + bounded_partitions -= needed; + self.pruned.add(1); + } + } + threshold = Some(current); + } + Ok(held + .into_rows() + .unwrap_or_else(|| RecordBatch::new_empty(Arc::clone(&self.schema)))) + } +} + +/// Runs DataFusion's TopK over one unit and returns at most `fetch` sorted rows. +async fn run_unit( + plan: Arc, + expr: LexOrdering, + fetch: usize, + schema: SchemaRef, + context: Arc, +) -> Result> { + 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 top: Arc = if partitions > 1 { + Arc::new(CoalescePartitionsExec::new(sort)) + } else { + sort + }; + let mut stream = top.execute(0, Arc::clone(&context))?; + let mut held = HeldRows::new( + "ProgressiveTopKExec[unit]", + schema, + expr, + fetch, + context.memory_pool(), + ); + while let Some(batch) = stream.next().await { + held.push(batch?)?; + } + Ok(held.into_rows()) +} + +/// Keeps the best `fetch` rows of `held` and `batch`, sorted. +fn merge_topk( + schema: &SchemaRef, + expr: &LexOrdering, + fetch: usize, + held: Option, + batch: RecordBatch, +) -> Result { + let batch = RecordBatch::try_new(Arc::clone(schema), batch.columns().to_vec())?; + let combined = match held { + Some(held) if batch.num_rows() == 0 => return Ok(held), + Some(held) => concat_batches(schema, [&held, &batch])?, + None => batch, + }; + if combined.num_rows() == 0 { + return Ok(combined); + } + let columns = expr + .iter() + .map(|sort_expr| sort_expr.evaluate_to_sort_column(&combined)) + .collect::>>()?; + let indices = lexsort_to_indices(&columns, Some(fetch))?; + debug_assert!(indices.null_count() == 0); + Ok(take_record_batch(&combined, &indices)?) +} + +#[cfg(test)] +mod tests { + use super::*; + + use std::future::Future; + use std::pin::Pin; + use std::sync::Mutex; + use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering}; + use std::task::{Context, Poll}; + + use datafusion::arrow::array::{ArrayRef, Int64Array, StringArray, TimestampMillisecondArray}; + use datafusion::arrow::compute::SortOptions; + use datafusion::arrow::datatypes::{Field, Schema, TimeUnit}; + use datafusion::arrow::util::pretty::pretty_format_batches; + use datafusion::catalog::{Session, TableProvider}; + use datafusion::common::ToDFSchema; + use datafusion::config::TableParquetOptions; + use datafusion::datasource::memory::MemorySourceConfig; + use datafusion::datasource::physical_plan::parquet::{ + DefaultParquetFileReaderFactory, ParquetFileReaderFactory, + }; + use datafusion::execution::SessionStateBuilder; + use datafusion::execution::memory_pool::GreedyMemoryPool; + use datafusion::execution::object_store::ObjectStoreUrl; + use datafusion::execution::runtime_env::RuntimeEnvBuilder; + use datafusion::logical_expr::{ + BinaryExpr as LogicalBinary, TableProviderFilterPushDown, TableType, + }; + use datafusion::parquet::arrow::ArrowWriter; + use datafusion::parquet::arrow::async_reader::AsyncFileReader; + use datafusion::physical_plan::filter::FilterExecBuilder; + use datafusion::physical_plan::{RecordBatchStream, collect, displayable}; + use datafusion::prelude::{Expr, SessionConfig, SessionContext}; + use object_store::local::LocalFileSystem; + use tempfile::TempDir; + + const BASE: i64 = 1_700_000_000_000; + const SPAN: i64 = 10_000; + + type Opens = Arc>>; + + fn schema() -> SchemaRef { + Arc::new(Schema::new(vec![ + Field::new("ts", DataType::Timestamp(TimeUnit::Millisecond, None), true), + Field::new("id", DataType::Int64, false), + Field::new("level", DataType::Utf8, true), + Field::new("val", DataType::Int64, true), + ])) + } + + #[derive(Clone, Debug)] + struct Row { + ts: Option, + id: i64, + level: Option<&'static str>, + val: Option, + } + + struct Rng(u64); + + impl Rng { + fn next(&mut self) -> u64 { + self.0 = self + .0 + .wrapping_mul(6_364_136_223_846_793_005) + .wrapping_add(1_442_695_040_888_963_407); + self.0 >> 33 + } + } + + /// Unsorted rows with coarse timestamps (many ties) in `[lo, hi)`. + fn rows( + rng: &mut Rng, + next_id: &mut i64, + count: usize, + lo: i64, + hi: i64, + null_every: Option, + ) -> Vec { + (0..count) + .map(|i| { + let r = rng.next(); + let ts = lo + ((r % ((hi - lo) as u64)) as i64 / 7) * 7; + let level = match r % 10 { + 0..=3 => Some("error"), + 4..=6 => Some("info"), + 7 => None, + 8 => Some("warn"), + _ if r.is_multiple_of(17) => Some("rare"), + _ => Some("debug"), + }; + let val = (!r.is_multiple_of(5)).then_some((r % 100) as i64); + let id = *next_id; + *next_id += 1; + Row { + ts: if null_every.is_some_and(|n| i % n == 0) { + None + } else { + Some(ts) + }, + id, + level, + val, + } + }) + .collect() + } + + fn batch(rows: &[Row]) -> RecordBatch { + let columns: Vec = vec![ + Arc::new(TimestampMillisecondArray::from( + rows.iter().map(|r| r.ts).collect::>(), + )), + Arc::new(Int64Array::from( + rows.iter().map(|r| r.id).collect::>(), + )), + Arc::new(StringArray::from( + rows.iter().map(|r| r.level).collect::>(), + )), + Arc::new(Int64Array::from( + rows.iter().map(|r| r.val).collect::>(), + )), + ]; + RecordBatch::try_new(schema(), columns).unwrap() + } + + #[derive(Clone, Debug)] + struct TestFile { + path: String, + size: u64, + stats: Statistics, + } + + fn column_stats(values: Vec>, exact_null_count: bool) -> ColumnStatistics { + let nulls = values.iter().filter(|v| v.is_none()).count(); + let present = values.into_iter().flatten().collect::>(); + let mut stats = ColumnStatistics::new_unknown(); + let min = present.iter().min_by(|a, b| a.partial_cmp(b).unwrap()); + let max = present.iter().max_by(|a, b| a.partial_cmp(b).unwrap()); + if let (Some(min), Some(max)) = (min, max) { + stats.min_value = Precision::Exact(min.clone()); + stats.max_value = Precision::Exact(max.clone()); + } + if exact_null_count { + stats.null_count = Precision::Exact(nulls); + } + stats + } + + /// Exact per-file statistics for every column. + fn file_stats(rows: &[Row], exact_null_count: bool) -> Statistics { + let ts = rows + .iter() + .map(|r| { + r.ts.map(|v| ScalarValue::TimestampMillisecond(Some(v), None)) + }) + .collect(); + let id = rows + .iter() + .map(|r| Some(ScalarValue::Int64(Some(r.id)))) + .collect(); + let level = rows + .iter() + .map(|r| r.level.map(|v| ScalarValue::Utf8(Some(v.to_owned())))) + .collect(); + let val = rows + .iter() + .map(|r| r.val.map(|v| ScalarValue::Int64(Some(v)))) + .collect(); + Statistics { + num_rows: Precision::Exact(rows.len()), + total_byte_size: Precision::Absent, + column_statistics: vec![ + column_stats(ts, exact_null_count), + column_stats(id, exact_null_count), + column_stats(level, exact_null_count), + column_stats(val, exact_null_count), + ], + } + } + + /// Table-level statistics merged the way Parseable merges manifest + /// statistics: exact min/max, unknown null count. + fn merged_stats(files: &[TestFile]) -> Statistics { + let mut stats = Statistics::new_unknown(&schema()); + stats.num_rows = Precision::Exact( + files + .iter() + .filter_map(|f| f.stats.num_rows.get_value().copied()) + .sum(), + ); + for (column, merged) in stats.column_statistics.iter_mut().enumerate() { + let pick = + |ordering: Ordering, value: fn(&ColumnStatistics) -> &Precision| { + files + .iter() + .filter_map(|f| match value(&f.stats.column_statistics[column]) { + Precision::Exact(v) => Some(v.clone()), + _ => None, + }) + .reduce(|a, b| { + if b.partial_cmp(&a) == Some(ordering) { + b + } else { + a + } + }) + }; + if let (Some(min), Some(max)) = ( + pick(Ordering::Less, |c| &c.min_value), + pick(Ordering::Greater, |c| &c.max_value), + ) { + merged.min_value = Precision::Exact(min); + merged.max_value = Precision::Exact(max); + } + } + stats + } + + struct Dataset { + _dir: TempDir, + staging: Vec, + segments: Vec>, + } + + #[derive(Clone, Copy, Debug)] + struct Layout { + staging: bool, + per_file_stats: bool, + exact_ts_filters: bool, + } + + impl Default for Layout { + fn default() -> Self { + Self { + staging: true, + per_file_stats: true, + exact_ts_filters: false, + } + } + } + + fn write_file(dir: &TempDir, name: &str, rows: &[Row], exact_null_count: bool) -> TestFile { + let path = dir.path().join(name); + let mut writer = + ArrowWriter::try_new(std::fs::File::create(&path).unwrap(), schema(), None).unwrap(); + // Several small batches so files hold more than one row group page. + for chunk in rows.chunks(37) { + writer.write(&batch(chunk)).unwrap(); + } + writer.close().unwrap(); + TestFile { + path: path.to_string_lossy().into_owned(), + size: std::fs::metadata(&path).unwrap().len(), + stats: file_stats(rows, exact_null_count), + } + } + + /// Staging (newest), then six disjoint, progressively older files and one + /// sparse file overlapping every range. Files listed in `null_files` hold + /// NULL timestamps. + fn dataset( + seed: u64, + exact_null_counts: bool, + null_files: &[usize], + staging_rows: usize, + ) -> Dataset { + let dir = TempDir::new().unwrap(); + let mut rng = Rng(seed); + let mut next_id = 0; + let staging_rows = rows( + &mut rng, + &mut next_id, + staging_rows, + BASE, + BASE + SPAN, + None, + ); + let staging = staging_rows.chunks(50).map(batch).collect::>(); + let mut files = Vec::new(); + for i in 0..6_i64 { + let null_every = null_files.contains(&(i as usize)).then_some(9); + let file_rows = rows( + &mut rng, + &mut next_id, + 150, + BASE - (i + 1) * SPAN, + BASE - i * SPAN, + null_every, + ); + files.push(write_file( + &dir, + &format!("f{i}.parquet"), + &file_rows, + exact_null_counts, + )); + } + let wide = rows(&mut rng, &mut next_id, 40, BASE - 6 * SPAN, BASE, None); + files.push(write_file(&dir, "wide.parquet", &wide, exact_null_counts)); + let remote = files.split_off(2); + Dataset { + _dir: dir, + staging, + segments: vec![files, remote], + } + } + + #[derive(Debug)] + struct CountingFactory { + inner: DefaultParquetFileReaderFactory, + opens: Opens, + } + + impl ParquetFileReaderFactory for CountingFactory { + fn create_reader( + &self, + partition: usize, + file: PartitionedFile, + hint: Option, + metrics: &ExecutionPlanMetricsSet, + ) -> Result> { + let name = file + .object_meta + .location + .filename() + .unwrap_or_default() + .to_owned(); + *self.opens.lock().unwrap().entry(name).or_default() += 1; + self.inner.create_reader(partition, file, hint, metrics) + } + } + + #[derive(Debug)] + struct TestTable { + staging: Vec, + segments: Vec>, + layout: Layout, + opens: Opens, + } + + impl TestTable { + fn new(data: &Dataset, layout: Layout) -> Arc { + Arc::new(Self { + staging: if layout.staging { + data.staging.clone() + } else { + Vec::new() + }, + segments: data.segments.clone(), + layout, + opens: Arc::default(), + }) + } + + fn opened(&self, name: &str) -> usize { + self.opens.lock().unwrap().get(name).copied().unwrap_or(0) + } + + fn total_opens(&self) -> usize { + self.opens.lock().unwrap().values().sum() + } + + fn is_exact(&self, filter: &Expr) -> bool { + self.layout.exact_ts_filters + && matches!( + filter, + Expr::BinaryExpr(LogicalBinary { left, op, right }) + if matches!(left.as_ref(), Expr::Column(c) if c.name == "ts") + && matches!(right.as_ref(), Expr::Literal(..)) + && matches!(op, Operator::Gt | Operator::GtEq | Operator::Lt | Operator::LtEq) + ) + } + } + + #[async_trait::async_trait] + impl TableProvider for TestTable { + fn schema(&self) -> SchemaRef { + schema() + } + + fn table_type(&self) -> TableType { + TableType::Base + } + + async fn scan( + &self, + state: &dyn Session, + projection: Option<&Vec>, + filters: &[Expr], + _limit: Option, + ) -> Result> { + let schema = schema(); + let exact = filters + .iter() + .filter(|filter| self.is_exact(filter)) + .cloned() + .reduce(Expr::and) + .map(|expr| state.create_physical_expr(expr, &schema.clone().to_dfschema()?)) + .transpose()?; + let mut children: Vec> = Vec::new(); + if !self.staging.is_empty() { + let memory: Arc = MemorySourceConfig::try_new_exec( + std::slice::from_ref(&self.staging), + schema.clone(), + None, + )?; + let memory: Arc = match &exact { + Some(predicate) => Arc::new( + FilterExecBuilder::new(Arc::clone(predicate), memory) + .apply_projection(projection.cloned())? + .build()?, + ), + None => match projection { + Some(projection) => MemorySourceConfig::try_new_exec( + std::slice::from_ref(&self.staging), + schema.clone(), + Some(projection.clone()), + )?, + None => memory, + }, + }; + children.push(memory); + } + let target = state.config_options().execution.target_partitions; + let options = TableParquetOptions { + global: state.config_options().execution.parquet.clone(), + ..Default::default() + }; + for segment in &self.segments { + let mut groups = vec![Vec::new(); target.min(segment.len()).max(1)]; + for (i, file) in segment.iter().enumerate() { + let mut partitioned = PartitionedFile::new(file.path.clone(), file.size); + if self.layout.per_file_stats { + partitioned = partitioned.with_statistics(Arc::new(file.stats.clone())); + } + let n = groups.len(); + groups[i % n].push(partitioned); + } + let mut source = ParquetSource::new(schema.clone()) + .with_table_parquet_options(options.clone()) + .with_parquet_file_reader_factory(Arc::new(CountingFactory { + inner: DefaultParquetFileReaderFactory::new(Arc::new( + LocalFileSystem::new(), + )), + opens: Arc::clone(&self.opens), + })); + if let Some(predicate) = &exact { + source = source.with_predicate(Arc::clone(predicate)); + } + let mut builder = FileScanConfigBuilder::new( + ObjectStoreUrl::local_filesystem(), + Arc::new(source), + ) + .with_file_groups(groups.into_iter().map(FileGroup::new).collect()) + .with_statistics(merged_stats(segment)); + if let Some(projection) = projection { + builder = builder.with_projection_indices(Some(projection.clone()))?; + } + children.push(DataSourceExec::from_data_source(builder.build())); + } + Ok(if children.len() == 1 { + children.pop().unwrap() + } else { + UnionExec::try_new(children)? + }) + } + + fn supports_filters_pushdown( + &self, + filters: &[&Expr], + ) -> Result> { + Ok(filters + .iter() + .map(|filter| { + if self.is_exact(filter) { + TableProviderFilterPushDown::Exact + } else { + TableProviderFilterPushDown::Inexact + } + }) + .collect()) + } + } + + /// Mirrors the options `Query::create_session_state` sets. + fn session_config(target_partitions: usize) -> SessionConfig { + let mut config = SessionConfig::default() + .with_parquet_pruning(true) + .with_prefer_existing_sort(true) + .with_collect_statistics(true) + .with_batch_size(64) + .with_target_partitions(target_partitions); + let options = config.options_mut(); + options.execution.parquet.pushdown_filters = true; + options.execution.parquet.reorder_filters = true; + options.execution.parquet.binary_as_string = true; + options.execution.parquet.enable_page_index = true; + options.execution.parquet.schema_force_view_types = true; + options.execution.enable_file_stream_work_stealing = true; + options.optimizer.repartition_file_scans = true; + options.optimizer.enable_dynamic_filter_pushdown = true; + options.optimizer.enable_topk_aggregation = true; + options.optimizer.enable_topk_repartition = true; + options.optimizer.enable_sort_pushdown = true; + config + } + + fn context(table: Arc, progressive: bool) -> SessionContext { + let mut builder = SessionStateBuilder::new() + .with_default_features() + .with_config(session_config(4)); + if progressive { + builder = builder.with_physical_optimizer_rule(Arc::new(ProgressiveTopKRule)); + } + let ctx = SessionContext::new_with_state(builder.build()); + ctx.register_table("t", table).unwrap(); + ctx + } + + async fn physical_plan(ctx: &SessionContext, sql: &str) -> String { + let df = ctx.sql(sql).await.unwrap(); + let plan = df.create_physical_plan().await.unwrap(); + displayable(plan.as_ref()).indent(true).to_string() + } + + async fn run(ctx: &SessionContext, sql: &str) -> String { + let batches = ctx.sql(sql).await.unwrap().collect().await.unwrap(); + pretty_format_batches(&batches).unwrap().to_string() + } + + /// Runs `sql` on stock DataFusion and with the progressive rule; returns + /// both results, the progressive plan and both tables. + async fn differential( + data: &Dataset, + layout: Layout, + sql: &str, + ) -> (String, String, String, Arc, Arc) { + let stock_table = TestTable::new(data, layout); + let progressive_table = TestTable::new(data, layout); + let stock = run(&context(Arc::clone(&stock_table), false), sql).await; + let ctx = context(Arc::clone(&progressive_table), true); + let plan = physical_plan(&ctx, sql).await; + let progressive = run(&ctx, sql).await; + assert_eq!( + stock, progressive, + "progressive TopK differs from DataFusion for {sql} with {layout:?}\nplan:\n{plan}" + ); + (stock, progressive, plan, stock_table, progressive_table) + } + + fn ts_literal(offset: i64) -> String { + format!("to_timestamp_millis({})", BASE + offset) + } + + const ORDERS: [&str; 6] = [ + "ts DESC NULLS LAST", + "ts DESC NULLS FIRST", + "ts ASC NULLS LAST", + "ts ASC NULLS FIRST", + "ts DESC", + "ts ASC", + ]; + + fn queries(order: &str) -> Vec { + vec![ + format!("SELECT * FROM t ORDER BY {order}, id ASC LIMIT 25"), + format!( + "SELECT * FROM t WHERE level = 'error' ORDER BY {order}, id DESC LIMIT 40 OFFSET 5" + ), + format!("SELECT id, ts FROM t WHERE level = 'rare' ORDER BY {order}, id LIMIT 50"), + format!("SELECT * FROM t WHERE level = 'fatal' ORDER BY {order} LIMIT 10"), + format!("SELECT ts FROM t ORDER BY {order} LIMIT 30"), + format!("SELECT ts FROM t WHERE val > 10 ORDER BY {order} LIMIT 7"), + format!( + "SELECT * FROM t WHERE ts >= {} AND ts < {} ORDER BY {order}, id LIMIT 20", + ts_literal(-3 * SPAN), + ts_literal(SPAN / 2) + ), + format!( + "SELECT id AS ident, ts AS t2, level FROM t ORDER BY t2 {}, ident LIMIT 15", + &order[3..] + ), + format!("SELECT * FROM t ORDER BY {order}, val DESC NULLS LAST, id ASC LIMIT 33"), + format!("SELECT ts, id FROM t ORDER BY {order}, id LIMIT 10 OFFSET 5"), + format!("SELECT ts, id FROM t ORDER BY {order}, id LIMIT 1000"), + // Other columns and types: Int64 and Utf8 (read back as Utf8View). + format!("SELECT * FROM t ORDER BY id {}, ts LIMIT 12", &order[3..]), + format!( + "SELECT * FROM t WHERE val < 50 ORDER BY level {}, id DESC LIMIT 9", + &order[3..] + ), + format!( + "SELECT val, id FROM t ORDER BY val {}, id LIMIT 21", + &order[3..] + ), + ] + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn prints_and_rewrites_real_datafusion_plan() { + let data = dataset(7, true, &[], 120); + let sql = "SELECT * FROM t WHERE level = 'error' ORDER BY ts DESC LIMIT 100"; + let stock = physical_plan( + &context(TestTable::new(&data, Layout::default()), false), + sql, + ) + .await; + let progressive = physical_plan( + &context(TestTable::new(&data, Layout::default()), true), + sql, + ) + .await; + println!("stock plan:\n{stock}\nprogressive plan:\n{progressive}"); + assert!(stock.contains("SortExec: TopK(fetch=100)"), "{stock}"); + assert!(stock.contains("UnionExec"), "{stock}"); + assert!( + progressive.starts_with("ProgressiveTopKExec: fetch=100, expr=[ts@0 DESC]"), + "{progressive}" + ); + assert!(!progressive.contains("UnionExec"), "{progressive}"); + assert!(!progressive.contains("SortExec"), "{progressive}"); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn matches_datafusion_for_every_order_query_and_layout() { + let layouts = [ + Layout::default(), + Layout { + per_file_stats: false, + ..Layout::default() + }, + Layout { + staging: false, + ..Layout::default() + }, + Layout { + staging: false, + per_file_stats: false, + ..Layout::default() + }, + Layout { + exact_ts_filters: true, + ..Layout::default() + }, + Layout { + staging: false, + per_file_stats: false, + exact_ts_filters: true, + }, + ]; + let mut rewritten = 0; + let mut checked = 0; + for (seed, null_files) in [(11_u64, &[][..]), (23, &[1, 4][..])] { + for exact_null_counts in [true, false] { + let data = dataset(seed, exact_null_counts, null_files, 120); + for layout in layouts { + for order in ORDERS { + for sql in queries(order) { + let (_, _, plan, _, _) = differential(&data, layout, &sql).await; + checked += 1; + rewritten += usize::from(plan.contains("ProgressiveTopKExec")); + } + } + } + } + } + // The comparison must exercise the progressive operator, not just the + // stock plan. + assert!( + rewritten * 2 > checked, + "only {rewritten} of {checked} plans rewritten" + ); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn older_files_are_never_opened_when_newer_files_fill_the_limit() { + let data = dataset(3, true, &[], 0); + let layout = Layout { + staging: false, + ..Layout::default() + }; + for (order, kept) in [ + ("ts DESC NULLS LAST", "f0.parquet"), + ("ts DESC NULLS FIRST", "f0.parquet"), + ("ts ASC NULLS LAST", "f5.parquet"), + ("ts ASC NULLS FIRST", "f5.parquet"), + ] { + let sql = format!("SELECT * FROM t ORDER BY {order}, id LIMIT 50"); + let (_, _, plan, stock, progressive) = differential(&data, layout, &sql).await; + assert!(plan.contains("bounded_units=7"), "{plan}"); + assert!(stock.total_opens() >= 7, "stock opens every file"); + assert!(progressive.opened(kept) > 0, "{order}"); + // The sparse overlapping file is executed (its range covers the + // threshold); every other disjoint file is pruned unopened. + for i in 0..6 { + let name = format!("f{i}.parquet"); + if name != kept { + assert_eq!(progressive.opened(&name), 0, "{order}: {name} was opened"); + } + } + } + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn staging_satisfying_the_limit_skips_table_level_parquet_sources() { + // Parseable today: no per-file statistics, one bounded source per scan. + let data = dataset(5, false, &[], 400); + let layout = Layout { + per_file_stats: false, + ..Layout::default() + }; + let sql = "SELECT * FROM t ORDER BY ts DESC NULLS LAST, id LIMIT 100"; + let (_, _, plan, stock, progressive) = differential(&data, layout, sql).await; + assert!(plan.contains("units=3, bounded_units=2"), "{plan}"); + assert!(stock.total_opens() > 0); + assert_eq!(progressive.total_opens(), 0, "{:?}", progressive.opens); + + // Default `DESC` is `NULLS FIRST`: the unknown null count blocks + // pruning unless a filter rejects NULL timestamps. + let sql = "SELECT * FROM t ORDER BY ts DESC, id LIMIT 100"; + let (_, _, _, _, progressive) = differential(&data, layout, sql).await; + assert!(progressive.total_opens() > 0, "NULLS FIRST must not prune"); + let sql = format!( + "SELECT * FROM t WHERE ts > {} ORDER BY ts DESC, id LIMIT 100", + ts_literal(-100 * SPAN) + ); + let (_, _, _, _, progressive) = differential(&data, layout, &sql).await; + assert_eq!( + progressive.total_opens(), + 0, + "a NULL-rejecting filter certifies no NULLs" + ); + let exact = Layout { + exact_ts_filters: true, + ..layout + }; + let (_, _, plan, _, progressive) = differential(&data, exact, &sql).await; + // The time filter is enforced inside the Parquet scans only. + assert_eq!(plan.matches("FilterExec").count(), 1, "{plan}"); + assert_eq!(progressive.total_opens(), 0, "{plan}"); + + // Too few staging rows: the newest Parquet source must be read. + let sql = "SELECT * FROM t WHERE level = 'warn' ORDER BY ts DESC NULLS LAST, id LIMIT 100"; + let (_, _, _, _, progressive) = differential(&data, layout, sql).await; + assert!(progressive.total_opens() > 0); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn nulls_first_never_prunes_a_source_that_may_hold_nulls() { + // f4 (old) holds NULL timestamps; its null count is exact. + let data = dataset(9, true, &[4], 0); + let layout = Layout { + staging: false, + ..Layout::default() + }; + for order in ["ts DESC NULLS FIRST", "ts ASC NULLS FIRST"] { + let sql = format!("SELECT * FROM t ORDER BY {order}, id LIMIT 20"); + let (result, _, _, _, progressive) = differential(&data, layout, &sql).await; + assert!( + result + .lines() + .nth(3) + .unwrap() + .starts_with("| |"), + "{result}" + ); + // DataFusion may open a file more than once (metadata, then data); + // only whether it was opened at all matters here. + assert!(progressive.opened("f4.parquet") > 0, "{order}"); + // NULL-free files outside the threshold are still pruned. + assert_eq!(progressive.opened("f2.parquet"), 0, "{order}"); + } + // Unknown null counts: nothing can be pruned under NULLS FIRST. + let data = dataset(9, false, &[4], 0); + let sql = "SELECT * FROM t ORDER BY ts DESC NULLS FIRST, id LIMIT 20"; + let (_, _, _, _, progressive) = differential(&data, layout, sql).await; + for i in 0..6 { + assert!(progressive.opened(&format!("f{i}.parquet")) > 0); + } + // NULLS LAST ignores NULLs, so the same files prune. + let sql = "SELECT * FROM t ORDER BY ts DESC NULLS LAST, id LIMIT 20"; + let (_, _, _, _, progressive) = differential(&data, layout, sql).await; + assert_eq!(progressive.opened("f4.parquet"), 0); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn ties_at_the_threshold_keep_sources_with_equal_bounds() { + let dir = TempDir::new().unwrap(); + let tie = BASE; + let make = |ids: std::ops::Range, ts: &dyn Fn(i64) -> i64| { + ids.map(|id| Row { + ts: Some(ts(id)), + id, + level: Some("error"), + val: Some(id % 3), + }) + .collect::>() + }; + // `a` alone fills every limit with tied rows. `b` reaches the same + // value (equal bound: never prunable), `c` is strictly older. + let a = write_file(&dir, "a.parquet", &make(0..50, &|_| tie), true); + let b = write_file( + &dir, + "b.parquet", + &make(100..160, &|id| if id % 2 == 0 { tie } else { tie - id }), + true, + ); + let c = write_file( + &dir, + "c.parquet", + &make(200..260, &|id| tie - 10_000 - id), + true, + ); + let data = Dataset { + _dir: dir, + staging: Vec::new(), + segments: vec![vec![a, b, c]], + }; + let layout = Layout { + staging: false, + ..Layout::default() + }; + for (sql, from_b) in [ + ("SELECT * FROM t ORDER BY ts DESC, id ASC LIMIT 40", false), + // Higher ids win the tie, so `b`'s tied rows must be returned. + ("SELECT * FROM t ORDER BY ts DESC, id DESC LIMIT 40", true), + ( + "SELECT * FROM t ORDER BY ts DESC NULLS LAST, val DESC, id DESC LIMIT 45", + true, + ), + ("SELECT ts FROM t ORDER BY ts DESC LIMIT 30", false), + ] { + let (result, _, _, _, progressive) = differential(&data, layout, sql).await; + assert!( + progressive.opened("b.parquet") > 0, + "{sql}: equal bound must run" + ); + assert_eq!(progressive.opened("c.parquet"), 0, "{sql}"); + assert_eq!(result.contains("| 158 "), from_b, "{sql}\n{result}"); + } + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn sparse_queries_run_every_unit() { + let data = dataset(13, true, &[], 60); + for sql in [ + "SELECT * FROM t WHERE level = 'fatal' ORDER BY ts DESC LIMIT 10", + "SELECT * FROM t WHERE level = 'rare' ORDER BY ts ASC NULLS LAST, id LIMIT 500", + ] { + let (_, _, _, stock, progressive) = differential(&data, Layout::default(), sql).await; + assert_eq!(progressive.total_opens(), stock.total_opens(), "{sql}"); + } + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn offset_explain_and_metrics() { + let data = dataset(17, true, &[], 120); + let ctx = context(TestTable::new(&data, Layout::default()), true); + let sql = "SELECT id, ts FROM t WHERE level = 'info' ORDER BY ts DESC NULLS LAST LIMIT 10 OFFSET 5"; + let explain = run(&ctx, &format!("EXPLAIN {sql}")).await; + assert!( + explain.contains("GlobalLimitExec: skip=5, fetch=10"), + "{explain}" + ); + assert!( + explain.contains("ProgressiveTopKExec: fetch=15, expr=[ts@1 DESC NULLS LAST]"), + "{explain}" + ); + let tree = run(&ctx, &format!("EXPLAIN FORMAT TREE {sql}")).await; + assert!(tree.contains("ProgressiveTopKExec"), "{tree}"); + let analyze = run(&ctx, &format!("EXPLAIN ANALYZE {sql}")).await; + assert!(analyze.contains("units_pruned="), "{analyze}"); + differential(&data, Layout::default(), sql).await; + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn unsupported_shapes_keep_the_stock_plan() { + let data = dataset(19, true, &[], 50); + let ctx = context(TestTable::new(&data, Layout::default()), true); + for sql in [ + "SELECT * FROM t ORDER BY ts DESC, id", + "SELECT * FROM t ORDER BY ts DESC, id LIMIT 1001", + "SELECT * FROM t ORDER BY val + 1 DESC, id LIMIT 10", + "SELECT * FROM t ORDER BY CAST(val AS DOUBLE) DESC, id LIMIT 10", + ] { + let plan = physical_plan(&ctx, sql).await; + assert!(!plan.contains("ProgressiveTopKExec"), "{sql}\n{plan}"); + differential(&data, Layout::default(), sql).await; + } + // When there is no unbounded live source and every Parquet file shares + // the exact same sort bound (e.g. `level` has min='debug', max='warn' + // in every file), pruning is impossible so the stock parallel SortExec + // must be kept. + let closed_layout = Layout { + staging: false, + ..Layout::default() + }; + let closed_ctx = context(TestTable::new(&data, closed_layout), true); + for sql in [ + "SELECT * FROM t ORDER BY level ASC, id LIMIT 10", + "SELECT * FROM t ORDER BY level DESC, id LIMIT 10", + ] { + let plan = physical_plan(&closed_ctx, sql).await; + assert!(!plan.contains("ProgressiveTopKExec"), "{sql}\n{plan}"); + differential(&data, closed_layout, sql).await; + } + // Under `NULLS FIRST` (including `DESC` default), when every bounded + // unit may hold NULLs, no unit can be pruned even with an unbounded + // staging source, so the stock parallel SortExec must be kept. + for sql in [ + "SELECT * FROM t ORDER BY level DESC, id LIMIT 10", + "SELECT * FROM t ORDER BY val ASC NULLS FIRST, id LIMIT 10", + ] { + let plan = physical_plan(&ctx, sql).await; + assert!(!plan.contains("ProgressiveTopKExec"), "{sql}\n{plan}"); + differential(&data, Layout::default(), sql).await; + } + // Any plain column of a supported type with exact statistics and a + // potentially prunable unit is eligible. + for sql in [ + "SELECT * FROM t ORDER BY ts DESC NULLS LAST, id LIMIT 1000", + "SELECT * FROM t ORDER BY id ASC LIMIT 10", + "SELECT * FROM t ORDER BY level DESC NULLS LAST, id LIMIT 10", + "SELECT * FROM t WHERE val IS NOT NULL ORDER BY val ASC NULLS FIRST, id LIMIT 10", + ] { + let plan = physical_plan(&ctx, sql).await; + assert!(plan.contains("ProgressiveTopKExec"), "{sql}\n{plan}"); + differential(&data, Layout::default(), sql).await; + } + // The smallest ids live in staging, so ordering by id prunes every file. + let sql = "SELECT * FROM t ORDER BY id ASC LIMIT 10"; + let (_, _, _, _, progressive) = differential(&data, Layout::default(), sql).await; + assert_eq!(progressive.total_opens(), 0); + } + + #[test] + fn prune_decisions_follow_direction_and_null_order() { + let ts = |v| ScalarValue::TimestampMillisecond(Some(v), None); + let key = |descending, nulls_first| PrimaryKey { + index: 0, + descending, + nulls_first, + }; + let bound = |v, no_nulls| UnitBound { + value: ts(v), + no_nulls, + }; + // DESC: prune only strictly below the threshold. + assert!(prunable(&bound(9, false), &ts(10), key(true, false))); + assert!(!prunable(&bound(10, false), &ts(10), key(true, false))); + assert!(!prunable(&bound(11, false), &ts(10), key(true, false))); + // ASC: prune only strictly above. + assert!(prunable(&bound(11, false), &ts(10), key(false, false))); + assert!(!prunable(&bound(10, false), &ts(10), key(false, false))); + // NULLS FIRST needs proof that the unit has no NULL keys. + assert!(!prunable(&bound(9, false), &ts(10), key(true, true))); + assert!(prunable(&bound(9, true), &ts(10), key(true, true))); + // A NULL threshold: under NULLS FIRST only NULL-free units prune, + // under NULLS LAST nothing prunes. + let null = ScalarValue::TimestampMillisecond(None, None); + assert!(prunable(&bound(100, true), &null, key(true, true))); + assert!(!prunable(&bound(100, false), &null, key(true, true))); + assert!(!prunable(&bound(1, true), &null, key(true, false))); + assert!(!prunable(&bound(1, true), &null, key(false, false))); + // Incomparable types never prune. + let other = UnitBound { + value: ScalarValue::Int64(Some(1)), + no_nulls: true, + }; + assert!(!prunable(&other, &ts(10), key(true, false))); + // Strings compare across Utf8 representations. + let s = UnitBound { + value: ScalarValue::Utf8(Some("abc".into())), + no_nulls: true, + }; + assert!(prunable( + &s, + &ScalarValue::Utf8View(Some("abd".into())), + key(true, false) + )); + } + + #[test] + fn merge_keeps_the_best_fetch_rows() { + let expr = LexOrdering::new([PhysicalSortExpr::new( + Arc::new(Column::new("ts", 0)), + SortOptions { + descending: true, + nulls_first: true, + }, + )]) + .unwrap(); + let mut rng = Rng(1); + let mut id = 0; + let mut held = None; + let mut all = Vec::new(); + for _ in 0..10 { + let rows = rows(&mut rng, &mut id, 50, 0, 1_000, Some(13)); + all.extend(rows.clone()); + held = Some(merge_topk(&schema(), &expr, 17, held, batch(&rows)).unwrap()); + assert!(held.as_ref().unwrap().num_rows() <= 17); + } + let mut expected = all.iter().map(|r| r.ts).collect::>(); + expected.sort_by(|a, b| match (a, b) { + (None, None) => Ordering::Equal, + (None, _) => Ordering::Less, + (_, None) => Ordering::Greater, + (Some(a), Some(b)) => b.cmp(a), + }); + expected.truncate(17); + let held = held.unwrap(); + let got = held + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .iter() + .collect::>(); + assert_eq!(got, expected); + } + + /// A slow source: never produces a batch, or produces `release`'s batch + /// after its delay. Records starts and stream drops. + #[derive(Debug)] + struct PendingExec { + cache: Arc, + started: Arc, + dropped: Arc, + release: Option<(Duration, RecordBatch)>, + } + + struct PendingStream { + dropped: Arc, + release: Option<(Pin>, Option)>, + } + + impl futures::Stream for PendingStream { + type Item = Result; + + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + match &mut self.release { + None => Poll::Pending, + Some((sleep, batch)) => { + std::task::ready!(sleep.as_mut().poll(cx)); + Poll::Ready(batch.take().map(Ok)) + } + } + } + } + + impl RecordBatchStream for PendingStream { + fn schema(&self) -> SchemaRef { + schema() + } + } + + impl Drop for PendingStream { + fn drop(&mut self) { + self.dropped.fetch_add(1, AtomicOrdering::SeqCst); + } + } + + impl DisplayAs for PendingExec { + fn fmt_as(&self, _: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "PendingExec") + } + } + + impl ExecutionPlan for PendingExec { + fn name(&self) -> &str { + "PendingExec" + } + + fn properties(&self) -> &Arc { + &self.cache + } + + fn children(&self) -> Vec<&Arc> { + vec![] + } + + fn apply_expressions( + &self, + _: &mut dyn FnMut(&Arc) -> Result, + ) -> Result { + Ok(TreeNodeRecursion::Continue) + } + + fn with_new_children( + self: Arc, + _: Vec>, + ) -> Result> { + Ok(self) + } + + fn execute(&self, _: usize, _: Arc) -> Result { + self.started.fetch_add(1, AtomicOrdering::SeqCst); + Ok(Box::pin(PendingStream { + dropped: Arc::clone(&self.dropped), + release: self.release.as_ref().map(|(delay, batch)| { + (Box::pin(tokio::time::sleep(*delay)), Some(batch.clone())) + }), + })) + } + } + + fn pending_exec( + started: &Arc, + dropped: &Arc, + release: Option<(Duration, RecordBatch)>, + ) -> Arc { + Arc::new(PendingExec { + cache: Arc::new(PlanProperties::new( + EquivalenceProperties::new(schema()), + Partitioning::UnknownPartitioning(1), + EmissionType::Incremental, + Boundedness::Bounded, + )), + started: Arc::clone(started), + dropped: Arc::clone(dropped), + release, + }) + } + + fn ts_order(descending: bool, nulls_first: bool) -> LexOrdering { + LexOrdering::new([PhysicalSortExpr::new( + Arc::new(Column::new("ts", 0)), + SortOptions { + descending, + nulls_first, + }, + )]) + .unwrap() + } + + /// The stock `SortPreservingMergeExec -> SortExec -> UnionExec` TopK. + fn stock_topk( + inputs: Vec>, + expr: LexOrdering, + fetch: usize, + ) -> Arc { + let union = UnionExec::try_new(inputs).unwrap(); + let sort = Arc::new( + SortExec::new(expr.clone(), union) + .with_fetch(Some(fetch)) + .with_preserve_partitioning(true), + ); + Arc::new(SortPreservingMergeExec::new(expr, sort).with_fetch(Some(fetch))) + } + + async fn wait_for(counter: &AtomicUsize, expected: usize) { + for _ in 0..200 { + if counter.load(AtomicOrdering::SeqCst) == expected { + return; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + assert_eq!(counter.load(AtomicOrdering::SeqCst), expected); + } + + async fn parquet_scan(table: &Arc) -> Arc { + let ctx = context(Arc::clone(table), false); + table.scan(&ctx.state(), None, &[], None).await.unwrap() + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn bounded_units_overlap_a_slow_unbounded_unit_and_drop_cancels() { + let data = dataset(29, true, &[], 0); + let layout = Layout { + staging: false, + ..Layout::default() + }; + let table = TestTable::new(&data, layout); + let ctx = context(Arc::clone(&table), false); + let parquet = parquet_scan(&table).await; + let started = Arc::new(AtomicUsize::new(0)); + let dropped = Arc::new(AtomicUsize::new(0)); + let pending = pending_exec(&started, &dropped, None); + let merge = stock_topk(vec![pending, parquet], ts_order(true, false), 5); + let plan = ProgressiveTopKRule + .optimize(merge, ctx.state().config_options()) + .unwrap(); + assert!(plan.is::()); + let mut stream = plan.execute(0, ctx.task_ctx()).unwrap(); + let next = tokio::time::timeout(OVERLAP_DELAY * 6, stream.next()).await; + assert!(next.is_err(), "the pending unbounded unit blocks the TopK"); + assert_eq!(started.load(AtomicOrdering::SeqCst), 1); + // Bounded units used the spare budget while the unbounded unit ran, + // best bound first; the threshold they set pruned every older + // disjoint file unopened. + assert!(table.total_opens() > 0, "bounded units did not overlap"); + for i in 1..6 { + let name = format!("f{i}.parquet"); + assert_eq!(table.opened(&name), 0, "{name} was opened"); + } + drop(stream); + wait_for(&dropped, 1).await; + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn pruning_while_an_unbounded_unit_runs_matches_datafusion() { + let data = dataset(37, true, &[], 0); + let layout = Layout { + staging: false, + ..Layout::default() + }; + // The slow unit returns the newest row and NULL keys, which win under + // NULLS FIRST, after the bounded units have set a threshold. + let late = [ + Row { + ts: None, + id: 100_000, + level: Some("error"), + val: None, + }, + Row { + ts: Some(BASE + 5), + id: 100_001, + level: Some("info"), + val: Some(1), + }, + Row { + ts: None, + id: 100_002, + level: None, + val: Some(2), + }, + ]; + for (descending, nulls_first) in [(true, true), (true, false), (false, true)] { + // `id` breaks ties between the late NULL keys. + let expr = LexOrdering::new(ts_order(descending, nulls_first).iter().cloned().chain([ + PhysicalSortExpr::new(Arc::new(Column::new("id", 1)), SortOptions::default()), + ])) + .unwrap(); + let release = || Some((OVERLAP_DELAY * 4, batch(&late))); + let unused = Arc::new(AtomicUsize::new(0)); + let stock_table = TestTable::new(&data, layout); + let stock = stock_topk( + vec![ + pending_exec(&unused, &unused, release()), + parquet_scan(&stock_table).await, + ], + expr.clone(), + 6, + ); + let progressive_table = TestTable::new(&data, layout); + let ctx = context(Arc::clone(&progressive_table), false); + let plan = ProgressiveTopKRule + .optimize( + stock_topk( + vec![ + pending_exec(&unused, &unused, release()), + parquet_scan(&progressive_table).await, + ], + expr, + 6, + ), + ctx.state().config_options(), + ) + .unwrap(); + assert!(plan.is::()); + let format = + |batches: Vec| pretty_format_batches(&batches).unwrap().to_string(); + let expected = format(collect(stock, ctx.task_ctx()).await.unwrap()); + let got = format(collect(plan, ctx.task_ctx()).await.unwrap()); + assert_eq!( + expected, got, + "descending={descending} nulls_first={nulls_first}" + ); + if descending { + for i in 1..6 { + let name = format!("f{i}.parquet"); + assert_eq!(progressive_table.opened(&name), 0, "{name} was opened"); + } + } + } + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn unbounded_units_share_the_partition_budget() { + let data = dataset(41, true, &[], 0); + let table = TestTable::new( + &data, + Layout { + staging: false, + ..Layout::default() + }, + ); + let ctx = context(Arc::clone(&table), false); + let started = Arc::new(AtomicUsize::new(0)); + let dropped = Arc::new(AtomicUsize::new(0)); + let mut sources = (0..6) + .map(|_| pending_exec(&started, &dropped, None)) + .collect::>(); + sources.extend( + distribute_over_union(&parquet_scan(&table).await) + .unwrap() + .unwrap(), + ); + let exec = + ProgressiveTopKExec::try_new(ts_order(true, false), 5, schema(), sources, None, 4) + .unwrap(); + assert_eq!(exec.units.len(), 6 + 7); + assert_eq!(exec.bounded_units(), 7); + let mut stream = exec.execute(0, ctx.task_ctx()).unwrap(); + let next = tokio::time::timeout(OVERLAP_DELAY * 4, stream.next()).await; + assert!(next.is_err()); + assert_eq!( + started.load(AtomicOrdering::SeqCst), + 4, + "unbounded units must stay within `target_partitions`" + ); + assert_eq!( + table.total_opens(), + 0, + "no budget is left for bounded units" + ); + drop(stream); + wait_for(&dropped, 4).await; + } + + #[test] + fn held_rows_are_reserved_in_the_memory_pool() { + let mut rng = Rng(3); + let mut id = 0; + let rows = rows(&mut rng, &mut id, 300, 0, 10_000, None); + let pool: Arc = Arc::new(GreedyMemoryPool::new(64 << 20)); + let mut held = HeldRows::new( + "ProgressiveTopKExec", + schema(), + ts_order(true, false), + 50, + &pool, + ); + for chunk in rows.chunks(100) { + held.push(batch(chunk)).unwrap(); + assert_eq!( + pool.reserved(), + held.rows().unwrap().get_array_memory_size() + ); + } + assert_eq!(held.rows().unwrap().num_rows(), 50); + drop(held); + assert_eq!(pool.reserved(), 0); + + let tiny: Arc = Arc::new(GreedyMemoryPool::new(1024)); + let mut held = HeldRows::new( + "ProgressiveTopKExec", + schema(), + ts_order(true, false), + 50, + &tiny, + ); + let error = held.push(batch(&rows)).unwrap_err(); + assert!(error.to_string().contains("ProgressiveTopKExec"), "{error}"); + assert!(held.rows().is_none()); + assert_eq!(tiny.reserved(), 0); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn queries_run_within_the_session_memory_pool() { + let data = dataset(43, true, &[], 120); + let sql = "SELECT * FROM t ORDER BY ts DESC NULLS LAST, id LIMIT 200"; + let expected = run( + &context(TestTable::new(&data, Layout::default()), false), + sql, + ) + .await; + let with_pool = |pool: Arc| { + let runtime = RuntimeEnvBuilder::new() + .with_memory_pool(pool) + .build_arc() + .unwrap(); + let state = SessionStateBuilder::new() + .with_default_features() + .with_config(session_config(4)) + .with_runtime_env(runtime) + .with_physical_optimizer_rule(Arc::new(ProgressiveTopKRule)) + .build(); + let ctx = SessionContext::new_with_state(state); + ctx.register_table("t", TestTable::new(&data, Layout::default())) + .unwrap(); + ctx + }; + let pool: Arc = Arc::new(GreedyMemoryPool::new(256 << 20)); + let ctx = with_pool(Arc::clone(&pool)); + assert!( + physical_plan(&ctx, sql) + .await + .contains("ProgressiveTopKExec") + ); + assert_eq!(run(&ctx, sql).await, expected); + assert_eq!(pool.reserved(), 0, "every reservation is released"); + + let ctx = with_pool(Arc::new(GreedyMemoryPool::new(2048))); + let result = ctx.sql(sql).await.unwrap().collect().await; + let error = result.expect_err("a tiny pool must fail the TopK"); + assert!(error.to_string().contains("Resources exhausted"), "{error}"); + } + + fn ts(value: i64) -> ScalarValue { + ScalarValue::TimestampMillisecond(Some(value), None) + } + + fn ts_stats(min: i64, max: i64, nulls: usize) -> Statistics { + let mut stats = Statistics::new_unknown(&schema()); + let column = &mut stats.column_statistics[0]; + column.min_value = Precision::Exact(ts(min)); + column.max_value = Precision::Exact(ts(max)); + column.null_count = Precision::Exact(nulls); + stats + } + + fn fake_file(i: usize, stats: Option) -> PartitionedFile { + let file = PartitionedFile::new(format!("/fake/f{i}.parquet"), 1_000 + i as u64); + match stats { + Some(stats) => file.with_statistics(Arc::new(stats)), + None => file, + } + } + + /// A Parquet scan that is planned but never executed. + fn fake_scan( + groups: Vec>, + limit: Option, + ) -> Arc { + let config = FileScanConfigBuilder::new( + ObjectStoreUrl::local_filesystem(), + Arc::new(ParquetSource::new(schema())), + ) + .with_file_groups(groups.into_iter().map(FileGroup::new).collect()) + .with_limit(limit) + .build(); + DataSourceExec::from_data_source(config) + } + + fn round_robin(files: Vec, groups: usize) -> Vec> { + let mut out = vec![Vec::new(); groups]; + for (i, file) in files.into_iter().enumerate() { + out[i % groups].push(file); + } + out + } + + fn scan_config(plan: &Arc) -> &FileScanConfig { + plan.downcast_ref::() + .unwrap() + .data_source() + .downcast_ref::() + .unwrap() + } + + const DESC_NULLS_LAST: PrimaryKey = PrimaryKey { + index: 0, + descending: true, + nulls_first: false, + }; + + #[test] + fn a_limited_scan_is_never_split_per_file() { + let files = (0..3) + .map(|i| fake_file(i, Some(ts_stats(i as i64 * 10, i as i64 * 10 + 9, 0)))) + .collect::>(); + let limited = fake_scan(vec![files.clone()], Some(5)); + let units = analyze_source(&limited, DESC_NULLS_LAST, 4).unwrap(); + assert_eq!(units.len(), 1, "a per-file split would multiply the limit"); + assert!(Arc::ptr_eq(&units[0].plan, &limited)); + assert_eq!(scan_config(&units[0].plan).limit, Some(5)); + let unlimited = fake_scan(vec![files], None); + assert_eq!( + analyze_source(&unlimited, DESC_NULLS_LAST, 4) + .unwrap() + .len(), + 3 + ); + } + + #[test] + fn uncertified_files_keep_the_scan_partition_count() { + let files = (0..2000) + .map(|i| fake_file(i, (i % 200 == 0).then(|| ts_stats(i as i64, i as i64, 0)))) + .collect::>(); + let scan = fake_scan(round_robin(files, 4), None); + for target in [1, 2, 4, 16] { + let units = analyze_source(&scan, DESC_NULLS_LAST, target).unwrap(); + assert_eq!(units.len(), 11); + let uncertified = units + .iter() + .filter(|unit| unit.bound.is_none()) + .collect::>(); + assert_eq!(uncertified.len(), 1); + let plan = &uncertified[0].plan; + assert_eq!( + plan.output_partitioning().partition_count(), + target.min(4), + "target_partitions={target}" + ); + let groups = &scan_config(plan).file_groups; + assert_eq!(groups.iter().map(|g| g.len()).sum::(), 1990); + let bytes = groups + .iter() + .map(|g| g.iter().map(piece_size).sum::()) + .collect::>(); + let spread = bytes.iter().max().unwrap() - bytes.iter().min().unwrap(); + assert!(spread <= 3_000, "unbalanced groups: {bytes:?}"); + for unit in units.iter().filter(|unit| unit.bound.is_some()) { + assert_eq!(unit.plan.output_partitioning().partition_count(), 1); + } + } + } + + #[test] + fn planning_thousands_of_certified_files_is_linear() { + let plan_files = |count: usize| { + let files = (0..count) + .map(|i| fake_file(i, Some(ts_stats(i as i64 * 10, i as i64 * 10 + 9, 0)))) + .collect::>(); + let scan = fake_scan(round_robin(files, 4), None); + let started = std::time::Instant::now(); + let units = analyze_source(&scan, DESC_NULLS_LAST, 4).unwrap(); + let elapsed = started.elapsed(); + assert_eq!(units.len(), count); + for unit in &units { + let groups = &scan_config(&unit.plan).file_groups; + assert_eq!(groups.len(), 1); + assert_eq!(groups[0].len(), 1); + } + elapsed + }; + let small = (0..3).map(|_| plan_files(500)).min().unwrap(); + let large = (0..3).map(|_| plan_files(2000)).min().unwrap(); + println!("500 files: {small:?}, 2000 files: {large:?}"); + // 4x the files: ~4x the time when linear, ~16x when quadratic. + assert!( + large < small * 10 + Duration::from_millis(50), + "planning is not linear: 500 files {small:?}, 2000 files {large:?}" + ); + assert!(large < Duration::from_secs(2), "{large:?}"); + + let files = (0..2000) + .map(|i| fake_file(i, Some(ts_stats(i as i64 * 10, i as i64 * 10 + 9, 0)))) + .collect::>(); + let exec = ProgressiveTopKExec::try_new( + ts_order(true, false), + 10, + schema(), + vec![fake_scan(round_robin(files, 4), None)], + None, + 4, + ) + .unwrap(); + assert_eq!(exec.bounded_units(), 2000); + } + + #[test] + fn every_piece_of_a_file_must_certify_no_nulls() { + let key = PrimaryKey { + index: 0, + descending: true, + nulls_first: true, + }; + let piece = |start, end, nulls| { + PartitionedFile::new("/fake/split.parquet", 1_000) + .with_range(start, end) + .with_statistics(Arc::new(ts_stats(0, 99, nulls))) + }; + for (first, second, no_nulls) in [(0, 0, true), (0, 3, false), (3, 0, false)] { + let other = fake_file(1, Some(ts_stats(100, 199, 0))); + let scan = fake_scan( + vec![ + vec![piece(0, 500, first), other], + vec![piece(500, 1_000, second)], + ], + None, + ); + let units = analyze_source(&scan, key, 4).unwrap(); + assert_eq!(units.len(), 2); + let split = units + .iter() + .find(|unit| unit.bound.as_ref().unwrap().value == ts(99)) + .unwrap(); + assert_eq!(split.plan.output_partitioning().partition_count(), 2); + let bound = split.bound.as_ref().unwrap(); + assert_eq!( + bound.no_nulls, no_nulls, + "pieces with {first}/{second} NULLs" + ); + // `ts DESC NULLS FIRST` with a threshold above the file's max: a + // NULL in any piece could still enter the TopK. + assert_eq!(prunable(bound, &ts(150), key), no_nulls); + } + } + + fn find_progressive(plan: &Arc) -> Arc { + let mut found = None; + plan.apply(|node| { + if node.is::() { + found = Some(Arc::clone(node)); + return Ok(TreeNodeRecursion::Stop); + } + Ok(TreeNodeRecursion::Continue) + }) + .unwrap(); + found.expect("plan has a ProgressiveTopKExec") + } + + /// Expression ids of the dynamic filters in the plan's file scans. + fn scan_filter_ids(plan: &Arc) -> Vec { + let mut ids = Vec::new(); + plan.apply(|node| { + let config = node + .downcast_ref::() + .and_then(|exec| exec.data_source().downcast_ref::()); + if let Some(predicate) = config.and_then(|config| config.file_source().filter()) { + predicate.apply(|expr| { + if expr.downcast_ref::().is_some() { + ids.extend(expr.expression_id()); + } + Ok(TreeNodeRecursion::Continue) + })?; + } + Ok(TreeNodeRecursion::Continue) + }) + .unwrap(); + ids + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn repeated_and_concurrent_executions_use_fresh_state() { + let data = dataset(31, true, &[], 120); + let sql = "SELECT * FROM t ORDER BY ts DESC NULLS LAST, id LIMIT 30"; + let expected = run( + &context(TestTable::new(&data, Layout::default()), false), + sql, + ) + .await; + let ctx = context(TestTable::new(&data, Layout::default()), true); + let plan = ctx + .sql(sql) + .await + .unwrap() + .create_physical_plan() + .await + .unwrap(); + let node = find_progressive(&plan); + let exec = node.downcast_ref::().unwrap(); + let format = + |batches: Vec| pretty_format_batches(&batches).unwrap().to_string(); + for _ in 0..2 { + let batches = collect(Arc::clone(&plan), ctx.task_ctx()).await.unwrap(); + assert_eq!(format(batches), expected, "repeated execution"); + } + let (a, b) = tokio::join!( + collect(Arc::clone(&plan), ctx.task_ctx()), + collect(Arc::clone(&plan), ctx.task_ctx()) + ); + assert_eq!(format(a.unwrap()), expected, "concurrent execution"); + assert_eq!(format(b.unwrap()), expected, "concurrent execution"); + + // The TopK dynamic filter was pushed into the Parquet scans; each run + // rebinds the scans to its own filter and the template stays untouched. + let template = exec + .dynamic_filter + .as_ref() + .expect("SortExec dynamic filter"); + let template_id = template.expression_id().unwrap(); + assert!( + exec.units + .iter() + .any(|unit| scan_filter_ids(&unit.plan).contains(&template_id)), + "the dynamic filter reached the scans" + ); + assert_eq!( + template + .downcast_ref::() + .unwrap() + .current() + .unwrap() + .to_string(), + "true" + ); + let filters = exec.run_filters.lock().unwrap().clone(); + assert_eq!(filters.len(), 4); + let ids = filters + .iter() + .map(|filter| filter.expression_id().unwrap()) + .collect::>(); + assert_eq!(ids.len(), 4, "every execution has its own filter"); + assert!(!ids.contains(&template_id)); + for filter in &filters { + tokio::time::timeout(Duration::from_secs(1), filter.wait_complete()) + .await + .expect("the run marked its filter complete"); + assert_ne!(filter.current().unwrap().to_string(), "true"); + } + let run = RunFilter { + template_id, + filter: Arc::clone(&filters[0]), + }; + let fresh = filters[0].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()); + assert!(!after.contains(&template_id)); + assert_eq!( + after.iter().filter(|id| **id == fresh).count(), + before.iter().filter(|id| **id == template_id).count() + ); + } + } +} diff --git a/src/query/stream_schema_provider.rs b/src/query/stream_schema_provider.rs index 948d448e5..31cd912ac 100644 --- a/src/query/stream_schema_provider.rs +++ b/src/query/stream_schema_provider.rs @@ -45,10 +45,15 @@ use datafusion::{ BinaryExpr, Operator, TableProviderFilterPushDown, TableSource, TableType, physical_planning_context::PhysicalPlanningContext, utils::conjunction, }, - physical_expr::create_physical_expr, + physical_expr::{EquivalenceProperties, create_physical_expr}, physical_plan::{ - ExecutionPlan, Statistics, empty::EmptyExec, filter::FilterExecBuilder, - stream::RecordBatchReceiverStream, streaming::PartitionStream, union::UnionExec, + DisplayAs, DisplayFormatType, ExecutionPlan, Partitioning, PlanProperties, Statistics, + empty::EmptyExec, + execution_plan::{Boundedness, EmissionType}, + filter::FilterExecBuilder, + stream::RecordBatchReceiverStream, + streaming::PartitionStream, + union::UnionExec, }, prelude::Expr, scalar::ScalarValue, @@ -313,6 +318,31 @@ fn build_parquet_scan_components_with_filters( Ok((file_format, file_source)) } +/// Downgrades file-level statistics from `Exact` to `Inexact` whenever a scan +/// enforces row-level predicates that may discard rows inside a file. +/// +/// Leaving `Precision::Exact` on a predicate-filtered scan allows DataFusion's +/// `AggregateStatistics` rule to shortcut `COUNT(*)`, `MIN`, or `MAX` to +/// pre-filter manifest totals/bounds. +fn to_inexact_statistics(statistics: Statistics) -> Statistics { + Statistics { + num_rows: statistics.num_rows.to_inexact(), + total_byte_size: statistics.total_byte_size.to_inexact(), + column_statistics: statistics + .column_statistics + .into_iter() + .map(|col| datafusion::common::ColumnStatistics { + null_count: col.null_count.to_inexact(), + max_value: col.max_value.to_inexact(), + min_value: col.min_value.to_inexact(), + distinct_count: col.distinct_count.to_inexact(), + sum_value: col.sum_value.to_inexact(), + byte_size: col.byte_size.to_inexact(), + }) + .collect(), + } +} + pub fn balanced_file_groups(manifest_files: Vec, target_partitions: usize) -> Vec> { let group_count = target_partitions.min(manifest_files.len()); if group_count == 0 { @@ -404,7 +434,53 @@ pub(super) async fn parquet_scan_plan_with_cache_options( batch_size: usize, cache_options: (usize, usize, bool), ) -> Result, DataFusionError> { - let (file_format, file_source) = build_parquet_scan_components(schema, filters, state)?; + let exact_filters = exact_source_filters(filters); + let statistics = if exact_filters.is_empty() { + statistics + } else { + to_inexact_statistics(statistics) + }; + let needs_post_scan_filter = !exact_filters.is_empty() + && !state + .default_table_options() + .parquet + .global + .pushdown_filters; + let post_scan_predicate = if needs_post_scan_filter { + conjunction(exact_filters.clone()) + } else { + None + }; + + let (scan_projection, output_projection) = if let Some(predicate) = post_scan_predicate.as_ref() + { + let scan_proj = projection + .map(|projection| { + let mut columns = projection.clone(); + for column in predicate.column_refs() { + columns.push(schema.index_of(&column.name)?); + } + columns.sort_unstable(); + columns.dedup(); + Ok::<_, DataFusionError>(columns) + }) + .transpose()?; + let out_proj = projection.zip(scan_proj.as_ref()).map(|(proj, scanned)| { + proj.iter() + .map(|index| { + scanned + .binary_search(index) + .expect("projected column is scanned") + }) + .collect_vec() + }); + (scan_proj, out_proj) + } else { + (projection.cloned(), None) + }; + + let (file_format, file_source) = + build_parquet_scan_components_with_filters(schema, exact_filters, state)?; let (cache_scope, cache_budget, cache_enabled) = cache_options; let cache_store = if object_store_url.as_str() != "file:///" && cache_enabled && cache_budget > 0 { @@ -423,12 +499,14 @@ pub(super) async fn parquet_scan_plan_with_cache_options( .with_file_groups(file_groups); // Set projection if provided - if let Some(proj_indices) = projection { - conf_builder = conf_builder.with_projection_indices(Some(proj_indices.clone()))?; + if let Some(proj_indices) = scan_projection { + conf_builder = conf_builder.with_projection_indices(Some(proj_indices))?; } - // Set limit if provided - if let Some(lim) = limit { + // Only push limit into Parquet when rows are not further filtered above it. + if post_scan_predicate.is_none() + && let Some(lim) = limit + { conf_builder = conf_builder.with_limit(Some(lim)); } @@ -442,7 +520,7 @@ pub(super) async fn parquet_scan_plan_with_cache_options( conf, ) .await?; - if let Some(store) = cache_store { + let plan = if let Some(store) = cache_store { super::small_file_cache::install( plan, store, @@ -453,7 +531,23 @@ pub(super) async fn parquet_scan_plan_with_cache_options( .config() .get_extension::() .unwrap_or_default(), - ) + )? + } else { + plan + }; + + if let Some(predicate) = post_scan_predicate { + let physical_predicate = create_physical_expr( + &predicate, + &plan.schema().to_dfschema()?, + state.execution_props(), + &PhysicalPlanningContext::default(), + )?; + let filter = FilterExecBuilder::new(physical_predicate, plan) + .apply_projection(output_projection)? + .with_fetch(limit) + .build()?; + Ok(Arc::new(filter)) } else { Ok(plan) } @@ -531,6 +625,64 @@ impl StandardTableProvider { Ok(()) } + #[allow(clippy::too_many_arguments)] + async fn push_manifest_parquet_plans( + &self, + execution_plans: &mut Vec>, + object_store_url: ObjectStoreUrl, + files: Vec, + is_hot_tier: bool, + time_column: &str, + projection: Option<&Vec>, + exact_filter_plan: &ExactTimeFilterPlan, + limit: Option, + state: &dyn Session, + ) -> Result<(), DataFusionError> { + let (interior_files, boundary_files) = exact_filter_plan.split_files(files, &self.schema); + if !interior_files.is_empty() { + let (partitioned_files, statistics, _) = self.partitioned_files( + interior_files, + state.config_options().execution.target_partitions, + is_hot_tier, + time_column, + ); + // Interior files provably satisfy every exact time bound without + // nulls; omit the exact time predicates so DataFusion does not + // decode the time column when unprojected. + self.create_parquet_physical_plan( + execution_plans, + object_store_url.clone(), + partitioned_files, + statistics, + projection, + &[], + limit, + state, + ) + .await?; + } + if !boundary_files.is_empty() { + let (partitioned_files, statistics, _) = self.partitioned_files( + boundary_files, + state.config_options().execution.target_partitions, + is_hot_tier, + time_column, + ); + self.create_parquet_physical_plan( + execution_plans, + object_store_url, + partitioned_files, + statistics, + projection, + &exact_filter_plan.exact_exprs, + limit, + state, + ) + .await?; + } + Ok(()) + } + #[allow(clippy::too_many_arguments)] async fn get_hottier_exectuion_plan( &self, @@ -538,7 +690,7 @@ impl StandardTableProvider { hot_tier_manager: &HotTierManager, manifest_files: &mut Vec, projection: Option<&Vec>, - filters: &[Expr], + exact_filter_plan: &ExactTimeFilterPlan, limit: Option, state: &dyn Session, time_partition: Option, @@ -555,6 +707,10 @@ impl StandardTableProvider { &self.stream, ); + if hot_tier_files.is_empty() { + return Ok(()); + } + let hot_tier_files: Vec = hot_tier_files .into_iter() .map(|mut file| { @@ -575,26 +731,18 @@ impl StandardTableProvider { }) .collect::>()?; - let (partitioned_files, statistics, _) = self.partitioned_files( + self.push_manifest_parquet_plans( + execution_plans, + ObjectStoreUrl::parse("file:///").unwrap(), hot_tier_files, - state.config_options().execution.target_partitions, true, time_partition.as_deref().unwrap_or(DEFAULT_TIMESTAMP_KEY), - ); - - self.create_parquet_physical_plan( - execution_plans, - ObjectStoreUrl::parse("file:///").unwrap(), - partitioned_files, - statistics, projection, - filters, + exact_filter_plan, limit, state, ) - .await?; - - Ok(()) + .await } /// Create an execution plan over the records in arrows and parquet that are still in staging, awaiting push to object storage @@ -607,68 +755,15 @@ impl StandardTableProvider { state: &dyn Session, captured: (StagingCapture, Vec), ) -> Result<(), DataFusionError> { - // Both sources were captured before the remote snapshot was read. - let (staged, partitioned_files) = captured; - let StagingCapture { - memory: records, - disk: disk_sources, - } = staged; - // Keep the reverse traversal within one partition when the scan is - // asked to stop early. Without a limit, contiguous groups can run - // independently and any SQL ordering is enforced by DataFusion. - let target_partitions = if limit.is_some() { - 1 - } else { - state - .config_options() - .execution - .target_partitions - .min(num_cpus::get()) - }; - let (mem_table, mem_projection) = projected_reversed_mem_table( - records, - self.schema.clone(), - projection, - filters, - target_partitions, - )?; - let arrow_exec = scan_enforcing_exact_filters( - &mem_table, - state, - mem_projection.as_ref(), - filters, - limit, - ) - .await?; - execution_plans.push(arrow_exec); - - // Rows the staging memory cache does not hold are streamed from the - // staging files captured with it, one partition per file. - if let Some(disk_exec) = staging_disk_plan( - self.schema.clone(), - disk_sources, - state, - projection, - filters, - limit, - ) - .await? - { - execution_plans.push(disk_exec); - } - - // Keep the native scan and its file extensions: each extension owns the - // hard-link lease through optimizer rewrites and execution streams. - let object_store_url = "file:///"; - self.create_parquet_physical_plan( + staging_execution_plans( + &self.schema, execution_plans, - ObjectStoreUrl::parse(object_store_url).unwrap(), - vec![partitioned_files], - Statistics::new_unknown(&self.schema), projection, filters, limit, state, + captured, + PARSEABLE.options.execution_batch_size, ) .await } @@ -753,6 +848,30 @@ impl StandardTableProvider { } } +/// Upper bound on `file_count * schema.fields().len()` for attaching full +/// per-file `ColumnStatistics` to every `PartitionedFile` and merging dense +/// non-time table statistics. Above this budget (e.g. 10,000 files × 400 +/// columns), `partitioned_files` skips per-file `Statistics` and only merges +/// certified bounds for `time_column` to bound planning memory and CPU. +const MAX_PER_FILE_COLUMN_STATS: usize = 250_000; + +fn merge_certified_scalar_bounds( + acc: (ScalarValue, ScalarValue), + next: (ScalarValue, ScalarValue), +) -> Option<(ScalarValue, ScalarValue)> { + let (acc_min, acc_max) = acc; + let (next_min, next_max) = next; + let min = match acc_min.partial_cmp(&next_min)? { + std::cmp::Ordering::Greater => next_min, + _ => acc_min, + }; + let max = match acc_max.partial_cmp(&next_max)? { + std::cmp::Ordering::Less => next_max, + _ => acc_max, + }; + Some((min, max)) +} + /// Groups manifest files into scan partitions and merges their statistics. /// /// The returned flag, whether the scan output is ordered by `time_column`, is always `false`: a @@ -765,16 +884,35 @@ pub fn partitioned_files( manifest_files: Vec, target_partitions: usize, _is_hot_tier: bool, - _time_column: &str, + time_column: &str, ) -> ( Vec>, datafusion::common::Statistics, bool, ) { + 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 time_col_idx = schema.index_of(time_column).ok(); + let file_groups = balanced_file_groups(manifest_files, target_partitions); let mut partitioned_files = Vec::with_capacity(file_groups.len()); - let mut column_statistics = HashMap::>::new(); - let mut count = 0; + // Per-schema-field merged certified min/max across ALL files: + // None => no file processed yet + // Some(Some((lo, hi))) => valid merged certified bounds across every file seen so far + // Some(None) => poisoned (at least one file lacked valid certified stats) + let mut merged_bounds: Vec>> = vec![None; num_fields]; + let mut merged_null_counts: Vec> = if within_stats_budget { + vec![Some(0); num_fields] + } else { + let mut counts = vec![None; num_fields]; + if let Some(idx) = time_col_idx { + counts[idx] = Some(0); + } + counts + }; + let mut total_rows: Option = Some(0); let mut file_count = 0u64; for group in file_groups { let mut partition = Vec::with_capacity(group.len()); @@ -805,50 +943,137 @@ pub fn partitioned_files( .to_string(); } } - let pf = PartitionedFile::new(file_path, file_size); - partition.push(pf); - columns.into_iter().for_each(|col| { - column_statistics - .entry(col.name) - .and_modify(|x| { - if let Some((stats, col_stats)) = x.as_ref().cloned().zip(col.stats.clone()) - { - // update() returns None on type mismatch (e.g. column - // historically written as both Utf8 and Timestamp(ms)). - // Dropping to None here makes the planner skip min/max - // pushdown for this column instead of crashing the worker. - *x = stats.update(col_stats); - } - }) - .or_insert_with(|| col.stats.as_ref().cloned()); - }); - count += num_rows; + let mut pf = PartitionedFile::new(file_path, file_size); + + if within_stats_budget { + let mut file_cols: HashMap<&str, &Column> = HashMap::with_capacity(columns.len()); + for col in &columns { + file_cols.entry(col.name.as_str()).or_insert(col); + } + + let mut file_column_stats = if attach_per_file_stats { + Vec::with_capacity(num_fields) + } else { + Vec::new() + }; + for (field_idx, field) in schema.fields().iter().enumerate() { + let col = file_cols.get(field.name().as_str()).copied(); + // Validate each file's column independently via provenance-checked + // `certified_min_max_as_scalar` before merging so invalid/uncertified/ + // float bounds are never published or rehabilitated. + let certified_bounds = + col.and_then(|c| c.certified_min_max_as_scalar(field.data_type())); + + if attach_per_file_stats { + let file_null_count = col + .and_then(|c| c.null_count) + .and_then(|n| usize::try_from(n).ok()) + .map(Precision::Exact) + .unwrap_or(Precision::Absent); + let (file_min, file_max) = certified_bounds + .as_ref() + .map(|(min, max)| { + (Precision::Exact(min.clone()), Precision::Exact(max.clone())) + }) + .unwrap_or((Precision::Absent, Precision::Absent)); + file_column_stats.push(datafusion::common::ColumnStatistics { + null_count: file_null_count, + max_value: file_max, + min_value: file_min, + distinct_count: Precision::Absent, + sum_value: Precision::Absent, + byte_size: Precision::Absent, + }); + } + + // Sound table-level merge: every file must provide certified + // compatible bounds for a column to remain `Precision::Exact`. + merged_bounds[field_idx] = + match (merged_bounds[field_idx].take(), certified_bounds) { + (None, Some(bounds)) => Some(Some(bounds)), + (Some(Some(acc)), Some(bounds)) => { + Some(merge_certified_scalar_bounds(acc, bounds)) + } + _ => Some(None), + }; + merged_null_counts[field_idx] = match ( + merged_null_counts[field_idx], + col.and_then(|c| c.null_count), + ) { + (Some(acc), Some(n)) => acc.checked_add(n), + _ => None, + }; + } + + if attach_per_file_stats { + // Leave `num_rows: Absent` on individual PartitionedFiles so + // DataFusion never mistakes pre-filter row counts on boundary + // scans, while exposing certified per-file min/max/null_count + // for ProgressiveTopKExec and pruning. + let file_stats = datafusion::common::Statistics { + num_rows: Precision::Absent, + total_byte_size: Precision::Absent, + column_statistics: file_column_stats, + }; + pf = pf.with_statistics(Arc::new(file_stats)); + } + } else if let Some(idx) = time_col_idx { + let field = schema.field(idx); + let col = columns.iter().find(|c| c.name == time_column); + let certified_bounds = + col.and_then(|c| c.certified_min_max_as_scalar(field.data_type())); + merged_bounds[idx] = match (merged_bounds[idx].take(), certified_bounds) { + (None, Some(bounds)) => Some(Some(bounds)), + (Some(Some(acc)), Some(bounds)) => { + Some(merge_certified_scalar_bounds(acc, bounds)) + } + _ => Some(None), + }; + merged_null_counts[idx] = + match (merged_null_counts[idx], col.and_then(|c| c.null_count)) { + (Some(acc), Some(n)) => acc.checked_add(n), + _ => None, + }; + } + + partition.push(pf); + total_rows = total_rows.and_then(|acc| acc.checked_add(num_rows)); } partitioned_files.push(partition); } - let statistics = schema - .fields() - .iter() - .map(|field| { - column_statistics - .get(field.name()) - .and_then(|stats| stats.as_ref()) - .and_then(|stats| stats.clone().min_max_as_scalar(field.data_type())) - .map(|(min, max)| datafusion::common::ColumnStatistics { - null_count: Precision::Absent, - max_value: Precision::Exact(max), - min_value: Precision::Exact(min), - distinct_count: Precision::Absent, - sum_value: Precision::Absent, - byte_size: Precision::Absent, - }) - .unwrap_or_default() + let statistics = (0..num_fields) + .map(|field_idx| { + let null_count = if file_count == 0 { + Precision::Absent + } else { + merged_null_counts[field_idx] + .and_then(|n| usize::try_from(n).ok()) + .map(Precision::Exact) + .unwrap_or(Precision::Absent) + }; + let (min_value, max_value) = merged_bounds[field_idx] + .as_ref() + .and_then(|bounds| bounds.as_ref()) + .map(|(min, max)| (Precision::Exact(min.clone()), Precision::Exact(max.clone()))) + .unwrap_or((Precision::Absent, Precision::Absent)); + datafusion::common::ColumnStatistics { + null_count, + max_value, + min_value, + distinct_count: Precision::Absent, + sum_value: Precision::Absent, + byte_size: Precision::Absent, + } }) .collect(); + let num_rows = total_rows + .and_then(|n| usize::try_from(n).ok()) + .map(Precision::Exact) + .unwrap_or(Precision::Absent); let statistics = datafusion::common::Statistics { - num_rows: Precision::Exact(count as usize), + num_rows, total_byte_size: Precision::Absent, column_statistics: statistics, }; @@ -880,19 +1105,124 @@ pub async fn collect_from_snapshot( stream_name, tenant_id, None, - false, + SharedManifestPolicy::Bypass, + None, ) .await } -/// Whether manifests may be read from the process-wide metadata cache. +/// Controls which manifests `collect_from_snapshot_cached` may share through +/// the process-wide [`METADATA_CACHE`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum SharedManifestPolicy { + /// Never read or populate `METADATA_CACHE`. + Bypass, + /// Historical scan: share every manifest through `METADATA_CACHE`. + All, + /// Standalone (`Mode::All`) live-window scan: keep `.stream.json` and + /// manifests overlapping the staging window uncached, while sharing + /// strictly closed historical manifests whose `time_upper_bound < cutoff`. + ClosedBefore(NaiveDateTime), +} + +/// Selects the shared manifest cache policy for a scan. +/// +/// Standalone vs. distributed consistency boundary: +/// - When `METADATA_CACHE` is disabled, always returns `Bypass`. +/// - Pure historical scans (`shared && !include_staging`) share all manifests +/// via `All`, bounded by `P_METADATA_CACHE_TTL_MS`. +/// - Live-window scans (`include_staging == true` or `!shared`): +/// - In standalone `Mode::All`, this single server process owns every +/// metastore write and synchronously calls `METADATA_CACHE.invalidate_stream` +/// after `put_manifest`, `put_stream_json`, `delete_manifest`, +/// `delete_stream_partition`, and `delete_stream` (before staged files are +/// unlinked). Strictly closed historical manifests +/// (`item.time_upper_bound.naive_utc() < cutoff`) can therefore be shared +/// safely via `ClosedBefore(cutoff)`. +/// - In distributed modes (`Mode::Query`, `Mode::Prism`, `Mode::Ingest`, +/// `Mode::Index`), separate ingest/index nodes can append late-arriving data +/// to older manifests without invalidating this node's local +/// `METADATA_CACHE`, so live-window scans MUST `Bypass` the shared manifest +/// cache completely. +fn shared_manifest_policy( + cache_enabled: bool, + shared: bool, + include_staging: bool, + mode: Mode, + cutoff: NaiveDateTime, +) -> SharedManifestPolicy { + if !cache_enabled { + SharedManifestPolicy::Bypass + } else if shared && !include_staging { + SharedManifestPolicy::All + } else if mode == Mode::All { + SharedManifestPolicy::ClosedBefore(cutoff) + } else { + SharedManifestPolicy::Bypass + } +} + +/// Whether `item` may be read from the process-wide metadata cache under +/// `policy`. /// -/// Historical scans share decoded manifests across concurrent queries. Scans -/// that reach into the staging window bypass the shared manifest cache so a -/// fresh stream snapshot cannot pair with a stale manifest after a late upload -/// into an older partition. -fn shares_manifest(historical_scan: bool) -> bool { - METADATA_CACHE.enabled() && historical_scan +/// See [`shared_manifest_policy`] for the standalone (`Mode::All`) versus +/// distributed (`Mode::Query | Mode::Prism`) consistency invariants. +fn shares_manifest(policy: SharedManifestPolicy, item: &ManifestItem) -> bool { + if !METADATA_CACHE.enabled() { + return false; + } + match policy { + SharedManifestPolicy::Bypass => false, + SharedManifestPolicy::All => true, + SharedManifestPolicy::ClosedBefore(cutoff) => item.time_upper_bound.naive_utc() < cutoff, + } +} + +/// Truncates `manifest_files` (ordered newest-first) once a prefix provably +/// contains at least `limit` rows that satisfy every filter in `filters`. +/// +/// Never truncates when any inexact filter is present, and never counts a +/// boundary file's rows toward `limit` because a mid-minute bound or nullable / +/// missing column statistics could discard rows inside that file. +fn truncate_manifest_files_for_limit( + manifest_files: &mut Vec, + limit: Option, + filters_empty: bool, + exact_filter_plan: Option<(&ExactTimeFilterPlan, &SchemaRef)>, +) { + let Some(limit) = limit else { + return; + }; + if limit == 0 { + manifest_files.clear(); + return; + } + if !filters_empty && !exact_filter_plan.is_some_and(|(plan, _)| plan.all_filters_exact) { + return; + } + + let limit = limit as u64; + let mut guaranteed_rows = 0u64; + let mut pos = None; + + for (index, file) in manifest_files.iter().enumerate() { + let fully_matching = if filters_empty { + true + } else { + exact_filter_plan.is_some_and(|(plan, schema)| plan.file_is_interior(file, schema)) + }; + if fully_matching { + guaranteed_rows = guaranteed_rows.saturating_add(file.num_rows()); + if guaranteed_rows >= limit { + pos = Some(index); + break; + } + } + } + + if let Some(pos) = pos { + manifest_files.truncate(pos + 1); + } } #[allow(clippy::too_many_arguments)] @@ -904,13 +1234,13 @@ async fn collect_from_snapshot_cached( stream_name: &str, tenant_id: &Option, cache: Option<&PlanningCache>, - shared: bool, + manifest_cache_policy: SharedManifestPolicy, + exact_filter_plan: Option<(&ExactTimeFilterPlan, &SchemaRef)>, ) -> Result, DataFusionError> { // Manifest fetches are one object store GET each and are pure round trip // latency, so run them concurrently instead of serially. `buffered` keeps // the snapshot ordering, which the `rev()` below depends on. let items = snapshot.manifests(time_filters); - let share_manifests = shares_manifest(shared); let mut uncached = Vec::new(); let mut reserved_slots = HashMap::new(); let mut batch_leases = HashMap::new(); @@ -924,7 +1254,7 @@ async fn collect_from_snapshot_cached( { continue; } - if share_manifests + if shares_manifest(manifest_cache_policy, item) && let Some((slot, lease)) = METADATA_CACHE.reserve_manifest_slot(stream_name, tenant_id, &item.manifest_path) { @@ -1060,23 +1390,12 @@ async fn collect_from_snapshot_cached( .filter_map(|(file, reason)| reason.is_none().then_some(file)) .collect(); - if let Some(limit) = limit { - let limit = limit as u64; - let mut curr_limit = 0; - let mut pos = None; - - for (index, file) in manifest_files.iter().enumerate() { - curr_limit += file.num_rows(); - if curr_limit >= limit { - pos = Some(index); - break; - } - } - - if let Some(pos) = pos { - manifest_files.truncate(pos + 1); - } - } + truncate_manifest_files_for_limit( + &mut manifest_files, + limit, + filters.is_empty(), + exact_filter_plan, + ); Ok(manifest_files) } @@ -1212,6 +1531,15 @@ impl TableProvider for StandardTableProvider { } } + let exact_filter_plan = ExactTimeFilterPlan::new(filters, &self.time_partition); + let manifest_cache_policy = shared_manifest_policy( + METADATA_CACHE.enabled(), + shared, + include_staging, + PARSEABLE.options.mode, + staging_window_cutoff(), + ); + let mut manifest_files = collect_from_snapshot_cached( &merged_snapshot, &time_filters, @@ -1220,7 +1548,8 @@ impl TableProvider for StandardTableProvider { &self.stream, &self.tenant_id, cache, - shared && !include_staging, + manifest_cache_policy, + Some((&exact_filter_plan, &self.schema)), ) .await?; @@ -1268,6 +1597,26 @@ impl TableProvider for StandardTableProvider { return self.final_plan(execution_plans, projection); } + // Zero-I/O interior COUNT(*): when no columns are projected and every + // query filter is an exact time bound satisfied by interior files, emit + // their checked manifest row count without opening any Parquet files. + let can_use_interior_row_count = + projection.is_some_and(Vec::is_empty) && exact_filter_plan.all_filters_exact; + if can_use_interior_row_count { + let (interior_files, boundary_files) = + exact_filter_plan.split_files(manifest_files, &self.schema); + if !interior_files.is_empty() + && let Some(count_plan) = + manifest_row_count_plan(&self.schema, &interior_files, limit, state).await? + { + execution_plans.push(count_plan); + } + manifest_files = boundary_files; + if manifest_files.is_empty() { + return self.final_plan(execution_plans, projection); + } + } + // Hot tier data fetch if self.hot_tier_guarded && let Some(hot_tier_manager) = GLOBAL_HOTTIER.get() @@ -1278,7 +1627,7 @@ impl TableProvider for StandardTableProvider { hot_tier_manager, &mut manifest_files, projection, - filters, + &exact_filter_plan, limit, state, time_partition.clone(), @@ -1295,22 +1644,15 @@ impl TableProvider for StandardTableProvider { return self.final_plan(execution_plans, projection); } - let (partitioned_files, statistics, _) = self.partitioned_files( - manifest_files, - state.config_options().execution.target_partitions, - false, - time_partition.as_deref().unwrap_or(DEFAULT_TIMESTAMP_KEY), - ); - let object_store_url = glob_storage.store_url(); - - self.create_parquet_physical_plan( + self.push_manifest_parquet_plans( &mut execution_plans, ObjectStoreUrl::parse(object_store_url).unwrap(), - partitioned_files, - statistics, + manifest_files, + false, + time_partition.as_deref().unwrap_or(DEFAULT_TIMESTAMP_KEY), projection, - filters, + &exact_filter_plan, limit, state, ) @@ -1341,1873 +1683,6263 @@ pub fn reversed_mem_table( partitioned_reversed_mem_table(records, schema, 1) } -/// A scan over staging files whose rows the memory cache does not hold, -/// bucketed into bounded partitions, enforcing exact filters like the in-memory scan. -async fn staging_disk_plan( +/// Per-partition `BufReader` capacity for `StagingDiskPartition`. Bounded to +/// 64 KiB so concurrent parallel partitions stay compact (~512 KiB at 8 cores). +const STAGING_DISK_PARTITION_READ_BUFFER_BYTES: usize = 64 * 1024; + +/// Minimum byte size of a single staging file before splitting its IPC record +/// batches across multiple DataFusion partitions. +const STAGING_DISK_MIN_SPLIT_BYTES: usize = 1024 * 1024; + +/// Minimal projection covering both requested output columns and filter columns. +struct NeededProjection { schema: SchemaRef, - sources: Vec, - state: &dyn Session, + needed_indices: Option>, + remapped_projection: Option>, +} + +/// Computes the minimal schema covering both `projection` and any column +/// referenced by `filters`, along with the retained column indices (when fewer +/// than all columns are needed) and the remapped `projection` indices. +fn needed_column_projection( + schema: &SchemaRef, projection: Option<&Vec>, filters: &[Expr], - limit: Option, -) -> DataFusionResult>> { - if sources.is_empty() { - return Ok(None); - } - let max_partitions = if limit.is_some() { - 1 - } else { - state - .config_options() - .execution - .target_partitions - .min(num_cpus::get()) - .max(1) +) -> DataFusionResult { + let Some(projection) = projection else { + return Ok(NeededProjection { + schema: schema.clone(), + needed_indices: None, + remapped_projection: None, + }); }; - let num_buckets = sources.len().min(max_partitions); - let mut buckets: Vec> = (0..num_buckets).map(|_| Vec::new()).collect(); - for (idx, source) in sources.into_iter().enumerate() { - buckets[idx % num_buckets].push(source); + let mut needed = projection.clone(); + for column in filters.iter().flat_map(Expr::column_refs) { + needed.push(schema.index_of(&column.name)?); } - let partitions = buckets - .into_iter() - .filter(|b| !b.is_empty()) - .map(|bucket| { - Arc::new(StagingDiskPartition { - schema: schema.clone(), - sources: bucket, - }) as Arc + needed.sort_unstable(); + needed.dedup(); + + if needed.iter().copied().eq(0..schema.fields().len()) { + return Ok(NeededProjection { + schema: schema.clone(), + needed_indices: None, + remapped_projection: Some(projection.clone()), + }); + } + let projected_schema = Arc::new(schema.project(&needed)?); + let remapped = projection + .iter() + .map(|index| { + needed + .binary_search(index) + .expect("projected column is retained") }) .collect(); - let table = StreamingTable::try_new(schema, partitions)?; - scan_enforcing_exact_filters(&table, state, projection, filters, limit) - .await - .map(Some) + Ok(NeededProjection { + schema: projected_schema, + needed_indices: Some(needed), + remapped_projection: Some(remapped), + }) } -/// The acknowledged rows of one or more staging files, streamed newest batch -/// first and adapted to the table schema. Any I/O or decode error fails the -/// query: a short read would otherwise silently drop acknowledged rows. -#[derive(Debug)] -struct StagingDiskPartition { - schema: SchemaRef, - sources: Vec, +/// Column projection to push into Arrow IPC `StreamReader` for a single file. +#[derive(Debug, Clone)] +enum IpcProjection { + /// Decode every column without passing a projection to `StreamReader` + /// (avoids Arrow's per-batch projected-field scan on `SELECT *` and + /// preserves duplicate-name fallback semantics). + Full, + /// Decode only the specified sorted column indices from the file. + Columns(Vec), + /// No columns from this file are needed; only validated row counts are + /// required (empty `COUNT(*)` projection or all-missing nullable columns). + Empty, } -impl PartitionStream for StagingDiskPartition { - fn schema(&self) -> &SchemaRef { - &self.schema +/// Maps `projected_schema` field names to sorted column indices in `file_schema` +/// in O(N + M) time using a single name-to-index map. +fn ipc_projection_for_file(file_schema: &Schema, projected_schema: &Schema) -> IpcProjection { + if projected_schema.fields().is_empty() { + return IpcProjection::Empty; + } + let mut file_indices = HashMap::with_capacity(file_schema.fields().len()); + for (idx, field) in file_schema.fields().iter().enumerate() { + if file_indices.insert(field.name().as_str(), idx).is_some() { + return IpcProjection::Full; + } + } + let mut indices = Vec::with_capacity(projected_schema.fields().len()); + for field in projected_schema.fields() { + if let Some(&idx) = file_indices.get(field.name().as_str()) { + indices.push(idx); + } + } + if indices.is_empty() { + return IpcProjection::Empty; } + indices.sort_unstable(); + indices.dedup(); + if indices.len() == file_schema.fields().len() { + return IpcProjection::Full; + } + IpcProjection::Columns(indices) +} - fn execute(&self, _ctx: Arc) -> SendableRecordBatchStream { - let mut builder = RecordBatchReceiverStream::builder(self.schema.clone(), 2); - let tx = builder.tx(); - let sources = self.sources.clone(); - let schema = self.schema.clone(); - builder.spawn_blocking(move || { - let mut adapter = BatchAdapter::new(schema); - 'sources: for source in sources { - let reader = source.reader(true).map_err(|err| { - DataFusionError::Execution(format!("Cannot read staging rows: {err}")) - })?; - for batch in reader { - let batch = batch.map_err(|err| { - DataFusionError::Execution(format!( - "Cannot read staging rows: {}", - source.decode_error(err) - )) - })?; - let batch = adapter.adapt(&batch).map_err(|err| { - DataFusionError::Execution(format!( - "staged rows in {:?} do not fit the stream schema: {err}", - source.path() - )) - })?; - // Newest rows first, like the in-memory staging scan. - let batch = if batch.num_rows() > 1 && batch.num_columns() > 0 { - crate::utils::arrow::reverse(&batch) - } else { - batch - }; - if tx.blocking_send(Ok(batch)).is_err() { - // The query was cancelled or finished early. - break 'sources; - } - } +/// Validates that a staged file's full schema adapts cleanly into the stream's +/// full `table_schema`, ensuring full, narrow, and empty (`COUNT(*)`) +/// projections fail closed identically on incompatible types or missing +/// non-nullable fields. +fn validate_file_schema_for_table( + table_schema: &SchemaRef, + file_schema: &SchemaRef, + has_rows: bool, + path: &std::path::Path, +) -> Result<(), String> { + let mut full_adapter = BatchAdapter::new(table_schema.clone()); + let empty = RecordBatch::new_empty(file_schema.clone()); + full_adapter.adapt(&empty).map(|_| ()).map_err(|err| { + format!( + "staged rows in {:?} do not fit the stream schema: {err}", + path + ) + })?; + if has_rows { + let file_fields: std::collections::HashSet<&str> = file_schema + .fields() + .iter() + .map(|f| f.name().as_str()) + .collect(); + for field in table_schema.fields() { + if !field.is_nullable() && !file_fields.contains(field.name().as_str()) { + return Err(format!( + "staged rows in {:?} do not fit the stream schema: missing non-nullable column \"{}\"", + path, + field.name() + )); } - Ok(()) - }); - builder.build() + } } + Ok(()) } -fn projected_reversed_mem_table( - mut records: Vec, - mut schema: SchemaRef, - projection: Option<&Vec>, - filters: &[Expr], - target_partitions: usize, -) -> DataFusionResult<(MemTable, Option>)> { - let mut mem_projection = projection.cloned(); - if let Some(projection) = projection { - let mut needed = projection.clone(); - for column in filters.iter().flat_map(Expr::column_refs) { - needed.push(schema.index_of(&column.name)?); - } - needed.sort_unstable(); - needed.dedup(); - - if !needed.iter().copied().eq(0..schema.fields().len()) { - schema = Arc::new(schema.project(&needed)?); - // Arrow projects by cloning column references. Only columns that - // survive this step enter the reverse/take kernel. - for batch in &mut records { - *batch = batch.project(&needed)?; - } - mem_projection = Some( - projection - .iter() - .map(|index| { - needed - .binary_search(index) - .expect("projected column is retained") - }) - .collect(), - ); - } +/// Sums validated per-batch row counts with checked arithmetic so a corrupt +/// IPC header never overflows or allocates upfront. +fn checked_total_rows( + messages: &[crate::parseable::staging::reader::ValidatedIpcMessage], + path: &std::path::Path, +) -> Result { + let mut total = 0u64; + for rows in messages.iter().filter_map(|m| m.rows) { + let rows = u64::try_from(rows).map_err(|_| { + format!( + "Cannot read staging rows: staging file {:?} has invalid batch row count {rows}", + path + ) + })?; + total = total.checked_add(rows).ok_or_else(|| { + format!( + "Cannot read staging rows: staging file {:?} row count overflowed", + path + ) + })?; } - - let table = partitioned_reversed_mem_table(records, schema, target_partitions)?; - Ok((table, mem_projection)) + Ok(total) } -fn partitioned_reversed_mem_table( - records: Vec, - schema: SchemaRef, - target_partitions: usize, -) -> DataFusionResult { - let partition_count = target_partitions.clamp(1, records.len().max(1)); - let batches_per_partition = records.len() / partition_count; - let extra_batches = records.len() % partition_count; - let mut reversed = records.into_iter().rev().map(|batch| { - // A zero-column projection still represents all of its original rows. - if batch.num_columns() == 0 { - batch - } else { - crate::utils::arrow::reverse(&batch) - } - }); - let partitions = (0..partition_count) - .map(|index| { - reversed - .by_ref() - .take(batches_per_partition + usize::from(index < extra_batches)) - .collect() - }) - .collect(); - MemTable::try_new(schema, partitions) +/// Sets a cancellation flag if an async planning future is dropped before its +/// blocking indexing task finishes. +struct CancelOnDrop(Arc); + +impl Drop for CancelOnDrop { + fn drop(&mut self) { + self.0.store(true, std::sync::atomic::Ordering::Relaxed); + } } +/// Compiled deterministic predicate evaluated against a narrow column subset +/// during two-phase filter-first Arrow IPC decoding on disk-backed staging files. #[derive(Debug, Clone)] -pub enum PartialTimeFilter { - Low(Bound), - High(Bound), - Eq(NaiveDateTime), +struct StagingTwoPhaseFilter { + filter_schema: SchemaRef, + predicate: Arc, } -impl PartialTimeFilter { - pub fn try_from_expr(expr: &Expr, time_partition: &Option) -> Option { - let Expr::BinaryExpr(binexpr) = expr else { - return None; - }; - - // Manifests (and staging/listing prefixes) are bucketed by the stream's - // time partition column, or `p_timestamp` when none is configured. A - // bound on any other column, including `p_timestamp` on a stream with a - // custom time partition, says nothing about which manifests hold - // matching rows and must not be used to prune them. - let partition_column = time_partition.as_deref().unwrap_or(DEFAULT_TIMESTAMP_KEY); - let Expr::Column(column) = binexpr.left.as_ref() else { - return None; - }; - if column.name != partition_column { - return None; - } - let (op, time) = extract_timestamp_bound(binexpr, time_partition)?; - let value = match op { - Operator::Gt => PartialTimeFilter::Low(Bound::Excluded(time)), - Operator::GtEq => PartialTimeFilter::Low(Bound::Included(time)), - Operator::Lt => PartialTimeFilter::High(Bound::Excluded(time)), - Operator::LtEq => PartialTimeFilter::High(Bound::Included(time)), - Operator::Eq => PartialTimeFilter::Eq(time), - Operator::IsNotDistinctFrom => PartialTimeFilter::Eq(time), - _ => return None, - }; - Some(value) - } +/// Minimum projected column count before two-phase filter-first IPC decoding is +/// used (avoids extra setup when only 1–3 columns are projected anyway). +const STAGING_TWO_PHASE_MIN_OUTPUT_COLUMNS: usize = 4; + +fn is_non_throwing_comparison_type(data_type: &arrow_schema::DataType) -> bool { + use arrow_schema::DataType; + 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::Decimal32(_, _) + | DataType::Decimal64(_, _) + | DataType::Decimal128(_, _) + | DataType::Decimal256(_, _) + | DataType::Date32 + | DataType::Date64 + | DataType::Time32(_) + | DataType::Time64(_) + | DataType::Timestamp(_, _) + | DataType::Duration(_) + | DataType::Utf8 + | DataType::LargeUtf8 + | DataType::Utf8View + | DataType::Binary + | DataType::LargeBinary + | DataType::BinaryView + ) +} - pub fn binary_expr(&self, left: Expr) -> Expr { - let (op, right) = match self { - PartialTimeFilter::Low(Bound::Excluded(time)) => { - (Operator::Gt, time.and_utc().timestamp_millis()) - } - PartialTimeFilter::Low(Bound::Included(time)) => { - (Operator::GtEq, time.and_utc().timestamp_millis()) +/// Returns `true` ONLY for provably non-throwing predicates safe to evaluate +/// before other short-circuiting query filters during two-phase staging decode: +/// - `And`, `Or`, `Not` +/// - `IsNull(Column)`, `IsNotNull(Column)` +/// - `InList` over a `Column` where every list item is a `Literal` with the +/// exact same `DataType` as the column in `projected_schema` +/// - `BinaryExpr` (`Eq`, `NotEq`, `Lt`, `LtEq`, `Gt`, `GtEq`, +/// `IsDistinctFrom`, `IsNotDistinctFrom`) between a `Column` and a `Literal` +/// of the exact same `DataType` as the column in `projected_schema`. +/// +/// Rejects `Cast`, `TryCast`, arithmetic, `Like`/regex, and all +/// `ScalarFunction`s so Phase 1 can never throw an error on a row that another +/// predicate would have excluded. +fn is_provably_non_throwing_staging_filter(expr: &Expr, projected_schema: &Schema) -> bool { + match expr { + Expr::BinaryExpr(bin) => match bin.op { + Operator::And | Operator::Or => { + is_provably_non_throwing_staging_filter(&bin.left, projected_schema) + && is_provably_non_throwing_staging_filter(&bin.right, projected_schema) } - PartialTimeFilter::High(Bound::Excluded(time)) => { - (Operator::Lt, time.and_utc().timestamp_millis()) + Operator::Eq + | Operator::NotEq + | Operator::Lt + | Operator::LtEq + | Operator::Gt + | Operator::GtEq + | Operator::IsDistinctFrom + | Operator::IsNotDistinctFrom => { + let Some((column, literal)) = (match (bin.left.as_ref(), bin.right.as_ref()) { + (Expr::Column(c), Expr::Literal(lit, _)) + | (Expr::Literal(lit, _), Expr::Column(c)) => Some((c, lit)), + _ => None, + }) else { + return false; + }; + let Ok(field) = projected_schema.field_with_name(&column.name) else { + return false; + }; + is_non_throwing_comparison_type(field.data_type()) + && literal.data_type() == *field.data_type() } - PartialTimeFilter::High(Bound::Included(time)) => { - (Operator::LtEq, time.and_utc().timestamp_millis()) + _ => false, + }, + Expr::Not(inner) => is_provably_non_throwing_staging_filter(inner, projected_schema), + Expr::IsNull(inner) | Expr::IsNotNull(inner) => { + matches!(inner.as_ref(), Expr::Column(c) if projected_schema.field_with_name(&c.name).is_ok()) + } + Expr::InList(in_list) => { + let Expr::Column(column) = in_list.expr.as_ref() else { + return false; + }; + let Ok(field) = projected_schema.field_with_name(&column.name) else { + return false; + }; + if !is_non_throwing_comparison_type(field.data_type()) { + return false; } - PartialTimeFilter::Eq(time) => (Operator::Eq, time.and_utc().timestamp_millis()), - _ => unimplemented!(), - }; + in_list.list.iter().all(|item| { + matches!(item, Expr::Literal(lit, _) if lit.data_type() == *field.data_type()) + }) + } + _ => false, + } +} - Expr::BinaryExpr(BinaryExpr::new( - Box::new(left), - op, - Box::new(Expr::Literal( - ScalarValue::TimestampMillisecond(Some(right), None), - None, - )), - )) +fn collect_top_level_conjuncts<'a>(expr: &'a Expr, out: &mut Vec<&'a Expr>) { + if let Expr::BinaryExpr(bin) = expr + && bin.op == Operator::And + { + collect_top_level_conjuncts(&bin.left, out); + collect_top_level_conjuncts(&bin.right, out); + } else { + out.push(expr); } } -fn is_overlapping_query( - manifest_list: &[ManifestItem], - time_filters: &[PartialTimeFilter], -) -> bool { - // This is for backwards compatiblity. Older table format relies on listing. - // if the start time is lower than lower bound of first file then we consider it overlapping - let Some(first_entry_lower_bound) = - manifest_list.iter().map(|file| file.time_lower_bound).min() - else { - return true; - }; +fn build_staging_two_phase_filter( + projected_schema: &SchemaRef, + filters: &[Expr], + state: &dyn Session, +) -> Option { + if filters.is_empty() || projected_schema.fields().len() < STAGING_TWO_PHASE_MIN_OUTPUT_COLUMNS + { + return None; + } + let mut conjuncts = Vec::new(); + for filter in filters { + collect_top_level_conjuncts(filter, &mut conjuncts); + } + let safe_filters: Vec = conjuncts + .into_iter() + .filter(|expr| is_provably_non_throwing_staging_filter(expr, projected_schema)) + .cloned() + .collect(); + if safe_filters.is_empty() { + return None; + } + let mut pred_indices = Vec::new(); + for column in safe_filters.iter().flat_map(Expr::column_refs) { + let idx = projected_schema.index_of(&column.name).ok()?; + pred_indices.push(idx); + } + pred_indices.sort_unstable(); + pred_indices.dedup(); + if pred_indices.is_empty() || pred_indices.len() >= projected_schema.fields().len() { + return None; + } + let filter_schema = Arc::new(projected_schema.project(&pred_indices).ok()?); + let expr = conjunction(safe_filters)?; + let df_schema = filter_schema.as_ref().clone().to_dfschema().ok()?; + let predicate = create_physical_expr( + &expr, + &df_schema, + state.execution_props(), + &PhysicalPlanningContext::default(), + ) + .ok()?; + Some(StagingTwoPhaseFilter { + filter_schema, + predicate, + }) +} - for filter in time_filters { - match filter { - PartialTimeFilter::Low(Bound::Excluded(time)) - | PartialTimeFilter::Low(Bound::Included(time)) - if time < &first_entry_lower_bound.naive_utc() => - { - return true; +/// Resolves sorted unique `(filter_indices, output_indices)` in `file_schema` +/// for two-phase filter-first IPC decoding. Returns `None` if `file_schema` +/// contains duplicate column names, if any projected column narrows +/// nullability (`file_field.is_nullable() && !table_field.is_nullable()`), or +/// if two-phase decoding would not skip any payload columns for this file. +fn two_phase_file_indices( + file_schema: &Schema, + filter_schema: &Schema, + projected_schema: &Schema, +) -> Option<(Vec, Vec)> { + let mut file_indices = HashMap::with_capacity(file_schema.fields().len()); + for (idx, field) in file_schema.fields().iter().enumerate() { + if file_indices.insert(field.name().as_str(), idx).is_some() { + return None; + } + } + let mut filter_cols = Vec::with_capacity(filter_schema.fields().len()); + for field in filter_schema.fields() { + if let Some(&idx) = file_indices.get(field.name().as_str()) { + filter_cols.push(idx); + } + } + filter_cols.sort_unstable(); + filter_cols.dedup(); + if filter_cols.is_empty() { + return None; + } + let mut output_cols = Vec::with_capacity(projected_schema.fields().len()); + for field in projected_schema.fields() { + if let Some(&idx) = file_indices.get(field.name().as_str()) { + // Skipping Phase 2 on zero-match batches would hide NULL values in + // a nullable file column that narrows into a non-nullable table + // column; disable two-phase decoding so BatchAdapter fails closed. + if file_schema.field(idx).is_nullable() && !field.is_nullable() { + return None; } - _ => {} + output_cols.push(idx); } } + output_cols.sort_unstable(); + output_cols.dedup(); + if output_cols.len() < STAGING_TWO_PHASE_MIN_OUTPUT_COLUMNS + || filter_cols.len() >= output_cols.len() + { + return None; + } + Some((filter_cols, output_cols)) +} - false +#[derive(Debug, Clone)] +enum StagingDiskWork { + Failed(String), + /// Planned lazily during execution (used for limited queries so `LIMIT 1` + /// never scans cold trailing files upfront). + LazySource(StagingDiskSource), + RowCounts { + source: StagingDiskSource, + total_rows: u64, + }, + Ranges { + source: StagingDiskSource, + ranges: Arc<[(u64, usize)]>, + ipc_projection: Option>, + byte_weight: usize, + }, + TwoPhaseRanges { + source: StagingDiskSource, + ranges: Arc<[(u64, usize)]>, + filter_indices: Vec, + output_indices: Vec, + byte_weight: usize, + }, } -/// This function will accept time filters provided to the query and will split them -/// into listing time filters and manifest time filters -/// This makes parseable backwards compatible for when it did not have manifests -/// Logic- -/// The control flow will only come to this function if there exists data without manifest files -/// Two new time filter vec![] are created -/// For listing table time filters, we will use OG time filter low bound and either OG time filter upper bound -/// or manifest lower bound -/// For manifest time filter, we will manifest lower bound and OG upper bound -fn return_listing_time_filters( - manifest_list: &[ManifestItem], - time_filters: &mut Vec, -) -> Option> { - if manifest_list.is_empty() { - return Some(time_filters.clone()); +impl StagingDiskWork { + fn byte_weight(&self) -> usize { + match self { + Self::Failed(_) => 0, + Self::LazySource(source) => { + usize::try_from(source.len().saturating_sub(source.start())).unwrap_or(usize::MAX) + } + Self::RowCounts { total_rows, .. } => { + usize::try_from(*total_rows).unwrap_or(usize::MAX) + } + Self::Ranges { byte_weight, .. } | Self::TwoPhaseRanges { byte_weight, .. } => { + *byte_weight + } + } } +} - // vec to hold timestamps for listing - let mut vec_listing_timestamps = Vec::new(); - - let mut first_entry_lower_bound = manifest_list - .iter() - .map(|file| file.time_lower_bound.naive_utc()) - .min()?; +/// Splits `messages` into up to `splits` contiguous byte-balanced slices. +fn split_ipc_messages_by_bytes( + messages: &[crate::parseable::staging::reader::ValidatedIpcMessage], + splits: usize, +) -> Vec> { + let splits = splits.max(1).min(messages.len()); + if splits <= 1 { + return vec![messages.iter().map(|m| (m.offset, m.size)).collect()]; + } + let total_bytes: usize = messages.iter().map(|m| m.size).sum(); + let target_per_chunk = total_bytes.div_ceil(splits).max(1); + let mut chunks = Vec::with_capacity(splits); + let mut current = Vec::new(); + let mut current_bytes = 0usize; + for (idx, msg) in messages.iter().enumerate() { + let remaining_msgs = messages.len() - idx; + let remaining_slots = splits - chunks.len(); + // Close the current chunk once it reached the byte target, while + // leaving at least one message for each remaining slot. + if !current.is_empty() + && remaining_slots > 1 + && (current_bytes >= target_per_chunk || remaining_msgs < remaining_slots) + { + chunks.push(std::mem::take(&mut current)); + current_bytes = 0; + } + current.push((msg.offset, msg.size)); + current_bytes = current_bytes.saturating_add(msg.size); + } + if !current.is_empty() { + chunks.push(current); + } + chunks +} - let mut new_time_filters = vec![PartialTimeFilter::Low(Bound::Included( - first_entry_lower_bound, - ))]; +/// 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 +/// across DataFusion partitions when unlimited. +async fn staging_disk_plan( + schema: SchemaRef, + sources: Vec, + state: &dyn Session, + projection: Option<&Vec>, + filters: &[Expr], + limit: Option, +) -> DataFusionResult>> { + if sources.is_empty() { + return Ok(None); + } + let needed_proj = needed_column_projection(&schema, projection, filters)?; + let projected_schema = needed_proj.schema; + let disk_projection = needed_proj.remapped_projection; + let reverse_rows = limit.is_some(); + let batch_size = usize::from(state.config_options().execution.batch_size).clamp(1, 65_536); + let two_phase_filter = build_staging_two_phase_filter(&projected_schema, filters, state); + + // Limited queries stay single-partition and plan each file lazily during + // execution so `LIMIT N` stops as soon as the newest files satisfy the + // fetch without indexing trailing cold files upfront. + if reverse_rows { + let partition = Arc::new(StagingDiskPartition { + table_schema: schema, + schema: projected_schema.clone(), + work: sources + .into_iter() + .map(StagingDiskWork::LazySource) + .collect(), + reverse_rows: true, + batch_size, + two_phase_filter, + }) as Arc; + let table = StreamingTable::try_new(projected_schema, vec![partition])?; + return scan_enforcing_exact_filters( + &table, + state, + disk_projection.as_ref(), + filters, + limit, + ) + .await + .map(Some); + } - time_filters.iter_mut().for_each(|filter| { - match filter { - // since we've already determined that there is a need to list tables, - // we just need to check whether the filter's upper bound is < manifest lower bound - PartialTimeFilter::High(Bound::Included(upper)) - | PartialTimeFilter::High(Bound::Excluded(upper)) => { - if upper.lt(&&mut first_entry_lower_bound) { - // filter upper bound is less than manifest lower bound, continue using filter upper bound - vec_listing_timestamps.push(filter.clone()); - } else { - // use manifest lower bound as excluded - vec_listing_timestamps.push(PartialTimeFilter::High(Bound::Excluded( - first_entry_lower_bound, + let max_partitions = state + .config_options() + .execution + .target_partitions + .min(num_cpus::get()) + .max(1); + + let cancel_flag = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let _cancel_guard = CancelOnDrop(Arc::clone(&cancel_flag)); + 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 mut units = Vec::with_capacity(sources.len()); + 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; } - new_time_filters.push(filter.clone()); + }; + if !plan.messages.iter().any(|m| m.rows.is_some()) { + continue; } - _ => { - vec_listing_timestamps.push(filter.clone()); + let has_rows = 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(), + ) { + units.push(StagingDiskWork::Failed(err)); + continue; } - } - }); - - // update time_filters - *time_filters = new_time_filters; + 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 => { + units.push(StagingDiskWork::RowCounts { source, total_rows }); + } + Ok(_) => {} + Err(err) => units.push(StagingDiskWork::Failed(err)), + } + continue; + } + IpcProjection::Full => None, + IpcProjection::Columns(cols) => Some(cols), + }; - if vec_listing_timestamps.len().gt(&0) { - Some(vec_listing_timestamps) - } else { - None - } -} + 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 + }; -/// We should consider data in staging for queries concerning a time period, -/// ending within 5 minutes from now. e.g. If current time is 5 -pub fn is_within_staging_window(time_filters: &[PartialTimeFilter]) -> bool { - let five_minutes_back = (Utc::now() - TimeDelta::minutes(5)) - .with_second(0) - .and_then(|x| x.with_nanosecond(0)) - .expect("zeroed value is valid") - .naive_utc(); + let mut messages = plan.messages; + // Dictionary-encoded streams keep forward IPC order so dictionary + // definitions precede the batches referencing them. + if !plan.has_dictionaries { + messages.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 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 { + source: source.clone(), + ranges: Arc::from(ranges), + filter_indices: filter_indices.clone(), + output_indices: output_indices.clone(), + byte_weight, + }); + } else { + units.push(StagingDiskWork::Ranges { + source: source.clone(), + ranges: Arc::from(ranges), + ipc_projection: ipc_projection.clone(), + byte_weight, + }); + } + } + } + units + }) + .await + .map_err(|err| DataFusionError::Execution(format!("Staging disk planning failed: {err}")))?; - if time_filters.iter().any(|filter| match filter { - PartialTimeFilter::High(Bound::Excluded(time)) - | PartialTimeFilter::High(Bound::Included(time)) - | PartialTimeFilter::Eq(time) => time >= &five_minutes_back, - _ => false, - }) { - return true; + if work_units.is_empty() { + return Ok(None); } - // does it even have a higher bound - let has_upper_bound = time_filters - .iter() - .any(|filter| matches!(filter, PartialTimeFilter::High(_))); + 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); + } + } - !has_upper_bound + 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) } -/// How `StandardTableProvider` can handle `filter`. -/// -/// Data files hold one minute of the stream's time partition column, so a -/// minute-aligned bound on that column either keeps or prunes each file whole. -/// Only then is the filter `Exact`: DataFusion drops the `FilterExec` above the -/// scan and may push `LIMIT` into it, and `collect_from_snapshot` truncates the -/// file list by row counts assuming every row of a surviving file matches. A -/// bound on any other column (including `p_timestamp` on a stream with a custom -/// time partition) only prunes files partially, so it stays `Inexact`. -fn filter_pushdown(filter: &Expr, time_partition: &Option) -> TableProviderFilterPushDown { - let partition_column = time_partition.as_deref().unwrap_or(DEFAULT_TIMESTAMP_KEY); - let is_partition_column = matches!( - filter, - Expr::BinaryExpr(BinaryExpr { left, .. }) - if matches!(left.as_ref(), Expr::Column(column) if column.name == partition_column) - ); - if is_partition_column && expr_in_boundary(filter) { - TableProviderFilterPushDown::Exact - } else { - // File level mechanisms such as Parquet row group pruning may still apply. - TableProviderFilterPushDown::Inexact +/// Emits lazy row-count-only batches (for `COUNT(*)` or all-missing nullable +/// projections) after re-verifying the file's length at execution time. +/// Returns `Ok(false)` if the receiver dropped (cancelled or `LIMIT` reached). +fn emit_row_count_batches( + source: &StagingDiskSource, + mut remaining_rows: u64, + batch_size: usize, + schema: &SchemaRef, + empty_schema: &SchemaRef, + adapter: &mut BatchAdapter, + tx: &tokio::sync::mpsc::Sender>, +) -> DataFusionResult { + source + .validate_file_len() + .map_err(|err| DataFusionError::Execution(format!("Cannot read staging rows: {err}")))?; + let chunk_cap = u64::try_from(batch_size.max(1)).unwrap_or(u64::MAX); + while remaining_rows > 0 { + let rows = remaining_rows.min(chunk_cap) as usize; + remaining_rows -= rows as u64; + let options = arrow_array::RecordBatchOptions::new().with_row_count(Some(rows)); + let batch = if schema.fields().is_empty() { + RecordBatch::try_new_with_options(schema.clone(), vec![], &options) + .map_err(DataFusionError::from)? + } else { + let empty = RecordBatch::try_new_with_options(empty_schema.clone(), vec![], &options) + .map_err(DataFusionError::from)?; + adapter.adapt(&empty).map_err(|err| { + DataFusionError::Execution(format!( + "staged rows in {:?} do not fit the stream schema: {err}", + source.path() + )) + })? + }; + if tx.blocking_send(Ok(batch)).is_err() { + return Ok(false); + } } + Ok(true) } -pub fn expr_in_boundary(filter: &Expr) -> bool { - let Expr::BinaryExpr(binexpr) = filter else { - return false; - }; - let Some((op, time)) = extract_timestamp_bound(binexpr, &None) else { - return false; - }; - - // this is due to knowlege of prefixes being minute long always. - // Without a consistent partition spec this cannot be guarenteed. - time.second() == 0 - && time.nanosecond() == 0 - && matches!( - op, - Operator::Gt | Operator::GtEq | Operator::Lt | Operator::LtEq +/// Decodes and emits pre-validated IPC message ranges for a single file slice. +/// Returns `Ok(false)` if the receiver dropped (cancelled or `LIMIT` reached). +fn emit_range_batches( + source: &StagingDiskSource, + ranges: Arc<[(u64, usize)]>, + ipc_projection: Option>, + reverse_rows: bool, + adapter: &mut BatchAdapter, + tx: &tokio::sync::mpsc::Sender>, +) -> DataFusionResult { + let reader = source + .reader_for_ranges( + ranges, + ipc_projection, + STAGING_DISK_PARTITION_READ_BUFFER_BYTES, ) -} - -pub fn extract_timestamp_bound( - binexpr: &BinaryExpr, - time_partition: &Option, -) -> Option<(Operator, NaiveDateTime)> { - let Expr::Literal(value, None) = binexpr.right.as_ref() else { - return None; - }; - - let is_time_partition = match (binexpr.left.as_ref(), time_partition) { - (Expr::Column(column), Some(time_partition)) => &column.name == time_partition, - _ => false, - }; - - match value { - // Out-of-range literals (reachable from SQL, e.g. - // `to_timestamp_millis(9223372036854775807)`) yield no bound. - ScalarValue::TimestampMillisecond(Some(value), _) => { - DateTime::from_timestamp_millis(*value).map(|time| (binexpr.op, time.naive_utc())) + .map_err(|err| DataFusionError::Execution(format!("Cannot read staging rows: {err}")))?; + for batch in reader { + if tx.is_closed() { + return Ok(false); } - ScalarValue::TimestampNanosecond(Some(value), _) => Some(( - binexpr.op, - DateTime::from_timestamp_nanos(*value).naive_utc(), - )), - ScalarValue::Utf8(Some(str_value)) if is_time_partition => { - match str_value.parse::() { - Ok(dt) => Some((binexpr.op, dt)), - Err(_) => None, - } + let batch = batch.map_err(|err| { + DataFusionError::Execution(format!( + "Cannot read staging rows: {}", + source.decode_error(err) + )) + })?; + let batch = adapter.adapt(&batch).map_err(|err| { + DataFusionError::Execution(format!( + "staged rows in {:?} do not fit the stream schema: {err}", + source.path() + )) + })?; + // Preserve newest-row-first order for limited scans without an explicit + // ORDER BY; unlimited scans run across parallel partitions where + // DataFusion owns any requested SQL ordering. + let batch = if reverse_rows && batch.num_rows() > 1 && batch.num_columns() > 0 { + crate::utils::arrow::reverse(&batch) + } else { + batch + }; + if tx.blocking_send(Ok(batch)).is_err() { + return Ok(false); } - _ => None, } + Ok(true) } -// Extract start time and end time from filter predicate -pub fn extract_primary_filter( - filters: &[Expr], - time_partition: &Option, -) -> Vec { - filters - .iter() - .filter_map(|expr| { - let mut time_filter = None; - let _ = expr.apply(&mut |expr| { - if let Some(time) = PartialTimeFilter::try_from_expr(expr, time_partition) { - time_filter = Some(time); - Ok(TreeNodeRecursion::Stop) // Stop further traversal - } else { - Ok(TreeNodeRecursion::Jump) // Skip this node - } - }); - time_filter - }) - .collect() -} - -pub trait ManifestExt: ManifestFile { - fn find_matching_column(&self, partial_filter: &Expr) -> Option<&Column> { - let name = match partial_filter { - Expr::BinaryExpr(binary_expr) => { - let Expr::Column(col) = binary_expr.left.as_ref() else { - return None; - }; - &col.name +/// Decodes pre-validated non-dictionary IPC ranges in two phases: filter +/// columns first, skipping payload column decompression when a batch has zero +/// matching rows. Returns `Ok(false)` if the receiver dropped. +#[allow(clippy::too_many_arguments)] +fn emit_two_phase_range_batches( + source: &StagingDiskSource, + ranges: Arc<[(u64, usize)]>, + filter_indices: Vec, + output_indices: Vec, + two_phase: &StagingTwoPhaseFilter, + reverse_rows: bool, + adapter: &mut BatchAdapter, + tx: &tokio::sync::mpsc::Sender>, +) -> DataFusionResult { + let mut filter_adapter = BatchAdapter::new(two_phase.filter_schema.clone()); + let predicate = Arc::clone(&two_phase.predicate); + let path_for_err = source.path().to_path_buf(); + let reader = source + .two_phase_filtered_reader( + ranges, + filter_indices, + output_indices, + move |filter_batch| { + let adapted = filter_adapter.adapt(filter_batch).map_err(|err| { + DataFusionError::Execution(format!( + "staged rows in {:?} do not fit the stream schema: {err}", + path_for_err + )) + })?; + let eval = predicate.evaluate(&adapted)?; + let array = eval.into_array(adapted.num_rows())?; + let mask = array + .as_any() + .downcast_ref::() + .ok_or_else(|| { + DataFusionError::Execution(format!( + "staging two-phase filter evaluated to non-boolean type {}", + array.data_type() + )) + })?; + Ok::<_, DataFusionError>(mask.clone()) + }, + ) + .map_err(|err| DataFusionError::Execution(format!("Cannot read staging rows: {err}")))? + .with_cancel_check({ + let tx_cancel = tx.clone(); + move || tx_cancel.is_closed() + }); + for batch in reader { + let batch = batch.map_err(|err| match err { + crate::parseable::staging::reader::TwoPhaseReadError::Io(io_err) => { + DataFusionError::Execution(format!( + "Cannot read staging rows: staging file {:?}: {io_err}", + source.path() + )) } - _ => { - return None; + crate::parseable::staging::reader::TwoPhaseReadError::Arrow(arrow_err) => { + DataFusionError::Execution(format!( + "Cannot read staging rows: {}", + source.decode_error(arrow_err) + )) } + crate::parseable::staging::reader::TwoPhaseReadError::Filter(df_err) => df_err, + })?; + let batch = adapter.adapt(&batch).map_err(|err| { + DataFusionError::Execution(format!( + "staged rows in {:?} do not fit the stream schema: {err}", + source.path() + )) + })?; + let batch = if reverse_rows && batch.num_rows() > 1 && batch.num_columns() > 0 { + crate::utils::arrow::reverse(&batch) + } else { + batch }; - - self.columns().iter().find(|col| &col.name == name) - } - - fn can_be_pruned(&self, partial_filter: &Expr) -> bool { - fn extract_op_scalar(expr: &Expr) -> Option<(Operator, &ScalarValue)> { - let Expr::BinaryExpr(expr) = expr else { - return None; - }; - let Expr::Literal(value, None) = &*expr.right else { - return None; - }; - /* `BinaryExp` doesn't implement `Copy` */ - Some((expr.op, value)) + if tx.blocking_send(Ok(batch)).is_err() { + return Ok(false); } - - let Some(col) = self.find_matching_column(partial_filter) else { - return false; - }; - - let Some((op, value)) = extract_op_scalar(partial_filter) else { - return false; - }; - - let Some(value) = cast_or_none(value) else { - return false; - }; - - let Some(stats) = &col.stats else { - return false; - }; - - !satisfy_constraints(value, op, stats).unwrap_or(true) } + Ok(true) } -impl ManifestExt for T {} - -enum CastRes<'a> { - Bool(bool), - Int(i64), - Float(f64), - String(&'a str), +/// The acknowledged rows of one or more staging file slices, projected and +/// adapted to the scan's reduced schema. Any I/O or decode error fails closed. +#[derive(Debug)] +struct StagingDiskPartition { + table_schema: SchemaRef, + schema: SchemaRef, + work: Vec, + reverse_rows: bool, + batch_size: usize, + two_phase_filter: Option, } -fn cast_or_none(scalar: &ScalarValue) -> Option> { - match scalar { - ScalarValue::Null => None, - ScalarValue::Boolean(val) => val.map(CastRes::Bool), - ScalarValue::Float32(val) => val.map(|val| CastRes::Float(val as f64)), - ScalarValue::Float64(val) => val.map(CastRes::Float), - ScalarValue::Int8(val) => val.map(|val| CastRes::Int(val as i64)), - ScalarValue::Int16(val) => val.map(|val| CastRes::Int(val as i64)), - ScalarValue::Int32(val) => val.map(|val| CastRes::Int(val as i64)), - ScalarValue::Int64(val) => val.map(CastRes::Int), - ScalarValue::UInt8(val) => val.map(|val| CastRes::Int(val as i64)), - ScalarValue::UInt16(val) => val.map(|val| CastRes::Int(val as i64)), - ScalarValue::UInt32(val) => val.map(|val| CastRes::Int(val as i64)), - ScalarValue::UInt64(val) => val.map(|val| CastRes::Int(val as i64)), - ScalarValue::Utf8(val) => val.as_ref().map(|val| CastRes::String(val)), - ScalarValue::Date32(val) => val.map(|val| CastRes::Int(val as i64)), - ScalarValue::TimestampMillisecond(val, _) => val.map(CastRes::Int), - _ => None, +impl PartitionStream for StagingDiskPartition { + fn schema(&self) -> &SchemaRef { + &self.schema + } + + fn execute(&self, _ctx: Arc) -> SendableRecordBatchStream { + let mut builder = RecordBatchReceiverStream::builder(self.schema.clone(), 2); + let tx = builder.tx(); + let work = self.work.clone(); + let table_schema = self.table_schema.clone(); + let schema = self.schema.clone(); + let reverse_rows = self.reverse_rows; + let batch_size = self.batch_size; + let two_phase_filter = self.two_phase_filter.clone(); + builder.spawn_blocking(move || { + let empty_schema = Arc::new(Schema::empty()); + let mut adapter = BatchAdapter::new(schema.clone()); + for unit in work { + if tx.is_closed() { + break; + } + let keep_going = match unit { + StagingDiskWork::Failed(err) => { + return Err(DataFusionError::Execution(err)); + } + StagingDiskWork::LazySource(source) => { + let plan = source.plan_prefix().map_err(|err| { + DataFusionError::Execution(format!("Cannot read staging rows: {err}")) + })?; + if !plan.messages.iter().any(|m| m.rows.is_some()) { + continue; + } + let has_rows = plan.messages.iter().any(|m| m.rows.is_some_and(|r| r > 0)); + validate_file_schema_for_table( + &table_schema, + &plan.schema, + has_rows, + source.path(), + ) + .map_err(DataFusionError::Execution)?; + match ipc_projection_for_file(&plan.schema, &schema) { + IpcProjection::Empty => { + let total_rows = checked_total_rows(&plan.messages, source.path()) + .map_err(DataFusionError::Execution)?; + emit_row_count_batches( + &source, + total_rows, + batch_size, + &schema, + &empty_schema, + &mut adapter, + &tx, + )? + } + proj @ (IpcProjection::Full | IpcProjection::Columns(_)) => { + let ipc_projection = match proj { + IpcProjection::Full => None, + IpcProjection::Columns(cols) => Some(cols), + IpcProjection::Empty => unreachable!(), + }; + let two_phase_cols = if !plan.has_dictionaries { + two_phase_filter.as_ref().and_then(|tp| { + two_phase_file_indices( + &plan.schema, + &tp.filter_schema, + &schema, + ) + }) + } else { + None + }; + let mut messages = plan.messages; + // Dictionary-encoded streams keep forward IPC order so + // dictionary definitions precede referencing batches. + if !plan.has_dictionaries { + messages.reverse(); + } + let mut ranges = Vec::with_capacity(messages.len() + 1); + ranges.push(plan.schema_range); + ranges.extend(messages.into_iter().map(|m| (m.offset, m.size))); + if let (Some(tp), Some((filter_indices, output_indices))) = + (two_phase_filter.as_ref(), two_phase_cols) + { + emit_two_phase_range_batches( + &source, + Arc::from(ranges), + filter_indices, + output_indices, + tp, + reverse_rows, + &mut adapter, + &tx, + )? + } else { + emit_range_batches( + &source, + Arc::from(ranges), + ipc_projection, + reverse_rows, + &mut adapter, + &tx, + )? + } + } + } + } + StagingDiskWork::RowCounts { source, total_rows } => emit_row_count_batches( + &source, + total_rows, + batch_size, + &schema, + &empty_schema, + &mut adapter, + &tx, + )?, + StagingDiskWork::Ranges { + source, + ranges, + ipc_projection, + .. + } => emit_range_batches( + &source, + ranges, + ipc_projection, + reverse_rows, + &mut adapter, + &tx, + )?, + StagingDiskWork::TwoPhaseRanges { + source, + ranges, + filter_indices, + output_indices, + .. + } => { + let tp = two_phase_filter.as_ref().ok_or_else(|| { + DataFusionError::Internal( + "StagingDiskWork::TwoPhaseRanges requires two_phase_filter" + .to_string(), + ) + })?; + emit_two_phase_range_batches( + &source, + ranges, + filter_indices, + output_indices, + tp, + reverse_rows, + &mut adapter, + &tx, + )? + } + }; + if !keep_going { + // The query was cancelled or finished early. + break; + } + } + Ok(()) + }); + builder.build() } } -fn satisfy_constraints(value: CastRes, op: Operator, stats: &TypedStatistics) -> Option { - fn matches(value: T, min: T, max: T, op: Operator) -> Option { - let val = match op { - Operator::Eq | Operator::IsNotDistinctFrom => value >= min && value <= max, - Operator::Lt => value > min, - Operator::LtEq => value >= min, - Operator::Gt => value < max, - Operator::GtEq => value <= max, +/// Builds execution plans for captured staging sources (memory, disk IPC, and +/// staged Parquet files), omitting empty branches so `UnionExec` is never +/// inflated with empty scans or unknown statistics. +#[allow(clippy::too_many_arguments)] +async fn staging_execution_plans( + schema: &SchemaRef, + execution_plans: &mut Vec>, + projection: Option<&Vec>, + filters: &[Expr], + limit: Option, + state: &dyn Session, + captured: (StagingCapture, Vec), + batch_size: usize, +) -> Result<(), DataFusionError> { + // Both sources were captured before the remote snapshot was read. + let (staged, partitioned_files) = captured; + let StagingCapture { + memory: records, + disk: disk_sources, + } = 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 + } else { + state + .config_options() + .execution + .target_partitions + .min(num_cpus::get()) + }; + 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); + } + + // Rows the staging memory cache does not hold are streamed from the + // staging files captured with it, one partition per file. + if let Some(disk_exec) = staging_disk_plan( + schema.clone(), + disk_sources, + state, + projection, + filters, + limit, + ) + .await? + { + execution_plans.push(disk_exec); + } + + if !partitioned_files.is_empty() { + // Keep the native scan and its file extensions: each extension owns the + // hard-link lease through optimizer rewrites and execution streams. + let plan = parquet_scan_plan( + schema.clone(), + ObjectStoreUrl::parse("file:///").unwrap(), + vec![partitioned_files], + Statistics::new_unknown(schema), + projection, + filters, + limit, + state, + batch_size, + ) + .await?; + execution_plans.push(plan); + } + + Ok(()) +} + +/// Sums manifest `num_rows` with checked `u64` arithmetic so corrupt metadata +/// can never wrap or trigger oversized allocations. +fn checked_manifest_total_rows(files: &[File]) -> DataFusionResult { + files.iter().try_fold(0u64, |acc, file| { + acc.checked_add(file.num_rows).ok_or_else(|| { + DataFusionError::Execution("manifest interior row count overflowed u64".to_string()) + }) + }) +} + +/// Lazy zero-I/O `ExecutionPlan` that exposes `Precision::Exact(total_rows)` +/// in `partition_statistics` (so DataFusion's `AggregateStatistics` folds pure +/// all-interior `SELECT COUNT(*)` in O(1)) while still emitting lazy +/// `batch_size` empty batches in `execute()` for any consumer (such as a +/// `UnionExec` with boundary/staging branches) that pulls rows. +#[derive(Debug)] +struct ManifestRowCountExec { + schema: SchemaRef, + total_rows: u64, + batch_size: usize, + properties: Arc, +} + +impl ManifestRowCountExec { + fn new(schema: SchemaRef, total_rows: u64, batch_size: usize) -> Self { + let properties = Arc::new(PlanProperties::new( + EquivalenceProperties::new(schema.clone()), + Partitioning::UnknownPartitioning(1), + EmissionType::Incremental, + Boundedness::Bounded, + )); + Self { + schema, + total_rows, + batch_size, + properties, + } + } +} + +impl DisplayAs for ManifestRowCountExec { + fn fmt_as(&self, _t: DisplayFormatType, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "ManifestRowCountExec: rows={}", self.total_rows) + } +} + +impl ExecutionPlan for ManifestRowCountExec { + fn name(&self) -> &str { + "ManifestRowCountExec" + } + + fn properties(&self) -> &Arc { + &self.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( + "ManifestRowCountExec does not accept children".to_string(), + )); + } + Ok(self) + } + + fn execute( + &self, + partition: usize, + _context: Arc, + ) -> DataFusionResult { + if partition != 0 { + return Err(DataFusionError::Internal(format!( + "ManifestRowCountExec invalid partition {partition}, expected 0" + ))); + } + Ok(Box::pin(ManifestRowCountStream { + schema: self.schema.clone(), + remaining: self.total_rows, + batch_size: u64::try_from(self.batch_size.max(1)).unwrap_or(u64::MAX), + })) + } + + 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()) + } +} + +impl ManifestRowCountExec { + 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 num_rows = usize::try_from(self.total_rows) + .map(Precision::Exact) + .unwrap_or(Precision::Absent); + Ok(Arc::new(Statistics { + num_rows, + total_byte_size: Precision::Absent, + column_statistics: Statistics::new_unknown(&self.schema).column_statistics, + })) + } +} + +struct ManifestRowCountStream { + schema: SchemaRef, + remaining: u64, + batch_size: u64, +} + +impl futures_util::Stream for ManifestRowCountStream { + type Item = DataFusionResult; + + fn poll_next( + mut self: std::pin::Pin<&mut Self>, + _cx: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + if self.remaining == 0 { + return std::task::Poll::Ready(None); + } + let rows = self.remaining.min(self.batch_size) as usize; + self.remaining -= rows as u64; + let options = arrow_array::RecordBatchOptions::new().with_row_count(Some(rows)); + let batch = RecordBatch::try_new_with_options(self.schema.clone(), vec![], &options) + .map_err(DataFusionError::from); + std::task::Poll::Ready(Some(batch)) + } +} + +impl datafusion::execution::RecordBatchStream for ManifestRowCountStream { + fn schema(&self) -> SchemaRef { + self.schema.clone() + } +} + +/// Builds a lightweight zero-I/O scan over `interior_files`' manifest row +/// counts for empty-projection queries whose filters are all satisfied by +/// `interior_files`. +async fn manifest_row_count_plan( + table_schema: &SchemaRef, + interior_files: &[File], + limit: Option, + state: &dyn Session, +) -> DataFusionResult>> { + let total_rows = checked_manifest_total_rows(interior_files)?; + let total_rows = limit.map_or(total_rows, |lim| total_rows.min(lim as u64)); + if total_rows == 0 { + return Ok(None); + } + let empty_schema = Arc::new(table_schema.project(&[])?); + let batch_size = usize::from(state.config_options().execution.batch_size).clamp(1, 65_536); + Ok(Some(Arc::new(ManifestRowCountExec::new( + empty_schema, + total_rows, + batch_size, + )))) +} + +fn projected_staging_mem_table( + mut records: Vec, + mut schema: SchemaRef, + projection: Option<&Vec>, + filters: &[Expr], + target_partitions: usize, + reverse_rows: bool, +) -> DataFusionResult<(MemTable, Option>)> { + let needed_proj = needed_column_projection(&schema, projection, filters)?; + if let Some(needed) = needed_proj.needed_indices { + schema = needed_proj.schema; + // Arrow projects by cloning column references. Only columns that + // survive this step are retained (or reversed when `reverse_rows`). + for batch in &mut records { + *batch = batch.project(&needed)?; + } + } + + let table = partitioned_mem_table(records, schema, target_partitions, reverse_rows)?; + Ok((table, needed_proj.remapped_projection)) +} + +#[cfg(test)] +fn projected_reversed_mem_table( + records: Vec, + schema: SchemaRef, + projection: Option<&Vec>, + filters: &[Expr], + target_partitions: usize, +) -> DataFusionResult<(MemTable, Option>)> { + projected_staging_mem_table( + records, + schema, + projection, + filters, + target_partitions, + true, + ) +} + +fn partitioned_reversed_mem_table( + records: Vec, + schema: SchemaRef, + target_partitions: usize, +) -> DataFusionResult { + partitioned_mem_table(records, schema, target_partitions, true) +} + +fn partitioned_mem_table( + mut records: Vec, + schema: SchemaRef, + target_partitions: usize, + reverse_rows: bool, +) -> DataFusionResult { + let partition_count = target_partitions.clamp(1, records.len().max(1)); + let batches_per_partition = records.len() / partition_count; + let extra_batches = records.len() % partition_count; + if reverse_rows { + records.reverse(); + for batch in &mut records { + // A zero-column projection still represents all of its original rows. + if batch.num_columns() > 0 && batch.num_rows() > 1 { + *batch = crate::utils::arrow::reverse(batch); + } + } + } + let mut batches = records.into_iter(); + let partitions = (0..partition_count) + .map(|index| { + batches + .by_ref() + .take(batches_per_partition + usize::from(index < extra_batches)) + .collect() + }) + .collect(); + MemTable::try_new(schema, partitions) +} + +#[derive(Debug, Clone)] +pub enum PartialTimeFilter { + Low(Bound), + High(Bound), + Eq(NaiveDateTime), +} + +impl PartialTimeFilter { + pub fn try_from_expr(expr: &Expr, time_partition: &Option) -> Option { + let Expr::BinaryExpr(binexpr) = expr else { + return None; + }; + + // Manifests (and staging/listing prefixes) are bucketed by the stream's + // time partition column, or `p_timestamp` when none is configured. A + // bound on any other column, including `p_timestamp` on a stream with a + // custom time partition, says nothing about which manifests hold + // matching rows and must not be used to prune them. + let partition_column = time_partition.as_deref().unwrap_or(DEFAULT_TIMESTAMP_KEY); + let Expr::Column(column) = binexpr.left.as_ref() else { + return None; + }; + if column.name != partition_column { + return None; + } + let (op, time) = extract_timestamp_bound(binexpr, time_partition)?; + let value = match op { + Operator::Gt => PartialTimeFilter::Low(Bound::Excluded(time)), + Operator::GtEq => PartialTimeFilter::Low(Bound::Included(time)), + Operator::Lt => PartialTimeFilter::High(Bound::Excluded(time)), + Operator::LtEq => PartialTimeFilter::High(Bound::Included(time)), + Operator::Eq => PartialTimeFilter::Eq(time), + Operator::IsNotDistinctFrom => PartialTimeFilter::Eq(time), _ => return None, }; - Some(val) + Some(value) + } + + pub fn binary_expr(&self, left: Expr) -> Expr { + let (op, right) = match self { + PartialTimeFilter::Low(Bound::Excluded(time)) => { + (Operator::Gt, time.and_utc().timestamp_millis()) + } + PartialTimeFilter::Low(Bound::Included(time)) => { + (Operator::GtEq, time.and_utc().timestamp_millis()) + } + PartialTimeFilter::High(Bound::Excluded(time)) => { + (Operator::Lt, time.and_utc().timestamp_millis()) + } + PartialTimeFilter::High(Bound::Included(time)) => { + (Operator::LtEq, time.and_utc().timestamp_millis()) + } + PartialTimeFilter::Eq(time) => (Operator::Eq, time.and_utc().timestamp_millis()), + _ => unimplemented!(), + }; + + Expr::BinaryExpr(BinaryExpr::new( + Box::new(left), + op, + Box::new(Expr::Literal( + ScalarValue::TimestampMillisecond(Some(right), None), + None, + )), + )) + } +} + +fn is_overlapping_query( + manifest_list: &[ManifestItem], + time_filters: &[PartialTimeFilter], +) -> bool { + // This is for backwards compatiblity. Older table format relies on listing. + // if the start time is lower than lower bound of first file then we consider it overlapping + let Some(first_entry_lower_bound) = + manifest_list.iter().map(|file| file.time_lower_bound).min() + else { + return true; + }; + + for filter in time_filters { + match filter { + PartialTimeFilter::Low(Bound::Excluded(time)) + | PartialTimeFilter::Low(Bound::Included(time)) + if time < &first_entry_lower_bound.naive_utc() => + { + return true; + } + _ => {} + } + } + + false +} + +/// This function will accept time filters provided to the query and will split them +/// into listing time filters and manifest time filters +/// This makes parseable backwards compatible for when it did not have manifests +/// Logic- +/// The control flow will only come to this function if there exists data without manifest files +/// Two new time filter vec![] are created +/// For listing table time filters, we will use OG time filter low bound and either OG time filter upper bound +/// or manifest lower bound +/// For manifest time filter, we will manifest lower bound and OG upper bound +fn return_listing_time_filters( + manifest_list: &[ManifestItem], + time_filters: &mut Vec, +) -> Option> { + if manifest_list.is_empty() { + return Some(time_filters.clone()); + } + + // vec to hold timestamps for listing + let mut vec_listing_timestamps = Vec::new(); + + let mut first_entry_lower_bound = manifest_list + .iter() + .map(|file| file.time_lower_bound.naive_utc()) + .min()?; + + let mut new_time_filters = vec![PartialTimeFilter::Low(Bound::Included( + first_entry_lower_bound, + ))]; + + time_filters.iter_mut().for_each(|filter| { + match filter { + // since we've already determined that there is a need to list tables, + // we just need to check whether the filter's upper bound is < manifest lower bound + PartialTimeFilter::High(Bound::Included(upper)) + | PartialTimeFilter::High(Bound::Excluded(upper)) => { + if upper.lt(&&mut first_entry_lower_bound) { + // filter upper bound is less than manifest lower bound, continue using filter upper bound + vec_listing_timestamps.push(filter.clone()); + } else { + // use manifest lower bound as excluded + vec_listing_timestamps.push(PartialTimeFilter::High(Bound::Excluded( + first_entry_lower_bound, + ))); + } + new_time_filters.push(filter.clone()); + } + _ => { + vec_listing_timestamps.push(filter.clone()); + } + } + }); + + // update time_filters + *time_filters = new_time_filters; + + if vec_listing_timestamps.len().gt(&0) { + Some(vec_listing_timestamps) + } else { + None + } +} + +/// Start of the 5-minute staging window (floored to the minute). +fn staging_window_cutoff() -> NaiveDateTime { + (Utc::now() - TimeDelta::minutes(5)) + .with_second(0) + .and_then(|x| x.with_nanosecond(0)) + .expect("zeroed value is valid") + .naive_utc() +} + +/// We should consider data in staging for queries concerning a time period, +/// ending within 5 minutes from now. e.g. If current time is 5 +pub fn is_within_staging_window(time_filters: &[PartialTimeFilter]) -> bool { + let five_minutes_back = staging_window_cutoff(); + + if time_filters.iter().any(|filter| match filter { + PartialTimeFilter::High(Bound::Excluded(time)) + | PartialTimeFilter::High(Bound::Included(time)) + | PartialTimeFilter::Eq(time) => time >= &five_minutes_back, + _ => false, + }) { + return true; + } + + // does it even have a higher bound + let has_upper_bound = time_filters + .iter() + .any(|filter| matches!(filter, PartialTimeFilter::High(_))); + + !has_upper_bound +} + +fn timestamp_to_nanos_i128(value: i64, unit: arrow_schema::TimeUnit) -> i128 { + let value = i128::from(value); + match unit { + arrow_schema::TimeUnit::Second => value * 1_000_000_000, + arrow_schema::TimeUnit::Millisecond => value * 1_000_000, + arrow_schema::TimeUnit::Microsecond => value * 1_000, + arrow_schema::TimeUnit::Nanosecond => value, + } +} + +/// Extracts `(column_name, operator, bound_nanos)` for any simple valid bound +/// (`Gt`, `GtEq`, `Lt`, `LtEq`, `Eq`) comparing a column on the left against a +/// valid non-null timestamp literal on the right. +fn extract_exact_timestamp_bound(filter: &Expr) -> Option<(&str, Operator, i128)> { + let Expr::BinaryExpr(binexpr) = filter else { + return None; + }; + if !matches!( + binexpr.op, + Operator::Gt | Operator::GtEq | Operator::Lt | Operator::LtEq | Operator::Eq + ) { + return None; + } + let Expr::Column(column) = binexpr.left.as_ref() else { + return None; + }; + let Expr::Literal(value, None) = binexpr.right.as_ref() else { + return None; + }; + let bound_nanos = match value { + // Out-of-range literals (reachable from SQL, e.g. + // `to_timestamp_millis(9223372036854775807)`) yield no bound. + ScalarValue::TimestampSecond(Some(value), _) => { + DateTime::from_timestamp(*value, 0)?; + timestamp_to_nanos_i128(*value, arrow_schema::TimeUnit::Second) + } + ScalarValue::TimestampMillisecond(Some(value), _) => { + DateTime::from_timestamp_millis(*value)?; + timestamp_to_nanos_i128(*value, arrow_schema::TimeUnit::Millisecond) + } + ScalarValue::TimestampMicrosecond(Some(value), _) => { + DateTime::from_timestamp_micros(*value)?; + timestamp_to_nanos_i128(*value, arrow_schema::TimeUnit::Microsecond) + } + ScalarValue::TimestampNanosecond(Some(value), _) => { + timestamp_to_nanos_i128(*value, arrow_schema::TimeUnit::Nanosecond) + } + _ => return None, + }; + Some((column.name.as_str(), binexpr.op, bound_nanos)) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct ExactTimeBound { + op: Operator, + bound_nanos: i128, +} + +/// Classification of query filters against the stream's time partition column. +/// +/// Tracks the exact time predicates reported to DataFusion via +/// [`filter_pushdown`], whether any inexact filters remain, and proves whether +/// individual manifest files satisfy all exact time bounds without nulls. +#[derive(Debug, Clone)] +struct ExactTimeFilterPlan { + partition_column: String, + exact_exprs: Vec, + exact_bounds: Vec, + all_filters_exact: bool, +} + +impl ExactTimeFilterPlan { + fn new(filters: &[Expr], time_partition: &Option) -> Self { + let partition_column = time_partition + .as_deref() + .unwrap_or(DEFAULT_TIMESTAMP_KEY) + .to_owned(); + let mut exact_exprs = Vec::new(); + let mut exact_bounds = Vec::new(); + for filter in filters { + if let Some((column, op, bound_nanos)) = extract_exact_timestamp_bound(filter) + && column == partition_column + { + exact_exprs.push(filter.clone()); + exact_bounds.push(ExactTimeBound { op, bound_nanos }); + } + } + let all_filters_exact = exact_exprs.len() == filters.len(); + Self { + partition_column, + exact_exprs, + exact_bounds, + all_filters_exact, + } + } + + fn file_is_interior(&self, file: &File, schema: &SchemaRef) -> bool { + if self.exact_bounds.is_empty() { + return true; + } + file_satisfies_exact_time_bounds(file, schema, &self.partition_column, &self.exact_bounds) + } + + fn split_files(&self, files: Vec, schema: &SchemaRef) -> (Vec, Vec) { + if self.exact_bounds.is_empty() { + return (files, Vec::new()); + } + let mut interior = Vec::with_capacity(files.len()); + let mut boundary = Vec::new(); + for file in files { + if self.file_is_interior(&file, schema) { + interior.push(file); + } else { + boundary.push(file); + } + } + (interior, boundary) + } +} + +/// Returns `true` only when `file`'s certified manifest statistics for +/// `time_column` prove that every row in the file is non-null and satisfies +/// every bound in `exact_bounds`. Missing provenance (legacy manifests), +/// incomplete row groups, non-exact bounds (e.g. `INT96`), missing/mismatched +/// timestamp units, nullable-with-unknown-null-count, non-timestamp, or +/// inverted statistics all fail closed (`false`). +fn file_satisfies_exact_time_bounds( + file: &File, + schema: &SchemaRef, + time_column: &str, + exact_bounds: &[ExactTimeBound], +) -> bool { + let Ok(field) = schema.field_with_name(time_column) else { + return false; + }; + let arrow_schema::DataType::Timestamp(field_unit, _) = field.data_type() else { + return false; + }; + let Some(col) = file.columns.iter().find(|col| col.name == time_column) else { + return false; + }; + let provably_no_nulls = match col.null_count { + Some(0) => true, + Some(_) => false, + None => !field.is_nullable(), + }; + if !provably_no_nulls { + return false; + } + let Some((min_val, max_val)) = col.certified_timestamp_bounds(*field_unit) else { + return false; + }; + let file_min = timestamp_to_nanos_i128(min_val, *field_unit); + let file_max = timestamp_to_nanos_i128(max_val, *field_unit); + exact_bounds.iter().all(|bound| match bound.op { + Operator::Gt => file_min > bound.bound_nanos, + Operator::GtEq => file_min >= bound.bound_nanos, + Operator::Lt => file_max < bound.bound_nanos, + Operator::LtEq => file_max <= bound.bound_nanos, + Operator::Eq => file_min == bound.bound_nanos && file_max == bound.bound_nanos, + _ => false, + }) +} + +/// How `StandardTableProvider` can handle `filter`. +/// +/// Any simple valid timestamp bound (`Gt`, `GtEq`, `Lt`, `LtEq`, `Eq`) on the +/// stream's time partition column is reported `Exact`: DataFusion drops the +/// `FilterExec` above the scan, while `StandardTableProvider` enforces all +/// exact bounds on every staging branch, legacy listing table, and boundary +/// Parquet file, and omits them only on interior Parquet files whose non-null +/// manifest statistics prove 100% of rows satisfy every exact bound. A bound on +/// any other column (including `p_timestamp` on a stream with a custom time +/// partition) stays `Inexact`. +fn filter_pushdown(filter: &Expr, time_partition: &Option) -> TableProviderFilterPushDown { + let partition_column = time_partition.as_deref().unwrap_or(DEFAULT_TIMESTAMP_KEY); + if extract_exact_timestamp_bound(filter) + .is_some_and(|(column, _, _)| column == partition_column) + { + TableProviderFilterPushDown::Exact + } else { + // File level mechanisms such as Parquet row group pruning may still apply. + TableProviderFilterPushDown::Inexact + } +} + +pub fn expr_in_boundary(filter: &Expr) -> bool { + extract_exact_timestamp_bound(filter).is_some() +} + +pub fn extract_timestamp_bound( + binexpr: &BinaryExpr, + time_partition: &Option, +) -> Option<(Operator, NaiveDateTime)> { + let Expr::Literal(value, None) = binexpr.right.as_ref() else { + return None; + }; + + let is_time_partition = match (binexpr.left.as_ref(), time_partition) { + (Expr::Column(column), Some(time_partition)) => &column.name == time_partition, + _ => false, + }; + + match value { + // Out-of-range literals (reachable from SQL, e.g. + // `to_timestamp_millis(9223372036854775807)`) yield no bound. + ScalarValue::TimestampSecond(Some(value), _) => { + DateTime::from_timestamp(*value, 0).map(|time| (binexpr.op, time.naive_utc())) + } + ScalarValue::TimestampMillisecond(Some(value), _) => { + DateTime::from_timestamp_millis(*value).map(|time| (binexpr.op, time.naive_utc())) + } + ScalarValue::TimestampMicrosecond(Some(value), _) => { + DateTime::from_timestamp_micros(*value).map(|time| (binexpr.op, time.naive_utc())) + } + ScalarValue::TimestampNanosecond(Some(value), _) => Some(( + binexpr.op, + DateTime::from_timestamp_nanos(*value).naive_utc(), + )), + ScalarValue::Utf8(Some(str_value)) if is_time_partition => { + match str_value.parse::() { + Ok(dt) => Some((binexpr.op, dt)), + Err(_) => None, + } + } + _ => None, + } +} + +// Extract start time and end time from filter predicate +pub fn extract_primary_filter( + filters: &[Expr], + time_partition: &Option, +) -> Vec { + filters + .iter() + .filter_map(|expr| { + let mut time_filter = None; + let _ = expr.apply(&mut |expr| { + if let Some(time) = PartialTimeFilter::try_from_expr(expr, time_partition) { + time_filter = Some(time); + Ok(TreeNodeRecursion::Stop) // Stop further traversal + } else { + Ok(TreeNodeRecursion::Jump) // Skip this node + } + }); + time_filter + }) + .collect() +} + +pub trait ManifestExt: ManifestFile { + fn find_matching_column(&self, partial_filter: &Expr) -> Option<&Column> { + let name = match partial_filter { + Expr::BinaryExpr(binary_expr) => { + let Expr::Column(col) = binary_expr.left.as_ref() else { + return None; + }; + &col.name + } + _ => { + return None; + } + }; + + self.columns().iter().find(|col| &col.name == name) + } + + fn can_be_pruned(&self, partial_filter: &Expr) -> bool { + fn extract_op_scalar(expr: &Expr) -> Option<(Operator, &ScalarValue)> { + let Expr::BinaryExpr(expr) = expr else { + return None; + }; + let Expr::Literal(value, None) = &*expr.right else { + return None; + }; + /* `BinaryExp` doesn't implement `Copy` */ + Some((expr.op, value)) + } + + let Some(col) = self.find_matching_column(partial_filter) else { + return false; + }; + + if col + .stats_provenance + .is_some_and(|prov| !prov.complete_row_groups) + { + return false; + } + + let Some((op, value)) = extract_op_scalar(partial_filter) else { + return false; + }; + + // Timestamp pruning requires verified provenance (`complete_row_groups`, + // `exact_min_max`, and lossless `timestamp_unit` conversion) so legacy + // manifests, `INT96` columns, or different-unit timestamps are never + // falsely pruned against a mismatched unit. + if let Some((unit, ts_val)) = extract_timestamp_scalar(value) { + let Some((min, max)) = col.certified_timestamp_bounds(unit) else { + return false; + }; + return !satisfy_constraints( + CastRes::Int(ts_val), + op, + &TypedStatistics::Int(crate::catalog::column::Int64Type { min, max }), + ) + .unwrap_or(true); + } + + let Some(value) = cast_or_none(value) else { + return false; + }; + + let Some(stats) = &col.stats else { + return false; + }; + + !satisfy_constraints(value, op, stats).unwrap_or(true) + } +} + +impl ManifestExt for T {} + +fn extract_timestamp_scalar(scalar: &ScalarValue) -> Option<(arrow_schema::TimeUnit, i64)> { + match scalar { + ScalarValue::TimestampSecond(Some(v), _) => Some((arrow_schema::TimeUnit::Second, *v)), + ScalarValue::TimestampMillisecond(Some(v), _) => { + Some((arrow_schema::TimeUnit::Millisecond, *v)) + } + ScalarValue::TimestampMicrosecond(Some(v), _) => { + Some((arrow_schema::TimeUnit::Microsecond, *v)) + } + ScalarValue::TimestampNanosecond(Some(v), _) => { + Some((arrow_schema::TimeUnit::Nanosecond, *v)) + } + _ => None, + } +} + +enum CastRes<'a> { + Bool(bool), + Float(f64), + Int(i64), + String(&'a str), +} + +fn cast_or_none(scalar: &ScalarValue) -> Option> { + match scalar { + ScalarValue::Null => None, + ScalarValue::Boolean(val) => val.map(CastRes::Bool), + // Non-NaN floats are eligible ONLY for exact equality pruning in + // `satisfy_constraints`; range predicates stay unpruned because Parquet + // omits NaN from min/max while DataFusion orders `-NaN < -inf` and + // `+NaN > +inf`. + ScalarValue::Float32(val) => val.map(|v| CastRes::Float(v as f64)), + ScalarValue::Float64(val) => val.map(CastRes::Float), + ScalarValue::Int8(val) => val.map(|val| CastRes::Int(val as i64)), + ScalarValue::Int16(val) => val.map(|val| CastRes::Int(val as i64)), + ScalarValue::Int32(val) => val.map(|val| CastRes::Int(val as i64)), + ScalarValue::Int64(val) => val.map(CastRes::Int), + ScalarValue::UInt8(val) => val.map(|val| CastRes::Int(val as i64)), + ScalarValue::UInt16(val) => val.map(|val| CastRes::Int(val as i64)), + ScalarValue::UInt32(val) => val.map(|val| CastRes::Int(val as i64)), + ScalarValue::UInt64(val) => val + .and_then(|val| i64::try_from(val).ok()) + .map(CastRes::Int), + ScalarValue::Utf8(val) => val.as_ref().map(|val| CastRes::String(val)), + ScalarValue::Date32(val) => val.map(|val| CastRes::Int(val as i64)), + _ => None, + } +} + +fn satisfy_constraints(value: CastRes, op: Operator, stats: &TypedStatistics) -> Option { + fn matches(value: T, min: T, max: T, op: Operator) -> Option { + if min > max { + return None; + } + let val = match op { + Operator::Eq | Operator::IsNotDistinctFrom => value >= min && value <= max, + Operator::Lt => value > min, + Operator::LtEq => value >= min, + Operator::Gt => value < max, + Operator::GtEq => value <= max, + _ => return None, + }; + Some(val) + } + + match (value, stats) { + (CastRes::Bool(val), TypedStatistics::Bool(stats)) => { + matches(val, stats.min, stats.max, op) + } + (CastRes::Float(val), TypedStatistics::Float(stats)) => { + if val.is_nan() || stats.min.is_nan() || stats.max.is_nan() || stats.min > stats.max { + return None; + } + // Only equality pruning is sound against Parquet float min/max: + // neither +NaN nor -NaN equals any non-NaN literal (and -0.0 == +0.0), + // whereas DataFusion evaluates `+NaN > +inf` and `-NaN < -inf` as true. + match op { + Operator::Eq | Operator::IsNotDistinctFrom => { + Some(val >= stats.min && val <= stats.max) + } + _ => None, + } + } + (CastRes::Int(val), TypedStatistics::Int(stats)) => matches(val, stats.min, stats.max, op), + (CastRes::String(val), TypedStatistics::String(stats)) => { + matches(val, &stats.min, &stats.max, op) + } + _ => None, + } +} + +#[cfg(test)] +mod tests { + use std::{ops::Add, sync::Arc}; + + use arrow_schema::{DataType, Field, Schema}; + use chrono::{DateTime, Duration, NaiveDate, NaiveDateTime, NaiveTime, Utc}; + use datafusion::{ + datasource::{ + TableProvider, + empty::EmptyTable, + listing::PartitionedFile, + physical_plan::{FileScanConfigBuilder, FileSource}, + provider_as_source, + source::DataSourceExec, + }, + execution::context::{SessionConfig, SessionContext}, + execution::object_store::ObjectStoreUrl, + logical_expr::{BinaryExpr, Operator, TableProviderFilterPushDown, TableType}, + physical_plan::{ExecutionPlan, displayable}, + prelude::Expr, + scalar::ScalarValue, + }; + + use crate::catalog::{ + Snapshot as _, + column::{Column, Int64Type, TypedStatistics}, + manifest::{File, SortOrder}, + snapshot::{ManifestItem, Snapshot}, + }; + use crate::event::DEFAULT_TIMESTAMP_KEY; + + use super::{ + HotTierStreamKey, PartialTimeFilter, StandardTableProvider, balanced_file_groups, + build_parquet_scan_components, build_parquet_scan_components_with_full_filters, + exact_source_filters, extract_primary_filter, extract_timestamp_bound, + guarded_hot_tier_table_source, hot_tier_stream_key, is_overlapping_query, + projected_reversed_mem_table, scan_enforcing_exact_filters, standard_table_provider, + }; + + #[tokio::test] + async fn staging_reverses_projected_and_filter_columns_in_contiguous_partitions() { + use arrow_array::{Int64Array, RecordBatch, StringArray, TimestampMillisecondArray}; + use datafusion::{physical_plan::collect_partitioned, prelude::col}; + + let schema = Arc::new(Schema::new(vec![ + Field::new("payload", DataType::Utf8, false), + Field::new("label", DataType::Utf8, false), + Field::new( + DEFAULT_TIMESTAMP_KEY, + DataType::Timestamp(arrow_schema::TimeUnit::Millisecond, None), + false, + ), + Field::new("id", DataType::Int64, false), + ])); + let large_value = "a".repeat(64 * 1024); + let payload = Arc::new(StringArray::from(vec![large_value.as_str(); 3])); + let records = (0..3) + .map(|offset| { + RecordBatch::try_new( + schema.clone(), + vec![ + payload.clone(), + Arc::new(StringArray::from(vec!["first", "second", "third"])), + Arc::new(TimestampMillisecondArray::from(vec![60_000, 0, 60_000])), + Arc::new(Int64Array::from(vec![ + offset * 3, + offset * 3 + 1, + offset * 3 + 2, + ])), + ], + ) + .unwrap() + }) + .collect(); + let projection = vec![3, 1]; + let filters = [col(DEFAULT_TIMESTAMP_KEY).gt_eq(Expr::Literal( + ScalarValue::TimestampMillisecond(Some(60_000), None), + None, + ))]; + let (table, mapped_projection) = + projected_reversed_mem_table(records, schema.clone(), Some(&projection), &filters, 2) + .unwrap(); + + assert_eq!( + table.schema().as_ref(), + &schema.project(&[1, 2, 3]).unwrap() + ); + assert_eq!(Arc::strong_count(&payload), 1); + assert_eq!(mapped_projection, Some(vec![2, 0])); + assert_eq!(table.batches.len(), 2); + + let context = SessionContext::new(); + let plan = scan_enforcing_exact_filters( + &table, + &context.state(), + mapped_projection.as_ref(), + &filters, + None, + ) + .await + .unwrap(); + assert_eq!( + plan.schema().as_ref(), + &schema.project(&projection).unwrap() + ); + let partitions = collect_partitioned(plan, context.task_ctx()).await.unwrap(); + let ids: Vec> = partitions + .iter() + .map(|batches| { + batches + .iter() + .flat_map(|batch| { + batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .values() + .iter() + .copied() + }) + .collect() + }) + .collect(); + assert_eq!(ids, vec![vec![8, 6, 5, 3], vec![2, 0]]); + } + + #[tokio::test] + async fn staging_empty_projection_keeps_row_count() { + use arrow_array::{ArrayRef, Int64Array, RecordBatch}; + + let batch = RecordBatch::try_from_iter([( + "id", + Arc::new(Int64Array::from(vec![1, 2, 3])) as ArrayRef, + )]) + .unwrap(); + let schema = batch.schema(); + let (table, projection) = + projected_reversed_mem_table(vec![batch], schema, Some(&vec![]), &[], 2).unwrap(); + assert_eq!(projection, Some(vec![])); + let partition = table.batches[0].read().await; + assert_eq!(partition[0].num_columns(), 0); + assert_eq!(partition[0].num_rows(), 3); + } + + #[test] + fn prefilter_cache_is_request_scoped_and_bypasses_staging() { + use datafusion::logical_expr::{LogicalPlan, LogicalPlanBuilder}; + use datafusion::prelude::{col, lit}; + let source = provider_as_source(Arc::new(StandardTableProvider { + schema: Arc::new(Schema::new(vec![Field::new( + "p_timestamp", + DataType::Timestamp(arrow_schema::TimeUnit::Millisecond, None), + false, + )])), + stream: "logs".to_owned(), + tenant_id: Some("tenant".to_owned()), + time_partition: None, + hot_tier_guarded: true, + planning_cache: None, + })); + let original = LogicalPlanBuilder::scan("logs", source.clone(), None) + .unwrap() + .build() + .unwrap(); + let first = super::with_planning_cache(original.clone()).unwrap(); + let second = super::with_planning_cache(original).unwrap(); + let provider = |plan: LogicalPlan| { + let LogicalPlan::TableScan(scan) = plan else { + panic!("expected scan") + }; + standard_table_provider(&scan.source).unwrap().clone() + }; + let a = provider(first.clone()); + let clone = provider(first); + let b = provider(second); + assert!( + standard_table_provider(&source) + .unwrap() + .planning_cache + .is_none() + ); + assert!(Arc::ptr_eq( + a.planning_cache.as_ref().unwrap(), + clone.planning_cache.as_ref().unwrap() + )); + assert!(!Arc::ptr_eq( + a.planning_cache.as_ref().unwrap(), + b.planning_cache.as_ref().unwrap() + )); + assert_eq!(a.tenant_id.as_deref(), Some("tenant")); + assert!(a.hot_tier_guarded); + let bounds = |end| { + vec![ + col("p_timestamp").gt_eq(lit(ScalarValue::TimestampMillisecond(Some(0), None))), + col("p_timestamp").lt_eq(lit(ScalarValue::TimestampMillisecond(Some(end), None))), + ] + }; + assert!(a.cache_for_filters(&bounds(60_000)).is_some()); + assert!( + a.cache_for_filters(&bounds(Utc::now().timestamp_millis())) + .is_none() + ); + } + + #[test] + fn live_window_scans_share_only_strictly_closed_manifests() { + use crate::metastore::metadata_cache::METADATA_CACHE; + use chrono::TimeDelta; + + let cutoff = super::staging_window_cutoff(); + let item = |upper: DateTime| ManifestItem { + manifest_path: String::new(), + time_lower_bound: upper - TimeDelta::hours(1), + time_upper_bound: upper, + events_ingested: 0, + ingestion_size: 0, + storage_size: 0, + }; + let closed = item((cutoff - TimeDelta::seconds(1)).and_utc()); + let exact_boundary = item(cutoff.and_utc()); + let open = item((cutoff + TimeDelta::minutes(1)).and_utc()); + + if !METADATA_CACHE.enabled() { + assert!(!super::shares_manifest( + super::SharedManifestPolicy::All, + &closed + )); + assert!(!super::shares_manifest( + super::SharedManifestPolicy::ClosedBefore(cutoff), + &closed + )); + return; + } + assert!(!super::shares_manifest( + super::SharedManifestPolicy::Bypass, + &closed + )); + assert!(super::shares_manifest( + super::SharedManifestPolicy::All, + &closed + )); + assert!(super::shares_manifest( + super::SharedManifestPolicy::All, + &open + )); + assert!(super::shares_manifest( + super::SharedManifestPolicy::ClosedBefore(cutoff), + &closed + )); + assert!(!super::shares_manifest( + super::SharedManifestPolicy::ClosedBefore(cutoff), + &exact_boundary + )); + assert!(!super::shares_manifest( + super::SharedManifestPolicy::ClosedBefore(cutoff), + &open + )); + } + + #[test] + fn guarded_hot_tier_source_preserves_provider_identity() { + let source = provider_as_source(Arc::new(StandardTableProvider { + schema: Arc::new(Schema::empty()), + stream: "logs".to_owned(), + tenant_id: Some("other-tenant".to_owned()), + time_partition: Some("event_time".to_owned()), + hot_tier_guarded: false, + planning_cache: None, + })); + + assert_eq!( + hot_tier_stream_key(&source), + Some(HotTierStreamKey { + tenant_id: Some("other-tenant".to_owned()), + stream: "logs".to_owned(), + }) + ); + + let guarded_source = guarded_hot_tier_table_source(&source).unwrap(); + let guarded_provider = standard_table_provider(&guarded_source).unwrap(); + assert_eq!(guarded_provider.stream, "logs"); + assert_eq!(guarded_provider.tenant_id.as_deref(), Some("other-tenant")); + assert_eq!( + guarded_provider.time_partition.as_deref(), + Some("event_time") + ); + assert!(guarded_provider.hot_tier_guarded); + } + + #[test] + fn hot_tier_source_rewrite_ignores_non_standard_providers() { + let source = provider_as_source(Arc::new(EmptyTable::new(Arc::new(Schema::empty())))); + + assert!(hot_tier_stream_key(&source).is_none()); + assert!(guarded_hot_tier_table_source(&source).is_none()); + } + + fn file(path: &str, size: u64) -> File { + File { + file_path: path.to_owned(), + file_size: size, + ..File::default() + } + } + + fn time_sorted_file(path: &str, size: u64, min: i64, max: i64) -> File { + use crate::catalog::column::{ManifestTimeUnit, StatsProvenance}; + File { + file_path: path.to_owned(), + file_size: size, + columns: vec![Column { + name: "p_timestamp".to_owned(), + stats: Some(TypedStatistics::Int(Int64Type { min, max })), + null_count: Some(0), + uncompressed_size: 0, + compressed_size: 0, + stats_provenance: Some(StatsProvenance { + complete_row_groups: true, + exact_min_max: true, + timestamp_unit: Some(ManifestTimeUnit::Millisecond), + }), + }], + sort_order_id: vec![("p_timestamp".to_owned(), SortOrder::DescNullsLast)], + ..File::default() + } + } + + fn group_paths(groups: &[Vec]) -> Vec> { + groups + .iter() + .map(|group| group.iter().map(|file| file.file_path.as_str()).collect()) + .collect() + } + + #[derive(Debug)] + struct TestParquetProvider { + schema: Arc, + } + + #[async_trait::async_trait] + impl TableProvider for TestParquetProvider { + fn schema(&self) -> Arc { + Arc::clone(&self.schema) + } + + fn table_type(&self) -> TableType { + TableType::Base + } + + async fn scan( + &self, + state: &dyn datafusion::catalog::Session, + projection: Option<&Vec>, + filters: &[Expr], + limit: Option, + ) -> datafusion::error::Result> { + let (_, source) = + build_parquet_scan_components(Arc::clone(&self.schema), filters, state)?; + let mut builder = + FileScanConfigBuilder::new(ObjectStoreUrl::local_filesystem(), source.into()) + .with_file(PartitionedFile::new("test.parquet", 10)) + .with_limit(limit); + if let Some(projection) = projection { + builder = builder.with_projection_indices(Some(projection.clone()))?; + } + Ok(DataSourceExec::from_data_source(builder.build())) + } + + fn supports_filters_pushdown( + &self, + filters: &[&Expr], + ) -> datafusion::error::Result> { + Ok(filters + .iter() + .map(|filter| super::filter_pushdown(filter, &None)) + .collect()) + } + } + + #[test] + fn parquet_scan_components_preserve_session_options() { + let mut config = SessionConfig::new(); + let parquet = &mut config.options_mut().execution.parquet; + parquet.pruning = false; + parquet.pushdown_filters = true; + parquet.reorder_filters = true; + parquet.binary_as_string = true; + parquet.metadata_size_hint = Some(2 * 1024 * 1024); + parquet.enable_page_index = true; + parquet.max_predicate_cache_size = Some(987_654); + parquet.schema_force_view_types = true; + let context = SessionContext::new_with_config(config); + let state = context.state(); + let schema = Arc::new(Schema::new(vec![Field::new( + "p_timestamp", + DataType::Timestamp(arrow_schema::TimeUnit::Millisecond, None), + false, + )])); + + let (format, source) = + build_parquet_scan_components(schema, &[], &state).expect("components build"); + + let format_options = format.options(); + let source_options = source.table_parquet_options(); + for options in [format_options, source_options] { + assert!(!options.global.pruning); + assert!(options.global.pushdown_filters); + assert!(options.global.reorder_filters); + assert!(options.global.binary_as_string); + assert_eq!(options.global.metadata_size_hint, Some(2 * 1024 * 1024)); + assert!(options.global.enable_page_index); + assert_eq!(options.global.max_predicate_cache_size, Some(987_654)); + assert!(options.global.schema_force_view_types); + } + } + + #[test] + fn only_exact_time_filters_are_preinstalled_in_parquet_source() { + let schema = Arc::new(Schema::new(vec![ + Field::new( + "p_timestamp", + DataType::Timestamp(arrow_schema::TimeUnit::Millisecond, None), + false, + ), + Field::new("job", DataType::Utf8, false), + ])); + let exact_time = Expr::Column("p_timestamp".into()).gt_eq(Expr::Literal( + ScalarValue::TimestampMillisecond(Some(1_672_531_200_000), None), + None, + )); + let inexact_label = Expr::Column("job".into()).eq(Expr::Literal( + ScalarValue::Utf8(Some("api".to_owned())), + None, + )); + let filters = vec![exact_time.clone(), inexact_label.clone()]; + + assert_eq!(exact_source_filters(&filters), vec![exact_time]); + + let context = SessionContext::new(); + let state = context.state(); + let (_, source) = + build_parquet_scan_components(schema, &filters, &state).expect("components build"); + let predicate = source.filter().expect("exact predicate").to_string(); + assert!(predicate.contains("p_timestamp")); + assert!(!predicate.contains("job")); + assert!(!predicate.contains("api")); + } + + #[test] + fn full_filters_are_preinstalled_in_parquet_source_when_requested() { + let schema = Arc::new(Schema::new(vec![ + Field::new( + "p_timestamp", + DataType::Timestamp(arrow_schema::TimeUnit::Millisecond, None), + false, + ), + Field::new("job", DataType::Utf8, false), + ])); + let filters = vec![ + Expr::Column("p_timestamp".into()).gt_eq(Expr::Literal( + ScalarValue::TimestampMillisecond(Some(1_672_531_200_000), None), + None, + )), + Expr::Column("job".into()).eq(Expr::Literal( + ScalarValue::Utf8(Some("api".to_owned())), + None, + )), + ]; + + let context = SessionContext::new(); + let state = context.state(); + let (_, source) = build_parquet_scan_components_with_full_filters(schema, &filters, &state) + .expect("components build"); + let predicate = source.filter().expect("full predicate").to_string(); + assert!(predicate.contains("p_timestamp")); + assert!(predicate.contains("job")); + assert!(predicate.contains("api")); + } + + #[test] + fn partition_column_timestamp_bounds_are_exact() { + let minute = ScalarValue::TimestampMillisecond(Some(1_672_531_200_000), None); + let mid_minute = ScalarValue::TimestampMillisecond(Some(1_672_531_230_000), None); + let null_ts = ScalarValue::TimestampMillisecond(None, None); + let utf8_ts = ScalarValue::Utf8(Some("2023-01-01T00:00:00".to_owned())); + let bound = |column: &str, op: Operator, value: &ScalarValue| { + Expr::BinaryExpr(BinaryExpr::new( + Box::new(Expr::Column(column.into())), + op, + Box::new(Expr::Literal(value.clone(), None)), + )) + }; + let event_time = Some("event_time".to_owned()); + + let cases = [ + (bound("p_timestamp", Operator::GtEq, &minute), &None, true), + ( + bound("p_timestamp", Operator::GtEq, &mid_minute), + &None, + true, + ), + (bound("p_timestamp", Operator::Gt, &mid_minute), &None, true), + (bound("p_timestamp", Operator::Lt, &mid_minute), &None, true), + ( + bound("p_timestamp", Operator::LtEq, &mid_minute), + &None, + true, + ), + (bound("p_timestamp", Operator::Eq, &mid_minute), &None, true), + ( + bound("p_timestamp", Operator::NotEq, &mid_minute), + &None, + false, + ), + (bound("p_timestamp", Operator::Eq, &null_ts), &None, false), + (bound("created_at", Operator::GtEq, &minute), &None, false), + ( + bound("event_time", Operator::GtEq, &minute), + &event_time, + true, + ), + ( + bound("event_time", Operator::Lt, &mid_minute), + &event_time, + true, + ), + ( + bound("event_time", Operator::GtEq, &utf8_ts), + &event_time, + false, + ), + // Ingestion time on a stream partitioned by event time must stay Inexact. + ( + bound("p_timestamp", Operator::GtEq, &minute), + &event_time, + false, + ), + ( + bound("p_timestamp", Operator::GtEq, &mid_minute), + &event_time, + false, + ), + ( + Expr::Literal(minute.clone(), None).lt(Expr::Column("p_timestamp".into())), + &None, + false, + ), + ]; + for (filter, time_partition, exact) in cases { + assert_eq!( + matches!( + super::filter_pushdown(&filter, time_partition), + TableProviderFilterPushDown::Exact + ), + exact, + "{filter} with time partition {time_partition:?}" + ); + } + } + + #[tokio::test] + async fn limit_is_pushed_into_scan_only_for_exact_partition_bounds() { + // `collect_from_snapshot` truncates the file list by row counts when a + // limit reaches the scan, so it must not see one when a filter only + // partially matches the surviving files. + let schema = Arc::new(Schema::new(vec![ + Field::new( + "p_timestamp", + DataType::Timestamp(arrow_schema::TimeUnit::Millisecond, None), + false, + ), + Field::new( + "created_at", + DataType::Timestamp(arrow_schema::TimeUnit::Millisecond, None), + false, + ), + ])); + let context = SessionContext::new(); + context + .register_table("logs", Arc::new(TestParquetProvider { schema })) + .unwrap(); + + for (column, limit_pushed) in [("p_timestamp", true), ("created_at", false)] { + let plan = context + .sql(&format!( + "SELECT * FROM logs WHERE {column} >= '2023-01-01T00:00:00' LIMIT 5" + )) + .await + .unwrap() + .create_physical_plan() + .await + .unwrap(); + let plan = displayable(plan.as_ref()).indent(true).to_string(); + let source_line = plan + .lines() + .find(|line| line.contains("DataSourceExec")) + .expect("parquet source line"); + + assert_eq!(source_line.contains("limit=5"), limit_pushed, "{plan}"); + assert_eq!( + plan.lines() + .any(|line| line.contains("FilterExec") && line.contains(column)), + !limit_pushed, + "{plan}" + ); + } + } + + #[tokio::test] + async fn optimized_plan_enforces_exact_time_once_without_duplicating_inexact_filter() { + let schema = Arc::new(Schema::new(vec![ + Field::new( + "p_timestamp", + DataType::Timestamp(arrow_schema::TimeUnit::Millisecond, None), + false, + ), + Field::new("job", DataType::Utf8, false), + ])); + let context = SessionContext::new(); + context + .register_table( + "metrics", + Arc::new(TestParquetProvider { + schema: Arc::clone(&schema), + }), + ) + .unwrap(); + let exact_time = Expr::Column("p_timestamp".into()).gt_eq(Expr::Literal( + ScalarValue::TimestampMillisecond(Some(1_672_531_200_000), None), + None, + )); + let inexact_label = Expr::Column("job".into()).eq(Expr::Literal( + ScalarValue::Utf8(Some("api".to_owned())), + None, + )); + + let plan = context + .table("metrics") + .await + .unwrap() + .filter(exact_time.and(inexact_label)) + .unwrap() + .create_physical_plan() + .await + .unwrap(); + let plan = displayable(plan.as_ref()).indent(true).to_string(); + let filter_lines = plan + .lines() + .filter(|line| line.contains("FilterExec")) + .collect::>(); + let source_line = plan + .lines() + .find(|line| line.contains("DataSourceExec")) + .expect("parquet source line"); + + assert_eq!(filter_lines.len(), 1, "{plan}"); + assert!(filter_lines[0].contains("job"), "{plan}"); + assert!(!filter_lines[0].contains("p_timestamp"), "{plan}"); + assert!(source_line.contains("predicate=p_timestamp"), "{plan}"); + assert!(!source_line.contains("predicate=job"), "{plan}"); + } + + #[test] + fn byte_balancing_uses_least_loaded_group_and_preserves_input_order() { + let files = vec![ + file("z.parquet", 10), + file("y.parquet", 9), + file("x.parquet", 8), + file("w.parquet", 7), + file("v.parquet", 6), + ]; + + let groups = balanced_file_groups(files, 3); + + assert_eq!( + group_paths(&groups), + vec![ + vec!["z.parquet"], + vec!["y.parquet", "v.parquet"], + vec!["x.parquet", "w.parquet"], + ] + ); + assert_eq!( + groups + .iter() + .map(|group| group.iter().map(|file| file.file_size).sum::()) + .collect::>(), + vec![10, 15, 15] + ); + } + + #[test] + fn byte_balancing_omits_empty_groups_and_handles_empty_input() { + assert_eq!( + group_paths(&balanced_file_groups( + vec![file("z.parquet", 2), file("y.parquet", 1)], + 8, + )), + vec![vec!["z.parquet"], vec!["y.parquet"]] + ); + assert!(balanced_file_groups(Vec::new(), 4).is_empty()); + assert!(balanced_file_groups(vec![file("z.parquet", 1)], 0).is_empty()); + } + + #[test] + fn byte_balancing_uses_largest_files_first_without_reordering_each_group() { + let files = vec![ + file("first.parquet", 6), + file("second.parquet", 10), + file("third.parquet", 7), + file("fourth.parquet", 9), + file("fifth.parquet", 8), + ]; + + let groups = balanced_file_groups(files, 3); + + assert_eq!( + group_paths(&groups), + vec![ + vec!["second.parquet"], + vec!["first.parquet", "fourth.parquet"], + vec!["third.parquet", "fifth.parquet"], + ] + ); + assert_eq!( + groups + .iter() + .map(|group| group.iter().map(|file| file.file_size).sum::()) + .collect::>(), + vec![10, 15, 15] + ); + } + + #[test] + fn scan_order_is_never_advertised_from_footer_sort_order() { + // Footer-derived `sort_order_id` plus non-overlapping statistics: a single file can still + // be unsorted inside, so neither one file nor a statistics-chained group is advertised. + let schema = Arc::new(Schema::new(vec![Field::new( + "p_timestamp", + DataType::Timestamp(arrow_schema::TimeUnit::Millisecond, None), + true, + )])); + for files in [ + vec![time_sorted_file("only.parquet", 10, 100, 199)], + vec![ + time_sorted_file("new.parquet", 10, 200, 299), + time_sorted_file("old.parquet", 10, 100, 199), + ], + ] { + for target_partitions in [1, 4] { + let (_, _, ordered) = super::partitioned_files( + &schema, + &None, + files.clone(), + target_partitions, + false, + "p_timestamp", + ); + assert!(!ordered); + } + } + } + + fn datetime_min(year: i32, month: u32, day: u32) -> DateTime { + NaiveDate::from_ymd_opt(year, month, day) + .unwrap() + .and_time(NaiveTime::MIN) + .and_utc() + } + + fn datetime_max(year: i32, month: u32, day: u32) -> DateTime { + NaiveDate::from_ymd_opt(year, month, day) + .unwrap() + .and_hms_milli_opt(23, 59, 59, 999) + .unwrap() + .and_utc() + } + + fn manifest_items() -> Vec { + vec![ + ManifestItem { + manifest_path: "1".to_string(), + time_lower_bound: datetime_min(2023, 12, 15), + time_upper_bound: datetime_max(2023, 12, 15), + events_ingested: 0, + ingestion_size: 0, + storage_size: 0, + }, + ManifestItem { + manifest_path: "2".to_string(), + time_lower_bound: datetime_min(2023, 12, 16), + time_upper_bound: datetime_max(2023, 12, 16), + events_ingested: 0, + ingestion_size: 0, + storage_size: 0, + }, + ManifestItem { + manifest_path: "3".to_string(), + time_lower_bound: datetime_min(2023, 12, 17), + time_upper_bound: datetime_max(2023, 12, 17), + events_ingested: 0, + ingestion_size: 0, + storage_size: 0, + }, + ] + } + + #[test] + fn bound_min_is_overlapping() { + let res = is_overlapping_query( + &manifest_items(), + &[PartialTimeFilter::Low(std::ops::Bound::Included( + datetime_min(2023, 12, 14).naive_utc(), + ))], + ); + + assert!(res) + } + + #[test] + fn bound_min_plus_hour_is_overlapping() { + let res = is_overlapping_query( + &manifest_items(), + &[PartialTimeFilter::Low(std::ops::Bound::Included( + datetime_min(2023, 12, 14) + .naive_utc() + .add(Duration::hours(3)), + ))], + ); + + assert!(res) + } + + #[test] + fn bound_next_day_min_is_not_overlapping() { + let res = is_overlapping_query( + &manifest_items(), + &[PartialTimeFilter::Low(std::ops::Bound::Included( + datetime_min(2023, 12, 16).naive_utc(), + ))], + ); + + assert!(!res) + } + + #[test] + fn out_of_range_millisecond_literal_yields_no_bound() { + let binexpr = BinaryExpr { + left: Box::new(Expr::Column("p_timestamp".into())), + op: Operator::GtEq, + right: Box::new(Expr::Literal( + ScalarValue::TimestampMillisecond(Some(i64::MAX), None), + None, + )), + }; + + assert_eq!(extract_timestamp_bound(&binexpr, &None), None); + assert!(!super::expr_in_boundary(&Expr::BinaryExpr(binexpr))); + } + + #[tokio::test] + async fn out_of_range_millisecond_literal_in_sql_does_not_panic() { + let schema = Arc::new(Schema::new(vec![Field::new( + "p_timestamp", + DataType::Timestamp(arrow_schema::TimeUnit::Millisecond, None), + false, + )])); + let context = SessionContext::new(); + context + .register_table("logs", Arc::new(TestParquetProvider { schema })) + .unwrap(); + + context + .sql("SELECT * FROM logs WHERE p_timestamp >= to_timestamp_millis(9223372036854775807)") + .await + .unwrap() + .create_physical_plan() + .await + .unwrap(); + } + + #[test] + fn timestamp_in_milliseconds() { + let binexpr = BinaryExpr { + left: Box::new(Expr::Column("timestamp_column".into())), + op: Operator::Eq, + right: Box::new(Expr::Literal( + ScalarValue::TimestampMillisecond(Some(1672531200000), None), + None, + )), + }; + + let time_partition = Some("timestamp_column".to_string()); + let result = extract_timestamp_bound(&binexpr, &time_partition); + + let expected = Some(( + Operator::Eq, + NaiveDateTime::parse_from_str("2023-01-01 00:00:00", "%Y-%m-%d %H:%M:%S").unwrap(), + )); + + assert_eq!(result, expected); + } + + #[test] + fn timestamp_in_nanoseconds() { + let binexpr = BinaryExpr { + left: Box::new(Expr::Column("timestamp_column".into())), + op: Operator::Gt, + right: Box::new(Expr::Literal( + ScalarValue::TimestampNanosecond(Some(1672531200000000000), None), + None, + )), + }; + + let time_partition = Some("timestamp_column".to_string()); + let result = extract_timestamp_bound(&binexpr, &time_partition); + + let expected = Some(( + Operator::Gt, + NaiveDateTime::parse_from_str("2023-01-01 00:00:00", "%Y-%m-%d %H:%M:%S").unwrap(), + )); + + assert_eq!(result, expected); + } + + #[test] + fn string_timestamp() { + let timestamp = "2023-01-01T00:00:00"; + let binexpr = BinaryExpr { + left: Box::new(Expr::Column("timestamp_column".into())), + op: Operator::Lt, + right: Box::new(Expr::Literal( + ScalarValue::Utf8(Some(timestamp.to_owned())), + None, + )), + }; + + let time_partition = Some("timestamp_column".to_string()); + let result = extract_timestamp_bound(&binexpr, &time_partition); + + let expected = Some(( + Operator::Lt, + NaiveDateTime::parse_from_str(timestamp, "%Y-%m-%dT%H:%M:%S").unwrap(), + )); + + assert_eq!(result, expected); + } + + #[test] + fn unexpected_utf8_column() { + let timestamp = "2023-01-01T00:00:00"; + let binexpr = BinaryExpr { + left: Box::new(Expr::Column("other_column".into())), + op: Operator::Eq, + right: Box::new(Expr::Literal( + ScalarValue::Utf8(Some(timestamp.to_owned())), + None, + )), + }; + + let time_partition = Some("timestamp_column".to_string()); + let result = extract_timestamp_bound(&binexpr, &time_partition); + + assert!(result.is_none()); + } + + #[test] + fn unsupported_literal_type() { + let binexpr = BinaryExpr { + left: Box::new(Expr::Column("timestamp_column".into())), + op: Operator::Eq, + right: Box::new(Expr::Literal(ScalarValue::Int32(Some(42)), None)), + }; + + let time_partition = Some("timestamp_column".to_string()); + let result = extract_timestamp_bound(&binexpr, &time_partition); + + assert!(result.is_none()); + } + + #[test] + fn no_literal_on_right() { + let binexpr = BinaryExpr { + left: Box::new(Expr::Column("timestamp_column".into())), + op: Operator::Eq, + right: Box::new(Expr::Column("other_column".into())), + }; + + let time_partition = Some("timestamp_column".to_string()); + let result = extract_timestamp_bound(&binexpr, &time_partition); + + assert!(result.is_none()); + } + + #[test] + fn non_time_partition_timestamps() { + let binexpr = BinaryExpr { + left: Box::new(Expr::Column("timestamp_column".into())), + op: Operator::Eq, + right: Box::new(Expr::Literal( + ScalarValue::TimestampMillisecond(Some(1672531200000), None), + None, + )), + }; + + let time_partition = None; + let result = extract_timestamp_bound(&binexpr, &time_partition); + let expected = Some(( + Operator::Eq, + NaiveDateTime::parse_from_str("2023-01-01T00:00:00", "%Y-%m-%dT%H:%M:%S").unwrap(), + )); + + assert_eq!(result, expected); + + let binexpr = BinaryExpr { + left: Box::new(Expr::Column("timestamp_column".into())), + op: Operator::Eq, + right: Box::new(Expr::Literal( + ScalarValue::TimestampNanosecond(Some(1672531200000000000), None), + None, + )), + }; + let result = extract_timestamp_bound(&binexpr, &time_partition); + + assert_eq!(result, expected); + } + + fn ts_millis(time: DateTime) -> Expr { + Expr::Literal( + ScalarValue::TimestampMillisecond(Some(time.timestamp_millis()), None), + None, + ) + } + + fn column(name: &str) -> Expr { + Expr::Column(name.into()) + } + + fn pruned_manifest_paths(filters: &[Expr], time_partition: &Option) -> Vec { + let time_filters = extract_primary_filter(filters, time_partition); + manifest_snapshot() + .manifests(&time_filters) + .into_iter() + .map(|item| item.manifest_path) + .collect() + } + + fn manifest_snapshot() -> Snapshot { + Snapshot { + manifest_list: manifest_items(), + ..Snapshot::default() + } + } + + #[test] + fn non_timestamp_column_filter_does_not_prune_manifests() { + // `created_at` is unrelated to how manifests are bucketed: rows with a + // late `created_at` can live in any day's manifest. + let filters = [ + column("created_at").gt_eq(ts_millis(datetime_min(2023, 12, 17))), + column("created_at").lt(ts_millis(datetime_max(2023, 12, 17))), + ]; + + assert!(extract_primary_filter(&filters, &None).is_empty()); + assert_eq!(pruned_manifest_paths(&filters, &None), ["1", "2", "3"]); + } + + #[test] + fn non_timestamp_string_literal_filter_does_not_prune_manifests() { + let filters = [column("created_at").gt(Expr::Literal( + ScalarValue::Utf8(Some("2023-12-17T00:00:00".to_owned())), + None, + ))]; + + assert!(extract_primary_filter(&filters, &None).is_empty()); + assert_eq!(pruned_manifest_paths(&filters, &None), ["1", "2", "3"]); + } + + #[test] + fn p_timestamp_filter_prunes_manifests() { + let filters = [ + column(DEFAULT_TIMESTAMP_KEY).gt_eq(ts_millis(datetime_min(2023, 12, 16))), + column(DEFAULT_TIMESTAMP_KEY).lt(ts_millis(datetime_max(2023, 12, 16))), + ]; + + assert_eq!(extract_primary_filter(&filters, &None).len(), 2); + assert_eq!(pruned_manifest_paths(&filters, &None), ["2"]); + } + + #[test] + fn qualified_p_timestamp_filter_prunes_manifests() { + // The query handler injects table-qualified time filters. + let filters = [Expr::Column(datafusion::common::Column::new( + Some("app_logs"), + DEFAULT_TIMESTAMP_KEY, + )) + .gt_eq(ts_millis(datetime_min(2023, 12, 17)))]; + + assert_eq!(pruned_manifest_paths(&filters, &None), ["3"]); + } + + #[test] + fn literal_on_left_or_non_comparison_does_not_prune_manifests() { + let filters = [ + ts_millis(datetime_min(2023, 12, 17)).lt(column(DEFAULT_TIMESTAMP_KEY)), + column(DEFAULT_TIMESTAMP_KEY).not_eq(ts_millis(datetime_min(2023, 12, 17))), + ]; + + assert!(extract_primary_filter(&filters, &None).is_empty()); + } + + #[test] + fn custom_time_partition_filter_prunes_manifests() { + // Manifests of time-partitioned streams are bucketed by the partition + // column, so bounds on it (timestamp or parseable string) prune. + let time_partition = Some("event_time".to_owned()); + let filters = [ + column("event_time").gt_eq(ts_millis(datetime_min(2023, 12, 16))), + column("event_time").lt(Expr::Literal( + ScalarValue::Utf8(Some("2023-12-16T12:00:00".to_owned())), + None, + )), + ]; + + assert_eq!(extract_primary_filter(&filters, &time_partition).len(), 2); + assert_eq!(pruned_manifest_paths(&filters, &time_partition), ["2"]); + } + + #[test] + fn p_timestamp_filter_does_not_prune_custom_time_partition_manifests() { + // On a time-partitioned stream `p_timestamp` is ingestion time, while + // manifests are bucketed by event time: back-filled events ingested on + // the 17th sit in the 15th's manifest and must not be pruned away. + let time_partition = Some("event_time".to_owned()); + let filters = [column(DEFAULT_TIMESTAMP_KEY).gt_eq(ts_millis(datetime_min(2023, 12, 17)))]; + + assert!(extract_primary_filter(&filters, &time_partition).is_empty()); + assert_eq!( + pruned_manifest_paths(&filters, &time_partition), + ["1", "2", "3"] + ); + } + + #[test] + fn unrelated_column_does_not_prune_custom_time_partition_manifests() { + let time_partition = Some("event_time".to_owned()); + let filters = [column("created_at").gt_eq(ts_millis(datetime_min(2023, 12, 17)))]; + + assert!(extract_primary_filter(&filters, &time_partition).is_empty()); + } +} + +#[cfg(test)] +mod ordering_tests; + +#[cfg(test)] +mod exact_filter_tests; + +#[cfg(test)] +mod snapshot_capture_tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + + #[tokio::test] + async fn publication_between_capture_and_read_cannot_hide_a_file() { + for predicted in [true, false] { + let published = AtomicUsize::new(0); + let reads = AtomicUsize::new(0); + let (snapshot, staging) = capture_before_snapshot( + predicted, + || { + // Capture a lease, then simulate publication and unlink. + let lease = "just-uploaded.parquet"; + published.store(1, Ordering::SeqCst); + Ok(lease) + }, + |_| async { + reads.fetch_add(1, Ordering::SeqCst); + Ok(published.load(Ordering::SeqCst)) + }, + |_| true, + ) + .await + .unwrap(); + assert_eq!(snapshot, 1); + assert_eq!(staging, Some("just-uploaded.parquet")); + assert_eq!(reads.load(Ordering::SeqCst), if predicted { 1 } else { 2 }); + } + } + + #[tokio::test] + async fn historical_queries_do_not_capture_staging() { + let (snapshot, staging) = capture_before_snapshot( + false, + || -> DataFusionResult<()> { panic!("historical scan must not lease staging") }, + |_| async { Ok(42) }, + |_| false, + ) + .await + .unwrap(); + assert_eq!(snapshot, 42); + assert_eq!(staging, None); + } + #[tokio::test] + async fn speculative_capture_error_only_fails_when_staging_is_needed() { + for needed in [false, true] { + let result = capture_before_snapshot( + true, + || -> DataFusionResult<()> { + Err(DataFusionError::Execution("capture failed".into())) + }, + |_| async { Ok(needed) }, + |needed| *needed, + ) + .await; + assert_eq!(result.is_err(), needed); + } + } +} + +#[cfg(test)] +mod staging_disk_tests { + use std::sync::Arc; + + use arrow_array::{Int32Array, RecordBatch, StringArray}; + use arrow_schema::{DataType, Field, Schema}; + use chrono::Utc; + use datafusion::{ + execution::context::SessionContext, + physical_plan::collect, + prelude::{col, lit}, + }; + use temp_dir::TempDir; + + use super::staging_disk_plan; + use crate::{ + OBJECT_STORE_DATA_GRANULARITY, + parseable::{ + StagingCapture, StagingMemoryBudget, + staging::writer::{MemWriter, Writer}, + }, + utils::time::TimeRange, + }; + + fn file_schema() -> Arc { + Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new("name", DataType::Utf8, false), + ])) + } + + fn table_schema() -> Arc { + Arc::new(Schema::new(vec![ + Field::new("name", DataType::Utf8, true), + Field::new("extra", DataType::Int32, true), + Field::new("id", DataType::Int32, true), + ])) + } + + /// Ingests `0..rows` in batches of 7 with a disk-only budget and captures. + fn disk_only_capture(dir: &TempDir, rows: i32) -> (Writer, StagingCapture) { + let budget = StagingMemoryBudget::new(0); + let mut writer = Writer { + mem: Some(MemWriter::with_budget(Arc::clone(&budget))), + disk: Default::default(), + }; + let range = TimeRange::granularity_range(Utc::now(), OBJECT_STORE_DATA_GRANULARITY); + for start in (0..rows).step_by(7) { + let ids = start..(start + 7).min(rows); + let batch = RecordBatch::try_new( + file_schema(), + vec![ + Arc::new(Int32Array::from_iter_values(ids.clone())), + Arc::new(StringArray::from_iter_values( + ids.map(|id| format!("n{id}")), + )), + ], + ) + .unwrap(); + for name in [ + "a.date=2020-01-02.data.arrows", + "b.date=2020-01-02.data.arrows", + ] { + writer + .push_disk_and_memory(name, "k", &batch, dir.path().join(name), range.clone()) + .unwrap(); + } + } + assert_eq!(budget.used(), 0); + let capture = writer.capture(&table_schema()).unwrap(); + assert!(capture.memory.is_empty()); + assert_eq!(capture.disk.len(), 2); + (writer, capture) } - match (value, stats) { - (CastRes::Bool(val), TypedStatistics::Bool(stats)) => { - matches(val, stats.min, stats.max, op) - } - (CastRes::Int(val), TypedStatistics::Int(stats)) => matches(val, stats.min, stats.max, op), - (CastRes::Float(val), TypedStatistics::Float(stats)) => { - matches(val, stats.min, stats.max, op) - } - (CastRes::String(val), TypedStatistics::String(stats)) => { - matches(val, &stats.min, &stats.max, op) - } - _ => None, + fn ids(batches: &[RecordBatch]) -> Vec { + let mut ids = batches + .iter() + .flat_map(|batch| { + batch + .column_by_name("id") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap() + .iter() + .map(Option::unwrap) + .collect::>() + }) + .collect::>(); + ids.sort_unstable(); + ids } -} -#[cfg(test)] -mod tests { - use std::{ops::Add, sync::Arc}; + #[tokio::test] + async fn staging_disk_plan_streams_every_row_with_projection_and_filters() { + let dir = TempDir::new().unwrap(); + let (_writer, capture) = disk_only_capture(&dir, 100); + let ctx = SessionContext::new(); + let state = ctx.state(); - use arrow_schema::{DataType, Field, Schema}; - use chrono::{DateTime, Duration, NaiveDate, NaiveDateTime, NaiveTime, Utc}; - use datafusion::{ - datasource::{ - TableProvider, - empty::EmptyTable, - listing::PartitionedFile, - physical_plan::{FileScanConfigBuilder, FileSource}, - provider_as_source, - source::DataSourceExec, - }, - execution::context::{SessionConfig, SessionContext}, - execution::object_store::ObjectStoreUrl, - logical_expr::{BinaryExpr, Operator, TableProviderFilterPushDown, TableType}, - physical_plan::{ExecutionPlan, displayable}, - prelude::Expr, - scalar::ScalarValue, - }; + let plan = staging_disk_plan( + table_schema(), + capture.disk.clone(), + &state, + None, + &[], + None, + ) + .await + .unwrap() + .unwrap(); + let all = collect(plan, ctx.task_ctx()).await.unwrap(); + assert!(all.iter().all(|batch| batch.schema() == table_schema())); + let mut expected = (0..100).chain(0..100).collect::>(); + expected.sort_unstable(); + assert_eq!(ids(&all), expected); - use crate::catalog::{ - Snapshot as _, - column::{Column, Int64Type, TypedStatistics}, - manifest::{File, SortOrder}, - snapshot::{ManifestItem, Snapshot}, - }; - use crate::event::DEFAULT_TIMESTAMP_KEY; + // Project `id` only. Filters this scan does not report as exact are + // applied by DataFusion above it; the scan must still read their + // columns and return every row. + let filter = col("name").eq(lit("n42")); + let plan = staging_disk_plan( + table_schema(), + capture.disk.clone(), + &state, + Some(&vec![2]), + &[filter], + None, + ) + .await + .unwrap() + .unwrap(); + let filtered = collect(plan, ctx.task_ctx()).await.unwrap(); + assert!(filtered.iter().all(|batch| batch.num_columns() == 1)); + assert_eq!(ids(&filtered), expected); - use super::{ - HotTierStreamKey, PartialTimeFilter, StandardTableProvider, balanced_file_groups, - build_parquet_scan_components, build_parquet_scan_components_with_full_filters, - exact_source_filters, extract_primary_filter, extract_timestamp_bound, - guarded_hot_tier_table_source, hot_tier_stream_key, is_overlapping_query, - projected_reversed_mem_table, scan_enforcing_exact_filters, standard_table_provider, - }; + assert!( + staging_disk_plan(table_schema(), vec![], &state, None, &[], None) + .await + .unwrap() + .is_none() + ); + } #[tokio::test] - async fn staging_reverses_projected_and_filter_columns_in_contiguous_partitions() { - use arrow_array::{Int64Array, RecordBatch, StringArray, TimestampMillisecondArray}; - use datafusion::{physical_plan::collect_partitioned, prelude::col}; + async fn staging_disk_plan_reads_unlinked_files_and_fails_closed_when_short() { + let dir = TempDir::new().unwrap(); + let (writer, capture) = disk_only_capture(&dir, 50); + let ctx = SessionContext::new(); + let state = ctx.state(); + // Detach, seal and delete the files: the captured descriptors still read. + let mut writer = writer; + for detached in writer.detach_flushable_disk_at(true, Utc::now()) { + let sealed = detached.seal().unwrap_or_else(|(_, err)| panic!("{err}")); + std::fs::remove_file(sealed.part).unwrap(); + } + let plan = staging_disk_plan( + table_schema(), + capture.disk.clone(), + &state, + None, + &[], + None, + ) + .await + .unwrap() + .unwrap(); + assert_eq!( + ids(&collect(plan, ctx.task_ctx()).await.unwrap()).len(), + 100 + ); + + // A file shorter than its acknowledged length is an error, not fewer rows. + let dir = TempDir::new().unwrap(); + let (writer, capture) = disk_only_capture(&dir, 50); + let path = writer.disk.values().next().unwrap().path().to_path_buf(); + let len = std::fs::metadata(&path).unwrap().len(); + std::fs::OpenOptions::new() + .write(true) + .open(&path) + .unwrap() + .set_len(len - 3) + .unwrap(); + let plan = staging_disk_plan(table_schema(), capture.disk, &state, None, &[], None) + .await + .unwrap() + .unwrap(); + assert!(collect(plan, ctx.task_ctx()).await.is_err()); + drop(writer); + } + + #[tokio::test] + async fn staging_disk_plan_empty_projection_counts_rows_without_decoding_bodies() { + let dir = TempDir::new().unwrap(); + let (_writer, capture) = disk_only_capture(&dir, 75); + let ctx = SessionContext::new(); + let state = ctx.state(); + + let plan = staging_disk_plan( + table_schema(), + capture.disk.clone(), + &state, + Some(&vec![]), + &[], + None, + ) + .await + .unwrap() + .unwrap(); + let batches = collect(plan, ctx.task_ctx()).await.unwrap(); + assert!(batches.iter().all(|b| b.num_columns() == 0)); + let total_rows: usize = batches.iter().map(RecordBatch::num_rows).sum(); + assert_eq!(total_rows, 150); + + // Projecting only a column absent from all staged files synthesizes nulls cleanly. + let wide_schema = Arc::new(Schema::new(vec![ + Field::new("name", DataType::Utf8, true), + Field::new("extra", DataType::Int32, true), + Field::new("id", DataType::Int32, true), + Field::new("absent_col", DataType::Int64, true), + ])); + let plan = staging_disk_plan(wide_schema, capture.disk, &state, Some(&vec![3]), &[], None) + .await + .unwrap() + .unwrap(); + let batches = collect(plan, ctx.task_ctx()).await.unwrap(); + let total_rows: usize = batches.iter().map(RecordBatch::num_rows).sum(); + assert_eq!(total_rows, 150); + assert!( + batches + .iter() + .all(|b| { b.num_columns() == 1 && b.column(0).null_count() == b.num_rows() }) + ); + } + + #[tokio::test] + async fn staging_disk_plan_splits_single_large_file_across_partitions_and_preserves_limit_order() + { + use arrow_array::TimestampMillisecondArray; + use arrow_schema::TimeUnit; + use datafusion::physical_plan::ExecutionPlanProperties; + use datafusion::prelude::SessionConfig; + let dir = TempDir::new().unwrap(); + let budget = StagingMemoryBudget::new(0); + let mut writer = Writer { + mem: Some(MemWriter::with_budget(Arc::clone(&budget))), + disk: Default::default(), + }; let schema = Arc::new(Schema::new(vec![ - Field::new("payload", DataType::Utf8, false), - Field::new("label", DataType::Utf8, false), Field::new( - DEFAULT_TIMESTAMP_KEY, - DataType::Timestamp(arrow_schema::TimeUnit::Millisecond, None), + "p_timestamp", + DataType::Timestamp(TimeUnit::Millisecond, None), false, ), - Field::new("id", DataType::Int64, false), + Field::new("id", DataType::Int32, false), + Field::new("payload", DataType::Utf8, false), ])); - let large_value = "a".repeat(64 * 1024); - let payload = Arc::new(StringArray::from(vec![large_value.as_str(); 3])); - let records = (0..3) - .map(|offset| { - RecordBatch::try_new( - schema.clone(), - vec![ - payload.clone(), - Arc::new(StringArray::from(vec!["first", "second", "third"])), - Arc::new(TimestampMillisecondArray::from(vec![60_000, 0, 60_000])), - Arc::new(Int64Array::from(vec![ - offset * 3, - offset * 3 + 1, - offset * 3 + 2, - ])), - ], - ) - .unwrap() - }) - .collect(); - let projection = vec![3, 1]; - let filters = [col(DEFAULT_TIMESTAMP_KEY).gt_eq(Expr::Literal( - ScalarValue::TimestampMillisecond(Some(60_000), None), - None, - ))]; - let (table, mapped_projection) = - projected_reversed_mem_table(records, schema.clone(), Some(&projection), &filters, 2) + let file = "big.data.arrows"; + let range = TimeRange::granularity_range(Utc::now(), OBJECT_STORE_DATA_GRANULARITY); + // Write 12 batches of 500 rows with high-entropy payloads (> 1 MiB after + // LZ4 compression) into a single `.arrows.part` file so `sources.len() == 1`. + let mut next_id = 0i32; + let mut rng = 0x1234_5678_9ABC_DEF0u64; + for _batch_idx in 0..12 { + let rows = 500usize; + let ts: Vec = (0..rows) + .map(|i| 1_700_000_000_000 + next_id as i64 + i as i64) + .collect(); + let ids_col: Vec = (0..rows).map(|i| next_id + i as i32).collect(); + let payloads: Vec = (0..rows) + .map(|_| { + let mut s = String::with_capacity(256); + for _ in 0..16 { + rng ^= rng << 13; + rng ^= rng >> 7; + rng ^= rng << 17; + use std::fmt::Write; + let _ = write!(&mut s, "{rng:016x}"); + } + s + }) + .collect(); + next_id += rows as i32; + let rb = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(TimestampMillisecondArray::from(ts)), + Arc::new(Int32Array::from(ids_col)), + Arc::new(StringArray::from(payloads)), + ], + ) + .unwrap(); + writer + .push_disk_and_memory(file, "k", &rb, dir.path().join(file), range.clone()) .unwrap(); - - assert_eq!( - table.schema().as_ref(), - &schema.project(&[1, 2, 3]).unwrap() - ); - assert_eq!(Arc::strong_count(&payload), 1); - assert_eq!(mapped_projection, Some(vec![2, 0])); - assert_eq!(table.batches.len(), 2); - - let context = SessionContext::new(); - let plan = scan_enforcing_exact_filters( - &table, - &context.state(), - mapped_projection.as_ref(), - &filters, + } + let capture = writer.capture(&schema).unwrap(); + assert_eq!(capture.disk.len(), 1); + assert!( + capture.disk[0].len() as usize > super::STAGING_DISK_MIN_SPLIT_BYTES, + "single staging file should exceed split threshold, got {} bytes", + capture.disk[0].len() + ); + + let config = SessionConfig::new().with_target_partitions(4); + let ctx = SessionContext::new_with_config(config); + let state = ctx.state(); + + // Unlimited projected scan splits the single file across multiple partitions. + let plan = staging_disk_plan( + schema.clone(), + capture.disk.clone(), + &state, + Some(&vec![1]), + &[], None, ) .await + .unwrap() .unwrap(); - assert_eq!( - plan.schema().as_ref(), - &schema.project(&projection).unwrap() + assert!( + plan.output_partitioning().partition_count() > 1, + "expected multi-partition split for single large staging file" ); - let partitions = collect_partitioned(plan, context.task_ctx()).await.unwrap(); - let ids: Vec> = partitions + let batches = collect(plan, ctx.task_ctx()).await.unwrap(); + assert_eq!(ids(&batches), (0..next_id).collect::>()); + + // Limited scan keeps a single partition and returns the newest rows first. + let limited_plan = + staging_disk_plan(schema, capture.disk, &state, Some(&vec![1]), &[], Some(5)) + .await + .unwrap() + .unwrap(); + assert_eq!(limited_plan.output_partitioning().partition_count(), 1); + let limited_batches = collect(limited_plan, ctx.task_ctx()).await.unwrap(); + let limited_ids: Vec = limited_batches .iter() - .map(|batches| { - batches + .flat_map(|batch| { + batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .values() .iter() - .flat_map(|batch| { - batch - .column(0) - .as_any() - .downcast_ref::() - .unwrap() - .values() - .iter() - .copied() - }) - .collect() + .copied() }) .collect(); - assert_eq!(ids, vec![vec![8, 6, 5, 3], vec![2, 0]]); + assert_eq!(limited_ids, vec![5999, 5998, 5997, 5996, 5995]); + drop(writer); } #[tokio::test] - async fn staging_empty_projection_keeps_row_count() { - use arrow_array::{ArrayRef, Int64Array, RecordBatch}; - - let batch = RecordBatch::try_from_iter([( - "id", - Arc::new(Int64Array::from(vec![1, 2, 3])) as ArrayRef, - )]) - .unwrap(); - let schema = batch.schema(); - let (table, projection) = - projected_reversed_mem_table(vec![batch], schema, Some(&vec![]), &[], 2).unwrap(); - assert_eq!(projection, Some(vec![])); - let partition = table.batches[0].read().await; - assert_eq!(partition[0].num_columns(), 0); - assert_eq!(partition[0].num_rows(), 3); - } + async fn staging_disk_plan_handles_dictionary_batches_with_projection() { + use arrow_array::{DictionaryArray, TimestampMillisecondArray, types::Int32Type}; + use arrow_schema::TimeUnit; + use datafusion::physical_plan::ExecutionPlanProperties; + use datafusion::prelude::SessionConfig; - #[test] - fn prefilter_cache_is_request_scoped_and_bypasses_staging() { - use datafusion::logical_expr::{LogicalPlan, LogicalPlanBuilder}; - use datafusion::prelude::{col, lit}; - let source = provider_as_source(Arc::new(StandardTableProvider { - schema: Arc::new(Schema::new(vec![Field::new( + let dir = TempDir::new().unwrap(); + let budget = StagingMemoryBudget::new(0); + let mut writer = Writer { + mem: Some(MemWriter::with_budget(Arc::clone(&budget))), + disk: Default::default(), + }; + let dict_type = DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)); + let schema = Arc::new(Schema::new(vec![ + Field::new( "p_timestamp", - DataType::Timestamp(arrow_schema::TimeUnit::Millisecond, None), + DataType::Timestamp(TimeUnit::Millisecond, None), false, - )])), - stream: "logs".to_owned(), - tenant_id: Some("tenant".to_owned()), - time_partition: None, - hot_tier_guarded: true, - planning_cache: None, - })); - let original = LogicalPlanBuilder::scan("logs", source.clone(), None) + ), + Field::new("id", DataType::Int32, false), + Field::new("level", dict_type, false), + ])); + let file = "dict.data.arrows"; + let range = TimeRange::granularity_range(Utc::now(), OBJECT_STORE_DATA_GRANULARITY); + for b in 0..4i32 { + let dict: DictionaryArray = + ["INFO", "ERROR", "WARN", "ERROR"].into_iter().collect(); + let rb = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(TimestampMillisecondArray::from(vec![ + 1_700_000_000_000 + b as i64 * 4, + 1_700_000_000_001 + b as i64 * 4, + 1_700_000_000_002 + b as i64 * 4, + 1_700_000_000_003 + b as i64 * 4, + ])), + Arc::new(Int32Array::from(vec![ + b * 4, + b * 4 + 1, + b * 4 + 2, + b * 4 + 3, + ])), + Arc::new(dict), + ], + ) + .unwrap(); + writer + .push_disk_and_memory(file, "dictk", &rb, dir.path().join(file), range.clone()) + .unwrap(); + } + let capture = writer.capture(&schema).unwrap(); + let config = SessionConfig::new().with_target_partitions(4); + let ctx = SessionContext::new_with_config(config); + let state = ctx.state(); + + let plan = staging_disk_plan(schema, capture.disk, &state, Some(&vec![2]), &[], None) + .await .unwrap() - .build() .unwrap(); - let first = super::with_planning_cache(original.clone()).unwrap(); - let second = super::with_planning_cache(original).unwrap(); - let provider = |plan: LogicalPlan| { - let LogicalPlan::TableScan(scan) = plan else { - panic!("expected scan") - }; - standard_table_provider(&scan.source).unwrap().clone() - }; - let a = provider(first.clone()); - let clone = provider(first); - let b = provider(second); - assert!( - standard_table_provider(&source) - .unwrap() - .planning_cache - .is_none() - ); - assert!(Arc::ptr_eq( - a.planning_cache.as_ref().unwrap(), - clone.planning_cache.as_ref().unwrap() - )); - assert!(!Arc::ptr_eq( - a.planning_cache.as_ref().unwrap(), - b.planning_cache.as_ref().unwrap() - )); - assert_eq!(a.tenant_id.as_deref(), Some("tenant")); - assert!(a.hot_tier_guarded); - let bounds = |end| { - vec![ - col("p_timestamp").gt_eq(lit(ScalarValue::TimestampMillisecond(Some(0), None))), - col("p_timestamp").lt_eq(lit(ScalarValue::TimestampMillisecond(Some(end), None))), - ] - }; - assert!(a.cache_for_filters(&bounds(60_000)).is_some()); - assert!( - a.cache_for_filters(&bounds(Utc::now().timestamp_millis())) - .is_none() - ); + // Dictionary streams must stay in a single partition in forward IPC order. + assert_eq!(plan.output_partitioning().partition_count(), 1); + let batches = collect(plan, ctx.task_ctx()).await.unwrap(); + let total_rows: usize = batches.iter().map(RecordBatch::num_rows).sum(); + assert_eq!(total_rows, 16); + let mut errors = 0usize; + for batch in &batches { + assert_eq!(batch.num_columns(), 1); + let col = batch + .column(0) + .as_any() + .downcast_ref::>() + .unwrap(); + let values = col.values().as_any().downcast_ref::().unwrap(); + for i in 0..col.len() { + if values.value(col.keys().value(i) as usize) == "ERROR" { + errors += 1; + } + } + } + assert_eq!(errors, 8); + drop(writer); } - #[test] - fn staging_scans_bypass_shared_manifest_cache() { - use crate::metastore::metadata_cache::METADATA_CACHE; - if !METADATA_CACHE.enabled() { - assert!(!super::shares_manifest(true)); - assert!(!super::shares_manifest(false)); - return; + #[tokio::test] + async fn staging_disk_plan_fails_closed_uniformly_across_full_narrow_and_empty_projections() { + let dir = TempDir::new().unwrap(); + let (_writer, capture) = disk_only_capture(&dir, 30); + let ctx = SessionContext::new(); + let state = ctx.state(); + + // Incompatible column type (`name` is Utf8 in staged file, Int64 in table schema) + // AND missing non-nullable column: full, narrow (unrelated valid `id`), and empty + // (`COUNT(*)`) projections must ALL fail closed identically. + let incompatible_type_schema = Arc::new(Schema::new(vec![ + Field::new("name", DataType::Int64, true), + Field::new("id", DataType::Int32, true), + ])); + let missing_non_null_schema = Arc::new(Schema::new(vec![ + Field::new("name", DataType::Utf8, true), + Field::new("id", DataType::Int32, true), + Field::new("required_col", DataType::Int64, false), + ])); + + for bad_schema in [incompatible_type_schema, missing_non_null_schema] { + for proj in [None, Some(vec![1]), Some(vec![])] { + let plan = staging_disk_plan( + bad_schema.clone(), + capture.disk.clone(), + &state, + proj.as_ref(), + &[], + None, + ) + .await + .unwrap() + .unwrap(); + assert!( + collect(plan, ctx.task_ctx()).await.is_err(), + "projection {proj:?} should fail closed against incompatible schema {bad_schema:?}" + ); + } } - assert!(!super::shares_manifest(false)); - assert!(super::shares_manifest(true)); } - #[test] - fn guarded_hot_tier_source_preserves_provider_identity() { - let source = provider_as_source(Arc::new(StandardTableProvider { - schema: Arc::new(Schema::empty()), - stream: "logs".to_owned(), - tenant_id: Some("other-tenant".to_owned()), - time_partition: Some("event_time".to_owned()), - hot_tier_guarded: false, - planning_cache: None, - })); + #[tokio::test] + async fn staging_disk_plan_rejects_post_plan_truncation_for_ranges_and_row_counts() { + let dir = TempDir::new().unwrap(); + let (writer, capture) = disk_only_capture(&dir, 30); + let ctx = SessionContext::new(); + let state = ctx.state(); - assert_eq!( - hot_tier_stream_key(&source), - Some(HotTierStreamKey { - tenant_id: Some("other-tenant".to_owned()), - stream: "logs".to_owned(), - }) - ); + // Plan BOTH a normal range scan AND an empty-projection (`COUNT(*)`) scan + // while the file is still intact. + let range_plan = staging_disk_plan( + table_schema(), + capture.disk.clone(), + &state, + Some(&vec![2]), + &[], + None, + ) + .await + .unwrap() + .unwrap(); + let count_plan = staging_disk_plan( + table_schema(), + capture.disk, + &state, + Some(&vec![]), + &[], + None, + ) + .await + .unwrap() + .unwrap(); - let guarded_source = guarded_hot_tier_table_source(&source).unwrap(); - let guarded_provider = standard_table_provider(&guarded_source).unwrap(); - assert_eq!(guarded_provider.stream, "logs"); - assert_eq!(guarded_provider.tenant_id.as_deref(), Some("other-tenant")); - assert_eq!( - guarded_provider.time_partition.as_deref(), - Some("event_time") + // Truncate one captured file AFTER planning and BEFORE execution. + let path = writer.disk.values().next().unwrap().path().to_path_buf(); + let len = std::fs::metadata(&path).unwrap().len(); + std::fs::OpenOptions::new() + .write(true) + .open(&path) + .unwrap() + .set_len(len / 2) + .unwrap(); + + assert!( + collect(range_plan, ctx.task_ctx()).await.is_err(), + "post-plan truncation must fail closed on range scan" ); - assert!(guarded_provider.hot_tier_guarded); + assert!( + collect(count_plan, ctx.task_ctx()).await.is_err(), + "post-plan truncation must fail closed on empty-projection count scan" + ); + drop(writer); } +} - #[test] - fn hot_tier_source_rewrite_ignores_non_standard_providers() { - let source = provider_as_source(Arc::new(EmptyTable::new(Arc::new(Schema::empty())))); +#[cfg(test)] +mod track_q1_tests { + use std::{fs, path::Path, sync::Arc, time::Duration}; - assert!(hot_tier_stream_key(&source).is_none()); - assert!(guarded_hot_tier_table_source(&source).is_none()); - } + use arrow_array::{Array, Int64Array, RecordBatch, StringArray, TimestampMillisecondArray}; + use arrow_schema::{DataType, Field, Schema, SchemaRef, TimeUnit}; + use chrono::NaiveDate; + use datafusion::{ + catalog::Session, + datasource::{TableProvider, listing::PartitionedFile}, + execution::{ + context::{SessionConfig, SessionContext}, + object_store::ObjectStoreUrl, + }, + logical_expr::{TableProviderFilterPushDown, TableType}, + physical_plan::{ + ExecutionPlan, collect, collect_partitioned, displayable, empty::EmptyExec, + union::UnionExec, + }, + prelude::{Expr, col, lit}, + scalar::ScalarValue, + }; + use parquet::arrow::ArrowWriter; + use temp_dir::TempDir; - fn file(path: &str, size: u64) -> File { - File { - file_path: path.to_owned(), - file_size: size, - ..File::default() - } - } + use super::{ + ExactTimeFilterPlan, ManifestExt, checked_manifest_total_rows, filter_pushdown, + manifest_row_count_plan, parquet_scan_plan_with_cache_options, partitioned_files, + projected_staging_mem_table, scan_enforcing_exact_filters, staging_execution_plans, + truncate_manifest_files_for_limit, + }; + use crate::{ + catalog::{ + column::{Column, Int64Type, TypedStatistics, Utf8Type}, + manifest::{File, Manifest, create_from_parquet_file}, + }, + event::DEFAULT_TIMESTAMP_KEY, + metastore::metadata_cache::MetadataCache, + parseable::StagingCapture, + }; - fn time_sorted_file(path: &str, size: u64, min: i64, max: i64) -> File { - File { - file_path: path.to_owned(), - file_size: size, - columns: vec![Column { - name: "p_timestamp".to_owned(), - stats: Some(TypedStatistics::Int(Int64Type { min, max })), - null_count: Some(0), - uncompressed_size: 0, - compressed_size: 0, - }], - sort_order_id: vec![("p_timestamp".to_owned(), SortOrder::DescNullsLast)], - ..File::default() - } + fn ts_ms(hour: u32, minute: u32, second: u32) -> i64 { + NaiveDate::from_ymd_opt(2026, 11, 30) + .unwrap() + .and_hms_opt(hour, minute, second) + .unwrap() + .and_utc() + .timestamp_millis() } - fn group_paths(groups: &[Vec]) -> Vec> { - groups - .iter() - .map(|group| group.iter().map(|file| file.file_path.as_str()).collect()) - .collect() + fn ts_lit(ms: i64) -> Expr { + lit(ScalarValue::TimestampMillisecond(Some(ms), None)) } + fn write_parquet(path: &Path, batch: &RecordBatch) -> File { + let file = fs::File::create(path).unwrap(); + let mut writer = ArrowWriter::try_new(file, batch.schema(), None).unwrap(); + writer.write(batch).unwrap(); + writer.close().unwrap(); + create_from_parquet_file(path.to_string_lossy().into_owned(), path).unwrap() + } + + /// Test `TableProvider` mirroring `StandardTableProvider`'s exact-pushdown, + /// limit truncation, staging, zero-I/O interior `COUNT(*)`, and interior vs. + /// boundary Parquet split without touching global `PARSEABLE` state. #[derive(Debug)] - struct TestParquetProvider { - schema: Arc, + struct InteriorSplitTestTable { + schema: SchemaRef, + time_partition: Option, + manifest_files: Vec, + staged_memory: Vec, } #[async_trait::async_trait] - impl TableProvider for TestParquetProvider { - fn schema(&self) -> Arc { - Arc::clone(&self.schema) + impl TableProvider for InteriorSplitTestTable { + fn schema(&self) -> SchemaRef { + self.schema.clone() } fn table_type(&self) -> TableType { TableType::Base } - async fn scan( - &self, - state: &dyn datafusion::catalog::Session, - projection: Option<&Vec>, - filters: &[Expr], - limit: Option, - ) -> datafusion::error::Result> { - let (_, source) = - build_parquet_scan_components(Arc::clone(&self.schema), filters, state)?; - let mut builder = - FileScanConfigBuilder::new(ObjectStoreUrl::local_filesystem(), source.into()) - .with_file(PartitionedFile::new("test.parquet", 10)) - .with_limit(limit); - if let Some(projection) = projection { - builder = builder.with_projection_indices(Some(projection.clone()))?; - } - Ok(DataSourceExec::from_data_source(builder.build())) - } - fn supports_filters_pushdown( &self, filters: &[&Expr], ) -> datafusion::error::Result> { Ok(filters .iter() - .map(|filter| super::filter_pushdown(filter, &None)) + .map(|filter| filter_pushdown(filter, &self.time_partition)) .collect()) } - } - #[test] - fn parquet_scan_components_preserve_session_options() { - let mut config = SessionConfig::new(); - let parquet = &mut config.options_mut().execution.parquet; - parquet.pruning = false; - parquet.pushdown_filters = true; - parquet.reorder_filters = true; - parquet.binary_as_string = true; - parquet.metadata_size_hint = Some(2 * 1024 * 1024); - parquet.enable_page_index = true; - parquet.max_predicate_cache_size = Some(987_654); - parquet.schema_force_view_types = true; - let context = SessionContext::new_with_config(config); - let state = context.state(); - let schema = Arc::new(Schema::new(vec![Field::new( - "p_timestamp", - DataType::Timestamp(arrow_schema::TimeUnit::Millisecond, None), - false, - )])); + async fn scan( + &self, + state: &dyn Session, + projection: Option<&Vec>, + filters: &[Expr], + limit: Option, + ) -> datafusion::error::Result> { + let exact_filter_plan = ExactTimeFilterPlan::new(filters, &self.time_partition); + let mut execution_plans: Vec> = Vec::new(); - let (format, source) = - build_parquet_scan_components(schema, &[], &state).expect("components build"); + // Prune manifest files by column stats in newest-first order and + // apply the guarded limit truncation. + let mut surviving: Vec = self + .manifest_files + .iter() + .filter(|file| !filters.iter().any(|filter| file.can_be_pruned(filter))) + .cloned() + .collect(); + truncate_manifest_files_for_limit( + &mut surviving, + limit, + filters.is_empty(), + Some((&exact_filter_plan, &self.schema)), + ); - let format_options = format.options(); - let source_options = source.table_parquet_options(); - for options in [format_options, source_options] { - assert!(!options.global.pruning); - assert!(options.global.pushdown_filters); - assert!(options.global.reorder_filters); - assert!(options.global.binary_as_string); - assert_eq!(options.global.metadata_size_hint, Some(2 * 1024 * 1024)); - assert!(options.global.enable_page_index); - assert_eq!(options.global.max_predicate_cache_size, Some(987_654)); - assert!(options.global.schema_force_view_types); + if !self.staged_memory.is_empty() { + staging_execution_plans( + &self.schema, + &mut execution_plans, + projection, + filters, + limit, + state, + ( + StagingCapture { + memory: self.staged_memory.clone(), + disk: Vec::new(), + }, + Vec::new(), + ), + 1024, + ) + .await?; + } + + if !surviving.is_empty() { + let can_use_interior_row_count = + projection.is_some_and(Vec::is_empty) && exact_filter_plan.all_filters_exact; + let time_col = self + .time_partition + .as_deref() + .unwrap_or(DEFAULT_TIMESTAMP_KEY); + + let (interior_files, boundary_files) = + exact_filter_plan.split_files(surviving, &self.schema); + if can_use_interior_row_count { + if !interior_files.is_empty() + && let Some(count_plan) = + manifest_row_count_plan(&self.schema, &interior_files, limit, state) + .await? + { + execution_plans.push(count_plan); + } + } else if !interior_files.is_empty() { + let (partitions, statistics, _) = partitioned_files( + &self.schema, + &None, + interior_files, + state.config_options().execution.target_partitions, + false, + time_col, + ); + let plan = parquet_scan_plan_with_cache_options( + self.schema.clone(), + ObjectStoreUrl::local_filesystem(), + partitions, + statistics, + projection, + &[], + limit, + state, + 1024, + (0, 0, false), + ) + .await?; + execution_plans.push(plan); + } + + if !boundary_files.is_empty() { + let (partitions, statistics, _) = partitioned_files( + &self.schema, + &None, + boundary_files, + state.config_options().execution.target_partitions, + false, + time_col, + ); + let plan = parquet_scan_plan_with_cache_options( + self.schema.clone(), + ObjectStoreUrl::local_filesystem(), + partitions, + statistics, + projection, + &exact_filter_plan.exact_exprs, + limit, + state, + 1024, + (0, 0, false), + ) + .await?; + execution_plans.push(plan); + } + } + + if execution_plans.is_empty() { + let schema = match projection { + Some(proj) => Arc::new(self.schema.project(proj)?), + None => self.schema.clone(), + }; + Ok(Arc::new(EmptyExec::new(schema))) + } else if execution_plans.len() == 1 { + Ok(execution_plans.pop().unwrap()) + } else { + UnionExec::try_new(execution_plans) + } } } - #[test] - fn only_exact_time_filters_are_preinstalled_in_parquet_source() { + #[tokio::test] + async fn staging_unlimited_mem_table_skips_row_reversal_and_is_zero_copy() { let schema = Arc::new(Schema::new(vec![ + Field::new("payload", DataType::Utf8, false), Field::new( - "p_timestamp", - DataType::Timestamp(arrow_schema::TimeUnit::Millisecond, None), + DEFAULT_TIMESTAMP_KEY, + DataType::Timestamp(TimeUnit::Millisecond, None), false, ), - Field::new("job", DataType::Utf8, false), + Field::new("id", DataType::Int64, false), ])); - let exact_time = Expr::Column("p_timestamp".into()).gt_eq(Expr::Literal( - ScalarValue::TimestampMillisecond(Some(1_672_531_200_000), None), - None, - )); - let inexact_label = Expr::Column("job".into()).eq(Expr::Literal( - ScalarValue::Utf8(Some("api".to_owned())), - None, - )); - let filters = vec![exact_time.clone(), inexact_label.clone()]; + let payload = Arc::new(StringArray::from(vec!["p0", "p1", "p2"])); + let id_col_0 = Arc::new(Int64Array::from(vec![0, 1, 2])); + let id_col_1 = Arc::new(Int64Array::from(vec![3, 4, 5])); + let id0_ptr = id_col_0.to_data().buffers()[0].as_ptr(); + let id1_ptr = id_col_1.to_data().buffers()[0].as_ptr(); + + let records = vec![ + RecordBatch::try_new( + schema.clone(), + vec![ + payload.clone(), + Arc::new(TimestampMillisecondArray::from(vec![ + ts_ms(12, 0, 10), + ts_ms(12, 0, 30), + ts_ms(12, 0, 50), + ])), + id_col_0, + ], + ) + .unwrap(), + RecordBatch::try_new( + schema.clone(), + vec![ + payload.clone(), + Arc::new(TimestampMillisecondArray::from(vec![ + ts_ms(12, 1, 10), + ts_ms(12, 1, 30), + ts_ms(12, 1, 50), + ])), + id_col_1, + ], + ) + .unwrap(), + ]; - assert_eq!(exact_source_filters(&filters), vec![exact_time]); + let projection = vec![2]; + let filters = [col(DEFAULT_TIMESTAMP_KEY).gt_eq(ts_lit(ts_ms(12, 0, 30)))]; + let (table, remapped) = projected_staging_mem_table( + records, + schema.clone(), + Some(&projection), + &filters, + 2, + false, + ) + .unwrap(); - let context = SessionContext::new(); - let state = context.state(); - let (_, source) = - build_parquet_scan_components(schema, &filters, &state).expect("components build"); - let predicate = source.filter().expect("exact predicate").to_string(); - assert!(predicate.contains("p_timestamp")); - assert!(!predicate.contains("job")); - assert!(!predicate.contains("api")); + // Unprojected `payload` was dropped; retained `id` column buffers are zero-copy. + assert_eq!(Arc::strong_count(&payload), 1); + assert_eq!(table.batches.len(), 2); + { + let p0 = table.batches[0].read().await; + let p1 = table.batches[1].read().await; + assert_eq!(p0[0].column(1).to_data().buffers()[0].as_ptr(), id0_ptr); + assert_eq!(p1[0].column(1).to_data().buffers()[0].as_ptr(), id1_ptr); + } + + let ctx = SessionContext::new(); + let plan = + scan_enforcing_exact_filters(&table, &ctx.state(), remapped.as_ref(), &filters, None) + .await + .unwrap(); + let partitions = collect_partitioned(plan, ctx.task_ctx()).await.unwrap(); + let ids: Vec> = partitions + .iter() + .map(|batches| { + batches + .iter() + .flat_map(|b| { + b.column(0) + .as_any() + .downcast_ref::() + .unwrap() + .values() + .iter() + .copied() + }) + .collect() + }) + .collect(); + // Forward order preserved (no row reversal), mid-minute filter enforced. + assert_eq!(ids, vec![vec![1, 2], vec![3, 4, 5]]); } - #[test] - fn full_filters_are_preinstalled_in_parquet_source_when_requested() { + #[tokio::test] + async fn staging_execution_plans_omits_empty_branches_and_reverses_only_when_limited() { + let dir = TempDir::new().unwrap(); let schema = Arc::new(Schema::new(vec![ Field::new( - "p_timestamp", - DataType::Timestamp(arrow_schema::TimeUnit::Millisecond, None), + DEFAULT_TIMESTAMP_KEY, + DataType::Timestamp(TimeUnit::Millisecond, None), false, ), - Field::new("job", DataType::Utf8, false), + Field::new("id", DataType::Int64, false), ])); - let filters = vec![ - Expr::Column("p_timestamp".into()).gt_eq(Expr::Literal( - ScalarValue::TimestampMillisecond(Some(1_672_531_200_000), None), - None, - )), - Expr::Column("job".into()).eq(Expr::Literal( - ScalarValue::Utf8(Some("api".to_owned())), - None, - )), - ]; + let batch = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(TimestampMillisecondArray::from(vec![ + ts_ms(12, 0, 10), + ts_ms(12, 0, 20), + ts_ms(12, 0, 30), + ])), + Arc::new(Int64Array::from(vec![10, 20, 30])), + ], + ) + .unwrap(); + let pq_path = dir.path().join("staged.parquet"); + let pq_file = write_parquet(&pq_path, &batch); + let ctx = SessionContext::new(); + let state = ctx.state(); - let context = SessionContext::new(); - let state = context.state(); - let (_, source) = build_parquet_scan_components_with_full_filters(schema, &filters, &state) - .expect("components build"); - let predicate = source.filter().expect("full predicate").to_string(); - assert!(predicate.contains("p_timestamp")); - assert!(predicate.contains("job")); - assert!(predicate.contains("api")); + // 1. All staging sources empty -> 0 execution plans pushed. + let mut plans = Vec::new(); + staging_execution_plans( + &schema, + &mut plans, + Some(&vec![1]), + &[], + None, + &state, + (StagingCapture::default(), Vec::new()), + 1024, + ) + .await + .unwrap(); + assert!(plans.is_empty()); + + // 2. Only memory present -> 1 plan pushed (no empty ParquetExec). + let mut plans = Vec::new(); + staging_execution_plans( + &schema, + &mut plans, + Some(&vec![1]), + &[], + None, + &state, + ( + StagingCapture { + memory: vec![batch.clone()], + disk: Vec::new(), + }, + Vec::new(), + ), + 1024, + ) + .await + .unwrap(); + assert_eq!(plans.len(), 1); + let unlimited_batches = collect(plans.pop().unwrap(), ctx.task_ctx()).await.unwrap(); + let unlimited_ids: Vec = unlimited_batches + .iter() + .flat_map(|b| { + b.column(0) + .as_any() + .downcast_ref::() + .unwrap() + .values() + .iter() + .copied() + }) + .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). + let mut plans = Vec::new(); + staging_execution_plans( + &schema, + &mut plans, + Some(&vec![1]), + &[], + Some(2), + &state, + ( + StagingCapture { + memory: vec![batch.clone()], + disk: Vec::new(), + }, + Vec::new(), + ), + 1024, + ) + .await + .unwrap(); + assert_eq!(plans.len(), 1); + let limited_plan = plans.pop().unwrap(); + assert_eq!(limited_plan.properties().partitioning.partition_count(), 1); + let limited_batches = collect(limited_plan, ctx.task_ctx()).await.unwrap(); + let limited_ids: Vec = limited_batches + .iter() + .flat_map(|b| { + b.column(0) + .as_any() + .downcast_ref::() + .unwrap() + .values() + .iter() + .copied() + }) + .collect(); + assert_eq!(limited_ids, vec![30, 20, 10]); + + let mut plans = Vec::new(); + let filters = [col(DEFAULT_TIMESTAMP_KEY).gt_eq(ts_lit(ts_ms(12, 0, 10)))]; + staging_execution_plans( + &schema, + &mut plans, + Some(&vec![1]), + &filters, + Some(2), + &state, + ( + StagingCapture { + memory: vec![batch], + disk: Vec::new(), + }, + Vec::new(), + ), + 1024, + ) + .await + .unwrap(); + assert_eq!(plans.len(), 1); + let filtered_limited_batches = collect(plans.pop().unwrap(), ctx.task_ctx()).await.unwrap(); + let filtered_limited_ids: Vec = filtered_limited_batches + .iter() + .flat_map(|b| { + b.column(0) + .as_any() + .downcast_ref::() + .unwrap() + .values() + .iter() + .copied() + }) + .collect(); + assert_eq!(filtered_limited_ids, vec![30, 20]); + + // 4. Only staged Parquet present -> 1 plan pushed (no empty MemTable). + let mut plans = Vec::new(); + staging_execution_plans( + &schema, + &mut plans, + Some(&vec![1]), + &[], + None, + &state, + ( + StagingCapture::default(), + vec![PartitionedFile::new(pq_file.file_path, pq_file.file_size)], + ), + 1024, + ) + .await + .unwrap(); + assert_eq!(plans.len(), 1); } - #[test] - fn only_minute_aligned_partition_column_bounds_are_exact() { - let minute = ScalarValue::TimestampMillisecond(Some(1_672_531_200_000), None); - let mid_minute = ScalarValue::TimestampMillisecond(Some(1_672_531_230_000), None); - let bound = |column: &str, value: &ScalarValue| { - Expr::Column(column.into()).gt_eq(Expr::Literal(value.clone(), None)) - }; - let event_time = Some("event_time".to_owned()); + #[tokio::test] + async fn late_upload_into_closed_manifest_invalidates_shared_slot() { + let cache = MetadataCache::new(Duration::from_secs(60)); + let closed_path = "logs/date=2026-11-29/manifest.json"; + + let mut old_manifest = Manifest::default(); + old_manifest.files.push(File { + file_path: "old.parquet".to_owned(), + num_rows: 10, + ..File::default() + }); + let (slot1, lease1) = cache + .reserve_manifest_slot("logs", &None, closed_path) + .expect("cache enabled"); + lease1 + .expect("first caller owns lease") + .fulfill(Some(old_manifest)); + let got1 = slot1 + .get_or_load(|| async { Ok::<_, String>(None) }) + .await + .unwrap(); + assert_eq!(got1.as_ref().as_ref().unwrap().files.len(), 1); + + // Concurrent live-window query hits the cached closed manifest. + let (slot2, lease2) = cache + .reserve_manifest_slot("logs", &None, closed_path) + .expect("cache enabled"); + assert!(lease2.is_none()); + let got2 = slot2 + .get_or_load(|| async { Ok::<_, String>(None) }) + .await + .unwrap(); + assert_eq!(got2.as_ref().as_ref().unwrap().files.len(), 1); - let cases = [ - (bound("p_timestamp", &minute), &None, true), - (bound("p_timestamp", &mid_minute), &None, false), - (bound("created_at", &minute), &None, false), - (bound("event_time", &minute), &event_time, true), - // Ingestion time on a stream partitioned by event time. - (bound("p_timestamp", &minute), &event_time, false), - ( - Expr::Literal(minute.clone(), None).lt(Expr::Column("p_timestamp".into())), - &None, - false, - ), - ]; - for (filter, time_partition, exact) in cases { - assert_eq!( - matches!( - super::filter_pushdown(&filter, time_partition), - TableProviderFilterPushDown::Exact - ), - exact, - "{filter} with time partition {time_partition:?}" - ); - } + // Local late upload publishes to the older manifest and invalidates the stream. + cache.invalidate_stream("logs", &None); + + let mut updated_manifest = Manifest::default(); + updated_manifest.files.push(File { + file_path: "old.parquet".to_owned(), + num_rows: 10, + ..File::default() + }); + updated_manifest.files.push(File { + file_path: "late.parquet".to_owned(), + num_rows: 5, + ..File::default() + }); + let (slot3, lease3) = cache + .reserve_manifest_slot("logs", &None, closed_path) + .expect("cache enabled"); + lease3 + .expect("invalidated closed manifest must reload") + .fulfill(Some(updated_manifest)); + let got3 = slot3 + .get_or_load(|| async { Ok::<_, String>(None) }) + .await + .unwrap(); + assert_eq!(got3.as_ref().as_ref().unwrap().files.len(), 2); } #[tokio::test] - async fn limit_is_pushed_into_scan_only_for_exact_partition_bounds() { - // `collect_from_snapshot` truncates the file list by row counts when a - // limit reaches the scan, so it must not see one when a filter only - // partially matches the surviving files. + async fn mid_minute_bounds_exact_row_parity_across_interior_boundary_and_staging() { + let dir = TempDir::new().unwrap(); let schema = Arc::new(Schema::new(vec![ Field::new( - "p_timestamp", - DataType::Timestamp(arrow_schema::TimeUnit::Millisecond, None), - false, - ), - Field::new( - "created_at", - DataType::Timestamp(arrow_schema::TimeUnit::Millisecond, None), + DEFAULT_TIMESTAMP_KEY, + DataType::Timestamp(TimeUnit::Millisecond, None), false, ), + Field::new("app", DataType::Utf8, false), + Field::new("id", DataType::Int64, false), ])); - let context = SessionContext::new(); - context - .register_table("logs", Arc::new(TestParquetProvider { schema })) + + // 4 Parquet files (minutes 00:00 .. 00:03), 6 rows each at seconds 0,10,20,30,40,50. + // Plus in-memory staging batch spanning minute 00:03 (seconds 5, 14, 15, 45). + let mut all_rows: Vec<(i64, &'static str, i64)> = Vec::new(); + let mut manifest_files_oldest_first = Vec::new(); + let mut next_id = 0i64; + for minute in 0..4u32 { + let mut ts = Vec::new(); + let mut apps = Vec::new(); + let mut ids = Vec::new(); + for (idx, sec) in [0u32, 10, 20, 30, 40, 50].into_iter().enumerate() { + let t = ts_ms(12, minute, sec); + let app = if idx % 2 == 0 { "api" } else { "worker" }; + let id = next_id; + next_id += 1; + ts.push(t); + apps.push(app); + ids.push(id); + all_rows.push((t, app, id)); + } + let batch = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(TimestampMillisecondArray::from(ts)), + Arc::new(StringArray::from(apps)), + Arc::new(Int64Array::from(ids)), + ], + ) .unwrap(); + manifest_files_oldest_first.push(write_parquet( + &dir.path().join(format!("m{minute}.parquet")), + &batch, + )); + } + // Newest-first manifest order. + manifest_files_oldest_first.reverse(); + + let staged_rows = [ + (ts_ms(12, 3, 5), "api", 1000i64), + (ts_ms(12, 3, 14), "worker", 1001i64), + (ts_ms(12, 3, 15), "api", 1002i64), + (ts_ms(12, 3, 45), "worker", 1003i64), + ]; + for &row in &staged_rows { + all_rows.push(row); + } + let staged_batch = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(TimestampMillisecondArray::from( + staged_rows.iter().map(|r| r.0).collect::>(), + )), + Arc::new(StringArray::from( + staged_rows.iter().map(|r| r.1).collect::>(), + )), + Arc::new(Int64Array::from( + staged_rows.iter().map(|r| r.2).collect::>(), + )), + ], + ) + .unwrap(); - for (column, limit_pushed) in [("p_timestamp", true), ("created_at", false)] { - let plan = context - .sql(&format!( - "SELECT * FROM logs WHERE {column} >= '2023-01-01T00:00:00' LIMIT 5" - )) + let start = ts_ms(12, 0, 30); + let end = ts_ms(12, 3, 15); + let expected_in_window: Vec<(i64, &str, i64)> = all_rows + .iter() + .copied() + .filter(|(t, _, _)| *t >= start && *t < end) + .collect(); + + // Test BOTH default SessionConfig (`pushdown_filters = false`) and + // production SessionConfig (`pushdown_filters = true`). + for pushdown_filters in [false, true] { + let mut config = SessionConfig::new(); + config.options_mut().execution.parquet.pushdown_filters = pushdown_filters; + let ctx = SessionContext::new_with_config(config); + ctx.register_table( + "t", + Arc::new(InteriorSplitTestTable { + schema: schema.clone(), + time_partition: None, + manifest_files: manifest_files_oldest_first.clone(), + staged_memory: vec![staged_batch.clone()], + }), + ) + .unwrap(); + + // 1. SELECT * with mid-minute start and end. + let select_all_sql = "SELECT id, p_timestamp, app FROM t \ + WHERE p_timestamp >= '2026-11-30T12:00:30' AND p_timestamp < '2026-11-30T12:03:15' \ + ORDER BY id"; + let batches = ctx + .sql(select_all_sql) + .await + .unwrap() + .collect() + .await + .unwrap(); + let mut got_ids = Vec::new(); + for b in &batches { + let ids = b.column(0).as_any().downcast_ref::().unwrap(); + got_ids.extend(ids.values().iter().copied()); + } + let mut expected_ids: Vec = expected_in_window.iter().map(|r| r.2).collect(); + expected_ids.sort_unstable(); + assert_eq!(got_ids, expected_ids, "pushdown_filters={pushdown_filters}"); + + // 2. SELECT app, count(*) GROUP BY app — interior ParquetExec must NOT have predicate, + // boundary ParquetExec MUST have predicate. + let group_sql = "SELECT app, count(*) AS c FROM t \ + WHERE p_timestamp >= '2026-11-30T12:00:30' AND p_timestamp < '2026-11-30T12:03:15' \ + GROUP BY app ORDER BY app"; + let group_plan = ctx + .sql(group_sql) .await .unwrap() .create_physical_plan() .await .unwrap(); - let plan = displayable(plan.as_ref()).indent(true).to_string(); - let source_line = plan + let plan_text = displayable(group_plan.as_ref()).indent(true).to_string(); + let parquet_lines: Vec<&str> = plan_text .lines() - .find(|line| line.contains("DataSourceExec")) - .expect("parquet source line"); + .filter(|line| line.contains("DataSourceExec") && line.contains("m")) + .collect(); + assert!( + parquet_lines + .iter() + .any(|line| line.contains("m1.parquet") && !line.contains("predicate=")), + "interior files must omit exact time predicate:\n{plan_text}" + ); + assert!( + parquet_lines + .iter() + .any(|line| line.contains("m0.parquet") && line.contains("predicate=")), + "boundary files must enforce exact time predicate:\n{plan_text}" + ); - assert_eq!(source_line.contains("limit=5"), limit_pushed, "{plan}"); + let group_batches = collect(group_plan, ctx.task_ctx()).await.unwrap(); + let mut got_groups = Vec::new(); + for b in &group_batches { + let apps = b.column(0).as_any().downcast_ref::().unwrap(); + let counts = b.column(1).as_any().downcast_ref::().unwrap(); + for i in 0..b.num_rows() { + got_groups.push((apps.value(i).to_owned(), counts.value(i))); + } + } + let expected_api = expected_in_window.iter().filter(|r| r.1 == "api").count() as i64; + let expected_worker = expected_in_window + .iter() + .filter(|r| r.1 == "worker") + .count() as i64; assert_eq!( - plan.lines() - .any(|line| line.contains("FilterExec") && line.contains(column)), - !limit_pushed, - "{plan}" + got_groups, + vec![ + ("api".to_owned(), expected_api), + ("worker".to_owned(), expected_worker), + ], + "pushdown_filters={pushdown_filters}" + ); + + // 3. SELECT count(*) with mid-minute bounds. + let count_sql = "SELECT count(*) AS c FROM t \ + WHERE p_timestamp >= '2026-11-30T12:00:30' AND p_timestamp < '2026-11-30T12:03:15'"; + let count_batches = ctx.sql(count_sql).await.unwrap().collect().await.unwrap(); + let got_count = count_batches[0] + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .value(0); + assert_eq!( + got_count, + expected_in_window.len() as i64, + "pushdown_filters={pushdown_filters}" ); + + // 4. Boundary-only sub-minute COUNT(*), MIN, MAX must never use stale pre-filter stats. + let sub_minute_sql = "SELECT count(*) AS c, min(p_timestamp) AS lo, max(p_timestamp) AS hi \ + FROM t WHERE p_timestamp >= '2026-11-30T12:00:20' AND p_timestamp <= '2026-11-30T12:00:40'"; + let sub_batches = ctx + .sql(sub_minute_sql) + .await + .unwrap() + .collect() + .await + .unwrap(); + let sub_count = sub_batches[0] + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .value(0); + let sub_min = sub_batches[0] + .column(1) + .as_any() + .downcast_ref::() + .unwrap() + .value(0); + let sub_max = sub_batches[0] + .column(2) + .as_any() + .downcast_ref::() + .unwrap() + .value(0); + assert_eq!(sub_count, 3, "pushdown_filters={pushdown_filters}"); + assert_eq!(sub_min, ts_ms(12, 0, 20)); + assert_eq!(sub_max, ts_ms(12, 0, 40)); + + // 5. Exact equality predicate (`Eq`) on mid-minute timestamp. + let eq_sql = "SELECT id FROM t WHERE p_timestamp = '2026-11-30T12:01:30' ORDER BY id"; + let eq_batches = ctx.sql(eq_sql).await.unwrap().collect().await.unwrap(); + let eq_ids: Vec = eq_batches + .iter() + .flat_map(|b| { + b.column(0) + .as_any() + .downcast_ref::() + .unwrap() + .values() + .iter() + .copied() + }) + .collect(); + let expected_eq_ids: Vec = all_rows + .iter() + .filter(|(t, _, _)| *t == ts_ms(12, 1, 30)) + .map(|r| r.2) + .collect(); + assert_eq!(eq_ids, expected_eq_ids); } } #[tokio::test] - async fn optimized_plan_enforces_exact_time_once_without_duplicating_inexact_filter() { + async fn zero_io_interior_count_never_opens_interior_parquet_files() { + let dir = TempDir::new().unwrap(); let schema = Arc::new(Schema::new(vec![ Field::new( - "p_timestamp", - DataType::Timestamp(arrow_schema::TimeUnit::Millisecond, None), + DEFAULT_TIMESTAMP_KEY, + DataType::Timestamp(TimeUnit::Millisecond, None), false, ), - Field::new("job", DataType::Utf8, false), + Field::new("app", DataType::Utf8, false), ])); - let context = SessionContext::new(); - context - .register_table( - "metrics", - Arc::new(TestParquetProvider { - schema: Arc::clone(&schema), - }), - ) - .unwrap(); - let exact_time = Expr::Column("p_timestamp".into()).gt_eq(Expr::Literal( - ScalarValue::TimestampMillisecond(Some(1_672_531_200_000), None), - None, - )); - let inexact_label = Expr::Column("job".into()).eq(Expr::Literal( - ScalarValue::Utf8(Some("api".to_owned())), - None, - )); - - let plan = context - .table("metrics") - .await - .unwrap() - .filter(exact_time.and(inexact_label)) - .unwrap() - .create_physical_plan() - .await - .unwrap(); - let plan = displayable(plan.as_ref()).indent(true).to_string(); - let filter_lines = plan - .lines() - .filter(|line| line.contains("FilterExec")) - .collect::>(); - let source_line = plan - .lines() - .find(|line| line.contains("DataSourceExec")) - .expect("parquet source line"); - - assert_eq!(filter_lines.len(), 1, "{plan}"); - assert!(filter_lines[0].contains("job"), "{plan}"); - assert!(!filter_lines[0].contains("p_timestamp"), "{plan}"); - assert!(source_line.contains("predicate=p_timestamp"), "{plan}"); - assert!(!source_line.contains("predicate=job"), "{plan}"); - } - - #[test] - fn byte_balancing_uses_least_loaded_group_and_preserves_input_order() { - let files = vec![ - file("z.parquet", 10), - file("y.parquet", 9), - file("x.parquet", 8), - file("w.parquet", 7), - file("v.parquet", 6), - ]; - let groups = balanced_file_groups(files, 3); - - assert_eq!( - group_paths(&groups), + // Real boundary files at 12:00 and 12:03. + let boundary_start_batch = RecordBatch::try_new( + schema.clone(), vec![ - vec!["z.parquet"], - vec!["y.parquet", "v.parquet"], - vec!["x.parquet", "w.parquet"], - ] - ); - assert_eq!( - groups - .iter() - .map(|group| group.iter().map(|file| file.file_size).sum::()) - .collect::>(), - vec![10, 15, 15] - ); - } - - #[test] - fn byte_balancing_omits_empty_groups_and_handles_empty_input() { - assert_eq!( - group_paths(&balanced_file_groups( - vec![file("z.parquet", 2), file("y.parquet", 1)], - 8, - )), - vec![vec!["z.parquet"], vec!["y.parquet"]] - ); - assert!(balanced_file_groups(Vec::new(), 4).is_empty()); - assert!(balanced_file_groups(vec![file("z.parquet", 1)], 0).is_empty()); - } - - #[test] - fn byte_balancing_uses_largest_files_first_without_reordering_each_group() { - let files = vec![ - file("first.parquet", 6), - file("second.parquet", 10), - file("third.parquet", 7), - file("fourth.parquet", 9), - file("fifth.parquet", 8), - ]; - - let groups = balanced_file_groups(files, 3); - - assert_eq!( - group_paths(&groups), + Arc::new(TimestampMillisecondArray::from(vec![ + ts_ms(12, 0, 10), + ts_ms(12, 0, 35), + ts_ms(12, 0, 50), + ])), + Arc::new(StringArray::from(vec!["api", "api", "worker"])), + ], + ) + .unwrap(); + let boundary_end_batch = RecordBatch::try_new( + schema.clone(), vec![ - vec!["second.parquet"], - vec!["first.parquet", "fourth.parquet"], - vec!["third.parquet", "fifth.parquet"], - ] + Arc::new(TimestampMillisecondArray::from(vec![ + ts_ms(12, 3, 5), + ts_ms(12, 3, 25), + ])), + Arc::new(StringArray::from(vec!["api", "worker"])), + ], + ) + .unwrap(); + let f_start = write_parquet(&dir.path().join("m0.parquet"), &boundary_start_batch); + let f_end = write_parquet(&dir.path().join("m3.parquet"), &boundary_end_batch); + + // Interior manifest entries point to NON-EXISTENT paths: if execution + // ever attempted to open them, the query would fail with NotFound. + let verified_ts = Some(crate::catalog::column::StatsProvenance { + complete_row_groups: true, + exact_min_max: true, + timestamp_unit: Some(crate::catalog::column::ManifestTimeUnit::Millisecond), + }); + let fake_interior = |name: &str, min_ms: i64, max_ms: i64, num_rows: u64| File { + file_path: dir.path().join(name).to_string_lossy().into_owned(), + num_rows, + file_size: 4096, + columns: vec![Column { + name: DEFAULT_TIMESTAMP_KEY.to_owned(), + stats: Some(TypedStatistics::Int(Int64Type { + min: min_ms, + max: max_ms, + })), + null_count: Some(0), + uncompressed_size: 0, + compressed_size: 0, + stats_provenance: verified_ts, + }], + ..File::default() + }; + let f_mid1 = fake_interior( + "does_not_exist_m1.parquet", + ts_ms(12, 1, 0), + ts_ms(12, 1, 59), + 15_000, ); - assert_eq!( - groups - .iter() - .map(|group| group.iter().map(|file| file.file_size).sum::()) - .collect::>(), - vec![10, 15, 15] + let f_mid2 = fake_interior( + "does_not_exist_m2.parquet", + ts_ms(12, 2, 0), + ts_ms(12, 2, 59), + 25_000, ); + + let ctx = SessionContext::new(); + ctx.register_table( + "t", + Arc::new(InteriorSplitTestTable { + schema: schema.clone(), + time_partition: None, + manifest_files: vec![f_end, f_mid2, f_mid1, f_start], + staged_memory: Vec::new(), + }), + ) + .unwrap(); + + // 2 matching rows in m0 (00:35, 00:50) + 15_000 + 25_000 interior + 1 matching row in m3 (03:05) = 40_003. + let batches = ctx + .sql( + "SELECT count(*) AS c FROM t \ + WHERE p_timestamp >= '2026-11-30T12:00:30' AND p_timestamp < '2026-11-30T12:03:15'", + ) + .await + .unwrap() + .collect() + .await + .unwrap(); + let count = batches[0] + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .value(0); + assert_eq!(count, 40_003); + + // Checked u64 overflow guard rejects corrupt row counts cleanly. + let overflow_files = vec![ + File { + num_rows: u64::MAX, + ..File::default() + }, + File { + num_rows: 1, + ..File::default() + }, + ]; + assert!(checked_manifest_total_rows(&overflow_files).is_err()); } - #[test] - fn scan_order_is_never_advertised_from_footer_sort_order() { - // Footer-derived `sort_order_id` plus non-overlapping statistics: a single file can still - // be unsorted inside, so neither one file nor a statistics-chained group is advertised. - let schema = Arc::new(Schema::new(vec![Field::new( - "p_timestamp", - DataType::Timestamp(arrow_schema::TimeUnit::Millisecond, None), - true, - )])); - for files in [ - vec![time_sorted_file("only.parquet", 10, 100, 199)], + #[tokio::test] + async fn empty_projection_count_with_inexact_filter_does_not_take_row_count_shortcut() { + let dir = TempDir::new().unwrap(); + let schema = Arc::new(Schema::new(vec![ + Field::new( + DEFAULT_TIMESTAMP_KEY, + DataType::Timestamp(TimeUnit::Millisecond, None), + false, + ), + Field::new("app", DataType::Utf8, false), + ])); + let batch = RecordBatch::try_new( + schema.clone(), vec![ - time_sorted_file("new.parquet", 10, 200, 299), - time_sorted_file("old.parquet", 10, 100, 199), + Arc::new(TimestampMillisecondArray::from(vec![ + ts_ms(12, 1, 10), + ts_ms(12, 1, 20), + ts_ms(12, 1, 30), + ts_ms(12, 1, 40), + ])), + Arc::new(StringArray::from(vec!["api", "worker", "api", "worker"])), ], - ] { - for target_partitions in [1, 4] { - let (_, _, ordered) = super::partitioned_files( - &schema, - &None, - files.clone(), - target_partitions, - false, - "p_timestamp", - ); - assert!(!ordered); - } - } - } + ) + .unwrap(); + let f_mid = write_parquet(&dir.path().join("m1.parquet"), &batch); - fn datetime_min(year: i32, month: u32, day: u32) -> DateTime { - NaiveDate::from_ymd_opt(year, month, day) - .unwrap() - .and_time(NaiveTime::MIN) - .and_utc() - } + let filters = [ + col(DEFAULT_TIMESTAMP_KEY).gt_eq(ts_lit(ts_ms(12, 0, 30))), + col(DEFAULT_TIMESTAMP_KEY).lt(ts_lit(ts_ms(12, 2, 15))), + col("app").eq(lit("api")), + ]; + let plan = ExactTimeFilterPlan::new(&filters, &None); + assert!(!plan.all_filters_exact); - fn datetime_max(year: i32, month: u32, day: u32) -> DateTime { - NaiveDate::from_ymd_opt(year, month, day) + let ctx = SessionContext::new(); + ctx.register_table( + "t", + Arc::new(InteriorSplitTestTable { + schema, + time_partition: None, + manifest_files: vec![f_mid], + staged_memory: Vec::new(), + }), + ) + .unwrap(); + + let batches = ctx + .sql( + "SELECT count(*) AS c FROM t \ + WHERE p_timestamp >= '2026-11-30T12:00:30' \ + AND p_timestamp < '2026-11-30T12:02:15' \ + AND app = 'api'", + ) + .await .unwrap() - .and_hms_milli_opt(23, 59, 59, 999) + .collect() + .await + .unwrap(); + let count = batches[0] + .column(0) + .as_any() + .downcast_ref::() .unwrap() - .and_utc() + .value(0); + assert_eq!(count, 2); } - fn manifest_items() -> Vec { - vec![ - ManifestItem { - manifest_path: "1".to_string(), - time_lower_bound: datetime_min(2023, 12, 15), - time_upper_bound: datetime_max(2023, 12, 15), - events_ingested: 0, - ingestion_size: 0, - storage_size: 0, - }, - ManifestItem { - manifest_path: "2".to_string(), - time_lower_bound: datetime_min(2023, 12, 16), - time_upper_bound: datetime_max(2023, 12, 16), - events_ingested: 0, - ingestion_size: 0, - storage_size: 0, - }, - ManifestItem { - manifest_path: "3".to_string(), - time_lower_bound: datetime_min(2023, 12, 17), - time_upper_bound: datetime_max(2023, 12, 17), - events_ingested: 0, - ingestion_size: 0, - storage_size: 0, - }, - ] - } + #[tokio::test] + async fn missing_or_nullable_timestamp_stats_stay_in_boundary_files() { + let nullable_schema = Arc::new(Schema::new(vec![Field::new( + DEFAULT_TIMESTAMP_KEY, + DataType::Timestamp(TimeUnit::Millisecond, None), + true, + )])); + let non_null_schema = Arc::new(Schema::new(vec![Field::new( + DEFAULT_TIMESTAMP_KEY, + DataType::Timestamp(TimeUnit::Millisecond, None), + false, + )])); - #[test] - fn bound_min_is_overlapping() { - let res = is_overlapping_query( - &manifest_items(), - &[PartialTimeFilter::Low(std::ops::Bound::Included( - datetime_min(2023, 12, 14).naive_utc(), - ))], - ); + let filters = [ + col(DEFAULT_TIMESTAMP_KEY).gt_eq(ts_lit(ts_ms(12, 0, 30))), + col(DEFAULT_TIMESTAMP_KEY).lt(ts_lit(ts_ms(12, 3, 15))), + ]; + let filter_plan = ExactTimeFilterPlan::new(&filters, &None); - assert!(res) - } + let valid_stats = Some(TypedStatistics::Int(Int64Type { + min: ts_ms(12, 1, 0), + max: ts_ms(12, 1, 59), + })); + let make_file = |path: &str, col: Option| File { + file_path: path.to_owned(), + num_rows: 10, + columns: col.into_iter().collect(), + ..File::default() + }; - #[test] - fn bound_min_plus_hour_is_overlapping() { - let res = is_overlapping_query( - &manifest_items(), - &[PartialTimeFilter::Low(std::ops::Bound::Included( - datetime_min(2023, 12, 14) - .naive_utc() - .add(Duration::hours(3)), - ))], + let verified_ts = Some(crate::catalog::column::StatsProvenance { + complete_row_groups: true, + exact_min_max: true, + timestamp_unit: Some(crate::catalog::column::ManifestTimeUnit::Millisecond), + }); + let missing_col = make_file("missing_col.parquet", None); + let missing_stats = make_file( + "missing_stats.parquet", + Some(Column { + name: DEFAULT_TIMESTAMP_KEY.to_owned(), + stats: None, + null_count: Some(0), + uncompressed_size: 0, + compressed_size: 0, + stats_provenance: verified_ts, + }), + ); + let has_nulls = make_file( + "has_nulls.parquet", + Some(Column { + name: DEFAULT_TIMESTAMP_KEY.to_owned(), + stats: valid_stats.clone(), + null_count: Some(1), + uncompressed_size: 0, + compressed_size: 0, + stats_provenance: verified_ts, + }), + ); + let unknown_nulls = make_file( + "unknown_nulls.parquet", + Some(Column { + name: DEFAULT_TIMESTAMP_KEY.to_owned(), + stats: valid_stats.clone(), + null_count: None, + uncompressed_size: 0, + compressed_size: 0, + stats_provenance: verified_ts, + }), + ); + let legacy_no_provenance = make_file( + "legacy_no_provenance.parquet", + Some(Column { + name: DEFAULT_TIMESTAMP_KEY.to_owned(), + stats: valid_stats.clone(), + null_count: Some(0), + uncompressed_size: 0, + compressed_size: 0, + stats_provenance: None, + }), + ); + let inverted_stats = make_file( + "inverted.parquet", + Some(Column { + name: DEFAULT_TIMESTAMP_KEY.to_owned(), + stats: Some(TypedStatistics::Int(Int64Type { + min: ts_ms(12, 1, 59), + max: ts_ms(12, 1, 0), + })), + null_count: Some(0), + uncompressed_size: 0, + compressed_size: 0, + stats_provenance: verified_ts, + }), + ); + let string_stats = make_file( + "string_stats.parquet", + Some(Column { + name: DEFAULT_TIMESTAMP_KEY.to_owned(), + stats: Some(TypedStatistics::String(Utf8Type { + min: "a".to_owned(), + max: "z".to_owned(), + })), + null_count: Some(0), + uncompressed_size: 0, + compressed_size: 0, + stats_provenance: verified_ts, + }), + ); + let verified_zero_nulls = make_file( + "verified_zero_nulls.parquet", + Some(Column { + name: DEFAULT_TIMESTAMP_KEY.to_owned(), + stats: valid_stats, + null_count: Some(0), + uncompressed_size: 0, + compressed_size: 0, + stats_provenance: verified_ts, + }), ); - assert!(res) - } + let all = vec![ + missing_col, + missing_stats, + has_nulls, + unknown_nulls, + legacy_no_provenance, + inverted_stats, + string_stats, + verified_zero_nulls, + ]; - #[test] - fn bound_next_day_min_is_not_overlapping() { - let res = is_overlapping_query( - &manifest_items(), - &[PartialTimeFilter::Low(std::ops::Bound::Included( - datetime_min(2023, 12, 16).naive_utc(), - ))], + // On nullable schema: ONLY `verified_zero_nulls` is interior. + let (interior, boundary) = filter_plan.split_files(all.clone(), &nullable_schema); + assert_eq!( + interior + .iter() + .map(|f| f.file_path.as_str()) + .collect::>(), + vec!["verified_zero_nulls.parquet"] ); + assert_eq!(boundary.len(), 7); - assert!(!res) - } + // On non-nullable schema: certified `unknown_nulls` AND `verified_zero_nulls` + // are interior; `legacy_no_provenance` and `has_nulls` STAY boundary! + let (interior, boundary) = filter_plan.split_files(all, &non_null_schema); + assert_eq!( + interior + .iter() + .map(|f| f.file_path.as_str()) + .collect::>(), + vec!["unknown_nulls.parquet", "verified_zero_nulls.parquet"] + ); + assert_eq!(boundary.len(), 6); - #[test] - fn out_of_range_millisecond_literal_yields_no_bound() { - let binexpr = BinaryExpr { - left: Box::new(Expr::Column("p_timestamp".into())), - op: Operator::GtEq, - right: Box::new(Expr::Literal( - ScalarValue::TimestampMillisecond(Some(i64::MAX), None), + // Real Parquet file with a NULL timestamp row inside an otherwise in-range minute: + // must stay in boundary_files and exclude the NULL row in COUNT(*). + let dir = TempDir::new().unwrap(); + let batch_with_null = RecordBatch::try_new( + nullable_schema.clone(), + vec![Arc::new(TimestampMillisecondArray::from(vec![ + Some(ts_ms(12, 1, 10)), None, - )), - }; - - assert_eq!(extract_timestamp_bound(&binexpr, &None), None); - assert!(!super::expr_in_boundary(&Expr::BinaryExpr(binexpr))); - } - - #[tokio::test] - async fn out_of_range_millisecond_literal_in_sql_does_not_panic() { - let schema = Arc::new(Schema::new(vec![Field::new( - "p_timestamp", - DataType::Timestamp(arrow_schema::TimeUnit::Millisecond, None), - false, - )])); - let context = SessionContext::new(); - context - .register_table("logs", Arc::new(TestParquetProvider { schema })) - .unwrap(); + Some(ts_ms(12, 1, 40)), + ]))], + ) + .unwrap(); + let f_null = write_parquet(&dir.path().join("with_null.parquet"), &batch_with_null); + assert!(!filter_plan.file_is_interior(&f_null, &nullable_schema)); - context - .sql("SELECT * FROM logs WHERE p_timestamp >= to_timestamp_millis(9223372036854775807)") + let ctx = SessionContext::new(); + ctx.register_table( + "t", + Arc::new(InteriorSplitTestTable { + schema: nullable_schema, + time_partition: None, + manifest_files: vec![f_null], + staged_memory: Vec::new(), + }), + ) + .unwrap(); + let batches = ctx + .sql( + "SELECT count(*) AS c FROM t \ + WHERE p_timestamp >= '2026-11-30T12:00:30' AND p_timestamp < '2026-11-30T12:03:15'", + ) .await .unwrap() - .create_physical_plan() + .collect() .await .unwrap(); + let count = batches[0] + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .value(0); + assert_eq!(count, 2); } - #[test] - fn timestamp_in_milliseconds() { - let binexpr = BinaryExpr { - left: Box::new(Expr::Column("timestamp_column".into())), - op: Operator::Eq, - right: Box::new(Expr::Literal( - ScalarValue::TimestampMillisecond(Some(1672531200000), None), - None, - )), - }; - - let time_partition = Some("timestamp_column".to_string()); - let result = extract_timestamp_bound(&binexpr, &time_partition); - - let expected = Some(( - Operator::Eq, - NaiveDateTime::parse_from_str("2023-01-01 00:00:00", "%Y-%m-%d %H:%M:%S").unwrap(), - )); - - assert_eq!(result, expected); - } - - #[test] - fn timestamp_in_nanoseconds() { - let binexpr = BinaryExpr { - left: Box::new(Expr::Column("timestamp_column".into())), - op: Operator::Gt, - right: Box::new(Expr::Literal( - ScalarValue::TimestampNanosecond(Some(1672531200000000000), None), - None, - )), - }; + #[tokio::test] + async fn custom_time_partition_uses_partition_column_and_keeps_p_timestamp_inexact() { + let dir = TempDir::new().unwrap(); + let schema = Arc::new(Schema::new(vec![ + Field::new( + DEFAULT_TIMESTAMP_KEY, + DataType::Timestamp(TimeUnit::Millisecond, None), + false, + ), + Field::new( + "event_time", + DataType::Timestamp(TimeUnit::Millisecond, None), + false, + ), + Field::new("id", DataType::Int64, false), + ])); + // Ingestion `p_timestamp` is at 12:05 (outside the event_time range), + // while `event_time` is in 12:01 (interior for [12:00:30, 12:02:15)). + let batch = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(TimestampMillisecondArray::from(vec![ + ts_ms(12, 5, 10), + ts_ms(12, 5, 20), + ts_ms(12, 5, 40), + ])), + Arc::new(TimestampMillisecondArray::from(vec![ + ts_ms(12, 1, 10), + ts_ms(12, 1, 20), + ts_ms(12, 1, 40), + ])), + Arc::new(Int64Array::from(vec![1, 2, 3])), + ], + ) + .unwrap(); + let f = write_parquet(&dir.path().join("custom_tp.parquet"), &batch); - let time_partition = Some("timestamp_column".to_string()); - let result = extract_timestamp_bound(&binexpr, &time_partition); + let custom_tp = Some("event_time".to_owned()); + let ctx = SessionContext::new(); + ctx.register_table( + "t", + Arc::new(InteriorSplitTestTable { + schema: schema.clone(), + time_partition: custom_tp.clone(), + manifest_files: vec![f], + staged_memory: Vec::new(), + }), + ) + .unwrap(); - let expected = Some(( - Operator::Gt, - NaiveDateTime::parse_from_str("2023-01-01 00:00:00", "%Y-%m-%d %H:%M:%S").unwrap(), - )); + // Bound on `p_timestamp` stays Inexact -> DataFusion retains FilterExec. + let p_ts_plan = ctx + .sql("SELECT count(*) AS c FROM t WHERE p_timestamp >= '2026-11-30T12:05:20'") + .await + .unwrap() + .create_physical_plan() + .await + .unwrap(); + let plan_text = displayable(p_ts_plan.as_ref()).indent(true).to_string(); + assert!( + plan_text.contains("FilterExec") && plan_text.contains("p_timestamp"), + "p_timestamp filter must remain Inexact on custom time_partition:\n{plan_text}" + ); + let p_ts_batches = collect(p_ts_plan, ctx.task_ctx()).await.unwrap(); + assert_eq!( + p_ts_batches[0] + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .value(0), + 2 + ); - assert_eq!(result, expected); + // Bound on `event_time` is Exact -> DataFusion drops FilterExec and classifies interior. + let ev_plan = ctx + .sql( + "SELECT count(*) AS c FROM t \ + WHERE event_time >= '2026-11-30T12:00:30' AND event_time < '2026-11-30T12:02:15'", + ) + .await + .unwrap() + .create_physical_plan() + .await + .unwrap(); + let ev_plan_text = displayable(ev_plan.as_ref()).indent(true).to_string(); + assert!( + !ev_plan_text.contains("FilterExec"), + "event_time exact filter should be pushed down:\n{ev_plan_text}" + ); + let ev_batches = collect(ev_plan, ctx.task_ctx()).await.unwrap(); + assert_eq!( + ev_batches[0] + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .value(0), + 3 + ); } - #[test] - fn string_timestamp() { - let timestamp = "2023-01-01T00:00:00"; - let binexpr = BinaryExpr { - left: Box::new(Expr::Column("timestamp_column".into())), - op: Operator::Lt, - right: Box::new(Expr::Literal( - ScalarValue::Utf8(Some(timestamp.to_owned())), - None, - )), - }; + #[tokio::test] + async fn limit_with_mid_minute_bounds_does_not_truncate_files_prematurely() { + let dir = TempDir::new().unwrap(); + let schema = Arc::new(Schema::new(vec![ + Field::new( + DEFAULT_TIMESTAMP_KEY, + DataType::Timestamp(TimeUnit::Millisecond, None), + false, + ), + Field::new("app", DataType::Utf8, false), + Field::new("id", DataType::Int64, false), + ])); - let time_partition = Some("timestamp_column".to_string()); - let result = extract_timestamp_bound(&binexpr, &time_partition); + // Newest file (m3): 50 rows, ONLY 2 rows have p_timestamp <= 12:03:05! + let m3_ts: Vec = (0..50) + .map(|i| { + if i < 2 { + ts_ms(12, 3, 2) + } else { + ts_ms(12, 3, 45) + } + }) + .collect(); + let m3_batch = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(TimestampMillisecondArray::from(m3_ts)), + Arc::new(StringArray::from(vec!["api"; 50])), + Arc::new(Int64Array::from_iter_values(300..350)), + ], + ) + .unwrap(); + // Second file (m2): 50 rows, ALL interior (p_timestamp = 12:02:30 <= 12:03:05). + let m2_batch = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(TimestampMillisecondArray::from(vec![ts_ms(12, 2, 30); 50])), + Arc::new(StringArray::from(vec!["api"; 50])), + Arc::new(Int64Array::from_iter_values(200..250)), + ], + ) + .unwrap(); + // Oldest file (m1): 50 rows, ALL interior (p_timestamp = 12:01:30 <= 12:03:05). + let m1_batch = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(TimestampMillisecondArray::from(vec![ts_ms(12, 1, 30); 50])), + Arc::new(StringArray::from(vec!["api"; 50])), + Arc::new(Int64Array::from_iter_values(100..150)), + ], + ) + .unwrap(); - let expected = Some(( - Operator::Lt, - NaiveDateTime::parse_from_str(timestamp, "%Y-%m-%dT%H:%M:%S").unwrap(), - )); + let f3 = write_parquet(&dir.path().join("m3.parquet"), &m3_batch); + let f2 = write_parquet(&dir.path().join("m2.parquet"), &m2_batch); + let f1 = write_parquet(&dir.path().join("m1.parquet"), &m1_batch); + + // Unit check on `truncate_manifest_files_for_limit`: + // 1. Mid-minute exact filter with LIMIT 10 must keep [m3, m2] (NOT truncate to [m3]!), + // and safely drops m1 because m2 alone guarantees 50 >= 10 matching rows. + let mid_filter = [col(DEFAULT_TIMESTAMP_KEY).lt_eq(ts_lit(ts_ms(12, 3, 5)))]; + let mid_plan = ExactTimeFilterPlan::new(&mid_filter, &None); + let mut files = vec![f3.clone(), f2.clone(), f1.clone()]; + truncate_manifest_files_for_limit(&mut files, Some(10), false, Some((&mid_plan, &schema))); + assert_eq!(files.len(), 2); + assert!(files[0].file_path.ends_with("m3.parquet")); + assert!(files[1].file_path.ends_with("m2.parquet")); + + // 2. With an inexact filter present, ZERO files may be truncated. + let inexact_filters = [ + col(DEFAULT_TIMESTAMP_KEY).lt_eq(ts_lit(ts_ms(12, 3, 5))), + col("app").eq(lit("api")), + ]; + let inexact_plan = ExactTimeFilterPlan::new(&inexact_filters, &None); + let mut files = vec![f3.clone(), f2.clone(), f1.clone()]; + truncate_manifest_files_for_limit( + &mut files, + Some(10), + false, + Some((&inexact_plan, &schema)), + ); + assert_eq!(files.len(), 3); - assert_eq!(result, expected); + // 3. End-to-end SQL with mid-minute bound + LIMIT 10 returns 10 valid rows (not 2!). + let ctx = SessionContext::new(); + ctx.register_table( + "t", + Arc::new(InteriorSplitTestTable { + schema, + time_partition: None, + manifest_files: vec![f3, f2, f1], + staged_memory: Vec::new(), + }), + ) + .unwrap(); + let batches = ctx + .sql( + "SELECT id, p_timestamp FROM t WHERE p_timestamp <= '2026-11-30T12:03:05' LIMIT 10", + ) + .await + .unwrap() + .collect() + .await + .unwrap(); + let mut total_rows = 0usize; + for b in &batches { + let ts = b + .column(1) + .as_any() + .downcast_ref::() + .unwrap(); + for i in 0..b.num_rows() { + assert!(ts.value(i) <= ts_ms(12, 3, 5)); + } + total_rows += b.num_rows(); + } + assert_eq!(total_rows, 10); } #[test] - fn unexpected_utf8_column() { - let timestamp = "2023-01-01T00:00:00"; - let binexpr = BinaryExpr { - left: Box::new(Expr::Column("other_column".into())), - op: Operator::Eq, - right: Box::new(Expr::Literal( - ScalarValue::Utf8(Some(timestamp.to_owned())), - None, - )), + fn partitioned_files_attaches_per_file_timestamp_stats_and_merges_soundly() { + use crate::catalog::column::{ + Column, Int64Type, ManifestTimeUnit, StatsProvenance, TypedStatistics, }; + use crate::catalog::manifest::File; + use datafusion::common::stats::Precision; - let time_partition = Some("timestamp_column".to_string()); - let result = extract_timestamp_bound(&binexpr, &time_partition); - - assert!(result.is_none()); - } + let schema = Arc::new(Schema::new(vec![ + Field::new( + DEFAULT_TIMESTAMP_KEY, + DataType::Timestamp(TimeUnit::Millisecond, None), + false, + ), + Field::new("app", DataType::Utf8, true), + ])); + let verified_ts = Some(StatsProvenance { + complete_row_groups: true, + exact_min_max: true, + timestamp_unit: Some(ManifestTimeUnit::Millisecond), + }); + let verified_plain = Some(StatsProvenance { + complete_row_groups: true, + exact_min_max: true, + timestamp_unit: None, + }); - #[test] - fn unsupported_literal_type() { - let binexpr = BinaryExpr { - left: Box::new(Expr::Column("timestamp_column".into())), - op: Operator::Eq, - right: Box::new(Expr::Literal(ScalarValue::Int32(Some(42)), None)), + let f1 = File { + file_path: "m1.parquet".to_string(), + file_size: 1024, + num_rows: 100, + columns: vec![ + Column { + name: DEFAULT_TIMESTAMP_KEY.to_string(), + stats: Some(TypedStatistics::Int(Int64Type { + min: 1000, + max: 2000, + })), + null_count: Some(0), + uncompressed_size: 800, + compressed_size: 400, + stats_provenance: verified_ts, + }, + Column { + name: "app".to_string(), + stats: Some(TypedStatistics::String(crate::catalog::column::Utf8Type { + min: "a".to_string(), + max: "b".to_string(), + })), + null_count: Some(0), + uncompressed_size: 800, + compressed_size: 400, + stats_provenance: verified_plain, + }, + ], + ..Default::default() }; - - let time_partition = Some("timestamp_column".to_string()); - let result = extract_timestamp_bound(&binexpr, &time_partition); - - assert!(result.is_none()); - } - - #[test] - fn no_literal_on_right() { - let binexpr = BinaryExpr { - left: Box::new(Expr::Column("timestamp_column".into())), - op: Operator::Eq, - right: Box::new(Expr::Column("other_column".into())), + let f2 = File { + file_path: "m2.parquet".to_string(), + file_size: 1024, + num_rows: 200, + columns: vec![ + Column { + name: DEFAULT_TIMESTAMP_KEY.to_string(), + stats: Some(TypedStatistics::Int(Int64Type { + min: 3000, + max: 4000, + })), + null_count: Some(0), + uncompressed_size: 800, + compressed_size: 400, + stats_provenance: verified_ts, + }, + // Deliberately omit `app` stats on f2 to verify sound merging. + Column { + name: "app".to_string(), + stats: None, + null_count: None, + uncompressed_size: 800, + compressed_size: 400, + stats_provenance: verified_plain, + }, + ], + ..Default::default() }; - let time_partition = Some("timestamp_column".to_string()); - let result = extract_timestamp_bound(&binexpr, &time_partition); + let (groups, table_stats, ordered) = partitioned_files( + &schema, + &None, + vec![f1, f2], + 2, + false, + DEFAULT_TIMESTAMP_KEY, + ); + assert!(!ordered); + assert_eq!(table_stats.num_rows, Precision::Exact(300)); + // Both files have valid p_timestamp stats -> table min/max/null_count Exact. + assert_eq!( + table_stats.column_statistics[0].min_value, + Precision::Exact(ScalarValue::TimestampMillisecond(Some(1000), None)) + ); + assert_eq!( + table_stats.column_statistics[0].max_value, + Precision::Exact(ScalarValue::TimestampMillisecond(Some(4000), None)) + ); + assert_eq!( + table_stats.column_statistics[0].null_count, + Precision::Exact(0) + ); + // f2 lacked `app` stats -> merged table bounds MUST be Absent (never partial Exact). + assert_eq!( + table_stats.column_statistics[1].min_value, + Precision::Absent + ); + assert_eq!( + table_stats.column_statistics[1].max_value, + Precision::Absent + ); + assert_eq!( + table_stats.column_statistics[1].null_count, + Precision::Absent + ); - assert!(result.is_none()); + // Each PartitionedFile carries its own certified per-file timestamp bounds. + let all_files: Vec<_> = groups.into_iter().flatten().collect(); + assert_eq!(all_files.len(), 2); + for pf in all_files { + let stats = pf.statistics.expect("per-file stats attached"); + assert_eq!(stats.num_rows, Precision::Absent); + assert!(matches!( + stats.column_statistics[0].max_value, + Precision::Exact(ScalarValue::TimestampMillisecond(Some(2000 | 4000), None)) + )); + assert_eq!(stats.column_statistics[0].null_count, Precision::Exact(0)); + } } - #[test] - fn non_time_partition_timestamps() { - let binexpr = BinaryExpr { - left: Box::new(Expr::Column("timestamp_column".into())), - op: Operator::Eq, - right: Box::new(Expr::Literal( - ScalarValue::TimestampMillisecond(Some(1672531200000), None), - None, - )), + #[tokio::test] + async fn staging_disk_plan_two_phase_filter_matches_wide_scan_across_selectivities() { + use super::staging_disk_plan; + use crate::OBJECT_STORE_DATA_GRANULARITY; + use crate::parseable::staging::{ + StagingMemoryBudget, + writer::{MemWriter, Writer}, }; + use crate::utils::time::TimeRange; + use arrow_array::{Int32Array, StringArray}; + use chrono::Utc; + use datafusion::physical_plan::collect; + use datafusion::prelude::{SessionContext, col, lit}; + use tempfile::TempDir; - let time_partition = None; - let result = extract_timestamp_bound(&binexpr, &time_partition); - let expected = Some(( - Operator::Eq, - NaiveDateTime::parse_from_str("2023-01-01T00:00:00", "%Y-%m-%dT%H:%M:%S").unwrap(), - )); - - assert_eq!(result, expected); - - let binexpr = BinaryExpr { - left: Box::new(Expr::Column("timestamp_column".into())), - op: Operator::Eq, - right: Box::new(Expr::Literal( - ScalarValue::TimestampNanosecond(Some(1672531200000000000), None), - None, - )), + let dir = TempDir::new().unwrap(); + let budget = StagingMemoryBudget::new(0); + let mut writer = Writer { + mem: Some(MemWriter::with_budget(Arc::clone(&budget))), + disk: Default::default(), }; - let result = extract_timestamp_bound(&binexpr, &time_partition); + let wide_schema = Arc::new(Schema::new(vec![ + Field::new( + DEFAULT_TIMESTAMP_KEY, + DataType::Timestamp(TimeUnit::Millisecond, None), + false, + ), + Field::new("id", DataType::Int32, false), + Field::new("level", DataType::Utf8, true), + Field::new("app", DataType::Utf8, true), + Field::new("payload_a", DataType::Utf8, true), + Field::new("payload_b", DataType::Utf8, true), + ])); + let file = "wide.data.arrows"; + let range = TimeRange::granularity_range(Utc::now(), OBJECT_STORE_DATA_GRANULARITY); + // Batch 0: 0 errors; Batch 1: sparse errors; Batch 2: all errors. + let batch_levels = [ + vec!["info", "info", "warn", "info"], + vec!["info", "error", "warn", "error"], + vec!["error", "error", "error", "error"], + ]; + for (b_idx, levels) in batch_levels.iter().enumerate() { + let base = (b_idx as i32) * 4; + let rb = RecordBatch::try_new( + wide_schema.clone(), + vec![ + Arc::new(TimestampMillisecondArray::from(vec![ + 1_700_000_000_000 + i64::from(base), + 1_700_000_000_001 + i64::from(base), + 1_700_000_000_002 + i64::from(base), + 1_700_000_000_003 + i64::from(base), + ])), + Arc::new(Int32Array::from(vec![base, base + 1, base + 2, base + 3])), + Arc::new(StringArray::from(levels.clone())), + Arc::new(StringArray::from(vec!["svc-a", "svc-b", "svc-a", "svc-c"])), + Arc::new(StringArray::from(vec!["pa0", "pa1", "pa2", "pa3"])), + Arc::new(StringArray::from(vec!["pb0", "pb1", "pb2", "pb3"])), + ], + ) + .unwrap(); + writer + .push_disk_and_memory(file, "widek", &rb, dir.path().join(file), range.clone()) + .unwrap(); + } + let capture = writer.capture(&wide_schema).unwrap(); + let ctx = SessionContext::new(); + let state = ctx.state(); - assert_eq!(result, expected); - } + // 1. Selective filter over wide projection (SELECT * WHERE level = 'error') + let err_filter = vec![col("level").eq(lit("error"))]; + let plan = staging_disk_plan( + wide_schema.clone(), + capture.disk.clone(), + &state, + None, + &err_filter, + None, + ) + .await + .unwrap() + .unwrap(); + let batches = collect(plan, ctx.task_ctx()).await.unwrap(); + let mut ids: Vec = batches + .iter() + .flat_map(|b| { + assert_eq!(b.num_columns(), 6); + b.column(1) + .as_any() + .downcast_ref::() + .unwrap() + .values() + .iter() + .copied() + }) + .collect(); + ids.sort_unstable(); + assert_eq!(ids, vec![5, 7, 8, 9, 10, 11]); - fn ts_millis(time: DateTime) -> Expr { - Expr::Literal( - ScalarValue::TimestampMillisecond(Some(time.timestamp_millis()), None), + // 2. Zero-match filter (all batches skipped before Phase 2 decode) + let none_filter = vec![col("level").eq(lit("fatal"))]; + let none_plan = staging_disk_plan( + wide_schema.clone(), + capture.disk.clone(), + &state, + None, + &none_filter, + None, + ) + .await + .unwrap() + .unwrap(); + let none_rows: usize = collect(none_plan, ctx.task_ctx()) + .await + .unwrap() + .iter() + .map(RecordBatch::num_rows) + .sum(); + assert_eq!(none_rows, 0); + + // 3. Limited wide scan (lazy source + two-phase + newest-first order) + let lim_plan = staging_disk_plan( + wide_schema, + capture.disk, + &state, None, + &err_filter, + Some(3), ) + .await + .unwrap() + .unwrap(); + let lim_ids: Vec = collect(lim_plan, ctx.task_ctx()) + .await + .unwrap() + .iter() + .flat_map(|b| { + b.column(1) + .as_any() + .downcast_ref::() + .unwrap() + .values() + .iter() + .copied() + }) + .collect(); + assert_eq!(lim_ids, vec![11, 10, 9]); + drop(writer); } - fn column(name: &str) -> Expr { - Expr::Column(name.into()) - } + #[tokio::test] + async fn float_nan_stats_never_published_as_exact_and_select_preserves_nan() { + use arrow_array::{Float32Array, Float64Array}; + use datafusion::common::stats::Precision; - fn pruned_manifest_paths(filters: &[Expr], time_partition: &Option) -> Vec { - let time_filters = extract_primary_filter(filters, time_partition); - manifest_snapshot() - .manifests(&time_filters) - .into_iter() - .map(|item| item.manifest_path) - .collect() - } + let dir = TempDir::new().unwrap(); + let schema = Arc::new(Schema::new(vec![ + Field::new("f64_col", DataType::Float64, false), + Field::new("f32_col", DataType::Float32, false), + ])); + let batch = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(Float64Array::from(vec![7.0_f64, f64::NAN])), + Arc::new(Float32Array::from(vec![7.0_f32, f32::NAN])), + ], + ) + .unwrap(); + let f1 = write_parquet(&dir.path().join("nan1.parquet"), &batch); + let f2 = write_parquet(&dir.path().join("nan2.parquet"), &batch); + + // Verify Parquet footer really did record min == max == 7.0, null_count == 0 + // (the exact trigger for DataFusion 55's literal substitution bug). + let f64_col = f1.columns.iter().find(|c| c.name == "f64_col").unwrap(); + assert_eq!(f64_col.null_count, Some(0)); + match f64_col.stats.as_ref().unwrap() { + TypedStatistics::Float(s) => { + assert_eq!(s.min, 7.0); + assert_eq!(s.max, 7.0); + } + other => panic!("expected Float stats, got {other:?}"), + } - fn manifest_snapshot() -> Snapshot { - Snapshot { - manifest_list: manifest_items(), - ..Snapshot::default() + // Check both 1-file and 2-file scans: neither per-file nor table stats + // may publish Exact min/max for Float32 or Float64. + for files in [vec![f1.clone()], vec![f1.clone(), f2]] { + let (groups, table_stats, _) = partitioned_files( + &schema, + &None, + files.clone(), + 2, + false, + DEFAULT_TIMESTAMP_KEY, + ); + for col_stats in &table_stats.column_statistics { + assert_eq!(col_stats.min_value, Precision::Absent); + assert_eq!(col_stats.max_value, Precision::Absent); + } + for pf in groups.iter().flatten() { + if let Some(pf_stats) = pf.statistics.as_ref() { + for col_stats in &pf_stats.column_statistics { + assert_eq!(col_stats.min_value, Precision::Absent); + assert_eq!(col_stats.max_value, Precision::Absent); + } + } + } + + // End-to-end DataFusion scan must return [7.0, NaN], NEVER [7.0, 7.0]! + let ctx = SessionContext::new(); + let plan = parquet_scan_plan_with_cache_options( + schema.clone(), + ObjectStoreUrl::local_filesystem(), + groups, + table_stats, + None, + &[], + None, + &ctx.state(), + 1024, + (0, 0, false), + ) + .await + .unwrap(); + let batches = collect(plan, ctx.task_ctx()).await.unwrap(); + let mut f64_vals = Vec::new(); + let mut f32_vals = Vec::new(); + for b in &batches { + let c64 = b.column(0).as_any().downcast_ref::().unwrap(); + let c32 = b.column(1).as_any().downcast_ref::().unwrap(); + f64_vals.extend(c64.values().iter().copied()); + f32_vals.extend(c32.values().iter().copied()); + } + assert_eq!(f64_vals.len(), files.len() * 2); + assert_eq!(f64_vals.iter().filter(|v| v.is_nan()).count(), files.len()); + assert_eq!(f64_vals.iter().filter(|v| **v == 7.0).count(), files.len()); + assert_eq!(f32_vals.iter().filter(|v| v.is_nan()).count(), files.len()); + assert_eq!(f32_vals.iter().filter(|v| **v == 7.0).count(), files.len()); } } #[test] - fn non_timestamp_column_filter_does_not_prune_manifests() { - // `created_at` is unrelated to how manifests are bucketed: rows with a - // late `created_at` can live in any day's manifest. + fn legacy_uncertified_and_mismatched_timestamp_manifests_never_interior_certified_or_falsely_pruned() + { + use crate::catalog::column::{ManifestTimeUnit, StatsProvenance}; + use datafusion::common::stats::Precision; + + let schema = Arc::new(Schema::new(vec![Field::new( + DEFAULT_TIMESTAMP_KEY, + DataType::Timestamp(TimeUnit::Millisecond, None), + false, + )])); let filters = [ - column("created_at").gt_eq(ts_millis(datetime_min(2023, 12, 17))), - column("created_at").lt(ts_millis(datetime_max(2023, 12, 17))), + col(DEFAULT_TIMESTAMP_KEY).gt_eq(ts_lit(ts_ms(12, 0, 30))), + col(DEFAULT_TIMESTAMP_KEY).lt(ts_lit(ts_ms(12, 3, 15))), ]; + let filter_plan = ExactTimeFilterPlan::new(&filters, &None); - assert!(extract_primary_filter(&filters, &None).is_empty()); - assert_eq!(pruned_manifest_paths(&filters, &None), ["1", "2", "3"]); - } + let make_file = |path: &str, min: i64, max: i64, prov: Option| File { + file_path: path.to_owned(), + num_rows: 10, + file_size: 512, + columns: vec![Column { + name: DEFAULT_TIMESTAMP_KEY.to_owned(), + stats: Some(TypedStatistics::Int(Int64Type { min, max })), + null_count: Some(0), + uncompressed_size: 100, + compressed_size: 50, + stats_provenance: prov, + }], + ..File::default() + }; - #[test] - fn non_timestamp_string_literal_filter_does_not_prune_manifests() { - let filters = [column("created_at").gt(Expr::Literal( - ScalarValue::Utf8(Some("2023-12-17T00:00:00".to_owned())), - None, - ))]; + // 1. Legacy uncertified manifest (`stats_provenance == None`) + let legacy = make_file("legacy.parquet", ts_ms(12, 1, 0), ts_ms(12, 1, 59), None); + // 2. INT96 timestamp (`exact_min_max == false`, Nanosecond values) + let int96 = make_file( + "int96.parquet", + ts_ms(12, 1, 0) * 1_000_000, + ts_ms(12, 1, 59) * 1_000_000, + Some(StatsProvenance { + complete_row_groups: true, + exact_min_max: false, + timestamp_unit: Some(ManifestTimeUnit::Nanosecond), + }), + ); + // 3. Mismatched Nanosecond unit with sub-millisecond remainder (lossy truncation) + let lossy_ns = make_file( + "lossy_ns.parquet", + ts_ms(12, 1, 0) * 1_000_000 + 123, + ts_ms(12, 1, 59) * 1_000_000 + 456, + Some(StatsProvenance { + complete_row_groups: true, + exact_min_max: true, + timestamp_unit: Some(ManifestTimeUnit::Nanosecond), + }), + ); + // 4. Missing timestamp_unit (`timestamp_unit == None`) + let no_unit = make_file( + "no_unit.parquet", + ts_ms(12, 1, 0), + ts_ms(12, 1, 59), + Some(StatsProvenance { + complete_row_groups: true, + exact_min_max: true, + timestamp_unit: None, + }), + ); - assert!(extract_primary_filter(&filters, &None).is_empty()); - assert_eq!(pruned_manifest_paths(&filters, &None), ["1", "2", "3"]); + let files = vec![legacy, int96, lossy_ns, no_unit]; + + // NONE may be treated as interior. + let (interior, boundary) = filter_plan.split_files(files.clone(), &schema); + assert!(interior.is_empty()); + assert_eq!(boundary.len(), 4); + + // NONE may be falsely pruned by a millisecond timestamp filter (even if raw + // nanosecond integer values exceed the millisecond upper bound!). + let upper_filter = col(DEFAULT_TIMESTAMP_KEY).lt(ts_lit(ts_ms(12, 3, 15))); + for f in &files { + assert!( + !f.can_be_pruned(&upper_filter), + "{} must not be pruned without certified timestamp bounds", + f.file_path + ); + } + + // NONE may receive Exact per-file or table-level bounds in `partitioned_files` + // (so `ProgressiveTopKExec` will never treat them as certified bounded units). + let (groups, table_stats, _) = + partitioned_files(&schema, &None, files, 2, false, DEFAULT_TIMESTAMP_KEY); + assert_eq!( + table_stats.column_statistics[0].min_value, + Precision::Absent + ); + assert_eq!( + table_stats.column_statistics[0].max_value, + Precision::Absent + ); + for pf in groups.into_iter().flatten() { + let stats = pf.statistics.expect("per-file stats attached"); + assert_eq!(stats.column_statistics[0].min_value, Precision::Absent); + assert_eq!(stats.column_statistics[0].max_value, Precision::Absent); + } } #[test] - fn p_timestamp_filter_prunes_manifests() { - let filters = [ - column(DEFAULT_TIMESTAMP_KEY).gt_eq(ts_millis(datetime_min(2023, 12, 16))), - column(DEFAULT_TIMESTAMP_KEY).lt(ts_millis(datetime_max(2023, 12, 16))), - ]; + fn truncated_parquet_string_stats_never_published_as_exact() { + use datafusion::common::stats::Precision; + use parquet::file::properties::WriterProperties; - assert_eq!(extract_primary_filter(&filters, &None).len(), 2); - assert_eq!(pruned_manifest_paths(&filters, &None), ["2"]); - } + let dir = TempDir::new().unwrap(); + let schema = Arc::new(Schema::new(vec![Field::new("msg", DataType::Utf8, false)])); + let long_a = format!("{}_a", "p".repeat(80)); + let long_z = format!("{}_z", "p".repeat(80)); + let batch = RecordBatch::try_new( + schema.clone(), + vec![Arc::new(StringArray::from(vec![ + long_a.as_str(), + long_z.as_str(), + ]))], + ) + .unwrap(); - #[test] - fn qualified_p_timestamp_filter_prunes_manifests() { - // The query handler injects table-qualified time filters. - let filters = [Expr::Column(datafusion::common::Column::new( - Some("app_logs"), + let write_trunc = |name: &str| { + let path = dir.path().join(name); + let file = fs::File::create(&path).unwrap(); + let props = WriterProperties::builder() + .set_statistics_truncate_length(Some(16)) + .build(); + let mut writer = ArrowWriter::try_new(file, schema.clone(), Some(props)).unwrap(); + writer.write(&batch).unwrap(); + writer.close().unwrap(); + create_from_parquet_file(path.to_string_lossy().into_owned(), &path).unwrap() + }; + let f1 = write_trunc("t1.parquet"); + let f2 = write_trunc("t2.parquet"); + + let (groups, table_stats, _) = partitioned_files( + &schema, + &None, + vec![f1, f2], + 2, + false, DEFAULT_TIMESTAMP_KEY, - )) - .gt_eq(ts_millis(datetime_min(2023, 12, 17)))]; - - assert_eq!(pruned_manifest_paths(&filters, &None), ["3"]); + ); + assert_eq!( + table_stats.column_statistics[0].min_value, + Precision::Absent + ); + assert_eq!( + table_stats.column_statistics[0].max_value, + Precision::Absent + ); + for pf in groups.into_iter().flatten() { + let stats = pf.statistics.expect("per-file stats attached"); + assert_eq!(stats.column_statistics[0].min_value, Precision::Absent); + assert_eq!(stats.column_statistics[0].max_value, Precision::Absent); + } } #[test] - fn literal_on_left_or_non_comparison_does_not_prune_manifests() { - let filters = [ - ts_millis(datetime_min(2023, 12, 17)).lt(column(DEFAULT_TIMESTAMP_KEY)), - column(DEFAULT_TIMESTAMP_KEY).not_eq(ts_millis(datetime_min(2023, 12, 17))), - ]; - - assert!(extract_primary_filter(&filters, &None).is_empty()); - } + fn distributed_modes_live_window_bypass_metadata_cache_while_standalone_shares_closed() { + use crate::catalog::snapshot::ManifestItem; + use crate::option::Mode; + use chrono::TimeDelta; + + let cutoff = super::staging_window_cutoff(); + let closed = ManifestItem { + manifest_path: "old/manifest.json".to_owned(), + time_lower_bound: (cutoff - TimeDelta::hours(2)).and_utc(), + time_upper_bound: (cutoff - TimeDelta::hours(1)).and_utc(), + events_ingested: 0, + ingestion_size: 0, + storage_size: 0, + }; - #[test] - fn custom_time_partition_filter_prunes_manifests() { - // Manifests of time-partitioned streams are bucketed by the partition - // column, so bounds on it (timestamp or parseable string) prune. - let time_partition = Some("event_time".to_owned()); - let filters = [ - column("event_time").gt_eq(ts_millis(datetime_min(2023, 12, 16))), - column("event_time").lt(Expr::Literal( - ScalarValue::Utf8(Some("2023-12-16T12:00:00".to_owned())), - None, - )), - ]; + // Distributed modes (Query, Prism, Ingest, Index) MUST bypass METADATA_CACHE + // completely for live-window scans (`include_staging == true`). + for mode in [Mode::Query, Mode::Prism, Mode::Ingest, Mode::Index] { + let policy = super::shared_manifest_policy(true, false, true, mode, cutoff); + assert_eq!(policy, super::SharedManifestPolicy::Bypass, "mode={mode:?}"); + assert!(!super::shares_manifest(policy, &closed)); - assert_eq!(extract_primary_filter(&filters, &time_partition).len(), 2); - assert_eq!(pruned_manifest_paths(&filters, &time_partition), ["2"]); - } + // Pure historical scan (`shared == true && !include_staging`) still shares All. + let hist_policy = super::shared_manifest_policy(true, true, false, mode, cutoff); + assert_eq!(hist_policy, super::SharedManifestPolicy::All); + } - #[test] - fn p_timestamp_filter_does_not_prune_custom_time_partition_manifests() { - // On a time-partitioned stream `p_timestamp` is ingestion time, while - // manifests are bucketed by event time: back-filled events ingested on - // the 17th sit in the 15th's manifest and must not be pruned away. - let time_partition = Some("event_time".to_owned()); - let filters = [column(DEFAULT_TIMESTAMP_KEY).gt_eq(ts_millis(datetime_min(2023, 12, 17)))]; + // Standalone `Mode::All` may share strictly closed historical manifests during + // live-window scans because every local metastore write invalidates METADATA_CACHE. + let standalone_live = super::shared_manifest_policy(true, false, true, Mode::All, cutoff); + assert_eq!( + standalone_live, + super::SharedManifestPolicy::ClosedBefore(cutoff) + ); - assert!(extract_primary_filter(&filters, &time_partition).is_empty()); + // Cache disabled always bypasses. assert_eq!( - pruned_manifest_paths(&filters, &time_partition), - ["1", "2", "3"] + super::shared_manifest_policy(false, true, false, Mode::All, cutoff), + super::SharedManifestPolicy::Bypass ); } #[test] - fn unrelated_column_does_not_prune_custom_time_partition_manifests() { - let time_partition = Some("event_time".to_owned()); - let filters = [column("created_at").gt_eq(ts_millis(datetime_min(2023, 12, 17)))]; - - assert!(extract_primary_filter(&filters, &time_partition).is_empty()); + fn partitioned_files_bounds_per_file_stats_budget_and_never_rehabilitates_invalid_bounds() { + use crate::catalog::column::{ManifestTimeUnit, StatsProvenance}; + use datafusion::common::stats::Precision; + + // 1. Invalid inverted integer bounds on File 1 + valid bracketing bounds on File 2 + // must NEVER be rehabilitated into valid merged table bounds, and u64 num_rows + // overflow must yield Precision::Absent. + let small_schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int64, false)])); + let verified_int = Some(StatsProvenance { + complete_row_groups: true, + exact_min_max: true, + timestamp_unit: None, + }); + let bad_file = File { + file_path: "bad.parquet".to_owned(), + num_rows: u64::MAX, + file_size: 100, + columns: vec![Column { + name: "id".to_owned(), + stats: Some(TypedStatistics::Int(Int64Type { min: 20, max: 10 })), + null_count: Some(0), + uncompressed_size: 0, + compressed_size: 0, + stats_provenance: verified_int, + }], + ..File::default() + }; + let good_file = File { + file_path: "good.parquet".to_owned(), + num_rows: 1, + file_size: 100, + columns: vec![Column { + name: "id".to_owned(), + stats: Some(TypedStatistics::Int(Int64Type { min: 1, max: 100 })), + null_count: Some(0), + uncompressed_size: 0, + compressed_size: 0, + stats_provenance: verified_int, + }], + ..File::default() + }; + let (_, stats, _) = partitioned_files( + &small_schema, + &None, + vec![bad_file, good_file], + 2, + false, + DEFAULT_TIMESTAMP_KEY, + ); + assert_eq!(stats.num_rows, Precision::Absent); + assert_eq!(stats.column_statistics[0].min_value, Precision::Absent); + assert_eq!(stats.column_statistics[0].max_value, Precision::Absent); + + // 2. Above budget (`file_count * num_fields > 250_000`): skip dense per-file + // PartitionedFile::statistics and non-time column stats while keeping + // `time_column` table-level certified bounds. + let mut fields = vec![Field::new( + DEFAULT_TIMESTAMP_KEY, + DataType::Timestamp(TimeUnit::Millisecond, None), + false, + )]; + for i in 0..499 { + fields.push(Field::new(format!("c{i}"), DataType::Int64, true)); + } + let wide_schema = Arc::new(Schema::new(fields)); // 500 fields + let verified_ts = Some(StatsProvenance { + complete_row_groups: true, + exact_min_max: true, + timestamp_unit: Some(ManifestTimeUnit::Millisecond), + }); + // 501 files × 500 fields = 250,500 > 250,000. + let many_files: Vec = (0..501_i64) + .map(|i| File { + file_path: format!("f{i}.parquet"), + num_rows: 10, + file_size: 128, + columns: vec![ + Column { + name: DEFAULT_TIMESTAMP_KEY.to_owned(), + stats: Some(TypedStatistics::Int(Int64Type { + min: 1_000 + i, + max: 2_000 + i, + })), + null_count: Some(0), + uncompressed_size: 0, + compressed_size: 0, + stats_provenance: verified_ts, + }, + Column { + name: "c0".to_owned(), + stats: Some(TypedStatistics::Int(Int64Type { min: 1, max: 2 })), + null_count: Some(0), + uncompressed_size: 0, + compressed_size: 0, + stats_provenance: verified_int, + }, + ], + ..File::default() + }) + .collect(); + let (groups, wide_stats, _) = partitioned_files( + &wide_schema, + &None, + many_files, + 4, + false, + DEFAULT_TIMESTAMP_KEY, + ); + assert_eq!(wide_stats.num_rows, Precision::Exact(5_010)); + // Per-file stats omitted above budget. + assert!(groups.iter().flatten().all(|pf| pf.statistics.is_none())); + // Time column table-level bounds are still Exact. + assert_eq!( + wide_stats.column_statistics[0].min_value, + Precision::Exact(ScalarValue::TimestampMillisecond(Some(1_000), None)) + ); + assert_eq!( + wide_stats.column_statistics[0].max_value, + Precision::Exact(ScalarValue::TimestampMillisecond(Some(2_500), None)) + ); + assert_eq!( + wide_stats.column_statistics[0].null_count, + Precision::Exact(0) + ); + // Non-time columns stay Absent (never fabricated as Exact(0)). + assert_eq!(wide_stats.column_statistics[1].min_value, Precision::Absent); + assert_eq!( + wide_stats.column_statistics[1].null_count, + Precision::Absent + ); } -} - -#[cfg(test)] -mod ordering_tests; -#[cfg(test)] -mod exact_filter_tests; + #[tokio::test] + async fn manifest_row_count_exec_reports_exact_statistics_so_aggregate_statistics_folds_count() + { + use crate::catalog::column::{ManifestTimeUnit, StatsProvenance}; + use datafusion::common::stats::Precision; -#[cfg(test)] -mod snapshot_capture_tests { - use super::*; - use std::sync::atomic::{AtomicUsize, Ordering}; + let schema = Arc::new(Schema::new(vec![ + Field::new( + DEFAULT_TIMESTAMP_KEY, + DataType::Timestamp(TimeUnit::Millisecond, None), + false, + ), + Field::new("app", DataType::Utf8, false), + ])); + let verified_ts = Some(StatsProvenance { + complete_row_groups: true, + exact_min_max: true, + timestamp_unit: Some(ManifestTimeUnit::Millisecond), + }); + let interior = vec![ + File { + file_path: "/does/not/exist/a.parquet".to_owned(), + num_rows: 123_456, + file_size: 1024, + columns: vec![Column { + name: DEFAULT_TIMESTAMP_KEY.to_owned(), + stats: Some(TypedStatistics::Int(Int64Type { + min: ts_ms(12, 1, 0), + max: ts_ms(12, 1, 59), + })), + null_count: Some(0), + uncompressed_size: 0, + compressed_size: 0, + stats_provenance: verified_ts, + }], + ..File::default() + }, + File { + file_path: "/does/not/exist/b.parquet".to_owned(), + num_rows: 876_544, + file_size: 1024, + columns: vec![Column { + name: DEFAULT_TIMESTAMP_KEY.to_owned(), + stats: Some(TypedStatistics::Int(Int64Type { + min: ts_ms(12, 2, 0), + max: ts_ms(12, 2, 59), + })), + null_count: Some(0), + uncompressed_size: 0, + compressed_size: 0, + stats_provenance: verified_ts, + }], + ..File::default() + }, + ]; - #[tokio::test] - async fn publication_between_capture_and_read_cannot_hide_a_file() { - for predicted in [true, false] { - let published = AtomicUsize::new(0); - let reads = AtomicUsize::new(0); - let (snapshot, staging) = capture_before_snapshot( - predicted, - || { - // Capture a lease, then simulate publication and unlink. - let lease = "just-uploaded.parquet"; - published.store(1, Ordering::SeqCst); - Ok(lease) - }, - |_| async { - reads.fetch_add(1, Ordering::SeqCst); - Ok(published.load(Ordering::SeqCst)) - }, - |_| true, - ) + let ctx = SessionContext::new(); + let count_exec = manifest_row_count_plan(&schema, &interior, None, &ctx.state()) .await + .unwrap() .unwrap(); - assert_eq!(snapshot, 1); - assert_eq!(staging, Some("just-uploaded.parquet")); - assert_eq!(reads.load(Ordering::SeqCst), if predicted { 1 } else { 2 }); - } - } - - #[tokio::test] - async fn historical_queries_do_not_capture_staging() { - let (snapshot, staging) = capture_before_snapshot( - false, - || -> DataFusionResult<()> { panic!("historical scan must not lease staging") }, - |_| async { Ok(42) }, - |_| false, - ) - .await - .unwrap(); - assert_eq!(snapshot, 42); - assert_eq!(staging, None); - } - #[tokio::test] - async fn speculative_capture_error_only_fails_when_staging_is_needed() { - for needed in [false, true] { - let result = capture_before_snapshot( - true, - || -> DataFusionResult<()> { - Err(DataFusionError::Execution("capture failed".into())) - }, - |_| async { Ok(needed) }, - |needed| *needed, + let exec_stats = datafusion::physical_plan::statistics::StatisticsContext::new() + .compute( + count_exec.as_ref(), + &datafusion::physical_plan::StatisticsArgs::default(), ) - .await; - assert_eq!(result.is_err(), needed); - } + .unwrap(); + assert_eq!(exec_stats.num_rows, Precision::Exact(1_000_000)); + + // End-to-end all-interior SELECT COUNT(*): DataFusion's AggregateStatistics + // must fold the plan in O(1) via PlaceholderRowExec without ManifestRowCountExec. + ctx.register_table( + "t", + Arc::new(InteriorSplitTestTable { + schema, + time_partition: None, + manifest_files: interior, + staged_memory: Vec::new(), + }), + ) + .unwrap(); + let plan = ctx + .sql( + "SELECT count(*) AS c FROM t \ + WHERE p_timestamp >= '2026-11-30T12:00:30' AND p_timestamp < '2026-11-30T12:03:15'", + ) + .await + .unwrap() + .create_physical_plan() + .await + .unwrap(); + let plan_text = displayable(plan.as_ref()).indent(true).to_string(); + assert!( + plan_text.contains("PlaceholderRowExec"), + "expected AggregateStatistics to fold COUNT(*) in O(1):\n{plan_text}" + ); + assert!( + !plan_text.contains("ManifestRowCountExec"), + "folded COUNT(*) should not retain ManifestRowCountExec:\n{plan_text}" + ); + let batches = collect(plan, ctx.task_ctx()).await.unwrap(); + let count = batches[0] + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .value(0); + assert_eq!(count, 1_000_000); } -} -#[cfg(test)] -mod staging_disk_tests { - use std::sync::Arc; + #[tokio::test] + async fn fallible_predicates_excluded_from_staging_two_phase_filter() { + use super::{build_staging_two_phase_filter, staging_disk_plan}; + use crate::OBJECT_STORE_DATA_GRANULARITY; + use crate::parseable::staging::{ + StagingMemoryBudget, + writer::{MemWriter, Writer}, + }; + use crate::utils::time::TimeRange; + use chrono::Utc; + use datafusion::logical_expr::Expr as LogicalExpr; + use datafusion::prelude::{cast, try_cast}; - use arrow_array::{Int32Array, RecordBatch, StringArray}; - use arrow_schema::{DataType, Field, Schema}; - use chrono::Utc; - use datafusion::{ - execution::context::SessionContext, - physical_plan::collect, - prelude::{col, lit}, - }; - use temp_dir::TempDir; + let wide_schema = Arc::new(Schema::new(vec![ + Field::new( + DEFAULT_TIMESTAMP_KEY, + DataType::Timestamp(TimeUnit::Millisecond, None), + false, + ), + Field::new("id", DataType::Int64, false), + Field::new("x", DataType::Utf8, true), + Field::new("payload_a", DataType::Utf8, true), + Field::new("payload_b", DataType::Utf8, true), + ])); + let ctx = SessionContext::new(); + let state = ctx.state(); - use super::staging_disk_plan; - use crate::{ - OBJECT_STORE_DATA_GRANULARITY, - parseable::{ - StagingCapture, StagingMemoryBudget, - staging::writer::{MemWriter, Writer}, - }, - utils::time::TimeRange, - }; + let exact_time = col(DEFAULT_TIMESTAMP_KEY).gt_eq(ts_lit(ts_ms(12, 1, 0))); + let cast_pred = cast(col("x"), DataType::Int32).eq(lit(5_i32)); + let try_cast_pred = try_cast(col("x"), DataType::Int32).eq(lit(5_i32)); + let arith_pred = (col("id") + lit(1_i64)).eq(lit(5_i64)); + let mismatched_lit = col("id").eq(lit(5_i32)); // Int32 literal vs Int64 column + let or_with_cast = exact_time.clone().or(cast_pred.clone()); + + // 1. Fallible predicates alone or inside OR must NOT produce a two-phase filter. + for bad in [ + cast_pred.clone(), + try_cast_pred, + arith_pred, + mismatched_lit, + or_with_cast, + ] { + assert!( + build_staging_two_phase_filter(&wide_schema, std::slice::from_ref(&bad), &state) + .is_none(), + "fallible predicate must not enter StagingTwoPhaseFilter: {bad}" + ); + } - fn file_schema() -> Arc { - Arc::new(Schema::new(vec![ - Field::new("id", DataType::Int32, false), - Field::new("name", DataType::Utf8, false), - ])) - } + // 2. Fallible `CAST(x AS INT) = 5` alongside an exact time bound: ONLY the + // safe exact time bound may enter `StagingTwoPhaseFilter`; `x` / `CAST` must NOT! + let tp = build_staging_two_phase_filter( + &wide_schema, + &[exact_time.clone(), cast_pred.clone()], + &state, + ) + .expect("safe exact time bound still eligible"); + assert_eq!(tp.filter_schema.fields().len(), 1); + assert_eq!(tp.filter_schema.field(0).name(), DEFAULT_TIMESTAMP_KEY); + let pred_str = tp.predicate.to_string(); + assert!(pred_str.contains(DEFAULT_TIMESTAMP_KEY), "{pred_str}"); + assert!( + !pred_str.contains("CAST") && !pred_str.contains('x'), + "{pred_str}" + ); - fn table_schema() -> Arc { - Arc::new(Schema::new(vec![ - Field::new("name", DataType::Utf8, true), - Field::new("extra", DataType::Int32, true), - Field::new("id", DataType::Int32, true), - ])) - } + // 3. Provably non-throwing InList and IsNotNull are accepted. + let in_list = LogicalExpr::InList(datafusion::logical_expr::expr::InList::new( + Box::new(col("x")), + vec![lit("5"), lit("6")], + false, + )); + assert!(build_staging_two_phase_filter(&wide_schema, &[in_list], &state).is_some()); + assert!( + build_staging_two_phase_filter(&wide_schema, &[col("x").is_not_null()], &state) + .is_some() + ); - /// Ingests `0..rows` in batches of 7 with a disk-only budget and captures. - fn disk_only_capture(dir: &TempDir, rows: i32) -> (Writer, StagingCapture) { + // 4. End-to-end staging disk scan with `x = "not_an_int"` outside the time window + // and `x = "5"` inside: Phase 1 filters out the old batch by time without + // evaluating `CAST("not_an_int" AS INT)`! + let dir = TempDir::new().unwrap(); let budget = StagingMemoryBudget::new(0); let mut writer = Writer { mem: Some(MemWriter::with_budget(Arc::clone(&budget))), disk: Default::default(), }; + let file = "fallible.data.arrows"; let range = TimeRange::granularity_range(Utc::now(), OBJECT_STORE_DATA_GRANULARITY); - for start in (0..rows).step_by(7) { - let ids = start..(start + 7).min(rows); - let batch = RecordBatch::try_new( - file_schema(), - vec![ - Arc::new(Int32Array::from_iter_values(ids.clone())), - Arc::new(StringArray::from_iter_values( - ids.map(|id| format!("n{id}")), - )), - ], - ) + let old_batch = RecordBatch::try_new( + wide_schema.clone(), + vec![ + Arc::new(TimestampMillisecondArray::from(vec![ts_ms(12, 0, 10)])), + Arc::new(Int64Array::from(vec![1])), + Arc::new(StringArray::from(vec!["not_an_int"])), + Arc::new(StringArray::from(vec!["pa"])), + Arc::new(StringArray::from(vec!["pb"])), + ], + ) + .unwrap(); + let new_batch = RecordBatch::try_new( + wide_schema.clone(), + vec![ + Arc::new(TimestampMillisecondArray::from(vec![ts_ms(12, 1, 10)])), + Arc::new(Int64Array::from(vec![2])), + Arc::new(StringArray::from(vec!["5"])), + Arc::new(StringArray::from(vec!["pa2"])), + Arc::new(StringArray::from(vec!["pb2"])), + ], + ) + .unwrap(); + writer + .push_disk_and_memory(file, "fk", &old_batch, dir.path().join(file), range.clone()) .unwrap(); - for name in [ - "a.date=2020-01-02.data.arrows", - "b.date=2020-01-02.data.arrows", - ] { - writer - .push_disk_and_memory(name, "k", &batch, dir.path().join(name), range.clone()) - .unwrap(); - } - } - assert_eq!(budget.used(), 0); - let capture = writer.capture(&table_schema()).unwrap(); - assert!(capture.memory.is_empty()); - assert_eq!(capture.disk.len(), 2); - (writer, capture) - } - - fn ids(batches: &[RecordBatch]) -> Vec { - let mut ids = batches - .iter() - .flat_map(|batch| { - batch - .column_by_name("id") - .unwrap() - .as_any() - .downcast_ref::() - .unwrap() - .iter() - .map(Option::unwrap) - .collect::>() - }) - .collect::>(); - ids.sort_unstable(); - ids - } - - #[tokio::test] - async fn staging_disk_plan_streams_every_row_with_projection_and_filters() { - let dir = TempDir::new().unwrap(); - let (_writer, capture) = disk_only_capture(&dir, 100); - let ctx = SessionContext::new(); - let state = ctx.state(); - + writer + .push_disk_and_memory(file, "fk", &new_batch, dir.path().join(file), range) + .unwrap(); + let capture = writer.capture(&wide_schema).unwrap(); let plan = staging_disk_plan( - table_schema(), - capture.disk.clone(), + wide_schema, + capture.disk, &state, None, - &[], + &[exact_time, cast_pred], None, ) .await .unwrap() .unwrap(); - let all = collect(plan, ctx.task_ctx()).await.unwrap(); - assert!(all.iter().all(|batch| batch.schema() == table_schema())); - let mut expected = (0..100).chain(0..100).collect::>(); - expected.sort_unstable(); - assert_eq!(ids(&all), expected); + let batches = collect(plan, ctx.task_ctx()).await.unwrap(); + let got_ids: Vec = batches + .iter() + .flat_map(|b| { + b.column(1) + .as_any() + .downcast_ref::() + .unwrap() + .values() + .iter() + .copied() + }) + .collect(); + assert_eq!(got_ids, vec![2]); + drop(writer); + } - // Project `id` only. Filters this scan does not report as exact are - // applied by DataFusion above it; the scan must still read their - // columns and return every row. - let filter = col("name").eq(lit("n42")); - let plan = staging_disk_plan( - table_schema(), - capture.disk.clone(), - &state, - Some(&vec![2]), - &[filter], - None, - ) - .await - .unwrap() - .unwrap(); - let filtered = collect(plan, ctx.task_ctx()).await.unwrap(); - assert!(filtered.iter().all(|batch| batch.num_columns() == 1)); - assert_eq!(ids(&filtered), expected); + #[tokio::test] + async fn narrowed_nullability_disables_two_phase_staging_decode_and_fails_closed() { + use super::{staging_disk_plan, two_phase_file_indices}; + use crate::OBJECT_STORE_DATA_GRANULARITY; + use crate::parseable::staging::{ + StagingMemoryBudget, + writer::{MemWriter, Writer}, + }; + use crate::utils::time::TimeRange; + use chrono::Utc; + + let file_schema = Arc::new(Schema::new(vec![ + Field::new( + DEFAULT_TIMESTAMP_KEY, + DataType::Timestamp(TimeUnit::Millisecond, None), + false, + ), + Field::new("id", DataType::Int64, false), + Field::new("level", DataType::Utf8, true), + Field::new("payload_a", DataType::Utf8, true), // nullable in file + Field::new("payload_b", DataType::Utf8, true), + ])); + let narrowed_table_schema = Arc::new(Schema::new(vec![ + Field::new( + DEFAULT_TIMESTAMP_KEY, + DataType::Timestamp(TimeUnit::Millisecond, None), + false, + ), + Field::new("id", DataType::Int64, false), + Field::new("level", DataType::Utf8, true), + Field::new("payload_a", DataType::Utf8, false), // narrowed to non-nullable! + Field::new("payload_b", DataType::Utf8, true), + ])); + let filter_schema = Arc::new(narrowed_table_schema.project(&[2]).unwrap()); + // Unit check: narrowed nullability disables two-phase decoding. assert!( - staging_disk_plan(table_schema(), vec![], &state, None, &[], None) - .await - .unwrap() - .is_none() + two_phase_file_indices(&file_schema, &filter_schema, &narrowed_table_schema).is_none() ); - } + // Same nullability keeps two-phase decoding enabled. + assert!(two_phase_file_indices(&file_schema, &filter_schema, &file_schema).is_some()); - #[tokio::test] - async fn staging_disk_plan_reads_unlinked_files_and_fails_closed_when_short() { + // End-to-end check: a batch with 0 matching filter rows (`level = 'info'` vs + // filter `level = 'error'`) contains a NULL in `payload_a`. Because two-phase + // decoding is disabled, single-phase decode runs `BatchAdapter::adapt` and + // fails closed instead of silently skipping the invalid NULL! let dir = TempDir::new().unwrap(); - let (writer, capture) = disk_only_capture(&dir, 50); + let budget = StagingMemoryBudget::new(0); + let mut writer = Writer { + mem: Some(MemWriter::with_budget(Arc::clone(&budget))), + disk: Default::default(), + }; + let file = "narrow.data.arrows"; + let range = TimeRange::granularity_range(Utc::now(), OBJECT_STORE_DATA_GRANULARITY); + let batch_with_null_payload = RecordBatch::try_new( + file_schema.clone(), + vec![ + Arc::new(TimestampMillisecondArray::from(vec![ts_ms(12, 1, 10)])), + Arc::new(Int64Array::from(vec![1])), + Arc::new(StringArray::from(vec!["info"])), + Arc::new(StringArray::from(vec![Option::<&str>::None])), + Arc::new(StringArray::from(vec!["pb"])), + ], + ) + .unwrap(); + writer + .push_disk_and_memory( + file, + "nk", + &batch_with_null_payload, + dir.path().join(file), + range, + ) + .unwrap(); + let capture = writer.capture(&file_schema).unwrap(); + let ctx = SessionContext::new(); - let state = ctx.state(); - // Detach, seal and delete the files: the captured descriptors still read. - let mut writer = writer; - for detached in writer.detach_flushable_disk_at(true, Utc::now()) { - let sealed = detached.seal().unwrap_or_else(|(_, err)| panic!("{err}")); - std::fs::remove_file(sealed.part).unwrap(); - } let plan = staging_disk_plan( - table_schema(), - capture.disk.clone(), - &state, + narrowed_table_schema, + capture.disk, + &ctx.state(), None, - &[], + &[col("level").eq(lit("error"))], None, ) .await .unwrap() .unwrap(); - assert_eq!( - ids(&collect(plan, ctx.task_ctx()).await.unwrap()).len(), - 100 + assert!( + collect(plan, ctx.task_ctx()).await.is_err(), + "narrowed non-nullable column with NULL must fail closed even on zero-match batch" ); - - // A file shorter than its acknowledged length is an error, not fewer rows. - let dir = TempDir::new().unwrap(); - let (writer, capture) = disk_only_capture(&dir, 50); - let path = writer.disk.values().next().unwrap().path().to_path_buf(); - let len = std::fs::metadata(&path).unwrap().len(); - std::fs::OpenOptions::new() - .write(true) - .open(&path) - .unwrap() - .set_len(len - 3) - .unwrap(); - let plan = staging_disk_plan(table_schema(), capture.disk, &state, None, &[], None) - .await - .unwrap() - .unwrap(); - assert!(collect(plan, ctx.task_ctx()).await.is_err()); drop(writer); } + + #[test] + fn float_manifest_pruning_allows_exact_equality_only_and_guards_nan() { + use crate::catalog::column::{Column, Float64Type, StatsProvenance, TypedStatistics}; + use crate::catalog::manifest::File; + use datafusion::logical_expr::{BinaryExpr, Operator}; + + let make_float_file = |min: f64, max: f64, complete: bool| File { + file_path: "f.parquet".to_string(), + file_size: 1024, + ingestion_size: 1024, + num_rows: 100, + sort_order_id: vec![], + columns: vec![Column { + name: "score".to_string(), + uncompressed_size: 800, + compressed_size: 400, + null_count: Some(0), + stats: Some(TypedStatistics::Float(Float64Type { min, max })), + stats_provenance: Some(StatsProvenance { + complete_row_groups: complete, + exact_min_max: true, + timestamp_unit: None, + }), + }], + }; + + let is_not_distinct = |val: f64| { + Expr::BinaryExpr(BinaryExpr::new( + Box::new(col("score")), + Operator::IsNotDistinctFrom, + Box::new(lit(val)), + )) + }; + + let file = make_float_file(0.0, 100.0, true); + // Equality outside [min, max] prunes soundly even if NaN/-NaN is present. + assert!(file.can_be_pruned(&col("score").eq(lit(999.0_f64)))); + assert!(file.can_be_pruned(&col("score").eq(lit(-1.0_f64)))); + assert!(file.can_be_pruned(&is_not_distinct(999.0_f64))); + assert!(file.can_be_pruned(&col("score").eq(lit(f64::INFINITY)))); + // Equality inside [min, max] (including -0.0 against min=0.0) must NOT prune. + assert!(!file.can_be_pruned(&col("score").eq(lit(50.0_f64)))); + assert!(!file.can_be_pruned(&col("score").eq(lit(-0.0_f64)))); + // NaN literal must NEVER prune. + assert!(!file.can_be_pruned(&col("score").eq(lit(f64::NAN)))); + assert!(!file.can_be_pruned(&is_not_distinct(f64::NAN))); + // Range operators must NEVER prune from Parquet float min/max because + // DataFusion evaluates `+NaN > +inf` and `-NaN < -inf` as true. + assert!(!file.can_be_pruned(&col("score").lt(lit(-1.0_f64)))); + assert!(!file.can_be_pruned(&col("score").lt_eq(lit(-1.0_f64)))); + assert!(!file.can_be_pruned(&col("score").gt(lit(999.0_f64)))); + assert!(!file.can_be_pruned(&col("score").gt_eq(lit(999.0_f64)))); + // Incomplete row-group stats or NaN/inverted manifest bounds never prune. + assert!( + !make_float_file(0.0, 100.0, false).can_be_pruned(&col("score").eq(lit(999.0_f64))) + ); + assert!(!make_float_file(100.0, 0.0, true).can_be_pruned(&col("score").eq(lit(999.0_f64)))); + assert!( + !make_float_file(f64::NAN, 100.0, true).can_be_pruned(&col("score").eq(lit(999.0_f64))) + ); + } } diff --git a/src/storage/field_stats.rs b/src/storage/field_stats.rs index b9a119c76..74a1a1c87 100644 --- a/src/storage/field_stats.rs +++ b/src/storage/field_stats.rs @@ -83,8 +83,8 @@ use rustc_hash::FxHashMap; use serde::Deserialize; use serde::Serialize; use std::borrow::Cow; -use std::collections::{HashMap, HashSet}; -use std::fmt::Debug; +use std::collections::{HashMap, HashSet, hash_map::Entry}; +use std::fmt::{Debug, Write as _}; use std::fs::File; use std::path::{Path, PathBuf}; use std::sync::LazyLock; @@ -109,13 +109,45 @@ const MAX_TRACKED_DISTINCT_VALUES_PER_FIELD: usize = 10_000; const NULL_VALUE: &str = "NULL"; const HLL_PRECISION_BITS: u32 = 12; const HLL_REGISTER_COUNT: usize = 1 << HLL_PRECISION_BITS; +const FIELD_STATS_THREADS_VAR: &str = "FIELD_STATS_THREADS"; + +/// Threads for `FIELD_STATS_RAYON_POOL`: a positive override, else half the +/// CPUs clamped to 2..=8 (matching `LOG_CONVERSION_THREADPOOL`) so field-stats +/// calculation cannot starve HTTP ingest of CPU cores. +fn field_stats_threads(var: Option<&str>, cpus: usize) -> usize { + var.and_then(|var| var.trim().parse::().ok()) + .filter(|&threads| threads > 0) + .unwrap_or_else(|| (cpus / 2).clamp(2, 8)) +} + static FIELD_STATS_RAYON_POOL: Lazy = Lazy::new(|| { + let threads = field_stats_threads( + std::env::var(FIELD_STATS_THREADS_VAR).ok().as_deref(), + num_cpus::get(), + ); ThreadPoolBuilder::new() + .num_threads(threads) .thread_name(|index| format!("field-stats-{index}")) .build() .expect("field stats rayon pool should initialize") }); +/// Runs parallel field-stats work on a bounded Rayon pool without cross-pool +/// oversubscription or deadlocks: +/// - If already executing inside a Rayon pool (e.g. `LOG_CONVERSION_THREADPOOL` +/// during periodic Parquet conversion), run directly on the current pool so +/// Rayon work-stealing stays within that pool's `cpus/2` budget and never +/// blocks a conversion thread waiting on a second pool. +/// - Otherwise (e.g. Tokio `spawn_blocking` fallback or sequential startup +/// conversion), run on the bounded `FIELD_STATS_RAYON_POOL`. +fn run_in_field_stats_pool(op: impl FnOnce() -> R + Send) -> R { + if rayon::current_thread_index().is_some() { + op() + } else { + FIELD_STATS_RAYON_POOL.install(op) + } +} + #[derive(Serialize, Debug, Clone, PartialEq, Eq)] pub struct DistinctStat { pub distinct_value: String, @@ -133,23 +165,75 @@ pub struct FieldStat { const MAX_STAGED_FIELD_STATS_CACHE_ENTRIES: usize = 512; const STAGED_FIELD_STATS_CACHE_TTL: Duration = Duration::from_secs(900); +/// Approximate bytes of tracked distinct values an inline +/// [`FieldStatsAccumulator`] may retain for one converted file. A conversion +/// whose accumulator grows past it (or whose counts become approximate, see +/// [`FieldStatsAccumulator::exceeds_inline_budget`]) drops the accumulator +/// and leaves the statistics to the post-write reread of the Parquet file. +/// It also bounds the size of one entry in the staged statistics cache. +pub const MAX_INLINE_FIELD_STATS_BYTES: usize = 16 * 1024 * 1024; + +/// Approximate bytes all staged statistics cache entries may hold together, +/// so statistics waiting for a lagging upload cannot pin unbounded strings. +const MAX_STAGED_FIELD_STATS_CACHE_BYTES: usize = 64 * 1024 * 1024; + +/// Approximate heap overhead of one tracked distinct value besides its text: +/// the `String` header, its count and the hash table slot. +const TRACKED_VALUE_OVERHEAD_BYTES: usize = + std::mem::size_of::() + std::mem::size_of::() + 8; + struct CachedFieldStats { max_field_statistics: usize, stats: Vec, + /// Approximate heap bytes of `stats`, see [`field_stats_bytes`]. + 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() +} + static STAGED_FIELD_STATS_CACHE: LazyLock> = LazyLock::new(DashMap::new); /// Caches precomputed per-field statistics for a newly staged Parquet file so /// post-upload field stats publication can consume them in memory without /// re-opening and re-decoding the Parquet file from disk. +/// +/// Entries are bounded in number, age and approximate bytes: an entry larger +/// than [`MAX_INLINE_FIELD_STATS_BYTES`] is not cached (the upload path then +/// reads the file back), and older entries are evicted so that all entries +/// 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(); - if !STAGED_FIELD_STATS_CACHE.contains_key(path) - && STAGED_FIELD_STATS_CACHE.len() >= MAX_STAGED_FIELD_STATS_CACHE_ENTRIES - { + 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 }); @@ -175,11 +259,52 @@ pub fn cache_staged_field_stats(path: &Path, max_field_statistics: usize, stats: 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); + } + } +} + /// 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> { @@ -564,7 +689,6 @@ async fn collect_all_field_stats_from_parquet( /// Incrementally accumulates per-field statistics from Arrow `RecordBatch`es /// using the exact same chunked counting logic as Parquet-backed field stats. pub struct FieldStatsAccumulator { - stream_name: String, max_field_statistics: usize, field_counts: Vec<(String, FieldCountState)>, } @@ -583,7 +707,6 @@ impl FieldStatsAccumulator { }) .collect(); Self { - stream_name: stream_name.to_string(), max_field_statistics, field_counts, } @@ -593,30 +716,48 @@ impl FieldStatsAccumulator { if batch.num_rows() == 0 { return; } - let stream_name = self.stream_name.as_str(); - let max_field_statistics = self.max_field_statistics; - FIELD_STATS_RAYON_POOL.install(|| { - self.field_counts.par_iter_mut().for_each(|(name, total)| { - if let Some(array) = batch.column_by_name(name) { - // Retain the old candidate-merge boundaries. Larger candidate states - // lose repeated tail values before they can be merged into the total. - // Decode and schedule in large batches, but merge in the same order as - // the former 1024-row Parquet reader, including across row groups. - for offset in (0..array.len()).step_by(1024) { - let chunk = array.slice(offset, (array.len() - offset).min(1024)); - let state = collect_array_field_counts( - stream_name, - chunk.as_ref(), - name, - max_field_statistics, - ); - total.merge_state(state); + run_in_field_stats_pool(|| { + self.field_counts.par_iter_mut().for_each_init( + BatchScratch::default, + |scratch, (name, total)| { + if let Some(array) = batch.column_by_name(name) { + // Retain the old 1,024-row candidate-merge boundaries. Larger + // candidate states lose repeated tail values before they can be + // merged into the total. Update `total.hll` and `total.counts` + // directly using reusable per-worker scratch buffers so steady-state + // high-cardinality scanning performs zero per-chunk HLL/map/String + // allocations. + accumulate_array_chunks(total, array.as_ref(), scratch); } - } - }); + }, + ); }); } + /// Whether any field has seen more distinct values than it tracks. Its + /// top values are then approximate and depend on the order rows are + /// 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) + } + + /// Approximate heap bytes of the distinct values tracked by all fields. + pub fn retained_bytes(&self) -> usize { + self.field_counts + .iter() + .map(|(_, state)| state.retained_bytes) + .fold(0, usize::saturating_add) + } + + /// Whether statistics collected inline, while rows are written in + /// another order than they are counted in, should be dropped and left to + /// the post-write reread: when their counts became approximate, or when + /// they retain more than `max_bytes` (see [`MAX_INLINE_FIELD_STATS_BYTES`]). + pub fn exceeds_inline_budget(&self, max_bytes: usize) -> bool { + self.is_approximate() || self.retained_bytes() > max_bytes + } + pub fn finish(self) -> Vec { let max_field_statistics = self.max_field_statistics; self.field_counts @@ -709,133 +850,502 @@ fn collect_field_stats_with_batch_size( Ok(accumulator.finish()) } -#[cfg(test)] -fn collect_field_counts( - stream_name: &str, - batch: &arrow_array::RecordBatch, - field_name: &str, - max_field_statistics: usize, -) -> Option<(String, FieldCountState)> { - let array = batch.column_by_name(field_name)?; - Some(( - field_name.to_string(), - collect_array_field_counts( - stream_name, - array.as_ref(), - field_name, - max_field_statistics, - ), - )) +/// Reusable per-worker scratch buffers for chunked field-stats accumulation. +/// Initialized once per participating Rayon thread per `RecordBatch`, eliminating +/// per-chunk `FieldCountState`, 4 KiB `HyperLogLog`, `FxHashMap`, and throwaway +/// `String` allocations. +#[derive(Default)] +struct BatchScratch<'a> { + /// Borrowed string frequency map for `Utf8`/`Utf8View` 1,024-row chunks. + str_counts: FxHashMap<&'a str, i64>, + /// First-seen string order for rare order-sensitive chunks (transition or eviction). + str_order: Vec<&'a str>, + /// Native-bit dedup map (`Option -> index in native_values`) for primitive chunks. + native_positions: FxHashMap, usize>, + /// Distinct `(row_index, count)` pairs in first-seen order within the current chunk. + native_values: Vec<(usize, i64)>, + /// Single reusable formatting buffer for numeric/timestamp/date/bool values. + format_buf: String, + /// Contiguous formatted-string arena + byte ranges for generic fallback and rare + /// order-sensitive native chunks (avoids per-value heap `String` allocations). + text_arena: String, + text_ranges: Vec<(usize, usize)>, } -fn collect_array_field_counts( - stream_name: &str, +#[inline] +fn timestamp_millis_key(v: i64) -> u64 { + if chrono::DateTime::from_timestamp_millis(v).is_some() { + v as u64 + } else { + // Canonicalize all out-of-range timestamps, which all format to "INVALID_TIMESTAMP". + i64::MIN as u64 + } +} + +#[inline] +fn f64_canonical_bits(v: f64) -> u64 { + if v.is_nan() { + // Canonicalize all NaN bit patterns (which all format to "NaN"), while + // keeping -0.0 and +0.0 distinct ("-0" vs "0"). + f64::NAN.to_bits() + } else { + v.to_bits() + } +} + +#[inline] +fn f32_canonical_bits(v: f32) -> u64 { + if v.is_nan() { + f32::NAN.to_bits() as u64 + } else { + v.to_bits() as u64 + } +} + +#[inline] +fn format_timestamp_millis_into(buf: &mut String, timestamp: i64) { + if let Some(dt) = chrono::DateTime::from_timestamp_millis(timestamp) { + let _ = write!(buf, "{}", dt.naive_utc().format("%Y-%m-%dT%H:%M:%S%.3f")); + } else { + buf.push_str("INVALID_TIMESTAMP"); + } +} + +fn accumulate_str_chunk<'a>( + total: &mut FieldCountState, + scratch: &mut BatchScratch<'a>, + len: usize, + mut value_at: impl FnMut(usize) -> &'a str, +) { + if len == 0 { + return; + } + scratch.str_counts.clear(); + scratch.str_order.clear(); + let mut max_chunk_count = 0i64; + for i in 0..len { + let value = value_at(i); + match scratch.str_counts.entry(value) { + Entry::Occupied(mut occupied) => { + let count = occupied.get_mut(); + *count += 1; + if *count > max_chunk_count { + max_chunk_count = *count; + } + } + Entry::Vacant(vacant) => { + vacant.insert(1); + scratch.str_order.push(value); + if max_chunk_count == 0 { + max_chunk_count = 1; + } + } + } + } + + total.total_count += len as i64; + + // Order within a chunk can affect `total.counts` only when crossing + // `max_tracked_values` (at most once per field) or when an unseen value in + // this chunk repeats more than `total.min_count_hint` while `total.counts` + // is already full. Otherwise merging is strictly order-independent. + let needs_legacy_order = if total.counts.len() < total.max_tracked_values { + total.counts.len() + scratch.str_counts.len() > total.max_tracked_values + } else { + max_chunk_count > total.min_count_hint + && scratch.str_counts.iter().any(|(&value, &count)| { + count > total.min_count_hint && !total.counts.contains_key(value) + }) + }; + + if needs_legacy_order { + let mut ordered: FxHashMap<&'a str, i64> = FxHashMap::default(); + for &value in &scratch.str_order { + let count = scratch.str_counts[value]; + 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); + } + } +} + +#[allow(clippy::too_many_arguments)] +fn accumulate_native_chunk( + total: &mut FieldCountState, + scratch: &mut BatchScratch<'_>, + arr: &A, + offset: usize, + chunk_len: usize, + has_nulls: bool, + mut key_at: K, + mut fmt_at: F, +) where + A: Array, + K: FnMut(&A, usize) -> u64, + F: FnMut(&mut String, &A, usize), +{ + if chunk_len == 0 { + return; + } + scratch.native_positions.clear(); + scratch.native_values.clear(); + let mut max_chunk_count = 0i64; + for i in 0..chunk_len { + let row_idx = offset + i; + let key = if has_nulls && arr.is_null(row_idx) { + None + } else { + Some(key_at(arr, row_idx)) + }; + if let Some(&position) = scratch.native_positions.get(&key) { + let count = &mut scratch.native_values[position].1; + *count += 1; + if *count > max_chunk_count { + max_chunk_count = *count; + } + } else { + let position = scratch.native_values.len(); + scratch.native_positions.insert(key, position); + scratch.native_values.push((row_idx, 1)); + if max_chunk_count == 0 { + max_chunk_count = 1; + } + } + } + + total.total_count += chunk_len as i64; + + let format_row = |buf: &mut String, row_idx: usize, fmt_at: &mut F| { + if has_nulls && arr.is_null(row_idx) { + buf.push_str(NULL_VALUE); + } else { + fmt_at(buf, arr, row_idx); + } + }; + + let needs_legacy_order = if total.counts.len() < total.max_tracked_values { + total.counts.len() + scratch.native_values.len() > total.max_tracked_values + } else if max_chunk_count > total.min_count_hint { + let mut unseen_can_evict = false; + for &(row_idx, count) in &scratch.native_values { + if count > total.min_count_hint { + scratch.format_buf.clear(); + format_row(&mut scratch.format_buf, row_idx, &mut fmt_at); + if !total.counts.contains_key(scratch.format_buf.as_str()) { + unseen_can_evict = true; + break; + } + } + } + unseen_can_evict + } else { + false + }; + + if needs_legacy_order { + scratch.text_arena.clear(); + scratch.text_ranges.clear(); + for &(row_idx, _) in &scratch.native_values { + let start = scratch.text_arena.len(); + format_row(&mut scratch.text_arena, row_idx, &mut fmt_at); + let end = scratch.text_arena.len(); + scratch.text_ranges.push((start, end)); + } + let mut ordered: FxHashMap<&str, i64> = FxHashMap::default(); + for (&(start, end), &(_, count)) in + scratch.text_ranges.iter().zip(scratch.native_values.iter()) + { + *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 { + for &(row_idx, count) in &scratch.native_values { + 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); + } + } +} + +fn accumulate_generic_chunk( + total: &mut FieldCountState, + scratch: &mut BatchScratch<'_>, array: &dyn Array, - field_name: &str, - max_field_statistics: usize, -) -> FieldCountState { - let mut field_count = FieldCountState::new_for_batch( - stream_name.to_string(), - field_name.to_string(), - max_field_statistics, - ); + offset: usize, + chunk_len: usize, +) { + if chunk_len == 0 { + return; + } + scratch.text_arena.clear(); + scratch.text_ranges.clear(); + for i in 0..chunk_len { + let start = scratch.text_arena.len(); + format_arrow_value_into(&mut scratch.text_arena, array, offset + i); + let end = scratch.text_arena.len(); + scratch.text_ranges.push((start, end)); + } + let mut chunk_counts: FxHashMap<&str, i64> = FxHashMap::default(); + for &(start, end) in &scratch.text_ranges { + *chunk_counts + .entry(&scratch.text_arena[start..end]) + .or_insert(0) += 1; + } + total.total_count += chunk_len as i64; + for (value, count) in chunk_counts { + total.hll.add(value); + total.track_value(Cow::Borrowed(value), count); + } +} - // Count by native bits, never float equality (NaNs and signed zero matter). - // Hash the same formatted bytes as before, preserving every HLL register. - // Native counting is bounded to one logical chunk, including for wide files. +fn accumulate_array_chunks<'a>( + total: &mut FieldCountState, + array: &'a dyn Array, + scratch: &mut BatchScratch<'a>, +) { + let len = array.len(); + if len == 0 { + return; + } + + // Count by canonical native bits (never float equality: NaNs and signed zero matter), + // hashing the exact formatted bytes directly into `total.hll` and probing `total.counts` + // via a reusable formatting scratch buffer. macro_rules! native_counts { - ($ty:ty, $key:expr) => { + ($ty:ty, $key:expr, $fmt:expr) => { if let Some(arr) = array.as_any().downcast_ref::<$ty>() { - if arr.len() <= MIN_TRACKED_DISTINCT_VALUES_PER_FIELD { - // A logical batch fits entirely below the cap. Count native values, - // then format/hash each distinct value once, in first-seen order so - // the resulting string map has the legacy insertion/merge order. - let mut positions: FxHashMap, usize> = FxHashMap::default(); - let mut values: Vec<(usize, i64)> = Vec::new(); - let mut aggregate = true; - for i in 0..arr.len() { - // Unique numeric columns cannot amortize formatting. Probe only - // a short prefix, then use the original single-map path. - if i == 32 && values.len() >= 30 { - aggregate = false; - break; - } - let key = (!arr.is_null(i)).then(|| ($key)(arr.value(i))); - if let Some(&position) = positions.get(&key) { - values[position].1 += 1; - } else { - positions.insert(key, values.len()); - values.push((i, 1)); - } - } - if aggregate { - for (i, count) in values { - let text = format_arrow_value(array, i); - field_count.hll.add(&text); - field_count.total_count += count; - field_count.track_value(Cow::Owned(text), count); - } - return field_count; - } - } - for i in 0..arr.len() { - field_count.record_value(Cow::Owned(format_arrow_value(array, i))); + let has_nulls = arr.null_count() > 0; + 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); + accumulate_native_chunk( + total, + scratch, + arr, + offset, + chunk_len, + has_nulls, + |a: &$ty, idx| ($key)(a.value(idx)), + |buf: &mut String, a: &$ty, idx| ($fmt)(buf, a.value(idx)), + ); } - return field_count; + return; } }; } - native_counts!(TimestampMillisecondArray, |v: i64| v as u64); - native_counts!(Int64Array, |v: i64| v as u64); - native_counts!(arrow_array::Int32Array, |v: i32| v as u64); - native_counts!(arrow_array::Int16Array, |v: i16| v as u64); - native_counts!(arrow_array::Int8Array, |v: i8| v as u64); - native_counts!(arrow_array::UInt64Array, |v: u64| v); - native_counts!(arrow_array::UInt32Array, |v: u32| v as u64); - native_counts!(arrow_array::UInt16Array, |v: u16| v as u64); - native_counts!(arrow_array::UInt8Array, |v: u8| v as u64); - native_counts!(Float64Array, |v: f64| v.to_bits()); - native_counts!(arrow_array::Float32Array, |v: f32| v.to_bits() as u64); - native_counts!(Date32Array, |v: i32| v as u64); - native_counts!(BooleanArray, |v: bool| v as u64); - // Fast paths for the string-like types that dominate log payloads. These read the value as a - // borrowed `&str` straight out of the Arrow buffer, so a `String` is only allocated when the - // value is actually inserted into the tracked-values map. + native_counts!( + TimestampMillisecondArray, + timestamp_millis_key, + format_timestamp_millis_into + ); + native_counts!(Int64Array, |v: i64| v as u64, |buf: &mut String, v: i64| { + let _ = write!(buf, "{v}"); + }); + native_counts!( + arrow_array::Int32Array, + |v: i32| v as u64, + |buf: &mut String, v: i32| { + let _ = write!(buf, "{v}"); + } + ); + native_counts!( + arrow_array::Int16Array, + |v: i16| v as u64, + |buf: &mut String, v: i16| { + let _ = write!(buf, "{v}"); + } + ); + native_counts!( + arrow_array::Int8Array, + |v: i8| v as u64, + |buf: &mut String, v: i8| { + let _ = write!(buf, "{v}"); + } + ); + native_counts!( + arrow_array::UInt64Array, + |v: u64| v, + |buf: &mut String, v: u64| { + let _ = write!(buf, "{v}"); + } + ); + native_counts!( + arrow_array::UInt32Array, + |v: u32| v as u64, + |buf: &mut String, v: u32| { + let _ = write!(buf, "{v}"); + } + ); + native_counts!( + arrow_array::UInt16Array, + |v: u16| v as u64, + |buf: &mut String, v: u16| { + let _ = write!(buf, "{v}"); + } + ); + native_counts!( + arrow_array::UInt8Array, + |v: u8| v as u64, + |buf: &mut String, v: u8| { + let _ = write!(buf, "{v}"); + } + ); + native_counts!( + Float64Array, + f64_canonical_bits, + |buf: &mut String, v: f64| { + let _ = write!(buf, "{v}"); + } + ); + native_counts!( + arrow_array::Float32Array, + f32_canonical_bits, + |buf: &mut String, v: f32| { + let _ = write!(buf, "{v}"); + } + ); + native_counts!( + Date32Array, + |v: i32| v as u64, + |buf: &mut String, v: i32| { + let _ = write!(buf, "{v}"); + } + ); + native_counts!( + BooleanArray, + |v: bool| v as u64, + |buf: &mut String, v: bool| { + buf.push_str(if v { "true" } else { "false" }); + } + ); + + // Fast paths for the string-like types that dominate log payloads. Values are borrowed + // straight out of the Arrow buffer into `scratch.str_counts`, so a heap `String` is only + // allocated when a value is actually inserted into `total.counts`. match array.data_type() { DataType::Utf8 => { if let Some(arr) = array.as_any().downcast_ref::() { - for row_index in 0..arr.len() { - if arr.is_null(row_index) { - field_count.record_value(Cow::Borrowed(NULL_VALUE)); + let has_nulls = arr.null_count() > 0; + 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); + if has_nulls { + accumulate_str_chunk(total, scratch, chunk_len, |i| { + let idx = offset + i; + if arr.is_null(idx) { + NULL_VALUE + } else { + arr.value(idx) + } + }); } else { - field_count.record_value(Cow::Borrowed(arr.value(row_index))); + accumulate_str_chunk(total, scratch, chunk_len, |i| arr.value(offset + i)); } } - return field_count; + return; } } DataType::Utf8View => { if let Some(arr) = array.as_any().downcast_ref::() { - for row_index in 0..arr.len() { - if arr.is_null(row_index) { - field_count.record_value(Cow::Borrowed(NULL_VALUE)); + let has_nulls = arr.null_count() > 0; + 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); + if has_nulls { + accumulate_str_chunk(total, scratch, chunk_len, |i| { + let idx = offset + i; + if arr.is_null(idx) { + NULL_VALUE + } else { + arr.value(idx) + } + }); } else { - field_count.record_value(Cow::Borrowed(arr.value(row_index))); + accumulate_str_chunk(total, scratch, chunk_len, |i| arr.value(offset + i)); } } - return field_count; + return; + } + } + 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); } + return; } _ => {} } - for row_index in 0..array.len() { - let value = format_arrow_value(array, row_index); - field_count.record_value(Cow::Owned(value)); + 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); + accumulate_generic_chunk(total, scratch, array, offset, chunk_len); } +} - field_count +#[cfg(test)] +fn collect_field_counts( + stream_name: &str, + batch: &arrow_array::RecordBatch, + field_name: &str, + max_field_statistics: usize, +) -> Option<(String, FieldCountState)> { + let array = batch.column_by_name(field_name)?; + let mut field_count = FieldCountState::new_for_batch( + stream_name.to_string(), + field_name.to_string(), + max_field_statistics, + ); + let mut scratch = BatchScratch::default(); + if array.len() <= MIN_TRACKED_DISTINCT_VALUES_PER_FIELD { + accumulate_array_chunks(&mut field_count, array.as_ref(), &mut scratch); + } else { + match array.data_type() { + DataType::Utf8 => { + if let Some(arr) = array.as_any().downcast_ref::() { + for row_index in 0..arr.len() { + if arr.is_null(row_index) { + field_count.record_value(Cow::Borrowed(NULL_VALUE)); + } else { + field_count.record_value(Cow::Borrowed(arr.value(row_index))); + } + } + return Some((field_name.to_string(), field_count)); + } + } + DataType::Utf8View => { + if let Some(arr) = array.as_any().downcast_ref::() { + for row_index in 0..arr.len() { + if arr.is_null(row_index) { + field_count.record_value(Cow::Borrowed(NULL_VALUE)); + } else { + field_count.record_value(Cow::Borrowed(arr.value(row_index))); + } + } + return Some((field_name.to_string(), field_count)); + } + } + _ => {} + } + for row_index in 0..array.len() { + scratch.format_buf.clear(); + format_arrow_value_into(&mut scratch.format_buf, array.as_ref(), row_index); + field_count.record_value(Cow::Borrowed(scratch.format_buf.as_str())); + } + } + Some((field_name.to_string(), field_count)) } #[cfg(test)] @@ -864,6 +1374,8 @@ struct FieldCountState { min_count_hint: i64, approximate: bool, log_cardinality_cap: bool, + /// Approximate heap bytes of the values in `counts`. + retained_bytes: usize, } impl FieldCountState { @@ -871,6 +1383,7 @@ impl FieldCountState { Self::new_with_logging(stream_name, field_name, max_field_statistics, true) } + #[cfg(test)] fn new_for_batch(stream_name: String, field_name: String, max_field_statistics: usize) -> Self { Self::new_with_logging(stream_name, field_name, max_field_statistics, false) } @@ -891,9 +1404,11 @@ impl FieldCountState { min_count_hint: i64::MAX, approximate: false, log_cardinality_cap, + retained_bytes: 0, } } + #[cfg(test)] fn record_value(&mut self, value: Cow<'_, str>) { self.hll.add(value.as_ref()); self.total_count += 1; @@ -909,6 +1424,7 @@ impl FieldCountState { } } + #[cfg(test)] fn merge_state(&mut self, state: FieldCountState) { self.hll.merge(&state.hll); self.total_count += state.total_count; @@ -930,6 +1446,9 @@ impl FieldCountState { if self.counts.len() < self.max_tracked_values { self.min_count_hint = self.min_count_hint.min(count); + self.retained_bytes = self + .retained_bytes + .saturating_add(value.len() + TRACKED_VALUE_OVERHEAD_BYTES); self.counts.insert(value.into_owned(), count); return; } @@ -949,6 +1468,10 @@ impl FieldCountState { self.min_count_hint = min_count; if count > min_count { self.counts.remove(&min_value); + self.retained_bytes = self + .retained_bytes + .saturating_sub(min_value.len()) + .saturating_add(value.len()); self.counts.insert(value.into_owned(), count); } } @@ -1034,6 +1557,7 @@ impl HyperLogLog { self.registers[register_index] = self.registers[register_index].max(rank); } + #[cfg(test)] fn merge(&mut self, other: &Self) { for (register, other_register) in self.registers.iter_mut().zip(other.registers.iter()) { *register = (*register).max(*other_register); @@ -1075,10 +1599,10 @@ fn hash_field_value(value: &str) -> u64 { xxhash_rust::xxh3::xxh3_64(value.as_bytes()) } -macro_rules! try_downcast { - ($ty:ty, $arr:expr, $body:expr) => { +macro_rules! try_downcast_into { + ($ty:ty, $arr:expr, $buf:expr, $body:expr) => { if let Some(arr) = $arr.as_any().downcast_ref::<$ty>() { - $body(arr) + $body(arr); } else { warn!( "Expected {} for {:?}, but found {:?}", @@ -1086,124 +1610,159 @@ macro_rules! try_downcast { $arr.data_type(), $arr.data_type() ); - "UNSUPPORTED".to_string() + $buf.push_str("UNSUPPORTED"); } }; } -/// Function to format an Arrow value at a given index into a string. -/// Handles null values and different data types by downcasting the array to the appropriate type. -fn format_arrow_value(array: &dyn Array, idx: usize) -> String { +/// Appends the formatted Arrow value at `idx` into `buf` without allocating a +/// per-row `String`. +fn format_arrow_value_into(buf: &mut String, array: &dyn Array, idx: usize) { if array.is_null(idx) { - return "NULL".to_string(); + buf.push_str(NULL_VALUE); + return; } match array.data_type() { - DataType::Utf8 => try_downcast!(StringArray, array, |arr: &StringArray| arr - .value(idx) - .to_string()), - DataType::Utf8View => try_downcast!(StringViewArray, array, |arr: &StringViewArray| arr - .value(idx) - .to_string()), - DataType::Binary => try_downcast!(BinaryArray, array, |arr: &BinaryArray| { - String::from_utf8_lossy(arr.value(idx)).to_string() + DataType::Utf8 => try_downcast_into!(StringArray, array, buf, |arr: &StringArray| { + buf.push_str(arr.value(idx)); }), - DataType::BinaryView => try_downcast!(BinaryViewArray, array, |arr: &BinaryViewArray| { - String::from_utf8_lossy(arr.value(idx)).to_string() + DataType::Utf8View => { + try_downcast_into!(StringViewArray, array, buf, |arr: &StringViewArray| { + buf.push_str(arr.value(idx)); + }) + } + DataType::Binary => try_downcast_into!(BinaryArray, array, buf, |arr: &BinaryArray| { + buf.push_str(&String::from_utf8_lossy(arr.value(idx))); }), - DataType::Int64 => try_downcast!(Int64Array, array, |arr: &Int64Array| arr - .value(idx) - .to_string()), - DataType::Int32 => try_downcast!( + DataType::BinaryView => { + try_downcast_into!(BinaryViewArray, array, buf, |arr: &BinaryViewArray| { + buf.push_str(&String::from_utf8_lossy(arr.value(idx))); + }) + } + DataType::Int64 => try_downcast_into!(Int64Array, array, buf, |arr: &Int64Array| { + let _ = write!(buf, "{}", arr.value(idx)); + }), + DataType::Int32 => try_downcast_into!( arrow_array::Int32Array, array, - |arr: &arrow_array::Int32Array| arr.value(idx).to_string() + buf, + |arr: &arrow_array::Int32Array| { + let _ = write!(buf, "{}", arr.value(idx)); + } ), - DataType::Int16 => try_downcast!( + DataType::Int16 => try_downcast_into!( arrow_array::Int16Array, array, - |arr: &arrow_array::Int16Array| arr.value(idx).to_string() + buf, + |arr: &arrow_array::Int16Array| { + let _ = write!(buf, "{}", arr.value(idx)); + } ), - DataType::Int8 => try_downcast!( + DataType::Int8 => try_downcast_into!( arrow_array::Int8Array, array, - |arr: &arrow_array::Int8Array| arr.value(idx).to_string() + buf, + |arr: &arrow_array::Int8Array| { + let _ = write!(buf, "{}", arr.value(idx)); + } ), - DataType::UInt64 => try_downcast!( + DataType::UInt64 => try_downcast_into!( arrow_array::UInt64Array, array, - |arr: &arrow_array::UInt64Array| arr.value(idx).to_string() + buf, + |arr: &arrow_array::UInt64Array| { + let _ = write!(buf, "{}", arr.value(idx)); + } ), - DataType::UInt32 => try_downcast!( + DataType::UInt32 => try_downcast_into!( arrow_array::UInt32Array, array, - |arr: &arrow_array::UInt32Array| arr.value(idx).to_string() + buf, + |arr: &arrow_array::UInt32Array| { + let _ = write!(buf, "{}", arr.value(idx)); + } ), - DataType::UInt16 => try_downcast!( + DataType::UInt16 => try_downcast_into!( arrow_array::UInt16Array, array, - |arr: &arrow_array::UInt16Array| arr.value(idx).to_string() + buf, + |arr: &arrow_array::UInt16Array| { + let _ = write!(buf, "{}", arr.value(idx)); + } ), - DataType::UInt8 => try_downcast!( + DataType::UInt8 => try_downcast_into!( arrow_array::UInt8Array, array, - |arr: &arrow_array::UInt8Array| arr.value(idx).to_string() + buf, + |arr: &arrow_array::UInt8Array| { + let _ = write!(buf, "{}", arr.value(idx)); + } ), - DataType::Float64 => try_downcast!(Float64Array, array, |arr: &Float64Array| arr - .value(idx) - .to_string()), - DataType::Float32 => try_downcast!( + DataType::Float64 => try_downcast_into!(Float64Array, array, buf, |arr: &Float64Array| { + let _ = write!(buf, "{}", arr.value(idx)); + }), + DataType::Float32 => try_downcast_into!( arrow_array::Float32Array, array, - |arr: &arrow_array::Float32Array| arr.value(idx).to_string() + buf, + |arr: &arrow_array::Float32Array| { + let _ = write!(buf, "{}", arr.value(idx)); + } ), - DataType::Timestamp(TimeUnit::Millisecond, _) => try_downcast!( + DataType::Timestamp(TimeUnit::Millisecond, _) => try_downcast_into!( TimestampMillisecondArray, array, + buf, |arr: &TimestampMillisecondArray| { - let timestamp = arr.value(idx); - chrono::DateTime::from_timestamp_millis(timestamp) - .map(|dt| dt.naive_utc().format("%Y-%m-%dT%H:%M:%S%.3f").to_string()) - .unwrap_or_else(|| "INVALID_TIMESTAMP".to_string()) + format_timestamp_millis_into(buf, arr.value(idx)); } ), - DataType::Date32 => try_downcast!(Date32Array, array, |arr: &Date32Array| arr - .value(idx) - .to_string()), - DataType::Boolean => try_downcast!(BooleanArray, array, |arr: &BooleanArray| if arr - .value(idx) - { - "true".to_string() - } else { - "false".to_string() + DataType::Date32 => try_downcast_into!(Date32Array, array, buf, |arr: &Date32Array| { + let _ = write!(buf, "{}", arr.value(idx)); }), - DataType::List(_field) => try_downcast!( + DataType::Boolean => try_downcast_into!(BooleanArray, array, buf, |arr: &BooleanArray| { + buf.push_str(if arr.value(idx) { "true" } else { "false" }); + }), + DataType::List(_field) => try_downcast_into!( arrow_array::ListArray, array, + buf, |list_array: &arrow_array::ListArray| { let child_array = list_array.values(); let offsets = list_array.value_offsets(); let start = offsets[idx] as usize; let end = offsets[idx + 1] as usize; - let formatted_values: Vec = (start..end) - .map(|i| format_arrow_value(child_array.as_ref(), i)) - .collect(); - - format!("[{}]", formatted_values.join(", ")) + buf.push('['); + for i in start..end { + if i > start { + buf.push_str(", "); + } + format_arrow_value_into(buf, child_array.as_ref(), i); + } + buf.push(']'); } ), - DataType::Null => "NULL".to_string(), + DataType::Null => buf.push_str(NULL_VALUE), _ => { warn!( "Unsupported array type for statistics: {:?}", array.data_type() ); - "UNSUPPORTED".to_string() + buf.push_str("UNSUPPORTED"); } } } +/// Function to format an Arrow value at a given index into a string. +#[cfg(test)] +fn format_arrow_value(array: &dyn Array, idx: usize) -> String { + let mut buf = String::new(); + format_arrow_value_into(&mut buf, array, idx); + buf +} + static PARQUET_DATETIME_REGEX: LazyLock = LazyLock::new(|| { Regex::new(r"date=(\d{4}-\d{2}-\d{2})\.hour=(\d{1,2})\.minute=(\d{1,2})") .expect("parquet datetime regex is valid") @@ -2767,6 +3326,83 @@ mod tests { ); } + #[test] + fn accumulator_reports_retained_bytes_and_approximate_mode() { + use super::{ + FieldStatsAccumulator, MAX_INLINE_FIELD_STATS_BYTES, TRACKED_VALUE_OVERHEAD_BYTES, + }; + + let schema = Schema::new(vec![Field::new("v", DataType::Utf8, true)]); + let batch_of = |values: std::ops::Range| { + RecordBatch::try_new( + Arc::new(schema.clone()), + vec![Arc::new(StringArray::from_iter_values( + values.map(|value| format!("{value:0100}")), + ))], + ) + .unwrap() + }; + let mut accumulator = FieldStatsAccumulator::new("s", &schema, 5); + assert_eq!(accumulator.retained_bytes(), 0); + assert!(!accumulator.exceeds_inline_budget(0)); + + // 1,000 distinct 100-byte values: exact, and counted by their bytes. + accumulator.update(&batch_of(0..1000)); + let exact = 1000 * (100 + TRACKED_VALUE_OVERHEAD_BYTES); + assert_eq!(accumulator.retained_bytes(), exact); + assert!(!accumulator.is_approximate()); + assert!(!accumulator.exceeds_inline_budget(MAX_INLINE_FIELD_STATS_BYTES)); + assert!(accumulator.exceeds_inline_budget(exact - 1)); + // Repeated values add no bytes. + accumulator.update(&batch_of(0..1000)); + assert_eq!(accumulator.retained_bytes(), exact); + + // Past the 1,024 tracked values the counts are approximate, and the + // tracked bytes stay bounded by the tracked-value limit. + accumulator.update(&batch_of(1000..5000)); + assert!(accumulator.is_approximate()); + assert!(accumulator.exceeds_inline_budget(MAX_INLINE_FIELD_STATS_BYTES)); + assert_eq!( + accumulator.retained_bytes(), + 1024 * (100 + TRACKED_VALUE_OVERHEAD_BYTES) + ); + } + + #[test] + fn staged_cache_skips_statistics_over_the_inline_budget() { + use super::{ + MAX_INLINE_FIELD_STATS_BYTES, cache_staged_field_stats, field_stats_bytes, + take_staged_field_stats, + }; + + let stats_of = |value_bytes: usize| { + vec![FieldStat { + field_name: "message".to_string(), + count: 1, + distinct_count: 1, + distinct_stats: vec![DistinctStat { + distinct_value: "m".repeat(value_bytes), + count: 1, + }], + }] + }; + let path = std::path::PathBuf::from(format!( + "/nonexistent/budget.{}.parquet", + uuid::Uuid::new_v4() + )); + let small = stats_of(16); + assert!(field_stats_bytes(&small) < 1024); + cache_staged_field_stats(&path, 5, small.clone()); + assert_eq!(take_staged_field_stats(&path, 5), Some(small.clone())); + + // An oversized entry is not cached, and does not keep an older one. + cache_staged_field_stats(&path, 5, small); + let large = stats_of(MAX_INLINE_FIELD_STATS_BYTES + 1); + assert!(field_stats_bytes(&large) > MAX_INLINE_FIELD_STATS_BYTES); + cache_staged_field_stats(&path, 5, large); + assert_eq!(take_staged_field_stats(&path, 5), None); + } + #[test] fn extract_datetime_from_parquet_path_regex_cached() { use super::extract_datetime_from_parquet_path_regex; @@ -2790,6 +3426,631 @@ mod tests { .is_err() ); } + + fn legacy_compute_field_stats_from_batches( + batches: &[RecordBatch], + stream_name: &str, + schema: &Schema, + max_field_statistics: usize, + ) -> Vec { + use super::{ + MIN_TRACKED_DISTINCT_VALUES_PER_FIELD, legacy_collect_batch_field_counts_parallel, + merge_field_counts, + }; + + let field_names: Vec = schema + .fields() + .iter() + .map(|field| field.name().clone()) + .collect(); + let mut field_counts: HashMap = field_names + .iter() + .map(|field_name| { + ( + field_name.clone(), + FieldCountState::new( + stream_name.to_string(), + field_name.clone(), + max_field_statistics, + ), + ) + }) + .collect(); + + for batch in batches { + if batch.num_rows() == 0 { + continue; + } + for offset in (0..batch.num_rows()).step_by(MIN_TRACKED_DISTINCT_VALUES_PER_FIELD) { + let chunk = batch.slice( + offset, + (batch.num_rows() - offset).min(MIN_TRACKED_DISTINCT_VALUES_PER_FIELD), + ); + let batch_field_counts = legacy_collect_batch_field_counts_parallel( + stream_name, + &chunk, + &field_names, + max_field_statistics, + ); + for (field_name, batch_field_count) in batch_field_counts { + merge_field_counts(&mut field_counts, &field_name, batch_field_count); + } + } + } + + field_names + .into_iter() + .filter_map(|field_name| { + let state = field_counts.remove(&field_name)?; + if state.total_count == 0 { + return None; + } + Some(FieldStat { + field_name, + count: state.total_count, + distinct_count: state.distinct_count(), + distinct_stats: state.into_distinct_stats(max_field_statistics), + }) + }) + .collect() + } + + #[test] + fn accumulator_matches_legacy_high_cardinality_columns() { + use super::compute_field_stats_from_batches; + + let schema = Arc::new(Schema::new(vec![ + Field::new("utf8_unique", DataType::Utf8, true), + Field::new("utf8_view_unique", DataType::Utf8View, true), + Field::new("int64_unique", DataType::Int64, true), + Field::new("float64_unique", DataType::Float64, true), + Field::new( + "ts_unique", + DataType::Timestamp(TimeUnit::Millisecond, None), + true, + ), + Field::new("utf8_sparse_nulls", DataType::Utf8, true), + Field::new("int64_sparse_nulls", DataType::Int64, true), + ])); + + let make_batch = |start: usize, len: usize| -> RecordBatch { + let utf8_unique = + StringArray::from_iter_values((start..start + len).map(|i| format!("req-{i:06}"))); + let utf8_view_unique = StringViewArray::from_iter_values( + (start..start + len).map(|i| format!("span-view-{i:06}-payload")), + ); + let int64_unique = Int64Array::from_iter_values((start..start + len).map(|i| i as i64)); + let float64_unique = + Float64Array::from_iter_values((start..start + len).map(|i| i as f64 * 0.125)); + let ts_unique = TimestampMillisecondArray::from_iter_values( + (start..start + len).map(|i| 1_730_000_000_000 + i as i64), + ); + let utf8_sparse_nulls = StringArray::from_iter((start..start + len).map(|i| { + if i % 97 == 0 { + None + } else { + Some(format!("u-{i:06}")) + } + })); + let int64_sparse_nulls = Int64Array::from_iter( + (start..start + len).map(|i| if i % 53 == 0 { None } else { Some(i as i64) }), + ); + + RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(utf8_unique), + Arc::new(utf8_view_unique), + Arc::new(int64_unique), + Arc::new(float64_unique), + Arc::new(ts_unique), + Arc::new(utf8_sparse_nulls), + Arc::new(int64_sparse_nulls), + ], + ) + .unwrap() + }; + + // 12,345 rows (>10,000) split across uneven batches that straddle 1,024-row chunks. + let batches = vec![ + make_batch(0, 3_100), + make_batch(3_100, 4_500), + make_batch(7_600, 4_745), + ]; + + let actual = compute_field_stats_from_batches(&batches, "high_card", &schema, 50); + let expected = legacy_compute_field_stats_from_batches(&batches, "high_card", &schema, 50); + + assert_eq!(actual, expected); + for stat in &actual { + assert_eq!(stat.count, 12_345, "field {}", stat.field_name); + assert!( + stat.distinct_count > 10_000, + "field {} HLL estimate too low: {}", + stat.field_name, + stat.distinct_count + ); + } + } + + #[test] + fn accumulator_matches_legacy_zipfian_and_repeated_tail_across_chunk_boundaries() { + use super::compute_field_stats_from_batches; + + let schema = Arc::new(Schema::new(vec![ + Field::new("utf8_tail_evict", DataType::Utf8, true), + Field::new("utf8_view_zipf", DataType::Utf8View, true), + Field::new("int64_tail_evict", DataType::Int64, true), + Field::new("float64_tail_evict", DataType::Float64, true), + Field::new( + "ts_tail_evict", + DataType::Timestamp(TimeUnit::Millisecond, None), + true, + ), + ])); + + // Build 5,120 rows (5 full 1,024-row chunks) plus a 333-row partial chunk: + // - Chunk 0 fills all 1,024 tracked slots (counts of 1, plus a couple repeated keys). + // - Chunks 1..5 start each 1,024-row chunk with 40 unique values (past any 32-row + // prefix probe) followed by repeated tail bursts that exceed `min_count_hint` and + // force evictions and lexicographical tie-breaking! + let total_rows = 5 * 1024 + 333; + let mut s_vals: Vec> = Vec::with_capacity(total_rows); + let mut sv_vals: Vec> = Vec::with_capacity(total_rows); + let mut i_vals: Vec> = Vec::with_capacity(total_rows); + let mut f_vals: Vec> = Vec::with_capacity(total_rows); + let mut ts_vals: Vec> = Vec::with_capacity(total_rows); + + for row in 0..total_rows { + let chunk = row / 1024; + let pos = row % 1024; + + if chunk == 0 { + // Leave 12 slots open after chunk 0 (by repeating one value 13 times) + // so chunk 1 exercises the transition-chunk overflow path too. + let id = if pos < 13 { 0 } else { pos }; + s_vals.push(Some(format!("val-{id:05}"))); + i_vals.push(Some(id as i64)); + f_vals.push(Some(id as f64 + 0.25)); + ts_vals.push(Some(1_730_000_000_000 + id as i64 * 1000)); + } else if pos < 45 { + // High-cardinality prefix (>32 unique items). + let id = chunk * 10_000 + pos; + s_vals.push(Some(format!("prefix-{id:06}"))); + i_vals.push(Some(id as i64)); + f_vals.push(Some(id as f64 + 0.5)); + ts_vals.push(Some(1_730_100_000_000 + id as i64 * 1000)); + } else if pos < 95 { + // Repeated unseen tail burst (50 occurrences -> must evict weak entries). + let burst_id = 900_000 + chunk; + s_vals.push(Some(format!("burst-{burst_id}"))); + i_vals.push(Some(burst_id as i64)); + f_vals.push(Some(burst_id as f64)); + ts_vals.push(Some(1_730_200_000_000 + burst_id as i64 * 1000)); + } else if pos < 145 { + // Second repeated unseen burst with identical count (50) to test tie-breaking. + let burst_id = 800_000 + chunk; + s_vals.push(Some(format!("burst-{burst_id}"))); + i_vals.push(Some(burst_id as i64)); + f_vals.push(Some(burst_id as f64)); + ts_vals.push(Some(1_730_200_000_000 + burst_id as i64 * 1000)); + } else if pos < 200 { + // Repeated existing values from chunk 0 (growing counts above initial hint). + let existing = (pos % 10) + 20; + s_vals.push(Some(format!("val-{existing:05}"))); + i_vals.push(Some(existing as i64)); + f_vals.push(Some(existing as f64 + 0.25)); + ts_vals.push(Some(1_730_000_000_000 + existing as i64 * 1000)); + } else { + // Mix of unique noise and nulls. + if pos % 73 == 0 { + s_vals.push(None); + i_vals.push(None); + f_vals.push(None); + ts_vals.push(None); + } else { + let id = chunk * 10_000 + pos; + s_vals.push(Some(format!("noise-{id:06}"))); + i_vals.push(Some(id as i64)); + f_vals.push(Some(id as f64 + 0.75)); + ts_vals.push(Some(1_730_300_000_000 + id as i64 * 1000)); + } + } + + // Zipfian-like distribution across 2,500 distinct values for Utf8View. + let zipf_bucket = if row % 5 == 0 { + row % 16 + } else if row % 3 == 0 { + 16 + (row % 200) + } else { + 216 + (row % 2_300) + }; + sv_vals.push(if row % 89 == 0 { + None + } else { + Some(format!("zipf-{zipf_bucket:04}")) + }); + } + + let full_batch = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(StringArray::from(s_vals)), + Arc::new(StringViewArray::from(sv_vals)), + Arc::new(Int64Array::from(i_vals)), + Arc::new(Float64Array::from(f_vals)), + Arc::new(TimestampMillisecondArray::from(ts_vals)), + ], + ) + .unwrap(); + + // Test both single large batch and multi-batch splits that align/misalign with 1024. + for batches in [ + vec![full_batch.clone()], + vec![ + full_batch.slice(0, 2048), + full_batch.slice(2048, 1500), + full_batch.slice(3548, total_rows - 3548), + ], + ] { + let actual = compute_field_stats_from_batches(&batches, "zipf_stream", &schema, 30); + let expected = + legacy_compute_field_stats_from_batches(&batches, "zipf_stream", &schema, 30); + assert_eq!(actual, expected); + + // Confirm repeated tail bursts actually evicted weak entries and landed in top stats. + let int_stat = actual + .iter() + .find(|s| s.field_name == "int64_tail_evict") + .unwrap(); + assert!( + int_stat + .distinct_stats + .iter() + .any(|d| d.distinct_value == "900001" && d.count == 50), + "expected repeated tail burst 900001 with count 50 in {:?}", + int_stat.distinct_stats + ); + } + } + + #[test] + fn accumulator_handles_nulls_nans_signed_zero_empty_batches_and_wide_schemas() { + use super::{FieldStatsAccumulator, compute_field_stats_from_batches}; + use arrow_array::{Float32Array, NullArray}; + + // 1. NaN bit patterns, -0.0 vs +0.0, invalid timestamps, and all-null columns. + let edge_schema = Arc::new(Schema::new(vec![ + Field::new("f64_edge", DataType::Float64, true), + Field::new("f32_edge", DataType::Float32, true), + Field::new( + "ts_edge", + DataType::Timestamp(TimeUnit::Millisecond, None), + true, + ), + Field::new("all_null", DataType::Null, true), + ])); + + // Include distinct NaN bit patterns and out-of-range timestamps, crossing 1,024 cap + // so canonicalization is exercised both below and above capacity. + let n = 2_200; + let f64_vals: Vec> = (0..n) + .map(|i| match i { + 0..=1050 => Some(i as f64 + 10.0), + 1051..=1060 => Some(0.0), + 1061..=1075 => Some(-0.0), + 1076..=1085 => Some(f64::NAN), + 1086..=1095 => Some(-f64::NAN), + 1096..=1105 => Some(f64::from_bits(0x7ff8_0000_0000_0001)), + 1106..=1115 => Some(f64::from_bits(0xfff8_0000_0000_0002)), + 1116..=1120 => None, + _ => Some((i % 7) as f64), + }) + .collect(); + let f32_vals: Vec> = (0..n) + .map(|i| match i { + 0..=1050 => Some(i as f32 + 10.0), + 1051..=1060 => Some(0.0_f32), + 1061..=1075 => Some(-0.0_f32), + 1076..=1085 => Some(f32::NAN), + 1086..=1095 => Some(-f32::NAN), + 1096..=1105 => Some(f32::from_bits(0x7fc0_0001)), + 1106..=1110 => None, + _ => Some((i % 5) as f32), + }) + .collect(); + let ts_vals: Vec> = (0..n) + .map(|i| match i { + 0..=1050 => Some(1_730_000_000_000 + i as i64), + 1051..=1065 => Some(i64::MIN), + 1066..=1080 => Some(i64::MAX), + 1081..=1090 => Some(i64::MIN + 1), + 1091..=1100 => None, + _ => Some(0), + }) + .collect(); + + let empty_edge = RecordBatch::new_empty(edge_schema.clone()); + let edge_batch = RecordBatch::try_new( + edge_schema.clone(), + vec![ + Arc::new(Float64Array::from(f64_vals)), + Arc::new(Float32Array::from(f32_vals)), + Arc::new(TimestampMillisecondArray::from(ts_vals)), + Arc::new(NullArray::new(n)), + ], + ) + .unwrap(); + + let batches = vec![empty_edge.clone(), edge_batch, empty_edge.clone()]; + let actual = compute_field_stats_from_batches(&batches, "edges", &edge_schema, 50); + let expected = legacy_compute_field_stats_from_batches(&batches, "edges", &edge_schema, 50); + assert_eq!(actual, expected); + + // Verify -0 and 0 remain distinct and all NaN bit patterns aggregated into "NaN". + let f64_stat = actual.iter().find(|s| s.field_name == "f64_edge").unwrap(); + assert!( + f64_stat + .distinct_stats + .iter() + .any(|d| d.distinct_value == "-0" && d.count == 15) + ); + assert!( + f64_stat + .distinct_stats + .iter() + .any(|d| d.distinct_value == "NaN" && d.count == 40) + ); + let ts_stat = actual.iter().find(|s| s.field_name == "ts_edge").unwrap(); + assert!( + ts_stat + .distinct_stats + .iter() + .any(|d| d.distinct_value == "INVALID_TIMESTAMP" && d.count == 40) + ); + + // All-empty batches yield no field stats. + assert!( + compute_field_stats_from_batches(&[empty_edge], "edges", &edge_schema, 50).is_empty() + ); + + // 2. Wide schema (128 columns) with partial batches where some columns are absent. + let wide_fields: Vec = (0..128) + .map(|i| { + let dt = match i % 4 { + 0 => DataType::Utf8, + 1 => DataType::Utf8View, + 2 => DataType::Int64, + _ => DataType::Float64, + }; + Field::new(format!("col_{i:03}"), dt, true) + }) + .collect(); + let wide_schema = Arc::new(Schema::new(wide_fields)); + let rows = 2_300; + let wide_cols: Vec> = (0..128) + .map(|c| -> Arc { + match c % 4 { + 0 => Arc::new(StringArray::from_iter_values( + (0..rows).map(|r| format!("c{c}-{}", r % (10 + c * 15))), + )), + 1 => Arc::new(StringViewArray::from_iter_values( + (0..rows).map(|r| format!("v{c}-{}", r % (5 + c * 11))), + )), + 2 => Arc::new(Int64Array::from_iter_values( + (0..rows).map(|r| (r % (7 + c * 13)) as i64), + )), + _ => Arc::new(Float64Array::from_iter_values( + (0..rows).map(|r| (r % (9 + c * 17)) as f64 * 0.5), + )), + } + }) + .collect(); + let wide_batch = RecordBatch::try_new(wide_schema.clone(), wide_cols).unwrap(); + + let mut acc = FieldStatsAccumulator::new("wide", &wide_schema, 20); + acc.update(&wide_batch); + let wide_actual = acc.finish(); + let wide_expected = + legacy_compute_field_stats_from_batches(&[wide_batch], "wide", &wide_schema, 20); + assert_eq!(wide_actual, wide_expected); + assert_eq!(wide_actual.len(), 128); + } + + #[test] + fn field_stats_thread_pool_bounds_and_nested_pool_reuse() { + use super::{ + FIELD_STATS_RAYON_POOL, FIELD_STATS_THREADS_VAR, compute_field_stats_from_batches, + field_stats_threads, run_in_field_stats_pool, + }; + use rayon::ThreadPoolBuilder; + use rayon::prelude::*; + + // Default `(cpus / 2).clamp(2, 8)` across core counts. + assert_eq!(field_stats_threads(None, 1), 2); + assert_eq!(field_stats_threads(None, 2), 2); + assert_eq!(field_stats_threads(None, 4), 2); + assert_eq!(field_stats_threads(None, 6), 3); + assert_eq!(field_stats_threads(None, 8), 4); + assert_eq!(field_stats_threads(None, 12), 6); + assert_eq!(field_stats_threads(None, 16), 8); + assert_eq!(field_stats_threads(None, 64), 8); + + // Positive `FIELD_STATS_THREADS` overrides work; invalid/zero fall back to default. + assert_eq!(field_stats_threads(Some("1"), 16), 1); + assert_eq!(field_stats_threads(Some(" 5 "), 16), 5); + assert_eq!(field_stats_threads(Some("12"), 4), 12); + assert_eq!(field_stats_threads(Some("0"), 16), 8); + assert_eq!(field_stats_threads(Some("-2"), 8), 4); + assert_eq!(field_stats_threads(Some(""), 8), 4); + assert_eq!(field_stats_threads(Some("many"), 4), 2); + + // Live pool matches configured bound. + assert_eq!( + FIELD_STATS_RAYON_POOL.current_num_threads(), + field_stats_threads( + std::env::var(FIELD_STATS_THREADS_VAR).ok().as_deref(), + num_cpus::get() + ) + ); + + // Outside Rayon, `run_in_field_stats_pool` runs on `field-stats-*` threads. + let outside_names: Vec = run_in_field_stats_pool(|| { + (0..32) + .into_par_iter() + .map(|_| std::thread::current().name().unwrap_or_default().to_owned()) + .collect() + }); + assert!( + outside_names + .iter() + .all(|name| name.starts_with("field-stats-")), + "{outside_names:?}" + ); + + // Inside a caller's bounded Rayon pool (like `LOG_CONVERSION_THREADPOOL`), + // `run_in_field_stats_pool` reuses that pool directly without jumping pools or deadlocking. + let caller_pool = ThreadPoolBuilder::new() + .num_threads(2) + .thread_name(|idx| format!("caller-pool-{idx}")) + .build() + .unwrap(); + let nested_names: Vec = caller_pool.install(|| { + run_in_field_stats_pool(|| { + (0..32) + .into_par_iter() + .map(|_| std::thread::current().name().unwrap_or_default().to_owned()) + .collect() + }) + }); + assert!( + nested_names + .iter() + .all(|name| name.starts_with("caller-pool-")), + "{nested_names:?}" + ); + + // Even inside a 1-thread Rayon pool, `FieldStatsAccumulator` completes without deadlock + // and matches the legacy implementation. + let single_thread_pool = ThreadPoolBuilder::new().num_threads(1).build().unwrap(); + let schema = Arc::new(Schema::new(vec![ + Field::new("k", DataType::Utf8, true), + Field::new("n", DataType::Int64, true), + ])); + let batch = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(StringArray::from_iter_values( + (0..2_500).map(|i| format!("k-{}", i % 1_200)), + )), + Arc::new(Int64Array::from_iter_values((0..2_500).map(|i| i as i64))), + ], + ) + .unwrap(); + let nested_stats = single_thread_pool.install(|| { + compute_field_stats_from_batches(std::slice::from_ref(&batch), "nested", &schema, 25) + }); + let legacy_stats = legacy_compute_field_stats_from_batches(&[batch], "nested", &schema, 25); + assert_eq!(nested_stats, legacy_stats); + } + + proptest::proptest! { + #![proptest_config(proptest::prelude::ProptestConfig::with_cases(16))] + + #[test] + fn proptest_accumulator_matches_legacy_across_random_batches( + seed in proptest::prelude::any::(), + batch_lens in proptest::collection::vec(0usize..=2_200, 1..=4), + cardinality in proptest::sample::select(vec![5usize, 1020, 1024, 1500, 3000]), + null_mod in proptest::sample::select(vec![0usize, 17, 64]), + ) { + use super::compute_field_stats_from_batches; + + let schema = Arc::new(Schema::new(vec![ + Field::new("s", DataType::Utf8, true), + Field::new("sv", DataType::Utf8View, true), + Field::new("i", DataType::Int64, true), + Field::new("f", DataType::Float64, true), + Field::new("ts", DataType::Timestamp(TimeUnit::Millisecond, None), true), + ])); + + let mut state = seed.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut next_u64 = || { + state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + state + }; + + let mut batches = Vec::with_capacity(batch_lens.len()); + for len in batch_lens { + if len == 0 { + batches.push(RecordBatch::new_empty(schema.clone())); + continue; + } + let mut s_col = Vec::with_capacity(len); + let mut sv_col = Vec::with_capacity(len); + let mut i_col = Vec::with_capacity(len); + let mut f_col = Vec::with_capacity(len); + let mut ts_col = Vec::with_capacity(len); + + // Pick a per-batch burst key to exercise repeated tails and evictions. + let burst_key = (next_u64() as usize) % (cardinality * 2 + 1); + for row in 0..len { + let r = next_u64() as usize; + let is_null = null_mod > 0 && (r % null_mod == 0); + let key = if row % 37 == 0 { + burst_key + } else { + r % cardinality + }; + if is_null { + s_col.push(None); + sv_col.push(None); + i_col.push(None); + f_col.push(None); + ts_col.push(None); + } else { + s_col.push(Some(format!("v-{key}"))); + sv_col.push(Some(format!("vw-{key}"))); + i_col.push(Some(key as i64 - 500)); + let fv = match key % 25 { + 0 => 0.0, + 1 => -0.0, + 2 => f64::NAN, + 3 => -f64::NAN, + _ => key as f64 * 0.25, + }; + f_col.push(Some(fv)); + let tsv = if key % 31 == 0 { + i64::MIN + } else if key % 31 == 1 { + i64::MAX + } else { + 1_730_000_000_000 + key as i64 * 100 + }; + ts_col.push(Some(tsv)); + } + } + + batches.push( + RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(StringArray::from(s_col)), + Arc::new(StringViewArray::from(sv_col)), + Arc::new(Int64Array::from(i_col)), + Arc::new(Float64Array::from(f_col)), + Arc::new(TimestampMillisecondArray::from(ts_col)), + ], + ) + .unwrap(), + ); + } + + let actual = compute_field_stats_from_batches(&batches, "prop", &schema, 25); + let expected = legacy_compute_field_stats_from_batches(&batches, "prop", &schema, 25); + proptest::prop_assert_eq!(actual, expected); + } + } } #[cfg(test)] diff --git a/src/storage/localfs.rs b/src/storage/localfs.rs index 8fb9a3193..612fce67d 100644 --- a/src/storage/localfs.rs +++ b/src/storage/localfs.rs @@ -247,6 +247,80 @@ impl LocalFS { .await .map_err(ObjectStorageError::from)? } + + async fn upload_multipart_with_link( + &self, + key: &RelativePath, + path: &Path, + tenant_id: &Option, + link: L, + ) -> Result<(), ObjectStorageError> + where + L: FnOnce(&Path, &Path) -> std::io::Result<()> + Send + 'static, + { + let mut file = 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(()); + } + Some(source) => source, + } + } else 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 => { + record_local_put_metrics(tenant_id); + return Ok(()); + } + Some(source) => source, + } + } else { + OpenOptions::new().read(true).open(path).await? + }; + let mut data = Vec::new(); + file.read_to_end(&mut data).await?; + self.put_object(key, data.into(), tenant_id).await + } +} + +fn is_immutable_parquet_key(key: &RelativePath) -> bool { + !is_dashboard_metadata(key) + && key + .extension() + .is_some_and(|ext| ext.eq_ignore_ascii_case("parquet")) +} + +fn record_local_put_metrics(tenant_id: &Option) { + let tenant_str = tenant_id.as_deref().unwrap_or(DEFAULT_TENANT); + increment_files_scanned_in_object_store_calls_by_date( + "PUT", + 1, + &Utc::now().date_naive().to_string(), + tenant_str, + ); + increment_object_store_calls_by_date("PUT", &Utc::now().date_naive().to_string(), tenant_str); } #[async_trait] @@ -280,31 +354,10 @@ impl ObjectStorage for LocalFS { path: &Path, tenant_id: &Option, ) -> Result<(), ObjectStorageError> { - let mut file = OpenOptions::new().read(true).open(path).await?; - if !is_dashboard_metadata(key) { - let to_path = self.path_in_root(key); - match copy_into_new_file(file, &to_path).await? { - None => { - let tenant_str = tenant_id.as_deref().unwrap_or(DEFAULT_TENANT); - increment_files_scanned_in_object_store_calls_by_date( - "PUT", - 1, - &Utc::now().date_naive().to_string(), - tenant_str, - ); - increment_object_store_calls_by_date( - "PUT", - &Utc::now().date_naive().to_string(), - tenant_str, - ); - return Ok(()); - } - Some(source) => file = source, - } - } - let mut data = Vec::new(); - file.read_to_end(&mut data).await?; - self.put_object(key, data.into(), tenant_id).await + self.upload_multipart_with_link(key, path, tenant_id, |src, dst| { + std::fs::hard_link(src, dst) + }) + .await } async fn get_buffered_reader( @@ -676,6 +729,11 @@ impl ObjectStorage for LocalFS { }) .await .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)) + .await + .map_err(ObjectStorageError::from)? } else { let path = self.path_in_root(path); if let Some(parent) = path.parent() { @@ -1239,6 +1297,27 @@ async fn dir_name(entry: DirEntry) -> Result, ObjectStorageError> // Reserved for operation-owned copies. No object suffix (in particular .parquet) // is retained, so query file discovery cannot mistake these for published data. const UPLOAD_TEMP_PREFIX: &str = ".parseable-upload-"; +const UPLOAD_COPY_BUFFER_SIZE: usize = 256 * 1024; + +fn copy_file_buffered( + 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]; + let mut total = 0u64; + loop { + let read = match source.read(&mut buf) { + Ok(0) => return Ok(total), + Ok(read) => read, + Err(err) if err.kind() == std::io::ErrorKind::Interrupted => continue, + Err(err) => return Err(err), + }; + dest.write_all(&buf[..read])?; + total += read as u64; + } +} /// Streams a regular source into an operation-private, same-directory file and /// publishes it with a no-replace hard link. Only the private name is cleaned up. @@ -1256,7 +1335,7 @@ async fn copy_into_new_file( copy_into_new_file_with( source, to_path, - std::io::copy, + copy_file_buffered, |temp, final_path| std::fs::hard_link(temp, final_path), |_, _| {}, ) @@ -1317,8 +1396,11 @@ where // Drop closes and removes only this invocation's private name. return Err(err); } + // Persist copied data before publishing so cross-device fallback has + // the same crash durability as the hard-link and atomic-put paths. + temp.file.as_mut().expect("open copy file").sync_all()?; // Close before linking/cleanup, including on platforms with restrictive - // file-sharing rules. std::io::copy writes directly to an unbuffered File. + // file-sharing rules. drop(temp.file.take()); hook(UploadCopyStage::BeforePublish, &temp.path); if publish(&temp.path, &to_path).is_err() { @@ -1328,6 +1410,7 @@ where source.seek(SeekFrom::Start(position))?; return Ok(Some(source)); } + let _ = sync_upload_parent_directory(parent); Ok(None) }) .await??; @@ -1395,6 +1478,202 @@ impl Drop for UploadTemp { // END localfs-copy helper +enum HardLinkResult { + Linked, + UseCopyFallback(fs::File), + UseBufferedFallback(fs::File), +} + +enum HardLinkBlockingOutcome { + Linked, + UseCopyFallback(std::fs::File), + UseBufferedFallback(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`. +async fn hard_link_into_new_file_with( + src_path: &Path, + to_path: &Path, + link: L, +) -> Result +where + L: FnOnce(&Path, &Path) -> std::io::Result<()> + Send + 'static, +{ + 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)); + }; + if !src_fd_meta.is_file() { + return Ok(HardLinkBlockingOutcome::UseBufferedFallback(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). + match std::fs::symlink_metadata(&to_path) { + Err(err) if err.kind() == std::io::ErrorKind::NotFound => {} + #[cfg(unix)] + Ok(dst_meta) + 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)?; + } + drop(source); + return Ok(HardLinkBlockingOutcome::Linked); + } + _ => return Ok(HardLinkBlockingOutcome::UseBufferedFallback(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)); + }; + if !src_path_meta.file_type().is_file() { + return Ok(HardLinkBlockingOutcome::UseCopyFallback(source)); + } + #[cfg(unix)] + if !same_unix_inode(&src_fd_meta, &src_path_meta) { + return Ok(HardLinkBlockingOutcome::UseCopyFallback(source)); + } + let Some(parent) = to_path.parent().filter(|p| !p.as_os_str().is_empty()) else { + return Ok(HardLinkBlockingOutcome::UseBufferedFallback(source)); + }; + if std::fs::create_dir_all(parent).is_err() { + // Preserve source-read-error priority over parent/setup errors. + return Ok(HardLinkBlockingOutcome::UseBufferedFallback(source)); + } + match link(&src_path, &to_path) { + Ok(()) => { + drop(source); + sync_upload_parent_directory(parent)?; + Ok(HardLinkBlockingOutcome::Linked) + } + Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => { + #[cfg(unix)] + if let Ok(dst_meta) = std::fs::symlink_metadata(&to_path) + && dst_meta.file_type().is_file() + && same_unix_inode(&src_fd_meta, &dst_meta) + { + drop(source); + sync_upload_parent_directory(parent)?; + return Ok(HardLinkBlockingOutcome::Linked); + } + Ok(HardLinkBlockingOutcome::UseBufferedFallback(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)) + } + }) +} + +#[cfg(unix)] +fn same_unix_inode(a: &std::fs::Metadata, b: &std::fs::Metadata) -> bool { + use std::os::unix::fs::MetadataExt; + 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. +async fn atomic_replace_parquet_from_file( + source: fs::File, + to_path: &Path, +) -> Result, ObjectStorageError> { + let mut source = source.into_std().await; + 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)); + }; + { + let dst = temp.file.as_mut().expect("open temp file"); + copy_file_buffered(&mut source, dst)?; + dst.sync_all()?; + } + drop(temp.file.take()); + std::fs::rename(&temp.path, &to_path)?; + sync_upload_parent_directory(parent)?; + Ok(None) + }) + .await??; + Ok(fallback.map(fs::File::from_std)) +} + +/// 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> { + use std::io::Write; + let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) else { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + "parquet object path has no parent directory", + ) + .into()); + }; + std::fs::create_dir_all(parent)?; + let mut temp = UploadTemp::create(parent, path)?; + { + let file = temp.file.as_mut().expect("open temp file"); + file.write_all(bytes)?; + file.sync_all()?; + } + drop(temp.file.take()); + std::fs::rename(&temp.path, path)?; + sync_upload_parent_directory(parent)?; + Ok(()) +} + +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), + } +} + impl From for ObjectStorageError { fn from(e: fs_extra::error::Error) -> Self { ObjectStorageError::UnhandledError(Box::new(e)) @@ -3220,4 +3499,285 @@ mod upload_multipart_tests { b"not a directory" ); } + + #[tokio::test] + async fn same_fs_upload_hard_links_zero_copy_and_survives_source_unlink() { + let dir = tempfile::tempdir().unwrap(); + let staging = dir.path().join("staging"); + let store = dir.path().join("data"); + std::fs::create_dir_all(&staging).unwrap(); + let source = staging.join("part-0001.parquet"); + let data = pattern(600 * 1024 + 13); + std::fs::write(&source, &data).unwrap(); + #[cfg(unix)] + let src_meta = std::fs::metadata(&source).unwrap(); + + upload(&store, "logs/date=2026-11-30/part-0001.parquet", &source) + .await + .unwrap(); + + let object = store.join("logs/date=2026-11-30/part-0001.parquet"); + assert_eq!(std::fs::read(&object).unwrap(), data); + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + let dst_meta = std::fs::metadata(&object).unwrap(); + assert_eq!(dst_meta.dev(), src_meta.dev()); + assert_eq!(dst_meta.ino(), src_meta.ino()); + assert!(dst_meta.nlink() >= 2); + } + + // Unlinking the staged source must leave the published object intact. + std::fs::remove_file(&source).unwrap(); + assert!(!source.exists()); + assert_eq!(std::fs::read(&object).unwrap(), data); + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + let dst_meta = std::fs::metadata(&object).unwrap(); + assert_eq!(dst_meta.ino(), src_meta.ino()); + assert_eq!(dst_meta.nlink(), 1); + } + assert_no_upload_temps(object.parent().unwrap()); + } + + #[tokio::test] + async fn existing_parquet_destination_is_atomically_replaced_preserving_existing_inode() { + let dir = tempfile::tempdir().unwrap(); + let source = dir.path().join("source.parquet"); + let data = pattern(128 * 1024 + 7); + std::fs::write(&source, &data).unwrap(); + #[cfg(unix)] + let src_ino = { + use std::os::unix::fs::MetadataExt; + std::fs::metadata(&source).unwrap().ino() + }; + + // Case 1: destination already exists before upload starts (e.g. held by a query lease). + let store1 = dir.path().join("store1"); + std::fs::create_dir_all(store1.join("stream")).unwrap(); + let existing = store1.join("stream/existing.parquet"); + std::fs::write(&existing, b"previous object contents").unwrap(); + let leased_fd = std::fs::File::open(&existing).unwrap(); + #[cfg(unix)] + let existing_ino = { + use std::os::unix::fs::MetadataExt; + std::fs::metadata(&existing).unwrap().ino() + }; + + upload(&store1, "stream/existing.parquet", &source) + .await + .unwrap(); + + assert_eq!(std::fs::read(&existing).unwrap(), data); + // Active reader holding an open fd to the prior inode must see unmodified bytes. + { + use std::io::Read; + let mut leased_bytes = Vec::new(); + (&leased_fd).read_to_end(&mut leased_bytes).unwrap(); + assert_eq!(leased_bytes, b"previous object contents"); + } + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + let after_ino = std::fs::metadata(&existing).unwrap().ino(); + assert_ne!(after_ino, existing_ino); + assert_ne!(after_ino, src_ino); + } + + // Case 2: concurrent destination appears right before hard_link (AlreadyExists). + // Replacing the destination must not mutate the hard-linked alias inode. + let store2 = dir.path().join("store2"); + let alias = dir.path().join("alias.parquet"); + std::fs::write(&alias, b"raced destination").unwrap(); + #[cfg(unix)] + let alias_ino = { + use std::os::unix::fs::MetadataExt; + std::fs::metadata(&alias).unwrap().ino() + }; + let raced_alias = alias.clone(); + let storage2 = LocalFS::new(store2.clone()); + storage2 + .upload_multipart_with_link( + RelativePath::new("stream/raced.parquet"), + &source, + &None, + move |src, dst| { + std::fs::hard_link(&raced_alias, dst)?; + // Now hard_link returns AlreadyExists, triggering atomic replacement fallback. + std::fs::hard_link(src, dst) + }, + ) + .await + .unwrap(); + + let raced_object = store2.join("stream/raced.parquet"); + assert_eq!(std::fs::read(&raced_object).unwrap(), data); + assert_eq!(std::fs::read(&alias).unwrap(), b"raced destination"); + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + let after_ino = std::fs::metadata(&raced_object).unwrap().ino(); + assert_ne!(after_ino, alias_ino); + assert_ne!(after_ino, src_ino); + } + assert_no_upload_temps(raced_object.parent().unwrap()); + } + + #[cfg(unix)] + #[tokio::test] + async fn parquet_put_object_does_not_mutate_hard_linked_staging_lease() { + use std::os::unix::fs::MetadataExt; + + let dir = tempfile::tempdir().unwrap(); + let staging = dir.path().join("staging"); + let store = dir.path().join("data"); + std::fs::create_dir_all(&staging).unwrap(); + let staged = staging.join("part-0001.parquet"); + std::fs::write(&staged, b"original parquet bytes").unwrap(); + let staged_ino = std::fs::metadata(&staged).unwrap().ino(); + + // Publish via zero-copy hard_link. + upload(&store, "logs/part-0001.parquet", &staged) + .await + .unwrap(); + let published = store.join("logs/part-0001.parquet"); + assert_eq!(std::fs::metadata(&published).unwrap().ino(), staged_ino); + + // Idempotent retry of the exact same source inode keeps the hard link intact. + upload(&store, "logs/part-0001.parquet", &staged) + .await + .unwrap(); + assert_eq!(std::fs::metadata(&published).unwrap().ino(), staged_ino); + assert_eq!(std::fs::read(&staged).unwrap(), b"original parquet bytes"); + + // A later put_object to the same .parquet key must replace atomically + // without truncating or mutating the staged/leased inode. + let storage = LocalFS::new(store.clone()); + storage + .put_object( + RelativePath::new("logs/part-0001.parquet"), + Bytes::from_static(b"replacement parquet bytes"), + &None, + ) + .await + .unwrap(); + assert_eq!( + std::fs::read(&published).unwrap(), + b"replacement parquet bytes" + ); + assert_eq!(std::fs::read(&staged).unwrap(), b"original parquet bytes"); + assert_ne!(std::fs::metadata(&published).unwrap().ino(), staged_ino); + assert_no_upload_temps(published.parent().unwrap()); + } + + #[cfg(unix)] + #[tokio::test] + async fn non_parquet_upload_bypasses_hard_link() { + use std::os::unix::fs::MetadataExt; + + let dir = tempfile::tempdir().unwrap(); + let source = dir.path().join("manifest.json"); + std::fs::write(&source, br#"{"version":1}"#).unwrap(); + let src_ino = std::fs::metadata(&source).unwrap().ino(); + + let store = dir.path().join("store"); + upload(&store, "logs/manifest.json", &source).await.unwrap(); + + let object = store.join("logs/manifest.json"); + assert_eq!(std::fs::read(&object).unwrap(), br#"{"version":1}"#); + assert_ne!(std::fs::metadata(&object).unwrap().ino(), src_ino); + } + + #[tokio::test] + async fn cross_device_and_failing_hard_link_falls_back_to_copy() { + let error_kinds = [ + std::io::ErrorKind::CrossesDevices, + std::io::ErrorKind::Unsupported, + std::io::ErrorKind::PermissionDenied, + ]; + // Exceed the 256 KiB copy buffer so multi-chunk streaming copy is exercised. + let data = pattern(600 * 1024 + 17); + + for (idx, kind) in error_kinds.into_iter().enumerate() { + let dir = tempfile::tempdir().unwrap(); + let source = dir.path().join(format!("source-{idx}.parquet")); + std::fs::write(&source, &data).unwrap(); + #[cfg(unix)] + let src_ino = { + use std::os::unix::fs::MetadataExt; + std::fs::metadata(&source).unwrap().ino() + }; + + let store = dir.path().join("store"); + let storage = LocalFS::new(store.clone()); + storage + .upload_multipart_with_link( + RelativePath::new("stream/date=2026-11-30/part.parquet"), + &source, + &None, + move |_, _| Err(std::io::Error::from(kind)), + ) + .await + .unwrap(); + + let object = store.join("stream/date=2026-11-30/part.parquet"); + assert_eq!(std::fs::read(&object).unwrap(), data); + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + assert_ne!(std::fs::metadata(&object).unwrap().ino(), src_ino); + } + assert_no_upload_temps(object.parent().unwrap()); + + std::fs::remove_file(&source).unwrap(); + assert_eq!(std::fs::read(&object).unwrap(), data); + } + } + + #[cfg(unix)] + #[tokio::test] + async fn symlink_source_falls_back_to_copy_creating_regular_destination() { + use std::os::unix::fs::MetadataExt; + + let dir = tempfile::tempdir().unwrap(); + let target = dir.path().join("target.parquet"); + let source_link = dir.path().join("source-link.parquet"); + let data = pattern(300 * 1024 + 3); + std::fs::write(&target, &data).unwrap(); + std::os::unix::fs::symlink(&target, &source_link).unwrap(); + + let store = dir.path().join("store"); + upload(&store, "stream/date=x/from-link.parquet", &source_link) + .await + .unwrap(); + + let object = store.join("stream/date=x/from-link.parquet"); + let meta = std::fs::symlink_metadata(&object).unwrap(); + assert!(meta.file_type().is_file()); + assert!(!meta.file_type().is_symlink()); + assert_ne!(meta.ino(), std::fs::metadata(&target).unwrap().ino()); + assert_eq!(std::fs::read(&object).unwrap(), data); + assert_no_upload_temps(object.parent().unwrap()); + } + + #[cfg(unix)] + #[tokio::test] + async fn dashboard_metadata_upload_bypasses_hard_link() { + use std::os::unix::fs::MetadataExt; + + let dir = tempfile::tempdir().unwrap(); + let source = dir.path().join("dashboard.json"); + std::fs::write(&source, br#"{"title":"Test"}"#).unwrap(); + let src_ino = std::fs::metadata(&source).unwrap().ino(); + + let store = dir.path().join("store"); + upload(&store, ".users/owner/dashboards/test.json", &source) + .await + .unwrap(); + + let object = store.join(".users/owner/dashboards/test.json"); + assert_eq!(std::fs::read(&object).unwrap(), br#"{"title":"Test"}"#); + assert_ne!(std::fs::metadata(&object).unwrap().ino(), src_ino); + } } diff --git a/src/utils/arrow/batch_adapter.rs b/src/utils/arrow/batch_adapter.rs index 2d4633dfb..4dc57f6cc 100644 --- a/src/utils/arrow/batch_adapter.rs +++ b/src/utils/arrow/batch_adapter.rs @@ -76,11 +76,17 @@ impl BatchAdapter { pub(crate) fn adapt(&mut self, batch: &RecordBatch) -> Result { let source_schema = batch.schema_ref(); let same_layout = self.last_plan.as_ref().is_some_and(|plan| { - // Arrow Fields is an immutable Arc<[FieldRef]>. Schema clones - // share it, even when their Schema Arcs or metadata differ. + // Arrow Fields is an immutable Arc<[FieldRef]>. Schema clones share + // it directly, and projected IPC batches clone the exact same + // FieldRef Arcs into a freshly allocated Fields slice. let previous = plan.source_schema.fields(); let current = source_schema.fields(); - previous.len() == current.len() && previous.as_ptr() == current.as_ptr() + previous.len() == current.len() + && (previous.as_ptr() == current.as_ptr() + || previous + .iter() + .zip(current.iter()) + .all(|(a, b)| Arc::ptr_eq(a, b))) }); if !same_layout { #[cfg(test)] diff --git a/src/utils/arrow/mod.rs b/src/utils/arrow/mod.rs index 3e5366b7c..6fd3a149e 100644 --- a/src/utils/arrow/mod.rs +++ b/src/utils/arrow/mod.rs @@ -19,12 +19,14 @@ use std::{collections::HashMap, sync::Arc}; -use arrow::compute::{CastOptions, cast_with_options, take, take_record_batch}; +use arrow::compute::{CastOptions, cast_with_options, take}; use arrow_array::{ - Array, ArrayRef, RecordBatch, StringArray, TimestampMillisecondArray, UInt32Array, UInt64Array, + Array, ArrayRef, RecordBatch, RecordBatchOptions, StringArray, TimestampMillisecondArray, + UInt32Array, UInt64Array, }; use arrow_schema::{ArrowError, DataType, Field, Schema, TimeUnit}; use chrono::{DateTime, Utc}; +use rayon::iter::{IntoParallelRefIterator, ParallelIterator}; pub mod batch_adapter; pub mod flight; @@ -226,9 +228,58 @@ fn custom_field_value_as(value: &str, data_type: &DataType, rows: usize) -> Opti take(&one, &UInt32Array::from(vec![0_u32; rows]), None).ok() } +/// Fewest columns for which `reverse` takes the columns in parallel. +const PARALLEL_REVERSE_MIN_COLUMNS: usize = 4; +/// Fewest rows for which `reverse` takes the columns in parallel. Below this +/// a column is reversed faster than a task for it is scheduled. +const PARALLEL_REVERSE_MIN_ROWS: usize = 256; + +/// Returns `rb` with its rows in the opposite order. +/// +/// The columns of a batch with enough columns and rows are reversed in +/// parallel, but only on a thread that already belongs to a Rayon pool, and +/// then on that pool. A caller outside any pool gets a sequential reversal: +/// this function never moves work onto the global Rayon pool. pub fn reverse(rb: &RecordBatch) -> RecordBatch { - let indices = UInt64Array::from_iter_values((0..rb.num_rows()).rev().map(|x| x as u64)); - take_record_batch(rb, &indices).unwrap() + reverse_with(rb, |column, indices| take(column, indices, None)) +} + +/// `reverse`, with the kernel applied to each column given by the caller. +fn reverse_with( + rb: &RecordBatch, + take_column: impl Fn(&ArrayRef, &dyn Array) -> Result + Sync, +) -> RecordBatch { + let rows = rb.num_rows(); + // Nothing to reorder; the columns are shared, not copied. + if rows <= 1 || rb.num_columns() == 0 { + return rb.clone(); + } + // Arrow's take kernels are fastest with 32-bit indices; a batch too long + // for them is not expected, and uses 64-bit ones. + let indices: ArrayRef = match u32::try_from(rows) { + Ok(rows) => Arc::new(UInt32Array::from_iter_values((0..rows).rev())), + Err(_) => Arc::new(UInt64Array::from_iter_values((0..rows as u64).rev())), + }; + let parallel = rb.num_columns() >= PARALLEL_REVERSE_MIN_COLUMNS + && rows >= PARALLEL_REVERSE_MIN_ROWS + && rayon::current_thread_index().is_some(); + let columns: Result, ArrowError> = if parallel { + rb.columns() + .par_iter() + .map(|column| take_column(column, indices.as_ref())) + .collect() + } else { + rb.columns() + .iter() + .map(|column| take_column(column, indices.as_ref())) + .collect() + }; + RecordBatch::try_new_with_options( + rb.schema(), + columns.unwrap(), + &RecordBatchOptions::new().with_row_count(Some(rows)), + ) + .unwrap() } #[cfg(test)] @@ -278,4 +329,143 @@ mod tests { assert_eq!(array.len(), 0); assert!(array.is_empty()); } + + fn reverse_fixture(rows: usize, columns: usize) -> RecordBatch { + let fields = (0..columns) + .map(|column| match column % 3 { + 0 => Field::new(format!("c{column}"), DataType::Int64, true), + 1 => Field::new(format!("c{column}"), DataType::Utf8, true), + _ => Field::new( + format!("c{column}"), + DataType::Timestamp(TimeUnit::Millisecond, None), + false, + ), + }) + .collect::>(); + let arrays = (0..columns) + .map(|column| match column % 3 { + 0 => { + Arc::new(arrow_array::Int64Array::from_iter((0..rows).map(|row| { + (row % 7 != 0).then_some((row * (column + 1)) as i64) + }))) as ArrayRef + } + 1 => { + Arc::new(StringArray::from_iter((0..rows).map(|row| { + (row % 5 != 0).then(|| format!("value-{column}-{row}")) + }))) as ArrayRef + } + _ => Arc::new(TimestampMillisecondArray::from_iter_values( + (0..rows).map(|row| (row + column) as i64), + )) as ArrayRef, + }) + .collect::>(); + RecordBatch::try_new(Arc::new(Schema::new(fields)), arrays).unwrap() + } + + /// The former implementation, kept as the reference result. + fn reverse_reference(rb: &RecordBatch) -> RecordBatch { + let indices = UInt64Array::from_iter_values((0..rb.num_rows()).rev().map(|x| x as u64)); + arrow::compute::take_record_batch(rb, &indices).unwrap() + } + + #[test] + fn reverse_matches_reference_for_every_shape() { + for (rows, columns) in [ + (0, 3), + (1, 3), + (2, 1), + (255, 8), + (256, 3), + (256, 4), + (1000, 12), + ] { + let batch = reverse_fixture(rows, columns); + let reversed = reverse(&batch); + assert_eq!(reversed, reverse_reference(&batch), "{rows}x{columns}"); + assert_eq!(reversed.schema(), batch.schema()); + // Reversing twice is the identity. + assert_eq!(reverse(&reversed), batch, "{rows}x{columns}"); + } + // A slice is reversed within its own bounds. + let sliced = reverse_fixture(1000, 6).slice(100, 300); + assert_eq!(reverse(&sliced), reverse_reference(&sliced)); + } + + #[test] + fn reverse_keeps_row_count_without_columns() { + let batch = RecordBatch::try_new_with_options( + Arc::new(Schema::empty()), + vec![], + &RecordBatchOptions::new().with_row_count(Some(5)), + ) + .unwrap(); + assert_eq!(reverse(&batch).num_rows(), 5); + } + + #[test] + fn reverse_stays_on_the_pool_of_its_caller() { + let pool = rayon::ThreadPoolBuilder::new() + .num_threads(4) + .thread_name(|index| format!("reverse-test-{index}")) + .build() + .unwrap(); + let threads = std::sync::Mutex::new(Vec::new()); + let recording_take = |column: &ArrayRef, indices: &dyn Array| { + threads.lock().unwrap().push(( + std::thread::current().id(), + std::thread::current().name().unwrap_or_default().to_owned(), + )); + // Long enough for the other workers to pick columns up. + std::thread::sleep(std::time::Duration::from_millis(2)); + take(column, indices, None) + }; + let batch = reverse_fixture(4096, 16); + let expected = reverse_reference(&batch); + + // Outside any pool every column is reversed on the caller's thread. + assert!(rayon::current_thread_index().is_none()); + assert_eq!(reverse_with(&batch, recording_take), expected); + let sequential = std::mem::take(&mut *threads.lock().unwrap()); + assert_eq!(sequential.len(), 16); + assert!( + sequential + .iter() + .all(|(id, _)| *id == std::thread::current().id()) + ); + + // Inside a pool the columns are spread over that pool's threads only. + assert_eq!( + pool.install(|| reverse_with(&batch, recording_take)), + expected + ); + let parallel = std::mem::take(&mut *threads.lock().unwrap()); + assert_eq!(parallel.len(), 16); + assert!( + parallel + .iter() + .all(|(_, name)| name.starts_with("reverse-test-")), + "{parallel:?}" + ); + let distinct = parallel + .iter() + .map(|(id, _)| *id) + .collect::>(); + assert!(distinct.len() > 1, "{parallel:?}"); + + // A batch below either threshold is reversed by the calling worker + // alone, even inside a pool. + for small in [reverse_fixture(4096, 3), reverse_fixture(255, 16)] { + let expected = reverse_reference(&small); + let (reversed, caller) = pool.install(|| { + ( + reverse_with(&small, recording_take), + std::thread::current().id(), + ) + }); + assert_eq!(reversed, expected); + let threads = std::mem::take(&mut *threads.lock().unwrap()); + assert_eq!(threads.len(), small.num_columns()); + assert!(threads.iter().all(|(id, _)| *id == caller), "{threads:?}"); + } + } } diff --git a/src/utils/json/strict.rs b/src/utils/json/strict.rs index 4232e67cb..46c0b2e89 100644 --- a/src/utils/json/strict.rs +++ b/src/utils/json/strict.rs @@ -431,6 +431,238 @@ impl<'de> Deserialize<'de> for StrictValue { } } +/// Receives the rows of a flat JSON batch while `parse_flat_rows` reads it, so +/// that no `serde_json::Value` is built for it. Every method returns `None` to +/// give the batch up; the caller then parses the body as a `StrictValue`, which +/// either reports the error or yields the value for the general path. +/// +/// The parser guarantees valid JSON; the sink owns everything about a row's +/// content. In particular it must refuse a key it has already been given for +/// the row being read, as `StrictValue` refuses duplicate keys. +pub(crate) trait FlatRowSink { + /// Names the column a key of the current row stands for + type Column: Copy; + + /// A key of the current row, unescaped + fn key(&mut self, key: &str) -> Option; + fn null(&mut self, column: Self::Column) -> Option<()>; + fn bool(&mut self, column: Self::Column, value: bool) -> Option<()>; + /// A non-negative integer that fits `u64`, `Number`'s `PosInt` + fn u64(&mut self, column: Self::Column, value: u64) -> Option<()>; + /// A negative integer that fits `i64`, `Number`'s `NegInt` + fn i64(&mut self, column: Self::Column, value: i64) -> Option<()>; + /// Any other number, always finite, `Number`'s `Float` + fn f64(&mut self, column: Self::Column, value: f64) -> Option<()>; + /// A string, unescaped + fn str(&mut self, column: Self::Column, value: &str) -> Option<()>; + /// The current row is complete + fn end_row(&mut self) -> Option<()>; +} + +/// Reads `bytes` as one object, or an array of objects, whose values are all +/// scalars, feeding every row to `sink` in a single pass. +/// +/// `Some` only when `bytes` is a complete JSON document of that shape and the +/// sink took every part of it. A `StrictValue` then parses from the same bytes, +/// provided the sink refused duplicate keys, and holds what the sink was given: +/// both read the document through the same `serde_json` deserializer, so +/// strings are unescaped and numbers classified identically. Anything else is +/// `None`: malformed JSON, trailing data, a nested value, a row that is not an +/// object, or a refusal by the sink. A sink that was given rows before a `None` +/// has to be discarded. +pub(crate) fn parse_flat_rows(bytes: &[u8], sink: &mut S) -> Option<()> { + let mut deserializer = serde_json::Deserializer::from_slice(bytes); + FlatRows(sink).deserialize(&mut deserializer).ok()?; + // Nothing but whitespace may follow the document + deserializer.end().ok() +} + +fn refused() -> E { + E::custom("not a flat batch the sink takes") +} + +/// The document: a row, or an array of rows +struct FlatRows<'a, S>(&'a mut S); + +impl<'de, S: FlatRowSink> DeserializeSeed<'de> for FlatRows<'_, S> { + type Value = (); + + fn deserialize(self, deserializer: D) -> Result<(), D::Error> + where + D: serde::Deserializer<'de>, + { + deserializer.deserialize_any(self) + } +} + +impl<'de, S: FlatRowSink> Visitor<'de> for FlatRows<'_, S> { + type Value = (); + + fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { + formatter.write_str("an object or an array of objects") + } + + fn visit_seq(self, mut seq: A) -> Result<(), A::Error> + where + A: serde::de::SeqAccess<'de>, + { + while seq.next_element_seed(FlatRow(&mut *self.0))?.is_some() {} + Ok(()) + } + + fn visit_map(self, map: A) -> Result<(), A::Error> + where + A: serde::de::MapAccess<'de>, + { + FlatRow(self.0).visit_map(map) + } +} + +/// One row: an object of scalars +struct FlatRow<'a, S>(&'a mut S); + +impl<'de, S: FlatRowSink> DeserializeSeed<'de> for FlatRow<'_, S> { + type Value = (); + + fn deserialize(self, deserializer: D) -> Result<(), D::Error> + where + D: serde::Deserializer<'de>, + { + deserializer.deserialize_any(self) + } +} + +impl<'de, S: FlatRowSink> Visitor<'de> for FlatRow<'_, S> { + type Value = (); + + fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { + formatter.write_str("an object") + } + + fn visit_map(self, mut map: A) -> Result<(), A::Error> + where + A: serde::de::MapAccess<'de>, + { + while let Some(column) = map.next_key_seed(FlatKey(&mut *self.0))? { + map.next_value_seed(FlatScalar(&mut *self.0, column))?; + } + self.0.end_row().ok_or_else(refused) + } +} + +struct FlatKey<'a, S>(&'a mut S); + +impl<'de, S: FlatRowSink> DeserializeSeed<'de> for FlatKey<'_, S> { + type Value = S::Column; + + fn deserialize(self, deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + deserializer.deserialize_str(self) + } +} + +impl Visitor<'_> for FlatKey<'_, S> { + type Value = S::Column; + + fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { + formatter.write_str("a key") + } + + fn visit_str(self, key: &str) -> Result + where + E: serde::de::Error, + { + self.0.key(key).ok_or_else(refused) + } +} + +/// A value of a row. The methods mirror `ValueSeed`'s, so a number reaches the +/// sink as the `Number` variant a `StrictValue` would hold; an object or an +/// array is refused by the methods left to their defaults. +struct FlatScalar<'a, S: FlatRowSink>(&'a mut S, S::Column); + +impl<'de, S: FlatRowSink> DeserializeSeed<'de> for FlatScalar<'_, S> { + type Value = (); + + fn deserialize(self, deserializer: D) -> Result<(), D::Error> + where + D: serde::Deserializer<'de>, + { + deserializer.deserialize_any(self) + } +} + +impl Visitor<'_> for FlatScalar<'_, S> { + type Value = (); + + fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { + formatter.write_str("a scalar") + } + + fn visit_bool(self, v: bool) -> Result<(), E> + where + E: serde::de::Error, + { + self.0.bool(self.1, v).ok_or_else(refused) + } + + fn visit_i64(self, v: i64) -> Result<(), E> + where + E: serde::de::Error, + { + // As `Number::from(i64)`: only a negative integer is a `NegInt` + match u64::try_from(v) { + Ok(v) => self.0.u64(self.1, v), + Err(_) => self.0.i64(self.1, v), + } + .ok_or_else(refused) + } + + fn visit_u64(self, v: u64) -> Result<(), E> + where + E: serde::de::Error, + { + self.0.u64(self.1, v).ok_or_else(refused) + } + + fn visit_f64(self, v: f64) -> Result<(), E> + where + E: serde::de::Error, + { + // `StrictValue` refuses a number JSON cannot hold + if !v.is_finite() { + return Err(refused()); + } + self.0.f64(self.1, v).ok_or_else(refused) + } + + fn visit_str(self, v: &str) -> Result<(), E> + where + E: serde::de::Error, + { + self.0.str(self.1, v).ok_or_else(refused) + } + + fn visit_unit(self) -> Result<(), E> + where + E: serde::de::Error, + { + self.0.null(self.1).ok_or_else(refused) + } +} + +/// `flatten::flat_batch_len`, which only this module tree sees, for the tests +/// that hold batches built from bytes to it. +#[cfg(test)] +pub(crate) fn flat_batch_len( + body: &serde_json::Value, + budget: &mut super::flatten::FlattenBudget, +) -> Option { + super::flatten::flat_batch_len(body, budget) +} + #[cfg(test)] mod tests { use super::*; @@ -780,6 +1012,246 @@ mod tests { assert_eq!(new, old, "extractor"); } } + /// A sink that takes every flat row, and holds what a `StrictValue` of + /// the rows holds + #[derive(Default)] + struct Recorder { + keys: Vec, + row: serde_json::Map, + rows: Vec, + } + + impl Recorder { + fn set(&mut self, column: usize, value: serde_json::Value) -> Option<()> { + self.row.insert(self.keys[column].clone(), value); + Some(()) + } + } + + impl FlatRowSink for Recorder { + type Column = usize; + + fn key(&mut self, key: &str) -> Option { + if self.row.contains_key(key) { + return None; + } + // Holds the key's place, as a row keeps its keys in order + self.row.insert(key.to_owned(), serde_json::Value::Null); + self.keys.push(key.to_owned()); + Some(self.keys.len() - 1) + } + + fn null(&mut self, column: usize) -> Option<()> { + self.set(column, serde_json::Value::Null) + } + + fn bool(&mut self, column: usize, value: bool) -> Option<()> { + self.set(column, value.into()) + } + + fn u64(&mut self, column: usize, value: u64) -> Option<()> { + self.set(column, value.into()) + } + + fn i64(&mut self, column: usize, value: i64) -> Option<()> { + assert!(value < 0, "a non-negative integer is a u64"); + self.set(column, value.into()) + } + + fn f64(&mut self, column: usize, value: f64) -> Option<()> { + let number = serde_json::Number::from_f64(value).expect("a finite float"); + self.set(column, number.into()) + } + + fn str(&mut self, column: usize, value: &str) -> Option<()> { + self.set(column, value.into()) + } + + fn end_row(&mut self) -> Option<()> { + self.rows + .push(serde_json::Value::Object(std::mem::take(&mut self.row))); + Some(()) + } + } + + /// The rows of a flat batch: an object, or an array of objects, of scalars + fn flat_rows(value: &serde_json::Value) -> Option> { + let rows = match value { + serde_json::Value::Array(rows) => rows.clone(), + row @ serde_json::Value::Object(_) => vec![row.clone()], + _ => return None, + }; + rows.iter() + .all(|row| { + row.as_object() + .is_some_and(|row| row.values().all(|v| !v.is_array() && !v.is_object())) + }) + .then_some(rows) + } + + /// `parse_flat_rows` takes exactly the documents that are flat batches as + /// a `StrictValue`, and gives the sink the rows that value holds. + fn check_flat_rows(raw: &[u8]) -> bool { + let mut recorder = Recorder::default(); + let parsed = parse_flat_rows(raw, &mut recorder).map(|()| recorder.rows); + let expected = serde_json::from_slice::(raw) + .ok() + .and_then(|value| flat_rows(&value.inner)); + assert_eq!( + parsed + .as_ref() + .map(|rows| fingerprint(serde_json::Value::Array(rows.clone()))), + expected + .as_ref() + .map(|rows| fingerprint(serde_json::Value::Array(rows.clone()))), + "{:?}", + String::from_utf8_lossy(raw) + ); + parsed.is_some() + } + + #[test] + fn flat_rows_match_strict_value() { + let mut taken = 0; + for raw in corpus() { + taken += check_flat_rows(&raw) as usize; + } + assert!( + taken >= 4, + "{taken} documents of the corpus are flat batches" + ); + + for (raw, flat) in [ + (r#"{}"#, true), + (r#"[]"#, true), + (r#"[{}]"#, true), + (r#" [ { "a" : 1 , "b" : null } , { "b" : "x" } ] "#, true), + ( + r#"{"a":-0,"b":-1,"c":0,"d":1.5e3,"e":18446744073709551615}"#, + true, + ), + ( + r#"{"a":18446744073709551616,"b":-9223372036854775809}"#, + true, + ), + ( + r#"{"a":"\u00e9\n\ud83d\ude00","\u0062":true,"":false}"#, + true, + ), + (r#"[{"a":1},{"a":1}]"#, true), + // Not strict + (r#"{"a":1,"a":2}"#, false), + (r#"{"a":1,"\u0061":2}"#, false), + (r#"[{"a":1},{"b":1,"b":1}]"#, false), + (r#"{"a":1e400}"#, false), + (r#"{"a":NaN}"#, false), + (r#"{"a":1}x"#, false), + (r#"{"a":1}{}"#, false), + (r#"[{"a":1},]"#, false), + (r#"[{"a":1}"#, false), + (r#"{"a":"\ud800"}"#, false), + (r#"{"a":01}"#, false), + (r#"{a:1}"#, false), + (r#"{1:1}"#, false), + (r#""#, false), + // Not flat rows + (r#"1"#, false), + (r#"null"#, false), + (r#""a""#, false), + (r#"[1]"#, false), + (r#"[null]"#, false), + (r#"[[{"a":1}]]"#, false), + (r#"[{"a":1},[]]"#, false), + (r#"{"a":{}}"#, false), + (r#"{"a":[]}"#, false), + (r#"[{"a":1},{"a":{"b":1}}]"#, false), + ] { + assert_eq!(check_flat_rows(raw.as_bytes()), flat, "{raw}"); + } + assert!(!check_flat_rows(b"{\"a\":\"\xff\"}")); + + // Every truncation, and every byte replaced, of a flat batch + let raw = r#"[{"a":1,"b":"x\n","c":null},{"c":-2.5e3,"a":true}]"#.as_bytes(); + for end in 0..raw.len() { + assert!(!check_flat_rows(&raw[..end])); + } + for at in 0..raw.len() { + for byte in [ + b'"', b',', b':', b'{', b'}', b'[', b']', b'a', b'1', b' ', b'\\', + ] { + let mut changed = raw.to_vec(); + changed[at] = byte; + check_flat_rows(&changed); + } + } + } + + /// A sink that refuses is a parse that fails, wherever it refuses + #[test] + fn flat_rows_stop_when_the_sink_refuses() { + struct RefuseAt { + calls: usize, + refuse_at: usize, + } + + impl RefuseAt { + fn call(&mut self) -> Option<()> { + self.calls += 1; + (self.calls != self.refuse_at).then_some(()) + } + } + + impl FlatRowSink for RefuseAt { + type Column = (); + + fn key(&mut self, _: &str) -> Option<()> { + self.call() + } + + fn null(&mut self, (): ()) -> Option<()> { + self.call() + } + + fn bool(&mut self, (): (), _: bool) -> Option<()> { + self.call() + } + + fn u64(&mut self, (): (), _: u64) -> Option<()> { + self.call() + } + + fn i64(&mut self, (): (), _: i64) -> Option<()> { + self.call() + } + + fn f64(&mut self, (): (), _: f64) -> Option<()> { + self.call() + } + + fn str(&mut self, (): (), _: &str) -> Option<()> { + self.call() + } + + fn end_row(&mut self) -> Option<()> { + self.call() + } + } + + let raw = br#"[{"a":1,"b":-1,"c":1.5},{"d":"x","e":null,"f":true}]"#; + // Six keys, six values and two rows + let calls = 14; + for refuse_at in 1..=calls + 1 { + let mut sink = RefuseAt { + calls: 0, + refuse_at, + }; + let parsed = parse_flat_rows(raw, &mut sink); + assert_eq!(parsed.is_some(), refuse_at > calls, "{refuse_at}"); + // Nothing is read past the refusal + assert_eq!(sink.calls, refuse_at.min(calls), "{refuse_at}"); + } + } + #[test] fn non_json_numeric_visitors_match_oracle() { use serde::de::value::{Error, F64Deserializer, I128Deserializer, U128Deserializer};