Skip to main content

micromegas_analytics/lakehouse/
view.rs

1use super::{
2    batch_update::PartitionCreationStrategy,
3    dataframe_time_bounds::DataFrameTimeBounds,
4    lakehouse_context::LakehouseContext,
5    materialized_view::MaterializedView,
6    merge::{MergeQueryResult, PartitionMerger, QueryMerger},
7    partition::Partition,
8    partition_cache::PartitionCache,
9    partitioned_execution_plan::ScanOrdering,
10    session_configurator::NoOpSessionConfigurator,
11    view_factory::ViewFactory,
12};
13use crate::{response_writer::Logger, time::TimeRange};
14use anyhow::Result;
15use async_trait::async_trait;
16use chrono::{DateTime, TimeDelta, Utc};
17use datafusion::{
18    arrow::datatypes::Schema, common::TableReference, logical_expr::Expr, prelude::*,
19};
20use micromegas_ingestion::data_lake_connection::DataLakeConnection;
21use std::fmt::Debug;
22use std::sync::Arc;
23
24/// A trait for defining a partition specification.
25#[async_trait]
26pub trait PartitionSpec: Send + Sync + Debug {
27    /// Returns true if the partition is empty.
28    fn is_empty(&self) -> bool;
29    /// Returns a hash of the source data.
30    fn get_source_data_hash(&self) -> Vec<u8>;
31    /// Writes the partition to the data lake.
32    async fn write(&self, lake: Arc<DataLakeConnection>, logger: Arc<dyn Logger>) -> Result<()>;
33
34    /// Writes the partition file without registering it, and returns the unregistered
35    /// `Partition`. The caller registers it (see `insert_partitions_replacing`) or deletes the
36    /// file.
37    async fn write_file(
38        &self,
39        _lake: Arc<DataLakeConnection>,
40        _logger: Arc<dyn Logger>,
41    ) -> Result<Partition> {
42        anyhow::bail!("write_file is not supported for this partition spec")
43    }
44}
45
46/// Metadata about a view.
47#[derive(Debug, Clone)]
48pub struct ViewMetadata {
49    pub view_set_name: Arc<String>,
50    pub view_instance_id: Arc<String>,
51    pub file_schema_hash: Vec<u8>,
52}
53
54/// A column an ordering is expressed over (ascending unless `descending`).
55#[derive(Clone, Debug)]
56pub struct ScanSortColumn {
57    pub column: Arc<String>,
58    pub descending: bool,
59}
60
61/// A trait for defining a view.
62#[async_trait]
63pub trait View: std::fmt::Debug + Send + Sync {
64    /// name of the table from the user's perspective
65    fn get_view_set_name(&self) -> Arc<String>;
66
67    /// get_view_instance_id can be a process_id, a stream_id or 'global'.
68    fn get_view_instance_id(&self) -> Arc<String>;
69
70    /// make_batch_partition_spec determines what should be found in an up to date partition.
71    /// The resulting PartitionSpec can be used to validate existing partitions are create a new one.
72    async fn make_batch_partition_spec(
73        &self,
74        lakehouse: Arc<LakehouseContext>,
75        existing_partitions: Arc<PartitionCache>,
76        insert_range: TimeRange,
77    ) -> Result<Arc<dyn PartitionSpec>>;
78
79    /// get_file_schema_hash returns a hash (can be a version number, version string, etc.) that allows
80    /// to identify out of date partitions.
81    fn get_file_schema_hash(&self) -> Vec<u8>;
82
83    /// get_file_schema returns the schema of the partition file in object storage
84    fn get_file_schema(&self) -> Arc<Schema>;
85
86    /// jit_update creates or updates process-specific partitions before a query
87    async fn jit_update(
88        &self,
89        lakehouse: Arc<LakehouseContext>,
90        query_range: Option<TimeRange>,
91    ) -> Result<()>;
92
93    /// make_time_filter returns a set of expressions that will filter out the rows of the partition
94    /// outside the time range requested.
95    fn make_time_filter(&self, _begin: DateTime<Utc>, _end: DateTime<Utc>) -> Result<Vec<Expr>>;
96
97    // a view must provide a way to compute the time bounds of a DataFrame corresponding to its schema
98    fn get_time_bounds(&self) -> Arc<dyn DataFrameTimeBounds>;
99
100    /// register the table in the SessionContext
101    async fn register_table(&self, ctx: &SessionContext, table: MaterializedView) -> Result<()> {
102        let view_set_name = self.get_view_set_name().to_string();
103        ctx.register_table(
104            TableReference::Bare {
105                table: view_set_name.into(),
106            },
107            Arc::new(table),
108        )?;
109        Ok(())
110    }
111
112    async fn merge_partitions(
113        &self,
114        lakehouse: Arc<LakehouseContext>,
115        partitions_to_merge: Arc<Vec<Partition>>,
116        partitions_all_views: Arc<PartitionCache>,
117        insert_range: TimeRange,
118    ) -> Result<MergeQueryResult> {
119        let merge_query = Arc::new(String::from("SELECT * FROM source;"));
120        let empty_view_factory = Arc::new(ViewFactory::new(vec![]));
121        let merger = QueryMerger::new(
122            empty_view_factory,
123            Arc::new(NoOpSessionConfigurator),
124            self.get_file_schema(),
125            merge_query,
126        );
127        merger
128            .execute_merge_query(
129                lakehouse,
130                partitions_to_merge,
131                partitions_all_views,
132                insert_range,
133            )
134            .await
135    }
136
137    /// Returns the sort guarantee a merge of `partitions_to_merge` will actually produce, to be
138    /// recorded as the resulting partition's `Partition::sort_order` (see
139    /// `merge::create_merged_partition`).
140    ///
141    /// This is a distinct concept from `get_scan_output_ordering()`: that one is a trusted
142    /// scan-ordering declaration consumed during physical planning, while this one is a record of
143    /// what a specific merge actually produced, computed purely from the input partitions (before
144    /// `merge_partitions` runs) and independent of whether DataFusion's elision optimization
145    /// happened to succeed for this particular run.
146    ///
147    /// Default: `None` -- no guarantee recorded, ignoring the argument.
148    fn get_merged_partition_sort_order(
149        &self,
150        _partitions_to_merge: &[Partition],
151    ) -> Option<Vec<String>> {
152        None
153    }
154
155    /// tells the daemon which view should be materialized and in what order
156    fn get_update_group(&self) -> Option<i32>;
157
158    /// True when the view fills its partitions from the query's own time range, so a query with
159    /// no range would serve only whatever earlier reads happened to leave behind.
160    fn requires_query_range(&self) -> bool {
161        false
162    }
163
164    /// allow the view to subdivide the requested partition
165    fn get_max_partition_time_delta(&self, _strategy: &PartitionCreationStrategy) -> TimeDelta {
166        TimeDelta::days(1)
167    }
168
169    /// Declares an ordering the view's partition scan *already* emits, letting DataFusion
170    /// elide redundant `Sort` nodes for queries that `ORDER BY` these columns.
171    ///
172    /// **A large or memory-heavy merge is not, on its own, a reason to declare an ordering here.**
173    /// Every `QueryMerger` merge scans its source partitions with a single sequential reader
174    /// regardless of what this method returns (`make_merge_session_context`,
175    /// `tasks/1491_merge_scan_memory_plan.md`), so a view with no natural sort contract gets a
176    /// bounded-memory merge for free, with no ordering guarantee to maintain. Reach for a declared
177    /// ordering only when a *query-side* need justifies it -- eliding a `Sort` for queries that
178    /// already `ORDER BY` these columns, or (via `PerFile`) a streaming k-way merge that must
179    /// preserve per-file order across an aggregation -- not to bound a merge's memory.
180    ///
181    /// Returning a non-`Unordered` value is a correctness contract the view must guarantee, and
182    /// its shape depends on which variant is returned:
183    /// - `Concatenated { columns, .. }`: rows within each partition file are already sorted by
184    ///   `columns`, the leading column is the view's min-event-time column, and partition
185    ///   event-time ranges are non-overlapping (so files concatenate in globally-sorted order).
186    ///   For `ThreadSpansView`, the *rows-sorted-within-a-file* half is obtained from JIT
187    ///   partitions being grouped under `jit_partitions::BlockOrder::EventTime`:
188    ///   `group_blocks_into_partitions` sorts a segment's blocks by event time and only cuts at
189    ///   insert-safe points (see its docs), so within a segment blocks land in event order rather
190    ///   than relying on an unenforced assumption about registration order, and
191    ///   `thread_spans_view::ensure_begin_non_decreasing` checks the resulting batch at write
192    ///   time.
193    ///
194    ///   The *partition-ranges-don't-overlap* half is **not** established by that grouping alone --
195    ///   a partition's declared event-time bounds come from its blocks' `begin_ticks`/`end_ticks`,
196    ///   not from the rows -- but by design both producers' consecutive blocks now *touch* exactly:
197    ///   - Both `micromegas_tracing::dispatch`'s four flush paths and the Unreal producer
198    ///     (`MicromegasTracing/Private/Dispatch.cpp`) take a single shared timestamp per flush and
199    ///     use it for both the outgoing block's close and the replacement block's `begin`, so
200    ///     `block[k].end_ticks == block[k+1].begin_ticks` by construction. This is the design intent
201    ///     the shared boundary stamp exists for: it lets call trees merge seamlessly across the cut
202    ///     (`group_contiguous_block_chains` treats touching blocks as chain-connected).
203    ///   - Data from `micromegas_tracing` versions predating that fix (or any other producer that
204    ///     stamps two separate timestamps) can still strictly overlap at block boundaries -- this is
205    ///     a legacy producer bug, not a supported producer shape, but the server tolerates it: the
206    ///     view records `max_sort_key_time` (the true max leading-sort-column value, exact per
207    ///     partition), and `partitioned_execution_plan::partition_bounds` reads that in preference
208    ///     to `max_event_time` for the non-overlap check, which the swap-window argument in
209    ///     `tasks/completed/thread_spans_segment_boundary_overlap_plan.md` shows can never trip for cuts at
210    ///     block boundaries of either producer. Partitions written before that column existed (or by
211    ///     a view that never populates it) fall back to the old, looser `max_event_time` bound, which
212    ///     is self-healing rather than a permanent gap: `ThreadSpansView::SCHEMA_VERSION`'s bump makes
213    ///     every pre-existing partition stale by schema hash, so it rebuilds -- carrying
214    ///     `max_sort_key_time` -- automatically on its next query, no admin `retire_partitions` call
215    ///     required.
216    ///
217    ///   Two residual caveats therefore remain, both backstopped by
218    ///   `sort_and_check_non_overlapping` (`partitioned_execution_plan.rs`) failing the query
219    ///   loudly rather than returning wrong rows: an insert-time inversion straddling a JIT
220    ///   *segment* boundary (segments are still grouped independently, see
221    ///   `generate_stream_jit_partitions`), which produces a genuine row-level overlap that the
222    ///   check correctly rejects; and TSC-frequency re-estimation drift across materialization
223    ///   epochs for `tsc_frequency == 0` processes, which can skew bounds written under different
224    ///   converters.
225    /// - `PerFile { columns }`: rows within each partition file are already sorted, ascending, by
226    ///   `columns`, but partitions may overlap each other arbitrarily on those columns. A false
227    ///   declaration here is not merely mis-ordered rows but, under order-aware aggregation, wrong
228    ///   aggregate results (groups closed early, duplicate group keys) -- see
229    ///   `SqlBatchView::with_merge_sort_order`. What makes declaring this safe is the
230    ///   recorded-`sort_order` certification gate inside `make_partitioned_execution_plan`: every
231    ///   non-empty partition must certify `columns` before the declaration reaches DataFusion at
232    ///   all.
233    ///
234    /// Default: `Unordered` (no declared ordering — DataFusion sorts as usual).
235    fn get_scan_output_ordering(&self) -> ScanOrdering {
236        ScanOrdering::Unordered
237    }
238
239    /// Ascending columns this view's partitions are written sorted by, as reported by
240    /// `list_view_sets()`. Informational only -- planning reads `get_scan_output_ordering()`.
241    fn get_reported_sort_order(&self) -> Option<Vec<String>> {
242        self.get_scan_output_ordering().sort_columns()
243    }
244}
245
246impl dyn View {
247    pub fn get_meta(&self) -> ViewMetadata {
248        ViewMetadata {
249            view_set_name: self.get_view_set_name(),
250            view_instance_id: self.get_view_instance_id(),
251            file_schema_hash: self.get_file_schema_hash(),
252        }
253    }
254}