1use std::fmt::Debug;
13use std::sync::Arc;
14use std::time::{Duration, Instant};
15
16use mz_compute_types::ComputeInstanceId;
17use mz_compute_types::dataflows::IndexDesc;
18use mz_compute_types::plan::Plan;
19use mz_expr::{MirRelationExpr, MirScalarExpr, OptimizedMirRelationExpr, RowSetFinishing};
20use mz_ore::soft_assert_or_log;
21use mz_repr::explain::trace_plan;
22use mz_repr::{GlobalId, ReprRelationType, SqlRelationType, Timestamp};
23use mz_sql::optimizer_metrics::OptimizerMetrics;
24use mz_sql::plan::HirRelationExpr;
25use mz_sql::session::metadata::SessionMetadata;
26use mz_transform::dataflow::DataflowMetainfo;
27use mz_transform::normalize_lets::normalize_lets;
28use mz_transform::typecheck::{SharedTypecheckingContext, empty_typechecking_context};
29use mz_transform::{StatisticsOracle, TransformCtx};
30use timely::progress::Antichain;
31use tracing::debug_span;
32
33use crate::TimestampContext;
34use crate::catalog::Catalog;
35use crate::coord::infer_sql_type_for_catalog;
36use crate::coord::peek::{PeekDataflowPlan, PeekPlan, create_fast_path_plan};
37use crate::optimize::dataflows::{
38 ComputeInstanceSnapshot, DataflowBuilder, EvalTime, ExprPrep, ExprPrepOneShot,
39};
40use crate::optimize::{
41 MirDataflowDescription, Optimize, OptimizeMode, OptimizerConfig, OptimizerError,
42 optimize_mir_local, trace_plan,
43};
44
45pub struct Optimizer {
46 typecheck_ctx: SharedTypecheckingContext,
48 catalog: Arc<Catalog>,
50 compute_instance: ComputeInstanceSnapshot,
52 finishing: RowSetFinishing,
54 select_id: GlobalId,
56 index_id: GlobalId,
58 config: OptimizerConfig,
60 metrics: OptimizerMetrics,
62 duration: Duration,
64}
65
66impl Optimizer {
67 pub fn new(
68 catalog: Arc<Catalog>,
69 compute_instance: ComputeInstanceSnapshot,
70 finishing: RowSetFinishing,
71 select_id: GlobalId,
72 index_id: GlobalId,
73 config: OptimizerConfig,
74 metrics: OptimizerMetrics,
75 ) -> Self {
76 Self {
77 typecheck_ctx: empty_typechecking_context(),
78 catalog,
79 compute_instance,
80 finishing,
81 select_id,
82 index_id,
83 config,
84 metrics,
85 duration: Default::default(),
86 }
87 }
88
89 pub fn cluster_id(&self) -> ComputeInstanceId {
90 self.compute_instance.instance_id()
91 }
92
93 pub fn finishing(&self) -> &RowSetFinishing {
94 &self.finishing
95 }
96
97 pub fn select_id(&self) -> GlobalId {
98 self.select_id
99 }
100
101 pub fn index_id(&self) -> GlobalId {
102 self.index_id
103 }
104
105 pub fn config(&self) -> &OptimizerConfig {
106 &self.config
107 }
108
109 pub fn metrics(&self) -> &OptimizerMetrics {
110 &self.metrics
111 }
112
113 pub fn duration(&self) -> Duration {
114 self.duration
115 }
116}
117
118impl Debug for Optimizer {
124 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
125 f.debug_struct("OptimizePeek")
126 .field("config", &self.config)
127 .finish_non_exhaustive()
128 }
129}
130
131pub struct Unresolved;
134
135#[derive(Clone)]
138pub struct LocalMirPlan<T = Unresolved> {
139 expr: MirRelationExpr,
140 typ: SqlRelationType,
141 df_meta: DataflowMetainfo,
142 context: T,
143}
144
145pub struct Resolved<'s> {
148 timestamp_ctx: TimestampContext<Timestamp>,
149 stats: Box<dyn StatisticsOracle>,
150 session: &'s dyn SessionMetadata,
151}
152
153#[derive(Debug)]
162pub struct GlobalLirPlan {
163 peek_plan: PeekPlan,
164 df_meta: DataflowMetainfo,
165 typ: SqlRelationType,
166}
167
168impl Optimize<HirRelationExpr> for Optimizer {
169 type To = LocalMirPlan;
170
171 fn optimize(&mut self, expr: HirRelationExpr) -> Result<Self::To, OptimizerError> {
172 let time = Instant::now();
173
174 trace_plan!(at: "raw", &expr);
176
177 let mir_expr = expr.clone().lower(&self.config, Some(&self.metrics))?;
179
180 let mut df_meta = DataflowMetainfo::default();
182 let mut transform_ctx = TransformCtx::local(
183 &self.config.features,
184 &self.typecheck_ctx,
185 &mut df_meta,
186 Some(&mut self.metrics),
187 Some(self.select_id),
188 );
189 let mir_expr = optimize_mir_local(mir_expr, &mut transform_ctx)?.into_inner();
190 let typ = infer_sql_type_for_catalog(&expr, &mir_expr);
191
192 self.duration += time.elapsed();
193
194 Ok(LocalMirPlan {
196 expr: mir_expr,
197 typ,
198 df_meta,
199 context: Unresolved,
200 })
201 }
202}
203
204impl LocalMirPlan<Unresolved> {
205 pub fn resolve(
208 self,
209 timestamp_ctx: TimestampContext<Timestamp>,
210 session: &dyn SessionMetadata,
211 stats: Box<dyn StatisticsOracle>,
212 ) -> LocalMirPlan<Resolved<'_>> {
213 LocalMirPlan {
214 expr: self.expr,
215 typ: self.typ,
216 df_meta: self.df_meta,
217 context: Resolved {
218 timestamp_ctx,
219 session,
220 stats,
221 },
222 }
223 }
224}
225
226impl<'s> Optimize<LocalMirPlan<Resolved<'s>>> for Optimizer {
227 type To = GlobalLirPlan;
228
229 fn optimize(&mut self, plan: LocalMirPlan<Resolved<'s>>) -> Result<Self::To, OptimizerError> {
230 let time = Instant::now();
231
232 let LocalMirPlan {
233 expr,
234 typ,
235 mut df_meta,
236 context:
237 Resolved {
238 timestamp_ctx,
239 stats,
240 session,
241 },
242 } = plan;
243
244 let expr = OptimizedMirRelationExpr(expr);
245
246 let key = typ
250 .default_key()
251 .iter()
252 .map(|k| MirScalarExpr::column(*k))
253 .collect();
254
255 let mut df_builder = {
257 let catalog = self.catalog.state();
258 let compute = self.compute_instance.clone();
259 DataflowBuilder::new(catalog, compute).with_config(&self.config)
260 };
261
262 let debug_name = format!("oneshot-select-{}", self.select_id);
263 let mut df_desc = MirDataflowDescription::new(debug_name.to_string());
264
265 df_builder.import_view_into_dataflow(
266 &self.select_id,
267 &expr,
268 &mut df_desc,
269 &self.config.features,
270 )?;
271 df_builder.maybe_reoptimize_imported_views(&mut df_desc, &self.config)?;
272
273 if self.config.mode != OptimizeMode::Explain {
277 df_desc.export_index(
278 self.index_id,
279 IndexDesc {
280 on_id: self.select_id,
281 key,
282 },
283 ReprRelationType::from(&typ),
284 );
285 }
286
287 df_desc.set_as_of(timestamp_ctx.antichain());
289
290 let as_of = df_desc
292 .as_of
293 .clone()
294 .expect("as_of antichain")
295 .into_option()
296 .expect("unique as_of element");
297
298 let style = ExprPrepOneShot {
300 logical_time: EvalTime::Time(as_of),
301 session,
302 catalog_state: self.catalog.state(),
303 };
304 df_desc.visit_children(
305 |r| style.prep_relation_expr(r),
306 |s| style.prep_scalar_expr(s),
307 )?;
308
309 if let Some(until) = timestamp_ctx
319 .timestamp()
320 .and_then(Timestamp::try_step_forward)
321 {
322 df_desc.until = Antichain::from_elem(until);
323 }
324
325 let mut transform_ctx = TransformCtx::global(
327 &df_builder,
328 &*stats,
329 &self.config.features,
330 &self.typecheck_ctx,
331 &mut df_meta,
332 Some(&mut self.metrics),
333 );
334
335 let use_fast_path_optimizer = match create_fast_path_plan(
340 &mut df_desc,
341 self.select_id,
342 Some(&self.finishing),
343 self.config.features.persist_fast_path_limit,
344 self.config.persist_fast_path_order,
345 ) {
346 Ok(maybe_fast_path_plan) => maybe_fast_path_plan.is_some(),
347 Err(OptimizerError::InternalUnsafeMfpPlan(_)) => {
348 false
351 }
352 Err(e) => {
353 return Err(e);
354 }
355 };
356
357 mz_transform::optimize_dataflow(&mut df_desc, &mut transform_ctx, use_fast_path_optimizer)?;
359
360 if self.config.mode == OptimizeMode::Explain {
361 trace_plan!(at: "global", &df_meta.used_indexes(&df_desc));
363 }
364
365 let peek_plan = match create_fast_path_plan(
375 &mut df_desc,
376 self.select_id,
377 Some(&self.finishing),
378 self.config.features.persist_fast_path_limit,
379 self.config.persist_fast_path_order,
380 )? {
381 Some(plan) if !self.config.no_fast_path => {
382 if self.config.mode == OptimizeMode::Explain {
383 debug_span!(target: "optimizer", "fast_path").in_scope(|| {
385 let finishing = if !self.finishing.is_trivial(typ.arity()) {
387 Some(&self.finishing)
388 } else {
389 None
390 };
391 trace_plan(&plan.used_indexes(finishing));
392 });
393 }
394 trace_plan!(at: "fast_path", &plan);
396
397 trace_plan(&plan);
399
400 PeekPlan::FastPath(plan)
402 }
403 _ => {
404 soft_assert_or_log!(
405 !use_fast_path_optimizer || self.config.no_fast_path,
406 "The fast_path_optimizer shouldn't make a fast path plan slow path."
407 );
408
409 for build in df_desc.objects_to_build.iter_mut() {
411 normalize_lets(&mut build.plan.0, &self.config.features)?
412 }
413
414 let df_desc = Plan::finalize_dataflow(df_desc, &self.config.features)?;
418
419 trace_plan(&df_desc);
421
422 PeekPlan::SlowPath(PeekDataflowPlan::new(df_desc, self.index_id(), &typ))
424 }
425 };
426
427 self.duration += time.elapsed();
428 let label = match &peek_plan {
429 PeekPlan::FastPath(_) => "peek:fast_path",
430 PeekPlan::SlowPath(_) => "peek:slow_path",
431 };
432 self.metrics
433 .observe_e2e_optimization_time(label, self.duration);
434
435 Ok(GlobalLirPlan {
436 peek_plan,
437 df_meta,
438 typ,
439 })
440 }
441}
442
443impl GlobalLirPlan {
444 pub fn peek_plan(&self) -> &PeekPlan {
446 &self.peek_plan
447 }
448
449 pub fn unapply(self) -> (PeekPlan, DataflowMetainfo, SqlRelationType) {
451 (self.peek_plan, self.df_meta, self.typ)
452 }
453}