Skip to main content

micromegas_analytics/lakehouse/
view_definition.rs

1//! The normalized shape of a DDL-defined (or seeded) materialized view -- the three queries plus
2//! every option -- and the one `validate_view_definition` function shared by the DDL executor
3//! (`rust/public/src/servers/view_ddl.rs`) and the registry loader (`view_registry.rs`), so a
4//! definition the loader would skip can never be accepted at `CREATE` time in the first place.
5
6use super::{
7    lakehouse_context::LakehouseContext,
8    materialized_view::MaterializedView,
9    partition_cache::NullPartitionProvider,
10    query::{SessionRange, make_session_context},
11    read_scope::CallerContext,
12    session_configurator::{NoOpSessionConfigurator, SessionConfigurator},
13    sql_batch_view::{SqlBatchView, guarded_sql_options},
14    sql_partition_spec::plan_sorted_extract,
15    view::{ScanSortColumn, View, ViewMetadata},
16    view_factory::ViewFactory,
17};
18use crate::time::TimeRange;
19use anyhow::{Context, Result};
20use chrono::{TimeDelta, Utc};
21use datafusion::{
22    arrow::datatypes::{DataType, Schema, TimeUnit},
23    common::{
24        TableReference,
25        tree_node::{TreeNode, TreeNodeRecursion},
26    },
27    datasource::{DefaultTableSource, MemTable},
28    execution::runtime_env::RuntimeEnv,
29    logical_expr::{Expr, LogicalPlan, TableScan, Volatility, expr::ScalarFunction},
30};
31use micromegas_ingestion::data_lake_connection::DataLakeConnection;
32use serde::{Deserialize, Serialize};
33use std::sync::Arc;
34
35/// The non-query, non-`update_group` options a `ViewDefinition` carries, serialized as JSON in
36/// `lakehouse_view_set_definitions.view_options`. `update_group` lives in its own column instead
37/// (reload() sorts and the registry loader projects on it), and `definition_sql` is the verbatim
38/// DDL text kept for display/audit only -- neither belongs here.
39#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
40pub struct ViewOptions {
41    pub min_time_column: String,
42    pub max_time_column: String,
43    pub source_partition_delta: String,
44    pub merge_partition_delta: String,
45    pub merge_sort_order: Option<Vec<String>>,
46    #[serde(default, skip_serializing_if = "Option::is_none")]
47    pub description: Option<String>,
48    /// On-demand views only: the most source data, as a `'<n> <unit>'` byte size, one
49    /// materialization step may read. `None` means [`DEFAULT_MAX_JIT_SRC_DATA`].
50    #[serde(default, skip_serializing_if = "Option::is_none")]
51    pub max_jit_src_data: Option<String>,
52}
53
54/// The `max_jit_src_data` of an on-demand view that doesn't set one (1 GiB).
55pub const DEFAULT_MAX_JIT_SRC_DATA: i64 = 1024 * 1024 * 1024;
56
57/// The normalized shape of a `CREATE MATERIALIZED VIEW` definition -- every option plus the three
58/// queries -- independent of whether it arrived over DDL or was seeded by a migration
59/// (`log_stats_view.rs`'s `log_stats_view_definition`).
60#[derive(Debug, Clone, PartialEq)]
61pub struct ViewDefinition {
62    pub view_set_name: String,
63    pub extract_query: String,
64    pub count_src_query: String,
65    pub merge_partitions_query: String,
66    /// `None` marks an on-demand view: the maintenance daemon never touches it, queries fill the
67    /// partitions covering their own range.
68    pub update_group: Option<i32>,
69    pub options: ViewOptions,
70}
71
72/// Parses a `"<n> <unit>"` string (e.g. `"1 day"`, `"2 hours"`) into a `TimeDelta`. Accepted units,
73/// singular or plural: `second(s)`, `minute(s)`, `hour(s)`, `day(s)`.
74pub fn parse_time_delta(s: &str) -> Result<TimeDelta> {
75    let s = s.trim();
76    let (num_str, unit) = s
77        .split_once(char::is_whitespace)
78        .with_context(|| format!("parse_time_delta: expected '<n> <unit>', got {s:?}"))?;
79    let n: i64 = num_str
80        .trim()
81        .parse()
82        .with_context(|| format!("parse_time_delta: invalid integer {num_str:?} in {s:?}"))?;
83    if n <= 0 {
84        anyhow::bail!("parse_time_delta: expected a positive integer, got {n} in {s:?}");
85    }
86    match unit.trim().to_lowercase().as_str() {
87        "second" | "seconds" => Ok(TimeDelta::seconds(n)),
88        "minute" | "minutes" => Ok(TimeDelta::minutes(n)),
89        "hour" | "hours" => Ok(TimeDelta::hours(n)),
90        "day" | "days" => Ok(TimeDelta::days(n)),
91        other => anyhow::bail!("parse_time_delta: unknown unit {other:?} in {s:?}"),
92    }
93}
94
95/// Parses a `"<n> <unit>"` string (e.g. `"1 GB"`, `"512 mb"`) into a byte count. Accepted units,
96/// case insensitive and base 1024: `B`, `KB`, `MB`, `GB`.
97pub fn parse_byte_size(s: &str) -> Result<i64> {
98    let s = s.trim();
99    let (num_str, unit) = s
100        .split_once(char::is_whitespace)
101        .with_context(|| format!("parse_byte_size: expected '<n> <unit>', got {s:?}"))?;
102    let n: i64 = num_str
103        .trim()
104        .parse()
105        .with_context(|| format!("parse_byte_size: invalid integer {num_str:?} in {s:?}"))?;
106    if n <= 0 {
107        anyhow::bail!("parse_byte_size: expected a positive integer, got {n} in {s:?}");
108    }
109    let multiplier: i64 = match unit.trim().to_lowercase().as_str() {
110        "b" => 1,
111        "kb" => 1024,
112        "mb" => 1024 * 1024,
113        "gb" => 1024 * 1024 * 1024,
114        other => anyhow::bail!("parse_byte_size: unknown unit {other:?} in {s:?}"),
115    };
116    n.checked_mul(multiplier)
117        .with_context(|| format!("parse_byte_size: {s:?} overflows"))
118}
119
120/// Fast, redundant, name-only pre-check -- also enforced, exhaustively, by
121/// [`validate_view_definition`], which remains the sole enforcement point since it is the only
122/// check that also runs on rows the registry loader reads back. `^[a-z_][a-z0-9_]{0,254}$`, not
123/// starting with `__` (which would collide with a view's own `__<name>__partitions` internal
124/// registration), and not `source` (substituted for `{source}` in every merge query and registered
125/// on every merge's session context).
126pub fn check_view_set_name_charset(name: &str) -> Result<()> {
127    let bytes = name.as_bytes();
128    let valid_charset = !bytes.is_empty()
129        && bytes.len() <= 255
130        && matches!(bytes[0], b'a'..=b'z' | b'_')
131        && bytes
132            .iter()
133            .all(|b| matches!(b, b'a'..=b'z' | b'0'..=b'9' | b'_'));
134    if !valid_charset {
135        anyhow::bail!("view set name {name:?} must match ^[a-z_][a-z0-9_]{{0,254}}$");
136    }
137    if name.starts_with("__") {
138        anyhow::bail!(
139            "view set name {name:?} must not start with '__' (reserved for internal partition tables)"
140        );
141    }
142    if name == "source" {
143        anyhow::bail!(
144            "view set name 'source' is reserved (substituted for '{{source}}' in merge queries)"
145        );
146    }
147    Ok(())
148}
149
150/// Builds the `SqlBatchView` a `ViewDefinition` describes. This *is* most of the validation --
151/// planning the extract query catches syntax errors, unknown tables and unknown columns, and
152/// yields the schema every later check inspects -- so callers (the DDL executor, the registry
153/// loader) must call this before [`validate_view_definition`], never after.
154pub async fn build_sql_batch_view(
155    def: &ViewDefinition,
156    runtime: Arc<RuntimeEnv>,
157    lake: Arc<DataLakeConnection>,
158    view_factory: Arc<ViewFactory>,
159    session_configurator: Arc<dyn SessionConfigurator>,
160) -> Result<SqlBatchView> {
161    let source_delta = parse_time_delta(&def.options.source_partition_delta)
162        .with_context(|| format!("{}: source_partition_delta", def.view_set_name))?;
163    let merge_delta = parse_time_delta(&def.options.merge_partition_delta)
164        .with_context(|| format!("{}: merge_partition_delta", def.view_set_name))?;
165    let max_jit_src_bytes = match &def.options.max_jit_src_data {
166        Some(s) => parse_byte_size(s)
167            .with_context(|| format!("{}: max_jit_src_data", def.view_set_name))?,
168        None => DEFAULT_MAX_JIT_SRC_DATA,
169    };
170    let view = SqlBatchView::new(
171        runtime,
172        Arc::new(def.view_set_name.clone()),
173        Arc::new(def.options.min_time_column.clone()),
174        Arc::new(def.options.max_time_column.clone()),
175        Arc::new(def.count_src_query.clone()),
176        Arc::new(def.extract_query.clone()),
177        Arc::new(def.merge_partitions_query.clone()),
178        lake,
179        view_factory,
180        session_configurator,
181        def.update_group,
182        source_delta,
183        merge_delta,
184        max_jit_src_bytes,
185    )
186    .await
187    .with_context(|| format!("building SqlBatchView for '{}'", def.view_set_name))?;
188    match &def.options.merge_sort_order {
189        Some(columns) if !columns.is_empty() => view
190            .with_merge_sort_order(columns.iter().map(|c| Arc::new(c.clone())).collect())
191            .with_context(|| format!("'{}': with_merge_sort_order", def.view_set_name)),
192        _ => Ok(view),
193    }
194}
195
196/// `Utf8View` is allowed because SQL `VARCHAR` casts produce it, and every `OwnershipRewrite`
197/// branch casts a non-`Utf8` ownership column to `Utf8` before comparing.
198fn is_stringy(dt: &DataType) -> bool {
199    matches!(dt, DataType::Utf8 | DataType::Utf8View)
200        || matches!(dt, DataType::Dictionary(_, inner) if **inner == DataType::Utf8)
201}
202
203/// Mirrors `OwnershipRewrite::predicate_for`'s own precedence -- an `audience` field, if
204/// present, governs regardless of whether a correctly-typed `process_id` field sits beside it.
205fn check_audience_reachable(schema: &Schema) -> Result<()> {
206    if let Ok(field) = schema.field_with_name("audience") {
207        if !is_stringy(field.data_type()) {
208            anyhow::bail!(
209                "extract_query's 'audience' column must be Utf8, Utf8View, or Dictionary(_, Utf8), got {:?}; \
210                 project it as e.g. arrow_cast(max(audience), 'Dictionary(Int32, Utf8)')",
211                field.data_type()
212            );
213        }
214        return Ok(());
215    }
216    if let Ok(field) = schema.field_with_name("process_id") {
217        if !is_stringy(field.data_type()) {
218            anyhow::bail!(
219                "extract_query's 'process_id' column must be Utf8, Utf8View, or Dictionary(_, Utf8), \
220                 got {:?}; project it as e.g. CAST(process_id AS VARCHAR)",
221                field.data_type()
222            );
223        }
224        return Ok(());
225    }
226    anyhow::bail!(
227        "extract_query's schema must carry an 'audience' column (preferred) or a 'process_id' \
228         column, so non-admin callers can be filtered by audience -- otherwise the view would \
229         silently serve every row to every caller with no error anywhere"
230    );
231}
232
233/// The resolved time column must exist and be a nanosecond timestamp.
234fn check_time_column(schema: &Schema, column: &str) -> Result<()> {
235    let field = schema
236        .field_with_name(column)
237        .with_context(|| format!("time column '{column}' not found in extract_query's schema"))?;
238    if !matches!(
239        field.data_type(),
240        DataType::Timestamp(TimeUnit::Nanosecond, _)
241    ) {
242        anyhow::bail!(
243            "time column '{column}' must be Timestamp(Nanosecond, _), got {:?}",
244            field.data_type()
245        );
246    }
247    Ok(())
248}
249
250/// `fetch_sql_partition_spec` requires a `count` field reachable as an `Int64Array`.
251fn check_count_query_schema(schema: &Schema) -> Result<()> {
252    let field = schema
253        .field_with_name("count")
254        .with_context(|| "count_src_query must project a 'count' column")?;
255    if field.data_type() != &DataType::Int64 {
256        anyhow::bail!(
257            "count_src_query's 'count' column must be Int64, got {:?}",
258            field.data_type()
259        );
260    }
261    Ok(())
262}
263
264/// Field names, types and order must match -- nullability and
265/// metadata are deliberately excluded (a `count(*)` extract column is non-nullable while its
266/// `sum(count)` merge counterpart is nullable, which the seeded `log_stats` calibration case
267/// exercises).
268fn check_schema_agrees(extract_schema: &Schema, merge_schema: &Schema) -> Result<()> {
269    let extract_fields: Vec<(&str, &DataType)> = extract_schema
270        .fields()
271        .iter()
272        .map(|f| (f.name().as_str(), f.data_type()))
273        .collect();
274    let merge_fields: Vec<(&str, &DataType)> = merge_schema
275        .fields()
276        .iter()
277        .map(|f| (f.name().as_str(), f.data_type()))
278        .collect();
279    if extract_fields != merge_fields {
280        anyhow::bail!(
281            "merge_partitions_query's output schema {merge_fields:?} disagrees with \
282             extract_query's {extract_fields:?} (name, type and order must match; nullability and \
283             metadata are ignored)"
284        );
285    }
286    Ok(())
287}
288
289/// Walks every `ScalarUDF` reachable from `plan` -- not just its top-level expressions,
290/// so a call nested inside another expression (e.g. `now()` inside `date_bin('1 minute',
291/// now())`) is still found -- and rejects the first whose `signature().volatility` is not
292/// `Immutable`.
293fn check_no_volatile_functions(plan: &LogicalPlan, label: &str) -> Result<()> {
294    let mut offender: Option<String> = None;
295    plan.apply_with_subqueries(|node| {
296        node.apply_expressions(|expr| {
297            expr.apply(|e| {
298                if offender.is_none()
299                    && let Expr::ScalarFunction(ScalarFunction { func, .. }) = e
300                    && func.signature().volatility != Volatility::Immutable
301                {
302                    offender = Some(func.name().to_string());
303                }
304                Ok(TreeNodeRecursion::Continue)
305            })
306        })
307    })?;
308    if let Some(name) = offender {
309        anyhow::bail!(
310            "{label} calls '{name}', a non-immutable function; its result would be frozen into a \
311             partition at materialization time (or, in count_src_query, corrupt freshness \
312             detection) instead of being recomputed"
313        );
314    }
315    Ok(())
316}
317
318/// Functions that change state: the four mutating table functions (all admin-gated)
319/// and the three admin-only scalar UDFs. Anything exposing a
320/// read-only surface (such as the MCP server) must refuse every name here.
321pub const MUTATING_FUNCTIONS: &[&str] = &[
322    "retire_partitions",
323    "materialize_partitions",
324    "regenerate_partitions",
325    "deny_queries",
326    "retire_partition_by_file",
327    "retire_partition_by_metadata",
328    "remove_query_denial",
329];
330
331/// Read-only table functions that a stored scan must still not call: their result depends on
332/// the caller or on arguments a stored definition cannot freeze.
333const STORED_SCAN_BANNED_READ_ONLY_FUNCTIONS: &[&str] =
334    &["view_instance", "process_spans", "perfetto_trace_chunks"];
335
336/// Whether a stored scan may not call `name`: every mutating function plus the read-only
337/// functions above, so a new entry in [`MUTATING_FUNCTIONS`] is covered here automatically.
338fn is_banned_from_stored_scans(name: &str) -> bool {
339    MUTATING_FUNCTIONS.contains(&name) || STORED_SCAN_BANNED_READ_ONLY_FUNCTIONS.contains(&name)
340}
341
342/// `ViewMetadata` has no `PartialEq`.
343fn same_view_metadata(a: &ViewMetadata, b: &ViewMetadata) -> bool {
344    a.view_set_name == b.view_set_name
345        && a.view_instance_id == b.view_instance_id
346        && a.file_schema_hash == b.file_schema_hash
347}
348
349/// Walks every `TableScan` reachable from `plan`, resolving each to a view set (to
350/// accumulate the highest `update_group` read) or to a banned table function name.
351///
352/// Returns a `datafusion::error::Result` (rather than this module's usual `anyhow::Result`) since
353/// it is called from inside `LogicalPlan::apply_with_subqueries`'s closure, which requires that
354/// exact type; callers outside that closure convert via `?` as usual (anyhow implements `From`
355/// for any `std::error::Error`, which `DataFusionError` is).
356fn walk_plan_for_scans(
357    plan: &LogicalPlan,
358    max_group: &mut Option<i32>,
359    mutating_hit: &mut Option<String>,
360    on_demand_sources: &mut Vec<Arc<dyn View>>,
361    scanned_sources: &mut Vec<ViewMetadata>,
362) -> datafusion::error::Result<()> {
363    plan.apply_with_subqueries(|node| {
364        if let LogicalPlan::TableScan(ts) = node {
365            inspect_scan(
366                ts,
367                max_group,
368                mutating_hit,
369                on_demand_sources,
370                scanned_sources,
371            )?;
372        }
373        Ok(TreeNodeRecursion::Continue)
374    })?;
375    Ok(())
376}
377
378fn inspect_scan(
379    ts: &TableScan,
380    max_group: &mut Option<i32>,
381    mutating_hit: &mut Option<String>,
382    on_demand_sources: &mut Vec<Arc<dyn View>>,
383    scanned_sources: &mut Vec<ViewMetadata>,
384) -> datafusion::error::Result<()> {
385    // Checked first, and unconditionally: `view_instance` resolves to a `MaterializedView` just
386    // like a well-behaved DDL view scan does (see `ViewInstanceTableFunction::call_with_args`),
387    // so the name check must run before the downcast branch below would otherwise `return Ok(())`
388    // and hide it.
389    // DataFusion's `TableFactor::Table` path (the one `foo('a', 'b')` call syntax actually takes,
390    // as opposed to the `TABLE(foo(...))` / `LATERAL` `TableFactor::Function` form) names the
391    // resulting scan `"{name}()"`, not `"{name}"` -- strip that suffix so the comparison below
392    // matches either form.
393    let raw_name = ts.table_name.table();
394    let leaf = raw_name
395        .strip_suffix("()")
396        .unwrap_or(raw_name)
397        .to_lowercase();
398    if mutating_hit.is_none() && is_banned_from_stored_scans(leaf.as_str()) {
399        *mutating_hit = Some(leaf);
400        return Ok(());
401    }
402    if let Some(default_source) = ts.source.downcast_ref::<DefaultTableSource>()
403        && let Some(mat_view) = default_source
404            .table_provider
405            .downcast_ref::<MaterializedView>()
406    {
407        let scanned = mat_view.get_view();
408        let scanned_meta = scanned.get_meta();
409        if !scanned_sources
410            .iter()
411            .any(|m| same_view_metadata(m, &scanned_meta))
412        {
413            scanned_sources.push(scanned_meta);
414        }
415        if let Some(group) = scanned.get_update_group() {
416            *max_group = Some(max_group.map_or(group, |m| m.max(group)));
417        }
418        if scanned.requires_query_range()
419            && scanned.get_view_instance_id().as_str() == "global"
420            && !on_demand_sources
421                .iter()
422                .any(|v| v.get_view_set_name() == scanned.get_view_set_name())
423        {
424            on_demand_sources.push(scanned);
425        }
426        return Ok(());
427    }
428    // A scan against a DDL/base SqlBatchView's user-visible name (not its
429    // `__<name>__partitions` form) resolves through a view-backed logical plan rather than a
430    // `MaterializedView` directly -- recurse into it to find the real scan.
431    if let Some(inner) = ts.source.get_logical_plan() {
432        return walk_plan_for_scans(
433            &inner,
434            max_group,
435            mutating_hit,
436            on_demand_sources,
437            scanned_sources,
438        );
439    }
440    Ok(())
441}
442
443/// Builds a session context mirroring `SqlBatchView::new`'s own -- `CallerContext::maintenance()`
444/// over `factory`, with the real `session_configurator` -- for checks that must see exactly what
445/// the daemon will plan against (extract_query, count_src_query, and the `table_exist` probe).
446async fn build_full_validation_ctx(
447    runtime: Arc<RuntimeEnv>,
448    lake: Arc<DataLakeConnection>,
449    factory: Arc<ViewFactory>,
450    session_configurator: Arc<dyn SessionConfigurator>,
451) -> Result<datafusion::execution::context::SessionContext> {
452    let lakehouse = Arc::new(LakehouseContext::new(lake, runtime)?);
453    make_session_context(
454        lakehouse,
455        Arc::new(NullPartitionProvider {}),
456        SessionRange::NoPartitions,
457        factory,
458        session_configurator,
459        CallerContext::maintenance(),
460    )
461    .await
462    .with_context(|| "make_session_context (full validation context)")
463}
464
465/// Builds the deliberately narrower session context `merge_partitions_query` is planned
466/// against: a non-admin caller (`CallerContext::internal()`) and `NoOpSessionConfigurator`
467/// regardless of what real configurator the deployment uses -- so a merge query naming an
468/// admin-gated UDTF or a `SessionConfigurator`-registered static table fails to plan here, for
469/// that reason, rather than resolving only because validation happened to run under a
470/// maintenance/admin caller.
471async fn build_narrow_validation_ctx(
472    runtime: Arc<RuntimeEnv>,
473    lake: Arc<DataLakeConnection>,
474    factory: Arc<ViewFactory>,
475) -> Result<datafusion::execution::context::SessionContext> {
476    let lakehouse = Arc::new(LakehouseContext::new(lake, runtime)?);
477    make_session_context(
478        lakehouse,
479        Arc::new(NullPartitionProvider {}),
480        SessionRange::NoPartitions,
481        factory,
482        Arc::new(NoOpSessionConfigurator),
483        CallerContext::internal(),
484    )
485    .await
486    .with_context(|| "make_session_context (narrow validation context)")
487}
488
489/// Every check runs before a definition's row is written, in this one function shared by the DDL
490/// executor and the registry loader -- so a definition the loader would skip can never be
491/// accepted at `CREATE` time in the first place. `view` must already be the result of
492/// [`build_sql_batch_view`] over `def` -- constructing it *is* most of the validation (it plans
493/// the extract query and yields the schema every check below inspects). `factory` is the factory
494/// `view` was built against -- every other definition, for the DDL executor, or the definitions
495/// the registry loader has folded in so far -- which the update-group ordering check and the
496/// on-demand source collection below read.
497///
498/// Returns, for `SqlBatchView::with_on_demand_sources`, the on-demand views the definition reads
499/// (a daemon-updated definition may not read one) and the metadata of every view its
500/// `extract_query` alone scans, daemon-maintained ones included: the merge and count queries can
501/// scan tables the extract never reads, and those bytes are not read by a materialization step.
502pub async fn validate_view_definition(
503    def: &ViewDefinition,
504    view: &SqlBatchView,
505    factory: &Arc<ViewFactory>,
506    runtime: Arc<RuntimeEnv>,
507    lake: Arc<DataLakeConnection>,
508    session_configurator: Arc<dyn SessionConfigurator>,
509) -> Result<(Vec<Arc<dyn View>>, Vec<ViewMetadata>)> {
510    let schema = view.get_file_schema();
511
512    check_view_set_name_charset(&def.view_set_name)?;
513    if factory.get_global_view(&def.view_set_name).is_some()
514        || factory.get_view_sets().contains_key(&def.view_set_name)
515    {
516        anyhow::bail!(
517            "'{}' is a code-driven view set and cannot be redefined by DDL",
518            def.view_set_name
519        );
520    }
521
522    // Placeholders, checked early since they're purely textual.
523    if !def.count_src_query.contains("{begin}") || !def.count_src_query.contains("{end}") {
524        anyhow::bail!("count_src_query must contain both '{{begin}}' and '{{end}}'");
525    }
526    if !def.merge_partitions_query.contains("{source}") {
527        anyhow::bail!("merge_partitions_query must contain '{{source}}'");
528    }
529
530    check_time_column(&schema, &def.options.min_time_column)?;
531    check_time_column(&schema, &def.options.max_time_column)?;
532
533    check_audience_reachable(&schema)?;
534
535    let full_ctx = build_full_validation_ctx(
536        runtime.clone(),
537        lake.clone(),
538        factory.clone(),
539        session_configurator.clone(),
540    )
541    .await?;
542    if full_ctx
543        .table_exist(def.view_set_name.as_str())
544        .unwrap_or(false)
545    {
546        anyhow::bail!(
547            "'{}' collides with a table already registered in the session (a static table?)",
548            def.view_set_name
549        );
550    }
551
552    // The merge query must plan, and its output schema must agree with the extract schema.
553    let narrow_ctx =
554        build_narrow_validation_ctx(runtime.clone(), lake.clone(), factory.clone()).await?;
555    let empty_source = Arc::new(
556        MemTable::try_new(schema.clone(), vec![vec![]])
557            .with_context(|| "building the empty source table for merge-query validation")?,
558    );
559    narrow_ctx
560        .register_table(
561            TableReference::Bare {
562                table: "source".into(),
563            },
564            empty_source,
565        )
566        .with_context(|| "registering the empty source table")?;
567    let merge_sql = def.merge_partitions_query.replace("{source}", "source");
568    let merge_df = narrow_ctx
569        .sql_with_options(&merge_sql, guarded_sql_options())
570        .await
571        .with_context(|| {
572            format!(
573                "planning merge_partitions_query for '{}'",
574                def.view_set_name
575            )
576        })?;
577    check_schema_agrees(&schema, merge_df.schema().as_arrow())?;
578
579    // The `{begin}`/`{end}`-substituted extract/count query texts the checks below all plan
580    // against. A zero-width range is enough -- these builds are never executed.
581    let now = Utc::now();
582    let now_str = now.to_rfc3339();
583    let extract_sql = def
584        .extract_query
585        .replace("{begin}", &now_str)
586        .replace("{end}", &now_str);
587    let count_sql = def
588        .count_src_query
589        .replace("{begin}", &now_str)
590        .replace("{end}", &now_str);
591
592    let extract_df = full_ctx
593        .sql_with_options(&extract_sql, guarded_sql_options())
594        .await
595        .with_context(|| format!("planning extract_query for '{}'", def.view_set_name))?;
596    let count_df = full_ctx
597        .sql_with_options(&count_sql, guarded_sql_options())
598        .await
599        .with_context(|| format!("planning count_src_query for '{}'", def.view_set_name))?;
600
601    check_count_query_schema(count_df.schema().as_arrow())?;
602
603    // Volatile-function and mutating-scan checks, over the three plans already built above --
604    // no extra planning cost.
605    let mut max_group: Option<i32> = None;
606    let mut mutating_hit: Option<String> = None;
607    let mut on_demand_sources: Vec<Arc<dyn View>> = vec![];
608    let mut extract_sources: Vec<ViewMetadata> = vec![];
609    for (label, plan) in [
610        ("extract_query", extract_df.logical_plan()),
611        ("merge_partitions_query", merge_df.logical_plan()),
612        ("count_src_query", count_df.logical_plan()),
613    ] {
614        check_no_volatile_functions(plan, label)?;
615        // Only the extract plan feeds the byte-sum source list.
616        let mut discarded = vec![];
617        let scanned_sources = if label == "extract_query" {
618            &mut extract_sources
619        } else {
620            &mut discarded
621        };
622        walk_plan_for_scans(
623            plan,
624            &mut max_group,
625            &mut mutating_hit,
626            &mut on_demand_sources,
627            scanned_sources,
628        )?;
629    }
630    if let Some(name) = mutating_hit {
631        anyhow::bail!(
632            "'{}' scans '{name}', a mutating or session-scoped table function, which cannot be \
633             stored in a materialized-view definition",
634            def.view_set_name
635        );
636    }
637    if let Some(update_group) = def.update_group {
638        if let Some(source) = on_demand_sources.first() {
639            anyhow::bail!(
640                "'{}' reads on-demand view '{}'; a daemon-updated view cannot read an on-demand one",
641                def.view_set_name,
642                source.get_view_set_name()
643            );
644        }
645        if let Some(max_group) = max_group
646            && update_group <= max_group
647        {
648            anyhow::bail!(
649                "'{}' has update_group {update_group}, which must be strictly greater than \
650                 {max_group}, the highest update_group among the view sets it reads",
651                def.view_set_name
652            );
653        }
654    }
655
656    // merge_sort_order, if declared, must apply and plan against extract_query.
657    if let Some(columns) = &def.options.merge_sort_order {
658        let scan_columns: Vec<ScanSortColumn> = columns
659            .iter()
660            .map(|c| ScanSortColumn {
661                column: Arc::new(c.clone()),
662                descending: false,
663            })
664            .collect();
665        let subject = format!("validation of '{}'", def.view_set_name);
666        let extract_df_for_sort = full_ctx
667            .sql_with_options(&extract_sql, guarded_sql_options())
668            .await
669            .with_context(|| format!("re-planning extract_query for '{}'", def.view_set_name))?;
670        plan_sorted_extract(
671            extract_df_for_sort,
672            Some(&scan_columns),
673            &subject,
674            TimeRange::new(now, now),
675        )
676        .await
677        .with_context(|| {
678            format!(
679                "'{}': merge_sort_order does not apply to extract_query",
680                def.view_set_name
681            )
682        })?;
683    }
684
685    Ok((on_demand_sources, extract_sources))
686}