Skip to main content

micromegas_analytics/lakehouse/
sql_batch_view.rs

1use super::{
2    batch_update::PartitionCreationStrategy,
3    dataframe_time_bounds::{DataFrameTimeBounds, NamedColumnsTimeBounds},
4    lakehouse_context::LakehouseContext,
5    materialized_view::MaterializedView,
6    merge::{MergeQueryResult, PartitionMerger, QueryMerger},
7    on_demand_jit::update_on_demand_view,
8    partition::Partition,
9    partition_cache::{NullPartitionProvider, PartitionCache},
10    partitioned_execution_plan::ScanOrdering,
11    query::{SessionRange, make_session_context},
12    read_scope::CallerContext,
13    session_configurator::SessionConfigurator,
14    sql_partition_spec::fetch_sql_partition_spec,
15    view::{PartitionSpec, ScanSortColumn, View, ViewMetadata},
16    view_factory::ViewFactory,
17};
18use crate::{
19    record_batch_transformer::TrivialRecordBatchTransformer,
20    time::{TimeRange, datetime_to_scalar},
21};
22use anyhow::{Context, Result};
23use async_trait::async_trait;
24use chrono::{DateTime, TimeDelta, Utc};
25use datafusion::{
26    arrow::datatypes::Schema, common::TableReference, execution::runtime_env::RuntimeEnv,
27    prelude::*,
28};
29use micromegas_ingestion::data_lake_connection::DataLakeConnection;
30use micromegas_tracing::{error, prelude::*};
31use std::hash::Hash;
32use std::hash::Hasher;
33use std::{hash::DefaultHasher, sync::Arc};
34
35/// The `SQLOptions` every plan-only build of a stored query text (extract/count/merge, at
36/// construction or validation time) must use instead of the unguarded `ctx.sql(...)`:
37/// `SQLOptions::new()`'s defaults are `allow_ddl`/`allow_dml`/`allow_statements: true`, so planning
38/// a stored query containing an embedded `CREATE EXTERNAL TABLE`/`DROP VIEW`/`COPY ... TO` would
39/// otherwise execute it once here and again on every daemon tick (`SqlPartitionSpec::write` plans
40/// `extract_query` the same way it was first planned). `pub(crate)` so `view_definition.rs`'s
41/// validation checks reuse the exact same guard.
42pub(crate) fn guarded_sql_options() -> SQLOptions {
43    SQLOptions::new()
44        .with_allow_ddl(false)
45        .with_allow_dml(false)
46        .with_allow_statements(false)
47}
48
49/// Builds the ascending `ScanSortColumn` list corresponding to a declared sort order.
50fn sort_order_as_scan_columns(columns: &[Arc<String>]) -> Vec<ScanSortColumn> {
51    columns
52        .iter()
53        .map(|column| ScanSortColumn {
54            column: column.clone(),
55            descending: false,
56        })
57        .collect()
58}
59
60/// SQL-defined view updated in batch
61#[derive(Debug, Clone)]
62pub struct SqlBatchView {
63    view_set_name: Arc<String>,
64    view_instance_id: Arc<String>,
65    min_event_time_column: Arc<String>,
66    max_event_time_column: Arc<String>,
67    count_src_query: Arc<String>,
68    extract_query: Arc<String>,
69    merge_partitions_query: Arc<String>,
70    schema: Arc<Schema>,
71    merger: Arc<dyn PartitionMerger>,
72    view_factory: Arc<ViewFactory>,
73    session_configurator: Arc<dyn SessionConfigurator>,
74    update_group: Option<i32>,
75    max_partition_delta_from_source: TimeDelta,
76    max_partition_delta_from_merge: TimeDelta,
77    /// The ascending sort order this view's partitions are declared to satisfy (see
78    /// `with_merge_sort_order`), if any.
79    sort_order: Option<Vec<Arc<String>>>,
80    /// A `QueryMerger` declaring `ScanOrdering::PerFile { columns: sort_order }`, used instead of
81    /// `merger` when every input to a merge certifies `sort_order`.
82    ordered_merger: Option<Arc<dyn PartitionMerger>>,
83    /// On-demand views this view's queries read. The JIT driver refreshes them before it
84    /// snapshots source partitions, because the extract and count sessions cannot refresh
85    /// upstream themselves.
86    on_demand_sources: Vec<Arc<dyn View>>,
87    /// Every view the extract query scans: the sources whose partition bytes a materialization
88    /// step reads.
89    extract_sources: Vec<ViewMetadata>,
90    /// Most source bytes one materialization step of an on-demand view may read.
91    max_jit_src_bytes: i64,
92}
93
94impl SqlBatchView {
95    #[expect(clippy::too_many_arguments)]
96    /// # Arguments
97    ///
98    /// * `runtime` - datafusion runtime
99    /// * `view_set_name` - name of the table
100    /// * `min_event_time_column` - min(column) should result in the first timestamp in a dataframe
101    /// * `max_event_time_column` - max(column) should result in the last timestamp in a dataframe
102    /// * `count_src_query` - used to count the rows of the underlying data to know if a cached partition is up to date
103    /// * `extract_query` - used to extract the source data into a cached partition
104    /// * `merge_partitions_query` - used to merge multiple partitions into a single one (and user queries which are one multiple partitions by default)
105    /// * `lake` - data lake
106    /// * `view_factory` - all views accessible to the `count_src_query`
107    /// * `session_configurator` - configurator for registering custom tables (e.g., JSON files)
108    /// * `update_group` - tells the daemon which view should be materialized and in what order
109    /// * `max_jit_src_bytes` - on-demand views only: the most source bytes one materialization step may read
110    pub async fn new(
111        runtime: Arc<RuntimeEnv>,
112        view_set_name: Arc<String>,
113        min_event_time_column: Arc<String>,
114        max_event_time_column: Arc<String>,
115        count_src_query: Arc<String>,
116        extract_query: Arc<String>,
117        merge_partitions_query: Arc<String>,
118        lake: Arc<DataLakeConnection>,
119        view_factory: Arc<ViewFactory>,
120        session_configurator: Arc<dyn SessionConfigurator>,
121        update_group: Option<i32>,
122        max_partition_delta_from_source: TimeDelta,
123        max_partition_delta_from_merge: TimeDelta,
124        max_jit_src_bytes: i64,
125    ) -> Result<Self> {
126        let null_part_provider = Arc::new(NullPartitionProvider {});
127        let lakehouse = Arc::new(LakehouseContext::new(lake.clone(), runtime.clone())?);
128        let ctx = make_session_context(
129            lakehouse,
130            null_part_provider,
131            SessionRange::NoPartitions,
132            view_factory.clone(),
133            session_configurator.clone(),
134            CallerContext::maintenance(),
135        )
136        .await
137        .with_context(|| "make_session_context")?;
138        let now_str = Utc::now().to_rfc3339();
139        let sql = extract_query
140            .replace("{begin}", &now_str)
141            .replace("{end}", &now_str);
142        // Guarded: an embedded DDL/DML statement in extract_query must never execute here (see
143        // `guarded_sql_options`'s doc comment) -- this is what makes the DDL validator's own check
144        // 10 hold even though construction runs before validation.
145        let extracted_df = ctx.sql_with_options(&sql, guarded_sql_options()).await?;
146        let schema = extracted_df.schema().inner().clone();
147        let merge_query = Arc::new(merge_partitions_query.replace("{source}", "source"));
148        let merger: Arc<dyn PartitionMerger> = Arc::new(QueryMerger::new(
149            view_factory.clone(),
150            session_configurator.clone(),
151            schema.clone(),
152            merge_query,
153        ));
154
155        Ok(Self {
156            view_set_name,
157            view_instance_id: Arc::new(String::from("global")),
158            min_event_time_column,
159            max_event_time_column,
160            count_src_query,
161            extract_query,
162            merge_partitions_query,
163            schema,
164            merger,
165            view_factory,
166            session_configurator,
167            update_group,
168            max_partition_delta_from_source,
169            max_partition_delta_from_merge,
170            sort_order: None,
171            ordered_merger: None,
172            on_demand_sources: vec![],
173            extract_sources: vec![],
174            max_jit_src_bytes,
175        })
176    }
177
178    /// An on-demand view has no `update_group`: the daemon never touches it and queries fill the
179    /// partitions covering their own range.
180    pub fn is_on_demand(&self) -> bool {
181        self.update_group.is_none()
182    }
183
184    /// Attaches the on-demand views this view reads and the views its extract query scans (see
185    /// `validate_view_definition`).
186    pub fn with_on_demand_sources(
187        mut self,
188        sources: Vec<Arc<dyn View>>,
189        extract_sources: Vec<ViewMetadata>,
190    ) -> Self {
191        self.on_demand_sources = sources;
192        self.extract_sources = extract_sources;
193        self
194    }
195
196    /// Declares that this view's partitions are internally sorted, ascending, by `columns` in
197    /// order. `columns` must be non-empty and every name must exist in this view's schema.
198    ///
199    /// This is a three-item view-author contract:
200    /// 1. Every declared sort column must appear among the merge query's `GROUP BY` keys (order
201    ///    within `GROUP BY` is irrelevant; extra keys degrade to `PartiallySorted`, not a blocking
202    ///    sort).
203    /// 2. Any enrichment join in the merge query must put the dimension table on the left and the
204    ///    ordered stream on the right -- `CollectLeft` buffers its left (build) input and inherits
205    ///    its output ordering from its right (probe) input, so the natural phrasing
206    ///    `(<ordered agg>) a LEFT JOIN dim d` reinstates a blocking sort.
207    /// 3. The merge query's aggregates must be composable over already-aggregated rows (e.g.
208    ///    `sum(count)`, not `count(*)`; no bare `avg` -- carry `sum` and `count` and divide at
209    ///    read time). `log_stats` is the in-repo model.
210    ///
211    /// Neither query needs an author-written `ORDER BY` any more: this builder forwards `columns`
212    /// to both sides, `QueryMerger` applies the sort to the merge query as a DataFusion
213    /// logical-plan node, and the extract path applies it to the extract query the same way (see
214    /// `sql_partition_spec::plan_sorted_extract`) -- no SQL text is derived or rewritten on either
215    /// side.
216    pub fn with_merge_sort_order(mut self, columns: Vec<Arc<String>>) -> Result<Self> {
217        if columns.is_empty() {
218            anyhow::bail!("with_merge_sort_order: columns must be non-empty");
219        }
220        for column in &columns {
221            self.schema.index_of(column.as_str()).with_context(|| {
222                format!(
223                    "with_merge_sort_order: column {column:?} not found in view {}'s schema",
224                    self.view_set_name
225                )
226            })?;
227        }
228        let scan_columns = sort_order_as_scan_columns(&columns);
229        let merge_query = Arc::new(self.merge_partitions_query.replace("{source}", "source"));
230        let ordered_merger: Arc<dyn PartitionMerger> = Arc::new(
231            QueryMerger::new(
232                self.view_factory.clone(),
233                self.session_configurator.clone(),
234                self.schema.clone(),
235                merge_query,
236            )
237            .with_merge_scan_ordering(ScanOrdering::PerFile {
238                columns: scan_columns,
239            }),
240        );
241        self.ordered_merger = Some(ordered_merger);
242        self.sort_order = Some(columns);
243        Ok(self)
244    }
245
246    /// The extract query as given to `SqlBatchView::new`, `{begin}`/`{end}` placeholders included.
247    pub fn get_extract_query(&self) -> Arc<String> {
248        self.extract_query.clone()
249    }
250
251    /// The merge query as given to `SqlBatchView::new`, `{source}` placeholder included.
252    pub fn get_merge_partitions_query(&self) -> Arc<String> {
253        self.merge_partitions_query.clone()
254    }
255
256    /// True when a merge sort order is declared and every partition in `partitions_to_merge`
257    /// certifies it (empty partitions certify vacuously -- see `Partition::certifies_sort_order`).
258    fn all_inputs_certify(&self, partitions_to_merge: &[Partition]) -> bool {
259        let Some(sort_order) = &self.sort_order else {
260            return false;
261        };
262        let columns = sort_order_as_scan_columns(sort_order);
263        partitions_to_merge
264            .iter()
265            .all(|p| p.certifies_sort_order(&columns))
266    }
267}
268
269#[async_trait]
270impl View for SqlBatchView {
271    fn get_view_set_name(&self) -> Arc<String> {
272        self.view_set_name.clone()
273    }
274
275    fn get_view_instance_id(&self) -> Arc<String> {
276        self.view_instance_id.clone()
277    }
278
279    #[span_fn(view = self.get_view_set_name())]
280    async fn make_batch_partition_spec(
281        &self,
282        lakehouse: Arc<LakehouseContext>,
283        existing_partitions: Arc<PartitionCache>,
284        insert_range: TimeRange,
285    ) -> Result<Arc<dyn PartitionSpec>> {
286        let view_meta = ViewMetadata {
287            view_set_name: self.get_view_set_name(),
288            view_instance_id: self.get_view_instance_id(),
289            file_schema_hash: self.get_file_schema_hash(),
290        };
291        let partitions_in_range = Arc::new(existing_partitions.filter_insert_range(insert_range));
292        let ctx = make_session_context(
293            lakehouse,
294            partitions_in_range.clone(),
295            SessionRange::Snapshot,
296            self.view_factory.clone(),
297            self.session_configurator.clone(),
298            CallerContext::maintenance(),
299        )
300        .await
301        .with_context(|| "make_session_context")?;
302
303        let count_src_sql = self
304            .count_src_query
305            .replace("{begin}", &insert_range.begin.to_rfc3339())
306            .replace("{end}", &insert_range.end.to_rfc3339());
307
308        let extract_sql = self
309            .extract_query
310            .replace("{begin}", &insert_range.begin.to_rfc3339())
311            .replace("{end}", &insert_range.end.to_rfc3339());
312
313        Ok(Arc::new(
314            fetch_sql_partition_spec(
315                ctx,
316                Arc::new(TrivialRecordBatchTransformer {}),
317                self.get_time_bounds(),
318                self.schema.clone(),
319                count_src_sql,
320                extract_sql,
321                view_meta,
322                insert_range,
323                self.sort_order
324                    .as_ref()
325                    .map(|columns| columns.iter().map(|c| c.to_string()).collect()),
326            )
327            .await
328            .with_context(|| "fetch_sql_partition_spec")?,
329        ))
330    }
331
332    fn get_file_schema_hash(&self) -> Vec<u8> {
333        let mut hasher = DefaultHasher::new();
334        self.schema.hash(&mut hasher);
335        hasher.finish().to_le_bytes().to_vec()
336    }
337
338    fn get_file_schema(&self) -> Arc<Schema> {
339        self.schema.clone()
340    }
341
342    async fn jit_update(
343        &self,
344        lakehouse: Arc<LakehouseContext>,
345        query_range: Option<TimeRange>,
346    ) -> Result<()> {
347        // `None` is a snapshot session, whose caller already refreshed the on-demand sources.
348        let (true, Some(query_range)) = (self.is_on_demand(), query_range) else {
349            return Ok(());
350        };
351        update_on_demand_view(
352            lakehouse,
353            Arc::new(self.clone()),
354            &self.on_demand_sources,
355            &self.extract_sources,
356            self.max_jit_src_bytes,
357            query_range,
358        )
359        .await
360    }
361
362    fn make_time_filter(&self, begin: DateTime<Utc>, end: DateTime<Utc>) -> Result<Vec<Expr>> {
363        Ok(vec![
364            col(&*self.min_event_time_column).lt_eq(lit(datetime_to_scalar(end))),
365            col(&*self.max_event_time_column).gt_eq(lit(datetime_to_scalar(begin))),
366        ])
367    }
368
369    fn get_time_bounds(&self) -> Arc<dyn DataFrameTimeBounds> {
370        Arc::new(NamedColumnsTimeBounds::new(
371            self.min_event_time_column.clone(),
372            self.max_event_time_column.clone(),
373        ))
374    }
375
376    async fn register_table(&self, ctx: &SessionContext, table: MaterializedView) -> Result<()> {
377        let view_name = self.get_view_set_name().to_string();
378        let partitions_table_name = format!("__{view_name}__partitions");
379        ctx.register_table(
380            TableReference::Bare {
381                table: partitions_table_name.clone().into(),
382            },
383            Arc::new(table),
384        )?;
385        let df = ctx
386            .sql(
387                &self
388                    .merge_partitions_query
389                    .replace("{source}", &partitions_table_name),
390            )
391            .await?;
392        ctx.register_table(
393            TableReference::Bare {
394                table: view_name.into(),
395            },
396            df.into_view(),
397        )?;
398        Ok(())
399    }
400
401    async fn merge_partitions(
402        &self,
403        lakehouse: Arc<LakehouseContext>,
404        partitions_to_merge: Arc<Vec<Partition>>,
405        partitions_all_views: Arc<PartitionCache>,
406        insert_range: TimeRange,
407    ) -> Result<MergeQueryResult> {
408        // An all-empty source scans as an EmptyExec, whose SortExec is never elided -- taking the
409        // ordered path there would trip the plan-shape check's memory-regression warning on every
410        // quiet-day retry. So the ordered path additionally requires at least one non-empty input.
411        let any_non_empty = partitions_to_merge.iter().any(|p| !p.is_empty());
412        let merger = match &self.ordered_merger {
413            Some(ordered_merger)
414                if any_non_empty && self.all_inputs_certify(&partitions_to_merge) =>
415            {
416                ordered_merger
417            }
418            _ => &self.merger,
419        };
420        let res = merger
421            .execute_merge_query(
422                lakehouse,
423                partitions_to_merge,
424                partitions_all_views,
425                insert_range,
426            )
427            .await;
428        if let Err(e) = &res {
429            error!("{e:?}");
430        }
431        res
432    }
433
434    fn get_merged_partition_sort_order(
435        &self,
436        partitions_to_merge: &[Partition],
437    ) -> Option<Vec<String>> {
438        if self.ordered_merger.is_some() && self.all_inputs_certify(partitions_to_merge) {
439            self.sort_order
440                .as_ref()
441                .map(|columns| columns.iter().map(|c| c.to_string()).collect())
442        } else {
443            None
444        }
445    }
446
447    fn get_scan_output_ordering(&self) -> ScanOrdering {
448        match &self.sort_order {
449            Some(columns) => ScanOrdering::PerFile {
450                columns: sort_order_as_scan_columns(columns),
451            },
452            None => ScanOrdering::Unordered,
453        }
454    }
455
456    fn get_update_group(&self) -> Option<i32> {
457        self.update_group
458    }
459
460    fn requires_query_range(&self) -> bool {
461        self.is_on_demand()
462    }
463
464    fn get_max_partition_time_delta(&self, strategy: &PartitionCreationStrategy) -> TimeDelta {
465        match strategy {
466            PartitionCreationStrategy::Abort | PartitionCreationStrategy::CreateFromSource => {
467                self.max_partition_delta_from_source
468            }
469            PartitionCreationStrategy::MergeExisting(_partitions) => {
470                self.max_partition_delta_from_merge
471            }
472        }
473    }
474}