Skip to main content

mz_adapter/coord/
sequencer.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
10// Prevents anyone from accidentally exporting a method from the `inner` module.
11#![allow(clippy::pub_use)]
12
13//! Logic for executing a planned SQL query.
14
15use std::collections::{BTreeMap, BTreeSet};
16use std::str::FromStr;
17use std::sync::Arc;
18use std::time::Duration;
19
20use futures::FutureExt;
21use futures::future::LocalBoxFuture;
22use futures::stream::FuturesOrdered;
23use http::Uri;
24use inner::return_if_err;
25use maplit::btreemap;
26use mz_catalog::memory::objects::Cluster;
27use mz_controller_types::ReplicaId;
28use mz_expr::row::RowCollection;
29use mz_expr::{Eval, MapFilterProject, MirRelationExpr, ResultSpec, RowSetFinishing};
30use mz_ore::cast::CastFrom;
31use mz_ore::tracing::OpenTelemetryContext;
32use mz_persist_client::stats::SnapshotPartStats;
33use mz_repr::explain::{ExprHumanizerExt, TransientItem};
34use mz_repr::{CatalogItemId, Datum, Diff, GlobalId, IntoRowIterator, Row, RowArena, Timestamp};
35use mz_sql::catalog::{CatalogError, SessionCatalog};
36use mz_sql::names::ResolvedIds;
37use mz_sql::plan::{
38    self, AbortTransactionPlan, CommitTransactionPlan, CreateRolePlan, CreateSourcePlanBundle,
39    FetchPlan, HirScalarExpr, MutationKind, Params, Plan, PlanKind, RaisePlan, SideEffectingFunc,
40};
41use mz_sql::rbac;
42use mz_sql::session::metadata::SessionMetadata;
43use mz_sql::session::vars;
44use mz_sql::session::vars::SessionVars;
45use mz_sql_parser::ast::{Raw, Statement};
46use mz_storage_client::client::TableData;
47use mz_storage_client::storage_collections::StorageCollections;
48use mz_storage_types::connections::inline::IntoInlineConnection;
49use mz_storage_types::controller::StorageError;
50use mz_storage_types::stats::RelationPartStats;
51use mz_transform::dataflow::DataflowMetainfo;
52use mz_transform::notice::{OptimizerNoticeApi, OptimizerNoticeKind, RawOptimizerNotice};
53use mz_transform::{EmptyStatisticsOracle, StatisticsOracle};
54use timely::progress::Antichain;
55use tokio::sync::oneshot;
56use tracing::{Instrument, Level, Span, event, warn};
57
58use crate::ExecuteContext;
59use crate::catalog::{Catalog, CatalogState};
60use crate::command::{Command, ExecuteResponse, Response};
61use crate::coord::appends::{DeferredOp, DeferredPlan};
62use crate::coord::validity::PlanValidity;
63use crate::coord::{
64    Coordinator, DeferredPlanStatement, ExplainPlanContext, Message, PlanStatement, TargetCluster,
65    catalog_serving,
66};
67use crate::error::AdapterError;
68use crate::explain::insights::PlanInsightsContext;
69use crate::notice::AdapterNotice;
70use crate::optimize::dataflows::{EvalTime, ExprPrep, ExprPrepOneShot};
71use crate::optimize::peek;
72use crate::session::{
73    EndTransactionAction, Session, StateRevision, TransactionOps, TransactionStatus, WriteOp,
74};
75use crate::util::ClientTransmitter;
76
77// DO NOT make this visible in any way, i.e. do not add any version of
78// `pub` to this mod. The inner `sequence_X` methods are hidden in this
79// private module to prevent anyone from calling them directly. All
80// sequencing should be done through the `sequence_plan` method.
81// This allows us to add catch-all logic that should be applied to all
82// plans in `sequence_plan` and guarantee that no caller can circumvent
83// that logic.
84//
85// The exceptions are:
86//
87// - Creating a role during connection startup. In this scenario, the session has not been properly
88// initialized and we need to skip directly to creating role. We have a specific method,
89// `sequence_create_role_for_startup` for this purpose.
90// - Methods that continue the execution of some plan that was being run asynchronously, such as
91// `sequence_peek_stage` and `sequence_create_connection_stage_finish`.
92// - The frontend peek sequencing temporarily reaches into this module for things that are needed
93//   by both the old and new peek sequencing. TODO(peek-seq): We plan to eliminate this with a
94//   big refactoring after the old peek sequencing is removed.
95
96mod inner;
97
98impl Coordinator {
99    /// BOXED FUTURE: As of Nov 2023 the returned Future from this function was 34KB. This would
100    /// get stored on the stack which is bad for runtime performance, and blow up our stack usage.
101    /// Because of that we purposefully move this Future onto the heap (i.e. Box it).
102    pub(crate) fn sequence_plan(
103        &mut self,
104        mut ctx: ExecuteContext,
105        plan: Plan,
106        resolved_ids: ResolvedIds,
107        sql_impl_resolved_ids: ResolvedIds,
108    ) -> LocalBoxFuture<'_, ()> {
109        async move {
110            let responses = ExecuteResponse::generated_from(&PlanKind::from(&plan));
111            ctx.tx_mut().set_allowed(responses);
112
113            if self.controller.read_only() && !plan.allowed_in_read_only() {
114                ctx.retire(Err(AdapterError::ReadOnly));
115                return;
116            }
117
118            // Check if we're still waiting for any of the builtin table appends from when we
119            // started the Session to complete.
120            if let Some((dependencies, wait_future)) =
121                super::appends::waiting_on_startup_appends(self.catalog(), ctx.session_mut(), &plan)
122            {
123                let conn_id = ctx.session().conn_id();
124                tracing::debug!(%conn_id, "deferring plan for startup appends");
125
126                let role_metadata = ctx.session().role_metadata().clone();
127                let validity =
128                    PlanValidity::new(&self.catalog, dependencies, None, None, role_metadata);
129                let deferred_plan = DeferredPlan {
130                    ctx,
131                    plan,
132                    validity,
133                    requires_locks: BTreeSet::default(),
134                    resolved_ids,
135                    sql_impl_resolved_ids,
136                };
137                // Defer op accepts an optional write lock, but there aren't any writes occurring
138                // here, since the map to `None`.
139                let acquire_future = wait_future.map(|()| None);
140
141                self.defer_op(acquire_future, DeferredOp::Plan(deferred_plan));
142
143                // Return early because our op is deferred on waiting for the builtin writes to
144                // complete.
145                return;
146            };
147
148            // Scope the borrow of the Catalog because we need to mutate the Coordinator state below.
149            let target_cluster = match ctx.session().transaction().cluster() {
150                // Use the current transaction's cluster.
151                Some(cluster_id) => TargetCluster::Transaction(cluster_id),
152                // If there isn't a current cluster set for a transaction, then try to auto route.
153                None => {
154                    let session_catalog = self.catalog.for_session(ctx.session());
155                    catalog_serving::auto_run_on_catalog_server(
156                        &session_catalog,
157                        ctx.session(),
158                        &plan,
159                    )
160                }
161            };
162            let (target_cluster_id, target_cluster_name) = match self
163                .catalog()
164                .resolve_target_cluster(target_cluster, ctx.session())
165            {
166                Ok(cluster) => (Some(cluster.id), Some(cluster.name.clone())),
167                Err(_) => (None, None),
168            };
169
170            if let (Some(cluster_id), Some(cluster_name), Some(statement_id)) = (
171                target_cluster_id,
172                target_cluster_name.clone(),
173                ctx.extra().contents(),
174            ) {
175                self.set_statement_execution_cluster(statement_id, cluster_id, cluster_name);
176            }
177
178            let session_catalog = self.catalog.for_session(ctx.session());
179
180            if let Some(cluster_name) = &target_cluster_name {
181                if let Err(e) = catalog_serving::check_cluster_restrictions(
182                    cluster_name,
183                    &session_catalog,
184                    &plan,
185                ) {
186                    return ctx.retire(Err(e));
187                }
188            }
189
190            // Look up the authenticated role of the connection targeted by
191            // pg_cancel_backend, which check_plan needs for its RBAC check.
192            // Linear search through active connections is fine because this
193            // happens at most once per statement.
194            let target_conn_role = match &plan {
195                Plan::SideEffectingFunc(SideEffectingFunc::PgCancelBackend {
196                    connection_id: Some(connection_id),
197                }) => self
198                    .active_conns()
199                    .into_iter()
200                    .find(|(conn_id, _)| conn_id.unhandled() == *connection_id)
201                    .map(|(_, conn_meta)| *conn_meta.authenticated_role_id()),
202                _ => None,
203            };
204
205            if let Err(e) = rbac::check_plan(
206                &session_catalog,
207                target_conn_role,
208                ctx.session(),
209                &plan,
210                target_cluster_id,
211                &resolved_ids,
212                &sql_impl_resolved_ids,
213            ) {
214                return ctx.retire(Err(e.into()));
215            }
216
217            match plan {
218                Plan::CreateSource(plan) => {
219                    let (item_id, global_id) = return_if_err!(self.allocate_user_id().await, ctx);
220                    let result = self
221                        .sequence_create_source(
222                            &mut ctx,
223                            vec![CreateSourcePlanBundle {
224                                item_id,
225                                global_id,
226                                plan,
227                                resolved_ids,
228                                available_source_references: None,
229                            }],
230                        )
231                        .await;
232                    ctx.retire(result);
233                }
234                Plan::CreateSources(plans) => {
235                    assert!(
236                        resolved_ids.is_empty(),
237                        "each plan has separate resolved_ids"
238                    );
239                    let result = self.sequence_create_source(&mut ctx, plans).await;
240                    ctx.retire(result);
241                }
242                Plan::CreateConnection(plan) => {
243                    self.sequence_create_connection(ctx, plan, resolved_ids)
244                        .await;
245                }
246                Plan::CreateDatabase(plan) => {
247                    let result = self.sequence_create_database(ctx.session_mut(), plan).await;
248                    ctx.retire(result);
249                }
250                Plan::CreateSchema(plan) => {
251                    let result = self.sequence_create_schema(ctx.session_mut(), plan).await;
252                    ctx.retire(result);
253                }
254                Plan::CreateRole(plan) => {
255                    let result = self
256                        .sequence_create_role(Some(ctx.session().conn_id()), plan)
257                        .await;
258                    if let Some(notice) = self.should_emit_rbac_notice(ctx.session()) {
259                        ctx.session().add_notice(notice);
260                    }
261                    ctx.retire(result);
262                }
263                Plan::CreateCluster(plan) => {
264                    let result = self.sequence_create_cluster(ctx.session(), plan).await;
265                    ctx.retire(result);
266                }
267                Plan::CreateClusterReplica(plan) => {
268                    let result = self
269                        .sequence_create_cluster_replica(ctx.session(), plan)
270                        .await;
271                    ctx.retire(result);
272                }
273                Plan::CreateTable(plan) => {
274                    let result = self
275                        .sequence_create_table(&mut ctx, plan, resolved_ids)
276                        .await;
277                    ctx.retire(result);
278                }
279                Plan::CreateSecret(plan) => {
280                    self.sequence_create_secret(ctx, plan).await;
281                }
282                Plan::CreateSink(plan) => {
283                    self.sequence_create_sink(ctx, plan, resolved_ids).await;
284                }
285                Plan::CreateView(plan) => {
286                    self.sequence_create_view(ctx, plan, resolved_ids).await;
287                }
288                Plan::CreateMaterializedView(plan) => {
289                    self.sequence_create_materialized_view(ctx, plan, resolved_ids)
290                        .await;
291                }
292                Plan::CreateIndex(plan) => {
293                    self.sequence_create_index(ctx, plan, resolved_ids).await;
294                }
295                Plan::CreateType(plan) => {
296                    let result = self
297                        .sequence_create_type(ctx.session(), plan, resolved_ids)
298                        .await;
299                    ctx.retire(result);
300                }
301                Plan::CreateNetworkPolicy(plan) => {
302                    let res = self
303                        .sequence_create_network_policy(ctx.session(), plan)
304                        .await;
305                    ctx.retire(res);
306                }
307                Plan::Comment(plan) => {
308                    let result = self.sequence_comment_on(ctx.session(), plan).await;
309                    ctx.retire(result);
310                }
311                Plan::CopyTo(plan) => {
312                    self.sequence_copy_to(ctx, plan, target_cluster).await;
313                }
314                Plan::DropObjects(plan) => {
315                    let result = self.sequence_drop_objects(&mut ctx, plan).await;
316                    ctx.retire(result);
317                }
318                Plan::DropOwned(plan) => {
319                    let result = self.sequence_drop_owned(ctx.session_mut(), plan).await;
320                    ctx.retire(result);
321                }
322                Plan::EmptyQuery => {
323                    ctx.retire(Ok(ExecuteResponse::EmptyQuery));
324                }
325                Plan::ShowAllVariables => {
326                    let result = self.sequence_show_all_variables(ctx.session());
327                    ctx.retire(result);
328                }
329                Plan::ShowVariable(plan) => {
330                    let result = self.sequence_show_variable(ctx.session(), plan);
331                    ctx.retire(result);
332                }
333                Plan::InspectShard(plan) => {
334                    // TODO: Ideally, this await would happen off the main thread.
335                    let result = self.sequence_inspect_shard(ctx.session(), plan).await;
336                    ctx.retire(result);
337                }
338                Plan::SetVariable(plan) => {
339                    let result = self.sequence_set_variable(ctx.session_mut(), plan);
340                    ctx.retire(result);
341                }
342                Plan::ResetVariable(plan) => {
343                    let result = self.sequence_reset_variable(ctx.session_mut(), plan);
344                    ctx.retire(result);
345                }
346                Plan::SetTransaction(plan) => {
347                    let result = self.sequence_set_transaction(ctx.session_mut(), plan);
348                    ctx.retire(result);
349                }
350                Plan::StartTransaction(plan) => {
351                    if matches!(
352                        ctx.session().transaction(),
353                        TransactionStatus::InTransaction(_)
354                    ) {
355                        ctx.session()
356                            .add_notice(AdapterNotice::ExistingTransactionInProgress);
357                    }
358                    let result = ctx.session_mut().start_transaction(
359                        self.now_datetime(),
360                        plan.access,
361                        plan.isolation_level,
362                    );
363                    ctx.retire(result.map(|_| ExecuteResponse::StartedTransaction))
364                }
365                Plan::CommitTransaction(CommitTransactionPlan {
366                    ref transaction_type,
367                })
368                | Plan::AbortTransaction(AbortTransactionPlan {
369                    ref transaction_type,
370                }) => {
371                    // Serialize DDL transactions. Statements that use this mode must return false
372                    // in `must_serialize_ddl()`.
373                    if ctx.session().transaction().is_ddl() {
374                        if let Ok(guard) = self.serialized_ddl.try_lock_owned() {
375                            let prev = self
376                                .active_conns
377                                .get_mut(ctx.session().conn_id())
378                                .expect("connection must exist")
379                                .deferred_lock
380                                .replace(guard);
381                            assert!(
382                                prev.is_none(),
383                                "connections should have at most one lock guard"
384                            );
385                        } else {
386                            self.serialized_ddl.push_back(DeferredPlanStatement {
387                                ctx,
388                                ps: PlanStatement::Plan {
389                                    plan,
390                                    resolved_ids,
391                                    sql_impl_resolved_ids,
392                                },
393                            });
394                            return;
395                        }
396                    }
397
398                    let action = match &plan {
399                        Plan::CommitTransaction(_) => EndTransactionAction::Commit,
400                        Plan::AbortTransaction(_) => EndTransactionAction::Rollback,
401                        _ => unreachable!(),
402                    };
403                    if ctx.session().transaction().is_implicit() && !transaction_type.is_implicit()
404                    {
405                        // In Postgres, if a user sends a COMMIT or ROLLBACK in an
406                        // implicit transaction, a warning is sent warning them.
407                        // (The transaction is still closed and a new implicit
408                        // transaction started, though.)
409                        ctx.session().add_notice(
410                            AdapterNotice::ExplicitTransactionControlInImplicitTransaction,
411                        );
412                    }
413                    self.sequence_end_transaction(ctx, action).await;
414                }
415                Plan::Select(plan) => {
416                    let max = Some(ctx.session().vars().max_query_result_size());
417                    self.sequence_peek(ctx, plan, target_cluster, max).await;
418                }
419                Plan::Subscribe(plan) => {
420                    self.sequence_subscribe(ctx, plan, target_cluster).await;
421                }
422                Plan::SideEffectingFunc(plan) => {
423                    self.sequence_side_effecting_func(ctx, plan).await;
424                }
425                Plan::ShowCreate(plan) => {
426                    ctx.retire(Ok(Self::send_immediate_rows(plan.row)));
427                }
428                Plan::ShowColumns(show_columns_plan) => {
429                    let max = Some(ctx.session().vars().max_query_result_size());
430                    self.sequence_peek(ctx, show_columns_plan.select_plan, target_cluster, max)
431                        .await;
432                }
433                Plan::CopyFrom(plan) => {
434                    self.sequence_copy_from(ctx, plan, target_cluster).await;
435                }
436                Plan::ExplainPlan(plan) => {
437                    self.sequence_explain_plan(ctx, plan, target_cluster).await;
438                }
439                Plan::ExplainPushdown(plan) => {
440                    self.sequence_explain_pushdown(ctx, plan, target_cluster)
441                        .await;
442                }
443                Plan::ExplainSinkSchema(plan) => {
444                    let result = self.sequence_explain_schema(plan);
445                    ctx.retire(result);
446                }
447                Plan::ExplainTimestamp(plan) => {
448                    self.sequence_explain_timestamp(ctx, plan, target_cluster)
449                        .await;
450                }
451                Plan::Insert(plan) => {
452                    self.sequence_insert(ctx, plan).await;
453                }
454                Plan::ReadThenWrite(plan) => {
455                    self.sequence_read_then_write(ctx, plan).await;
456                }
457                Plan::AlterNoop(plan) => {
458                    ctx.retire(Ok(ExecuteResponse::AlteredObject(plan.object_type)));
459                }
460                Plan::AlterCluster(plan) => {
461                    self.sequence_alter_cluster_staged(ctx, plan).await;
462                }
463                Plan::AlterClusterRename(plan) => {
464                    let result = self.sequence_alter_cluster_rename(&mut ctx, plan).await;
465                    ctx.retire(result);
466                }
467                Plan::AlterClusterSwap(plan) => {
468                    let result = self.sequence_alter_cluster_swap(&mut ctx, plan).await;
469                    ctx.retire(result);
470                }
471                Plan::AlterClusterReplicaRename(plan) => {
472                    let result = self
473                        .sequence_alter_cluster_replica_rename(ctx.session(), plan)
474                        .await;
475                    ctx.retire(result);
476                }
477                Plan::AlterConnection(plan) => {
478                    self.sequence_alter_connection(ctx, plan).await;
479                }
480                Plan::AlterSetCluster(plan) => {
481                    let result = self.sequence_alter_set_cluster(ctx.session(), plan).await;
482                    ctx.retire(result);
483                }
484                Plan::AlterRetainHistory(plan) => {
485                    let result = self.sequence_alter_retain_history(&mut ctx, plan).await;
486                    ctx.retire(result);
487                }
488                Plan::AlterSourceTimestampInterval(plan) => {
489                    let result = self
490                        .sequence_alter_source_timestamp_interval(&mut ctx, plan)
491                        .await;
492                    ctx.retire(result);
493                }
494                Plan::AlterItemRename(plan) => {
495                    let result = self.sequence_alter_item_rename(&mut ctx, plan).await;
496                    ctx.retire(result);
497                }
498                Plan::AlterSchemaRename(plan) => {
499                    let result = self.sequence_alter_schema_rename(&mut ctx, plan).await;
500                    ctx.retire(result);
501                }
502                Plan::AlterSchemaSwap(plan) => {
503                    let result = self.sequence_alter_schema_swap(&mut ctx, plan).await;
504                    ctx.retire(result);
505                }
506                Plan::AlterRole(plan) => {
507                    let result = self.sequence_alter_role(ctx.session_mut(), plan).await;
508                    ctx.retire(result);
509                }
510                Plan::AlterSecret(plan) => {
511                    self.sequence_alter_secret(ctx, plan).await;
512                }
513                Plan::AlterSink(plan) => {
514                    self.sequence_alter_sink_prepare(ctx, plan).await;
515                }
516                Plan::AlterSource(plan) => {
517                    let result = self.sequence_alter_source(ctx.session_mut(), plan).await;
518                    ctx.retire(result);
519                }
520                Plan::AlterSystemSet(plan) => {
521                    let result = self.sequence_alter_system_set(ctx.session(), plan).await;
522                    ctx.retire(result);
523                }
524                Plan::AlterSystemReset(plan) => {
525                    let result = self.sequence_alter_system_reset(ctx.session(), plan).await;
526                    ctx.retire(result);
527                }
528                Plan::AlterSystemResetAll(plan) => {
529                    let result = self
530                        .sequence_alter_system_reset_all(ctx.session(), plan)
531                        .await;
532                    ctx.retire(result);
533                }
534                Plan::AlterTableAddColumn(plan) => {
535                    let result = self.sequence_alter_table(&mut ctx, plan).await;
536                    ctx.retire(result);
537                }
538                Plan::AlterMaterializedViewApplyReplacement(plan) => {
539                    self.sequence_alter_materialized_view_apply_replacement_prepare(ctx, plan)
540                        .await;
541                }
542                Plan::AlterNetworkPolicy(plan) => {
543                    let res = self
544                        .sequence_alter_network_policy(ctx.session(), plan)
545                        .await;
546                    ctx.retire(res);
547                }
548                Plan::DiscardTemp => {
549                    self.drop_temp_items(ctx.session().conn_id()).await;
550                    ctx.retire(Ok(ExecuteResponse::DiscardedTemp));
551                }
552                Plan::DiscardAll => {
553                    let ret = if let TransactionStatus::Started(_) = ctx.session().transaction() {
554                        let (_, retire_notify) = self.clear_transaction(ctx.session_mut()).await;
555                        ctx.delay_response_until(retire_notify);
556                        self.drop_temp_items(ctx.session().conn_id()).await;
557                        ctx.session_mut().reset();
558                        Ok(ExecuteResponse::DiscardedAll)
559                    } else {
560                        Err(AdapterError::OperationProhibitsTransaction(
561                            "DISCARD ALL".into(),
562                        ))
563                    };
564                    ctx.retire(ret);
565                }
566                Plan::Declare(plan) => {
567                    self.declare(ctx, plan.name, plan.stmt, plan.sql, plan.params);
568                }
569                Plan::Fetch(FetchPlan {
570                    name,
571                    count,
572                    timeout,
573                }) => {
574                    let ctx_extra = std::mem::take(ctx.extra_mut());
575                    ctx.retire(Ok(ExecuteResponse::Fetch {
576                        name,
577                        count,
578                        timeout,
579                        ctx_extra,
580                    }));
581                }
582                Plan::Close(plan) => {
583                    if ctx.session_mut().remove_portal(&plan.name) {
584                        ctx.retire(Ok(ExecuteResponse::ClosedCursor));
585                    } else {
586                        ctx.retire(Err(AdapterError::UnknownCursor(plan.name)));
587                    }
588                }
589                Plan::Prepare(plan) => {
590                    if ctx
591                        .session()
592                        .get_prepared_statement_unverified(&plan.name)
593                        .is_some()
594                    {
595                        ctx.retire(Err(AdapterError::PreparedStatementExists(plan.name)));
596                    } else {
597                        let state_revision = StateRevision {
598                            catalog_revision: self.catalog().transient_revision(),
599                            session_state_revision: ctx.session().state_revision(),
600                        };
601                        ctx.session_mut().set_prepared_statement(
602                            plan.name,
603                            Some(plan.stmt),
604                            plan.sql,
605                            plan.desc,
606                            state_revision,
607                            self.now(),
608                        );
609                        ctx.retire(Ok(ExecuteResponse::Prepare));
610                    }
611                }
612                Plan::Execute(plan) => {
613                    match self.sequence_execute(ctx.session_mut(), plan) {
614                        Ok(portal_name) => {
615                            let (tx, _, session, extra, response_barriers) = ctx.into_parts();
616                            let command = Message::Command(
617                                OpenTelemetryContext::obtain(),
618                                Command::Execute {
619                                    portal_name,
620                                    session,
621                                    tx: tx.take(),
622                                    outer_ctx_extra: Some(extra),
623                                },
624                            );
625                            if response_barriers.is_empty() {
626                                self.internal_cmd_tx
627                                    .send(command)
628                                    .expect("sending to self.internal_cmd_tx cannot fail");
629                            } else {
630                                let internal_cmd_tx = self.internal_cmd_tx.clone();
631                                mz_ore::task::spawn(
632                                    || "execute_after_response_barriers",
633                                    async move {
634                                        for barrier in response_barriers {
635                                            barrier.await;
636                                        }
637                                        let _ = internal_cmd_tx.send(command);
638                                    },
639                                );
640                            }
641                        }
642                        Err(err) => ctx.retire(Err(err)),
643                    };
644                }
645                Plan::Deallocate(plan) => match plan.name {
646                    Some(name) => {
647                        if ctx.session_mut().remove_prepared_statement(&name) {
648                            ctx.retire(Ok(ExecuteResponse::Deallocate { all: false }));
649                        } else {
650                            ctx.retire(Err(AdapterError::UnknownPreparedStatement(name)));
651                        }
652                    }
653                    None => {
654                        ctx.session_mut().remove_all_prepared_statements();
655                        ctx.retire(Ok(ExecuteResponse::Deallocate { all: true }));
656                    }
657                },
658                Plan::Raise(RaisePlan { severity }) => {
659                    ctx.session()
660                        .add_notice(AdapterNotice::UserRequested { severity });
661                    ctx.retire(Ok(ExecuteResponse::Raised));
662                }
663                Plan::GrantPrivileges(plan) => {
664                    let result = self
665                        .sequence_grant_privileges(ctx.session_mut(), plan)
666                        .await;
667                    ctx.retire(result);
668                }
669                Plan::RevokePrivileges(plan) => {
670                    let result = self
671                        .sequence_revoke_privileges(ctx.session_mut(), plan)
672                        .await;
673                    ctx.retire(result);
674                }
675                Plan::AlterDefaultPrivileges(plan) => {
676                    let result = self
677                        .sequence_alter_default_privileges(ctx.session_mut(), plan)
678                        .await;
679                    ctx.retire(result);
680                }
681                Plan::GrantRole(plan) => {
682                    let result = self.sequence_grant_role(ctx.session_mut(), plan).await;
683                    ctx.retire(result);
684                }
685                Plan::RevokeRole(plan) => {
686                    let result = self.sequence_revoke_role(ctx.session_mut(), plan).await;
687                    ctx.retire(result);
688                }
689                Plan::AlterOwner(plan) => {
690                    let result = self.sequence_alter_owner(ctx.session_mut(), plan).await;
691                    ctx.retire(result);
692                }
693                Plan::ReassignOwned(plan) => {
694                    let result = self.sequence_reassign_owned(ctx.session_mut(), plan).await;
695                    ctx.retire(result);
696                }
697                Plan::ValidateConnection(plan) => {
698                    let connection = plan
699                        .connection
700                        .into_inline_connection(self.catalog().state());
701                    let current_storage_configuration = self.controller.storage.config().clone();
702                    mz_ore::task::spawn(|| "coord::validate_connection", async move {
703                        let res = match connection
704                            .validate(plan.id, &current_storage_configuration)
705                            .await
706                        {
707                            Ok(()) => Ok(ExecuteResponse::ValidatedConnection),
708                            Err(err) => Err(err.into()),
709                        };
710                        ctx.retire(res);
711                    });
712                }
713            }
714        }
715        .instrument(tracing::debug_span!("coord::sequencer::sequence_plan"))
716        .boxed_local()
717    }
718
719    #[mz_ore::instrument(level = "debug")]
720    pub(crate) async fn sequence_execute_single_statement_transaction(
721        &mut self,
722        ctx: ExecuteContext,
723        stmt: Arc<Statement<Raw>>,
724        params: Params,
725    ) {
726        // Put the session into single statement implicit so anything can execute.
727        let (tx, internal_cmd_tx, mut session, extra, response_barriers) = ctx.into_parts();
728        assert!(matches!(session.transaction(), TransactionStatus::Default));
729        session.start_transaction_single_stmt(self.now_datetime());
730        let conn_id = session.conn_id().unhandled();
731
732        // Execute the saved statement in a temp transmitter so we can run COMMIT.
733        let (sub_tx, sub_rx) = oneshot::channel();
734        let sub_ct = ClientTransmitter::new(sub_tx, self.internal_cmd_tx.clone());
735        let sub_ctx = ExecuteContext::from_parts_with_response_barriers(
736            sub_ct,
737            internal_cmd_tx,
738            session,
739            extra,
740            response_barriers,
741        );
742        self.handle_execute_inner(stmt, params, sub_ctx).await;
743
744        // The response can need off-thread processing. Wait for it elsewhere so the coordinator can
745        // continue processing.
746        let internal_cmd_tx = self.internal_cmd_tx.clone();
747        mz_ore::task::spawn(
748            || format!("execute_single_statement:{conn_id}"),
749            async move {
750                let Ok(Response {
751                    result,
752                    session,
753                    otel_ctx,
754                }) = sub_rx.await
755                else {
756                    // Coordinator went away.
757                    return;
758                };
759                otel_ctx.attach_as_parent();
760                let (sub_tx, sub_rx) = oneshot::channel();
761                let _ = internal_cmd_tx.send(Message::Command(
762                    otel_ctx,
763                    Command::Commit {
764                        action: EndTransactionAction::Commit,
765                        session,
766                        tx: sub_tx,
767                    },
768                ));
769                let Ok(commit_response) = sub_rx.await else {
770                    // Coordinator went away.
771                    return;
772                };
773                assert!(matches!(
774                    commit_response.session.transaction(),
775                    TransactionStatus::Default
776                ));
777                // The fake, generated response was already sent to the user and we don't need to
778                // ever send an `Ok(result)` to the user, because they are expecting a response from
779                // a `COMMIT`. So, always send the `COMMIT`'s result if the original statement
780                // succeeded. If it failed, we can send an error and don't need to wrap it or send a
781                // later COMMIT or ROLLBACK.
782                let result = match (result, commit_response.result) {
783                    (Ok(_), commit) => commit,
784                    (Err(result), _) => Err(result),
785                };
786                // We ignore the resp.result because it's not clear what to do if it failed since we
787                // can only send a single ExecuteResponse to tx.
788                tx.send(result, commit_response.session);
789            }
790            .instrument(Span::current()),
791        );
792    }
793
794    /// Creates a role during connection startup.
795    ///
796    /// This should not be called from anywhere except connection startup.
797    #[mz_ore::instrument(level = "debug")]
798    pub(crate) async fn sequence_create_role_for_startup(
799        &mut self,
800        plan: CreateRolePlan,
801    ) -> Result<ExecuteResponse, AdapterError> {
802        // This does not set conn_id because it's not yet in active_conns. That is because we can't
803        // make a ConnMeta until we have a role id which we don't have until after the catalog txn
804        // is committed. Passing None here means the audit log won't have a user set in the event's
805        // user field. This seems fine because it is indeed the system that is creating this role,
806        // not a user request, and the user name is still recorded in the plan, so we aren't losing
807        // information.
808        self.sequence_create_role(None, plan).await
809    }
810
811    pub(crate) fn allocate_transient_id(&self) -> (CatalogItemId, GlobalId) {
812        self.transient_id_gen.allocate_id()
813    }
814
815    fn should_emit_rbac_notice(&self, session: &Session) -> Option<AdapterNotice> {
816        if !rbac::is_rbac_enabled_for_session(self.catalog.system_config(), session) {
817            Some(AdapterNotice::RbacUserDisabled)
818        } else {
819            None
820        }
821    }
822
823    /// Inserts the rows from `constants` into the table identified by `target_id`.
824    ///
825    /// # Panics
826    ///
827    /// Panics if `target_id` doesn't refer to a table.
828    /// Panics if `constants` is not an `MirRelationExpr::Constant`.
829    pub(crate) fn insert_constant(
830        catalog: &Catalog,
831        session: &mut Session,
832        target_id: CatalogItemId,
833        constants: MirRelationExpr,
834    ) -> Result<ExecuteResponse, AdapterError> {
835        // Insert can be queued, so we need to re-verify the id exists.
836        let desc = match catalog.try_get_entry(&target_id) {
837            Some(table) => {
838                // Inserts always happen at the latest version of a table.
839                table.relation_desc_latest().expect("table has desc")
840            }
841            None => {
842                return Err(AdapterError::Catalog(mz_catalog::memory::error::Error {
843                    kind: mz_catalog::memory::error::ErrorKind::Sql(CatalogError::UnknownItem(
844                        target_id.to_string(),
845                    )),
846                }));
847            }
848        };
849
850        match constants.as_const() {
851            Some((rows, ..)) => {
852                let rows = rows.clone()?;
853                for (row, _) in &rows {
854                    for (i, datum) in row.iter().enumerate() {
855                        desc.constraints_met(i, &datum)?;
856                    }
857                }
858                let diffs_plan = plan::SendDiffsPlan {
859                    id: target_id,
860                    updates: rows,
861                    kind: MutationKind::Insert,
862                    returning: Vec::new(),
863                    max_result_size: catalog.system_config().max_result_size(),
864                };
865                Self::send_diffs(session, diffs_plan)
866            }
867            None => panic!(
868                "tried using sequence_insert_constant on non-constant MirRelationExpr\n{}",
869                constants.pretty(),
870            ),
871        }
872    }
873
874    #[mz_ore::instrument(level = "debug")]
875    pub(crate) fn send_diffs(
876        session: &mut Session,
877        mut plan: plan::SendDiffsPlan,
878    ) -> Result<ExecuteResponse, AdapterError> {
879        let affected_rows = {
880            let mut affected_rows = Diff::from(0);
881            let mut all_positive_diffs = true;
882            // If all diffs are positive, the number of affected rows is just the
883            // sum of all unconsolidated diffs.
884            for (_, diff) in plan.updates.iter() {
885                if diff.is_negative() {
886                    all_positive_diffs = false;
887                    break;
888                }
889
890                affected_rows += diff;
891            }
892
893            if !all_positive_diffs {
894                // Consolidate rows. This is useful e.g. for an UPDATE where the row
895                // doesn't change, and we need to reflect that in the number of
896                // affected rows.
897                differential_dataflow::consolidation::consolidate(&mut plan.updates);
898
899                affected_rows = Diff::ZERO;
900                // With retractions, the number of affected rows is not the number
901                // of rows we see, but the sum of the absolute value of their diffs,
902                // e.g. if one row is retracted and another is added, the total
903                // number of rows affected is 2.
904                for (_, diff) in plan.updates.iter() {
905                    affected_rows += diff.abs();
906                }
907            }
908
909            usize::try_from(affected_rows.into_inner()).expect("positive Diff must fit")
910        };
911        event!(
912            Level::TRACE,
913            affected_rows,
914            id = format!("{:?}", plan.id),
915            kind = format!("{:?}", plan.kind),
916            updates = plan.updates.len(),
917            returning = plan.returning.len(),
918        );
919
920        session.add_transaction_ops(TransactionOps::Writes(vec![WriteOp {
921            id: plan.id,
922            rows: TableData::Rows(plan.updates),
923        }]))?;
924        if !plan.returning.is_empty() {
925            let finishing = RowSetFinishing {
926                order_by: Vec::new(),
927                limit: None,
928                offset: 0,
929                project: (0..plan.returning[0].0.iter().count()).collect(),
930            };
931            let max_returned_query_size = session.vars().max_query_result_size();
932            let duration_histogram = session.metrics().row_set_finishing_seconds();
933
934            return match finishing.finish(
935                RowCollection::new(plan.returning, &finishing.order_by),
936                plan.max_result_size,
937                Some(max_returned_query_size),
938                duration_histogram,
939            ) {
940                Ok((rows, _size_bytes)) => Ok(Self::send_immediate_rows(rows)),
941                Err(e) => Err(AdapterError::ResultSize(e)),
942            };
943        }
944        Ok(match plan.kind {
945            MutationKind::Delete => ExecuteResponse::Deleted(affected_rows),
946            MutationKind::Insert => ExecuteResponse::Inserted(affected_rows),
947            MutationKind::Update => ExecuteResponse::Updated(affected_rows / 2),
948        })
949    }
950}
951
952/// Checks whether we should emit diagnostic
953/// information associated with reading per-replica sources.
954///
955/// If an unrecoverable error is found (today: an untargeted read on a
956/// cluster with a non-1 number of replicas), return that.  Otherwise,
957/// return a list of associated notices (today: we always emit exactly
958/// one notice if there are any per-replica log dependencies and if
959/// `emit_introspection_query_notice` is set, and none otherwise.)
960pub(crate) fn check_log_reads(
961    catalog: &Catalog,
962    cluster: &Cluster,
963    source_ids: &BTreeSet<GlobalId>,
964    target_replica: &mut Option<ReplicaId>,
965    vars: &SessionVars,
966) -> Result<impl IntoIterator<Item = AdapterNotice>, AdapterError>
967where
968{
969    let log_names = source_ids
970        .iter()
971        .map(|gid| catalog.resolve_item_id(gid))
972        .flat_map(|item_id| catalog.introspection_dependencies(item_id))
973        .map(|item_id| catalog.get_entry(&item_id).name().item.clone())
974        .collect::<Vec<_>>();
975
976    if log_names.is_empty() {
977        return Ok(None);
978    }
979
980    // Reading from log sources on replicated clusters is only allowed if a
981    // target replica is selected. Otherwise, we have no way of knowing which
982    // replica we read the introspection data from.
983    let num_replicas = cluster.replicas().count();
984    if target_replica.is_none() {
985        if num_replicas == 1 {
986            *target_replica = cluster.replicas().map(|r| r.replica_id).next();
987        } else {
988            return Err(AdapterError::UntargetedLogRead { log_names });
989        }
990    }
991
992    // Ensure that logging is initialized for the target replica, lest
993    // we try to read from a non-existing arrangement.
994    let replica_id = target_replica.expect("set to `Some` above");
995    let replica = &cluster.replica(replica_id).expect("Replica must exist");
996    if !replica.config.compute.logging.enabled() {
997        return Err(AdapterError::IntrospectionDisabled { log_names });
998    }
999
1000    Ok(vars
1001        .emit_introspection_query_notice()
1002        .then_some(AdapterNotice::PerReplicaLogRead { log_names }))
1003}
1004
1005/// Forward notices that we got from the optimizer.
1006pub(crate) fn emit_optimizer_notices(
1007    catalog: &Catalog,
1008    session: &Session,
1009    notices: &[RawOptimizerNotice],
1010) {
1011    // `for_session` below is expensive, so return early if there's nothing to do.
1012    if notices.is_empty() {
1013        return;
1014    }
1015    let humanizer = catalog.for_session(session);
1016    let system_vars = catalog.system_config();
1017    for notice in notices {
1018        let kind = OptimizerNoticeKind::from(notice);
1019        let notice_enabled = match kind {
1020            OptimizerNoticeKind::EqualsNull => system_vars.enable_notices_for_equals_null(),
1021            OptimizerNoticeKind::IndexAlreadyExists => {
1022                system_vars.enable_notices_for_index_already_exists()
1023            }
1024            OptimizerNoticeKind::IndexTooWideForLiteralConstraints => {
1025                system_vars.enable_notices_for_index_too_wide_for_literal_constraints()
1026            }
1027            OptimizerNoticeKind::IndexKeyEmpty => system_vars.enable_notices_for_index_empty_key(),
1028        };
1029        if notice_enabled {
1030            // We don't need to redact the notice parts because
1031            // `emit_optimizer_notices` is only called by the `sequence_~`
1032            // method for the statement that produces that notice.
1033            session.add_notice(AdapterNotice::OptimizerNotice {
1034                notice: notice.message(&humanizer, false).to_string(),
1035                hint: notice.hint(&humanizer, false).to_string(),
1036            });
1037        }
1038        session
1039            .metrics()
1040            .optimization_notices(&[kind.metric_label()])
1041            .inc_by(1);
1042    }
1043}
1044
1045/// Evaluates a COPY TO target URI expression and validates it.
1046///
1047/// This function is shared between the old peek sequencing (sequence_copy_to)
1048/// and the new frontend peek sequencing to avoid code duplication.
1049pub fn eval_copy_to_uri(
1050    to: HirScalarExpr,
1051    session: &Session,
1052    catalog_state: &CatalogState,
1053) -> Result<Uri, AdapterError> {
1054    let style = ExprPrepOneShot {
1055        logical_time: EvalTime::NotAvailable,
1056        session,
1057        catalog_state,
1058    };
1059    let mut to = to.lower_uncorrelated(catalog_state.system_config())?;
1060    style.prep_scalar_expr(&mut to)?;
1061    let temp_storage = RowArena::new();
1062    let evaled = to.eval(&[], &temp_storage)?;
1063    if evaled == Datum::Null {
1064        coord_bail!("COPY TO target value can not be null");
1065    }
1066    let to_url = match Uri::from_str(evaled.unwrap_str()) {
1067        Ok(url) => {
1068            if url.scheme_str() != Some("s3") && url.scheme_str() != Some("gs") {
1069                coord_bail!("only 's3://...' and 'gs://...' urls are supported as COPY TO target");
1070            }
1071            url
1072        }
1073        Err(e) => coord_bail!("could not parse COPY TO target url: {}", e),
1074    };
1075    Ok(to_url)
1076}
1077
1078/// Returns a future that will execute EXPLAIN FILTER PUSHDOWN, i.e., compute the filter pushdown
1079/// statistics for the given collections with the given MFPs.
1080///
1081/// (Shared helper fn between the old and new sequencing. This doesn't take the Coordinator as a
1082/// parameter, but instead just the specifically necessary things are passed in, so that the
1083/// frontend peek sequencing can also call it.)
1084pub(crate) async fn explain_pushdown_future_inner<
1085    I: IntoIterator<Item = (GlobalId, MapFilterProject)>,
1086>(
1087    session: &Session,
1088    catalog: &Catalog,
1089    storage_collections: &Arc<dyn StorageCollections + Send + Sync>,
1090    as_of: Antichain<Timestamp>,
1091    mz_now: ResultSpec<'static>,
1092    imports: I,
1093) -> impl Future<Output = Result<ExecuteResponse, AdapterError>> + use<I> {
1094    let mut explain_timeout = *session.vars().statement_timeout();
1095    // Timeout of 0 is equivalent to "off", meaning we will wait "forever."
1096    if explain_timeout == Duration::ZERO {
1097        explain_timeout = Duration::MAX;
1098    }
1099    let mut futures = FuturesOrdered::new();
1100    for (id, mfp) in imports {
1101        let catalog_entry = catalog.get_entry_by_global_id(&id);
1102        let full_name = catalog
1103            .for_session(session)
1104            .resolve_full_name(&catalog_entry.name);
1105        let name = format!("{}", full_name);
1106        let relation_desc = catalog_entry
1107            .relation_desc()
1108            .expect("source should have a proper desc")
1109            .into_owned();
1110        let stats_future = storage_collections
1111            .snapshot_parts_stats(id, as_of.clone())
1112            .await;
1113
1114        let mz_now = mz_now.clone();
1115        // These futures may block if the source is not yet readable at the as-of;
1116        // stash them in `futures` and only block on them in a separate task.
1117        // TODO(peek-seq): This complication won't be needed once this function will only be called
1118        // from the new peek sequencing, in which case it will be fine to block the current task.
1119        futures.push_back(async move {
1120            let snapshot_stats = match stats_future.await {
1121                Ok(stats) => stats,
1122                Err(e) => return Err(e),
1123            };
1124            let mut total_bytes = 0;
1125            let mut total_parts = 0;
1126            let mut selected_bytes = 0;
1127            let mut selected_parts = 0;
1128            for SnapshotPartStats {
1129                encoded_size_bytes: bytes,
1130                stats,
1131            } in &snapshot_stats.parts
1132            {
1133                let bytes = u64::cast_from(*bytes);
1134                total_bytes += bytes;
1135                total_parts += 1u64;
1136                let selected = match stats {
1137                    None => true,
1138                    Some(stats) => {
1139                        let stats = stats.decode();
1140                        let stats = RelationPartStats::new(
1141                            name.as_str(),
1142                            &snapshot_stats.metrics.pushdown.part_stats,
1143                            &relation_desc,
1144                            &stats,
1145                        );
1146                        stats.may_match_mfp(mz_now.clone(), &mfp)
1147                    }
1148                };
1149
1150                if selected {
1151                    selected_bytes += bytes;
1152                    selected_parts += 1u64;
1153                }
1154            }
1155            Ok(Row::pack_slice(&[
1156                name.as_str().into(),
1157                total_bytes.into(),
1158                selected_bytes.into(),
1159                total_parts.into(),
1160                selected_parts.into(),
1161            ]))
1162        });
1163    }
1164
1165    let fut = async move {
1166        match tokio::time::timeout(
1167            explain_timeout,
1168            futures::TryStreamExt::try_collect::<Vec<_>>(futures),
1169        )
1170        .await
1171        {
1172            Ok(Ok(rows)) => Ok(ExecuteResponse::SendingRowsImmediate {
1173                rows: Box::new(rows.into_row_iter()),
1174            }),
1175            Ok(Err(err)) => Err(err.into()),
1176            Err(_) => Err(AdapterError::StatementTimeout),
1177        }
1178    };
1179    fut
1180}
1181
1182/// Generates EXPLAIN PLAN output.
1183/// (Shared helper fn between the old and new sequencing.)
1184pub(crate) async fn explain_plan_inner(
1185    session: &Session,
1186    catalog: &Catalog,
1187    df_meta: DataflowMetainfo,
1188    explain_ctx: ExplainPlanContext,
1189    optimizer: peek::Optimizer,
1190    insights_ctx: Option<Box<PlanInsightsContext>>,
1191) -> Result<Vec<Row>, AdapterError> {
1192    let ExplainPlanContext {
1193        config,
1194        format,
1195        stage,
1196        desc,
1197        optimizer_trace,
1198        ..
1199    } = explain_ctx;
1200
1201    let desc = desc.expect("RelationDesc for SelectPlan in EXPLAIN mode");
1202
1203    let session_catalog = catalog.for_session(session);
1204    let expr_humanizer = {
1205        let transient_items = btreemap! {
1206            optimizer.select_id() => TransientItem::new(
1207                Some(vec![GlobalId::Explain.to_string()]),
1208                Some(desc.iter_names().map(|c| c.to_string()).collect()),
1209            )
1210        };
1211        ExprHumanizerExt::new(transient_items, &session_catalog)
1212    };
1213
1214    let finishing = if optimizer.finishing().is_trivial(desc.arity()) {
1215        None
1216    } else {
1217        Some(optimizer.finishing().clone())
1218    };
1219
1220    let target_cluster = catalog.get_cluster(optimizer.cluster_id());
1221    let features = optimizer.config().features.clone();
1222
1223    let rows = optimizer_trace
1224        .into_rows(
1225            format,
1226            &config,
1227            &features,
1228            &expr_humanizer,
1229            finishing,
1230            Some(target_cluster),
1231            df_meta,
1232            stage,
1233            plan::ExplaineeStatementKind::Select,
1234            insights_ctx,
1235        )
1236        .await?;
1237
1238    Ok(rows)
1239}
1240
1241/// Creates a statistics oracle for query optimization.
1242///
1243/// This is a free-standing function that can be called from both the old peek sequencing
1244/// and the new frontend peek sequencing.
1245pub(crate) async fn statistics_oracle(
1246    session: &Session,
1247    source_ids: &BTreeSet<GlobalId>,
1248    query_as_of: &Antichain<Timestamp>,
1249    is_oneshot: bool,
1250    system_config: &vars::SystemVars,
1251    storage_collections: &dyn StorageCollections,
1252) -> Result<Box<dyn StatisticsOracle>, AdapterError> {
1253    if !session.vars().enable_session_cardinality_estimates() {
1254        let stats: Box<dyn StatisticsOracle> = Box::new(EmptyStatisticsOracle);
1255        return Ok(stats);
1256    }
1257
1258    let timeout = if is_oneshot {
1259        // TODO(mgree): ideally, we would shorten the timeout even more if we think the query could take the fast path
1260        system_config.optimizer_oneshot_stats_timeout()
1261    } else {
1262        system_config.optimizer_stats_timeout()
1263    };
1264
1265    let cached_stats = mz_ore::future::timeout(
1266        timeout,
1267        CachedStatisticsOracle::new(source_ids, query_as_of, storage_collections),
1268    )
1269    .await;
1270
1271    match cached_stats {
1272        Ok(stats) => Ok(Box::new(stats)),
1273        Err(mz_ore::future::TimeoutError::DeadlineElapsed) => {
1274            warn!(
1275                is_oneshot = is_oneshot,
1276                "optimizer statistics collection timed out after {}ms",
1277                timeout.as_millis()
1278            );
1279
1280            Ok(Box::new(EmptyStatisticsOracle))
1281        }
1282        Err(mz_ore::future::TimeoutError::Inner(e)) => Err(AdapterError::Storage(e)),
1283    }
1284}
1285
1286#[derive(Debug)]
1287struct CachedStatisticsOracle {
1288    cache: BTreeMap<GlobalId, usize>,
1289}
1290
1291impl CachedStatisticsOracle {
1292    pub async fn new(
1293        ids: &BTreeSet<GlobalId>,
1294        as_of: &Antichain<Timestamp>,
1295        storage_collections: &dyn StorageCollections,
1296    ) -> Result<Self, StorageError> {
1297        let mut cache = BTreeMap::new();
1298
1299        for id in ids {
1300            let stats = storage_collections.snapshot_stats(*id, as_of.clone()).await;
1301
1302            match stats {
1303                Ok(stats) => {
1304                    cache.insert(*id, stats.num_updates);
1305                }
1306                Err(StorageError::IdentifierMissing(id)) => {
1307                    ::tracing::debug!("no statistics for {id}")
1308                }
1309                Err(e) => return Err(e),
1310            }
1311        }
1312
1313        Ok(Self { cache })
1314    }
1315}
1316
1317impl StatisticsOracle for CachedStatisticsOracle {
1318    fn cardinality_estimate(&self, id: GlobalId) -> Option<usize> {
1319        self.cache.get(&id).map(|estimate| *estimate)
1320    }
1321
1322    fn as_map(&self) -> BTreeMap<GlobalId, usize> {
1323        self.cache.clone()
1324    }
1325}