micromegas_analytics/lakehouse/partitioned_execution_plan.rs
1use super::{partition::Partition, reader_factory::ReaderFactory, view::ScanSortColumn};
2use crate::{
3 dfext::predicate::filters_to_predicate,
4 time::{TimeRange, datetime_to_scalar},
5};
6use anyhow::Context;
7use chrono::{DateTime, Utc};
8use datafusion::{
9 arrow::{compute::SortOptions, datatypes::SchemaRef},
10 catalog::{Session, memory::DataSourceExec},
11 common::stats::Precision,
12 datasource::{
13 listing::PartitionedFile,
14 physical_plan::{FileScanConfigBuilder, ParquetSource},
15 },
16 execution::object_store::ObjectStoreUrl,
17 logical_expr::SortExpr,
18 physical_expr::{LexOrdering, PhysicalSortExpr},
19 physical_plan::{ColumnStatistics, ExecutionPlan, Statistics},
20 prelude::*,
21};
22use micromegas_tracing::prelude::*;
23use std::sync::Arc;
24
25/// Which pair of bounds on `Partition` a declared ordering's leading column is checked against.
26#[derive(Clone, Copy, Debug)]
27pub enum OrderingBounds {
28 /// `min_event_time()` / `max_event_time()` -- `Option`, absent for empty partitions.
29 EventTime,
30 /// `begin_insert_time()` / `end_insert_time()` -- always present.
31 InsertTime,
32}
33
34/// Reads the pair of bounds a declared ordering's leading column is checked against, per
35/// `OrderingBounds`. `InsertTime` bounds are always present; `EventTime` bounds are `None` for
36/// empty partitions (callers are expected to have already filtered those out).
37///
38/// The `EventTime` upper bound prefers `max_sort_key_time` (the partition's true recorded max of
39/// the leading sort column, e.g. `begin` for `thread_spans`) and falls back to `max_event_time`
40/// (the max span *end*, a merely conservative stand-in) when it is `None` -- true for every
41/// partition written before that column existed, and for any view that never declares a
42/// `Concatenated` event-time ordering. This single change point upgrades all three consumers of
43/// `partition_bounds` coherently: the sort key stays `min_event_time`; the non-overlap check below
44/// compares the previous partition's *true* max `begin` against the next's block-derived min
45/// (which can never strictly overlap for cuts at block boundaries of a producer using a shared
46/// flush timestamp); and `attach_ordering_statistics` attaches a tighter, exact `begin` max
47/// statistic. The fallback preserves bit-for-bit behavior for legacy partitions.
48fn partition_bounds(
49 p: &Partition,
50 bounds: OrderingBounds,
51) -> Option<(DateTime<Utc>, DateTime<Utc>)> {
52 match bounds {
53 OrderingBounds::EventTime => p
54 .min_event_time()
55 .zip(p.max_sort_key_time().or(p.max_event_time())),
56 OrderingBounds::InsertTime => Some((p.begin_insert_time(), p.end_insert_time())),
57 }
58}
59
60/// Sorts the non-empty partitions by their leading-column bound ascending (tiebreak `file_path`)
61/// and verifies that adjacent partitions' ranges do not overlap. This makes the declared scan
62/// ordering self-contained: the file group is guaranteed to concatenate in globally-sorted order,
63/// independent of the order the partition cache returned.
64///
65/// Returns an error if any adjacent pair overlaps: the declared ordering cannot be honored, so we
66/// fail loudly instead of silently emitting a mis-ordered scan. For `OrderingBounds::EventTime`,
67/// block-boundary tick overlap no longer trips this check for partitions carrying
68/// `max_sort_key_time` (`partition_bounds` reads it in preference to `max_event_time`): the
69/// producer now stamps one shared timestamp per flush (matching the Unreal producer), so
70/// consecutive blocks touch exactly, and the recorded bound reflects that. Legacy partitions
71/// written before that column existed fall back to the old, looser `max_event_time` bound and so
72/// remain a residual until they are rebuilt -- which happens automatically on their next query,
73/// since `ThreadSpansView::SCHEMA_VERSION`'s bump makes every pre-existing partition stale by
74/// schema hash; this is a self-healing residual, not an admin-retire dependency. The two remaining
75/// residual causes are: an insert-time inversion straddling a JIT segment boundary (a genuine
76/// row-level overlap, correctly rejected); and TSC-frequency estimation drift across
77/// materialization epochs (for `tsc_frequency == 0` processes whose blocks were materialized under
78/// different clock estimates) -- fixed the same way, by retiring the affected stream's partitions
79/// so they rebuild with a single, consistent converter. See the ordering-invariant notes on
80/// `View::get_scan_output_ordering`. For `OrderingBounds::InsertTime` an overlap indicates a
81/// genuine partitioning bug -- input partitions are expected to be non-overlapping in insert_time
82/// by construction.
83fn sort_and_check_non_overlapping(
84 mut partitions: Vec<&Partition>,
85 bounds: OrderingBounds,
86) -> datafusion::error::Result<Vec<&Partition>> {
87 partitions.sort_by(|a, b| {
88 partition_bounds(a, bounds)
89 .map(|(begin, _)| begin)
90 .cmp(&partition_bounds(b, bounds).map(|(begin, _)| begin))
91 .then_with(|| a.file_path.cmp(&b.file_path))
92 });
93 for pair in partitions.windows(2) {
94 let prev = pair[0];
95 let next = pair[1];
96 if let (Some((_, prev_max)), Some((next_min, _))) = (
97 partition_bounds(prev, bounds),
98 partition_bounds(next, bounds),
99 ) && prev_max > next_min
100 {
101 return Err(datafusion::error::DataFusionError::Internal(format!(
102 "declared scan ordering violated: partition {:?} (range ending {prev_max}) overlaps partition {:?} (range starting {next_min}). \
103 If either partition predates max_sort_key_time (schema v8), this heals itself on its next query: a schema-hash bump makes it stale and it \
104 rebuilds automatically, carrying the exact bound, with no admin action needed. Otherwise, for event-time ordering the remaining causes are an \
105 insert-time inversion straddling a JIT segment boundary, or -- for tsc_frequency == 0 processes -- TSC-frequency re-estimation drift across \
106 materialization epochs spanning a clock adjustment; both are fixed by retiring the affected stream's partitions so they rebuild with a single, \
107 consistent time converter. See the rustdoc on sort_and_check_non_overlapping (partitioned_execution_plan.rs) and the ordering-invariant notes on \
108 View::get_scan_output_ordering in view.rs for the full cause list.",
109 prev.file_path, next.file_path
110 )));
111 }
112 }
113 Ok(partitions)
114}
115
116/// Attaches the leading `output_ordering` column's min/max statistics to a `PartitionedFile`,
117/// using `Precision::Inexact` since the bounds read from `Partition` (per `OrderingBounds`) are
118/// not necessarily the column's exact min/max -- though for `EventTime` bounds when
119/// `max_sort_key_time` is recorded, the attached max happens to be exact; `Precision::Inexact` is
120/// still correct to declare, since an exact statistic is a legal special case of an inexact one.
121/// DataFusion's multi-file-group ordering validation (`is_ordering_valid_for_file_groups`)
122/// requires these statistics to be present -- without them the declared ordering is silently
123/// dropped for any file group with more than one file.
124fn attach_ordering_statistics(
125 mut file: PartitionedFile,
126 schema: &SchemaRef,
127 leading_column: &ScanSortColumn,
128 partition: &Partition,
129 bounds: OrderingBounds,
130) -> datafusion::error::Result<PartitionedFile> {
131 let mut stats = Statistics::new_unknown(schema);
132 if let Some((min_time, max_time)) = partition_bounds(partition, bounds) {
133 let idx = schema.index_of(&leading_column.column)?;
134 stats.column_statistics[idx] = ColumnStatistics::new_unknown()
135 .with_min_value(Precision::Inexact(datetime_to_scalar(min_time)))
136 .with_max_value(Precision::Inexact(datetime_to_scalar(max_time)));
137 }
138 file = file.with_statistics(Arc::new(stats));
139 Ok(file)
140}
141
142/// How a partition scan's declared output ordering is realized.
143///
144/// Two scan shapes exist: a single sequential file group spanning every input partition
145/// (`Unordered`, `Concatenated`) and one file group per input partition (`PerFile`, scanned by k
146/// readers for a downstream `SortPreservingMergeExec`). `Unordered` and `Concatenated` build and
147/// execute the identical single-file-group scan -- they differ only in whether the resulting order
148/// is declared to DataFusion, not in scan shape or execution strategy (see
149/// `ScanOrdering::declares_concatenated_ordering`).
150#[derive(Clone, Debug)]
151pub enum ScanOrdering {
152 /// No declared ordering (today's default).
153 Unordered,
154 /// All files form one sequential file group that concatenates in globally-sorted order.
155 /// Requires non-overlapping leading-column bounds (checked against `bounds`).
156 Concatenated {
157 columns: Vec<ScanSortColumn>,
158 bounds: OrderingBounds,
159 },
160 /// Each file is internally sorted by `columns`; files may overlap arbitrarily. The scan
161 /// yields one ordered plan partition per file, for a downstream `SortPreservingMergeExec`.
162 /// `columns` should be non-empty -- `SqlBatchView::with_merge_sort_order` rejects an empty
163 /// list at construction, but this enum and `View::get_scan_output_ordering` are public, so
164 /// that is not the only construction path. An empty `columns` is still safe: it never
165 /// certifies (see `Partition::certifies_sort_order`), so `make_partitioned_execution_plan`
166 /// degrades it to `Unordered` for any non-empty partition rather than planning and recording a
167 /// vacuous ordering.
168 PerFile { columns: Vec<ScanSortColumn> },
169}
170
171impl ScanOrdering {
172 /// True when this ordering declares a concatenating scan's global order (`Concatenated`).
173 /// `PerFile` returns `false` because a per-file ordering only becomes a global one through a
174 /// downstream merge -- it is the other strategy, not an undeclared version of this one. A
175 /// bool, not the columns themselves: nothing on the concatenating path inspects the declared
176 /// columns, only whether an ordering was declared at all (see
177 /// `QueryMerger::execute_concatenated_merge` in `merge.rs`).
178 pub fn declares_concatenated_ordering(&self) -> bool {
179 matches!(self, ScanOrdering::Concatenated { .. })
180 }
181
182 /// Names of the declared sort columns, or `None` when `Unordered`.
183 pub fn sort_columns(&self) -> Option<Vec<String>> {
184 match self {
185 ScanOrdering::Unordered => None,
186 ScanOrdering::Concatenated { columns, .. } | ScanOrdering::PerFile { columns } => {
187 Some(columns.iter().map(|c| c.column.to_string()).collect())
188 }
189 }
190 }
191}
192
193/// Builds the `DataFrame::sort` expressions for `columns`, pairing each with `!descending` for
194/// `asc` so the logical sort matches the `nulls_first: c.descending` physical ordering
195/// `make_lex_ordering` declares below -- the two must stay in lockstep or
196/// `assert_ordering_satisfied` stops matching the sort that was actually applied.
197pub fn sort_exprs(columns: &[ScanSortColumn]) -> Vec<SortExpr> {
198 columns
199 .iter()
200 .map(|c| {
201 Expr::Column(datafusion::common::Column::new_unqualified(
202 c.column.as_str(),
203 ))
204 .sort(!c.descending, c.descending)
205 })
206 .collect()
207}
208
209/// Builds the `LexOrdering` declaring the already-satisfied output ordering of the scan, matching
210/// DataFusion's default `ORDER BY` semantics (ASC NULLS LAST unless `descending`).
211pub fn make_lex_ordering(
212 schema: &SchemaRef,
213 output_ordering: &[ScanSortColumn],
214) -> datafusion::error::Result<Option<LexOrdering>> {
215 let sort_exprs = output_ordering
216 .iter()
217 .map(|c| {
218 let col =
219 datafusion::physical_expr::expressions::Column::new_with_schema(&c.column, schema)?;
220 Ok(PhysicalSortExpr::new(
221 Arc::new(col),
222 SortOptions {
223 descending: c.descending,
224 // Match DataFusion's default ORDER BY semantics: ASC NULLS LAST, DESC NULLS
225 // FIRST. Hardcoding `false` here would declare `DESC NULLS LAST`, which fails
226 // to satisfy a descending query's `DESC NULLS FIRST` requirement and silently
227 // keeps a redundant Sort.
228 nulls_first: c.descending,
229 },
230 ))
231 })
232 .collect::<datafusion::error::Result<Vec<_>>>()?;
233 Ok(LexOrdering::new(sort_exprs))
234}
235
236/// Bails unless `plan` is a single-partition physical plan. `subject` names the query for the
237/// error message (e.g. `format!("merge query {:?}", query)` or `format!("extract query for
238/// {view}")`); `reason` supplies the full, call-site-specific trailing sentence(s) explaining what
239/// a non-single-partition plan means here -- executing such a plan would coalesce partitions and
240/// silently destroy a declared ordering before it is safe to record or execute. Shared by the
241/// query-execution paths that must verify this before executing:
242/// `QueryMerger::execute_concatenated_merge` (only when its ordering is declared),
243/// `QueryMerger::execute_sorted_merge`, and `sql_partition_spec::plan_sorted_extract`.
244pub fn assert_single_partition(
245 plan: &Arc<dyn ExecutionPlan>,
246 subject: &str,
247 insert_range: TimeRange,
248 reason: &str,
249) -> anyhow::Result<()> {
250 let partition_count = plan.properties().output_partitioning().partition_count();
251 if partition_count != 1 {
252 anyhow::bail!(
253 "{subject} (insert_range=[{}, {}]) produced a {partition_count}-partition physical \
254 plan; {reason}",
255 insert_range.begin.to_rfc3339(),
256 insert_range.end.to_rfc3339()
257 );
258 }
259 Ok(())
260}
261
262/// Bails unless `plan`'s output ordering satisfies the declared `columns`, defensively
263/// re-verifying that a `sort_order` guarantee about to be recorded on a fresh partition is
264/// truthful. `label` is a short noun phrase used in the intermediate error-context messages (e.g.
265/// `"per-file merge"` or `"extract-query"`); `subject` names the query for the bail message;
266/// `reason` supplies the full, call-site-specific trailing text of the bail message (what was
267/// declared, and any guidance for diagnosing a mismatch). Shared by the two paths that record a
268/// `sort_order` guarantee: `QueryMerger::execute_sorted_merge` and
269/// `sql_partition_spec::plan_sorted_extract`. `QueryMerger::execute_concatenated_merge` does not
270/// call this -- its ordering is a structural property of the sorted, non-overlapping file group
271/// rather than a query-plan sort DataFusion could get wrong.
272pub fn assert_ordering_satisfied(
273 plan: &Arc<dyn ExecutionPlan>,
274 columns: &[ScanSortColumn],
275 label: &str,
276 subject: &str,
277 insert_range: TimeRange,
278 reason: &str,
279) -> anyhow::Result<()> {
280 let lex = make_lex_ordering(&plan.schema(), columns)
281 .with_context(|| format!("building the declared {label} ordering"))?
282 .with_context(|| format!("declared {label} columns must be non-empty"))?;
283 let ordering_satisfied = plan
284 .properties()
285 .equivalence_properties()
286 .ordering_satisfy(lex)
287 .with_context(|| format!("checking {label} plan output ordering"))?;
288 if !ordering_satisfied {
289 anyhow::bail!(
290 "{subject} (insert_range=[{}, {}]) produced a physical plan whose output ordering \
291 does not satisfy {reason}",
292 insert_range.begin.to_rfc3339(),
293 insert_range.end.to_rfc3339()
294 );
295 }
296 Ok(())
297}
298
299/// Creates a partitioned execution plan for scanning Parquet files.
300///
301/// `scan_ordering` declares how the scan's already-satisfied ordering (see
302/// `View::get_scan_output_ordering`), if any, is realized:
303/// - `Unordered`: no ordering is declared to DataFusion.
304/// - `Concatenated { columns, bounds }`: the file group is sorted by the leading column's bound
305/// (read per `bounds`) and checked for non-overlap (erroring if violated), per-file min/max
306/// statistics are attached so DataFusion accepts the declared ordering, and the ordering is
307/// attached to the resulting `FileScanConfig` so `EnsureRequirements` can elide a redundant `Sort`
308/// node.
309/// - `PerFile { columns }`: gated by `Partition::certifies_sort_order` -- if every non-empty
310/// partition's recorded `sort_order` certifies `columns`, each non-empty partition becomes its
311/// own single-file group (no overlap check, no per-file statistics -- DataFusion's multi-file-group
312/// ordering validation only needs those to prove cross-file order *within* a group, and
313/// single-file groups pass trivially), all declaring the same `columns` ordering for a
314/// downstream `SortPreservingMergeExec`. If any non-empty partition fails to certify, this
315/// degrades to the same plan shape as `Unordered`.
316#[span_fn]
317#[expect(clippy::too_many_arguments)]
318pub fn make_partitioned_execution_plan(
319 schema: SchemaRef,
320 reader_factory: Arc<ReaderFactory>,
321 state: &dyn Session,
322 projection: Option<&Vec<usize>>,
323 filters: &[Expr],
324 limit: Option<usize>,
325 partitions: Arc<Vec<Partition>>,
326 scan_ordering: &ScanOrdering,
327) -> datafusion::error::Result<Arc<dyn ExecutionPlan>> {
328 let predicate = filters_to_predicate(schema.clone(), state, filters)?;
329
330 let non_empty_partitions: Vec<&Partition> =
331 partitions.iter().filter(|p| !p.is_empty()).collect();
332
333 // A PerFile declaration that any non-empty partition does not certify degrades to Unordered:
334 // both consumers (user-query scans and merge scans) fall back to sorting rather than trust a
335 // stale or uncertified guarantee.
336 let scan_ordering = match scan_ordering {
337 ScanOrdering::PerFile { columns }
338 if !non_empty_partitions
339 .iter()
340 .all(|p| p.certifies_sort_order(columns)) =>
341 {
342 &ScanOrdering::Unordered
343 }
344 other => other,
345 };
346
347 match scan_ordering {
348 ScanOrdering::Unordered => build_unordered_or_concatenated_plan(
349 schema,
350 reader_factory,
351 predicate,
352 projection,
353 limit,
354 non_empty_partitions,
355 None,
356 ),
357 ScanOrdering::Concatenated { columns, bounds } => {
358 let non_empty_partitions =
359 sort_and_check_non_overlapping(non_empty_partitions, *bounds)?;
360 build_unordered_or_concatenated_plan(
361 schema,
362 reader_factory,
363 predicate,
364 projection,
365 limit,
366 non_empty_partitions,
367 Some((columns.as_slice(), *bounds)),
368 )
369 }
370 ScanOrdering::PerFile { columns } => build_per_file_plan(
371 schema,
372 reader_factory,
373 predicate,
374 projection,
375 limit,
376 non_empty_partitions,
377 columns,
378 ),
379 }
380}
381
382/// Builds the `Unordered` (`ordering: None`) and `Concatenated` (`ordering: Some((columns,
383/// bounds))`) scan shapes: every non-empty partition in one sequential file group.
384fn build_unordered_or_concatenated_plan(
385 schema: SchemaRef,
386 reader_factory: Arc<ReaderFactory>,
387 predicate: Arc<dyn datafusion::physical_expr::PhysicalExpr>,
388 projection: Option<&Vec<usize>>,
389 limit: Option<usize>,
390 non_empty_partitions: Vec<&Partition>,
391 ordering: Option<(&[ScanSortColumn], OrderingBounds)>,
392) -> datafusion::error::Result<Arc<dyn ExecutionPlan>> {
393 let mut file_group = vec![];
394 for part in &non_empty_partitions {
395 let file_path = part.file_path.as_ref().ok_or_else(|| {
396 datafusion::error::DataFusionError::Internal(format!(
397 "non-empty partition has no file_path: num_rows={}",
398 part.num_rows
399 ))
400 })?;
401 let mut pf = PartitionedFile::new(file_path, part.file_size as u64);
402 if let Some((output_ordering, ordering_bounds)) = ordering
403 && let Some(leading_column) = output_ordering.first()
404 {
405 pf = attach_ordering_statistics(pf, &schema, leading_column, part, ordering_bounds)?;
406 }
407 file_group.push(pf);
408 }
409
410 // If all partitions are empty, return EmptyExec with projected schema
411 if file_group.is_empty() {
412 return empty_exec(schema, projection);
413 }
414
415 let object_store_url = ObjectStoreUrl::parse("obj://lakehouse/").unwrap();
416 let source = Arc::new(
417 ParquetSource::new(schema.clone())
418 .with_predicate(predicate)
419 .with_parquet_file_reader_factory(reader_factory),
420 );
421 let mut builder = FileScanConfigBuilder::new(object_store_url, source)
422 .with_limit(limit)
423 .with_projection_indices(projection.cloned())?
424 .with_file_groups(vec![file_group.into()]);
425
426 if let Some((output_ordering, _)) = ordering
427 && let Some(lex) = make_lex_ordering(&schema, output_ordering)?
428 {
429 builder = builder.with_output_ordering(vec![lex]);
430 }
431 let file_scan_config = builder.build();
432 Ok(Arc::new(DataSourceExec::new(Arc::new(file_scan_config))))
433}
434
435/// Builds the `PerFile` scan shape: one single-file file group per non-empty partition, all
436/// declaring the same `columns` ordering. No overlap check and no per-file statistics -- see the
437/// module-level rustdoc on `ScanOrdering::PerFile`.
438fn build_per_file_plan(
439 schema: SchemaRef,
440 reader_factory: Arc<ReaderFactory>,
441 predicate: Arc<dyn datafusion::physical_expr::PhysicalExpr>,
442 projection: Option<&Vec<usize>>,
443 limit: Option<usize>,
444 non_empty_partitions: Vec<&Partition>,
445 columns: &[ScanSortColumn],
446) -> datafusion::error::Result<Arc<dyn ExecutionPlan>> {
447 let mut file_groups = vec![];
448 for part in &non_empty_partitions {
449 let file_path = part.file_path.as_ref().ok_or_else(|| {
450 datafusion::error::DataFusionError::Internal(format!(
451 "non-empty partition has no file_path: num_rows={}",
452 part.num_rows
453 ))
454 })?;
455 let pf = PartitionedFile::new(file_path, part.file_size as u64);
456 file_groups.push(vec![pf].into());
457 }
458
459 if file_groups.is_empty() {
460 return empty_exec(schema, projection);
461 }
462
463 let object_store_url = ObjectStoreUrl::parse("obj://lakehouse/").unwrap();
464 let source = Arc::new(
465 ParquetSource::new(schema.clone())
466 .with_predicate(predicate)
467 .with_parquet_file_reader_factory(reader_factory),
468 );
469 let mut builder = FileScanConfigBuilder::new(object_store_url, source)
470 .with_limit(limit)
471 .with_projection_indices(projection.cloned())?
472 .with_file_groups(file_groups);
473
474 if let Some(lex) = make_lex_ordering(&schema, columns)? {
475 builder = builder.with_output_ordering(vec![lex]);
476 }
477 let file_scan_config = builder.build();
478 Ok(Arc::new(DataSourceExec::new(Arc::new(file_scan_config))))
479}
480
481fn empty_exec(
482 schema: SchemaRef,
483 projection: Option<&Vec<usize>>,
484) -> datafusion::error::Result<Arc<dyn ExecutionPlan>> {
485 use datafusion::physical_plan::empty::EmptyExec;
486 let projected_schema = if let Some(projection) = projection {
487 Arc::new(schema.project(projection)?)
488 } else {
489 schema
490 };
491 Ok(Arc::new(EmptyExec::new(projected_schema)))
492}