Skip to main content

micromegas_analytics/lakehouse/
merge.rs

1use super::{
2    lakehouse_context::LakehouseContext,
3    partition::Partition,
4    partition_cache::{PartitionCache, QueryPartitionProvider},
5    partition_source_data::hash_to_object_count,
6    partitioned_execution_plan::{
7        ScanOrdering, assert_ordering_satisfied, assert_single_partition, sort_exprs,
8    },
9    partitioned_table_provider::PartitionedTableProvider,
10    query::{SessionRange, make_session_context},
11    read_scope::CallerContext,
12    session_configurator::SessionConfigurator,
13    view::{ScanSortColumn, View},
14    view_factory::ViewFactory,
15    write_partition::{PartitionRowSet, RetireMatch, write_partition_from_rows},
16};
17use crate::{response_writer::Logger, time::TimeRange};
18use anyhow::{Context, Result};
19use async_trait::async_trait;
20use datafusion::{
21    arrow::datatypes::Schema,
22    common::TableReference,
23    execution::{SendableRecordBatchStream, TaskContext},
24    physical_plan::{ExecutionPlan, displayable, execute_stream},
25    prelude::*,
26};
27use futures::stream::StreamExt;
28use micromegas_tracing::prelude::*;
29use std::fmt::Debug;
30use std::sync::Arc;
31use std::time::Instant;
32use xxhash_rust::xxh32::xxh32;
33
34/// A merge is a bounded, streaming rewrite of a fixed set of files whose consumer is a single
35/// writer task (`create_merged_partition` -> `write_partition_from_rows`), not a query that
36/// benefits from scan parallelism. Left at DataFusion's default (`true`), `EnsureRequirements`
37/// splits the source scan into `target_partitions` byte-range file groups and `execute_stream`
38/// coalesces them, so the reader working set is multiplied by the host's core count for no
39/// throughput the writer can absorb. Forcing one sequential file group here fixes that for the
40/// `Unordered` and `Concatenated` shapes, which both start from a single file group spanning every
41/// input partition: left unsplit, one reader works through that group's files one at a time instead
42/// of `target_partitions` concurrent byte-range readers. `PerFile` already builds one file group per
43/// input partition, and this setting is load-bearing there too: left at `true`,
44/// `repartition_file_groups` (via `repartition_preserving_order`) splits each of those k
45/// per-partition groups into `target_partitions` byte-range groups whenever k < `target_partitions`,
46/// so this setting is what keeps `PerFile` at one reader per input file for its k-way ordered merge.
47/// Downstream parallelism is untouched: a merge query with a GROUP BY still gets its round-robin
48/// fan-out above the scan.
49pub async fn make_merge_session_context(
50    lakehouse: Arc<LakehouseContext>,
51    part_provider: Arc<dyn QueryPartitionProvider>,
52    query_range: SessionRange,
53    view_factory: Arc<ViewFactory>,
54    configurator: Arc<dyn SessionConfigurator>,
55    caller: CallerContext,
56) -> Result<SessionContext> {
57    let ctx = make_session_context(
58        lakehouse,
59        part_provider,
60        query_range,
61        view_factory,
62        configurator,
63        caller,
64    )
65    .await?;
66    ctx.state_ref()
67        .write()
68        .config_mut()
69        .options_mut()
70        .optimizer
71        .repartition_file_scans = false;
72    Ok(ctx)
73}
74
75/// The outcome of running a merge query.
76pub struct MergeQueryResult {
77    /// The merged rows.
78    pub stream: SendableRecordBatchStream,
79    /// Whether the merger's declared scan ordering (if any) was honored by the physical plan
80    /// without falling back to a buffering `Sort` node. Always `true` for the concatenate
81    /// strategy's undeclared shape (`ScanOrdering::Unordered`) -- there is no declared ordering to
82    /// defeat -- and only ever computed dynamically for the two strategies that declare one. This
83    /// drives only a memory-regression warning; it never gates the recorded `sort_order` (see
84    /// `View::get_merged_partition_sort_order`).
85    ///
86    /// For the sort-merge strategy (`ScanOrdering::PerFile`), a surviving `SortPreservingMergeExec`
87    /// is the *expected* operator, not a regression -- only a surviving `SortExec` means the
88    /// streaming shape was lost. For the concatenate strategy's declared shape
89    /// (`ScanOrdering::Concatenated`), either operator surviving is a regression.
90    pub ordering_honored: bool,
91}
92
93/// A `PerFile` merge plan, built but not executed.
94pub struct PlannedSortedMerge {
95    pub plan: Arc<dyn ExecutionPlan>,
96    pub task_ctx: Arc<TaskContext>,
97    pub plan_text: String,
98    /// `false` when a `SortExec` survived, i.e. the merge buffers its input instead of streaming.
99    pub ordering_honored: bool,
100}
101
102/// Builds the `PerFile` k-way merge plan: four optimizer settings keep the merge a bounded-memory
103/// streaming k-way merge instead of fanning out to `target_partitions` --
104/// `repartition_file_scans = false` is the fifth, applied to every merge by the caller's
105/// `make_merge_session_context` session rather than set here -- an unconditional logical-plan
106/// `DataFrame::sort` makes the declared ordering a property of the query plan rather than of an
107/// optimizer preference (so a wrong or missing merge-query sort is not representable), and three
108/// checks -- two hard, one reported through `ordering_honored` -- run against the physical plan.
109/// Shared by the daemon's merge and the admin streaming check so the two cannot drift.
110pub async fn plan_sorted_merge(
111    ctx: &SessionContext,
112    query: &str,
113    columns: &[ScanSortColumn],
114    insert_range: TimeRange,
115) -> Result<PlannedSortedMerge> {
116    {
117        let state = ctx.state_ref();
118        let mut state = state.write();
119        let optimizer = &mut state.config_mut().options_mut().optimizer;
120        optimizer.enable_round_robin_repartition = false;
121        optimizer.repartition_aggregations = false;
122        optimizer.prefer_existing_sort = true;
123        optimizer.repartition_joins = false;
124    }
125
126    let df = ctx.sql(query).await?;
127    let df = df.sort(sort_exprs(columns))?;
128    let task_ctx = Arc::new(df.task_ctx());
129    let plan = df
130        .create_physical_plan()
131        .await
132        .with_context(|| "creating physical plan for per-file merge query")?;
133
134    // Check 1 (hard): execute_stream would otherwise coalesce partitions and destroy order.
135    assert_single_partition(
136        &plan,
137        &format!("merge query {query:?}"),
138        insert_range,
139        "executing it would coalesce partitions and destroy the declared ordering. This \
140         likely means repartition_aggregations or enable_round_robin_repartition did not \
141         take effect, or the merge query is missing a collapsing operator (e.g. a \
142         SortPreservingMergeExec) to bring the per-file partitions back to one.",
143    )?;
144
145    // Check 2 (hard): the plan's output ordering must satisfy the declared columns -- a
146    // defensive assertion that the sort_order about to be recorded is truthful. This has no
147    // author-reachable failure path under this design (the sort above is applied
148    // unconditionally): it is a backstop against a future DataFusion regression, not against
149    // author error.
150    assert_ordering_satisfied(
151        &plan,
152        columns,
153        "per-file merge",
154        &format!("merge query {query:?}"),
155        insert_range,
156        &format!(
157            "the declared per-file merge columns {columns:?}; refusing to record a false \
158             sort_order guarantee."
159        ),
160    )?;
161
162    // Check 3 (reported, not hard): a SortPreservingMergeExec is the *expected* operator here --
163    // only a surviving SortExec signals the streaming shape regressed (memory, not correctness --
164    // check 2 already proved the output order).
165    let plan_text = displayable(plan.as_ref()).indent(true).to_string();
166    let ordering_honored = !plan_text.contains("SortExec");
167    Ok(PlannedSortedMerge {
168        plan,
169        task_ctx,
170        plan_text,
171        ordering_honored,
172    })
173}
174
175/// A trait for merging partitions.
176#[async_trait]
177pub trait PartitionMerger: Send + Sync + Debug {
178    /// Executes the merge query.
179    async fn execute_merge_query(
180        &self,
181        lakehouse: Arc<LakehouseContext>,
182        partitions_to_merge: Arc<Vec<Partition>>,
183        partitions_all_views: Arc<PartitionCache>,
184        insert_range: TimeRange,
185    ) -> Result<MergeQueryResult>;
186}
187
188/// A `PartitionMerger` that executes a SQL query to merge partitions.
189#[derive(Debug)]
190pub struct QueryMerger {
191    view_factory: Arc<ViewFactory>,
192    session_configurator: Arc<dyn SessionConfigurator>,
193    file_schema: Arc<Schema>,
194    query: Arc<String>,
195    merge_scan_ordering: ScanOrdering,
196}
197
198impl QueryMerger {
199    pub fn new(
200        view_factory: Arc<ViewFactory>,
201        session_configurator: Arc<dyn SessionConfigurator>,
202        file_schema: Arc<Schema>,
203        query: Arc<String>,
204    ) -> Self {
205        Self {
206            view_factory,
207            session_configurator,
208            file_schema,
209            query,
210            merge_scan_ordering: ScanOrdering::Unordered,
211        }
212    }
213
214    /// Declares an ordering the merge's source scan already satisfies (see
215    /// `PartitionedTableProvider::with_scan_ordering`), letting DataFusion elide the merge query's
216    /// `Sort` node instead of buffering. Default: `Unordered` (matching today's behavior for every
217    /// existing caller).
218    pub fn with_merge_scan_ordering(mut self, ordering: ScanOrdering) -> Self {
219        self.merge_scan_ordering = ordering;
220        self
221    }
222
223    /// The concatenating merge path: one sequential reader over one file group, covering both
224    /// `ScanOrdering::Unordered` and `ScanOrdering::Concatenated` -- they build and execute the
225    /// identical scan, differing only in whether `declared` is `true`, i.e. whether the
226    /// resulting order is declared to DataFusion.
227    /// `repartition_file_scans = false` is applied to every merge by the caller's
228    /// `make_merge_session_context` session, not here; this method just builds the physical plan
229    /// once, inspects it, and executes that exact plan -- never planning or building twice.
230    /// `declared` gates `assert_single_partition` and the `SortExec`/`SortPreservingMergeExec`
231    /// plan-string check, both of which exist to protect a declared ordering: with nothing
232    /// declared there is nothing to protect, and `ordering_honored` is unconditionally `true`,
233    /// matching `MergeQueryResult::ordering_honored`'s documented default for an undeclared
234    /// ordering.
235    async fn execute_concatenated_merge(
236        &self,
237        ctx: &SessionContext,
238        declared: bool,
239        insert_range: TimeRange,
240    ) -> Result<MergeQueryResult> {
241        let df = ctx.sql(&self.query).await?;
242        let task_ctx = Arc::new(df.task_ctx());
243        let plan = df
244            .create_physical_plan()
245            .await
246            .with_context(|| "creating physical plan for merge query")?;
247
248        if declared {
249            assert_single_partition(
250                &plan,
251                &format!("merge query {:?}", self.query),
252                insert_range,
253                "executing it would coalesce partitions and destroy the declared ordering. This \
254                 likely means repartition_file_scans did not take effect.",
255            )?;
256        }
257
258        let ordering_honored = if declared {
259            let plan_str = displayable(plan.as_ref()).indent(true).to_string();
260            let honored =
261                !plan_str.contains("SortExec") && !plan_str.contains("SortPreservingMergeExec");
262            if !honored {
263                warn!(
264                    "merge query {:?} (insert_range=[{}, {}]) did not elide its declared \
265                     ordering -- the merge will still produce a correctly ordered result, but \
266                     it will buffer in memory instead of streaming. Plan:\n{plan_str}",
267                    self.query,
268                    insert_range.begin.to_rfc3339(),
269                    insert_range.end.to_rfc3339()
270                );
271            }
272            honored
273        } else {
274            true
275        };
276
277        let stream =
278            execute_stream(plan, task_ctx).with_context(|| "executing merge query plan")?;
279        Ok(MergeQueryResult {
280            stream,
281            ordering_honored,
282        })
283    }
284
285    /// The `PerFile` k-way merge path: plans via [`plan_sorted_merge`], warns when the streaming
286    /// shape was lost, then executes that exact plan.
287    async fn execute_sorted_merge(
288        &self,
289        ctx: &SessionContext,
290        columns: &[ScanSortColumn],
291        insert_range: TimeRange,
292    ) -> Result<MergeQueryResult> {
293        let planned = plan_sorted_merge(ctx, &self.query, columns, insert_range).await?;
294        if !planned.ordering_honored {
295            warn!(
296                "merge query {:?} (insert_range=[{}, {}]) did not elide its declared per-file \
297                 ordering -- the merge will still produce a correctly ordered result, but it will \
298                 buffer in memory instead of streaming. Plan:\n{}",
299                self.query,
300                insert_range.begin.to_rfc3339(),
301                insert_range.end.to_rfc3339(),
302                planned.plan_text
303            );
304        }
305
306        let stream = execute_stream(planned.plan, planned.task_ctx)
307            .with_context(|| "executing per-file merge query plan")?;
308        Ok(MergeQueryResult {
309            stream,
310            ordering_honored: planned.ordering_honored,
311        })
312    }
313}
314
315#[async_trait]
316impl PartitionMerger for QueryMerger {
317    async fn execute_merge_query(
318        &self,
319        lakehouse: Arc<LakehouseContext>,
320        partitions_to_merge: Arc<Vec<Partition>>,
321        partitions_all_views: Arc<PartitionCache>,
322        insert_range: TimeRange,
323    ) -> Result<MergeQueryResult> {
324        let reader_factory = lakehouse.reader_factory().clone();
325        let ctx = make_merge_session_context(
326            lakehouse.clone(),
327            partitions_all_views,
328            SessionRange::Query(insert_range),
329            self.view_factory.clone(),
330            self.session_configurator.clone(),
331            CallerContext::maintenance(),
332        )
333        .await?;
334        let src_table = PartitionedTableProvider::with_scan_ordering(
335            self.file_schema.clone(),
336            reader_factory,
337            partitions_to_merge,
338            self.merge_scan_ordering.clone(),
339        );
340        ctx.register_table(
341            TableReference::Bare {
342                table: "source".into(),
343            },
344            Arc::new(src_table),
345        )?;
346
347        match &self.merge_scan_ordering {
348            // Sort-merge: k ordered readers, collapsed by a SortPreservingMergeExec.
349            ScanOrdering::PerFile { columns } => {
350                self.execute_sorted_merge(&ctx, columns, insert_range).await
351            }
352            // Concatenate: one sequential reader over one file group. `Unordered` and
353            // `Concatenated` are the same strategy -- they differ only in whether the resulting
354            // order is declared, which is what gates the checks inside. Spelled out rather than a
355            // wildcard so a future `ScanOrdering` variant fails to compile here instead of
356            // silently taking this arm.
357            other @ (ScanOrdering::Unordered | ScanOrdering::Concatenated { .. }) => {
358                self.execute_concatenated_merge(
359                    &ctx,
360                    other.declares_concatenated_ordering(),
361                    insert_range,
362                )
363                .await
364            }
365        }
366    }
367}
368
369fn partition_set_stats(
370    view: Arc<dyn View>,
371    filtered_partitions: &[Partition],
372) -> Result<(i64, i64)> {
373    let mut sum_size: i64 = 0;
374    let mut source_hash: i64 = 0;
375    let latest_file_schema_hash = view.get_file_schema_hash();
376    for p in filtered_partitions {
377        // for some time all the hashes will actually be the number of events in the source data
378        // when views have different hash algos, we should delegate to the view the creation of the merged hash
379        source_hash = if p.source_data_hash.len() == std::mem::size_of::<i64>() {
380            source_hash + hash_to_object_count(&p.source_data_hash)?
381        } else {
382            //previous hash algo
383            xxh32(&p.source_data_hash, source_hash as u32).into()
384        };
385
386        sum_size += p.file_size;
387
388        if p.view_metadata.file_schema_hash != latest_file_schema_hash {
389            anyhow::bail!(
390                "incompatible file schema with [{},{}]",
391                p.begin_insert_time().to_rfc3339(),
392                p.end_insert_time().to_rfc3339()
393            );
394        }
395    }
396    Ok((sum_size, source_hash))
397}
398
399/// Creates a merged partition from a set of existing partitions.
400#[span_fn(view = view.get_view_set_name())]
401pub async fn create_merged_partition(
402    partitions_to_merge: Arc<PartitionCache>,
403    partitions_all_views: Arc<PartitionCache>,
404    lakehouse: Arc<LakehouseContext>,
405    view: Arc<dyn View>,
406    insert_range: TimeRange,
407    logger: Arc<dyn Logger>,
408) -> Result<()> {
409    let view_set_name = &view.get_view_set_name();
410    let view_instance_id = &view.get_view_instance_id();
411    let desc = format!(
412        "[{}, {}] {view_set_name} {view_instance_id}",
413        insert_range.begin.to_rfc3339(),
414        insert_range.end.to_rfc3339()
415    );
416    // we are not looking for intersecting partitions, but only those that fit completely in the range
417    // otherwise we'd get duplicated records
418    let mut filtered_partitions = partitions_to_merge
419        .filter_inside_range(view_set_name, view_instance_id, insert_range)
420        .partitions;
421    if filtered_partitions.len() != partitions_to_merge.len() {
422        warn!("partitions_to_merge was not filtered properly");
423    }
424    if filtered_partitions.len() < 2 {
425        logger
426            .write_log_entry(format!("{desc}: not enough partitions to merge"))
427            .await
428            .with_context(|| "writing log")?;
429        return Ok(());
430    }
431    let (sum_size, source_hash) = partition_set_stats(view.clone(), &filtered_partitions)
432        .with_context(|| "partition_set_stats")?;
433    logger
434        .write_log_entry(format!(
435            "{desc}: merging {} partitions sum_size={sum_size}",
436            filtered_partitions.len()
437        ))
438        .await
439        .with_context(|| "write_log_entry")?;
440    let merge_start = Instant::now();
441    filtered_partitions.sort_by_key(|p| p.begin_insert_time());
442    // Computed before merge_partitions runs: a pure function of the input slice alone.
443    let merged_sort_order = view.get_merged_partition_sort_order(&filtered_partitions);
444    let merge_result = instrument_named!(
445        view.merge_partitions(
446            lakehouse.clone(),
447            Arc::new(filtered_partitions),
448            partitions_all_views,
449            insert_range,
450        ),
451        "merge_plan",
452        |_, span| span.set_property("view", view_set_name)
453    )
454    .await
455    .with_context(|| "view.merge_partitions")?;
456    // A defeated ordering elision (ordering_honored: false) is already warned about, with the
457    // offending plan, inside QueryMerger::execute_merge_query.
458    let mut merged_stream = merge_result.stream;
459    let (tx, rx) = tokio::sync::mpsc::channel(1);
460    let view_copy = view.clone();
461    let lake = lakehouse.lake().clone();
462    let join_handle = spawn_with_context(write_partition_from_rows(
463        lake,
464        view_copy.get_meta(),
465        view_copy.get_file_schema(),
466        insert_range,
467        source_hash.to_le_bytes().to_vec(),
468        merged_sort_order,
469        RetireMatch::Containment,
470        Vec::new(),
471        rx,
472        logger.clone(),
473    ));
474    let compute_time_bounds = view.get_time_bounds();
475    let ctx =
476        SessionContext::new_with_config_rt(SessionConfig::default(), lakehouse.runtime().clone());
477    let stream_result: Result<()> = async {
478        while let Some(rb_res) =
479            instrument_named!(merged_stream.next(), "merge_next_batch", |_, span| span
480                .set_property("view", view_set_name))
481            .await
482        {
483            let rb = rb_res.with_context(|| "receiving record_batch from stream")?;
484            let event_time_range = instrument_named!(
485                compute_time_bounds
486                    .get_time_bounds(ctx.read_batch(rb.clone()).with_context(|| "read_batch")?),
487                "get_time_bounds",
488                |_, span| span.set_property("view", view_set_name)
489            )
490            .await?;
491            instrument_named!(
492                tx.send(Ok(PartitionRowSet::new(event_time_range, rb, None))),
493                "merge_channel_send",
494                |_, span| span.set_property("view", view_set_name)
495            )
496            .await
497            .with_context(|| "sending partition row set")?;
498        }
499        Ok(())
500    }
501    .await;
502
503    match stream_result {
504        Ok(()) => {
505            drop(tx);
506            instrument_named!(join_handle, "merge_writer_join", |_, span| span
507                .set_property("view", view_set_name))
508            .await??;
509            logger
510                .write_log_entry(format!(
511                    "{desc}: merge completed in {:.3}s",
512                    merge_start.elapsed().as_secs_f64()
513                ))
514                .await
515                .with_context(|| "write_log_entry")?;
516            Ok(())
517        }
518        Err(e) => {
519            warn!("aborting merge partition write for {desc}: {e:?}");
520            let _ = tx.send(Err(anyhow::anyhow!("merge stream aborted"))).await;
521            drop(tx);
522            match instrument_named!(join_handle, "merge_writer_join", |_, span| span
523                .set_property("view", view_set_name))
524            .await
525            {
526                Ok(Ok(())) => {}
527                Ok(Err(writer_err)) => {
528                    debug!("merge writer task error during abort: {writer_err:?}");
529                }
530                Err(join_err) => {
531                    warn!("merge writer task panicked during abort: {join_err:?}");
532                }
533            }
534            Err(e)
535        }
536    }
537}