Skip to main content

mz_adapter/
peek_sequencing.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10use std::collections::BTreeMap;
11use std::collections::BTreeSet;
12use std::str::FromStr;
13use std::sync::Arc;
14use std::time::Duration;
15
16use futures::StreamExt;
17use http::Uri;
18use itertools::Itertools;
19use maplit::btreemap;
20use mz_catalog::memory::objects::Cluster;
21use mz_compute_types::ComputeInstanceId;
22use mz_controller_types::{ClusterId, ReplicaId};
23use mz_expr::{CollectionPlan, ResultSpec, RowSetFinishing};
24use mz_ore::cast::{CastFrom, CastLossy};
25use mz_ore::collections::CollectionExt;
26use mz_ore::now::EpochMillis;
27use mz_ore::task::JoinHandle;
28use mz_ore::{soft_assert_eq_or_log, soft_assert_or_log, soft_panic_or_log};
29use mz_repr::explain::{ExplainFormat, ExprHumanizerExt, TransientItem};
30use mz_repr::optimize::{OptimizerFeatures, OverrideFrom};
31use mz_repr::{Datum, GlobalId, IntoRowIterator, Row, RowArena, RowIterator, Timestamp};
32use mz_sql::ast::Raw;
33use mz_sql::catalog::CatalogCluster;
34use mz_sql::plan::Params;
35use mz_sql::plan::{
36    self, Explainee, ExplaineeStatement, HirScalarExpr, Plan, QueryWhen, SelectPlan,
37    SideEffectingFunc, SubscribeFrom, SubscribePlan,
38};
39use mz_sql::rbac;
40use mz_sql::session::metadata::SessionMetadata;
41use mz_sql::session::user::MZ_SYSTEM_ROLE_ID;
42use mz_sql::session::vars::{
43    self, CLUSTER, CLUSTER_REPLICA, IsolationLevel, SessionVars, TRANSACTION_ISOLATION, Var,
44    VarInput,
45};
46use mz_sql_parser::ast::{CopyDirection, ExplainStage, ShowStatement, Statement, StatementKind};
47use mz_storage_client::storage_collections::StorageCollections;
48use mz_storage_types::controller::StorageError;
49use mz_transform::dataflow::DataflowMetainfo;
50use mz_transform::{EmptyStatisticsOracle, StatisticsOracle};
51use opentelemetry::trace::TraceContextExt;
52use timely::progress::Antichain;
53use tracing::{Span, debug, warn};
54use tracing_opentelemetry::OpenTelemetrySpanExt;
55
56use crate::catalog::{Catalog, CatalogState};
57use crate::command::{CatalogSnapshot, Command};
58use crate::coord;
59use crate::coord::peek::{FastPathPlan, PeekPlan, PeekResponseUnary};
60use crate::coord::timeline::timedomain_for;
61use crate::coord::timestamp_selection::TimestampDetermination;
62use crate::coord::{Coordinator, CopyToContext, ExplainContext, ExplainPlanContext, TargetCluster};
63use crate::explain::insights::PlanInsightsContext;
64use crate::explain::optimizer_trace::OptimizerTrace;
65use crate::optimize::Optimize;
66use crate::optimize::dataflows::{
67    ComputeInstanceSnapshot, DataflowBuilder, EvalTime, ExprPrep, ExprPrepOneShot,
68};
69use crate::optimize::peek;
70use crate::peek_client::{ExecutionLogging, PeekCancelSafety, TakeOver};
71use crate::session::{Session, TransactionOps, TransactionStatus};
72use crate::statement_logging::StatementLifecycleEvent;
73use crate::{
74    AdapterError, AdapterNotice, CollectionIdBundle, ExecuteResponse, PeekClient, ReadHolds,
75    TimelineContext, TimestampContext, TimestampProvider, optimize,
76};
77
78impl PeekClient {
79    /// Attempt to sequence a peek from the session task.
80    ///
81    /// Returns `Ok(Some(response))` if we handled the peek, or `Ok(None)` to fall back to the
82    /// Coordinator's sequencing. If it returns an error, it should be returned to the user.
83    ///
84    /// `logging` holds the end-of-execution obligation for this statement. The
85    /// caller retires it unless dispatch transfers it to the peek lifecycle
86    /// or a coordinator-owned non-peek operation.
87    pub(crate) async fn try_peek(
88        &mut self,
89        portal_name: &str,
90        session: &mut Session,
91        logging: &mut ExecutionLogging,
92        cancel_safety: &PeekCancelSafety,
93    ) -> Result<Option<ExecuteResponse>, AdapterError> {
94        let cancellation_epoch = self.connection_peeks().cancellation_epoch();
95        // # From handle_execute
96
97        if session.vars().emit_trace_id_notice() {
98            let span_context = tracing::Span::current()
99                .context()
100                .span()
101                .span_context()
102                .clone();
103            if span_context.is_valid() {
104                session.add_notice(AdapterNotice::QueryTrace {
105                    trace_id: span_context.trace_id(),
106                });
107            }
108        }
109
110        let catalog = self.catalog_snapshot("try_peek").await;
111
112        // Extract things from the portal. A failed verification does not begin
113        // an entry, mirroring the coordinator: the portal is what statement
114        // logging draws its record from. An adopted outer entry still gets its
115        // `Errored` end from the retirement site in `SessionClient::execute`.
116        let (stmt, params, logging_info, lifecycle_timestamps) = {
117            Coordinator::verify_portal(&*catalog, session, portal_name)?;
118            let portal = session
119                .get_portal_unverified(portal_name)
120                // The portal is a session-level thing, so it couldn't have concurrently disappeared
121                // since the above verification.
122                .expect("called verify_portal above");
123            let params = portal.parameters.clone();
124            let stmt = portal.stmt.clone();
125            let logging_info = Arc::clone(&portal.logging);
126            let lifecycle_timestamps = portal.lifecycle_timestamps.clone();
127            (stmt, params, logging_info, lifecycle_timestamps)
128        };
129
130        // Before planning, check if this is a statement type we can handle.
131        // This must happen BEFORE statement logging setup to avoid orphaned execution records.
132        if let Some(ref stmt) = stmt {
133            if StatementKind::from(&**stmt).is_explain() {
134                session.transaction_mut().record_explain()?;
135            }
136            match &**stmt {
137                Statement::Select(_)
138                | Statement::ExplainAnalyzeObject(_)
139                | Statement::ExplainAnalyzeCluster(_)
140                | Statement::Show(ShowStatement::ShowObjects(_))
141                | Statement::Show(ShowStatement::ShowColumns(_)) => {
142                    // These are always fine, just continue.
143                    // Note: EXPLAIN ANALYZE will `plan` to `Plan::Select`.
144                    // Note: ShowObjects plans to `Plan::Select`, ShowColumns plans to `Plan::ShowColumns`.
145                    // We handle `Plan::ShowColumns` specially in `try_peek_inner`.
146                }
147                Statement::ExplainPlan(explain_stmt) => {
148                    // Only handle ExplainPlan for SELECT and SUBSCRIBE statements.
149                    // We don't want to handle e.g. EXPLAIN CREATE MATERIALIZED VIEW here, because that
150                    // requires purification before planning, which the frontend peek sequencing doesn't
151                    // do.
152                    match &explain_stmt.explainee {
153                        mz_sql_parser::ast::Explainee::Select(..)
154                        | mz_sql_parser::ast::Explainee::Subscribe(..) => {}
155                        _ => {
156                            debug!(
157                                "Bailing out from try_peek, because EXPLAIN is not for a SELECT or SUBSCRIBE"
158                            );
159                            return Ok(None);
160                        }
161                    }
162                }
163                Statement::ExplainPushdown(explain_stmt) => {
164                    // Only handle EXPLAIN FILTER PUSHDOWN for non-BROKEN SELECT statements
165                    match &explain_stmt.explainee {
166                        mz_sql_parser::ast::Explainee::Select(_, false) => {}
167                        _ => {
168                            debug!(
169                                "Bailing out from try_peek, because EXPLAIN FILTER PUSHDOWN is not for a SELECT query or is for EXPLAIN BROKEN"
170                            );
171                            return Ok(None);
172                        }
173                    }
174                }
175                Statement::Copy(copy_stmt) => {
176                    match &copy_stmt.direction {
177                        CopyDirection::To => {
178                            // This is COPY TO (...), continue
179                        }
180                        CopyDirection::From => {
181                            debug!("Bailing out from try_peek, because COPY FROM is not supported");
182                            return Ok(None);
183                        }
184                    }
185                }
186
187                Statement::Subscribe(_) | Statement::ExplainTimestamp(_) => {}
188                _ => {
189                    debug!("Bailing out from try_peek, because statement type is not supported");
190                    return Ok(None);
191                }
192            }
193        }
194
195        // Past this point the coordinator never sees this statement, so every
196        // exit has to produce an outcome for it. The `Ok(None)` bailouts are all
197        // above.
198        logging.take_over(
199            self,
200            session,
201            stmt.as_deref(),
202            &params,
203            &logging_info,
204            &catalog,
205            lifecycle_timestamps,
206            TakeOver::StatementToRun,
207        );
208
209        self.try_peek_inner(
210            session,
211            catalog,
212            stmt,
213            params,
214            logging,
215            cancellation_epoch,
216            cancel_safety,
217        )
218        .await
219    }
220
221    /// Executes a coordinator-owned `SELECT`, pinned to `replica_id`, and
222    /// returns its rows.
223    ///
224    /// The caller must build `sql` itself rather than accept it from a user.
225    /// It runs as the system role, in a session of its own, and is not
226    /// statement-logged. This calls into the coordinator, so awaiting it on the
227    /// coordinator's main loop deadlocks.
228    ///
229    /// Dropping the returned future retires its frontend-owned peek and
230    /// requests compute cancellation if the peek has already been issued.
231    pub(crate) async fn background_peek(
232        &mut self,
233        sql: &str,
234        cluster_id: ClusterId,
235        replica_id: ReplicaId,
236    ) -> Result<Vec<Row>, AdapterError> {
237        // Not `catalog_snapshot`, which expects the coordinator to outlive its
238        // caller. A background client may race the coordinator's shutdown.
239        let CatalogSnapshot { catalog } = self
240            .call_coordinator(|tx| Command::CatalogSnapshot { tx })
241            .await?;
242        let (cluster_name, replica_name) = {
243            let cluster = catalog
244                .try_get_cluster(cluster_id)
245                .ok_or_else(|| AdapterError::Internal(format!("unknown cluster {cluster_id}")))?;
246            let replica = cluster
247                .replica(replica_id)
248                .ok_or_else(|| AdapterError::Internal(format!("unknown replica {replica_id}")))?;
249            (cluster.name.clone(), replica.name.clone())
250        };
251        let stmt = mz_sql::parse::parse(sql)?.into_element().ast;
252
253        let mut session = Session::dummy();
254        session.initialize_role_metadata(MZ_SYSTEM_ROLE_ID);
255        let system_vars = catalog.system_config();
256        // Serializable reads at the freshest time the inputs can serve. A
257        // strict-serializable read picks the stalest valid time at or past the
258        // oracle's read timestamp instead. In a read-only environment whose
259        // leader is not running, nothing advances the oracle, and such a read
260        // sees introspection logs as of a time before the replicas started.
261        for (var, value) in [
262            (&CLUSTER, cluster_name.as_str()),
263            (&CLUSTER_REPLICA, replica_name.as_str()),
264            (&TRANSACTION_ISOLATION, "serializable"),
265        ] {
266            session
267                .vars_mut()
268                .set(system_vars, var.name(), VarInput::Flat(value), false)?;
269        }
270        session.start_transaction_single_stmt(mz_ore::now::to_datetime((catalog.config().now)()));
271
272        let mut logging = ExecutionLogging::adopt(None, self);
273        let cancellation_epoch = self.connection_peeks().cancellation_epoch();
274        let cancel_safety = PeekCancelSafety::new();
275        let response = self
276            .try_peek_inner(
277                &mut session,
278                catalog,
279                Some(Arc::new(stmt)),
280                Params::empty(),
281                &mut logging,
282                cancellation_epoch,
283                &cancel_safety,
284            )
285            .await?;
286
287        let mut rows = Vec::new();
288        let mut collect = |mut iter: Box<dyn RowIterator + Send + Sync>| {
289            while let Some(row) = iter.next() {
290                rows.push(row.to_owned());
291            }
292        };
293        match response {
294            Some(ExecuteResponse::SendingRowsImmediate { rows }) => collect(rows),
295            Some(ExecuteResponse::SendingRowsStreaming { mut rows, .. }) => {
296                while let Some(response) = rows.next().await {
297                    match response {
298                        PeekResponseUnary::Rows(iter) => collect(iter),
299                        PeekResponseUnary::Error(error) => return Err(error),
300                        PeekResponseUnary::Canceled => return Err(AdapterError::Canceled),
301                        PeekResponseUnary::DependencyDropped(dependency) => {
302                            return Err(dependency.to_concurrent_dependency_drop());
303                        }
304                    }
305                }
306            }
307            response => {
308                return Err(AdapterError::Internal(format!(
309                    "background peek returned an unexpected response: {response:?}"
310                )));
311            }
312        }
313        Ok(rows)
314    }
315
316    /// This is encapsulated in an inner function so that the outer function can still do statement
317    /// logging after the `?` returns of the inner function.
318    ///
319    /// Streaming peeks transfer logging to their lifecycle. Subscribes transfer
320    /// it to the protocol layer. Immediate responses leave it with the caller.
321    #[mz_ore::instrument(level = "debug")]
322    async fn try_peek_inner(
323        &mut self,
324        session: &mut Session,
325        catalog: Arc<Catalog>,
326        stmt: Option<Arc<Statement<Raw>>>,
327        params: Params,
328        logging: &mut ExecutionLogging,
329        cancellation_epoch: u64,
330        cancel_safety: &PeekCancelSafety,
331    ) -> Result<Option<ExecuteResponse>, AdapterError> {
332        let stmt = match stmt {
333            Some(stmt) => stmt,
334            None => {
335                debug!("try_peek_inner succeeded on an empty query");
336                return Ok(Some(ExecuteResponse::EmptyQuery));
337            }
338        };
339
340        // # From handle_execute_inner
341
342        let conn_catalog = catalog.for_session(session);
343        // (`resolved_ids` should be derivable from `stmt`. If `stmt` is later transformed to
344        // remove/add IDs, then `resolved_ids` should be updated to also remove/add those IDs.)
345        let (stmt, resolved_ids) = mz_sql::names::resolve(&conn_catalog, (*stmt).clone())?;
346
347        // EXPLAIN ANALYZE lowers to a SELECT over introspection, but diagnostics
348        // must remain available when query policies reject ordinary SELECTs.
349        let explain_analyze = matches!(
350            stmt,
351            Statement::ExplainAnalyzeObject(_) | Statement::ExplainAnalyzeCluster(_)
352        );
353        let pcx = session.pcx();
354        let (plan, sql_impl_ids) =
355            mz_sql::plan::plan(Some(pcx), &conn_catalog, stmt, &params, &resolved_ids)?;
356
357        /// What do we do with the result of the select?
358        enum QueryPlan<'a> {
359            Select(&'a SelectPlan),
360            CopyTo(&'a SelectPlan, CopyToContext),
361            Subscribe(&'a SubscribePlan),
362            ExplainTimestamp(&'a plan::ExplainTimestampPlan),
363        }
364
365        impl QueryPlan<'_> {
366            /// Whether statement logging records the timestamp the statement executes at as
367            /// soon as it is determined. EXPLAIN only determines a timestamp, and COPY TO does
368            /// not log one.
369            fn logs_execution_timestamp(&self, explain_ctx: &ExplainContext) -> bool {
370                let executes = match explain_ctx {
371                    ExplainContext::None | ExplainContext::PlanInsightsNotice(_) => true,
372                    ExplainContext::Plan(_)
373                    | ExplainContext::Pushdown
374                    | ExplainContext::Timestamp => false,
375                };
376                executes
377                    && match self {
378                        QueryPlan::Select(_) | QueryPlan::Subscribe(_) => true,
379                        QueryPlan::CopyTo(..) | QueryPlan::ExplainTimestamp(_) => false,
380                    }
381            }
382        }
383
384        /// A [`QueryPlan`] that goes on to be optimized.
385        enum OptimizerInput<'a> {
386            Select(&'a SelectPlan),
387            CopyTo(&'a SelectPlan, CopyToContext),
388            Subscribe(&'a SubscribePlan),
389        }
390
391        let (query_plan, explain_ctx) = match &plan {
392            Plan::Select(select_plan) => {
393                let explain_ctx = if session.vars().emit_plan_insights_notice() {
394                    let optimizer_trace = OptimizerTrace::new(ExplainStage::PlanInsights.paths());
395                    ExplainContext::PlanInsightsNotice(optimizer_trace)
396                } else {
397                    ExplainContext::None
398                };
399                (QueryPlan::Select(select_plan), explain_ctx)
400            }
401            Plan::ShowColumns(show_columns_plan) => {
402                // ShowColumns wraps a SelectPlan, extract it and proceed as normal.
403                (
404                    QueryPlan::Select(&show_columns_plan.select_plan),
405                    ExplainContext::None,
406                )
407            }
408            Plan::ExplainPlan(plan::ExplainPlanPlan {
409                stage,
410                format,
411                config,
412                explainee: Explainee::Statement(ExplaineeStatement::Select { broken, plan, desc }),
413            }) => {
414                // Create OptimizerTrace to collect optimizer plans
415                let optimizer_trace = OptimizerTrace::new(stage.paths());
416                let explain_ctx = ExplainContext::Plan(ExplainPlanContext {
417                    broken: *broken,
418                    config: config.clone(),
419                    format: *format,
420                    stage: *stage,
421                    replan: None,
422                    desc: Some(desc.clone()),
423                    optimizer_trace,
424                });
425                (QueryPlan::Select(plan), explain_ctx)
426            }
427            // COPY TO S3
428            Plan::CopyTo(plan::CopyToPlan {
429                select_plan,
430                desc,
431                to,
432                connection,
433                connection_id,
434                format,
435                max_file_size,
436            }) => {
437                let uri = eval_copy_to_uri(to.clone(), session, catalog.state())?;
438
439                // (output_batch_count will be set later)
440                let copy_to_ctx = CopyToContext {
441                    desc: desc.clone(),
442                    uri,
443                    connection: connection.clone(),
444                    connection_id: *connection_id,
445                    format: format.clone(),
446                    max_file_size: *max_file_size,
447                    output_batch_count: None,
448                };
449
450                (
451                    QueryPlan::CopyTo(select_plan, copy_to_ctx),
452                    ExplainContext::None,
453                )
454            }
455            Plan::ExplainPushdown(plan::ExplainPushdownPlan { explainee }) => {
456                // Only handle EXPLAIN FILTER PUSHDOWN for SELECT statements
457                match explainee {
458                    plan::Explainee::Statement(plan::ExplaineeStatement::Select {
459                        broken: false,
460                        plan,
461                        desc: _,
462                    }) => {
463                        let explain_ctx = ExplainContext::Pushdown;
464                        (QueryPlan::Select(plan), explain_ctx)
465                    }
466                    _ => {
467                        // This shouldn't happen because we already checked for this at the AST
468                        // level before calling `try_peek_inner`. The logging takeover
469                        // has already happened, so falling back to the coordinator would count
470                        // the statement twice. Report the inconsistency instead.
471                        soft_panic_or_log!(
472                            "unexpected EXPLAIN FILTER PUSHDOWN plan kind in frontend peek sequencing: {:?}",
473                            explainee
474                        );
475                        return Err(AdapterError::Internal(
476                            "unexpected EXPLAIN FILTER PUSHDOWN plan kind in frontend peek sequencing"
477                                .into(),
478                        ));
479                    }
480                }
481            }
482            Plan::SideEffectingFunc(sef_plan) => {
483                // Look up the target connection's authenticated role, so that
484                // check_plan can perform RBAC for side-effecting functions.
485                //
486                // The RBAC check reflects the state at this point in time. A
487                // concurrent change to the issuer's role membership does not
488                // affect the already in-flight execution, similarly to how
489                // privilege changes don't affect other kinds of in-flight
490                // statements.
491                let target_conn = match sef_plan {
492                    SideEffectingFunc::PgCancelBackend {
493                        connection_id: Some(connection_id),
494                    } => {
495                        self.call_coordinator(|tx| Command::LookupConnection {
496                            connection_id: *connection_id,
497                            tx,
498                        })
499                        .await?
500                    }
501                    SideEffectingFunc::PgCancelBackend {
502                        connection_id: None,
503                    } => None,
504                };
505                let target_conn_role = target_conn.as_ref().map(|(_, role)| *role);
506
507                rbac::check_plan(
508                    &conn_catalog,
509                    target_conn_role,
510                    session,
511                    &plan,
512                    None,
513                    &resolved_ids,
514                    &sql_impl_ids,
515                )?;
516
517                // RBAC passed. Delegate execution to the Coordinator.
518                cancel_safety.delegate_side_effect();
519                let response = self
520                    .call_coordinator(|tx| Command::ExecuteSideEffectingFunc {
521                        plan: sef_plan.clone(),
522                        conn_id: session.conn_id().clone(),
523                        tx,
524                    })
525                    .await??;
526
527                // We held the target's `ConnectionId` handle from the RBAC
528                // check until the Coordinator executed the function, which
529                // prevented the raw connection ID from being reused by a new
530                // connection. So the connection the Coordinator acted on (if
531                // it found one) is the one whose role we checked above.
532                drop(target_conn);
533
534                return Ok(Some(response));
535            }
536            Plan::Subscribe(subscribe) => (QueryPlan::Subscribe(subscribe), ExplainContext::None),
537            Plan::ExplainTimestamp(explain_timestamp_plan) => {
538                if explain_timestamp_plan.format == ExplainFormat::Dot {
539                    return Err(AdapterError::Unsupported("EXPLAIN TIMESTAMP AS DOT"));
540                }
541                (
542                    QueryPlan::ExplainTimestamp(explain_timestamp_plan),
543                    ExplainContext::Timestamp,
544                )
545            }
546            Plan::ExplainPlan(plan::ExplainPlanPlan {
547                stage,
548                format,
549                config,
550                explainee: Explainee::Statement(ExplaineeStatement::Subscribe { broken, plan }),
551            }) => {
552                let desc = match &plan.from {
553                    SubscribeFrom::Id(_) => None,
554                    SubscribeFrom::Query { desc, .. } => Some(desc.clone()),
555                };
556                let explain_ctx = ExplainContext::Plan(ExplainPlanContext {
557                    broken: *broken,
558                    config: config.clone(),
559                    format: *format,
560                    stage: *stage,
561                    replan: None,
562                    desc,
563                    optimizer_trace: OptimizerTrace::new(stage.paths()),
564                });
565                (QueryPlan::Subscribe(plan), explain_ctx)
566            }
567            Plan::CreateConnection(_)
568            | Plan::CreateDatabase(_)
569            | Plan::CreateSchema(_)
570            | Plan::CreateRole(_)
571            | Plan::CreateCluster(_)
572            | Plan::CreateClusterReplica(_)
573            | Plan::CreateSource(_)
574            | Plan::CreateSources(_)
575            | Plan::CreateSecret(_)
576            | Plan::CreateSink(_)
577            | Plan::CreateTable(_)
578            | Plan::CreateView(_)
579            | Plan::CreateMaterializedView(_)
580            | Plan::CreateNetworkPolicy(_)
581            | Plan::CreateQueryPolicy(_)
582            | Plan::CreateIndex(_)
583            | Plan::CreateMetricSink(_)
584            | Plan::CreateType(_)
585            | Plan::Comment(_)
586            | Plan::DiscardTemp
587            | Plan::DiscardAll
588            | Plan::DropObjects(_)
589            | Plan::DropOwned(_)
590            | Plan::EmptyQuery
591            | Plan::ShowAllVariables
592            | Plan::ShowCreate(_)
593            | Plan::ShowVariable(_)
594            | Plan::InspectShard(_)
595            | Plan::SetVariable(_)
596            | Plan::ResetVariable(_)
597            | Plan::SetTransaction(_)
598            | Plan::StartTransaction(_)
599            | Plan::CommitTransaction(_)
600            | Plan::AbortTransaction(_)
601            | Plan::CopyFrom(_)
602            | Plan::ExplainPlan(_)
603            | Plan::ExplainSinkSchema(_)
604            | Plan::Insert(_)
605            | Plan::AlterCluster(_)
606            | Plan::AlterClusterSwap(_)
607            | Plan::AlterNoop(_)
608            | Plan::AlterSetCluster(_)
609            | Plan::AlterConnection(_)
610            | Plan::AlterSource(_)
611            | Plan::AlterClusterRename(_)
612            | Plan::AlterClusterReplicaRename(_)
613            | Plan::AlterItemRename(_)
614            | Plan::AlterSchemaRename(_)
615            | Plan::AlterSchemaSwap(_)
616            | Plan::AlterSecret(_)
617            | Plan::AlterSink(_)
618            | Plan::AlterSystemSet(_)
619            | Plan::AlterSystemReset(_)
620            | Plan::AlterSystemResetAll(_)
621            | Plan::AlterRole(_)
622            | Plan::AlterOwner(_)
623            | Plan::AlterTableAddColumn(_)
624            | Plan::AlterMaterializedViewApplyReplacement(_)
625            | Plan::AlterNetworkPolicy(_)
626            | Plan::AlterQueryPolicy(_)
627            | Plan::Declare(_)
628            | Plan::Fetch(_)
629            | Plan::Close(_)
630            | Plan::ReadThenWrite(_)
631            | Plan::Prepare(_)
632            | Plan::Execute(_)
633            | Plan::Deallocate(_)
634            | Plan::Raise(_)
635            | Plan::GrantRole(_)
636            | Plan::RevokeRole(_)
637            | Plan::GrantPrivileges(_)
638            | Plan::RevokePrivileges(_)
639            | Plan::AlterDefaultPrivileges(_)
640            | Plan::ReassignOwned(_)
641            | Plan::ValidateConnection(_)
642            | Plan::AlterRetainHistory(_)
643            | Plan::AlterSourceTimestampInterval(_) => {
644                // The other `EXPLAIN` explainees and every other plan kind are excluded at the
645                // AST level before calling `try_peek_inner`. The logging takeover has
646                // already happened, so falling back to the coordinator would count the
647                // statement twice. Report the inconsistency instead.
648                soft_panic_or_log!(
649                    "Unexpected plan kind in frontend peek sequencing: {:?}",
650                    plan
651                );
652                return Err(AdapterError::Internal(
653                    "unexpected plan kind in frontend peek sequencing".into(),
654                ));
655            }
656        };
657
658        let when = match &query_plan {
659            QueryPlan::Select(s) => &s.when,
660            QueryPlan::CopyTo(s, _) => &s.when,
661            QueryPlan::Subscribe(s) => &s.when,
662            QueryPlan::ExplainTimestamp(p) => &p.when,
663        };
664
665        // # From sequence_plan
666
667        // We have checked the plan kind above.
668        assert!(plan.allowed_in_read_only());
669
670        let (cluster, target_cluster_id, target_cluster_name) = {
671            let target_cluster = match session.transaction().cluster() {
672                // Use the current transaction's cluster.
673                Some(cluster_id) => TargetCluster::Transaction(cluster_id),
674                // If there isn't a current cluster set for a transaction, then try to auto route.
675                None => coord::catalog_serving::auto_run_on_catalog_server(
676                    &conn_catalog,
677                    session,
678                    &plan,
679                ),
680            };
681            let cluster = catalog.resolve_target_cluster(target_cluster, session)?;
682            (cluster, cluster.id, &cluster.name)
683        };
684
685        // Log cluster selection
686        if let Some(logging_id) = logging.id() {
687            self.log_set_cluster(logging_id, target_cluster_id, target_cluster_name.clone());
688        }
689
690        coord::catalog_serving::check_cluster_restrictions(
691            target_cluster_name.as_str(),
692            &conn_catalog,
693            &plan,
694        )?;
695
696        rbac::check_plan(
697            &conn_catalog,
698            // SideEffectingFunc is handled above (with its own check_plan call) and returns
699            // early, so no target connection role is needed for the remaining plan types here.
700            None,
701            session,
702            &plan,
703            Some(target_cluster_id),
704            &resolved_ids,
705            &sql_impl_ids,
706        )?;
707
708        if let Some(wait_future) =
709            coord::appends::waiting_on_startup_appends(&*catalog, session, &plan)
710        {
711            wait_future.await;
712        }
713
714        let (depends_on, contains_temporal) = match &query_plan {
715            QueryPlan::Select(s) | QueryPlan::CopyTo(s, _) => {
716                (s.source.depends_on(), s.source.contains_temporal())
717            }
718            QueryPlan::Subscribe(s) => (s.from.depends_on(), s.from.contains_temporal()),
719            QueryPlan::ExplainTimestamp(p) => {
720                // The timestamp depends on what the locally optimized query reads: folding can
721                // remove dependencies that the unoptimized query has.
722                let mut optimizer = optimize::view::Optimizer::new(
723                    optimize::OptimizerConfig::from(catalog.system_config()),
724                    None,
725                );
726                let raw_plan = p.raw_plan.clone();
727                // HIR ⇒ MIR lowering and MIR ⇒ MIR optimization (local)
728                let optimized = mz_ore::task::spawn_blocking(
729                    || "optimize explain timestamp",
730                    move || optimizer.catch_unwind_optimize(raw_plan),
731                )
732                .await?;
733                (optimized.depends_on(), optimized.contains_temporal())
734            }
735        };
736
737        let max_query_result_size = Some(session.vars().max_query_result_size());
738
739        let compute_instance_snapshot =
740            ComputeInstanceSnapshot::new_without_collections(cluster.id());
741
742        let optimizer_config = optimize::OptimizerConfig::from(catalog.system_config())
743            .override_from(&catalog.get_cluster(cluster.id()).config.features())
744            // A cluster-scoped LaunchDarkly rule beats a manual `FEATURES` pin.
745            .override_from(
746                &catalog
747                    .state()
748                    .cluster_scoped_optimizer_overrides(cluster.id()),
749            )
750            .override_from(&explain_ctx);
751
752        if cluster.replicas().next().is_none() && explain_ctx.needs_cluster() {
753            return Err(AdapterError::NoClusterReplicasAvailable {
754                name: cluster.name.clone(),
755                is_managed: cluster.is_managed(),
756            });
757        }
758
759        let (_, view_id) = self.transient_id_gen.allocate_id();
760        let (_, index_id) = self.transient_id_gen.allocate_id();
761
762        let target_replica_name = session.vars().cluster_replica();
763        let mut target_replica = target_replica_name
764            .map(|name| {
765                cluster
766                    .replica_id(name)
767                    .ok_or(AdapterError::UnknownClusterReplica {
768                        cluster_name: cluster.name.clone(),
769                        replica_name: name.to_string(),
770                    })
771            })
772            .transpose()?;
773
774        let source_ids = depends_on;
775        // TODO(peek-seq): validate_timeline_context can be expensive in real scenarios (not in
776        // simple benchmarks), because it traverses transitive dependencies even of indexed views and
777        // materialized views (also traversing their MIR plans).
778        let mut timeline_context = catalog.validate_timeline_context(source_ids.iter().copied())?;
779        if matches!(timeline_context, TimelineContext::TimestampIndependent) && contains_temporal {
780            // If the source IDs are timestamp independent but the query contains temporal functions,
781            // then the timeline context needs to be upgraded to timestamp dependent. This is
782            // required because `source_ids` doesn't contain functions.
783            timeline_context = TimelineContext::TimestampDependent;
784        }
785
786        if explain_ctx.checks_log_reads() {
787            let notices = check_log_reads(
788                &catalog,
789                cluster,
790                &source_ids,
791                &mut target_replica,
792                session.vars(),
793            )?;
794            session.add_notices(notices);
795        }
796
797        let isolation_level = session.vars().transaction_isolation().clone();
798        let timeline = Coordinator::get_timeline(&timeline_context);
799        let needs_linearized_read_ts =
800            Coordinator::needs_linearized_read_ts(&isolation_level, when);
801
802        let oracle_read_ts = match timeline {
803            Some(timeline) if needs_linearized_read_ts => {
804                let oracle = self.ensure_oracle(timeline).await?;
805                let oracle_read_ts = oracle.read_ts().await;
806                #[cfg(debug_assertions)]
807                fail::fail_point!("frontend_peek_after_oracle_read");
808                Some(oracle_read_ts)
809            }
810            Some(_) | None => None,
811        };
812
813        let vars = session.vars();
814        let real_time_recency_ts: Option<Timestamp> = if vars.real_time_recency()
815            && vars.transaction_isolation() == &IsolationLevel::StrictSerializable
816            && !session.contains_read_timestamp()
817        {
818            // Only call the coordinator when we actually need real-time recency
819            self.call_coordinator(|tx| Command::DetermineRealTimeRecentTimestamp {
820                source_ids: source_ids.clone(),
821                real_time_recency_timeout: *vars.real_time_recency_timeout(),
822                tx,
823            })
824            .await??
825        } else {
826            None
827        };
828
829        let dataflow_builder =
830            DataflowBuilder::new(catalog.state(), compute_instance_snapshot.clone());
831        let input_id_bundle = dataflow_builder.sufficient_collections(source_ids.clone());
832
833        // Warning: This will be false for AS OF queries, even if we are otherwise inside a
834        // multi-statement transaction. (It's also false for FreshestTableWrite, which is currently
835        // only read-then-write queries, which can't be part of multi-statement transactions, so
836        // FreshestTableWrite doesn't matter.)
837        //
838        // TODO(peek-seq): It's not totally clear to me what the intended semantics are for AS OF
839        // queries inside a transaction: We clearly can't use the transaction timestamp, and we don't
840        // do timedomain validation for AS OF queries, which seems natural. But I'm thinking that it
841        // would be the cleanest to just simply disallow AS OF queries inside transactions.
842        let in_immediate_multi_stmt_txn = session.transaction().in_immediate_multi_stmt_txn(when)
843            && !matches!(query_plan, QueryPlan::Subscribe { .. });
844
845        // Fetch or generate a timestamp for this query and fetch or acquire read holds.
846        let (determination, read_holds) = match session.get_transaction_timestamp_determination() {
847            // Use the transaction's timestamp if it exists and this isn't an AS OF query.
848            // (`in_immediate_multi_stmt_txn` is false for AS OF queries.)
849            Some(
850                determination @ TimestampDetermination {
851                    timestamp_context: TimestampContext::TimelineTimestamp { .. },
852                    ..
853                },
854            ) if in_immediate_multi_stmt_txn => {
855                // This is a subsequent (non-AS OF, non-constant) query in a multi-statement
856                // transaction. We now:
857                // - Validate that the query only accesses collections within the transaction's
858                //   timedomain (which we know from the stored read holds).
859                // - Use the transaction's stored timestamp determination.
860                // - Use the (relevant subset of the) transaction's read holds.
861
862                let txn_read_holds_opt = self
863                    .call_coordinator(|tx| Command::GetTransactionReadHoldsBundle {
864                        conn_id: session.conn_id().clone(),
865                        tx,
866                    })
867                    .await?;
868
869                if let Some(txn_read_holds) = txn_read_holds_opt {
870                    let allowed_id_bundle = txn_read_holds.id_bundle();
871                    let outside = input_id_bundle.difference(&allowed_id_bundle);
872
873                    // Queries without a timestamp and timeline can belong to any existing timedomain.
874                    if determination.timestamp_context.contains_timestamp() && !outside.is_empty() {
875                        let valid_names =
876                            allowed_id_bundle.resolve_names(&*catalog, session.conn_id());
877                        let invalid_names = outside.resolve_names(&*catalog, session.conn_id());
878                        return Err(AdapterError::RelationOutsideTimeDomain {
879                            relations: invalid_names,
880                            names: valid_names,
881                        });
882                    }
883
884                    // Extract the subset of read holds for the collections this query accesses.
885                    let read_holds = txn_read_holds.subset(&input_id_bundle);
886
887                    (determination, read_holds)
888                } else {
889                    // This should never happen: we're in a subsequent query of a multi-statement
890                    // transaction (we have a transaction timestamp), but the coordinator has no
891                    // transaction read holds stored. This indicates a bug in the transaction
892                    // handling.
893                    return Err(AdapterError::Internal(
894                        "Missing transaction read holds for multi-statement transaction"
895                            .to_string(),
896                    ));
897                }
898            }
899            _ => {
900                // There is no timestamp determination yet for this transaction. Either:
901                // - We are not in a multi-statement transaction.
902                // - This is the first (non-AS OF) query in a multi-statement transaction.
903                // - This is an AS OF query.
904                // - This is a constant query (`TimestampContext::NoTimestamp`).
905
906                let timedomain_bundle;
907                let determine_bundle = if in_immediate_multi_stmt_txn {
908                    // This is the first (non-AS OF) query in a multi-statement transaction.
909                    // Determine a timestamp that will be valid for anything in any schema
910                    // referenced by the first query.
911                    timedomain_bundle = timedomain_for(
912                        &*catalog,
913                        &dataflow_builder,
914                        &source_ids,
915                        &timeline_context,
916                        session.conn_id(),
917                        target_cluster_id,
918                    )?;
919                    &timedomain_bundle
920                } else {
921                    // Simply use the inputs of the current query.
922                    &input_id_bundle
923                };
924                let (determination, read_holds) = self
925                    .determine_timestamp(
926                        session,
927                        determine_bundle,
928                        when,
929                        target_cluster_id,
930                        &timeline_context,
931                        oracle_read_ts,
932                        real_time_recency_ts,
933                    )
934                    .await?;
935
936                // If this query pins the timestamp of a multi-statement transaction, store
937                // the read holds in the coordinator, so subsequent queries can validate
938                // against them. The stored holds define the transaction's timedomain, so
939                // only the statement that determines the transaction timestamp may establish
940                // them, over the same id bundle. A timestamp-less determination (e.g. a
941                // constant query) doesn't pin the transaction timestamp, so its holds must
942                // not be stored.
943                if in_immediate_multi_stmt_txn
944                    && determination.timestamp_context.contains_timestamp()
945                {
946                    session.require_coordinator_completion();
947                    self.call_coordinator(|tx| Command::StoreTransactionReadHolds {
948                        conn_id: session.conn_id().clone(),
949                        read_holds: read_holds.clone(),
950                        tx,
951                    })
952                    .await?;
953                }
954
955                (determination, read_holds)
956            }
957        };
958
959        {
960            // Assert that we have a read hold for all the collections in our `input_id_bundle`.
961            for id in input_id_bundle.iter() {
962                let s = read_holds.storage_holds.contains_key(&id);
963                let c = read_holds
964                    .compute_ids()
965                    .map(|(_instance, coll)| coll)
966                    .contains(&id);
967                soft_assert_or_log!(
968                    s || c,
969                    "missing read hold for collection {} in `input_id_bundle`; (in_immediate_multi_stmt_txn: {})",
970                    id,
971                    in_immediate_multi_stmt_txn,
972                );
973            }
974
975            // Assert that each part of the `input_id_bundle` corresponds to the right part of
976            // `read_holds`.
977            for id in input_id_bundle.storage_ids.iter() {
978                soft_assert_or_log!(
979                    read_holds.storage_holds.contains_key(id),
980                    "missing storage read hold for collection {} in `input_id_bundle`; (in_immediate_multi_stmt_txn: {})",
981                    id,
982                    in_immediate_multi_stmt_txn,
983                );
984            }
985            for id in input_id_bundle
986                .compute_ids
987                .iter()
988                .flat_map(|(_instance, colls)| colls)
989            {
990                soft_assert_or_log!(
991                    read_holds
992                        .compute_ids()
993                        .map(|(_instance, coll)| coll)
994                        .contains(id),
995                    "missing compute read hold for collection {} in `input_id_bundle`; (in_immediate_multi_stmt_txn: {})",
996                    id,
997                    in_immediate_multi_stmt_txn,
998                );
999            }
1000        }
1001
1002        if let (Some(logging_id), Some(timestamp), true) = (
1003            logging.id(),
1004            determination.timestamp_context.timestamp(),
1005            query_plan.logs_execution_timestamp(&explain_ctx),
1006        ) {
1007            self.log_set_timestamp(logging_id, *timestamp);
1008        }
1009
1010        // TODO: Checking for only `InTransaction` and not `Implied` (also `Started`?) seems
1011        // arbitrary and we don't recall why we did it (possibly an error!). Change this to always
1012        // set the transaction ops. Decide and document what our policy should be on AS OF queries.
1013        // Maybe they shouldn't be allowed in transactions at all because it's hard to explain
1014        // what's going on there. This should probably get a small design document.
1015
1016        // We only track the peeks in the session if the query doesn't use AS
1017        // OF or we're inside an explicit transaction. The latter case is
1018        // necessary to support PG's `BEGIN` semantics, whose behavior can
1019        // depend on whether or not reads have occurred in the txn.
1020        let requires_linearization = (&explain_ctx).into();
1021        let mut transaction_determination = determination.clone();
1022        match &query_plan {
1023            QueryPlan::Subscribe { .. } => {
1024                if when.is_transactional() && explain_ctx.needs_cluster() {
1025                    session.add_transaction_ops(TransactionOps::Subscribe)?;
1026                }
1027            }
1028            QueryPlan::Select(..) | QueryPlan::CopyTo(..) | QueryPlan::ExplainTimestamp(..) => {
1029                if when.is_transactional() {
1030                    session.add_transaction_ops(TransactionOps::Peeks {
1031                        determination: transaction_determination,
1032                        cluster_id: target_cluster_id,
1033                        requires_linearization,
1034                    })?;
1035                } else if matches!(session.transaction(), &TransactionStatus::InTransaction(_)) {
1036                    // If the query uses AS OF, then ignore the timestamp.
1037                    transaction_determination.timestamp_context = TimestampContext::NoTimestamp;
1038                    session.add_transaction_ops(TransactionOps::Peeks {
1039                        determination: transaction_determination,
1040                        cluster_id: target_cluster_id,
1041                        requires_linearization,
1042                    })?;
1043                }
1044            }
1045        }
1046
1047        // EXPLAIN TIMESTAMP is done once its timestamp is determined.
1048        let query_plan = match query_plan {
1049            QueryPlan::Select(select_plan) => OptimizerInput::Select(select_plan),
1050            QueryPlan::CopyTo(select_plan, copy_to_ctx) => {
1051                OptimizerInput::CopyTo(select_plan, copy_to_ctx)
1052            }
1053            QueryPlan::Subscribe(plan) => OptimizerInput::Subscribe(plan),
1054            QueryPlan::ExplainTimestamp(explain_timestamp_plan) => {
1055                // Test-only synchronization point: parks the statement before the coordinator
1056                // looks up the frontiers of `input_id_bundle`, so a test can drop one of its
1057                // collections in between.
1058                fail::fail_point!("explain_timestamp_before_dispatch");
1059                let explanation = self
1060                    .call_coordinator(|tx| Command::ExplainTimestamp {
1061                        conn_id: session.conn_id().clone(),
1062                        session_wall_time: session.pcx().wall_time,
1063                        cluster_id: target_cluster_id,
1064                        id_bundle: input_id_bundle.clone(),
1065                        determination,
1066                        tx,
1067                    })
1068                    .await??;
1069                let s = match explain_timestamp_plan.format {
1070                    ExplainFormat::Json => serde_json::to_string_pretty(&explanation)
1071                        .expect("failed to serialize explanation"),
1072                    // `AS DOT` is rejected before any work, when the plan is matched.
1073                    ExplainFormat::Text | ExplainFormat::Dot => explanation.to_string(),
1074                };
1075                let rows = vec![Row::pack_slice(&[Datum::from(s.as_str())])];
1076                return Ok(Some(Coordinator::send_immediate_rows(rows)));
1077            }
1078        };
1079
1080        let stats = statistics_oracle(
1081            session,
1082            &source_ids,
1083            &determination.timestamp_context.antichain(),
1084            true,
1085            catalog.system_config(),
1086            &*self.storage_collections,
1087        )
1088        .await
1089        .unwrap_or_else(|_| Box::new(EmptyStatisticsOracle));
1090
1091        // Generate data structures that can be moved to another task where we will perform possibly
1092        // expensive optimizations.
1093        let timestamp_context = determination.timestamp_context.clone();
1094        let subscribe_as_of = determination.subscribe_as_of();
1095        let session_meta = session.meta();
1096        let now = catalog.config().now.clone();
1097        let target_cluster_name = target_cluster_name.clone();
1098        let needs_plan_insights = explain_ctx.needs_plan_insights();
1099        let determination_for_pushdown = if matches!(explain_ctx, ExplainContext::Pushdown) {
1100            // This is a hairy data structure, so avoid this clone if we are not in
1101            // EXPLAIN FILTER PUSHDOWN.
1102            Some(determination.clone())
1103        } else {
1104            None
1105        };
1106
1107        let span = Span::current();
1108
1109        // Prepare data for plan insights if needed
1110        let catalog_for_insights = if needs_plan_insights {
1111            Some(Arc::clone(&catalog))
1112        } else {
1113            None
1114        };
1115        let mut compute_instances = BTreeMap::new();
1116        if needs_plan_insights {
1117            for user_cluster in catalog.user_clusters() {
1118                let snapshot = ComputeInstanceSnapshot::new_without_collections(user_cluster.id);
1119                compute_instances.insert(user_cluster.name.clone(), snapshot);
1120            }
1121        }
1122
1123        let source_ids_for_closure = source_ids.clone();
1124
1125        let optimization_future: JoinHandle<Result<_, AdapterError>> = match query_plan {
1126            OptimizerInput::CopyTo(select_plan, mut copy_to_ctx) => {
1127                let raw_expr = select_plan.source.clone();
1128
1129                // COPY TO path: calculate output_batch_count and create copy_to optimizer
1130                let worker_counts = cluster.replicas().map(|r| {
1131                    let loc = &r.config.location;
1132                    loc.workers().unwrap_or_else(|| loc.num_processes())
1133                });
1134                let max_worker_count = match worker_counts.max() {
1135                    Some(count) => u64::cast_from(count),
1136                    None => {
1137                        return Err(AdapterError::NoClusterReplicasAvailable {
1138                            name: cluster.name.clone(),
1139                            is_managed: cluster.is_managed(),
1140                        });
1141                    }
1142                };
1143                copy_to_ctx.output_batch_count = Some(max_worker_count);
1144
1145                let mut optimizer = optimize::copy_to::Optimizer::new(
1146                    Arc::clone(&catalog),
1147                    compute_instance_snapshot,
1148                    view_id,
1149                    copy_to_ctx,
1150                    optimizer_config,
1151                    self.optimizer_metrics.clone(),
1152                );
1153
1154                mz_ore::task::spawn_blocking(
1155                    || "optimize copy-to",
1156                    move || {
1157                        span.in_scope(|| {
1158                            let _dispatch_guard = explain_ctx.dispatch_guard();
1159
1160                            // COPY TO path: HIR ⇒ local MIR ⇒ resolve ⇒ global LIR.
1161                            let global_lir_plan = optimize::optimize_oneshot(
1162                                &mut optimizer,
1163                                raw_expr.clone(),
1164                                |local_mir_plan| {
1165                                    local_mir_plan.resolve(
1166                                        timestamp_context.clone(),
1167                                        &session_meta,
1168                                        stats,
1169                                    )
1170                                },
1171                            )?;
1172                            Ok(Execution::CopyToS3 {
1173                                global_lir_plan,
1174                                source_ids: source_ids_for_closure,
1175                            })
1176                        })
1177                    },
1178                )
1179            }
1180            OptimizerInput::Select(select_plan) => {
1181                let select_plan = select_plan.clone();
1182                let raw_expr = select_plan.source.clone();
1183
1184                // SELECT/EXPLAIN path: create peek optimizer
1185                let mut optimizer = optimize::peek::Optimizer::new(
1186                    Arc::clone(&catalog),
1187                    compute_instance_snapshot,
1188                    select_plan.finishing.clone(),
1189                    view_id,
1190                    index_id,
1191                    optimizer_config,
1192                    self.optimizer_metrics.clone(),
1193                );
1194
1195                mz_ore::task::spawn_blocking(
1196                    || "optimize peek",
1197                    move || {
1198                        fail::fail_point!("peek_before_optimize");
1199                        span.in_scope(|| {
1200                            let _dispatch_guard = explain_ctx.dispatch_guard();
1201
1202                            // SELECT/EXPLAIN path: HIR ⇒ local MIR ⇒ resolve ⇒
1203                            // global LIR. We capture the result (rather than
1204                            // propagating with `?`) so that a failure can still be
1205                            // routed to `EXPLAIN BROKEN` below.
1206                            let global_lir_plan_result = optimize::optimize_oneshot(
1207                                &mut optimizer,
1208                                raw_expr.clone(),
1209                                |local_mir_plan| {
1210                                    local_mir_plan.resolve(
1211                                        timestamp_context.clone(),
1212                                        &session_meta,
1213                                        stats,
1214                                    )
1215                                },
1216                            )
1217                            .map_err(AdapterError::from);
1218                            let optimization_finished_at = now();
1219
1220                            let create_insights_ctx =
1221                                |optimizer: &optimize::peek::Optimizer,
1222                                 is_notice: bool|
1223                                 -> Option<Box<PlanInsightsContext>> {
1224                                    if !needs_plan_insights {
1225                                        return None;
1226                                    }
1227
1228                                    let catalog = catalog_for_insights.as_ref()?;
1229
1230                                    let enable_re_optimize = if needs_plan_insights {
1231                                        // Disable any plan insights that use the optimizer if we only want the
1232                                        // notice and plan optimization took longer than the threshold. This is
1233                                        // to prevent a situation where optimizing takes a while and there are
1234                                        // lots of clusters, which would delay peek execution by the product of
1235                                        // those.
1236                                        //
1237                                        // (This heuristic doesn't work well, see #9492.)
1238                                        let dyncfgs = catalog.system_config().dyncfgs();
1239                                        let opt_limit = mz_adapter_types::dyncfgs
1240                                        ::PLAN_INSIGHTS_NOTICE_FAST_PATH_CLUSTERS_OPTIMIZE_DURATION
1241                                            .get(dyncfgs);
1242                                        !(is_notice && optimizer.duration() > opt_limit)
1243                                    } else {
1244                                        false
1245                                    };
1246
1247                                    Some(Box::new(PlanInsightsContext {
1248                                        stmt: select_plan
1249                                            .select
1250                                            .as_deref()
1251                                            .map(Clone::clone)
1252                                            .map(Statement::Select),
1253                                        raw_expr: raw_expr.clone(),
1254                                        catalog: Arc::clone(catalog),
1255                                        compute_instances,
1256                                        target_instance: target_cluster_name,
1257                                        metrics: optimizer.metrics().clone(),
1258                                        finishing: optimizer.finishing().clone(),
1259                                        optimizer_config: optimizer.config().clone(),
1260                                        session: session_meta,
1261                                        timestamp_context,
1262                                        view_id: optimizer.select_id(),
1263                                        index_id: optimizer.index_id(),
1264                                        enable_re_optimize,
1265                                    }))
1266                                };
1267
1268                            let global_lir_plan = match global_lir_plan_result {
1269                                Ok(plan) => plan,
1270                                Err(err) => {
1271                                    let result = if let ExplainContext::Plan(explain_ctx) =
1272                                        explain_ctx
1273                                        && explain_ctx.broken
1274                                    {
1275                                        // EXPLAIN BROKEN: log error and continue with defaults
1276                                        tracing::error!(
1277                                            "error while handling EXPLAIN statement: {}",
1278                                            err
1279                                        );
1280                                        Ok(Execution::ExplainPlan {
1281                                            df_meta: Default::default(),
1282                                            explain_ctx,
1283                                            optimizer,
1284                                            insights_ctx: None,
1285                                        })
1286                                    } else {
1287                                        Err(err)
1288                                    };
1289                                    return result;
1290                                }
1291                            };
1292
1293                            match explain_ctx {
1294                                // EXPLAIN TIMESTAMP is done before optimization.
1295                                ExplainContext::Timestamp => {
1296                                    soft_panic_or_log!(
1297                                        "EXPLAIN TIMESTAMP reached peek optimization"
1298                                    );
1299                                    Err(AdapterError::Internal(
1300                                        "EXPLAIN TIMESTAMP reached peek optimization".into(),
1301                                    ))
1302                                }
1303                                ExplainContext::Plan(explain_ctx) => {
1304                                    let (_, df_meta, _) = global_lir_plan.unapply();
1305                                    let insights_ctx = create_insights_ctx(&optimizer, false);
1306                                    Ok(Execution::ExplainPlan {
1307                                        df_meta,
1308                                        explain_ctx,
1309                                        optimizer,
1310                                        insights_ctx,
1311                                    })
1312                                }
1313                                ExplainContext::None => Ok(Execution::Peek {
1314                                    global_lir_plan,
1315                                    optimization_finished_at,
1316                                    plan_insights_optimizer_trace: None,
1317                                    finishing: select_plan.finishing,
1318                                    copy_to: select_plan.copy_to,
1319                                    insights_ctx: None,
1320                                }),
1321                                ExplainContext::PlanInsightsNotice(optimizer_trace) => {
1322                                    let insights_ctx = create_insights_ctx(&optimizer, true);
1323                                    Ok(Execution::Peek {
1324                                        global_lir_plan,
1325                                        optimization_finished_at,
1326                                        plan_insights_optimizer_trace: Some(optimizer_trace),
1327                                        finishing: select_plan.finishing,
1328                                        copy_to: select_plan.copy_to,
1329                                        insights_ctx,
1330                                    })
1331                                }
1332                                ExplainContext::Pushdown => {
1333                                    let (plan, _, _) = global_lir_plan.unapply();
1334                                    let imports = match plan {
1335                                        PeekPlan::SlowPath(plan) => plan
1336                                            .desc
1337                                            .source_imports
1338                                            .into_iter()
1339                                            .filter_map(|(id, import)| {
1340                                                import
1341                                                    .desc
1342                                                    .arguments
1343                                                    .operators
1344                                                    .map(|plan| (id, plan))
1345                                            })
1346                                            .collect(),
1347                                        PeekPlan::FastPath(_) => {
1348                                            std::collections::BTreeMap::default()
1349                                        }
1350                                    };
1351                                    Ok(Execution::ExplainPushdown {
1352                                        imports,
1353                                        determination: determination_for_pushdown
1354                                            .expect("it's present for the ExplainPushdown case"),
1355                                    })
1356                                }
1357                            }
1358                        })
1359                    },
1360                )
1361            }
1362            OptimizerInput::Subscribe(plan) => {
1363                let plan = plan.clone();
1364                let catalog: Arc<Catalog> = Arc::clone(&catalog);
1365                let debug_name = format!("subscribe-{}", index_id);
1366                let mut optimizer = optimize::subscribe::Optimizer::new(
1367                    catalog,
1368                    compute_instance_snapshot.clone(),
1369                    view_id,
1370                    index_id,
1371                    plan.with_snapshot,
1372                    plan.up_to,
1373                    debug_name,
1374                    optimizer_config,
1375                    self.optimizer_metrics.clone(),
1376                );
1377                mz_ore::task::spawn_blocking(
1378                    || "optimize subscribe",
1379                    move || {
1380                        span.in_scope(|| {
1381                            let _dispatch_guard = explain_ctx.dispatch_guard();
1382
1383                            let global_mir_plan = optimizer.catch_unwind_optimize(plan.clone())?;
1384                            let as_of = subscribe_as_of;
1385
1386                            if let Some(up_to) = optimizer.up_to() {
1387                                if as_of > up_to {
1388                                    return Err(AdapterError::AbsurdSubscribeBounds {
1389                                        as_of,
1390                                        up_to,
1391                                    });
1392                                }
1393                            }
1394                            let local_mir_plan =
1395                                global_mir_plan.resolve(Antichain::from_elem(as_of));
1396
1397                            let global_lir_plan = optimizer.catch_unwind_optimize(local_mir_plan);
1398                            if let ExplainContext::Plan(explain_ctx) = explain_ctx {
1399                                let df_meta = match global_lir_plan {
1400                                    Ok(global_lir_plan) => global_lir_plan.unapply().1,
1401                                    // EXPLAIN BROKEN: log the error and continue with defaults.
1402                                    Err(err) if explain_ctx.broken => {
1403                                        tracing::error!(
1404                                            "error while handling EXPLAIN statement: {}",
1405                                            err
1406                                        );
1407                                        Default::default()
1408                                    }
1409                                    Err(err) => return Err(err.into()),
1410                                };
1411                                return Ok(Execution::ExplainSubscribe {
1412                                    df_meta,
1413                                    explain_ctx,
1414                                    sink_id: optimizer.sink_id(),
1415                                    cluster_id: optimizer.cluster_id(),
1416                                    features: optimizer.config().features.clone(),
1417                                    equal_bounds: optimizer.up_to().filter(|up_to| *up_to == as_of),
1418                                });
1419                            }
1420                            let global_lir_plan = global_lir_plan?;
1421                            let optimization_finished_at = now();
1422
1423                            let (df_desc, df_meta) = global_lir_plan.unapply();
1424                            Ok(Execution::Subscribe {
1425                                subscribe_plan: plan,
1426                                df_desc,
1427                                df_meta,
1428                                optimization_finished_at,
1429                            })
1430                        })
1431                    },
1432                )
1433            }
1434        };
1435
1436        let mut optimization_timeout = *session.vars().statement_timeout();
1437        // Timeout of 0 is equivalent to "off", meaning we will wait "forever."
1438        if optimization_timeout == Duration::ZERO {
1439            optimization_timeout = Duration::MAX;
1440        }
1441        // Note: spawn_blocking tasks cannot be cancelled, so on timeout, or when the caller drops
1442        // this future because the client canceled or went away, we stop waiting but the
1443        // optimization task continues running in the background until completion. See
1444        // https://github.com/MaterializeInc/database-issues/issues/8644 for properly cancelling
1445        // optimizer runs.
1446        let optimization_wait =
1447            tokio::time::timeout(optimization_timeout, optimization_future).await;
1448        let optimization_result = match optimization_wait {
1449            Ok(Ok(result)) => result,
1450            Ok(Err(AdapterError::Optimizer(err))) => {
1451                return Err(AdapterError::Internal(format!(
1452                    "internal error in optimizer: {}",
1453                    err
1454                )));
1455            }
1456            Ok(Err(err)) => {
1457                return Err(err);
1458            }
1459            Err(_elapsed) => {
1460                warn!("optimize peek timed out after {:?}", optimization_timeout);
1461                return Err(AdapterError::StatementTimeout);
1462            }
1463        };
1464
1465        // Log optimization finished
1466        if let Some(logging_id) = logging.id() {
1467            self.log_lifecycle_event(logging_id, StatementLifecycleEvent::OptimizationFinished);
1468        }
1469
1470        // Assert that read holds are correct for the execution plan
1471        Self::assert_read_holds_correct(
1472            &read_holds,
1473            &optimization_result,
1474            &determination,
1475            target_cluster_id,
1476            in_immediate_multi_stmt_txn,
1477        );
1478
1479        // Handle the optimization result: either generate EXPLAIN output or continue with execution
1480        match optimization_result {
1481            Execution::ExplainPlan {
1482                df_meta,
1483                explain_ctx,
1484                optimizer,
1485                insights_ctx,
1486            } => {
1487                let rows = explain_plan_inner(
1488                    session,
1489                    &catalog,
1490                    df_meta,
1491                    explain_ctx,
1492                    optimizer,
1493                    insights_ctx,
1494                )
1495                .await?;
1496
1497                Ok(Some(ExecuteResponse::SendingRowsImmediate {
1498                    rows: Box::new(rows.into_row_iter()),
1499                }))
1500            }
1501            Execution::ExplainSubscribe {
1502                df_meta,
1503                explain_ctx,
1504                sink_id,
1505                cluster_id,
1506                features,
1507                equal_bounds,
1508            } => {
1509                if let Some(bound) = equal_bounds {
1510                    session.add_notice(AdapterNotice::EqualSubscribeBounds { bound });
1511                }
1512                let rows = explain_subscribe_inner(
1513                    session,
1514                    &catalog,
1515                    df_meta,
1516                    explain_ctx,
1517                    sink_id,
1518                    cluster_id,
1519                    &features,
1520                )
1521                .await?;
1522
1523                Ok(Some(ExecuteResponse::SendingRowsImmediate {
1524                    rows: Box::new(rows.into_row_iter()),
1525                }))
1526            }
1527            Execution::ExplainPushdown {
1528                imports,
1529                determination,
1530            } => {
1531                let as_of = determination.timestamp_context.antichain();
1532                let mz_now = determination
1533                    .timestamp_context
1534                    .timestamp()
1535                    .map(|t| ResultSpec::value(Datum::MzTimestamp(*t)))
1536                    .unwrap_or_else(ResultSpec::value_all);
1537
1538                Ok(Some(
1539                    coord::sequencer::explain_pushdown_future_inner(
1540                        session,
1541                        &*catalog,
1542                        &self.storage_collections,
1543                        as_of,
1544                        mz_now,
1545                        imports,
1546                    )
1547                    .await
1548                    .await?,
1549                ))
1550            }
1551            Execution::Peek {
1552                global_lir_plan,
1553                optimization_finished_at: _optimization_finished_at,
1554                plan_insights_optimizer_trace,
1555                finishing,
1556                copy_to,
1557                insights_ctx,
1558            } => {
1559                // Continue with normal execution
1560
1561                // The typ here was generated from the HIR SQL type and simply stored in LIR.
1562                let (peek_plan, df_meta, typ) = global_lir_plan.unapply();
1563
1564                if !explain_analyze {
1565                    crate::query_policy::check_query_policies(
1566                        &catalog,
1567                        session,
1568                        target_cluster_id,
1569                        &peek_plan,
1570                    )?;
1571                }
1572
1573                coord::sequencer::emit_optimizer_notices(
1574                    &*catalog,
1575                    session,
1576                    &df_meta.optimizer_notices,
1577                );
1578
1579                // Generate plan insights notice if needed
1580                if let Some(trace) = plan_insights_optimizer_trace {
1581                    let target_cluster = catalog.get_cluster(target_cluster_id);
1582                    let features = OptimizerFeatures::from(catalog.system_config())
1583                        .override_from(&target_cluster.config.features())
1584                        // A cluster-scoped LaunchDarkly rule beats a manual
1585                        // `FEATURES` pin.
1586                        .override_from(
1587                            &catalog
1588                                .state()
1589                                .cluster_scoped_optimizer_overrides(target_cluster_id),
1590                        );
1591                    let insights = trace
1592                        .into_plan_insights(
1593                            &features,
1594                            &catalog.for_session(session),
1595                            Some(finishing.clone()),
1596                            Some(target_cluster),
1597                            df_meta.clone(),
1598                            insights_ctx,
1599                        )
1600                        .await?;
1601                    session.add_notice(AdapterNotice::PlanInsights(insights));
1602                }
1603
1604                let watch_set = logging.id().and_then(|logging_id| {
1605                    self.dependency_watch_set(
1606                        logging_id,
1607                        catalog.state(),
1608                        &input_id_bundle,
1609                        &determination,
1610                    )
1611                });
1612
1613                let max_result_size = catalog.system_config().max_result_size();
1614
1615                // Clone determination if we need it for emit_timestamp_notice, since it may be
1616                // moved into Command::ExecuteSlowPathPeek.
1617                let determination_for_notice = if session.vars().emit_timestamp_notice() {
1618                    Some(determination.clone())
1619                } else {
1620                    None
1621                };
1622
1623                let response = match peek_plan {
1624                    PeekPlan::FastPath(fast_path_plan) => {
1625                        let row_set_finishing_seconds =
1626                            session.metrics().row_set_finishing_seconds().clone();
1627
1628                        let peek_stash_read_batch_size_bytes =
1629                            mz_compute_types::dyncfgs::PEEK_RESPONSE_STASH_READ_BATCH_SIZE_BYTES
1630                                .get(catalog.system_config().dyncfgs());
1631                        let peek_stash_read_memory_budget_bytes =
1632                            mz_compute_types::dyncfgs::PEEK_RESPONSE_STASH_READ_MEMORY_BUDGET_BYTES
1633                                .get(catalog.system_config().dyncfgs());
1634
1635                        self.implement_fast_path_peek_plan(
1636                            fast_path_plan,
1637                            determination.timestamp_context.timestamp_or_default(),
1638                            finishing,
1639                            target_cluster_id,
1640                            target_replica,
1641                            typ,
1642                            max_result_size,
1643                            max_query_result_size,
1644                            row_set_finishing_seconds,
1645                            read_holds,
1646                            peek_stash_read_batch_size_bytes,
1647                            peek_stash_read_memory_budget_bytes,
1648                            session.conn_id().clone(),
1649                            source_ids,
1650                            watch_set,
1651                            logging,
1652                            Arc::clone(&catalog),
1653                            cancellation_epoch,
1654                        )
1655                        .await?
1656                    }
1657                    PeekPlan::SlowPath(dataflow_plan) => {
1658                        session.require_coordinator_completion();
1659                        if let Some(logging_id) = logging.id() {
1660                            self.log_set_transient_index_id(logging_id, dataflow_plan.id);
1661                        }
1662
1663                        let peek = self
1664                            .register_peek(
1665                                target_cluster_id,
1666                                source_ids,
1667                                Arc::clone(&catalog),
1668                                cancellation_epoch,
1669                                logging,
1670                                false,
1671                            )
1672                            .await?;
1673
1674                        let response = self
1675                            .call_coordinator(|tx| Command::ExecuteSlowPathPeek {
1676                                peek,
1677                                dataflow_plan: Box::new(dataflow_plan),
1678                                determination,
1679                                finishing,
1680                                compute_instance: target_cluster_id,
1681                                target_replica,
1682                                intermediate_result_type: typ,
1683                                conn_id: session.conn_id().clone(),
1684                                max_result_size,
1685                                max_query_result_size,
1686                                watch_set,
1687                                tx,
1688                            })
1689                            .await??;
1690                        response
1691                    }
1692                };
1693
1694                // Add timestamp notice if emit_timestamp_notice is enabled
1695                if let Some(determination) = determination_for_notice {
1696                    self.add_timestamp_notice(
1697                        session,
1698                        target_cluster_id,
1699                        input_id_bundle.clone(),
1700                        determination,
1701                    )
1702                    .await?;
1703                }
1704
1705                Ok(Some(match copy_to {
1706                    None => response,
1707                    // COPY TO STDOUT
1708                    Some(format) => ExecuteResponse::CopyTo {
1709                        format,
1710                        resp: Box::new(response),
1711                    },
1712                }))
1713            }
1714            Execution::Subscribe {
1715                subscribe_plan,
1716                df_desc,
1717                df_meta,
1718                optimization_finished_at: _optimization_finished_at,
1719            } => {
1720                cancel_safety.delegate_side_effect();
1721                session.require_coordinator_completion();
1722                crate::query_policy::check_query_policies(
1723                    &catalog,
1724                    session,
1725                    target_cluster_id,
1726                    &df_desc,
1727                )?;
1728                if df_desc.as_of.as_ref().expect("as of set") == &df_desc.until {
1729                    session.add_notice(AdapterNotice::EqualSubscribeBounds {
1730                        bound: *df_desc.until.as_option().expect("as of set"),
1731                    });
1732                }
1733                coord::sequencer::emit_optimizer_notices(
1734                    &*catalog,
1735                    session,
1736                    &df_meta.optimizer_notices,
1737                );
1738
1739                // Test-only synchronization point: parks a subscribe between
1740                // sequencing and dispatch, so a test can land a concurrent DROP
1741                // of a dependency in this window. Used by
1742                // workflow_test_drop_index_during_subscribe_sequencing.
1743                fail::fail_point!("subscribe_before_dispatch");
1744
1745                let response = self
1746                    .call_coordinator(|tx| Command::ExecuteSubscribe {
1747                        df_desc,
1748                        dependency_ids: subscribe_plan.from.depends_on(),
1749                        cluster_id: target_cluster_id,
1750                        replica_id: target_replica,
1751                        conn_id: session.conn_id().clone(),
1752                        session_uuid: session.uuid(),
1753                        read_holds,
1754                        plan: subscribe_plan,
1755                        statement_logging_id: logging.id(),
1756                        tx,
1757                    })
1758                    .await??;
1759                // On success the `Subscribing` response carries the
1760                // coordinator-side logging guard and the protocol layer logs
1761                // the end when the subscribe terminates. On error the
1762                // coordinator logs nothing (`implement_subscribe` creates its
1763                // guard only for the response), so the guard stays armed and
1764                // the caller logs the error.
1765                logging.defuse();
1766                Ok(Some(response))
1767            }
1768            Execution::CopyToS3 {
1769                global_lir_plan,
1770                source_ids,
1771            } => {
1772                cancel_safety.delegate_side_effect();
1773                let (df_desc, df_meta) = global_lir_plan.unapply();
1774
1775                crate::query_policy::check_query_policies(
1776                    &catalog,
1777                    session,
1778                    target_cluster_id,
1779                    &df_desc,
1780                )?;
1781
1782                coord::sequencer::emit_optimizer_notices(
1783                    &*catalog,
1784                    session,
1785                    &df_meta.optimizer_notices,
1786                );
1787
1788                // Extract S3 sink connection info for preflight check
1789                let sink_id = df_desc.sink_id();
1790                let sinks = &df_desc.sink_exports;
1791                if sinks.len() != 1 {
1792                    return Err(AdapterError::Internal(
1793                        "expected exactly one copy to s3 sink".into(),
1794                    ));
1795                }
1796                let (_, sink_desc) = sinks
1797                    .first_key_value()
1798                    .expect("known to be exactly one copy to s3 sink");
1799                let s3_sink_connection = match &sink_desc.connection {
1800                    mz_compute_types::sinks::ComputeSinkConnection::CopyToS3Oneshot(conn) => {
1801                        conn.clone()
1802                    }
1803                    _ => {
1804                        return Err(AdapterError::Internal(
1805                            "expected copy to s3 oneshot sink".into(),
1806                        ));
1807                    }
1808                };
1809
1810                // Perform S3 preflight check in background task (via coordinator).
1811                // This runs slow S3 operations without blocking the coordinator's main task.
1812                session.require_coordinator_completion();
1813                self.call_coordinator(|tx| Command::CopyToPreflight {
1814                    s3_sink_connection,
1815                    sink_id,
1816                    tx,
1817                })
1818                .await??;
1819
1820                // Preflight succeeded, now execute the actual COPY TO dataflow
1821                let watch_set = logging.id().and_then(|logging_id| {
1822                    self.dependency_watch_set(
1823                        logging_id,
1824                        catalog.state(),
1825                        &input_id_bundle,
1826                        &determination,
1827                    )
1828                });
1829
1830                // We keep ownership of end-of-execution logging:
1831                // `implement_copy_to` logs nothing, and the final response,
1832                // success or error, comes back through this command and is
1833                // logged by the caller.
1834                let response = self
1835                    .call_coordinator(|tx| Command::ExecuteCopyTo {
1836                        df_desc: Box::new(df_desc),
1837                        compute_instance: target_cluster_id,
1838                        target_replica,
1839                        source_ids,
1840                        conn_id: session.conn_id().clone(),
1841                        watch_set,
1842                        tx,
1843                    })
1844                    .await??;
1845
1846                Ok(Some(response))
1847            }
1848        }
1849    }
1850
1851    /// Determines the timestamp for a query, acquires read holds that ensure the
1852    /// query remains executable at that time, and returns those.
1853    /// The caller is responsible for eventually dropping those read holds.
1854    ///
1855    /// Note: self is taken &mut because of the lazy fetching in `get_compute_instance_client`.
1856    pub(crate) async fn determine_timestamp(
1857        &mut self,
1858        session: &Session,
1859        id_bundle: &CollectionIdBundle,
1860        when: &QueryWhen,
1861        compute_instance: ComputeInstanceId,
1862        timeline_context: &TimelineContext,
1863        oracle_read_ts: Option<Timestamp>,
1864        real_time_recency_ts: Option<Timestamp>,
1865    ) -> Result<(TimestampDetermination, ReadHolds), AdapterError> {
1866        let isolation_level = session.vars().transaction_isolation();
1867
1868        let (read_holds, upper) = self
1869            .acquire_read_holds_and_least_valid_write(id_bundle)
1870            .await
1871            .map_err(|err| {
1872                AdapterError::concurrent_dependency_drop_from_collection_lookup_error(
1873                    err,
1874                    compute_instance,
1875                )
1876            })?;
1877        let (det, read_holds) = <Coordinator as TimestampProvider>::determine_timestamp_for_inner(
1878            session,
1879            id_bundle,
1880            when,
1881            timeline_context,
1882            oracle_read_ts,
1883            real_time_recency_ts,
1884            isolation_level,
1885            read_holds,
1886            upper.clone(),
1887        )?;
1888
1889        session
1890            .metrics()
1891            .by_cluster()
1892            .determine_timestamp(
1893                compute_instance,
1894                det.respond_immediately(),
1895                *isolation_level,
1896            )
1897            .inc();
1898        if !det.respond_immediately()
1899            && isolation_level.is_bounded_staleness()
1900            && real_time_recency_ts.is_none()
1901        {
1902            // Note down the difference between BoundedStaleness and Serializable into a metric.
1903            if let Some(bs_ts) = det.timestamp_context.timestamp() {
1904                let (serializable_det, _tmp_read_holds) =
1905                    <Coordinator as TimestampProvider>::determine_timestamp_for_inner(
1906                        session,
1907                        id_bundle,
1908                        when,
1909                        timeline_context,
1910                        oracle_read_ts,
1911                        real_time_recency_ts,
1912                        &IsolationLevel::Serializable,
1913                        read_holds.clone(),
1914                        upper,
1915                    )?;
1916                if let Some(serializable) = serializable_det.timestamp_context.timestamp() {
1917                    session
1918                        .metrics()
1919                        .by_cluster()
1920                        .timestamp_difference_for_bounded_staleness_ms(compute_instance)
1921                        .observe(f64::cast_lossy(u64::from(
1922                            serializable.saturating_sub(*bs_ts),
1923                        )));
1924                }
1925            }
1926        }
1927
1928        Ok((det, read_holds))
1929    }
1930
1931    fn assert_read_holds_correct(
1932        read_holds: &ReadHolds,
1933        execution: &Execution,
1934        determination: &TimestampDetermination,
1935        target_cluster_id: ClusterId,
1936        in_immediate_multi_stmt_txn: bool,
1937    ) {
1938        // Extract source_imports, index_imports, as_of, and execution_name based on Execution variant
1939        let (source_imports, index_imports, as_of, execution_name): (
1940            Vec<GlobalId>,
1941            Vec<GlobalId>,
1942            Timestamp,
1943            &str,
1944        ) = match execution {
1945            Execution::Peek {
1946                global_lir_plan, ..
1947            } => match global_lir_plan.peek_plan() {
1948                PeekPlan::FastPath(fast_path_plan) => {
1949                    let (sources, indexes) = match fast_path_plan {
1950                        FastPathPlan::Constant(..) => (vec![], vec![]),
1951                        FastPathPlan::PeekExisting(_coll_id, idx_id, ..) => (vec![], vec![*idx_id]),
1952                        FastPathPlan::PeekPersist(global_id, ..) => (vec![*global_id], vec![]),
1953                    };
1954                    (
1955                        sources,
1956                        indexes,
1957                        determination.timestamp_context.timestamp_or_default(),
1958                        "FastPath",
1959                    )
1960                }
1961                PeekPlan::SlowPath(dataflow_plan) => {
1962                    let as_of = dataflow_plan
1963                        .desc
1964                        .as_of
1965                        .clone()
1966                        .expect("dataflow has an as_of")
1967                        .into_element();
1968                    (
1969                        dataflow_plan.desc.source_imports.keys().cloned().collect(),
1970                        dataflow_plan.desc.index_imports.keys().cloned().collect(),
1971                        as_of,
1972                        "SlowPath",
1973                    )
1974                }
1975            },
1976            Execution::CopyToS3 {
1977                global_lir_plan, ..
1978            } => {
1979                let df_desc = global_lir_plan.df_desc();
1980                let as_of = df_desc
1981                    .as_of
1982                    .clone()
1983                    .expect("dataflow has an as_of")
1984                    .into_element();
1985                (
1986                    df_desc.source_imports.keys().cloned().collect(),
1987                    df_desc.index_imports.keys().cloned().collect(),
1988                    as_of,
1989                    "CopyToS3",
1990                )
1991            }
1992            Execution::ExplainPlan { .. }
1993            | Execution::ExplainSubscribe { .. }
1994            | Execution::ExplainPushdown { .. } => {
1995                // No read holds assertions needed for EXPLAIN variants
1996                return;
1997            }
1998            Execution::Subscribe { df_desc, .. } => {
1999                let as_of = df_desc
2000                    .as_of
2001                    .clone()
2002                    .expect("dataflow has an as_of")
2003                    .into_element();
2004                (
2005                    df_desc.source_imports.keys().cloned().collect(),
2006                    df_desc.index_imports.keys().cloned().collect(),
2007                    as_of,
2008                    "Subscribe",
2009                )
2010            }
2011        };
2012
2013        // Assert that we have some read holds for all the imports of the dataflow.
2014        for id in source_imports.iter() {
2015            soft_assert_or_log!(
2016                read_holds.storage_holds.contains_key(id),
2017                "[{}] missing read hold for the source import {}; (in_immediate_multi_stmt_txn: {})",
2018                execution_name,
2019                id,
2020                in_immediate_multi_stmt_txn,
2021            );
2022        }
2023        for id in index_imports.iter() {
2024            soft_assert_or_log!(
2025                read_holds
2026                    .compute_ids()
2027                    .map(|(_instance, coll)| coll)
2028                    .contains(id),
2029                "[{}] missing read hold for the index import {}; (in_immediate_multi_stmt_txn: {})",
2030                execution_name,
2031                id,
2032                in_immediate_multi_stmt_txn,
2033            );
2034        }
2035
2036        // Also check the holds against the as_of.
2037        for (id, h) in read_holds.storage_holds.iter() {
2038            soft_assert_or_log!(
2039                h.since().less_equal(&as_of),
2040                "[{}] storage read hold at {:?} for collection {} is not enough for as_of {:?}, determination: {:?}; (in_immediate_multi_stmt_txn: {})",
2041                execution_name,
2042                h.since(),
2043                id,
2044                as_of,
2045                determination,
2046                in_immediate_multi_stmt_txn,
2047            );
2048        }
2049        for ((instance, id), h) in read_holds.compute_holds.iter() {
2050            soft_assert_eq_or_log!(
2051                *instance,
2052                target_cluster_id,
2053                "[{}] the read hold on {} is on the wrong cluster; (in_immediate_multi_stmt_txn: {})",
2054                execution_name,
2055                id,
2056                in_immediate_multi_stmt_txn,
2057            );
2058            soft_assert_or_log!(
2059                h.since().less_equal(&as_of),
2060                "[{}] compute read hold at {:?} for collection {} is not enough for as_of {:?}, determination: {:?}; (in_immediate_multi_stmt_txn: {})",
2061                execution_name,
2062                h.since(),
2063                id,
2064                as_of,
2065                determination,
2066                in_immediate_multi_stmt_txn,
2067            );
2068        }
2069    }
2070}
2071
2072/// Enum for branching among various execution steps after optimization
2073enum Execution {
2074    Peek {
2075        global_lir_plan: optimize::peek::GlobalLirPlan,
2076        optimization_finished_at: EpochMillis,
2077        plan_insights_optimizer_trace: Option<OptimizerTrace>,
2078        finishing: RowSetFinishing,
2079        copy_to: Option<plan::CopyFormat>,
2080        insights_ctx: Option<Box<PlanInsightsContext>>,
2081    },
2082    Subscribe {
2083        subscribe_plan: SubscribePlan,
2084        df_desc: mz_compute_types::dataflows::LirDataflowDescription,
2085        df_meta: DataflowMetainfo,
2086        optimization_finished_at: EpochMillis,
2087    },
2088    CopyToS3 {
2089        global_lir_plan: optimize::copy_to::GlobalLirPlan,
2090        source_ids: BTreeSet<GlobalId>,
2091    },
2092    ExplainPlan {
2093        df_meta: DataflowMetainfo,
2094        explain_ctx: ExplainPlanContext,
2095        optimizer: optimize::peek::Optimizer,
2096        insights_ctx: Option<Box<PlanInsightsContext>>,
2097    },
2098    ExplainSubscribe {
2099        df_meta: DataflowMetainfo,
2100        explain_ctx: ExplainPlanContext,
2101        sink_id: GlobalId,
2102        cluster_id: ComputeInstanceId,
2103        features: OptimizerFeatures,
2104        equal_bounds: Option<Timestamp>,
2105    },
2106    ExplainPushdown {
2107        imports:
2108            BTreeMap<GlobalId, mz_expr::MfpPlan<mz_compute_types::plan::scalar::LirScalarExpr>>,
2109        determination: TimestampDetermination,
2110    },
2111}
2112
2113/// Evaluates a COPY TO target URI expression and validates it.
2114fn eval_copy_to_uri(
2115    to: HirScalarExpr,
2116    session: &Session,
2117    catalog_state: &CatalogState,
2118) -> Result<Uri, AdapterError> {
2119    let style = ExprPrepOneShot {
2120        logical_time: EvalTime::NotAvailable,
2121        session,
2122        catalog_state,
2123    };
2124    let mut to = to.lower_uncorrelated(catalog_state.system_config())?;
2125    style.prep_scalar_expr(&mut to)?;
2126    let temp_storage = RowArena::new();
2127    let evaled = to.eval_constant_foldable(&temp_storage)?;
2128    if evaled == Datum::Null {
2129        coord_bail!("COPY TO target value can not be null");
2130    }
2131    let to_url = match Uri::from_str(evaled.unwrap_str()) {
2132        Ok(url) => {
2133            if url.scheme_str() != Some("s3") && url.scheme_str() != Some("gs") {
2134                coord_bail!("only 's3://...' and 'gs://...' urls are supported as COPY TO target");
2135            }
2136            url
2137        }
2138        Err(e) => coord_bail!("could not parse COPY TO target url: {}", e),
2139    };
2140    Ok(to_url)
2141}
2142
2143/// Generates EXPLAIN PLAN output.
2144async fn explain_plan_inner(
2145    session: &Session,
2146    catalog: &Catalog,
2147    df_meta: DataflowMetainfo,
2148    explain_ctx: ExplainPlanContext,
2149    optimizer: peek::Optimizer,
2150    insights_ctx: Option<Box<PlanInsightsContext>>,
2151) -> Result<Vec<Row>, AdapterError> {
2152    let ExplainPlanContext {
2153        config,
2154        format,
2155        stage,
2156        desc,
2157        optimizer_trace,
2158        ..
2159    } = explain_ctx;
2160
2161    let desc = desc.expect("RelationDesc for SelectPlan in EXPLAIN mode");
2162
2163    let session_catalog = catalog.for_session(session);
2164    let expr_humanizer = {
2165        let transient_items = btreemap! {
2166            optimizer.select_id() => TransientItem::new(
2167                Some(vec![GlobalId::Explain.to_string()]),
2168                Some(desc.iter_names().map(|c| c.to_string()).collect()),
2169            )
2170        };
2171        ExprHumanizerExt::new(transient_items, &session_catalog)
2172    };
2173
2174    let finishing = if optimizer.finishing().is_trivial(desc.arity()) {
2175        None
2176    } else {
2177        Some(optimizer.finishing().clone())
2178    };
2179
2180    let target_cluster = catalog.get_cluster(optimizer.cluster_id());
2181    let features = optimizer.config().features.clone();
2182
2183    let rows = optimizer_trace
2184        .into_rows(
2185            format,
2186            &config,
2187            &features,
2188            &expr_humanizer,
2189            finishing,
2190            Some(target_cluster),
2191            df_meta,
2192            stage,
2193            plan::ExplaineeStatementKind::Select,
2194            insights_ctx,
2195        )
2196        .await?;
2197
2198    Ok(rows)
2199}
2200
2201/// Renders the rows of an `EXPLAIN ... SUBSCRIBE` from its optimizer trace.
2202///
2203/// `features` are the optimizer features the `SUBSCRIBE` was optimized with.
2204async fn explain_subscribe_inner(
2205    session: &Session,
2206    catalog: &Catalog,
2207    df_meta: DataflowMetainfo,
2208    explain_ctx: ExplainPlanContext,
2209    sink_id: GlobalId,
2210    cluster_id: ComputeInstanceId,
2211    features: &OptimizerFeatures,
2212) -> Result<Vec<Row>, AdapterError> {
2213    let ExplainPlanContext {
2214        config,
2215        format,
2216        stage,
2217        desc,
2218        optimizer_trace,
2219        ..
2220    } = explain_ctx;
2221
2222    let session_catalog = catalog.for_session(session);
2223    let expr_humanizer = {
2224        let transient_items = btreemap! {
2225            sink_id => TransientItem::new(
2226                Some(vec![GlobalId::Explain.to_string()]),
2227                desc.map(|d| d.iter_names().map(|c| c.to_string()).collect()),
2228            )
2229        };
2230        ExprHumanizerExt::new(transient_items, &session_catalog)
2231    };
2232
2233    let target_cluster = catalog.get_cluster(cluster_id);
2234
2235    let rows = optimizer_trace
2236        .into_rows(
2237            format,
2238            &config,
2239            features,
2240            &expr_humanizer,
2241            None,
2242            Some(target_cluster),
2243            df_meta,
2244            stage,
2245            plan::ExplaineeStatementKind::Subscribe,
2246            None,
2247        )
2248        .await?;
2249
2250    Ok(rows)
2251}
2252
2253/// Creates a statistics oracle for query optimization.
2254async fn statistics_oracle(
2255    session: &Session,
2256    source_ids: &BTreeSet<GlobalId>,
2257    query_as_of: &Antichain<Timestamp>,
2258    is_oneshot: bool,
2259    system_config: &vars::SystemVars,
2260    storage_collections: &dyn StorageCollections,
2261) -> Result<Box<dyn StatisticsOracle>, AdapterError> {
2262    if !session.vars().enable_session_cardinality_estimates() {
2263        let stats: Box<dyn StatisticsOracle> = Box::new(EmptyStatisticsOracle);
2264        return Ok(stats);
2265    }
2266
2267    let timeout = if is_oneshot {
2268        // TODO(mgree): ideally, we would shorten the timeout even more if we think the query could take the fast path
2269        system_config.optimizer_oneshot_stats_timeout()
2270    } else {
2271        system_config.optimizer_stats_timeout()
2272    };
2273
2274    let cached_stats = mz_ore::future::timeout(
2275        timeout,
2276        CachedStatisticsOracle::new(source_ids, query_as_of, storage_collections),
2277    )
2278    .await;
2279
2280    match cached_stats {
2281        Ok(stats) => Ok(Box::new(stats)),
2282        Err(mz_ore::future::TimeoutError::DeadlineElapsed) => {
2283            warn!(
2284                is_oneshot = is_oneshot,
2285                "optimizer statistics collection timed out after {}ms",
2286                timeout.as_millis()
2287            );
2288
2289            Ok(Box::new(EmptyStatisticsOracle))
2290        }
2291        Err(mz_ore::future::TimeoutError::Inner(e)) => Err(AdapterError::Storage(e)),
2292    }
2293}
2294
2295/// Checks whether we should emit diagnostic
2296/// information associated with reading per-replica sources.
2297///
2298/// If an unrecoverable error is found (today: an untargeted read on a
2299/// cluster with a non-1 number of replicas), return that.  Otherwise,
2300/// return a list of associated notices (today: we always emit exactly
2301/// one notice if there are any per-replica log dependencies and if
2302/// `emit_introspection_query_notice` is set, and none otherwise.)
2303fn check_log_reads(
2304    catalog: &Catalog,
2305    cluster: &Cluster,
2306    source_ids: &BTreeSet<GlobalId>,
2307    target_replica: &mut Option<ReplicaId>,
2308    vars: &SessionVars,
2309) -> Result<impl IntoIterator<Item = AdapterNotice>, AdapterError>
2310where
2311{
2312    let log_names = source_ids
2313        .iter()
2314        .map(|gid| catalog.resolve_item_id(gid))
2315        .flat_map(|item_id| catalog.introspection_dependencies(item_id))
2316        .map(|item_id| catalog.get_entry(&item_id).name().item.clone())
2317        .collect::<Vec<_>>();
2318
2319    if log_names.is_empty() {
2320        return Ok(None);
2321    }
2322
2323    // Reading from log sources on replicated clusters is only allowed if a
2324    // target replica is selected. Otherwise, we have no way of knowing which
2325    // replica we read the introspection data from.
2326    let num_replicas = cluster.replicas().count();
2327    if target_replica.is_none() {
2328        if num_replicas == 1 {
2329            *target_replica = cluster.replicas().map(|r| r.replica_id).next();
2330        } else {
2331            return Err(AdapterError::UntargetedLogRead { log_names });
2332        }
2333    }
2334
2335    // Ensure that logging is initialized for the target replica, lest
2336    // we try to read from a non-existing arrangement.
2337    let replica_id = target_replica.expect("set to `Some` above");
2338    let replica = &cluster.replica(replica_id).expect("Replica must exist");
2339    if !replica.config.compute.logging.enabled() {
2340        return Err(AdapterError::IntrospectionDisabled { log_names });
2341    }
2342
2343    Ok(vars
2344        .emit_introspection_query_notice()
2345        .then_some(AdapterNotice::PerReplicaLogRead { log_names }))
2346}
2347
2348#[derive(Debug)]
2349struct CachedStatisticsOracle {
2350    cache: BTreeMap<GlobalId, usize>,
2351}
2352
2353impl CachedStatisticsOracle {
2354    pub async fn new(
2355        ids: &BTreeSet<GlobalId>,
2356        as_of: &Antichain<Timestamp>,
2357        storage_collections: &dyn StorageCollections,
2358    ) -> Result<Self, StorageError> {
2359        let mut cache = BTreeMap::new();
2360
2361        for id in ids {
2362            let stats = storage_collections.snapshot_stats(*id, as_of.clone()).await;
2363
2364            match stats {
2365                Ok(stats) => {
2366                    cache.insert(*id, stats.num_updates);
2367                }
2368                Err(StorageError::IdentifierMissing(id)) => {
2369                    ::tracing::debug!("no statistics for {id}")
2370                }
2371                Err(e) => return Err(e),
2372            }
2373        }
2374
2375        Ok(Self { cache })
2376    }
2377}
2378
2379impl StatisticsOracle for CachedStatisticsOracle {
2380    fn cardinality_estimate(&self, id: GlobalId) -> Option<usize> {
2381        self.cache.get(&id).map(|estimate| *estimate)
2382    }
2383
2384    fn as_map(&self) -> BTreeMap<GlobalId, usize> {
2385        self.cache.clone()
2386    }
2387}