Skip to main content

micromegas_analytics/lakehouse/
materialized_view.rs

1use super::{
2    audience_guard::AudienceGuard, lakehouse_context::LakehouseContext,
3    partition_cache::QueryPartitionProvider,
4    partitioned_execution_plan::make_partitioned_execution_plan, query::SessionRange,
5    reader_factory::ReaderFactory, view::View,
6};
7use async_trait::async_trait;
8use datafusion::{
9    arrow::datatypes::SchemaRef,
10    catalog::{Session, TableProvider},
11    datasource::TableType,
12    error::DataFusionError,
13    logical_expr::{Expr, TableProviderFilterPushDown},
14    physical_plan::{ExecutionPlan, empty::EmptyExec},
15};
16use micromegas_ingestion::data_lake_connection::is_read_only_violation;
17use micromegas_tracing::prelude::*;
18use std::sync::Arc;
19
20/// A DataFusion `TableProvider` for materialized views.
21#[derive(Debug)]
22pub struct MaterializedView {
23    lakehouse: Arc<LakehouseContext>,
24    reader_factory: Arc<ReaderFactory>,
25    view: Arc<dyn View>,
26    part_provider: Arc<dyn QueryPartitionProvider>,
27    query_range: SessionRange,
28    /// The `view_instance(...)` scan-time audience check, run before `jit_update`.
29    /// `Some` only when this provider was built by `ViewInstanceTableFunction` -- a
30    /// caller-named instance. `None` for every server-constructed `MaterializedView`: the
31    /// implicitly-registered global tables (`query.rs::register_table`) and `OwnershipRewrite`'s
32    /// own `processes`/`streams` sources, which are the row-level filter's job to filter row-by-row and must
33    /// never be denied wholesale.
34    instance_guard: Option<Arc<AudienceGuard>>,
35}
36
37impl MaterializedView {
38    pub fn new(
39        lakehouse: Arc<LakehouseContext>,
40        reader_factory: Arc<ReaderFactory>,
41        view: Arc<dyn View>,
42        part_provider: Arc<dyn QueryPartitionProvider>,
43        query_range: SessionRange,
44        instance_guard: Option<Arc<AudienceGuard>>,
45    ) -> Self {
46        Self {
47            lakehouse,
48            reader_factory,
49            view,
50            part_provider,
51            query_range,
52            instance_guard,
53        }
54    }
55
56    pub fn get_view(&self) -> Arc<dyn View> {
57        self.view.clone()
58    }
59
60    /// Whether `AudienceGuard::authorize_view_instance` will resolve this view's instance id
61    /// against the caller's scope, and deny, before `scan` yields a row. True only for a
62    /// caller-named, non-`'global'` `view_instance(...)`: those take the guard's Uuid arm (or its
63    /// fail-closed fallthrough). `'global'` is excluded because the guard passes it unconditionally
64    /// -- global instances are row-filtered instead, including an on-demand view's, whose read
65    /// materializes global partitions under the maintenance caller.
66    ///
67    /// Deliberately does not mirror the guard's public-view-set arm: this accessor would still
68    /// return `true` for a public view set's instance, even though the guard passes it
69    /// unconditionally before ever reaching the Uuid arm. Harmless --
70    /// `OwnershipRewrite::predicate_for`'s own public-view-set check already returns `Ok(None)`
71    /// before this accessor is ever consulted, and both checks read
72    /// `IsolationConfig::public_view_sets`.
73    ///
74    /// Kept in step with `AudienceGuard::authorize_view_instance`'s arms; changing those means
75    /// revisiting this.
76    pub fn instance_is_audience_guarded(&self) -> bool {
77        self.instance_guard.is_some() && self.view.get_view_instance_id().as_str() != "global"
78    }
79}
80
81#[async_trait]
82impl TableProvider for MaterializedView {
83    fn schema(&self) -> SchemaRef {
84        self.view.get_file_schema()
85    }
86
87    fn table_type(&self) -> TableType {
88        TableType::Base
89    }
90
91    #[span_fn]
92    async fn scan(
93        &self,
94        state: &dyn Session,
95        projection: Option<&Vec<usize>>,
96        filters: &[Expr],
97        limit: Option<usize>,
98    ) -> datafusion::error::Result<Arc<dyn ExecutionPlan>> {
99        if let Some(guard) = &self.instance_guard {
100            guard
101                .authorize_view_instance(
102                    &self.view.get_view_set_name(),
103                    &self.view.get_view_instance_id(),
104                )
105                .await?;
106        }
107
108        let projected_schema = || match projection {
109            Some(indices) => self.schema().project(indices).map(Arc::new),
110            None => Ok(self.schema()),
111        };
112        match self.query_range {
113            SessionRange::NoPartitions => {
114                return Ok(Arc::new(EmptyExec::new(projected_schema()?)));
115            }
116            SessionRange::Unbounded if self.view.requires_query_range() => {
117                return Err(DataFusionError::External(
118                    format!(
119                        "{} is an on-demand view and needs a query time range (pass begin/end \
120                         with the query)",
121                        self.view.get_view_set_name()
122                    )
123                    .into(),
124                ));
125            }
126            SessionRange::Query(_) | SessionRange::Unbounded | SessionRange::Snapshot => {}
127        }
128        let query_range = self.query_range.query_range();
129
130        if let Err(e) = self
131            .view
132            .jit_update(self.lakehouse.clone(), query_range)
133            .await
134        {
135            if is_read_only_violation(&e) {
136                warn!(
137                    "jit_update failed on a read-only connection for {}/{}: {e:#}",
138                    self.view.get_view_set_name(),
139                    self.view.get_view_instance_id()
140                );
141                imetric!("jit_update_failed_read_only", "count", 1_u64);
142                return Err(DataFusionError::External(
143                    format!(
144                        "the lakehouse is on a read-only connection and the requested range needs \
145                         partitions that aren't materialized yet for {}/{}",
146                        self.view.get_view_set_name(),
147                        self.view.get_view_instance_id()
148                    )
149                    .into(),
150                ));
151            }
152            return Err(DataFusionError::External(format!("{e:#}").into()));
153        }
154
155        let partitions = self
156            .part_provider
157            .fetch(
158                &self.view.get_view_set_name(),
159                &self.view.get_view_instance_id(),
160                query_range,
161                self.view.get_file_schema_hash(),
162            )
163            .await
164            .map_err(|e| datafusion::error::DataFusionError::External(e.into()))?;
165        trace!("MaterializedView::scan nb_partitions={}", partitions.len());
166
167        make_partitioned_execution_plan(
168            self.schema(),
169            self.reader_factory.clone(),
170            state,
171            projection,
172            filters,
173            limit,
174            Arc::new(partitions),
175            &self.view.get_scan_output_ordering(),
176        )
177    }
178
179    /// Tell DataFusion to push filters down to the scan method
180    fn supports_filters_pushdown(
181        &self,
182        filters: &[&Expr],
183    ) -> datafusion::error::Result<Vec<TableProviderFilterPushDown>> {
184        // Inexact because the pruning can't handle all expressions and pruning
185        // is not done at the row level -- there may be rows in returned files
186        // that do not pass the filter
187        Ok(vec![TableProviderFilterPushDown::Inexact; filters.len()])
188    }
189}