Skip to main content

micromegas_analytics/lakehouse/
query.rs

1use super::{
2    answer::Answer,
3    check_view_merge_table_function::CheckViewMergeTableFunction,
4    deny_queries_table_function::DenyQueriesTableFunction,
5    get_payload_function::GetPayload,
6    lakehouse_context::LakehouseContext,
7    list_audience_grants_table_function::{GrantVisibility, ListAudienceGrantsTableFunction},
8    list_partitions_table_function::ListPartitionsTableFunction,
9    list_query_denials_table_function::ListQueryDenialsTableFunction,
10    list_view_set_definitions_table_function::ListViewSetDefinitionsTableFunction,
11    list_view_sets_table_function::ListViewSetsTableFunction,
12    materialize_partitions_table_function::MaterializePartitionsTableFunction,
13    parse_block_table_function::ParseBlockTableFunction,
14    partition::Partition,
15    partition_cache::QueryPartitionProvider,
16    partitioned_table_provider::PartitionedTableProvider,
17    perfetto_trace_table_function::PerfettoTraceTableFunction,
18    process_spans_table_function::ProcessSpansTableFunction,
19    reader_factory::ReaderFactory,
20    regenerate_partitions_table_function::RegeneratePartitionsTableFunction,
21    remove_query_denial_udf::make_remove_query_denial_udf,
22    retire_partition_by_file_udf::make_retire_partition_by_file_udf,
23    retire_partition_by_metadata_udf::make_retire_partition_by_metadata_udf,
24    retire_partitions_table_function::RetirePartitionsTableFunction,
25    session_configurator::SessionConfigurator,
26    view::View,
27    view_factory::ViewFactory,
28};
29use crate::{
30    lakehouse::{
31        audience_guard::AudienceGuard,
32        materialized_view::MaterializedView,
33        ownership_rewrite::OwnershipRewrite,
34        read_scope::{CallerContext, ReadScope},
35        table_scan_rewrite::TableScanRewrite,
36        view_instance_table_function::ViewInstanceTableFunction,
37    },
38    properties::{
39        properties_to_dict_udf::PropertiesToDict, properties_to_jsonb_udf::PropertiesToJsonb,
40    },
41    time::TimeRange,
42};
43use anyhow::{Context, Result};
44use datafusion::{
45    arrow::{array::RecordBatch, datatypes::SchemaRef},
46    common::TableReference,
47    datasource::DefaultTableSource,
48    execution::{context::SessionContext, object_store::ObjectStoreUrl},
49    logical_expr::{ScalarUDF, TableSource, async_udf::AsyncScalarUDF},
50    prelude::*,
51};
52use micromegas_tracing::prelude::*;
53use std::sync::Arc;
54
55/// What a session knows about the time range it serves. The range decides event-time pruning and
56/// range-driven JIT, and whether a view that needs a range may be read at all.
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub enum SessionRange {
59    /// User query over a time range: event-time pruning (`TableScanRewrite`) + JIT over it.
60    Query(TimeRange),
61    /// User query with no time range: no pruning; views that need a range refuse.
62    Unbounded,
63    /// Internal session over the caller's partition snapshot. The caller already brought on-demand
64    /// sources up to date for the snapshot's insert range, so no range-driven JIT runs here.
65    Snapshot,
66    /// Planning only: an explicit absence of partitions. Scans yield an empty plan with the
67    /// view's schema, with no partition fetch and no JIT.
68    NoPartitions,
69}
70
71impl SessionRange {
72    /// The range handed to `View::jit_update` and to the partition provider.
73    pub fn query_range(&self) -> Option<TimeRange> {
74        match self {
75            SessionRange::Query(range) => Some(*range),
76            SessionRange::Unbounded | SessionRange::Snapshot | SessionRange::NoPartitions => None,
77        }
78    }
79}
80
81#[span_fn]
82async fn register_table(
83    lakehouse: Arc<LakehouseContext>,
84    reader_factory: Arc<ReaderFactory>,
85    part_provider: Arc<dyn QueryPartitionProvider>,
86    query_range: SessionRange,
87    ctx: &SessionContext,
88    view: Arc<dyn View>,
89) -> Result<()> {
90    let table = MaterializedView::new(
91        lakehouse,
92        reader_factory,
93        view.clone(),
94        part_provider,
95        query_range,
96        None,
97    );
98    view.register_table(ctx, table).await
99}
100
101/// query_partitions_context returns a context to run queries using the partitions as the "source" table
102#[span_fn]
103pub async fn query_partitions_context(
104    lakehouse: &LakehouseContext,
105    schema: SchemaRef,
106    partitions: Arc<Vec<Partition>>,
107) -> Result<SessionContext> {
108    let table =
109        PartitionedTableProvider::new(schema, lakehouse.reader_factory().clone(), partitions);
110    let object_store_url = ObjectStoreUrl::parse("obj://lakehouse/").unwrap();
111    let ctx = SessionContext::new_with_config_rt(
112        lakehouse.session_config().await?,
113        lakehouse.runtime().clone(),
114    );
115    ctx.register_object_store(
116        object_store_url.as_ref(),
117        lakehouse.lake().blob_storage.inner(),
118    );
119    ctx.register_table(
120        TableReference::Bare {
121            table: "source".into(),
122        },
123        Arc::new(table),
124    )?;
125    register_extension_functions(&ctx);
126    Ok(ctx)
127}
128
129// query_partitions returns a dataframe, leaving the option of streaming the results
130#[span_fn]
131pub async fn query_partitions(
132    lakehouse: &LakehouseContext,
133    schema: SchemaRef,
134    partitions: Arc<Vec<Partition>>,
135    sql: &str,
136) -> Result<DataFrame> {
137    let ctx = query_partitions_context(lakehouse, schema, partitions).await?;
138    Ok(ctx.sql(sql).await?)
139}
140
141/// register functions that are part of the lakehouse architecture
142#[span_fn]
143pub fn register_lakehouse_functions(
144    ctx: &SessionContext,
145    lakehouse: Arc<LakehouseContext>,
146    part_provider: Arc<dyn QueryPartitionProvider>,
147    query_range: SessionRange,
148    view_factory: Arc<ViewFactory>,
149    caller: &CallerContext,
150    configurator: Arc<dyn SessionConfigurator>,
151) {
152    // The call-level guard: one guard, shared (via `Arc`) across every
153    // arg-addressed UDTF/UDF this call registers below -- `view_instance`, `process_spans`,
154    // `perfetto_trace_chunks`, `parse_block`, `get_payload`, and `list_partitions`' row filter.
155    // `ReadScope::All` makes every one of its checks a no-op, so this costs nothing for
156    // internal/maintenance callers or an auth-unset deployment.
157    let lakehouse_admin = caller.is_admin;
158    let audience_guard = Arc::new(AudienceGuard::new(
159        caller.read_scope.clone(),
160        lakehouse_admin,
161        caller.isolation_config.public_view_sets.clone(),
162        lakehouse.audience_index().clone(),
163    ));
164    ctx.register_udtf(
165        "view_instance",
166        Arc::new(ViewInstanceTableFunction::new(
167            lakehouse.clone(),
168            view_factory.clone(),
169            part_provider.clone(),
170            query_range,
171            audience_guard.clone(),
172        )),
173    );
174    ctx.register_udtf(
175        "list_partitions",
176        Arc::new(ListPartitionsTableFunction::new(
177            lakehouse.lake().clone(),
178            audience_guard.clone(),
179        )),
180    );
181    ctx.register_udtf(
182        "list_view_sets",
183        Arc::new(ListViewSetsTableFunction::new(view_factory.clone())),
184    );
185    // Caller-scoped, not admin-gated: registered for every caller, admin or not, with the
186    // visibility split decided here rather than inside the function -- an admin sees every
187    // row, a non-admin only the pairs their `grant_selectors` hold.
188    ctx.register_udtf(
189        "list_audience_grants",
190        Arc::new(ListAudienceGrantsTableFunction::new(
191            lakehouse.lake().db_pool.clone(),
192            if caller.is_admin {
193                GrantVisibility::All
194            } else {
195                GrantVisibility::Held(caller.grant_selectors.clone())
196            },
197        )),
198    );
199    ctx.register_udtf(
200        "perfetto_trace_chunks",
201        Arc::new(PerfettoTraceTableFunction::new(
202            lakehouse.clone(),
203            view_factory.clone(),
204            part_provider.clone(),
205            audience_guard.clone(),
206        )),
207    );
208    ctx.register_udtf(
209        "parse_block",
210        Arc::new(ParseBlockTableFunction::new(
211            lakehouse.clone(),
212            view_factory.clone(),
213            part_provider.clone(),
214            query_range,
215            audience_guard.clone(),
216        )),
217    );
218    ctx.register_udtf(
219        "process_spans",
220        Arc::new(ProcessSpansTableFunction::new(
221            lakehouse.clone(),
222            view_factory.clone(),
223            part_provider.clone(),
224            query_range,
225            audience_guard.clone(),
226        )),
227    );
228    ctx.register_udf(
229        AsyncScalarUDF::new(Arc::new(GetPayload::new(
230            lakehouse.lake().clone(),
231            audience_guard.clone(),
232        )))
233        .into_scalar_udf(),
234    );
235    if lakehouse_admin {
236        ctx.register_udtf(
237            "retire_partitions",
238            Arc::new(RetirePartitionsTableFunction::new(lakehouse.lake().clone())),
239        );
240        ctx.register_udtf(
241            "materialize_partitions",
242            Arc::new(MaterializePartitionsTableFunction::new(
243                lakehouse.clone(),
244                view_factory.clone(),
245            )),
246        );
247        ctx.register_udtf(
248            "regenerate_partitions",
249            Arc::new(RegeneratePartitionsTableFunction::new(
250                lakehouse.clone(),
251                view_factory.clone(),
252            )),
253        );
254        ctx.register_udf(
255            make_retire_partition_by_file_udf(lakehouse.lake().clone()).into_scalar_udf(),
256        );
257        ctx.register_udf(
258            make_retire_partition_by_metadata_udf(lakehouse.lake().clone()).into_scalar_udf(),
259        );
260        // Admin-managed query deny list: same admin gate as the five functions above.
261        ctx.register_udtf(
262            "list_query_denials",
263            Arc::new(ListQueryDenialsTableFunction::new(
264                lakehouse.query_denials().clone(),
265            )),
266        );
267        ctx.register_udtf(
268            "deny_queries",
269            Arc::new(DenyQueriesTableFunction::new(
270                lakehouse.query_denials().clone(),
271                caller.identity.clone(),
272            )),
273        );
274        ctx.register_udf(
275            make_remove_query_denial_udf(lakehouse.query_denials().clone()).into_scalar_udf(),
276        );
277        // Reads `lakehouse_view_set_definitions` straight from Postgres, so an admin can see a
278        // definition that exists on disk but failed to load, and adds the built-in view sets.
279        ctx.register_udtf(
280            "list_view_set_definitions",
281            Arc::new(ListViewSetDefinitionsTableFunction::new(
282                lakehouse.lake().clone(),
283                view_factory.clone(),
284            )),
285        );
286        // Plans a definition's merge as the daemon would, so it needs the same session
287        // configurator the real sessions use.
288        ctx.register_udtf(
289            "check_view_merge",
290            Arc::new(CheckViewMergeTableFunction::new(
291                lakehouse.clone(),
292                view_factory.clone(),
293                configurator,
294            )),
295        );
296    }
297}
298
299/// register functions that are not depended on the lakehouse architecture
300#[span_fn]
301pub fn register_extension_functions(ctx: &SessionContext) {
302    ctx.register_udf(ScalarUDF::from(PropertiesToDict::new()));
303    ctx.register_udf(ScalarUDF::from(PropertiesToJsonb::new()));
304    micromegas_datafusion_extensions::register_extension_udfs(ctx);
305}
306
307#[span_fn]
308pub fn register_functions(
309    ctx: &SessionContext,
310    lakehouse: Arc<LakehouseContext>,
311    part_provider: Arc<dyn QueryPartitionProvider>,
312    query_range: SessionRange,
313    view_factory: Arc<ViewFactory>,
314    caller: &CallerContext,
315    configurator: Arc<dyn SessionConfigurator>,
316) {
317    register_lakehouse_functions(
318        ctx,
319        lakehouse,
320        part_provider,
321        query_range,
322        view_factory,
323        caller,
324        configurator,
325    );
326    register_extension_functions(ctx);
327}
328
329#[span_fn]
330pub async fn make_session_context(
331    lakehouse: Arc<LakehouseContext>,
332    part_provider: Arc<dyn QueryPartitionProvider>,
333    query_range: SessionRange,
334    view_factory: Arc<ViewFactory>,
335    configurator: Arc<dyn SessionConfigurator>,
336    caller: CallerContext,
337) -> Result<SessionContext> {
338    // Disable page index reading for backward compatibility with legacy Parquet files
339    // Legacy files may have incomplete ColumnIndex metadata (missing null_pages field)
340    // which causes errors in DataFusion 51+ with Arrow 57.0 when reading page indexes
341    let config = lakehouse
342        .session_config()
343        .await?
344        .set_bool("datafusion.execution.parquet.enable_page_index", false)
345        // Populate `Diagnostic`/`Span` on plan-time errors (unknown column, ambiguous
346        // reference, type mismatch, ...) so a caller-facing message can point at a
347        // line/column in their SQL text instead of just naming the problem. Off by
348        // default in DataFusion.
349        .set_bool("datafusion.sql_parser.collect_spans", true)
350        .with_information_schema(true);
351    let ctx = SessionContext::new_with_config_rt(config, lakehouse.runtime().clone());
352    if let SessionRange::Query(range) = &query_range {
353        ctx.add_analyzer_rule(Arc::new(TableScanRewrite::new(*range)));
354    }
355    let object_store_url = ObjectStoreUrl::parse("obj://lakehouse/").unwrap();
356    let object_store = lakehouse.lake().blob_storage.inner();
357    ctx.register_object_store(object_store_url.as_ref(), object_store);
358    let reader_factory = lakehouse.reader_factory().clone();
359    register_functions(
360        &ctx,
361        lakehouse.clone(),
362        part_provider.clone(),
363        query_range,
364        view_factory.clone(),
365        &caller,
366        configurator.clone(),
367    );
368    for view in view_factory.get_global_views() {
369        register_table(
370            lakehouse.clone(),
371            reader_factory.clone(),
372            part_provider.clone(),
373            query_range,
374            &ctx,
375            view.clone(),
376        )
377        .await?;
378    }
379    if caller.read_scope != ReadScope::All {
380        // ReadScope::All is the internal/maintenance marker -- OwnershipRewrite would no-op for
381        // it anyway, so skip resolving `processes`/`streams` sources and registering the rule
382        // entirely rather than requiring every ReadScope::All caller's ViewFactory to carry them.
383        //
384        // Must be registered *after* the TableScanRewrite registration above (`SessionRange::Query`
385        // block): TableScanRewrite::analyze walks the whole plan with transform_up_with_subqueries
386        // and would time-bound the audience lookup's own processes/streams scans if it ran after
387        // OwnershipRewrite injected them (analyzer rules each run exactly once, in registration
388        // order). The audience lookup must stay time-unbounded (`SessionRange::Unbounded` below).
389        let processes_view = view_factory.get_global_view("processes").with_context(
390            || "OwnershipRewrite requires the `processes` global view to be registered",
391        )?;
392        let streams_view = view_factory.get_global_view("streams").with_context(
393            || "OwnershipRewrite requires the `streams` global view to be registered",
394        )?;
395        let processes_source: Arc<dyn TableSource> =
396            Arc::new(DefaultTableSource::new(Arc::new(MaterializedView::new(
397                lakehouse.clone(),
398                reader_factory.clone(),
399                processes_view,
400                part_provider.clone(),
401                SessionRange::Unbounded,
402                None,
403            ))));
404        let streams_source: Arc<dyn TableSource> =
405            Arc::new(DefaultTableSource::new(Arc::new(MaterializedView::new(
406                lakehouse.clone(),
407                reader_factory.clone(),
408                streams_view,
409                part_provider.clone(),
410                SessionRange::Unbounded,
411                None,
412            ))));
413        ctx.add_analyzer_rule(Arc::new(OwnershipRewrite::new(
414            caller.read_scope.clone(),
415            caller.isolation_config.public_view_sets.clone(),
416            processes_source,
417            streams_source,
418        )));
419    }
420    // Apply custom configuration
421    configurator.configure(&ctx).await?;
422    Ok(ctx)
423}
424
425#[span_fn]
426pub async fn query(
427    lakehouse: Arc<LakehouseContext>,
428    part_provider: Arc<dyn QueryPartitionProvider>,
429    query_range: SessionRange,
430    sql: &str,
431    view_factory: Arc<ViewFactory>,
432    configurator: Arc<dyn SessionConfigurator>,
433    caller: CallerContext,
434) -> Result<Answer> {
435    info!("query sql={sql}");
436    let ctx = make_session_context(
437        lakehouse,
438        part_provider,
439        query_range,
440        view_factory,
441        configurator,
442        caller,
443    )
444    .await
445    .with_context(|| "make_session_context")?;
446    let df = ctx.sql(sql).await?;
447    let schema = df.schema().inner().clone();
448    let batches: Vec<RecordBatch> = df.collect().await?;
449    Ok(Answer::new(schema, batches))
450}