1use 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#[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 #[serde(default, skip_serializing_if = "Option::is_none")]
51 pub max_jit_src_data: Option<String>,
52}
53
54pub const DEFAULT_MAX_JIT_SRC_DATA: i64 = 1024 * 1024 * 1024;
56
57#[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 pub update_group: Option<i32>,
69 pub options: ViewOptions,
70}
71
72pub 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
95pub 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
120pub 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
150pub 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
196fn is_stringy(dt: &DataType) -> bool {
199 matches!(dt, DataType::Utf8 | DataType::Utf8View)
200 || matches!(dt, DataType::Dictionary(_, inner) if **inner == DataType::Utf8)
201}
202
203fn 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
233fn 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
250fn 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
264fn 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
289fn 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
318pub 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
331const STORED_SCAN_BANNED_READ_ONLY_FUNCTIONS: &[&str] =
334 &["view_instance", "process_spans", "perfetto_trace_chunks"];
335
336fn is_banned_from_stored_scans(name: &str) -> bool {
339 MUTATING_FUNCTIONS.contains(&name) || STORED_SCAN_BANNED_READ_ONLY_FUNCTIONS.contains(&name)
340}
341
342fn 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
349fn 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 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 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
443async 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
465async 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
489pub 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 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 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 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 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 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 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}