Skip to main content

mz_adapter/
coord.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//! Translation of SQL commands into timestamped `Controller` commands.
11//!
12//! The various SQL commands instruct the system to take actions that are not
13//! yet explicitly timestamped. On the other hand, the underlying data continually
14//! change as time moves forward. On the third hand, we greatly benefit from the
15//! information that some times are no longer of interest, so that we may
16//! compact the representation of the continually changing collections.
17//!
18//! The [`Coordinator`] curates these interactions by observing the progress
19//! collections make through time, choosing timestamps for its own commands,
20//! and eventually communicating that certain times have irretrievably "passed".
21//!
22//! ## Frontiers another way
23//!
24//! If the above description of frontiers left you with questions, this
25//! repackaged explanation might help.
26//!
27//! - `since` is the least recent time (i.e. oldest time) that you can read
28//!   from sources and be guaranteed that the returned data is accurate as of
29//!   that time.
30//!
31//!   Reads at times less than `since` may return values that were not actually
32//!   seen at the specified time, but arrived later (i.e. the results are
33//!   compacted).
34//!
35//!   For correctness' sake, the coordinator never chooses to read at a time
36//!   less than an arrangement's `since`.
37//!
38//! - `upper` is the first time after the most recent time that you can read
39//!   from sources and receive an immediate response. Alternately, it is the
40//!   least time at which the data may still change (that is the reason we may
41//!   not be able to respond immediately).
42//!
43//!   Reads at times >= `upper` may not immediately return because the answer
44//!   isn't known yet. However, once the `upper` is > the specified read time,
45//!   the read can return.
46//!
47//!   For the sake of returned values' freshness, the coordinator prefers
48//!   performing reads at an arrangement's `upper`. However, because we more
49//!   strongly prefer correctness, the coordinator will choose timestamps
50//!   greater than an object's `upper` if it is also being accessed alongside
51//!   objects whose `since` times are >= its `upper`.
52//!
53//! This illustration attempts to show, with time moving left to right, the
54//! relationship between `since` and `upper`.
55//!
56//! - `#`: possibly inaccurate results
57//! - `-`: immediate, correct response
58//! - `?`: not yet known
59//! - `s`: since
60//! - `u`: upper
61//! - `|`: eligible for coordinator to select
62//!
63//! ```nofmt
64//! ####s----u?????
65//!     |||||||||||
66//! ```
67//!
68
69use std::borrow::Cow;
70use std::collections::{BTreeMap, BTreeSet, VecDeque};
71use std::net::IpAddr;
72use std::num::NonZeroI64;
73use std::ops::Neg;
74use std::str::FromStr;
75use std::sync::LazyLock;
76use std::sync::{Arc, Mutex};
77use std::thread;
78use std::time::{Duration, Instant};
79use std::{fmt, mem};
80
81use anyhow::Context;
82use chrono::{DateTime, Utc};
83use derivative::Derivative;
84use differential_dataflow::lattice::Lattice;
85use fail::fail_point;
86use futures::StreamExt;
87use futures::future::{BoxFuture, FutureExt, LocalBoxFuture};
88use http::Uri;
89use ipnet::IpNet;
90use itertools::{Either, Itertools};
91use mz_adapter_types::bootstrap_builtin_cluster_config::BootstrapBuiltinClusterConfig;
92use mz_adapter_types::compaction::CompactionWindow;
93use mz_adapter_types::connection::ConnectionId;
94use mz_adapter_types::dyncfgs::{
95    USER_ID_POOL_BATCH_SIZE, WITH_0DT_DEPLOYMENT_CAUGHT_UP_CHECK_INTERVAL,
96};
97use mz_auth::password::Password;
98use mz_build_info::BuildInfo;
99use mz_catalog::builtin::{BUILTINS, BUILTINS_STATIC, MZ_AUDIT_EVENTS, MZ_STORAGE_USAGE_BY_SHARD};
100use mz_catalog::config::{AwsPrincipalContext, BuiltinItemMigrationConfig, ClusterReplicaSizeMap};
101use mz_catalog::durable::{AuditLogIterator, OpenableDurableCatalogState};
102use mz_catalog::expr_cache::{GlobalExpressions, LocalExpressions};
103use mz_catalog::memory::objects::{
104    CatalogEntry, CatalogItem, ClusterReplicaProcessStatus, ClusterVariantManaged, Connection,
105    DataSourceDesc, StateDiff, StateUpdate, StateUpdateKind, Table, TableDataSource,
106};
107use mz_cloud_resources::{CloudResourceController, VpcEndpointConfig, VpcEndpointEvent};
108use mz_compute_client::as_of_selection;
109use mz_compute_client::controller::error::{
110    CollectionLookupError, CollectionMissing, DataflowCreationError, InstanceMissing,
111};
112use mz_compute_types::ComputeInstanceId;
113use mz_compute_types::dataflows::DataflowDescription;
114use mz_compute_types::plan::Plan;
115use mz_controller::clusters::{
116    ClusterConfig, ClusterEvent, ClusterStatus, ProcessId, ReplicaLocation,
117};
118use mz_controller::{ControllerConfig, Readiness};
119use mz_controller_types::{ClusterId, ReplicaId, WatchSetId};
120use mz_expr::{MapFilterProject, MirRelationExpr, OptimizedMirRelationExpr, RowSetFinishing};
121use mz_license_keys::ValidatedLicenseKey;
122use mz_orchestrator::OfflineReason;
123use mz_ore::cast::{CastFrom, CastInto, CastLossy};
124use mz_ore::channel::trigger::Trigger;
125use mz_ore::future::TimeoutError;
126use mz_ore::metrics::MetricsRegistry;
127use mz_ore::now::{EpochMillis, NowFn};
128use mz_ore::task::{JoinHandle, spawn};
129use mz_ore::thread::JoinHandleExt;
130use mz_ore::tracing::{OpenTelemetryContext, TracingHandle};
131use mz_ore::url::SensitiveUrl;
132use mz_ore::{
133    assert_none, instrument, soft_assert_eq_or_log, soft_assert_or_log, soft_panic_or_log, stack,
134};
135use mz_persist_client::PersistClient;
136use mz_persist_client::batch::ProtoBatch;
137use mz_persist_client::usage::{ShardsUsageReferenced, StorageUsageClient};
138use mz_repr::adt::numeric::Numeric;
139use mz_repr::explain::{ExplainConfig, ExplainFormat};
140use mz_repr::global_id::TransientIdGen;
141use mz_repr::optimize::{OptimizerFeatures, OverrideFrom};
142use mz_repr::role_id::RoleId;
143use mz_repr::{CatalogItemId, Diff, GlobalId, RelationDesc, SqlRelationType, Timestamp};
144use mz_secrets::cache::CachingSecretsReader;
145use mz_secrets::{SecretsController, SecretsReader};
146use mz_sql::ast::{Raw, Statement};
147use mz_sql::catalog::{CatalogCluster, EnvironmentId};
148use mz_sql::names::{QualifiedItemName, ResolvedIds, SchemaSpecifier};
149use mz_sql::optimizer_metrics::OptimizerMetrics;
150use mz_sql::plan::{
151    self, AlterSinkPlan, ConnectionDetails, CreateConnectionPlan, HirRelationExpr,
152    NetworkPolicyRule, OnTimeoutAction, Params, QueryWhen,
153};
154use mz_sql::session::user::User;
155use mz_sql::session::vars::{MAX_CREDIT_CONSUMPTION_RATE, SystemVars, Var};
156use mz_sql_parser::ast::ExplainStage;
157use mz_sql_parser::ast::display::AstDisplay;
158use mz_storage_client::client::TableData;
159use mz_storage_client::controller::{CollectionDescription, DataSource, ExportDescription};
160use mz_storage_types::connections::Connection as StorageConnection;
161use mz_storage_types::connections::ConnectionContext;
162use mz_storage_types::connections::inline::{IntoInlineConnection, ReferencedConnection};
163use mz_storage_types::read_holds::ReadHold;
164use mz_storage_types::sinks::{S3SinkFormat, StorageSinkDesc};
165use mz_storage_types::sources::kafka::KAFKA_PROGRESS_DESC;
166use mz_storage_types::sources::{IngestionDescription, SourceExport, Timeline};
167use mz_timestamp_oracle::{TimestampOracleConfig, WriteTimestamp};
168use mz_transform::dataflow::DataflowMetainfo;
169use opentelemetry::trace::TraceContextExt;
170use serde::Serialize;
171use thiserror::Error;
172use timely::progress::{Antichain, Timestamp as _};
173use tokio::runtime::Handle as TokioHandle;
174use tokio::select;
175use tokio::sync::{OwnedMutexGuard, mpsc, oneshot, watch};
176use tokio::time::{Interval, MissedTickBehavior};
177use tracing::{Instrument, Level, Span, debug, info, info_span, span, warn};
178use tracing_opentelemetry::OpenTelemetrySpanExt;
179use uuid::Uuid;
180
181use crate::active_compute_sink::{ActiveComputeSink, ActiveCopyFrom};
182use crate::catalog::{BuiltinTableUpdate, Catalog, OpenCatalogResult};
183use crate::client::{Client, Handle};
184use crate::command::{Command, ExecuteResponse};
185use crate::config::{SynchronizedParameters, SystemParameterFrontend, SystemParameterSyncConfig};
186use crate::coord::appends::{
187    BuiltinTableAppendNotify, DeferredOp, GroupCommitPermit, PendingWriteTxn,
188};
189use crate::coord::caught_up::CaughtUpCheckContext;
190use crate::coord::cluster_scheduling::SchedulingDecision;
191use crate::coord::id_bundle::CollectionIdBundle;
192use crate::coord::introspection::IntrospectionSubscribe;
193use crate::coord::peek::PendingPeek;
194use crate::coord::statement_logging::StatementLogging;
195use crate::coord::timeline::{TimelineContext, TimelineState};
196use crate::coord::timestamp_selection::{TimestampContext, TimestampDetermination};
197use crate::coord::validity::PlanValidity;
198use crate::error::AdapterError;
199use crate::explain::insights::PlanInsightsContext;
200use crate::explain::optimizer_trace::{DispatchGuard, OptimizerTrace};
201use crate::metrics::Metrics;
202use crate::optimize::dataflows::{ComputeInstanceSnapshot, DataflowBuilder};
203use crate::optimize::{self, Optimize, OptimizerConfig};
204use crate::session::{EndTransactionAction, Session};
205use crate::statement_logging::{
206    StatementEndedExecutionReason, StatementLifecycleEvent, StatementLoggingId,
207};
208use crate::util::{ClientTransmitter, ResultExt, sort_topological};
209use crate::webhook::{WebhookAppenderInvalidator, WebhookConcurrencyLimiter};
210use crate::{AdapterNotice, ReadHolds, flags};
211
212pub(crate) mod appends;
213pub(crate) mod catalog_serving;
214pub(crate) mod cluster_scheduling;
215pub(crate) mod consistency;
216pub(crate) mod id_bundle;
217pub(crate) mod in_memory_oracle;
218pub(crate) mod peek;
219pub(crate) mod read_policy;
220pub(crate) mod sequencer;
221pub(crate) mod statement_logging;
222pub(crate) mod timeline;
223pub(crate) mod timestamp_selection;
224
225pub mod catalog_implications;
226mod caught_up;
227mod command_handler;
228mod ddl;
229mod indexes;
230mod introspection;
231mod message_handler;
232mod privatelink_status;
233mod sql;
234mod validity;
235
236/// A pool of pre-allocated user IDs to avoid per-DDL persist writes.
237///
238/// IDs in the range `[next, upper)` are available for allocation.
239/// When exhausted, the pool must be refilled via the catalog.
240///
241/// # Correctness
242///
243/// The pool is owned by [`Coordinator`], which processes all requests
244/// on a single-threaded event loop. Because every access requires
245/// `&mut self` on the coordinator, there is no concurrent access to the
246/// pool — no additional synchronization is needed.
247///
248/// Global ID uniqueness is guaranteed because each refill calls
249/// [`Catalog::allocate_user_ids`], which performs a durable persist
250/// write that atomically reserves the entire batch before any IDs from
251/// it are handed out. If the process crashes after a refill but before
252/// all pre-allocated IDs are consumed, the unused IDs form harmless
253/// gaps in the sequence — user IDs are not required to be contiguous.
254///
255/// This guarantee holds even if multiple `environmentd` processes run
256/// concurrently. Each process has its own independent pool,
257/// but every refill goes through the shared persist-backed catalog,
258/// which serializes allocations across all callers. Two processes
259/// will therefore never receive overlapping ID ranges,
260/// for the same reason they could not before this pool existed.
261#[derive(Debug)]
262pub(crate) struct IdPool {
263    next: u64,
264    upper: u64,
265}
266
267impl IdPool {
268    /// Creates an empty pool.
269    pub fn empty() -> Self {
270        IdPool { next: 0, upper: 0 }
271    }
272
273    /// Allocates a single ID from the pool, returning `None` if exhausted.
274    pub fn allocate(&mut self) -> Option<u64> {
275        if self.next < self.upper {
276            let id = self.next;
277            self.next += 1;
278            Some(id)
279        } else {
280            None
281        }
282    }
283
284    /// Allocates `n` consecutive IDs from the pool, returning `None` if
285    /// insufficient IDs remain.
286    pub fn allocate_many(&mut self, n: u64) -> Option<Vec<u64>> {
287        if self.remaining() >= n {
288            let ids = (self.next..self.next + n).collect();
289            self.next += n;
290            Some(ids)
291        } else {
292            None
293        }
294    }
295
296    /// Returns the number of IDs remaining in the pool.
297    pub fn remaining(&self) -> u64 {
298        self.upper - self.next
299    }
300
301    /// Refills the pool with the given range `[next, upper)`.
302    pub fn refill(&mut self, next: u64, upper: u64) {
303        assert!(next <= upper, "invalid pool range: {next}..{upper}");
304        self.next = next;
305        self.upper = upper;
306    }
307}
308
309#[derive(Debug)]
310pub enum Message {
311    Command(OpenTelemetryContext, Command),
312    ControllerReady {
313        controller: ControllerReadiness,
314    },
315    PurifiedStatementReady(PurifiedStatementReady),
316    CreateConnectionValidationReady(CreateConnectionValidationReady),
317    AlterConnectionValidationReady(AlterConnectionValidationReady),
318    TryDeferred {
319        /// The connection that created this op.
320        conn_id: ConnectionId,
321        /// The write lock that notified us our deferred op might be able to run.
322        ///
323        /// Note: While we never want to hold a partial set of locks, it can be important to hold
324        /// onto the _one_ that notified us our op might be ready. If there are multiple operations
325        /// waiting on a single collection, and we don't hold this lock through retyring the op,
326        /// then everything waiting on this collection will get retried causing traffic in the
327        /// Coordinator's message queue.
328        ///
329        /// See [`DeferredOp::can_be_optimistically_retried`] for more detail.
330        acquired_lock: Option<(CatalogItemId, tokio::sync::OwnedMutexGuard<()>)>,
331    },
332    /// Initiates a group commit.
333    GroupCommitInitiate(Span, Option<GroupCommitPermit>),
334    DeferredStatementReady,
335    AdvanceTimelines,
336    ClusterEvent(ClusterEvent),
337    CancelPendingPeeks {
338        conn_id: ConnectionId,
339    },
340    LinearizeReads,
341    StagedBatches {
342        conn_id: ConnectionId,
343        table_id: CatalogItemId,
344        batches: Vec<Result<ProtoBatch, String>>,
345    },
346    StorageUsageSchedule,
347    StorageUsageFetch,
348    StorageUsageUpdate(ShardsUsageReferenced),
349    StorageUsagePrune(Vec<BuiltinTableUpdate>),
350    /// Performs any cleanup and logging actions necessary for
351    /// finalizing a statement execution.
352    RetireExecute {
353        data: ExecuteContextExtra,
354        otel_ctx: OpenTelemetryContext,
355        reason: StatementEndedExecutionReason,
356    },
357    ExecuteSingleStatementTransaction {
358        ctx: ExecuteContext,
359        otel_ctx: OpenTelemetryContext,
360        stmt: Arc<Statement<Raw>>,
361        params: mz_sql::plan::Params,
362    },
363    PeekStageReady {
364        ctx: ExecuteContext,
365        span: Span,
366        stage: PeekStage,
367    },
368    CreateIndexStageReady {
369        ctx: ExecuteContext,
370        span: Span,
371        stage: CreateIndexStage,
372    },
373    CreateViewStageReady {
374        ctx: ExecuteContext,
375        span: Span,
376        stage: CreateViewStage,
377    },
378    CreateMaterializedViewStageReady {
379        ctx: ExecuteContext,
380        span: Span,
381        stage: CreateMaterializedViewStage,
382    },
383    SubscribeStageReady {
384        ctx: ExecuteContext,
385        span: Span,
386        stage: SubscribeStage,
387    },
388    IntrospectionSubscribeStageReady {
389        span: Span,
390        stage: IntrospectionSubscribeStage,
391    },
392    SecretStageReady {
393        ctx: ExecuteContext,
394        span: Span,
395        stage: SecretStage,
396    },
397    ClusterStageReady {
398        ctx: ExecuteContext,
399        span: Span,
400        stage: ClusterStage,
401    },
402    ExplainTimestampStageReady {
403        ctx: ExecuteContext,
404        span: Span,
405        stage: ExplainTimestampStage,
406    },
407    DrainStatementLog,
408    PrivateLinkVpcEndpointEvents(Vec<VpcEndpointEvent>),
409    CheckSchedulingPolicies,
410
411    /// Scheduling policy decisions about turning clusters On/Off.
412    /// `Vec<(policy name, Vec of decisions by the policy)>`
413    /// A cluster will be On if and only if there is at least one On decision for it.
414    /// Scheduling decisions for clusters that have `SCHEDULE = MANUAL` are ignored.
415    SchedulingDecisions(Vec<(&'static str, Vec<(ClusterId, SchedulingDecision)>)>),
416}
417
418impl Message {
419    /// Returns a string to identify the kind of [`Message`], useful for logging.
420    pub const fn kind(&self) -> &'static str {
421        match self {
422            Message::Command(_, msg) => match msg {
423                Command::CatalogSnapshot { .. } => "command-catalog_snapshot",
424                Command::Startup { .. } => "command-startup",
425                Command::Execute { .. } => "command-execute",
426                Command::Commit { .. } => "command-commit",
427                Command::CancelRequest { .. } => "command-cancel_request",
428                Command::PrivilegedCancelRequest { .. } => "command-privileged_cancel_request",
429                Command::GetWebhook { .. } => "command-get_webhook",
430                Command::GetSystemVars { .. } => "command-get_system_vars",
431                Command::SetSystemVars { .. } => "command-set_system_vars",
432                Command::Terminate { .. } => "command-terminate",
433                Command::RetireExecute { .. } => "command-retire_execute",
434                Command::CheckConsistency { .. } => "command-check_consistency",
435                Command::Dump { .. } => "command-dump",
436                Command::AuthenticatePassword { .. } => "command-auth_check",
437                Command::AuthenticateGetSASLChallenge { .. } => "command-auth_get_sasl_challenge",
438                Command::AuthenticateVerifySASLProof { .. } => "command-auth_verify_sasl_proof",
439                Command::CheckRoleCanLogin { .. } => "command-check_role_can_login",
440                Command::GetComputeInstanceClient { .. } => "get-compute-instance-client",
441                Command::GetOracle { .. } => "get-oracle",
442                Command::DetermineRealTimeRecentTimestamp { .. } => {
443                    "determine-real-time-recent-timestamp"
444                }
445                Command::GetTransactionReadHoldsBundle { .. } => {
446                    "get-transaction-read-holds-bundle"
447                }
448                Command::StoreTransactionReadHolds { .. } => "store-transaction-read-holds",
449                Command::ExecuteSlowPathPeek { .. } => "execute-slow-path-peek",
450                Command::ExecuteSubscribe { .. } => "execute-subscribe",
451                Command::CopyToPreflight { .. } => "copy-to-preflight",
452                Command::ExecuteCopyTo { .. } => "execute-copy-to",
453                Command::ExecuteSideEffectingFunc { .. } => "execute-side-effecting-func",
454                Command::RegisterFrontendPeek { .. } => "register-frontend-peek",
455                Command::UnregisterFrontendPeek { .. } => "unregister-frontend-peek",
456                Command::ExplainTimestamp { .. } => "explain-timestamp",
457                Command::FrontendStatementLogging(..) => "frontend-statement-logging",
458                Command::StartCopyFromStdin { .. } => "start-copy-from-stdin",
459                Command::InjectAuditEvents { .. } => "inject-audit-events",
460            },
461            Message::ControllerReady {
462                controller: ControllerReadiness::Compute,
463            } => "controller_ready(compute)",
464            Message::ControllerReady {
465                controller: ControllerReadiness::Storage,
466            } => "controller_ready(storage)",
467            Message::ControllerReady {
468                controller: ControllerReadiness::Metrics,
469            } => "controller_ready(metrics)",
470            Message::ControllerReady {
471                controller: ControllerReadiness::Internal,
472            } => "controller_ready(internal)",
473            Message::PurifiedStatementReady(_) => "purified_statement_ready",
474            Message::CreateConnectionValidationReady(_) => "create_connection_validation_ready",
475            Message::TryDeferred { .. } => "try_deferred",
476            Message::GroupCommitInitiate(..) => "group_commit_initiate",
477            Message::AdvanceTimelines => "advance_timelines",
478            Message::ClusterEvent(_) => "cluster_event",
479            Message::CancelPendingPeeks { .. } => "cancel_pending_peeks",
480            Message::LinearizeReads => "linearize_reads",
481            Message::StagedBatches { .. } => "staged_batches",
482            Message::StorageUsageSchedule => "storage_usage_schedule",
483            Message::StorageUsageFetch => "storage_usage_fetch",
484            Message::StorageUsageUpdate(_) => "storage_usage_update",
485            Message::StorageUsagePrune(_) => "storage_usage_prune",
486            Message::RetireExecute { .. } => "retire_execute",
487            Message::ExecuteSingleStatementTransaction { .. } => {
488                "execute_single_statement_transaction"
489            }
490            Message::PeekStageReady { .. } => "peek_stage_ready",
491            Message::ExplainTimestampStageReady { .. } => "explain_timestamp_stage_ready",
492            Message::CreateIndexStageReady { .. } => "create_index_stage_ready",
493            Message::CreateViewStageReady { .. } => "create_view_stage_ready",
494            Message::CreateMaterializedViewStageReady { .. } => {
495                "create_materialized_view_stage_ready"
496            }
497            Message::SubscribeStageReady { .. } => "subscribe_stage_ready",
498            Message::IntrospectionSubscribeStageReady { .. } => {
499                "introspection_subscribe_stage_ready"
500            }
501            Message::SecretStageReady { .. } => "secret_stage_ready",
502            Message::ClusterStageReady { .. } => "cluster_stage_ready",
503            Message::DrainStatementLog => "drain_statement_log",
504            Message::AlterConnectionValidationReady(..) => "alter_connection_validation_ready",
505            Message::PrivateLinkVpcEndpointEvents(_) => "private_link_vpc_endpoint_events",
506            Message::CheckSchedulingPolicies => "check_scheduling_policies",
507            Message::SchedulingDecisions { .. } => "scheduling_decision",
508            Message::DeferredStatementReady => "deferred_statement_ready",
509        }
510    }
511}
512
513/// The reason for why a controller needs processing on the main loop.
514#[derive(Debug)]
515pub enum ControllerReadiness {
516    /// The storage controller is ready.
517    Storage,
518    /// The compute controller is ready.
519    Compute,
520    /// A batch of metric data is ready.
521    Metrics,
522    /// An internally-generated message is ready to be returned.
523    Internal,
524}
525
526#[derive(Derivative)]
527#[derivative(Debug)]
528pub struct BackgroundWorkResult<T> {
529    #[derivative(Debug = "ignore")]
530    pub ctx: ExecuteContext,
531    pub result: Result<T, AdapterError>,
532    pub params: Params,
533    pub plan_validity: PlanValidity,
534    pub original_stmt: Arc<Statement<Raw>>,
535    pub otel_ctx: OpenTelemetryContext,
536}
537
538pub type PurifiedStatementReady = BackgroundWorkResult<mz_sql::pure::PurifiedStatement>;
539
540#[derive(Derivative)]
541#[derivative(Debug)]
542pub struct ValidationReady<T> {
543    #[derivative(Debug = "ignore")]
544    pub ctx: ExecuteContext,
545    pub result: Result<T, AdapterError>,
546    pub resolved_ids: ResolvedIds,
547    pub connection_id: CatalogItemId,
548    pub connection_gid: GlobalId,
549    pub plan_validity: PlanValidity,
550    pub otel_ctx: OpenTelemetryContext,
551}
552
553pub type CreateConnectionValidationReady = ValidationReady<CreateConnectionPlan>;
554pub type AlterConnectionValidationReady = ValidationReady<Connection>;
555
556#[derive(Debug)]
557pub enum PeekStage {
558    /// Common stages across SELECT, EXPLAIN and COPY TO queries.
559    LinearizeTimestamp(PeekStageLinearizeTimestamp),
560    RealTimeRecency(PeekStageRealTimeRecency),
561    TimestampReadHold(PeekStageTimestampReadHold),
562    Optimize(PeekStageOptimize),
563    /// Final stage for a peek.
564    Finish(PeekStageFinish),
565    /// Final stage for an explain.
566    ExplainPlan(PeekStageExplainPlan),
567    ExplainPushdown(PeekStageExplainPushdown),
568    /// Preflight checks for a copy to operation.
569    CopyToPreflight(PeekStageCopyTo),
570    /// Final stage for a copy to which involves shipping the dataflow.
571    CopyToDataflow(PeekStageCopyTo),
572}
573
574#[derive(Debug)]
575pub struct CopyToContext {
576    /// The `RelationDesc` of the data to be copied.
577    pub desc: RelationDesc,
578    /// The destination uri of the external service where the data will be copied.
579    pub uri: Uri,
580    /// Connection information required to connect to the external service to copy the data.
581    pub connection: StorageConnection<ReferencedConnection>,
582    /// The ID of the CONNECTION object to be used for copying the data.
583    pub connection_id: CatalogItemId,
584    /// Format params to format the data.
585    pub format: S3SinkFormat,
586    /// Approximate max file size of each uploaded file.
587    pub max_file_size: u64,
588    /// Number of batches the output of the COPY TO will be partitioned into
589    /// to distribute the load across workers deterministically.
590    /// This is only an option since it's not set when CopyToContext is instantiated
591    /// but immediately after in the PeekStageValidate stage.
592    pub output_batch_count: Option<u64>,
593}
594
595#[derive(Debug)]
596pub struct PeekStageLinearizeTimestamp {
597    validity: PlanValidity,
598    plan: mz_sql::plan::SelectPlan,
599    max_query_result_size: Option<u64>,
600    source_ids: BTreeSet<GlobalId>,
601    target_replica: Option<ReplicaId>,
602    timeline_context: TimelineContext,
603    optimizer: Either<optimize::peek::Optimizer, optimize::copy_to::Optimizer>,
604    /// An optional context set iff the state machine is initiated from
605    /// sequencing an EXPLAIN for this statement.
606    explain_ctx: ExplainContext,
607}
608
609#[derive(Debug)]
610pub struct PeekStageRealTimeRecency {
611    validity: PlanValidity,
612    plan: mz_sql::plan::SelectPlan,
613    max_query_result_size: Option<u64>,
614    source_ids: BTreeSet<GlobalId>,
615    target_replica: Option<ReplicaId>,
616    timeline_context: TimelineContext,
617    oracle_read_ts: Option<Timestamp>,
618    optimizer: Either<optimize::peek::Optimizer, optimize::copy_to::Optimizer>,
619    /// An optional context set iff the state machine is initiated from
620    /// sequencing an EXPLAIN for this statement.
621    explain_ctx: ExplainContext,
622}
623
624#[derive(Debug)]
625pub struct PeekStageTimestampReadHold {
626    validity: PlanValidity,
627    plan: mz_sql::plan::SelectPlan,
628    max_query_result_size: Option<u64>,
629    source_ids: BTreeSet<GlobalId>,
630    target_replica: Option<ReplicaId>,
631    timeline_context: TimelineContext,
632    oracle_read_ts: Option<Timestamp>,
633    real_time_recency_ts: Option<mz_repr::Timestamp>,
634    optimizer: Either<optimize::peek::Optimizer, optimize::copy_to::Optimizer>,
635    /// An optional context set iff the state machine is initiated from
636    /// sequencing an EXPLAIN for this statement.
637    explain_ctx: ExplainContext,
638}
639
640#[derive(Debug)]
641pub struct PeekStageOptimize {
642    validity: PlanValidity,
643    plan: mz_sql::plan::SelectPlan,
644    max_query_result_size: Option<u64>,
645    source_ids: BTreeSet<GlobalId>,
646    id_bundle: CollectionIdBundle,
647    target_replica: Option<ReplicaId>,
648    determination: TimestampDetermination,
649    optimizer: Either<optimize::peek::Optimizer, optimize::copy_to::Optimizer>,
650    /// An optional context set iff the state machine is initiated from
651    /// sequencing an EXPLAIN for this statement.
652    explain_ctx: ExplainContext,
653}
654
655#[derive(Debug)]
656pub struct PeekStageFinish {
657    validity: PlanValidity,
658    plan: mz_sql::plan::SelectPlan,
659    max_query_result_size: Option<u64>,
660    id_bundle: CollectionIdBundle,
661    target_replica: Option<ReplicaId>,
662    source_ids: BTreeSet<GlobalId>,
663    determination: TimestampDetermination,
664    cluster_id: ComputeInstanceId,
665    finishing: RowSetFinishing,
666    /// When present, an optimizer trace to be used for emitting a plan insights
667    /// notice.
668    plan_insights_optimizer_trace: Option<OptimizerTrace>,
669    insights_ctx: Option<Box<PlanInsightsContext>>,
670    global_lir_plan: optimize::peek::GlobalLirPlan,
671    optimization_finished_at: EpochMillis,
672}
673
674#[derive(Debug)]
675pub struct PeekStageCopyTo {
676    validity: PlanValidity,
677    optimizer: optimize::copy_to::Optimizer,
678    global_lir_plan: optimize::copy_to::GlobalLirPlan,
679    optimization_finished_at: EpochMillis,
680    source_ids: BTreeSet<GlobalId>,
681}
682
683#[derive(Debug)]
684pub struct PeekStageExplainPlan {
685    validity: PlanValidity,
686    optimizer: optimize::peek::Optimizer,
687    df_meta: DataflowMetainfo,
688    explain_ctx: ExplainPlanContext,
689    insights_ctx: Option<Box<PlanInsightsContext>>,
690}
691
692#[derive(Debug)]
693pub struct PeekStageExplainPushdown {
694    validity: PlanValidity,
695    determination: TimestampDetermination,
696    imports: BTreeMap<GlobalId, MapFilterProject>,
697}
698
699#[derive(Debug)]
700pub enum CreateIndexStage {
701    Optimize(CreateIndexOptimize),
702    Finish(CreateIndexFinish),
703    Explain(CreateIndexExplain),
704}
705
706#[derive(Debug)]
707pub struct CreateIndexOptimize {
708    validity: PlanValidity,
709    plan: plan::CreateIndexPlan,
710    resolved_ids: ResolvedIds,
711    /// An optional context set iff the state machine is initiated from
712    /// sequencing an EXPLAIN for this statement.
713    explain_ctx: ExplainContext,
714}
715
716#[derive(Debug)]
717pub struct CreateIndexFinish {
718    validity: PlanValidity,
719    item_id: CatalogItemId,
720    global_id: GlobalId,
721    plan: plan::CreateIndexPlan,
722    resolved_ids: ResolvedIds,
723    global_mir_plan: optimize::index::GlobalMirPlan,
724    global_lir_plan: optimize::index::GlobalLirPlan,
725    optimizer_features: OptimizerFeatures,
726}
727
728#[derive(Debug)]
729pub struct CreateIndexExplain {
730    validity: PlanValidity,
731    exported_index_id: GlobalId,
732    plan: plan::CreateIndexPlan,
733    df_meta: DataflowMetainfo,
734    explain_ctx: ExplainPlanContext,
735}
736
737#[derive(Debug)]
738pub enum CreateViewStage {
739    Optimize(CreateViewOptimize),
740    Finish(CreateViewFinish),
741    Explain(CreateViewExplain),
742}
743
744#[derive(Debug)]
745pub struct CreateViewOptimize {
746    validity: PlanValidity,
747    plan: plan::CreateViewPlan,
748    resolved_ids: ResolvedIds,
749    /// An optional context set iff the state machine is initiated from
750    /// sequencing an EXPLAIN for this statement.
751    explain_ctx: ExplainContext,
752}
753
754#[derive(Debug)]
755pub struct CreateViewFinish {
756    validity: PlanValidity,
757    /// ID of this item in the Catalog.
758    item_id: CatalogItemId,
759    /// ID by with Compute will reference this View.
760    global_id: GlobalId,
761    plan: plan::CreateViewPlan,
762    /// IDs of objects resolved during name resolution.
763    resolved_ids: ResolvedIds,
764    optimized_expr: OptimizedMirRelationExpr,
765}
766
767#[derive(Debug)]
768pub struct CreateViewExplain {
769    validity: PlanValidity,
770    id: GlobalId,
771    plan: plan::CreateViewPlan,
772    explain_ctx: ExplainPlanContext,
773}
774
775#[derive(Debug)]
776pub enum ExplainTimestampStage {
777    Optimize(ExplainTimestampOptimize),
778    RealTimeRecency(ExplainTimestampRealTimeRecency),
779    Finish(ExplainTimestampFinish),
780}
781
782#[derive(Debug)]
783pub struct ExplainTimestampOptimize {
784    validity: PlanValidity,
785    plan: plan::ExplainTimestampPlan,
786    cluster_id: ClusterId,
787}
788
789#[derive(Debug)]
790pub struct ExplainTimestampRealTimeRecency {
791    validity: PlanValidity,
792    format: ExplainFormat,
793    optimized_plan: OptimizedMirRelationExpr,
794    cluster_id: ClusterId,
795    when: QueryWhen,
796}
797
798#[derive(Debug)]
799pub struct ExplainTimestampFinish {
800    validity: PlanValidity,
801    format: ExplainFormat,
802    optimized_plan: OptimizedMirRelationExpr,
803    cluster_id: ClusterId,
804    source_ids: BTreeSet<GlobalId>,
805    when: QueryWhen,
806    real_time_recency_ts: Option<Timestamp>,
807}
808
809#[derive(Debug)]
810pub enum ClusterStage {
811    Alter(AlterCluster),
812    WaitForHydrated(AlterClusterWaitForHydrated),
813    Finalize(AlterClusterFinalize),
814}
815
816#[derive(Debug)]
817pub struct AlterCluster {
818    validity: PlanValidity,
819    plan: plan::AlterClusterPlan,
820}
821
822#[derive(Debug)]
823pub struct AlterClusterWaitForHydrated {
824    validity: PlanValidity,
825    plan: plan::AlterClusterPlan,
826    new_config: ClusterVariantManaged,
827    timeout_time: Instant,
828    on_timeout: OnTimeoutAction,
829}
830
831#[derive(Debug)]
832pub struct AlterClusterFinalize {
833    validity: PlanValidity,
834    plan: plan::AlterClusterPlan,
835    new_config: ClusterVariantManaged,
836}
837
838#[derive(Debug)]
839pub enum ExplainContext {
840    /// The ordinary, non-explain variant of the statement.
841    None,
842    /// The `EXPLAIN <level> PLAN FOR <explainee>` version of the statement.
843    Plan(ExplainPlanContext),
844    /// Generate a notice containing the `EXPLAIN PLAN INSIGHTS` output
845    /// alongside the query's normal output.
846    PlanInsightsNotice(OptimizerTrace),
847    /// `EXPLAIN FILTER PUSHDOWN`
848    Pushdown,
849}
850
851impl ExplainContext {
852    /// If available for this context, wrap the [`OptimizerTrace`] into a
853    /// [`tracing::Dispatch`] and set it as default, returning the resulting
854    /// guard in a `Some(guard)` option.
855    pub(crate) fn dispatch_guard(&self) -> Option<DispatchGuard<'_>> {
856        let optimizer_trace = match self {
857            ExplainContext::Plan(explain_ctx) => Some(&explain_ctx.optimizer_trace),
858            ExplainContext::PlanInsightsNotice(optimizer_trace) => Some(optimizer_trace),
859            _ => None,
860        };
861        optimizer_trace.map(|optimizer_trace| optimizer_trace.as_guard())
862    }
863
864    pub(crate) fn needs_cluster(&self) -> bool {
865        match self {
866            ExplainContext::None => true,
867            ExplainContext::Plan(..) => false,
868            ExplainContext::PlanInsightsNotice(..) => true,
869            ExplainContext::Pushdown => false,
870        }
871    }
872
873    pub(crate) fn needs_plan_insights(&self) -> bool {
874        matches!(
875            self,
876            ExplainContext::Plan(ExplainPlanContext {
877                stage: ExplainStage::PlanInsights,
878                ..
879            }) | ExplainContext::PlanInsightsNotice(_)
880        )
881    }
882}
883
884#[derive(Debug)]
885pub struct ExplainPlanContext {
886    /// EXPLAIN BROKEN is internal syntax for showing EXPLAIN output despite an internal error in
887    /// the optimizer: we don't immediately bail out from peek sequencing when an internal optimizer
888    /// error happens, but go on with trying to show the requested EXPLAIN stage. This can still
889    /// succeed if the requested EXPLAIN stage is before the point where the error happened.
890    pub broken: bool,
891    pub config: ExplainConfig,
892    pub format: ExplainFormat,
893    pub stage: ExplainStage,
894    pub replan: Option<GlobalId>,
895    pub desc: Option<RelationDesc>,
896    pub optimizer_trace: OptimizerTrace,
897}
898
899#[derive(Debug)]
900pub enum CreateMaterializedViewStage {
901    Optimize(CreateMaterializedViewOptimize),
902    Finish(CreateMaterializedViewFinish),
903    Explain(CreateMaterializedViewExplain),
904}
905
906#[derive(Debug)]
907pub struct CreateMaterializedViewOptimize {
908    validity: PlanValidity,
909    plan: plan::CreateMaterializedViewPlan,
910    resolved_ids: ResolvedIds,
911    /// An optional context set iff the state machine is initiated from
912    /// sequencing an EXPLAIN for this statement.
913    explain_ctx: ExplainContext,
914}
915
916#[derive(Debug)]
917pub struct CreateMaterializedViewFinish {
918    /// The ID of this Materialized View in the Catalog.
919    item_id: CatalogItemId,
920    /// The ID of the durable pTVC backing this Materialized View.
921    global_id: GlobalId,
922    validity: PlanValidity,
923    plan: plan::CreateMaterializedViewPlan,
924    resolved_ids: ResolvedIds,
925    local_mir_plan: optimize::materialized_view::LocalMirPlan,
926    global_mir_plan: optimize::materialized_view::GlobalMirPlan,
927    global_lir_plan: optimize::materialized_view::GlobalLirPlan,
928    optimizer_features: OptimizerFeatures,
929}
930
931#[derive(Debug)]
932pub struct CreateMaterializedViewExplain {
933    global_id: GlobalId,
934    validity: PlanValidity,
935    plan: plan::CreateMaterializedViewPlan,
936    df_meta: DataflowMetainfo,
937    explain_ctx: ExplainPlanContext,
938}
939
940#[derive(Debug)]
941pub enum SubscribeStage {
942    OptimizeMir(SubscribeOptimizeMir),
943    TimestampOptimizeLir(SubscribeTimestampOptimizeLir),
944    Finish(SubscribeFinish),
945    Explain(SubscribeExplain),
946}
947
948#[derive(Debug)]
949pub struct SubscribeOptimizeMir {
950    validity: PlanValidity,
951    plan: plan::SubscribePlan,
952    timeline: TimelineContext,
953    dependency_ids: BTreeSet<GlobalId>,
954    cluster_id: ComputeInstanceId,
955    replica_id: Option<ReplicaId>,
956    /// An optional context set iff the state machine is initiated from
957    /// sequencing an EXPLAIN for this statement.
958    explain_ctx: ExplainContext,
959}
960
961#[derive(Debug)]
962pub struct SubscribeTimestampOptimizeLir {
963    validity: PlanValidity,
964    plan: plan::SubscribePlan,
965    timeline: TimelineContext,
966    optimizer: optimize::subscribe::Optimizer,
967    global_mir_plan: optimize::subscribe::GlobalMirPlan<optimize::subscribe::Unresolved>,
968    dependency_ids: BTreeSet<GlobalId>,
969    replica_id: Option<ReplicaId>,
970    /// An optional context set iff the state machine is initiated from
971    /// sequencing an EXPLAIN for this statement.
972    explain_ctx: ExplainContext,
973}
974
975#[derive(Debug)]
976pub struct SubscribeFinish {
977    validity: PlanValidity,
978    cluster_id: ComputeInstanceId,
979    replica_id: Option<ReplicaId>,
980    plan: plan::SubscribePlan,
981    global_lir_plan: optimize::subscribe::GlobalLirPlan,
982    dependency_ids: BTreeSet<GlobalId>,
983}
984
985#[derive(Debug)]
986pub struct SubscribeExplain {
987    validity: PlanValidity,
988    optimizer: optimize::subscribe::Optimizer,
989    df_meta: DataflowMetainfo,
990    cluster_id: ComputeInstanceId,
991    explain_ctx: ExplainPlanContext,
992}
993
994#[derive(Debug)]
995pub enum IntrospectionSubscribeStage {
996    OptimizeMir(IntrospectionSubscribeOptimizeMir),
997    TimestampOptimizeLir(IntrospectionSubscribeTimestampOptimizeLir),
998    Finish(IntrospectionSubscribeFinish),
999}
1000
1001#[derive(Debug)]
1002pub struct IntrospectionSubscribeOptimizeMir {
1003    validity: PlanValidity,
1004    plan: plan::SubscribePlan,
1005    subscribe_id: GlobalId,
1006    cluster_id: ComputeInstanceId,
1007    replica_id: ReplicaId,
1008}
1009
1010#[derive(Debug)]
1011pub struct IntrospectionSubscribeTimestampOptimizeLir {
1012    validity: PlanValidity,
1013    optimizer: optimize::subscribe::Optimizer,
1014    global_mir_plan: optimize::subscribe::GlobalMirPlan<optimize::subscribe::Unresolved>,
1015    cluster_id: ComputeInstanceId,
1016    replica_id: ReplicaId,
1017}
1018
1019#[derive(Debug)]
1020pub struct IntrospectionSubscribeFinish {
1021    validity: PlanValidity,
1022    global_lir_plan: optimize::subscribe::GlobalLirPlan,
1023    read_holds: ReadHolds,
1024    cluster_id: ComputeInstanceId,
1025    replica_id: ReplicaId,
1026}
1027
1028#[derive(Debug)]
1029pub enum SecretStage {
1030    CreateEnsure(CreateSecretEnsure),
1031    CreateFinish(CreateSecretFinish),
1032    RotateKeysEnsure(RotateKeysSecretEnsure),
1033    RotateKeysFinish(RotateKeysSecretFinish),
1034    Alter(AlterSecret),
1035}
1036
1037#[derive(Debug)]
1038pub struct CreateSecretEnsure {
1039    validity: PlanValidity,
1040    plan: plan::CreateSecretPlan,
1041}
1042
1043#[derive(Debug)]
1044pub struct CreateSecretFinish {
1045    validity: PlanValidity,
1046    item_id: CatalogItemId,
1047    global_id: GlobalId,
1048    plan: plan::CreateSecretPlan,
1049}
1050
1051#[derive(Debug)]
1052pub struct RotateKeysSecretEnsure {
1053    validity: PlanValidity,
1054    id: CatalogItemId,
1055}
1056
1057#[derive(Debug)]
1058pub struct RotateKeysSecretFinish {
1059    validity: PlanValidity,
1060    ops: Vec<crate::catalog::Op>,
1061}
1062
1063#[derive(Debug)]
1064pub struct AlterSecret {
1065    validity: PlanValidity,
1066    plan: plan::AlterSecretPlan,
1067}
1068
1069/// An enum describing which cluster to run a statement on.
1070///
1071/// One example usage would be that if a query depends only on system tables, we might
1072/// automatically run it on the catalog server cluster to benefit from indexes that exist there.
1073#[derive(Debug, Copy, Clone, PartialEq, Eq)]
1074pub enum TargetCluster {
1075    /// The catalog server cluster.
1076    CatalogServer,
1077    /// The current user's active cluster.
1078    Active,
1079    /// The cluster selected at the start of a transaction.
1080    Transaction(ClusterId),
1081}
1082
1083/// Result types for each stage of a sequence.
1084pub(crate) enum StageResult<T> {
1085    /// A task was spawned that will return the next stage.
1086    Handle(JoinHandle<Result<T, AdapterError>>),
1087    /// A task was spawned that will return a response for the client.
1088    HandleRetire(JoinHandle<Result<ExecuteResponse, AdapterError>>),
1089    /// The next stage is immediately ready and will execute.
1090    Immediate(T),
1091    /// The final stage was executed and is ready to respond to the client.
1092    Response(ExecuteResponse),
1093}
1094
1095/// Common functionality for [Coordinator::sequence_staged].
1096pub(crate) trait Staged: Send {
1097    type Ctx: StagedContext;
1098
1099    fn validity(&mut self) -> &mut PlanValidity;
1100
1101    /// Returns the next stage or final result.
1102    async fn stage(
1103        self,
1104        coord: &mut Coordinator,
1105        ctx: &mut Self::Ctx,
1106    ) -> Result<StageResult<Box<Self>>, AdapterError>;
1107
1108    /// Prepares a message for the Coordinator.
1109    fn message(self, ctx: Self::Ctx, span: Span) -> Message;
1110
1111    /// Whether it is safe to SQL cancel this stage.
1112    fn cancel_enabled(&self) -> bool;
1113}
1114
1115pub trait StagedContext {
1116    fn retire(self, result: Result<ExecuteResponse, AdapterError>);
1117    fn session(&self) -> Option<&Session>;
1118}
1119
1120impl StagedContext for ExecuteContext {
1121    fn retire(self, result: Result<ExecuteResponse, AdapterError>) {
1122        self.retire(result);
1123    }
1124
1125    fn session(&self) -> Option<&Session> {
1126        Some(self.session())
1127    }
1128}
1129
1130impl StagedContext for () {
1131    fn retire(self, _result: Result<ExecuteResponse, AdapterError>) {}
1132
1133    fn session(&self) -> Option<&Session> {
1134        None
1135    }
1136}
1137
1138/// Configures a coordinator.
1139pub struct Config {
1140    pub controller_config: ControllerConfig,
1141    pub controller_envd_epoch: NonZeroI64,
1142    pub storage: Box<dyn mz_catalog::durable::DurableCatalogState>,
1143    pub audit_logs_iterator: AuditLogIterator,
1144    pub timestamp_oracle_url: Option<SensitiveUrl>,
1145    pub unsafe_mode: bool,
1146    pub all_features: bool,
1147    pub build_info: &'static BuildInfo,
1148    pub environment_id: EnvironmentId,
1149    pub metrics_registry: MetricsRegistry,
1150    pub now: NowFn,
1151    pub secrets_controller: Arc<dyn SecretsController>,
1152    pub cloud_resource_controller: Option<Arc<dyn CloudResourceController>>,
1153    pub availability_zones: Vec<String>,
1154    pub cluster_replica_sizes: ClusterReplicaSizeMap,
1155    pub builtin_system_cluster_config: BootstrapBuiltinClusterConfig,
1156    pub builtin_catalog_server_cluster_config: BootstrapBuiltinClusterConfig,
1157    pub builtin_probe_cluster_config: BootstrapBuiltinClusterConfig,
1158    pub builtin_support_cluster_config: BootstrapBuiltinClusterConfig,
1159    pub builtin_analytics_cluster_config: BootstrapBuiltinClusterConfig,
1160    pub system_parameter_defaults: BTreeMap<String, String>,
1161    pub storage_usage_client: StorageUsageClient,
1162    pub storage_usage_collection_interval: Duration,
1163    pub storage_usage_retention_period: Option<Duration>,
1164    pub segment_client: Option<mz_segment::Client>,
1165    pub egress_addresses: Vec<IpNet>,
1166    pub remote_system_parameters: Option<BTreeMap<String, String>>,
1167    pub aws_account_id: Option<String>,
1168    pub aws_privatelink_availability_zones: Option<Vec<String>>,
1169    pub connection_context: ConnectionContext,
1170    pub connection_limit_callback: Box<dyn Fn(u64, u64) -> () + Send + Sync + 'static>,
1171    pub webhook_concurrency_limit: WebhookConcurrencyLimiter,
1172    pub http_host_name: Option<String>,
1173    pub tracing_handle: TracingHandle,
1174    /// Whether or not to start controllers in read-only mode. This is only
1175    /// meant for use during development of read-only clusters and 0dt upgrades
1176    /// and should go away once we have proper orchestration during upgrades.
1177    pub read_only_controllers: bool,
1178
1179    /// A trigger that signals that the current deployment has caught up with a
1180    /// previous deployment. Only used during 0dt deployment, while in read-only
1181    /// mode.
1182    pub caught_up_trigger: Option<Trigger>,
1183
1184    pub helm_chart_version: Option<String>,
1185    pub license_key: ValidatedLicenseKey,
1186    pub external_login_password_mz_system: Option<Password>,
1187    pub force_builtin_schema_migration: Option<String>,
1188}
1189
1190/// Metadata about an active connection.
1191#[derive(Debug, Serialize)]
1192pub struct ConnMeta {
1193    /// Pgwire specifies that every connection have a 32-bit secret associated
1194    /// with it, that is known to both the client and the server. Cancellation
1195    /// requests are required to authenticate with the secret of the connection
1196    /// that they are targeting.
1197    secret_key: u32,
1198    /// The time when the session's connection was initiated.
1199    connected_at: EpochMillis,
1200    user: User,
1201    application_name: String,
1202    uuid: Uuid,
1203    conn_id: ConnectionId,
1204    client_ip: Option<IpAddr>,
1205
1206    /// Sinks that will need to be dropped when the current transaction, if
1207    /// any, is cleared.
1208    drop_sinks: BTreeSet<GlobalId>,
1209
1210    /// Lock for the Coordinator's deferred statements that is dropped on transaction clear.
1211    #[serde(skip)]
1212    deferred_lock: Option<OwnedMutexGuard<()>>,
1213
1214    /// Cluster reconfigurations that will need to be
1215    /// cleaned up when the current transaction is cleared
1216    pending_cluster_alters: BTreeSet<ClusterId>,
1217
1218    /// Channel on which to send notices to a session.
1219    #[serde(skip)]
1220    notice_tx: mpsc::UnboundedSender<AdapterNotice>,
1221
1222    /// The role that initiated the database context. Fixed for the duration of the connection.
1223    /// WARNING: This role reference is not updated when the role is dropped.
1224    /// Consumers should not assume that this role exist.
1225    authenticated_role: RoleId,
1226}
1227
1228impl ConnMeta {
1229    pub fn conn_id(&self) -> &ConnectionId {
1230        &self.conn_id
1231    }
1232
1233    pub fn user(&self) -> &User {
1234        &self.user
1235    }
1236
1237    pub fn application_name(&self) -> &str {
1238        &self.application_name
1239    }
1240
1241    pub fn authenticated_role_id(&self) -> &RoleId {
1242        &self.authenticated_role
1243    }
1244
1245    pub fn uuid(&self) -> Uuid {
1246        self.uuid
1247    }
1248
1249    pub fn client_ip(&self) -> Option<IpAddr> {
1250        self.client_ip
1251    }
1252
1253    pub fn connected_at(&self) -> EpochMillis {
1254        self.connected_at
1255    }
1256}
1257
1258#[derive(Debug)]
1259/// A pending transaction waiting to be committed.
1260pub struct PendingTxn {
1261    /// Context used to send a response back to the client.
1262    ctx: ExecuteContext,
1263    /// Client response for transaction.
1264    response: Result<PendingTxnResponse, AdapterError>,
1265    /// The action to take at the end of the transaction.
1266    action: EndTransactionAction,
1267}
1268
1269#[derive(Debug)]
1270/// The response we'll send for a [`PendingTxn`].
1271pub enum PendingTxnResponse {
1272    /// The transaction will be committed.
1273    Committed {
1274        /// Parameters that will change, and their values, once this transaction is complete.
1275        params: BTreeMap<&'static str, String>,
1276    },
1277    /// The transaction will be rolled back.
1278    Rolledback {
1279        /// Parameters that will change, and their values, once this transaction is complete.
1280        params: BTreeMap<&'static str, String>,
1281    },
1282}
1283
1284impl PendingTxnResponse {
1285    pub fn extend_params(&mut self, p: impl IntoIterator<Item = (&'static str, String)>) {
1286        match self {
1287            PendingTxnResponse::Committed { params }
1288            | PendingTxnResponse::Rolledback { params } => params.extend(p),
1289        }
1290    }
1291}
1292
1293impl From<PendingTxnResponse> for ExecuteResponse {
1294    fn from(value: PendingTxnResponse) -> Self {
1295        match value {
1296            PendingTxnResponse::Committed { params } => {
1297                ExecuteResponse::TransactionCommitted { params }
1298            }
1299            PendingTxnResponse::Rolledback { params } => {
1300                ExecuteResponse::TransactionRolledBack { params }
1301            }
1302        }
1303    }
1304}
1305
1306#[derive(Debug)]
1307/// A pending read transaction waiting to be linearized along with metadata about it's state
1308pub struct PendingReadTxn {
1309    /// The transaction type
1310    txn: PendingRead,
1311    /// The timestamp context of the transaction.
1312    timestamp_context: TimestampContext,
1313    /// When we created this pending txn, when the transaction ends. Only used for metrics.
1314    created: Instant,
1315    /// Number of times we requeued the processing of this pending read txn.
1316    /// Requeueing is necessary if the time we executed the query is after the current oracle time;
1317    /// see [`Coordinator::message_linearize_reads`] for more details.
1318    num_requeues: u64,
1319    /// Telemetry context.
1320    otel_ctx: OpenTelemetryContext,
1321}
1322
1323impl PendingReadTxn {
1324    /// Return the timestamp context of the pending read transaction.
1325    pub fn timestamp_context(&self) -> &TimestampContext {
1326        &self.timestamp_context
1327    }
1328
1329    pub(crate) fn take_context(self) -> ExecuteContext {
1330        self.txn.take_context()
1331    }
1332}
1333
1334#[derive(Debug)]
1335/// A pending read transaction waiting to be linearized.
1336enum PendingRead {
1337    Read {
1338        /// The inner transaction.
1339        txn: PendingTxn,
1340    },
1341    ReadThenWrite {
1342        /// Context used to send a response back to the client.
1343        ctx: ExecuteContext,
1344        /// Channel used to alert the transaction that the read has been linearized and send back
1345        /// `ctx`.
1346        tx: oneshot::Sender<Option<ExecuteContext>>,
1347    },
1348}
1349
1350impl PendingRead {
1351    /// Alert the client that the read has been linearized.
1352    ///
1353    /// If it is necessary to finalize an execute, return the state necessary to do so
1354    /// (execution context and result)
1355    #[instrument(level = "debug")]
1356    pub fn finish(self) -> Option<(ExecuteContext, Result<ExecuteResponse, AdapterError>)> {
1357        match self {
1358            PendingRead::Read {
1359                txn:
1360                    PendingTxn {
1361                        mut ctx,
1362                        response,
1363                        action,
1364                    },
1365                ..
1366            } => {
1367                let changed = ctx.session_mut().vars_mut().end_transaction(action);
1368                // Append any parameters that changed to the response.
1369                let response = response.map(|mut r| {
1370                    r.extend_params(changed);
1371                    ExecuteResponse::from(r)
1372                });
1373
1374                Some((ctx, response))
1375            }
1376            PendingRead::ReadThenWrite { ctx, tx, .. } => {
1377                // Ignore errors if the caller has hung up.
1378                let _ = tx.send(Some(ctx));
1379                None
1380            }
1381        }
1382    }
1383
1384    fn label(&self) -> &'static str {
1385        match self {
1386            PendingRead::Read { .. } => "read",
1387            PendingRead::ReadThenWrite { .. } => "read_then_write",
1388        }
1389    }
1390
1391    pub(crate) fn take_context(self) -> ExecuteContext {
1392        match self {
1393            PendingRead::Read { txn, .. } => txn.ctx,
1394            PendingRead::ReadThenWrite { ctx, tx, .. } => {
1395                // Inform the transaction that we've taken their context.
1396                // Ignore errors if the caller has hung up.
1397                let _ = tx.send(None);
1398                ctx
1399            }
1400        }
1401    }
1402}
1403
1404/// State that the coordinator must process as part of retiring
1405/// command execution.  `ExecuteContextExtra::Default` is guaranteed
1406/// to produce a value that will cause the coordinator to do nothing, and
1407/// is intended for use by code that invokes the execution processing flow
1408/// (i.e., `sequence_plan`) without actually being a statement execution.
1409///
1410/// This is a pure data struct containing only the statement logging ID.
1411/// For auto-retire-on-drop behavior, use `ExecuteContextGuard` which wraps
1412/// this struct and owns the channel for sending retirement messages.
1413#[derive(Debug, Default)]
1414#[must_use]
1415pub struct ExecuteContextExtra {
1416    statement_uuid: Option<StatementLoggingId>,
1417}
1418
1419impl ExecuteContextExtra {
1420    pub(crate) fn new(statement_uuid: Option<StatementLoggingId>) -> Self {
1421        Self { statement_uuid }
1422    }
1423    pub fn is_trivial(&self) -> bool {
1424        self.statement_uuid.is_none()
1425    }
1426    pub fn contents(&self) -> Option<StatementLoggingId> {
1427        self.statement_uuid
1428    }
1429    /// Consume this extra and return the statement UUID for retirement.
1430    /// This should only be called from code that knows what to do to finish
1431    /// up logging based on the inner value.
1432    #[must_use]
1433    pub(crate) fn retire(self) -> Option<StatementLoggingId> {
1434        self.statement_uuid
1435    }
1436}
1437
1438/// A guard that wraps `ExecuteContextExtra` and owns a channel for sending
1439/// retirement messages to the coordinator.
1440///
1441/// If this guard is dropped with a `Some` `statement_uuid` in its inner
1442/// `ExecuteContextExtra`, the `Drop` implementation will automatically send a
1443/// `Message::RetireExecute` to log the statement ending.
1444/// This handles cases like connection drops where the context cannot be
1445/// explicitly retired.
1446/// See <https://github.com/MaterializeInc/database-issues/issues/7304>
1447#[derive(Debug)]
1448#[must_use]
1449pub struct ExecuteContextGuard {
1450    extra: ExecuteContextExtra,
1451    /// Channel for sending messages to the coordinator. Used for auto-retiring on drop.
1452    /// For `Default` instances, this is a dummy sender (receiver already dropped), so
1453    /// sends will fail silently - which is the desired behavior since Default instances
1454    /// should only be used for non-logged statements.
1455    coordinator_tx: mpsc::UnboundedSender<Message>,
1456}
1457
1458impl Default for ExecuteContextGuard {
1459    fn default() -> Self {
1460        // Create a dummy sender by immediately dropping the receiver.
1461        // Any send on this channel will fail silently, which is the desired
1462        // behavior for Default instances (non-logged statements).
1463        let (tx, _rx) = mpsc::unbounded_channel();
1464        Self {
1465            extra: ExecuteContextExtra::default(),
1466            coordinator_tx: tx,
1467        }
1468    }
1469}
1470
1471impl ExecuteContextGuard {
1472    pub(crate) fn new(
1473        statement_uuid: Option<StatementLoggingId>,
1474        coordinator_tx: mpsc::UnboundedSender<Message>,
1475    ) -> Self {
1476        Self {
1477            extra: ExecuteContextExtra::new(statement_uuid),
1478            coordinator_tx,
1479        }
1480    }
1481    pub fn is_trivial(&self) -> bool {
1482        self.extra.is_trivial()
1483    }
1484    pub fn contents(&self) -> Option<StatementLoggingId> {
1485        self.extra.contents()
1486    }
1487    /// Take responsibility for the contents.  This should only be
1488    /// called from code that knows what to do to finish up logging
1489    /// based on the inner value.
1490    ///
1491    /// Returns the inner `ExecuteContextExtra`, consuming the guard without
1492    /// triggering the auto-retire behavior.
1493    pub(crate) fn defuse(mut self) -> ExecuteContextExtra {
1494        // Taking statement_uuid prevents the Drop impl from sending a retire message
1495        std::mem::take(&mut self.extra)
1496    }
1497}
1498
1499impl Drop for ExecuteContextGuard {
1500    fn drop(&mut self) {
1501        if let Some(statement_uuid) = self.extra.statement_uuid.take() {
1502            // Auto-retire since the guard was dropped without explicit retirement (likely due
1503            // to connection drop).
1504            let msg = Message::RetireExecute {
1505                data: ExecuteContextExtra {
1506                    statement_uuid: Some(statement_uuid),
1507                },
1508                otel_ctx: OpenTelemetryContext::obtain(),
1509                reason: StatementEndedExecutionReason::Aborted,
1510            };
1511            // Send may fail for Default instances (dummy sender), which is fine since
1512            // Default instances should only be used for non-logged statements.
1513            let _ = self.coordinator_tx.send(msg);
1514        }
1515    }
1516}
1517
1518/// Bundle of state related to statement execution.
1519///
1520/// This struct collects a bundle of state that needs to be threaded
1521/// through various functions as part of statement execution.
1522/// It is used to finalize execution, by calling `retire`. Finalizing execution
1523/// involves sending the session back to the pgwire layer so that it
1524/// may be used to process further commands. It also involves
1525/// performing some work on the main coordinator thread
1526/// (e.g., recording the time at which the statement finished
1527/// executing). The state necessary to perform this work is bundled in
1528/// the `ExecuteContextGuard` object.
1529#[derive(Debug)]
1530pub struct ExecuteContext {
1531    inner: Box<ExecuteContextInner>,
1532}
1533
1534impl std::ops::Deref for ExecuteContext {
1535    type Target = ExecuteContextInner;
1536    fn deref(&self) -> &Self::Target {
1537        &*self.inner
1538    }
1539}
1540
1541impl std::ops::DerefMut for ExecuteContext {
1542    fn deref_mut(&mut self) -> &mut Self::Target {
1543        &mut *self.inner
1544    }
1545}
1546
1547#[derive(Debug)]
1548pub struct ExecuteContextInner {
1549    tx: ClientTransmitter<ExecuteResponse>,
1550    internal_cmd_tx: mpsc::UnboundedSender<Message>,
1551    session: Session,
1552    extra: ExecuteContextGuard,
1553}
1554
1555impl ExecuteContext {
1556    pub fn session(&self) -> &Session {
1557        &self.session
1558    }
1559
1560    pub fn session_mut(&mut self) -> &mut Session {
1561        &mut self.session
1562    }
1563
1564    pub fn tx(&self) -> &ClientTransmitter<ExecuteResponse> {
1565        &self.tx
1566    }
1567
1568    pub fn tx_mut(&mut self) -> &mut ClientTransmitter<ExecuteResponse> {
1569        &mut self.tx
1570    }
1571
1572    pub fn from_parts(
1573        tx: ClientTransmitter<ExecuteResponse>,
1574        internal_cmd_tx: mpsc::UnboundedSender<Message>,
1575        session: Session,
1576        extra: ExecuteContextGuard,
1577    ) -> Self {
1578        Self {
1579            inner: ExecuteContextInner {
1580                tx,
1581                session,
1582                extra,
1583                internal_cmd_tx,
1584            }
1585            .into(),
1586        }
1587    }
1588
1589    /// By calling this function, the caller takes responsibility for
1590    /// dealing with the instance of `ExecuteContextGuard`. This is
1591    /// intended to support protocols (like `COPY FROM`) that involve
1592    /// multiple passes of sending the session back and forth between
1593    /// the coordinator and the pgwire layer. As part of any such
1594    /// protocol, we must ensure that the `ExecuteContextGuard`
1595    /// (possibly wrapped in a new `ExecuteContext`) is passed back to the coordinator for
1596    /// eventual retirement.
1597    pub fn into_parts(
1598        self,
1599    ) -> (
1600        ClientTransmitter<ExecuteResponse>,
1601        mpsc::UnboundedSender<Message>,
1602        Session,
1603        ExecuteContextGuard,
1604    ) {
1605        let ExecuteContextInner {
1606            tx,
1607            internal_cmd_tx,
1608            session,
1609            extra,
1610        } = *self.inner;
1611        (tx, internal_cmd_tx, session, extra)
1612    }
1613
1614    /// Retire the execution, by sending a message to the coordinator.
1615    #[instrument(level = "debug")]
1616    pub fn retire(self, result: Result<ExecuteResponse, AdapterError>) {
1617        let ExecuteContextInner {
1618            tx,
1619            internal_cmd_tx,
1620            session,
1621            extra,
1622        } = *self.inner;
1623        let reason = if extra.is_trivial() {
1624            None
1625        } else {
1626            Some((&result).into())
1627        };
1628        tx.send(result, session);
1629        if let Some(reason) = reason {
1630            // Retire the guard to get the inner ExecuteContextExtra without triggering auto-retire
1631            let extra = extra.defuse();
1632            if let Err(e) = internal_cmd_tx.send(Message::RetireExecute {
1633                otel_ctx: OpenTelemetryContext::obtain(),
1634                data: extra,
1635                reason,
1636            }) {
1637                warn!("internal_cmd_rx dropped before we could send: {:?}", e);
1638            }
1639        }
1640    }
1641
1642    pub fn extra(&self) -> &ExecuteContextGuard {
1643        &self.extra
1644    }
1645
1646    pub fn extra_mut(&mut self) -> &mut ExecuteContextGuard {
1647        &mut self.extra
1648    }
1649}
1650
1651#[derive(Debug)]
1652struct ClusterReplicaStatuses(
1653    BTreeMap<ClusterId, BTreeMap<ReplicaId, BTreeMap<ProcessId, ClusterReplicaProcessStatus>>>,
1654);
1655
1656impl ClusterReplicaStatuses {
1657    pub(crate) fn new() -> ClusterReplicaStatuses {
1658        ClusterReplicaStatuses(BTreeMap::new())
1659    }
1660
1661    /// Initializes the statuses of the specified cluster.
1662    ///
1663    /// Panics if the cluster statuses are already initialized.
1664    pub(crate) fn initialize_cluster_statuses(&mut self, cluster_id: ClusterId) {
1665        let prev = self.0.insert(cluster_id, BTreeMap::new());
1666        assert_eq!(
1667            prev, None,
1668            "cluster {cluster_id} statuses already initialized"
1669        );
1670    }
1671
1672    /// Initializes the statuses of the specified cluster replica.
1673    ///
1674    /// Panics if the cluster replica statuses are already initialized.
1675    pub(crate) fn initialize_cluster_replica_statuses(
1676        &mut self,
1677        cluster_id: ClusterId,
1678        replica_id: ReplicaId,
1679        num_processes: usize,
1680        time: DateTime<Utc>,
1681    ) {
1682        tracing::info!(
1683            ?cluster_id,
1684            ?replica_id,
1685            ?time,
1686            "initializing cluster replica status"
1687        );
1688        let replica_statuses = self.0.entry(cluster_id).or_default();
1689        let process_statuses = (0..num_processes)
1690            .map(|process_id| {
1691                let status = ClusterReplicaProcessStatus {
1692                    status: ClusterStatus::Offline(Some(OfflineReason::Initializing)),
1693                    time: time.clone(),
1694                };
1695                (u64::cast_from(process_id), status)
1696            })
1697            .collect();
1698        let prev = replica_statuses.insert(replica_id, process_statuses);
1699        assert_none!(
1700            prev,
1701            "cluster replica {cluster_id}.{replica_id} statuses already initialized"
1702        );
1703    }
1704
1705    /// Removes the statuses of the specified cluster.
1706    ///
1707    /// Panics if the cluster does not exist.
1708    pub(crate) fn remove_cluster_statuses(
1709        &mut self,
1710        cluster_id: &ClusterId,
1711    ) -> BTreeMap<ReplicaId, BTreeMap<ProcessId, ClusterReplicaProcessStatus>> {
1712        let prev = self.0.remove(cluster_id);
1713        prev.unwrap_or_else(|| panic!("unknown cluster: {cluster_id}"))
1714    }
1715
1716    /// Removes the statuses of the specified cluster replica.
1717    ///
1718    /// Panics if the cluster or replica does not exist.
1719    pub(crate) fn remove_cluster_replica_statuses(
1720        &mut self,
1721        cluster_id: &ClusterId,
1722        replica_id: &ReplicaId,
1723    ) -> BTreeMap<ProcessId, ClusterReplicaProcessStatus> {
1724        let replica_statuses = self
1725            .0
1726            .get_mut(cluster_id)
1727            .unwrap_or_else(|| panic!("unknown cluster: {cluster_id}"));
1728        let prev = replica_statuses.remove(replica_id);
1729        prev.unwrap_or_else(|| panic!("unknown cluster replica: {cluster_id}.{replica_id}"))
1730    }
1731
1732    /// Inserts or updates the status of the specified cluster replica process.
1733    ///
1734    /// Panics if the cluster or replica does not exist.
1735    pub(crate) fn ensure_cluster_status(
1736        &mut self,
1737        cluster_id: ClusterId,
1738        replica_id: ReplicaId,
1739        process_id: ProcessId,
1740        status: ClusterReplicaProcessStatus,
1741    ) {
1742        let replica_statuses = self
1743            .0
1744            .get_mut(&cluster_id)
1745            .unwrap_or_else(|| panic!("unknown cluster: {cluster_id}"))
1746            .get_mut(&replica_id)
1747            .unwrap_or_else(|| panic!("unknown cluster replica: {cluster_id}.{replica_id}"));
1748        replica_statuses.insert(process_id, status);
1749    }
1750
1751    /// Computes the status of the cluster replica as a whole.
1752    ///
1753    /// Panics if `cluster_id` or `replica_id` don't exist.
1754    pub fn get_cluster_replica_status(
1755        &self,
1756        cluster_id: ClusterId,
1757        replica_id: ReplicaId,
1758    ) -> ClusterStatus {
1759        let process_status = self.get_cluster_replica_statuses(cluster_id, replica_id);
1760        Self::cluster_replica_status(process_status)
1761    }
1762
1763    /// Computes the status of the cluster replica as a whole.
1764    pub fn cluster_replica_status(
1765        process_status: &BTreeMap<ProcessId, ClusterReplicaProcessStatus>,
1766    ) -> ClusterStatus {
1767        process_status
1768            .values()
1769            .fold(ClusterStatus::Online, |s, p| match (s, p.status) {
1770                (ClusterStatus::Online, ClusterStatus::Online) => ClusterStatus::Online,
1771                (x, y) => {
1772                    let reason_x = match x {
1773                        ClusterStatus::Offline(reason) => reason,
1774                        ClusterStatus::Online => None,
1775                    };
1776                    let reason_y = match y {
1777                        ClusterStatus::Offline(reason) => reason,
1778                        ClusterStatus::Online => None,
1779                    };
1780                    // Arbitrarily pick the first known not-ready reason.
1781                    ClusterStatus::Offline(reason_x.or(reason_y))
1782                }
1783            })
1784    }
1785
1786    /// Gets the statuses of the given cluster replica.
1787    ///
1788    /// Panics if the cluster or replica does not exist
1789    pub(crate) fn get_cluster_replica_statuses(
1790        &self,
1791        cluster_id: ClusterId,
1792        replica_id: ReplicaId,
1793    ) -> &BTreeMap<ProcessId, ClusterReplicaProcessStatus> {
1794        self.try_get_cluster_replica_statuses(cluster_id, replica_id)
1795            .unwrap_or_else(|| panic!("unknown cluster replica: {cluster_id}.{replica_id}"))
1796    }
1797
1798    /// Gets the statuses of the given cluster replica.
1799    pub(crate) fn try_get_cluster_replica_statuses(
1800        &self,
1801        cluster_id: ClusterId,
1802        replica_id: ReplicaId,
1803    ) -> Option<&BTreeMap<ProcessId, ClusterReplicaProcessStatus>> {
1804        self.try_get_cluster_statuses(cluster_id)
1805            .and_then(|statuses| statuses.get(&replica_id))
1806    }
1807
1808    /// Gets the statuses of the given cluster.
1809    pub(crate) fn try_get_cluster_statuses(
1810        &self,
1811        cluster_id: ClusterId,
1812    ) -> Option<&BTreeMap<ReplicaId, BTreeMap<ProcessId, ClusterReplicaProcessStatus>>> {
1813        self.0.get(&cluster_id)
1814    }
1815}
1816
1817/// Glues the external world to the Timely workers.
1818#[derive(Derivative)]
1819#[derivative(Debug)]
1820pub struct Coordinator {
1821    /// The controller for the storage and compute layers.
1822    #[derivative(Debug = "ignore")]
1823    controller: mz_controller::Controller,
1824    /// The catalog in an Arc suitable for readonly references. The Arc allows
1825    /// us to hand out cheap copies of the catalog to functions that can use it
1826    /// off of the main coordinator thread. If the coordinator needs to mutate
1827    /// the catalog, call [`Self::catalog_mut`], which will clone this struct member,
1828    /// allowing it to be mutated here while the other off-thread references can
1829    /// read their catalog as long as needed. In the future we would like this
1830    /// to be a pTVC, but for now this is sufficient.
1831    catalog: Arc<Catalog>,
1832
1833    /// A client for persist. Initially, this is only used for reading stashed
1834    /// peek responses out of batches.
1835    persist_client: PersistClient,
1836
1837    /// Channel to manage internal commands from the coordinator to itself.
1838    internal_cmd_tx: mpsc::UnboundedSender<Message>,
1839    /// Notification that triggers a group commit.
1840    group_commit_tx: appends::GroupCommitNotifier,
1841
1842    /// Channel for strict serializable reads ready to commit.
1843    strict_serializable_reads_tx: mpsc::UnboundedSender<(ConnectionId, PendingReadTxn)>,
1844
1845    /// Mechanism for totally ordering write and read timestamps, so that all reads
1846    /// reflect exactly the set of writes that precede them, and no writes that follow.
1847    global_timelines: BTreeMap<Timeline, TimelineState>,
1848
1849    /// A generator for transient [`GlobalId`]s, shareable with other threads.
1850    transient_id_gen: Arc<TransientIdGen>,
1851    /// A map from connection ID to metadata about that connection for all
1852    /// active connections.
1853    active_conns: BTreeMap<ConnectionId, ConnMeta>,
1854
1855    /// For each transaction, the read holds taken to support any performed reads.
1856    ///
1857    /// Upon completing a transaction, these read holds should be dropped.
1858    txn_read_holds: BTreeMap<ConnectionId, read_policy::ReadHolds>,
1859
1860    /// Access to the peek fields should be restricted to methods in the [`peek`] API.
1861    /// A map from pending peek ids to the queue into which responses are sent, and
1862    /// the connection id of the client that initiated the peek.
1863    pending_peeks: BTreeMap<Uuid, PendingPeek>,
1864    /// A map from client connection ids to a set of all pending peeks for that client.
1865    client_pending_peeks: BTreeMap<ConnectionId, BTreeMap<Uuid, ClusterId>>,
1866
1867    /// A map from client connection ids to pending linearize read transaction.
1868    pending_linearize_read_txns: BTreeMap<ConnectionId, PendingReadTxn>,
1869
1870    /// A map from the compute sink ID to it's state description.
1871    active_compute_sinks: BTreeMap<GlobalId, ActiveComputeSink>,
1872    /// A map from active webhooks to their invalidation handle.
1873    active_webhooks: BTreeMap<CatalogItemId, WebhookAppenderInvalidator>,
1874    /// A map of active `COPY FROM` statements. The Coordinator waits for `clusterd`
1875    /// to stage Batches in Persist that we will then link into the shard.
1876    active_copies: BTreeMap<ConnectionId, ActiveCopyFrom>,
1877
1878    /// A map from connection ids to a watch channel that is set to `true` if the connection
1879    /// received a cancel request.
1880    staged_cancellation: BTreeMap<ConnectionId, (watch::Sender<bool>, watch::Receiver<bool>)>,
1881    /// Active introspection subscribes.
1882    introspection_subscribes: BTreeMap<GlobalId, IntrospectionSubscribe>,
1883
1884    /// Locks that grant access to a specific object, populated lazily as objects are written to.
1885    write_locks: BTreeMap<CatalogItemId, Arc<tokio::sync::Mutex<()>>>,
1886    /// Plans that are currently deferred and waiting on a write lock.
1887    deferred_write_ops: BTreeMap<ConnectionId, DeferredOp>,
1888
1889    /// Pending writes waiting for a group commit.
1890    pending_writes: Vec<PendingWriteTxn>,
1891
1892    /// For the realtime timeline, an explicit SELECT or INSERT on a table will bump the
1893    /// table's timestamps, but there are cases where timestamps are not bumped but
1894    /// we expect the closed timestamps to advance (`AS OF X`, SUBSCRIBing views over
1895    /// RT sources and tables). To address these, spawn a task that forces table
1896    /// timestamps to close on a regular interval. This roughly tracks the behavior
1897    /// of realtime sources that close off timestamps on an interval.
1898    ///
1899    /// For non-realtime timelines, nothing pushes the timestamps forward, so we must do
1900    /// it manually.
1901    advance_timelines_interval: Interval,
1902
1903    /// Serialized DDL. DDL must be serialized because:
1904    /// - Many of them do off-thread work and need to verify the catalog is in a valid state, but
1905    ///   [`PlanValidity`] does not currently support tracking all changes. Doing that correctly
1906    ///   seems to be more difficult than it's worth, so we would instead re-plan and re-sequence
1907    ///   the statements.
1908    /// - Re-planning a statement is hard because Coordinator and Session state is mutated at
1909    ///   various points, and we would need to correctly reset those changes before re-planning and
1910    ///   re-sequencing.
1911    serialized_ddl: LockedVecDeque<DeferredPlanStatement>,
1912
1913    /// Handle to secret manager that can create and delete secrets from
1914    /// an arbitrary secret storage engine.
1915    secrets_controller: Arc<dyn SecretsController>,
1916    /// A secrets reader than maintains an in-memory cache, where values have a set TTL.
1917    caching_secrets_reader: CachingSecretsReader,
1918
1919    /// Handle to a manager that can create and delete kubernetes resources
1920    /// (ie: VpcEndpoint objects)
1921    cloud_resource_controller: Option<Arc<dyn CloudResourceController>>,
1922
1923    /// Persist client for fetching storage metadata such as size metrics.
1924    storage_usage_client: StorageUsageClient,
1925    /// The interval at which to collect storage usage information.
1926    storage_usage_collection_interval: Duration,
1927
1928    /// Segment analytics client.
1929    #[derivative(Debug = "ignore")]
1930    segment_client: Option<mz_segment::Client>,
1931
1932    /// Coordinator metrics.
1933    metrics: Metrics,
1934    /// Optimizer metrics.
1935    optimizer_metrics: OptimizerMetrics,
1936
1937    /// Tracing handle.
1938    tracing_handle: TracingHandle,
1939
1940    /// Data used by the statement logging feature.
1941    statement_logging: StatementLogging,
1942
1943    /// Limit for how many concurrent webhook requests we allow.
1944    webhook_concurrency_limit: WebhookConcurrencyLimiter,
1945
1946    /// Optional config for the timestamp oracle. This is _required_ when
1947    /// a timestamp oracle backend is configured.
1948    timestamp_oracle_config: Option<TimestampOracleConfig>,
1949
1950    /// Periodically asks cluster scheduling policies to make their decisions.
1951    check_cluster_scheduling_policies_interval: Interval,
1952
1953    /// This keeps the last On/Off decision for each cluster and each scheduling policy.
1954    /// (Clusters that have been dropped or are otherwise out of scope for automatic scheduling are
1955    /// periodically cleaned up from this Map.)
1956    cluster_scheduling_decisions: BTreeMap<ClusterId, BTreeMap<&'static str, SchedulingDecision>>,
1957
1958    /// When doing 0dt upgrades/in read-only mode, periodically ask all known
1959    /// clusters/collections whether they are caught up.
1960    caught_up_check_interval: Interval,
1961
1962    /// Context needed to check whether all clusters/collections have caught up.
1963    /// Only used during 0dt deployment, while in read-only mode.
1964    caught_up_check: Option<CaughtUpCheckContext>,
1965
1966    /// Tracks the state associated with the currently installed watchsets.
1967    installed_watch_sets: BTreeMap<WatchSetId, (ConnectionId, WatchSetResponse)>,
1968
1969    /// Tracks the currently installed watchsets for each connection.
1970    connection_watch_sets: BTreeMap<ConnectionId, BTreeSet<WatchSetId>>,
1971
1972    /// Tracks the statuses of all cluster replicas.
1973    cluster_replica_statuses: ClusterReplicaStatuses,
1974
1975    /// Whether or not to start controllers in read-only mode. This is only
1976    /// meant for use during development of read-only clusters and 0dt upgrades
1977    /// and should go away once we have proper orchestration during upgrades.
1978    read_only_controllers: bool,
1979
1980    /// Updates to builtin tables that are being buffered while we are in
1981    /// read-only mode. We apply these all at once when coming out of read-only
1982    /// mode.
1983    ///
1984    /// This is a `Some` while in read-only mode and will be replaced by a
1985    /// `None` when we transition out of read-only mode and write out any
1986    /// buffered updates.
1987    buffered_builtin_table_updates: Option<Vec<BuiltinTableUpdate>>,
1988
1989    license_key: ValidatedLicenseKey,
1990
1991    /// Pre-allocated pool of user IDs to amortize persist writes across DDL operations.
1992    user_id_pool: IdPool,
1993}
1994
1995impl Coordinator {
1996    /// Initializes coordinator state based on the contained catalog. Must be
1997    /// called after creating the coordinator and before calling the
1998    /// `Coordinator::serve` method.
1999    #[instrument(name = "coord::bootstrap")]
2000    pub(crate) async fn bootstrap(
2001        &mut self,
2002        boot_ts: Timestamp,
2003        migrated_storage_collections_0dt: BTreeSet<CatalogItemId>,
2004        mut builtin_table_updates: Vec<BuiltinTableUpdate>,
2005        cached_global_exprs: BTreeMap<GlobalId, GlobalExpressions>,
2006        uncached_local_exprs: BTreeMap<GlobalId, LocalExpressions>,
2007        audit_logs_iterator: AuditLogIterator,
2008    ) -> Result<(), AdapterError> {
2009        let bootstrap_start = Instant::now();
2010        info!("startup: coordinator init: bootstrap beginning");
2011        info!("startup: coordinator init: bootstrap: preamble beginning");
2012
2013        // Initialize cluster replica statuses.
2014        // Gross iterator is to avoid partial borrow issues.
2015        let cluster_statuses: Vec<(_, Vec<_>)> = self
2016            .catalog()
2017            .clusters()
2018            .map(|cluster| {
2019                (
2020                    cluster.id(),
2021                    cluster
2022                        .replicas()
2023                        .map(|replica| {
2024                            (replica.replica_id, replica.config.location.num_processes())
2025                        })
2026                        .collect(),
2027                )
2028            })
2029            .collect();
2030        let now = self.now_datetime();
2031        for (cluster_id, replica_statuses) in cluster_statuses {
2032            self.cluster_replica_statuses
2033                .initialize_cluster_statuses(cluster_id);
2034            for (replica_id, num_processes) in replica_statuses {
2035                self.cluster_replica_statuses
2036                    .initialize_cluster_replica_statuses(
2037                        cluster_id,
2038                        replica_id,
2039                        num_processes,
2040                        now,
2041                    );
2042            }
2043        }
2044
2045        let system_config = self.catalog().system_config();
2046
2047        // Inform metrics about the initial system configuration.
2048        mz_metrics::update_dyncfg(&system_config.dyncfg_updates());
2049
2050        // Inform the controllers about their initial configuration.
2051        let compute_config = flags::compute_config(system_config);
2052        let storage_config = flags::storage_config(system_config);
2053        let scheduling_config = flags::orchestrator_scheduling_config(system_config);
2054        let dyncfg_updates = system_config.dyncfg_updates();
2055        self.controller.compute.update_configuration(compute_config);
2056        self.controller.storage.update_parameters(storage_config);
2057        self.controller
2058            .update_orchestrator_scheduling_config(scheduling_config);
2059        self.controller.update_configuration(dyncfg_updates);
2060
2061        self.validate_resource_limit_numeric(
2062            Numeric::zero(),
2063            self.current_credit_consumption_rate(),
2064            |system_vars| {
2065                self.license_key
2066                    .max_credit_consumption_rate()
2067                    .map_or_else(|| system_vars.max_credit_consumption_rate(), Numeric::from)
2068            },
2069            "cluster replica",
2070            MAX_CREDIT_CONSUMPTION_RATE.name(),
2071        )?;
2072
2073        let mut policies_to_set: BTreeMap<CompactionWindow, CollectionIdBundle> =
2074            Default::default();
2075
2076        let enable_worker_core_affinity =
2077            self.catalog().system_config().enable_worker_core_affinity();
2078        for instance in self.catalog.clusters() {
2079            self.controller.create_cluster(
2080                instance.id,
2081                ClusterConfig {
2082                    arranged_logs: instance.log_indexes.clone(),
2083                    workload_class: instance.config.workload_class.clone(),
2084                },
2085            )?;
2086            for replica in instance.replicas() {
2087                let role = instance.role();
2088                self.controller.create_replica(
2089                    instance.id,
2090                    replica.replica_id,
2091                    instance.name.clone(),
2092                    replica.name.clone(),
2093                    role,
2094                    replica.config.clone(),
2095                    enable_worker_core_affinity,
2096                )?;
2097            }
2098        }
2099
2100        info!(
2101            "startup: coordinator init: bootstrap: preamble complete in {:?}",
2102            bootstrap_start.elapsed()
2103        );
2104
2105        let init_storage_collections_start = Instant::now();
2106        info!("startup: coordinator init: bootstrap: storage collections init beginning");
2107        self.bootstrap_storage_collections(&migrated_storage_collections_0dt)
2108            .await;
2109        info!(
2110            "startup: coordinator init: bootstrap: storage collections init complete in {:?}",
2111            init_storage_collections_start.elapsed()
2112        );
2113
2114        // The storage controller knows about the introspection collections now, so we can start
2115        // sinking introspection updates in the compute controller. It makes sense to do that as
2116        // soon as possible, to avoid updates piling up in the compute controller's internal
2117        // buffers.
2118        self.controller.start_compute_introspection_sink();
2119
2120        let sorting_start = Instant::now();
2121        info!("startup: coordinator init: bootstrap: sorting catalog entries");
2122        let entries = self.bootstrap_sort_catalog_entries();
2123        info!(
2124            "startup: coordinator init: bootstrap: sorting catalog entries complete in {:?}",
2125            sorting_start.elapsed()
2126        );
2127
2128        let optimize_dataflows_start = Instant::now();
2129        info!("startup: coordinator init: bootstrap: optimize dataflow plans beginning");
2130        let uncached_global_exps = self.bootstrap_dataflow_plans(&entries, cached_global_exprs)?;
2131        info!(
2132            "startup: coordinator init: bootstrap: optimize dataflow plans complete in {:?}",
2133            optimize_dataflows_start.elapsed()
2134        );
2135
2136        // We don't need to wait for the cache to update.
2137        let _fut = self.catalog().update_expression_cache(
2138            uncached_local_exprs.into_iter().collect(),
2139            uncached_global_exps.into_iter().collect(),
2140            Default::default(),
2141        );
2142
2143        // Select dataflow as-ofs. This step relies on the storage collections created by
2144        // `bootstrap_storage_collections` and the dataflow plans created by
2145        // `bootstrap_dataflow_plans`.
2146        let bootstrap_as_ofs_start = Instant::now();
2147        info!("startup: coordinator init: bootstrap: dataflow as-of bootstrapping beginning");
2148        let dataflow_read_holds = self.bootstrap_dataflow_as_ofs().await;
2149        info!(
2150            "startup: coordinator init: bootstrap: dataflow as-of bootstrapping complete in {:?}",
2151            bootstrap_as_ofs_start.elapsed()
2152        );
2153
2154        let postamble_start = Instant::now();
2155        info!("startup: coordinator init: bootstrap: postamble beginning");
2156
2157        let logs: BTreeSet<_> = BUILTINS::logs()
2158            .map(|log| self.catalog().resolve_builtin_log(log))
2159            .flat_map(|item_id| self.catalog().get_global_ids(&item_id))
2160            .collect();
2161
2162        let mut privatelink_connections = BTreeMap::new();
2163
2164        for entry in &entries {
2165            debug!(
2166                "coordinator init: installing {} {}",
2167                entry.item().typ(),
2168                entry.id()
2169            );
2170            let mut policy = entry.item().initial_logical_compaction_window();
2171            match entry.item() {
2172                // Currently catalog item rebuild assumes that sinks and
2173                // indexes are always built individually and does not store information
2174                // about how it was built. If we start building multiple sinks and/or indexes
2175                // using a single dataflow, we have to make sure the rebuild process re-runs
2176                // the same multiple-build dataflow.
2177                CatalogItem::Source(source) => {
2178                    // Propagate source compaction windows to subsources if needed.
2179                    if source.custom_logical_compaction_window.is_none() {
2180                        if let DataSourceDesc::IngestionExport { ingestion_id, .. } =
2181                            source.data_source
2182                        {
2183                            policy = Some(
2184                                self.catalog()
2185                                    .get_entry(&ingestion_id)
2186                                    .source()
2187                                    .expect("must be source")
2188                                    .custom_logical_compaction_window
2189                                    .unwrap_or_default(),
2190                            );
2191                        }
2192                    }
2193                    policies_to_set
2194                        .entry(policy.expect("sources have a compaction window"))
2195                        .or_insert_with(Default::default)
2196                        .storage_ids
2197                        .insert(source.global_id());
2198                }
2199                CatalogItem::Table(table) => {
2200                    policies_to_set
2201                        .entry(policy.expect("tables have a compaction window"))
2202                        .or_insert_with(Default::default)
2203                        .storage_ids
2204                        .extend(table.global_ids());
2205                }
2206                CatalogItem::Index(idx) => {
2207                    let policy_entry = policies_to_set
2208                        .entry(policy.expect("indexes have a compaction window"))
2209                        .or_insert_with(Default::default);
2210
2211                    if logs.contains(&idx.on) {
2212                        policy_entry
2213                            .compute_ids
2214                            .entry(idx.cluster_id)
2215                            .or_insert_with(BTreeSet::new)
2216                            .insert(idx.global_id());
2217                    } else {
2218                        let df_desc = self
2219                            .catalog()
2220                            .try_get_physical_plan(&idx.global_id())
2221                            .expect("added in `bootstrap_dataflow_plans`")
2222                            .clone();
2223
2224                        let df_meta = self
2225                            .catalog()
2226                            .try_get_dataflow_metainfo(&idx.global_id())
2227                            .expect("added in `bootstrap_dataflow_plans`");
2228
2229                        if self.catalog().state().system_config().enable_mz_notices() {
2230                            // Collect optimization hint updates.
2231                            self.catalog().state().pack_optimizer_notices(
2232                                &mut builtin_table_updates,
2233                                df_meta.optimizer_notices.iter(),
2234                                Diff::ONE,
2235                            );
2236                        }
2237
2238                        // What follows is morally equivalent to `self.ship_dataflow(df, idx.cluster_id)`,
2239                        // but we cannot call that as it will also downgrade the read hold on the index.
2240                        policy_entry
2241                            .compute_ids
2242                            .entry(idx.cluster_id)
2243                            .or_insert_with(Default::default)
2244                            .extend(df_desc.export_ids());
2245
2246                        self.controller
2247                            .compute
2248                            .create_dataflow(idx.cluster_id, df_desc, None)
2249                            .unwrap_or_terminate("cannot fail to create dataflows");
2250                    }
2251                }
2252                CatalogItem::View(_) => (),
2253                CatalogItem::MaterializedView(mview) => {
2254                    policies_to_set
2255                        .entry(policy.expect("materialized views have a compaction window"))
2256                        .or_insert_with(Default::default)
2257                        .storage_ids
2258                        .insert(mview.global_id_writes());
2259
2260                    let mut df_desc = self
2261                        .catalog()
2262                        .try_get_physical_plan(&mview.global_id_writes())
2263                        .expect("added in `bootstrap_dataflow_plans`")
2264                        .clone();
2265
2266                    if let Some(initial_as_of) = mview.initial_as_of.clone() {
2267                        df_desc.set_initial_as_of(initial_as_of);
2268                    }
2269
2270                    // If we have a refresh schedule that has a last refresh, then set the `until` to the last refresh.
2271                    let until = mview
2272                        .refresh_schedule
2273                        .as_ref()
2274                        .and_then(|s| s.last_refresh())
2275                        .and_then(|r| r.try_step_forward());
2276                    if let Some(until) = until {
2277                        df_desc.until.meet_assign(&Antichain::from_elem(until));
2278                    }
2279
2280                    let df_meta = self
2281                        .catalog()
2282                        .try_get_dataflow_metainfo(&mview.global_id_writes())
2283                        .expect("added in `bootstrap_dataflow_plans`");
2284
2285                    if self.catalog().state().system_config().enable_mz_notices() {
2286                        // Collect optimization hint updates.
2287                        self.catalog().state().pack_optimizer_notices(
2288                            &mut builtin_table_updates,
2289                            df_meta.optimizer_notices.iter(),
2290                            Diff::ONE,
2291                        );
2292                    }
2293
2294                    self.ship_dataflow(df_desc, mview.cluster_id, mview.target_replica)
2295                        .await;
2296
2297                    // If this is a replacement MV, it must remain read-only until the replacement
2298                    // gets applied.
2299                    if mview.replacement_target.is_none() {
2300                        self.allow_writes(mview.cluster_id, mview.global_id_writes());
2301                    }
2302                }
2303                CatalogItem::Sink(sink) => {
2304                    policies_to_set
2305                        .entry(CompactionWindow::Default)
2306                        .or_insert_with(Default::default)
2307                        .storage_ids
2308                        .insert(sink.global_id());
2309                }
2310                CatalogItem::Connection(catalog_connection) => {
2311                    if let ConnectionDetails::AwsPrivatelink(conn) = &catalog_connection.details {
2312                        privatelink_connections.insert(
2313                            entry.id(),
2314                            VpcEndpointConfig {
2315                                aws_service_name: conn.service_name.clone(),
2316                                availability_zone_ids: conn.availability_zones.clone(),
2317                            },
2318                        );
2319                    }
2320                }
2321                CatalogItem::ContinualTask(ct) => {
2322                    policies_to_set
2323                        .entry(policy.expect("continual tasks have a compaction window"))
2324                        .or_insert_with(Default::default)
2325                        .storage_ids
2326                        .insert(ct.global_id());
2327
2328                    let mut df_desc = self
2329                        .catalog()
2330                        .try_get_physical_plan(&ct.global_id())
2331                        .expect("added in `bootstrap_dataflow_plans`")
2332                        .clone();
2333
2334                    if let Some(initial_as_of) = ct.initial_as_of.clone() {
2335                        df_desc.set_initial_as_of(initial_as_of);
2336                    }
2337
2338                    let df_meta = self
2339                        .catalog()
2340                        .try_get_dataflow_metainfo(&ct.global_id())
2341                        .expect("added in `bootstrap_dataflow_plans`");
2342
2343                    if self.catalog().state().system_config().enable_mz_notices() {
2344                        // Collect optimization hint updates.
2345                        self.catalog().state().pack_optimizer_notices(
2346                            &mut builtin_table_updates,
2347                            df_meta.optimizer_notices.iter(),
2348                            Diff::ONE,
2349                        );
2350                    }
2351
2352                    self.ship_dataflow(df_desc, ct.cluster_id, None).await;
2353                    self.allow_writes(ct.cluster_id, ct.global_id());
2354                }
2355                // Nothing to do for these cases
2356                CatalogItem::Log(_)
2357                | CatalogItem::Type(_)
2358                | CatalogItem::Func(_)
2359                | CatalogItem::Secret(_) => {}
2360            }
2361        }
2362
2363        if let Some(cloud_resource_controller) = &self.cloud_resource_controller {
2364            // Clean up any extraneous VpcEndpoints that shouldn't exist.
2365            let existing_vpc_endpoints = cloud_resource_controller
2366                .list_vpc_endpoints()
2367                .await
2368                .context("list vpc endpoints")?;
2369            let existing_vpc_endpoints = BTreeSet::from_iter(existing_vpc_endpoints.into_keys());
2370            let desired_vpc_endpoints = privatelink_connections.keys().cloned().collect();
2371            let vpc_endpoints_to_remove = existing_vpc_endpoints.difference(&desired_vpc_endpoints);
2372            for id in vpc_endpoints_to_remove {
2373                cloud_resource_controller
2374                    .delete_vpc_endpoint(*id)
2375                    .await
2376                    .context("deleting extraneous vpc endpoint")?;
2377            }
2378
2379            // Ensure desired VpcEndpoints are up to date.
2380            for (id, spec) in privatelink_connections {
2381                cloud_resource_controller
2382                    .ensure_vpc_endpoint(id, spec)
2383                    .await
2384                    .context("ensuring vpc endpoint")?;
2385            }
2386        }
2387
2388        // Having installed all entries, creating all constraints, we can now drop read holds and
2389        // relax read policies.
2390        drop(dataflow_read_holds);
2391        // TODO -- Improve `initialize_read_policies` API so we can avoid calling this in a loop.
2392        for (cw, policies) in policies_to_set {
2393            self.initialize_read_policies(&policies, cw).await;
2394        }
2395
2396        // Expose mapping from T-shirt sizes to actual sizes
2397        builtin_table_updates.extend(
2398            self.catalog().state().resolve_builtin_table_updates(
2399                self.catalog().state().pack_all_replica_size_updates(),
2400            ),
2401        );
2402
2403        debug!("startup: coordinator init: bootstrap: initializing migrated builtin tables");
2404        // When 0dt is enabled, we create new shards for any migrated builtin storage collections.
2405        // In read-only mode, the migrated builtin tables (which are a subset of migrated builtin
2406        // storage collections) need to be back-filled so that any dependent dataflow can be
2407        // hydrated. Additionally, these shards are not registered with the txn-shard, and cannot
2408        // be registered while in read-only, so they are written to directly.
2409        let migrated_updates_fut = if self.controller.read_only() {
2410            let min_timestamp = Timestamp::minimum();
2411            let migrated_builtin_table_updates: Vec<_> = builtin_table_updates
2412                .extract_if(.., |update| {
2413                    let gid = self.catalog().get_entry(&update.id).latest_global_id();
2414                    migrated_storage_collections_0dt.contains(&update.id)
2415                        && self
2416                            .controller
2417                            .storage_collections
2418                            .collection_frontiers(gid)
2419                            .expect("all tables are registered")
2420                            .write_frontier
2421                            .elements()
2422                            == &[min_timestamp]
2423                })
2424                .collect();
2425            if migrated_builtin_table_updates.is_empty() {
2426                futures::future::ready(()).boxed()
2427            } else {
2428                // Group all updates per-table.
2429                let mut grouped_appends: BTreeMap<GlobalId, Vec<TableData>> = BTreeMap::new();
2430                for update in migrated_builtin_table_updates {
2431                    let gid = self.catalog().get_entry(&update.id).latest_global_id();
2432                    grouped_appends.entry(gid).or_default().push(update.data);
2433                }
2434                info!(
2435                    "coordinator init: rehydrating migrated builtin tables in read-only mode: {:?}",
2436                    grouped_appends.keys().collect::<Vec<_>>()
2437                );
2438
2439                // Consolidate Row data, staged batches must already be consolidated.
2440                let mut all_appends = Vec::with_capacity(grouped_appends.len());
2441                for (item_id, table_data) in grouped_appends.into_iter() {
2442                    let mut all_rows = Vec::new();
2443                    let mut all_data = Vec::new();
2444                    for data in table_data {
2445                        match data {
2446                            TableData::Rows(rows) => all_rows.extend(rows),
2447                            TableData::Batches(_) => all_data.push(data),
2448                        }
2449                    }
2450                    differential_dataflow::consolidation::consolidate(&mut all_rows);
2451                    all_data.push(TableData::Rows(all_rows));
2452
2453                    // TODO(parkmycar): Use SmallVec throughout.
2454                    all_appends.push((item_id, all_data));
2455                }
2456
2457                let fut = self
2458                    .controller
2459                    .storage
2460                    .append_table(min_timestamp, boot_ts.step_forward(), all_appends)
2461                    .expect("cannot fail to append");
2462                async {
2463                    fut.await
2464                        .expect("One-shot shouldn't be dropped during bootstrap")
2465                        .unwrap_or_terminate("cannot fail to append")
2466                }
2467                .boxed()
2468            }
2469        } else {
2470            futures::future::ready(()).boxed()
2471        };
2472
2473        info!(
2474            "startup: coordinator init: bootstrap: postamble complete in {:?}",
2475            postamble_start.elapsed()
2476        );
2477
2478        let builtin_update_start = Instant::now();
2479        info!("startup: coordinator init: bootstrap: generate builtin updates beginning");
2480
2481        if self.controller.read_only() {
2482            info!(
2483                "coordinator init: bootstrap: stashing builtin table updates while in read-only mode"
2484            );
2485
2486            // TODO(jkosh44) Optimize deserializing the audit log in read-only mode.
2487            let audit_join_start = Instant::now();
2488            info!("startup: coordinator init: bootstrap: audit log deserialization beginning");
2489            let audit_log_updates: Vec<_> = audit_logs_iterator
2490                .map(|(audit_log, ts)| StateUpdate {
2491                    kind: StateUpdateKind::AuditLog(audit_log),
2492                    ts,
2493                    diff: StateDiff::Addition,
2494                })
2495                .collect();
2496            let audit_log_builtin_table_updates = self
2497                .catalog()
2498                .state()
2499                .generate_builtin_table_updates(audit_log_updates);
2500            builtin_table_updates.extend(audit_log_builtin_table_updates);
2501            info!(
2502                "startup: coordinator init: bootstrap: audit log deserialization complete in {:?}",
2503                audit_join_start.elapsed()
2504            );
2505            self.buffered_builtin_table_updates
2506                .as_mut()
2507                .expect("in read-only mode")
2508                .append(&mut builtin_table_updates);
2509        } else {
2510            self.bootstrap_tables(&entries, builtin_table_updates, audit_logs_iterator)
2511                .await;
2512        };
2513        info!(
2514            "startup: coordinator init: bootstrap: generate builtin updates complete in {:?}",
2515            builtin_update_start.elapsed()
2516        );
2517
2518        let cleanup_secrets_start = Instant::now();
2519        info!("startup: coordinator init: bootstrap: generate secret cleanup beginning");
2520        // Cleanup orphaned secrets. Errors during list() or delete() do not
2521        // need to prevent bootstrap from succeeding; we will retry next
2522        // startup.
2523        {
2524            // Destructure Self so we can selectively move fields into the async
2525            // task.
2526            let Self {
2527                secrets_controller,
2528                catalog,
2529                ..
2530            } = self;
2531
2532            let next_user_item_id = catalog.get_next_user_item_id().await?;
2533            let next_system_item_id = catalog.get_next_system_item_id().await?;
2534            let read_only = self.controller.read_only();
2535            // Fetch all IDs from the catalog to future-proof against other
2536            // things using secrets. Today, SECRET and CONNECTION objects use
2537            // secrets_controller.ensure, but more things could in the future
2538            // that would be easy to miss adding here.
2539            let catalog_ids: BTreeSet<CatalogItemId> =
2540                catalog.entries().map(|entry| entry.id()).collect();
2541            let secrets_controller = Arc::clone(secrets_controller);
2542
2543            spawn(|| "cleanup-orphaned-secrets", async move {
2544                if read_only {
2545                    info!(
2546                        "coordinator init: not cleaning up orphaned secrets while in read-only mode"
2547                    );
2548                    return;
2549                }
2550                info!("coordinator init: cleaning up orphaned secrets");
2551
2552                match secrets_controller.list().await {
2553                    Ok(controller_secrets) => {
2554                        let controller_secrets: BTreeSet<CatalogItemId> =
2555                            controller_secrets.into_iter().collect();
2556                        let orphaned = controller_secrets.difference(&catalog_ids);
2557                        for id in orphaned {
2558                            let id_too_large = match id {
2559                                CatalogItemId::System(id) => *id >= next_system_item_id,
2560                                CatalogItemId::User(id) => *id >= next_user_item_id,
2561                                CatalogItemId::IntrospectionSourceIndex(_)
2562                                | CatalogItemId::Transient(_) => false,
2563                            };
2564                            if id_too_large {
2565                                info!(
2566                                    %next_user_item_id, %next_system_item_id,
2567                                    "coordinator init: not deleting orphaned secret {id} that was likely created by a newer deploy generation"
2568                                );
2569                            } else {
2570                                info!("coordinator init: deleting orphaned secret {id}");
2571                                fail_point!("orphan_secrets");
2572                                if let Err(e) = secrets_controller.delete(*id).await {
2573                                    warn!(
2574                                        "Dropping orphaned secret has encountered an error: {}",
2575                                        e
2576                                    );
2577                                }
2578                            }
2579                        }
2580                    }
2581                    Err(e) => warn!("Failed to list secrets during orphan cleanup: {:?}", e),
2582                }
2583            });
2584        }
2585        info!(
2586            "startup: coordinator init: bootstrap: generate secret cleanup complete in {:?}",
2587            cleanup_secrets_start.elapsed()
2588        );
2589
2590        // Run all of our final steps concurrently.
2591        let final_steps_start = Instant::now();
2592        info!(
2593            "startup: coordinator init: bootstrap: migrate builtin tables in read-only mode beginning"
2594        );
2595        migrated_updates_fut
2596            .instrument(info_span!("coord::bootstrap::final"))
2597            .await;
2598
2599        debug!(
2600            "startup: coordinator init: bootstrap: announcing completion of initialization to controller"
2601        );
2602        // Announce the completion of initialization.
2603        self.controller.initialization_complete();
2604
2605        // Initialize unified introspection.
2606        self.bootstrap_introspection_subscribes().await;
2607
2608        info!(
2609            "startup: coordinator init: bootstrap: migrate builtin tables in read-only mode complete in {:?}",
2610            final_steps_start.elapsed()
2611        );
2612
2613        info!(
2614            "startup: coordinator init: bootstrap complete in {:?}",
2615            bootstrap_start.elapsed()
2616        );
2617        Ok(())
2618    }
2619
2620    /// Prepares tables for writing by resetting them to a known state and
2621    /// appending the given builtin table updates. The timestamp oracle
2622    /// will be advanced to the write timestamp of the append when this
2623    /// method returns.
2624    #[allow(clippy::async_yields_async)]
2625    #[instrument]
2626    async fn bootstrap_tables(
2627        &mut self,
2628        entries: &[CatalogEntry],
2629        mut builtin_table_updates: Vec<BuiltinTableUpdate>,
2630        audit_logs_iterator: AuditLogIterator,
2631    ) {
2632        /// Smaller helper struct of metadata for bootstrapping tables.
2633        struct TableMetadata<'a> {
2634            id: CatalogItemId,
2635            name: &'a QualifiedItemName,
2636            table: &'a Table,
2637        }
2638
2639        // Filter our entries down to just tables.
2640        let table_metas: Vec<_> = entries
2641            .into_iter()
2642            .filter_map(|entry| {
2643                entry.table().map(|table| TableMetadata {
2644                    id: entry.id(),
2645                    name: entry.name(),
2646                    table,
2647                })
2648            })
2649            .collect();
2650
2651        // Append empty batches to advance the timestamp of all tables.
2652        debug!("coordinator init: advancing all tables to current timestamp");
2653        let WriteTimestamp {
2654            timestamp: write_ts,
2655            advance_to,
2656        } = self.get_local_write_ts().await;
2657        let appends = table_metas
2658            .iter()
2659            .map(|meta| (meta.table.global_id_writes(), Vec::new()))
2660            .collect();
2661        // Append the tables in the background. We apply the write timestamp before getting a read
2662        // timestamp and reading a snapshot of each table, so the snapshots will block on their own
2663        // until the appends are complete.
2664        let table_fence_rx = self
2665            .controller
2666            .storage
2667            .append_table(write_ts.clone(), advance_to, appends)
2668            .expect("invalid updates");
2669
2670        self.apply_local_write(write_ts).await;
2671
2672        // Add builtin table updates the clear the contents of all system tables
2673        debug!("coordinator init: resetting system tables");
2674        let read_ts = self.get_local_read_ts().await;
2675
2676        // Filter out the 'mz_storage_usage_by_shard' table since we need to retain that info for
2677        // billing purposes.
2678        let mz_storage_usage_by_shard_schema: SchemaSpecifier = self
2679            .catalog()
2680            .resolve_system_schema(MZ_STORAGE_USAGE_BY_SHARD.schema)
2681            .into();
2682        let is_storage_usage_by_shard = |meta: &TableMetadata| -> bool {
2683            meta.name.item == MZ_STORAGE_USAGE_BY_SHARD.name
2684                && meta.name.qualifiers.schema_spec == mz_storage_usage_by_shard_schema
2685        };
2686
2687        let mut retraction_tasks = Vec::new();
2688        let mut system_tables: Vec<_> = table_metas
2689            .iter()
2690            .filter(|meta| meta.id.is_system() && !is_storage_usage_by_shard(meta))
2691            .collect();
2692
2693        // Special case audit events because it's append only.
2694        let (audit_events_idx, _) = system_tables
2695            .iter()
2696            .find_position(|table| {
2697                table.id == self.catalog().resolve_builtin_table(&MZ_AUDIT_EVENTS)
2698            })
2699            .expect("mz_audit_events must exist");
2700        let audit_events = system_tables.remove(audit_events_idx);
2701        let audit_log_task = self.bootstrap_audit_log_table(
2702            audit_events.id,
2703            audit_events.name,
2704            audit_events.table,
2705            audit_logs_iterator,
2706            read_ts,
2707        );
2708
2709        for system_table in system_tables {
2710            let table_id = system_table.id;
2711            let full_name = self.catalog().resolve_full_name(system_table.name, None);
2712            debug!("coordinator init: resetting system table {full_name} ({table_id})");
2713
2714            // Fetch the current contents of the table for retraction.
2715            let snapshot_fut = self
2716                .controller
2717                .storage_collections
2718                .snapshot_cursor(system_table.table.global_id_writes(), read_ts);
2719            let batch_fut = self
2720                .controller
2721                .storage_collections
2722                .create_update_builder(system_table.table.global_id_writes());
2723
2724            let task = spawn(|| format!("snapshot-{table_id}"), async move {
2725                // Create a TimestamplessUpdateBuilder.
2726                let mut batch = batch_fut
2727                    .await
2728                    .unwrap_or_terminate("cannot fail to create a batch for a BuiltinTable");
2729                tracing::info!(?table_id, "starting snapshot");
2730                // Get a cursor which will emit a consolidated snapshot.
2731                let mut snapshot_cursor = snapshot_fut
2732                    .await
2733                    .unwrap_or_terminate("cannot fail to snapshot");
2734
2735                // Retract the current contents, spilling into our builder.
2736                while let Some(values) = snapshot_cursor.next().await {
2737                    for (key, _t, d) in values {
2738                        let d_invert = d.neg();
2739                        batch.add(&key, &(), &d_invert).await;
2740                    }
2741                }
2742                tracing::info!(?table_id, "finished snapshot");
2743
2744                let batch = batch.finish().await;
2745                BuiltinTableUpdate::batch(table_id, batch)
2746            });
2747            retraction_tasks.push(task);
2748        }
2749
2750        let retractions_res = futures::future::join_all(retraction_tasks).await;
2751        for retractions in retractions_res {
2752            builtin_table_updates.push(retractions);
2753        }
2754
2755        let audit_join_start = Instant::now();
2756        info!("startup: coordinator init: bootstrap: join audit log deserialization beginning");
2757        let audit_log_updates = audit_log_task.await;
2758        let audit_log_builtin_table_updates = self
2759            .catalog()
2760            .state()
2761            .generate_builtin_table_updates(audit_log_updates);
2762        builtin_table_updates.extend(audit_log_builtin_table_updates);
2763        info!(
2764            "startup: coordinator init: bootstrap: join audit log deserialization complete in {:?}",
2765            audit_join_start.elapsed()
2766        );
2767
2768        // Now that the snapshots are complete, the appends must also be complete.
2769        table_fence_rx
2770            .await
2771            .expect("One-shot shouldn't be dropped during bootstrap")
2772            .unwrap_or_terminate("cannot fail to append");
2773
2774        info!("coordinator init: sending builtin table updates");
2775        let (_builtin_updates_fut, write_ts) = self
2776            .builtin_table_update()
2777            .execute(builtin_table_updates)
2778            .await;
2779        info!(?write_ts, "our write ts");
2780        if let Some(write_ts) = write_ts {
2781            self.apply_local_write(write_ts).await;
2782        }
2783    }
2784
2785    /// Prepare updates to the audit log table. The audit log table append only and very large, so
2786    /// we only need to find the events present in `audit_logs_iterator` but not in the audit log
2787    /// table.
2788    #[instrument]
2789    fn bootstrap_audit_log_table<'a>(
2790        &self,
2791        table_id: CatalogItemId,
2792        name: &'a QualifiedItemName,
2793        table: &'a Table,
2794        audit_logs_iterator: AuditLogIterator,
2795        read_ts: Timestamp,
2796    ) -> JoinHandle<Vec<StateUpdate>> {
2797        let full_name = self.catalog().resolve_full_name(name, None);
2798        debug!("coordinator init: reconciling audit log: {full_name} ({table_id})");
2799        let current_contents_fut = self
2800            .controller
2801            .storage_collections
2802            .snapshot(table.global_id_writes(), read_ts);
2803        spawn(|| format!("snapshot-audit-log-{table_id}"), async move {
2804            let current_contents = current_contents_fut
2805                .await
2806                .unwrap_or_terminate("cannot fail to fetch snapshot");
2807            let contents_len = current_contents.len();
2808            debug!("coordinator init: audit log table ({table_id}) size {contents_len}");
2809
2810            // Fetch the largest audit log event ID that has been written to the table.
2811            let max_table_id = current_contents
2812                .into_iter()
2813                .filter(|(_, diff)| *diff == 1)
2814                .map(|(row, _diff)| row.unpack_first().unwrap_uint64())
2815                .sorted()
2816                .rev()
2817                .next();
2818
2819            // Filter audit log catalog updates to those that are not present in the table.
2820            audit_logs_iterator
2821                .take_while(|(audit_log, _)| match max_table_id {
2822                    Some(id) => audit_log.event.sortable_id() > id,
2823                    None => true,
2824                })
2825                .map(|(audit_log, ts)| StateUpdate {
2826                    kind: StateUpdateKind::AuditLog(audit_log),
2827                    ts,
2828                    diff: StateDiff::Addition,
2829                })
2830                .collect::<Vec<_>>()
2831        })
2832    }
2833
2834    /// Initializes all storage collections required by catalog objects in the storage controller.
2835    ///
2836    /// This method takes care of collection creation, as well as migration of existing
2837    /// collections.
2838    ///
2839    /// Creating all storage collections in a single `create_collections` call, rather than on
2840    /// demand, is more efficient as it reduces the number of writes to durable storage. It also
2841    /// allows subsequent bootstrap logic to fetch metadata (such as frontiers) of arbitrary
2842    /// storage collections, without needing to worry about dependency order.
2843    ///
2844    /// `migrated_storage_collections` is a set of builtin storage collections that have been
2845    /// migrated and should be handled specially.
2846    #[instrument]
2847    async fn bootstrap_storage_collections(
2848        &mut self,
2849        migrated_storage_collections: &BTreeSet<CatalogItemId>,
2850    ) {
2851        let catalog = self.catalog();
2852
2853        let source_desc = |object_id: GlobalId,
2854                           data_source: &DataSourceDesc,
2855                           desc: &RelationDesc,
2856                           timeline: &Timeline| {
2857            let data_source = match data_source.clone() {
2858                // Re-announce the source description.
2859                DataSourceDesc::Ingestion { desc, cluster_id } => {
2860                    let desc = desc.into_inline_connection(catalog.state());
2861                    let ingestion = IngestionDescription::new(desc, cluster_id, object_id);
2862                    DataSource::Ingestion(ingestion)
2863                }
2864                DataSourceDesc::OldSyntaxIngestion {
2865                    desc,
2866                    progress_subsource,
2867                    data_config,
2868                    details,
2869                    cluster_id,
2870                } => {
2871                    let desc = desc.into_inline_connection(catalog.state());
2872                    let data_config = data_config.into_inline_connection(catalog.state());
2873                    // TODO(parkmycar): We should probably check the type here, but I'm not sure if
2874                    // this will always be a Source or a Table.
2875                    let progress_subsource =
2876                        catalog.get_entry(&progress_subsource).latest_global_id();
2877                    let mut ingestion =
2878                        IngestionDescription::new(desc, cluster_id, progress_subsource);
2879                    let legacy_export = SourceExport {
2880                        storage_metadata: (),
2881                        data_config,
2882                        details,
2883                    };
2884                    ingestion.source_exports.insert(object_id, legacy_export);
2885
2886                    DataSource::Ingestion(ingestion)
2887                }
2888                DataSourceDesc::IngestionExport {
2889                    ingestion_id,
2890                    external_reference: _,
2891                    details,
2892                    data_config,
2893                } => {
2894                    // TODO(parkmycar): We should probably check the type here, but I'm not sure if
2895                    // this will always be a Source or a Table.
2896                    let ingestion_id = catalog.get_entry(&ingestion_id).latest_global_id();
2897
2898                    DataSource::IngestionExport {
2899                        ingestion_id,
2900                        details,
2901                        data_config: data_config.into_inline_connection(catalog.state()),
2902                    }
2903                }
2904                DataSourceDesc::Webhook { .. } => DataSource::Webhook,
2905                DataSourceDesc::Progress => DataSource::Progress,
2906                DataSourceDesc::Introspection(introspection) => {
2907                    DataSource::Introspection(introspection)
2908                }
2909                DataSourceDesc::Catalog => DataSource::Other,
2910            };
2911            CollectionDescription {
2912                desc: desc.clone(),
2913                data_source,
2914                since: None,
2915                timeline: Some(timeline.clone()),
2916                primary: None,
2917            }
2918        };
2919
2920        let mut compute_collections = vec![];
2921        let mut collections = vec![];
2922        for entry in catalog.entries() {
2923            match entry.item() {
2924                CatalogItem::Source(source) => {
2925                    collections.push((
2926                        source.global_id(),
2927                        source_desc(
2928                            source.global_id(),
2929                            &source.data_source,
2930                            &source.desc,
2931                            &source.timeline,
2932                        ),
2933                    ));
2934                }
2935                CatalogItem::Table(table) => {
2936                    match &table.data_source {
2937                        TableDataSource::TableWrites { defaults: _ } => {
2938                            let versions: BTreeMap<_, _> = table
2939                                .collection_descs()
2940                                .map(|(gid, version, desc)| (version, (gid, desc)))
2941                                .collect();
2942                            let collection_descs = versions.iter().map(|(version, (gid, desc))| {
2943                                let next_version = version.bump();
2944                                let primary_collection =
2945                                    versions.get(&next_version).map(|(gid, _desc)| gid).copied();
2946                                let mut collection_desc =
2947                                    CollectionDescription::for_table(desc.clone());
2948                                collection_desc.primary = primary_collection;
2949
2950                                (*gid, collection_desc)
2951                            });
2952                            collections.extend(collection_descs);
2953                        }
2954                        TableDataSource::DataSource {
2955                            desc: data_source_desc,
2956                            timeline,
2957                        } => {
2958                            // TODO(alter_table): Support versioning tables that read from sources.
2959                            soft_assert_eq_or_log!(table.collections.len(), 1);
2960                            let collection_descs =
2961                                table.collection_descs().map(|(gid, _version, desc)| {
2962                                    (
2963                                        gid,
2964                                        source_desc(
2965                                            entry.latest_global_id(),
2966                                            data_source_desc,
2967                                            &desc,
2968                                            timeline,
2969                                        ),
2970                                    )
2971                                });
2972                            collections.extend(collection_descs);
2973                        }
2974                    };
2975                }
2976                CatalogItem::MaterializedView(mv) => {
2977                    let collection_descs = mv.collection_descs().map(|(gid, _version, desc)| {
2978                        let collection_desc =
2979                            CollectionDescription::for_other(desc, mv.initial_as_of.clone());
2980                        (gid, collection_desc)
2981                    });
2982
2983                    collections.extend(collection_descs);
2984                    compute_collections.push((mv.global_id_writes(), mv.desc.latest()));
2985                }
2986                CatalogItem::ContinualTask(ct) => {
2987                    let collection_desc =
2988                        CollectionDescription::for_other(ct.desc.clone(), ct.initial_as_of.clone());
2989                    compute_collections.push((ct.global_id(), ct.desc.clone()));
2990                    collections.push((ct.global_id(), collection_desc));
2991                }
2992                CatalogItem::Sink(sink) => {
2993                    let storage_sink_from_entry = self.catalog().get_entry_by_global_id(&sink.from);
2994                    let from_desc = storage_sink_from_entry
2995                        .relation_desc()
2996                        .expect("sinks can only be built on items with descs")
2997                        .into_owned();
2998                    let collection_desc = CollectionDescription {
2999                        // TODO(sinks): make generic once we have more than one sink type.
3000                        desc: KAFKA_PROGRESS_DESC.clone(),
3001                        data_source: DataSource::Sink {
3002                            desc: ExportDescription {
3003                                sink: StorageSinkDesc {
3004                                    from: sink.from,
3005                                    from_desc,
3006                                    connection: sink
3007                                        .connection
3008                                        .clone()
3009                                        .into_inline_connection(self.catalog().state()),
3010                                    envelope: sink.envelope,
3011                                    as_of: Antichain::from_elem(Timestamp::minimum()),
3012                                    with_snapshot: sink.with_snapshot,
3013                                    version: sink.version,
3014                                    from_storage_metadata: (),
3015                                    to_storage_metadata: (),
3016                                    commit_interval: sink.commit_interval,
3017                                },
3018                                instance_id: sink.cluster_id,
3019                            },
3020                        },
3021                        since: None,
3022                        timeline: None,
3023                        primary: None,
3024                    };
3025                    collections.push((sink.global_id, collection_desc));
3026                }
3027                CatalogItem::Log(_)
3028                | CatalogItem::View(_)
3029                | CatalogItem::Index(_)
3030                | CatalogItem::Type(_)
3031                | CatalogItem::Func(_)
3032                | CatalogItem::Secret(_)
3033                | CatalogItem::Connection(_) => (),
3034            }
3035        }
3036
3037        let register_ts = if self.controller.read_only() {
3038            self.get_local_read_ts().await
3039        } else {
3040            // Getting a write timestamp bumps the write timestamp in the
3041            // oracle, which we're not allowed in read-only mode.
3042            self.get_local_write_ts().await.timestamp
3043        };
3044
3045        let storage_metadata = self.catalog.state().storage_metadata();
3046        let migrated_storage_collections = migrated_storage_collections
3047            .into_iter()
3048            .flat_map(|item_id| self.catalog.get_entry(item_id).global_ids())
3049            .collect();
3050
3051        // Before possibly creating collections, make sure their schemas are correct.
3052        //
3053        // Across different versions of Materialize the nullability of columns can change based on
3054        // updates to our optimizer.
3055        self.controller
3056            .storage
3057            .evolve_nullability_for_bootstrap(storage_metadata, compute_collections)
3058            .await
3059            .unwrap_or_terminate("cannot fail to evolve collections");
3060
3061        // New builtin storage collections are by default created with [0] since/upper frontiers.
3062        // For collections that have dependencies on other collections (MVs, CTs), this can violate
3063        // the frontier invariants assumed by as-of selection. For example, as-of selection expects
3064        // to be able to pick up computing a materialized view from its most recent upper, but if
3065        // that upper is [0] it's likely that the required times are not available anymore in the
3066        // MV inputs.
3067        //
3068        // To avoid violating frontier invariants, we need to bump their sinces to times greater
3069        // than all of their upstream storage inputs. To know the since of a storage input, it has
3070        // to be registered with the storage controller first. Thus we register collections in
3071        // layers: Each iteration registers the collections whose dependencies are all already
3072        // registered.
3073        let mut pending: BTreeMap<_, _> = collections.into_iter().collect();
3074
3075        // Precompute storage-collection dependencies for each collection.
3076        let transitive_dep_gids: BTreeMap<_, _> = pending
3077            .keys()
3078            .map(|gid| {
3079                let entry = self.catalog.get_entry_by_global_id(gid);
3080                let item_id = entry.id();
3081                let deps = self.catalog.state().transitive_uses(item_id);
3082                let dep_gids: BTreeSet<_> = deps
3083                    // Ignore self-dependencies. For example, `transitive_uses` includes the input ID,
3084                    // and CTs can depend on themselves.
3085                    .filter(|dep_id| *dep_id != item_id)
3086                    .map(|dep_id| self.catalog.get_entry(&dep_id).latest_global_id())
3087                    // Ignore dependencies on objects that are not storage collections.
3088                    .filter(|dep_gid| pending.contains_key(dep_gid))
3089                    .collect();
3090                (*gid, dep_gids)
3091            })
3092            .collect();
3093
3094        while !pending.is_empty() {
3095            // Drain collections whose dependencies have all been registered already
3096            // (i.e., are not in `pending`).
3097            let ready_gids: BTreeSet<_> = pending
3098                .keys()
3099                .filter(|gid| {
3100                    let mut deps = transitive_dep_gids[gid].iter();
3101                    !deps.any(|dep_gid| pending.contains_key(dep_gid))
3102                })
3103                .copied()
3104                .collect();
3105            let mut ready: Vec<_> = pending
3106                .extract_if(.., |gid, _| ready_gids.contains(gid))
3107                .collect();
3108
3109            // Bump sinces of builtin collections.
3110            for (gid, collection) in &mut ready {
3111                // Don't silently overwrite an explicitly specified `since`.
3112                if !gid.is_system() || collection.since.is_some() {
3113                    continue;
3114                }
3115
3116                let mut derived_since = Antichain::from_elem(Timestamp::MIN);
3117                for dep_gid in &transitive_dep_gids[gid] {
3118                    let (since, _) = self
3119                        .controller
3120                        .storage
3121                        .collection_frontiers(*dep_gid)
3122                        .expect("previously registered");
3123                    derived_since.join_assign(&since);
3124                }
3125                collection.since = Some(derived_since);
3126            }
3127
3128            if ready.is_empty() {
3129                soft_panic_or_log!(
3130                    "cycle in storage collections: {:?}",
3131                    pending.keys().collect::<Vec<_>>(),
3132                );
3133                // We get here only due to a bug. Rather than crash-looping, we try our best to
3134                // reach a sane state by attempting to register all the remaining collections at
3135                // once.
3136                ready = mem::take(&mut pending).into_iter().collect();
3137            }
3138
3139            self.controller
3140                .storage
3141                .create_collections_for_bootstrap(
3142                    storage_metadata,
3143                    Some(register_ts),
3144                    ready,
3145                    &migrated_storage_collections,
3146                )
3147                .await
3148                .unwrap_or_terminate("cannot fail to create collections");
3149        }
3150
3151        if !self.controller.read_only() {
3152            self.apply_local_write(register_ts).await;
3153        }
3154    }
3155
3156    /// Returns the current list of catalog entries, sorted into an appropriate order for
3157    /// bootstrapping.
3158    ///
3159    /// The returned entries are in dependency order. Indexes are sorted immediately after the
3160    /// objects they index, to ensure that all dependants of these indexed objects can make use of
3161    /// the respective indexes.
3162    fn bootstrap_sort_catalog_entries(&self) -> Vec<CatalogEntry> {
3163        let mut indexes_on = BTreeMap::<_, Vec<_>>::new();
3164        let mut non_indexes = Vec::new();
3165        for entry in self.catalog().entries().cloned() {
3166            if let Some(index) = entry.index() {
3167                let on = self.catalog().get_entry_by_global_id(&index.on);
3168                indexes_on.entry(on.id()).or_default().push(entry);
3169            } else {
3170                non_indexes.push(entry);
3171            }
3172        }
3173
3174        let key_fn = |entry: &CatalogEntry| entry.id;
3175        let dependencies_fn = |entry: &CatalogEntry| entry.uses();
3176        sort_topological(&mut non_indexes, key_fn, dependencies_fn);
3177
3178        let mut result = Vec::new();
3179        for entry in non_indexes {
3180            let id = entry.id();
3181            result.push(entry);
3182            if let Some(mut indexes) = indexes_on.remove(&id) {
3183                result.append(&mut indexes);
3184            }
3185        }
3186
3187        soft_assert_or_log!(
3188            indexes_on.is_empty(),
3189            "indexes with missing dependencies: {indexes_on:?}",
3190        );
3191
3192        result
3193    }
3194
3195    /// Invokes the optimizer on all indexes and materialized views in the catalog and inserts the
3196    /// resulting dataflow plans into the catalog state.
3197    ///
3198    /// `ordered_catalog_entries` must be sorted in dependency order, with dependencies ordered
3199    /// before their dependants.
3200    ///
3201    /// This method does not perform timestamp selection for the dataflows, nor does it create them
3202    /// in the compute controller. Both of these steps happen later during bootstrapping.
3203    ///
3204    /// Returns a map of expressions that were not cached.
3205    #[instrument]
3206    fn bootstrap_dataflow_plans(
3207        &mut self,
3208        ordered_catalog_entries: &[CatalogEntry],
3209        mut cached_global_exprs: BTreeMap<GlobalId, GlobalExpressions>,
3210    ) -> Result<BTreeMap<GlobalId, GlobalExpressions>, AdapterError> {
3211        // The optimizer expects to be able to query its `ComputeInstanceSnapshot` for
3212        // collections the current dataflow can depend on. But since we don't yet install anything
3213        // on compute instances, the snapshot information is incomplete. We fix that by manually
3214        // updating `ComputeInstanceSnapshot` objects to ensure they contain collections previously
3215        // optimized.
3216        let mut instance_snapshots = BTreeMap::new();
3217        let mut uncached_expressions = BTreeMap::new();
3218
3219        let optimizer_config = |catalog: &Catalog, cluster_id| {
3220            let system_config = catalog.system_config();
3221            let overrides = catalog.get_cluster(cluster_id).config.features();
3222            OptimizerConfig::from(system_config).override_from(&overrides)
3223        };
3224
3225        for entry in ordered_catalog_entries {
3226            match entry.item() {
3227                CatalogItem::Index(idx) => {
3228                    // Collect optimizer parameters.
3229                    let compute_instance =
3230                        instance_snapshots.entry(idx.cluster_id).or_insert_with(|| {
3231                            self.instance_snapshot(idx.cluster_id)
3232                                .expect("compute instance exists")
3233                        });
3234                    let global_id = idx.global_id();
3235
3236                    // The index may already be installed on the compute instance. For example,
3237                    // this is the case for introspection indexes.
3238                    if compute_instance.contains_collection(&global_id) {
3239                        continue;
3240                    }
3241
3242                    let optimizer_config = optimizer_config(&self.catalog, idx.cluster_id);
3243
3244                    let (optimized_plan, physical_plan, metainfo) =
3245                        match cached_global_exprs.remove(&global_id) {
3246                            Some(global_expressions)
3247                                if global_expressions.optimizer_features
3248                                    == optimizer_config.features =>
3249                            {
3250                                debug!("global expression cache hit for {global_id:?}");
3251                                (
3252                                    global_expressions.global_mir,
3253                                    global_expressions.physical_plan,
3254                                    global_expressions.dataflow_metainfos,
3255                                )
3256                            }
3257                            Some(_) | None => {
3258                                let (optimized_plan, global_lir_plan) = {
3259                                    // Build an optimizer for this INDEX.
3260                                    let mut optimizer = optimize::index::Optimizer::new(
3261                                        self.owned_catalog(),
3262                                        compute_instance.clone(),
3263                                        global_id,
3264                                        optimizer_config.clone(),
3265                                        self.optimizer_metrics(),
3266                                    );
3267
3268                                    // MIR ⇒ MIR optimization (global)
3269                                    let index_plan = optimize::index::Index::new(
3270                                        entry.name().clone(),
3271                                        idx.on,
3272                                        idx.keys.to_vec(),
3273                                    );
3274                                    let global_mir_plan = optimizer.optimize(index_plan)?;
3275                                    let optimized_plan = global_mir_plan.df_desc().clone();
3276
3277                                    // MIR ⇒ LIR lowering and LIR ⇒ LIR optimization (global)
3278                                    let global_lir_plan = optimizer.optimize(global_mir_plan)?;
3279
3280                                    (optimized_plan, global_lir_plan)
3281                                };
3282
3283                                let (physical_plan, metainfo) = global_lir_plan.unapply();
3284                                let metainfo = {
3285                                    // Pre-allocate a vector of transient GlobalIds for each notice.
3286                                    let notice_ids =
3287                                        std::iter::repeat_with(|| self.allocate_transient_id())
3288                                            .map(|(_item_id, gid)| gid)
3289                                            .take(metainfo.optimizer_notices.len())
3290                                            .collect::<Vec<_>>();
3291                                    // Return a metainfo with rendered notices.
3292                                    self.catalog().render_notices(
3293                                        metainfo,
3294                                        notice_ids,
3295                                        Some(idx.global_id()),
3296                                    )
3297                                };
3298                                uncached_expressions.insert(
3299                                    global_id,
3300                                    GlobalExpressions {
3301                                        global_mir: optimized_plan.clone(),
3302                                        physical_plan: physical_plan.clone(),
3303                                        dataflow_metainfos: metainfo.clone(),
3304                                        optimizer_features: optimizer_config.features.clone(),
3305                                    },
3306                                );
3307                                (optimized_plan, physical_plan, metainfo)
3308                            }
3309                        };
3310
3311                    let catalog = self.catalog_mut();
3312                    catalog.set_optimized_plan(idx.global_id(), optimized_plan);
3313                    catalog.set_physical_plan(idx.global_id(), physical_plan);
3314                    catalog.set_dataflow_metainfo(idx.global_id(), metainfo);
3315
3316                    compute_instance.insert_collection(idx.global_id());
3317                }
3318                CatalogItem::MaterializedView(mv) => {
3319                    // Collect optimizer parameters.
3320                    let compute_instance =
3321                        instance_snapshots.entry(mv.cluster_id).or_insert_with(|| {
3322                            self.instance_snapshot(mv.cluster_id)
3323                                .expect("compute instance exists")
3324                        });
3325                    let global_id = mv.global_id_writes();
3326
3327                    let optimizer_config = optimizer_config(&self.catalog, mv.cluster_id);
3328
3329                    let (optimized_plan, physical_plan, metainfo) = match cached_global_exprs
3330                        .remove(&global_id)
3331                    {
3332                        Some(global_expressions)
3333                            if global_expressions.optimizer_features
3334                                == optimizer_config.features =>
3335                        {
3336                            debug!("global expression cache hit for {global_id:?}");
3337                            (
3338                                global_expressions.global_mir,
3339                                global_expressions.physical_plan,
3340                                global_expressions.dataflow_metainfos,
3341                            )
3342                        }
3343                        Some(_) | None => {
3344                            let (_, internal_view_id) = self.allocate_transient_id();
3345                            let debug_name = self
3346                                .catalog()
3347                                .resolve_full_name(entry.name(), None)
3348                                .to_string();
3349                            let force_non_monotonic = Default::default();
3350
3351                            let (optimized_plan, global_lir_plan) = {
3352                                // Build an optimizer for this MATERIALIZED VIEW.
3353                                let mut optimizer = optimize::materialized_view::Optimizer::new(
3354                                    self.owned_catalog().as_optimizer_catalog(),
3355                                    compute_instance.clone(),
3356                                    global_id,
3357                                    internal_view_id,
3358                                    mv.desc.latest().iter_names().cloned().collect(),
3359                                    mv.non_null_assertions.clone(),
3360                                    mv.refresh_schedule.clone(),
3361                                    debug_name,
3362                                    optimizer_config.clone(),
3363                                    self.optimizer_metrics(),
3364                                    force_non_monotonic,
3365                                );
3366
3367                                // MIR ⇒ MIR optimization (global)
3368                                // We make sure to use the HIR SQL type (since MIR SQL types may not be coherent).
3369                                let typ = infer_sql_type_for_catalog(
3370                                    &mv.raw_expr,
3371                                    &mv.locally_optimized_expr.as_ref().clone(),
3372                                );
3373                                let global_mir_plan = optimizer
3374                                    .optimize((mv.locally_optimized_expr.as_ref().clone(), typ))?;
3375                                let optimized_plan = global_mir_plan.df_desc().clone();
3376
3377                                // MIR ⇒ LIR lowering and LIR ⇒ LIR optimization (global)
3378                                let global_lir_plan = optimizer.optimize(global_mir_plan)?;
3379
3380                                (optimized_plan, global_lir_plan)
3381                            };
3382
3383                            let (physical_plan, metainfo) = global_lir_plan.unapply();
3384                            let metainfo = {
3385                                // Pre-allocate a vector of transient GlobalIds for each notice.
3386                                let notice_ids =
3387                                    std::iter::repeat_with(|| self.allocate_transient_id())
3388                                        .map(|(_item_id, global_id)| global_id)
3389                                        .take(metainfo.optimizer_notices.len())
3390                                        .collect::<Vec<_>>();
3391                                // Return a metainfo with rendered notices.
3392                                self.catalog().render_notices(
3393                                    metainfo,
3394                                    notice_ids,
3395                                    Some(mv.global_id_writes()),
3396                                )
3397                            };
3398                            uncached_expressions.insert(
3399                                global_id,
3400                                GlobalExpressions {
3401                                    global_mir: optimized_plan.clone(),
3402                                    physical_plan: physical_plan.clone(),
3403                                    dataflow_metainfos: metainfo.clone(),
3404                                    optimizer_features: optimizer_config.features.clone(),
3405                                },
3406                            );
3407                            (optimized_plan, physical_plan, metainfo)
3408                        }
3409                    };
3410
3411                    let catalog = self.catalog_mut();
3412                    catalog.set_optimized_plan(mv.global_id_writes(), optimized_plan);
3413                    catalog.set_physical_plan(mv.global_id_writes(), physical_plan);
3414                    catalog.set_dataflow_metainfo(mv.global_id_writes(), metainfo);
3415
3416                    compute_instance.insert_collection(mv.global_id_writes());
3417                }
3418                CatalogItem::ContinualTask(ct) => {
3419                    let compute_instance =
3420                        instance_snapshots.entry(ct.cluster_id).or_insert_with(|| {
3421                            self.instance_snapshot(ct.cluster_id)
3422                                .expect("compute instance exists")
3423                        });
3424                    let global_id = ct.global_id();
3425
3426                    let optimizer_config = optimizer_config(&self.catalog, ct.cluster_id);
3427
3428                    let (optimized_plan, physical_plan, metainfo) =
3429                        match cached_global_exprs.remove(&global_id) {
3430                            Some(global_expressions)
3431                                if global_expressions.optimizer_features
3432                                    == optimizer_config.features =>
3433                            {
3434                                debug!("global expression cache hit for {global_id:?}");
3435                                (
3436                                    global_expressions.global_mir,
3437                                    global_expressions.physical_plan,
3438                                    global_expressions.dataflow_metainfos,
3439                                )
3440                            }
3441                            Some(_) | None => {
3442                                let debug_name = self
3443                                    .catalog()
3444                                    .resolve_full_name(entry.name(), None)
3445                                    .to_string();
3446                                let (optimized_plan, physical_plan, metainfo, optimizer_features) =
3447                                    self.optimize_create_continual_task(
3448                                        ct,
3449                                        global_id,
3450                                        self.owned_catalog(),
3451                                        debug_name,
3452                                    )?;
3453                                uncached_expressions.insert(
3454                                    global_id,
3455                                    GlobalExpressions {
3456                                        global_mir: optimized_plan.clone(),
3457                                        physical_plan: physical_plan.clone(),
3458                                        dataflow_metainfos: metainfo.clone(),
3459                                        optimizer_features,
3460                                    },
3461                                );
3462                                (optimized_plan, physical_plan, metainfo)
3463                            }
3464                        };
3465
3466                    let catalog = self.catalog_mut();
3467                    catalog.set_optimized_plan(ct.global_id(), optimized_plan);
3468                    catalog.set_physical_plan(ct.global_id(), physical_plan);
3469                    catalog.set_dataflow_metainfo(ct.global_id(), metainfo);
3470
3471                    compute_instance.insert_collection(ct.global_id());
3472                }
3473                CatalogItem::Table(_)
3474                | CatalogItem::Source(_)
3475                | CatalogItem::Log(_)
3476                | CatalogItem::View(_)
3477                | CatalogItem::Sink(_)
3478                | CatalogItem::Type(_)
3479                | CatalogItem::Func(_)
3480                | CatalogItem::Secret(_)
3481                | CatalogItem::Connection(_) => (),
3482            }
3483        }
3484
3485        Ok(uncached_expressions)
3486    }
3487
3488    /// Selects for each compute dataflow an as-of suitable for bootstrapping it.
3489    ///
3490    /// Returns a set of [`ReadHold`]s that ensures the read frontiers of involved collections stay
3491    /// in place and that must not be dropped before all compute dataflows have been created with
3492    /// the compute controller.
3493    ///
3494    /// This method expects all storage collections and dataflow plans to be available, so it must
3495    /// run after [`Coordinator::bootstrap_storage_collections`] and
3496    /// [`Coordinator::bootstrap_dataflow_plans`].
3497    async fn bootstrap_dataflow_as_ofs(&mut self) -> BTreeMap<GlobalId, ReadHold> {
3498        let mut catalog_ids = Vec::new();
3499        let mut dataflows = Vec::new();
3500        let mut read_policies = BTreeMap::new();
3501        for entry in self.catalog.entries() {
3502            let gid = match entry.item() {
3503                CatalogItem::Index(idx) => idx.global_id(),
3504                CatalogItem::MaterializedView(mv) => mv.global_id_writes(),
3505                CatalogItem::ContinualTask(ct) => ct.global_id(),
3506                CatalogItem::Table(_)
3507                | CatalogItem::Source(_)
3508                | CatalogItem::Log(_)
3509                | CatalogItem::View(_)
3510                | CatalogItem::Sink(_)
3511                | CatalogItem::Type(_)
3512                | CatalogItem::Func(_)
3513                | CatalogItem::Secret(_)
3514                | CatalogItem::Connection(_) => continue,
3515            };
3516            if let Some(plan) = self.catalog.try_get_physical_plan(&gid) {
3517                catalog_ids.push(gid);
3518                dataflows.push(plan.clone());
3519
3520                if let Some(compaction_window) = entry.item().initial_logical_compaction_window() {
3521                    read_policies.insert(gid, compaction_window.into());
3522                }
3523            }
3524        }
3525
3526        let read_ts = self.get_local_read_ts().await;
3527        let read_holds = as_of_selection::run(
3528            &mut dataflows,
3529            &read_policies,
3530            &*self.controller.storage_collections,
3531            read_ts,
3532            self.controller.read_only(),
3533        );
3534
3535        let catalog = self.catalog_mut();
3536        for (id, plan) in catalog_ids.into_iter().zip_eq(dataflows) {
3537            catalog.set_physical_plan(id, plan);
3538        }
3539
3540        read_holds
3541    }
3542
3543    /// Serves the coordinator, receiving commands from users over `cmd_rx`
3544    /// and feedback from dataflow workers over `feedback_rx`.
3545    ///
3546    /// You must call `bootstrap` before calling this method.
3547    ///
3548    /// BOXED FUTURE: As of Nov 2023 the returned Future from this function was 92KB. This would
3549    /// get stored on the stack which is bad for runtime performance, and blow up our stack usage.
3550    /// Because of that we purposefully move this Future onto the heap (i.e. Box it).
3551    fn serve(
3552        mut self,
3553        mut internal_cmd_rx: mpsc::UnboundedReceiver<Message>,
3554        mut strict_serializable_reads_rx: mpsc::UnboundedReceiver<(ConnectionId, PendingReadTxn)>,
3555        mut cmd_rx: mpsc::UnboundedReceiver<(OpenTelemetryContext, Command)>,
3556        group_commit_rx: appends::GroupCommitWaiter,
3557    ) -> LocalBoxFuture<'static, ()> {
3558        async move {
3559            // Watcher that listens for and reports cluster service status changes.
3560            let mut cluster_events = self.controller.events_stream();
3561            let last_message = Arc::new(Mutex::new(LastMessage {
3562                kind: "none",
3563                stmt: None,
3564            }));
3565
3566            let (idle_tx, mut idle_rx) = tokio::sync::mpsc::channel(1);
3567            let idle_metric = self.metrics.queue_busy_seconds.clone();
3568            let last_message_watchdog = Arc::clone(&last_message);
3569
3570            spawn(|| "coord watchdog", async move {
3571                // Every 5 seconds, attempt to measure how long it takes for the
3572                // coord select loop to be empty, because this message is the last
3573                // processed. If it is idle, this will result in some microseconds
3574                // of measurement.
3575                let mut interval = tokio::time::interval(Duration::from_secs(5));
3576                // If we end up having to wait more than 5 seconds for the coord to respond, then the
3577                // behavior of Delay results in the interval "restarting" from whenever we yield
3578                // instead of trying to catch up.
3579                interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
3580
3581                // Track if we become stuck to de-dupe error reporting.
3582                let mut coord_stuck = false;
3583
3584                loop {
3585                    interval.tick().await;
3586
3587                    // Wait for space in the channel, if we timeout then the coordinator is stuck!
3588                    let duration = tokio::time::Duration::from_secs(30);
3589                    let timeout = tokio::time::timeout(duration, idle_tx.reserve()).await;
3590                    let Ok(maybe_permit) = timeout else {
3591                        // Only log if we're newly stuck, to prevent logging repeatedly.
3592                        if !coord_stuck {
3593                            let last_message = last_message_watchdog.lock().expect("poisoned");
3594                            tracing::warn!(
3595                                last_message_kind = %last_message.kind,
3596                                last_message_sql = %last_message.stmt_to_string(),
3597                                "coordinator stuck for {duration:?}",
3598                            );
3599                        }
3600                        coord_stuck = true;
3601
3602                        continue;
3603                    };
3604
3605                    // We got a permit, we're not stuck!
3606                    if coord_stuck {
3607                        tracing::info!("Coordinator became unstuck");
3608                    }
3609                    coord_stuck = false;
3610
3611                    // If we failed to acquire a permit it's because we're shutting down.
3612                    let Ok(permit) = maybe_permit else {
3613                        break;
3614                    };
3615
3616                    permit.send(idle_metric.start_timer());
3617                }
3618            });
3619
3620            self.schedule_storage_usage_collection().await;
3621            self.spawn_privatelink_vpc_endpoints_watch_task();
3622            self.spawn_statement_logging_task();
3623            flags::tracing_config(self.catalog.system_config()).apply(&self.tracing_handle);
3624
3625            // Report if the handling of a single message takes longer than this threshold.
3626            let warn_threshold = self
3627                .catalog()
3628                .system_config()
3629                .coord_slow_message_warn_threshold();
3630
3631            // How many messages we'd like to batch up before processing them. Must be > 0.
3632            const MESSAGE_BATCH: usize = 64;
3633            let mut messages = Vec::with_capacity(MESSAGE_BATCH);
3634            let mut cmd_messages = Vec::with_capacity(MESSAGE_BATCH);
3635
3636            let message_batch = self.metrics.message_batch.clone();
3637
3638            loop {
3639                // Before adding a branch to this select loop, please ensure that the branch is
3640                // cancellation safe and add a comment explaining why. You can refer here for more
3641                // info: https://docs.rs/tokio/latest/tokio/macro.select.html#cancellation-safety
3642                select! {
3643                    // We prioritize internal commands over other commands. However, we work through
3644                    // batches of commands in some branches of this select, which means that even if
3645                    // a command generates internal commands, we will work through the current batch
3646                    // before receiving a new batch of commands.
3647                    biased;
3648
3649                    // `recv_many()` on `UnboundedReceiver` is cancellation safe:
3650                    // https://docs.rs/tokio/1.38.0/tokio/sync/mpsc/struct.UnboundedReceiver.html#cancel-safety-1
3651                    // Receive a batch of commands.
3652                    _ = internal_cmd_rx.recv_many(&mut messages, MESSAGE_BATCH) => {},
3653                    // `next()` on any stream is cancel-safe:
3654                    // https://docs.rs/tokio-stream/0.1.9/tokio_stream/trait.StreamExt.html#cancel-safety
3655                    // Receive a single command.
3656                    Some(event) = cluster_events.next() => {
3657                        messages.push(Message::ClusterEvent(event))
3658                    },
3659                    // See [`mz_controller::Controller::Controller::ready`] for notes
3660                    // on why this is cancel-safe.
3661                    // Receive a single command.
3662                    () = self.controller.ready() => {
3663                        // NOTE: We don't get a `Readiness` back from `ready()`
3664                        // because the controller wants to keep it and it's not
3665                        // trivially `Clone` or `Copy`. Hence this accessor.
3666                        let controller = match self.controller.get_readiness() {
3667                            Readiness::Storage => ControllerReadiness::Storage,
3668                            Readiness::Compute => ControllerReadiness::Compute,
3669                            Readiness::Metrics(_) => ControllerReadiness::Metrics,
3670                            Readiness::Internal(_) => ControllerReadiness::Internal,
3671                            Readiness::NotReady => unreachable!("just signaled as ready"),
3672                        };
3673                        messages.push(Message::ControllerReady { controller });
3674                    }
3675                    // See [`appends::GroupCommitWaiter`] for notes on why this is cancel safe.
3676                    // Receive a single command.
3677                    permit = group_commit_rx.ready() => {
3678                        // If we happen to have batched exactly one user write, use
3679                        // that span so the `emit_trace_id_notice` hooks up.
3680                        // Otherwise, the best we can do is invent a new root span
3681                        // and make it follow from all the Spans in the pending
3682                        // writes.
3683                        let user_write_spans = self.pending_writes.iter().flat_map(|x| match x {
3684                            PendingWriteTxn::User{span, ..} => Some(span),
3685                            PendingWriteTxn::System{..} => None,
3686                        });
3687                        let span = match user_write_spans.exactly_one() {
3688                            Ok(span) => span.clone(),
3689                            Err(user_write_spans) => {
3690                                let span = info_span!(parent: None, "group_commit_notify");
3691                                for s in user_write_spans {
3692                                    span.follows_from(s);
3693                                }
3694                                span
3695                            }
3696                        };
3697                        messages.push(Message::GroupCommitInitiate(span, Some(permit)));
3698                    },
3699                    // `recv_many()` on `UnboundedReceiver` is cancellation safe:
3700                    // https://docs.rs/tokio/1.38.0/tokio/sync/mpsc/struct.UnboundedReceiver.html#cancel-safety-1
3701                    // Receive a batch of commands.
3702                    count = cmd_rx.recv_many(&mut cmd_messages, MESSAGE_BATCH) => {
3703                        if count == 0 {
3704                            break;
3705                        } else {
3706                            messages.extend(cmd_messages.drain(..).map(
3707                                |(otel_ctx, cmd)| Message::Command(otel_ctx, cmd),
3708                            ));
3709                        }
3710                    },
3711                    // `recv()` on `UnboundedReceiver` is cancellation safe:
3712                    // https://docs.rs/tokio/1.38.0/tokio/sync/mpsc/struct.UnboundedReceiver.html#cancel-safety
3713                    // Receive a single command.
3714                    Some(pending_read_txn) = strict_serializable_reads_rx.recv() => {
3715                        let mut pending_read_txns = vec![pending_read_txn];
3716                        while let Ok(pending_read_txn) = strict_serializable_reads_rx.try_recv() {
3717                            pending_read_txns.push(pending_read_txn);
3718                        }
3719                        for (conn_id, pending_read_txn) in pending_read_txns {
3720                            let prev = self
3721                                .pending_linearize_read_txns
3722                                .insert(conn_id, pending_read_txn);
3723                            soft_assert_or_log!(
3724                                prev.is_none(),
3725                                "connections can not have multiple concurrent reads, prev: {prev:?}"
3726                            )
3727                        }
3728                        messages.push(Message::LinearizeReads);
3729                    }
3730                    // `tick()` on `Interval` is cancel-safe:
3731                    // https://docs.rs/tokio/1.19.2/tokio/time/struct.Interval.html#cancel-safety
3732                    // Receive a single command.
3733                    _ = self.advance_timelines_interval.tick() => {
3734                        let span = info_span!(parent: None, "coord::advance_timelines_interval");
3735                        span.follows_from(Span::current());
3736
3737                        // Group commit sends an `AdvanceTimelines` message when
3738                        // done, which is what downgrades read holds. In
3739                        // read-only mode we send this message directly because
3740                        // we're not doing group commits.
3741                        if self.controller.read_only() {
3742                            messages.push(Message::AdvanceTimelines);
3743                        } else {
3744                            messages.push(Message::GroupCommitInitiate(span, None));
3745                        }
3746                    },
3747                    // `tick()` on `Interval` is cancel-safe:
3748                    // https://docs.rs/tokio/1.19.2/tokio/time/struct.Interval.html#cancel-safety
3749                    // Receive a single command.
3750                    _ = self.check_cluster_scheduling_policies_interval.tick() => {
3751                        messages.push(Message::CheckSchedulingPolicies);
3752                    },
3753
3754                    // `tick()` on `Interval` is cancel-safe:
3755                    // https://docs.rs/tokio/1.19.2/tokio/time/struct.Interval.html#cancel-safety
3756                    // Receive a single command.
3757                    _ = self.caught_up_check_interval.tick() => {
3758                        // We do this directly on the main loop instead of
3759                        // firing off a message. We are still in read-only mode,
3760                        // so optimizing for latency, not blocking the main loop
3761                        // is not that important.
3762                        self.maybe_check_caught_up().await;
3763
3764                        continue;
3765                    },
3766
3767                    // Process the idle metric at the lowest priority to sample queue non-idle time.
3768                    // `recv()` on `Receiver` is cancellation safe:
3769                    // https://docs.rs/tokio/1.8.0/tokio/sync/mpsc/struct.Receiver.html#cancel-safety
3770                    // Receive a single command.
3771                    timer = idle_rx.recv() => {
3772                        timer.expect("does not drop").observe_duration();
3773                        self.metrics
3774                            .message_handling
3775                            .with_label_values(&["watchdog"])
3776                            .observe(0.0);
3777                        continue;
3778                    }
3779                };
3780
3781                // Observe the number of messages we're processing at once.
3782                message_batch.observe(f64::cast_lossy(messages.len()));
3783
3784                for msg in messages.drain(..) {
3785                    // All message processing functions trace. Start a parent span
3786                    // for them to make it easy to find slow messages.
3787                    let msg_kind = msg.kind();
3788                    let span = span!(
3789                        target: "mz_adapter::coord::handle_message_loop",
3790                        Level::INFO,
3791                        "coord::handle_message",
3792                        kind = msg_kind
3793                    );
3794                    let otel_context = span.context().span().span_context().clone();
3795
3796                    // Record the last kind of message in case we get stuck. For
3797                    // execute commands, we additionally stash the user's SQL,
3798                    // statement, so we can log it in case we get stuck.
3799                    *last_message.lock().expect("poisoned") = LastMessage {
3800                        kind: msg_kind,
3801                        stmt: match &msg {
3802                            Message::Command(
3803                                _,
3804                                Command::Execute {
3805                                    portal_name,
3806                                    session,
3807                                    ..
3808                                },
3809                            ) => session
3810                                .get_portal_unverified(portal_name)
3811                                .and_then(|p| p.stmt.as_ref().map(Arc::clone)),
3812                            _ => None,
3813                        },
3814                    };
3815
3816                    let start = Instant::now();
3817                    self.handle_message(msg).instrument(span).await;
3818                    let duration = start.elapsed();
3819
3820                    self.metrics
3821                        .message_handling
3822                        .with_label_values(&[msg_kind])
3823                        .observe(duration.as_secs_f64());
3824
3825                    // If something is _really_ slow, print a trace id for debugging, if OTEL is enabled.
3826                    if duration > warn_threshold {
3827                        let trace_id = otel_context.is_valid().then(|| otel_context.trace_id());
3828                        tracing::error!(
3829                            ?msg_kind,
3830                            ?trace_id,
3831                            ?duration,
3832                            "very slow coordinator message"
3833                        );
3834                    }
3835                }
3836            }
3837            // Try and cleanup as a best effort. There may be some async tasks out there holding a
3838            // reference that prevents us from cleaning up.
3839            if let Some(catalog) = Arc::into_inner(self.catalog) {
3840                catalog.expire().await;
3841            }
3842        }
3843        .boxed_local()
3844    }
3845
3846    /// Obtain a read-only Catalog reference.
3847    fn catalog(&self) -> &Catalog {
3848        &self.catalog
3849    }
3850
3851    /// Obtain a read-only Catalog snapshot, suitable for giving out to
3852    /// non-Coordinator thread tasks.
3853    fn owned_catalog(&self) -> Arc<Catalog> {
3854        Arc::clone(&self.catalog)
3855    }
3856
3857    /// Obtain a handle to the optimizer metrics, suitable for giving
3858    /// out to non-Coordinator thread tasks.
3859    fn optimizer_metrics(&self) -> OptimizerMetrics {
3860        self.optimizer_metrics.clone()
3861    }
3862
3863    /// Obtain a writeable Catalog reference.
3864    fn catalog_mut(&mut self) -> &mut Catalog {
3865        // make_mut will cause any other Arc references (from owned_catalog) to
3866        // continue to be valid by cloning the catalog, putting it in a new Arc,
3867        // which lives at self._catalog. If there are no other Arc references,
3868        // then no clone is made, and it returns a reference to the existing
3869        // object. This makes this method and owned_catalog both very cheap: at
3870        // most one clone per catalog mutation, but only if there's a read-only
3871        // reference to it.
3872        Arc::make_mut(&mut self.catalog)
3873    }
3874
3875    /// Refills the user ID pool by allocating IDs from the catalog.
3876    ///
3877    /// Requests `max(min_count, batch_size)` IDs so the pool is never
3878    /// under-filled relative to the configured batch size.
3879    async fn refill_user_id_pool(&mut self, min_count: u64) -> Result<(), AdapterError> {
3880        let batch_size = USER_ID_POOL_BATCH_SIZE.get(self.catalog().system_config().dyncfgs());
3881        let to_allocate = min_count.max(u64::from(batch_size));
3882        let id_ts = self.get_catalog_write_ts().await;
3883        let ids = self.catalog().allocate_user_ids(to_allocate, id_ts).await?;
3884        if let (Some((first_id, _)), Some((last_id, _))) = (ids.first(), ids.last()) {
3885            let start = match first_id {
3886                CatalogItemId::User(id) => *id,
3887                other => {
3888                    return Err(AdapterError::Internal(format!(
3889                        "expected User CatalogItemId, got {other:?}"
3890                    )));
3891                }
3892            };
3893            let end = match last_id {
3894                CatalogItemId::User(id) => *id + 1, // exclusive upper bound
3895                other => {
3896                    return Err(AdapterError::Internal(format!(
3897                        "expected User CatalogItemId, got {other:?}"
3898                    )));
3899                }
3900            };
3901            self.user_id_pool.refill(start, end);
3902        } else {
3903            return Err(AdapterError::Internal(
3904                "catalog returned no user IDs".into(),
3905            ));
3906        }
3907        Ok(())
3908    }
3909
3910    /// Allocates a single user ID, refilling the pool from the catalog if needed.
3911    async fn allocate_user_id(&mut self) -> Result<(CatalogItemId, GlobalId), AdapterError> {
3912        if let Some(id) = self.user_id_pool.allocate() {
3913            return Ok((CatalogItemId::User(id), GlobalId::User(id)));
3914        }
3915        self.refill_user_id_pool(1).await?;
3916        let id = self.user_id_pool.allocate().expect("ID pool just refilled");
3917        Ok((CatalogItemId::User(id), GlobalId::User(id)))
3918    }
3919
3920    /// Allocates `count` user IDs, refilling the pool from the catalog if needed.
3921    async fn allocate_user_ids(
3922        &mut self,
3923        count: u64,
3924    ) -> Result<Vec<(CatalogItemId, GlobalId)>, AdapterError> {
3925        if self.user_id_pool.remaining() < count {
3926            self.refill_user_id_pool(count).await?;
3927        }
3928        let raw_ids = self
3929            .user_id_pool
3930            .allocate_many(count)
3931            .expect("pool has enough IDs after refill");
3932        Ok(raw_ids
3933            .into_iter()
3934            .map(|id| (CatalogItemId::User(id), GlobalId::User(id)))
3935            .collect())
3936    }
3937
3938    /// Obtain a reference to the coordinator's connection context.
3939    fn connection_context(&self) -> &ConnectionContext {
3940        self.controller.connection_context()
3941    }
3942
3943    /// Obtain a reference to the coordinator's secret reader, in an `Arc`.
3944    fn secrets_reader(&self) -> &Arc<dyn SecretsReader> {
3945        &self.connection_context().secrets_reader
3946    }
3947
3948    /// Publishes a notice message to all sessions.
3949    ///
3950    /// TODO(parkmycar): This code is dead, but is a nice parallel to [`Coordinator::broadcast_notice_tx`]
3951    /// so we keep it around.
3952    #[allow(dead_code)]
3953    pub(crate) fn broadcast_notice(&self, notice: AdapterNotice) {
3954        for meta in self.active_conns.values() {
3955            let _ = meta.notice_tx.send(notice.clone());
3956        }
3957    }
3958
3959    /// Returns a closure that will publish a notice to all sessions that were active at the time
3960    /// this method was called.
3961    pub(crate) fn broadcast_notice_tx(
3962        &self,
3963    ) -> Box<dyn FnOnce(AdapterNotice) -> () + Send + 'static> {
3964        let senders: Vec<_> = self
3965            .active_conns
3966            .values()
3967            .map(|meta| meta.notice_tx.clone())
3968            .collect();
3969        Box::new(move |notice| {
3970            for tx in senders {
3971                let _ = tx.send(notice.clone());
3972            }
3973        })
3974    }
3975
3976    pub(crate) fn active_conns(&self) -> &BTreeMap<ConnectionId, ConnMeta> {
3977        &self.active_conns
3978    }
3979
3980    #[instrument(level = "debug")]
3981    pub(crate) fn retire_execution(
3982        &mut self,
3983        reason: StatementEndedExecutionReason,
3984        ctx_extra: ExecuteContextExtra,
3985    ) {
3986        if let Some(uuid) = ctx_extra.retire() {
3987            self.end_statement_execution(uuid, reason);
3988        }
3989    }
3990
3991    /// Creates a new dataflow builder from the catalog and indexes in `self`.
3992    #[instrument(level = "debug")]
3993    pub fn dataflow_builder(&self, instance: ComputeInstanceId) -> DataflowBuilder<'_> {
3994        let compute = self
3995            .instance_snapshot(instance)
3996            .expect("compute instance does not exist");
3997        DataflowBuilder::new(self.catalog().state(), compute)
3998    }
3999
4000    /// Return a reference-less snapshot to the indicated compute instance.
4001    pub fn instance_snapshot(
4002        &self,
4003        id: ComputeInstanceId,
4004    ) -> Result<ComputeInstanceSnapshot, InstanceMissing> {
4005        ComputeInstanceSnapshot::new(&self.controller, id)
4006    }
4007
4008    /// Call into the compute controller to install a finalized dataflow, and
4009    /// initialize the read policies for its exported readable objects.
4010    ///
4011    /// # Panics
4012    ///
4013    /// Panics if dataflow creation fails.
4014    pub(crate) async fn ship_dataflow(
4015        &mut self,
4016        dataflow: DataflowDescription<Plan>,
4017        instance: ComputeInstanceId,
4018        target_replica: Option<ReplicaId>,
4019    ) {
4020        self.try_ship_dataflow(dataflow, instance, target_replica)
4021            .await
4022            .unwrap_or_terminate("dataflow creation cannot fail");
4023    }
4024
4025    /// Call into the compute controller to install a finalized dataflow, and
4026    /// initialize the read policies for its exported readable objects.
4027    pub(crate) async fn try_ship_dataflow(
4028        &mut self,
4029        dataflow: DataflowDescription<Plan>,
4030        instance: ComputeInstanceId,
4031        target_replica: Option<ReplicaId>,
4032    ) -> Result<(), DataflowCreationError> {
4033        // We must only install read policies for indexes, not for sinks.
4034        // Sinks are write-only compute collections that don't have read policies.
4035        let export_ids = dataflow.exported_index_ids().collect();
4036
4037        self.controller
4038            .compute
4039            .create_dataflow(instance, dataflow, target_replica)?;
4040
4041        self.initialize_compute_read_policies(export_ids, instance, CompactionWindow::Default)
4042            .await;
4043
4044        Ok(())
4045    }
4046
4047    /// Call into the compute controller to allow writes to the specified IDs
4048    /// from the specified instance. Calling this function multiple times and
4049    /// calling it on a read-only instance has no effect.
4050    pub(crate) fn allow_writes(&mut self, instance: ComputeInstanceId, id: GlobalId) {
4051        self.controller
4052            .compute
4053            .allow_writes(instance, id)
4054            .unwrap_or_terminate("allow_writes cannot fail");
4055    }
4056
4057    /// Like `ship_dataflow`, but also await on builtin table updates.
4058    pub(crate) async fn ship_dataflow_and_notice_builtin_table_updates(
4059        &mut self,
4060        dataflow: DataflowDescription<Plan>,
4061        instance: ComputeInstanceId,
4062        notice_builtin_updates_fut: Option<BuiltinTableAppendNotify>,
4063        target_replica: Option<ReplicaId>,
4064    ) {
4065        if let Some(notice_builtin_updates_fut) = notice_builtin_updates_fut {
4066            let ship_dataflow_fut = self.ship_dataflow(dataflow, instance, target_replica);
4067            let ((), ()) =
4068                futures::future::join(notice_builtin_updates_fut, ship_dataflow_fut).await;
4069        } else {
4070            self.ship_dataflow(dataflow, instance, target_replica).await;
4071        }
4072    }
4073
4074    /// Install a _watch set_ in the controller that is automatically associated with the given
4075    /// connection id. The watchset will be automatically cleared if the connection terminates
4076    /// before the watchset completes.
4077    pub fn install_compute_watch_set(
4078        &mut self,
4079        conn_id: ConnectionId,
4080        objects: BTreeSet<GlobalId>,
4081        t: Timestamp,
4082        state: WatchSetResponse,
4083    ) -> Result<(), CollectionLookupError> {
4084        let ws_id = self.controller.install_compute_watch_set(objects, t)?;
4085        self.connection_watch_sets
4086            .entry(conn_id.clone())
4087            .or_default()
4088            .insert(ws_id);
4089        self.installed_watch_sets.insert(ws_id, (conn_id, state));
4090        Ok(())
4091    }
4092
4093    /// Install a _watch set_ in the controller that is automatically associated with the given
4094    /// connection id. The watchset will be automatically cleared if the connection terminates
4095    /// before the watchset completes.
4096    pub fn install_storage_watch_set(
4097        &mut self,
4098        conn_id: ConnectionId,
4099        objects: BTreeSet<GlobalId>,
4100        t: Timestamp,
4101        state: WatchSetResponse,
4102    ) -> Result<(), CollectionMissing> {
4103        let ws_id = self.controller.install_storage_watch_set(objects, t)?;
4104        self.connection_watch_sets
4105            .entry(conn_id.clone())
4106            .or_default()
4107            .insert(ws_id);
4108        self.installed_watch_sets.insert(ws_id, (conn_id, state));
4109        Ok(())
4110    }
4111
4112    /// Cancels pending watchsets associated with the provided connection id.
4113    pub fn cancel_pending_watchsets(&mut self, conn_id: &ConnectionId) {
4114        if let Some(ws_ids) = self.connection_watch_sets.remove(conn_id) {
4115            for ws_id in ws_ids {
4116                self.installed_watch_sets.remove(&ws_id);
4117            }
4118        }
4119    }
4120
4121    /// Returns the state of the [`Coordinator`] formatted as JSON.
4122    ///
4123    /// The returned value is not guaranteed to be stable and may change at any point in time.
4124    pub async fn dump(&self) -> Result<serde_json::Value, anyhow::Error> {
4125        // Note: We purposefully use the `Debug` formatting for the value of all fields in the
4126        // returned object as a tradeoff between usability and stability. `serde_json` will fail
4127        // to serialize an object if the keys aren't strings, so `Debug` formatting the values
4128        // prevents a future unrelated change from silently breaking this method.
4129
4130        let global_timelines: BTreeMap<_, _> = self
4131            .global_timelines
4132            .iter()
4133            .map(|(timeline, state)| (timeline.to_string(), format!("{state:?}")))
4134            .collect();
4135        let active_conns: BTreeMap<_, _> = self
4136            .active_conns
4137            .iter()
4138            .map(|(id, meta)| (id.unhandled().to_string(), format!("{meta:?}")))
4139            .collect();
4140        let txn_read_holds: BTreeMap<_, _> = self
4141            .txn_read_holds
4142            .iter()
4143            .map(|(id, capability)| (id.unhandled().to_string(), format!("{capability:?}")))
4144            .collect();
4145        let pending_peeks: BTreeMap<_, _> = self
4146            .pending_peeks
4147            .iter()
4148            .map(|(id, peek)| (id.to_string(), format!("{peek:?}")))
4149            .collect();
4150        let client_pending_peeks: BTreeMap<_, _> = self
4151            .client_pending_peeks
4152            .iter()
4153            .map(|(id, peek)| {
4154                let peek: BTreeMap<_, _> = peek
4155                    .iter()
4156                    .map(|(uuid, storage_id)| (uuid.to_string(), storage_id))
4157                    .collect();
4158                (id.to_string(), peek)
4159            })
4160            .collect();
4161        let pending_linearize_read_txns: BTreeMap<_, _> = self
4162            .pending_linearize_read_txns
4163            .iter()
4164            .map(|(id, read_txn)| (id.unhandled().to_string(), format!("{read_txn:?}")))
4165            .collect();
4166
4167        Ok(serde_json::json!({
4168            "global_timelines": global_timelines,
4169            "active_conns": active_conns,
4170            "txn_read_holds": txn_read_holds,
4171            "pending_peeks": pending_peeks,
4172            "client_pending_peeks": client_pending_peeks,
4173            "pending_linearize_read_txns": pending_linearize_read_txns,
4174            "controller": self.controller.dump().await?,
4175        }))
4176    }
4177
4178    /// Prune all storage usage events from the [`MZ_STORAGE_USAGE_BY_SHARD`] table that are older
4179    /// than `retention_period`.
4180    ///
4181    /// This method will read the entire contents of [`MZ_STORAGE_USAGE_BY_SHARD`] into memory
4182    /// which can be expensive.
4183    ///
4184    /// DO NOT call this method outside of startup. The safety of reading at the current oracle read
4185    /// timestamp and then writing at whatever the current write timestamp is (instead of
4186    /// `read_ts + 1`) relies on the fact that there are no outstanding writes during startup.
4187    ///
4188    /// Group commit, which this method uses to write the retractions, has builtin fencing, and we
4189    /// never commit retractions to [`MZ_STORAGE_USAGE_BY_SHARD`] outside of this method, which is
4190    /// only called once during startup. So we don't have to worry about double/invalid retractions.
4191    async fn prune_storage_usage_events_on_startup(&self, retention_period: Duration) {
4192        let item_id = self
4193            .catalog()
4194            .resolve_builtin_table(&MZ_STORAGE_USAGE_BY_SHARD);
4195        let global_id = self.catalog.get_entry(&item_id).latest_global_id();
4196        let read_ts = self.get_local_read_ts().await;
4197        let current_contents_fut = self
4198            .controller
4199            .storage_collections
4200            .snapshot(global_id, read_ts);
4201        let internal_cmd_tx = self.internal_cmd_tx.clone();
4202        spawn(|| "storage_usage_prune", async move {
4203            let mut current_contents = current_contents_fut
4204                .await
4205                .unwrap_or_terminate("cannot fail to fetch snapshot");
4206            differential_dataflow::consolidation::consolidate(&mut current_contents);
4207
4208            let cutoff_ts = u128::from(read_ts).saturating_sub(retention_period.as_millis());
4209            let mut expired = Vec::new();
4210            for (row, diff) in current_contents {
4211                assert_eq!(
4212                    diff, 1,
4213                    "consolidated contents should not contain retractions: ({row:#?}, {diff:#?})"
4214                );
4215                // This logic relies on the definition of `mz_storage_usage_by_shard` not changing.
4216                let collection_timestamp = row
4217                    .unpack()
4218                    .get(3)
4219                    .expect("definition of mz_storage_by_shard changed")
4220                    .unwrap_timestamptz();
4221                let collection_timestamp = collection_timestamp.timestamp_millis();
4222                let collection_timestamp: u128 = collection_timestamp
4223                    .try_into()
4224                    .expect("all collections happen after Jan 1 1970");
4225                if collection_timestamp < cutoff_ts {
4226                    debug!("pruning storage event {row:?}");
4227                    let builtin_update = BuiltinTableUpdate::row(item_id, row, Diff::MINUS_ONE);
4228                    expired.push(builtin_update);
4229                }
4230            }
4231
4232            // main thread has shut down.
4233            let _ = internal_cmd_tx.send(Message::StorageUsagePrune(expired));
4234        });
4235    }
4236
4237    fn current_credit_consumption_rate(&self) -> Numeric {
4238        self.catalog()
4239            .user_cluster_replicas()
4240            .filter_map(|replica| match &replica.config.location {
4241                ReplicaLocation::Managed(location) => Some(location.size_for_billing()),
4242                ReplicaLocation::Unmanaged(_) => None,
4243            })
4244            .map(|size| {
4245                self.catalog()
4246                    .cluster_replica_sizes()
4247                    .0
4248                    .get(size)
4249                    .expect("location size is validated against the cluster replica sizes")
4250                    .credits_per_hour
4251            })
4252            .sum()
4253    }
4254}
4255
4256#[cfg(test)]
4257impl Coordinator {
4258    #[allow(dead_code)]
4259    async fn verify_ship_dataflow_no_error(&mut self, dataflow: DataflowDescription<Plan>) {
4260        // `ship_dataflow_new` is not allowed to have a `Result` return because this function is
4261        // called after `catalog_transact`, after which no errors are allowed. This test exists to
4262        // prevent us from incorrectly teaching those functions how to return errors (which has
4263        // happened twice and is the motivation for this test).
4264
4265        // An arbitrary compute instance ID to satisfy the function calls below. Note that
4266        // this only works because this function will never run.
4267        let compute_instance = ComputeInstanceId::user(1).expect("1 is a valid ID");
4268
4269        let _: () = self.ship_dataflow(dataflow, compute_instance, None).await;
4270    }
4271}
4272
4273/// Contains information about the last message the [`Coordinator`] processed.
4274struct LastMessage {
4275    kind: &'static str,
4276    stmt: Option<Arc<Statement<Raw>>>,
4277}
4278
4279impl LastMessage {
4280    /// Returns a redacted version of the statement that is safe for logs.
4281    fn stmt_to_string(&self) -> Cow<'static, str> {
4282        self.stmt
4283            .as_ref()
4284            .map(|stmt| stmt.to_ast_string_redacted().into())
4285            .unwrap_or(Cow::Borrowed("<none>"))
4286    }
4287}
4288
4289impl fmt::Debug for LastMessage {
4290    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4291        f.debug_struct("LastMessage")
4292            .field("kind", &self.kind)
4293            .field("stmt", &self.stmt_to_string())
4294            .finish()
4295    }
4296}
4297
4298impl Drop for LastMessage {
4299    fn drop(&mut self) {
4300        // Only print the last message if we're currently panicking, otherwise we'd spam our logs.
4301        if std::thread::panicking() {
4302            // If we're panicking theres no guarantee `tracing` still works, so print to stderr.
4303            eprintln!("Coordinator panicking, dumping last message\n{self:?}",);
4304        }
4305    }
4306}
4307
4308/// Serves the coordinator based on the provided configuration.
4309///
4310/// For a high-level description of the coordinator, see the [crate
4311/// documentation](crate).
4312///
4313/// Returns a handle to the coordinator and a client to communicate with the
4314/// coordinator.
4315///
4316/// BOXED FUTURE: As of Nov 2023 the returned Future from this function was 42KB. This would
4317/// get stored on the stack which is bad for runtime performance, and blow up our stack usage.
4318/// Because of that we purposefully move this Future onto the heap (i.e. Box it).
4319pub fn serve(
4320    Config {
4321        controller_config,
4322        controller_envd_epoch,
4323        mut storage,
4324        audit_logs_iterator,
4325        timestamp_oracle_url,
4326        unsafe_mode,
4327        all_features,
4328        build_info,
4329        environment_id,
4330        metrics_registry,
4331        now,
4332        secrets_controller,
4333        cloud_resource_controller,
4334        cluster_replica_sizes,
4335        builtin_system_cluster_config,
4336        builtin_catalog_server_cluster_config,
4337        builtin_probe_cluster_config,
4338        builtin_support_cluster_config,
4339        builtin_analytics_cluster_config,
4340        system_parameter_defaults,
4341        availability_zones,
4342        storage_usage_client,
4343        storage_usage_collection_interval,
4344        storage_usage_retention_period,
4345        segment_client,
4346        egress_addresses,
4347        aws_account_id,
4348        aws_privatelink_availability_zones,
4349        connection_context,
4350        connection_limit_callback,
4351        remote_system_parameters,
4352        webhook_concurrency_limit,
4353        http_host_name,
4354        tracing_handle,
4355        read_only_controllers,
4356        caught_up_trigger: clusters_caught_up_trigger,
4357        helm_chart_version,
4358        license_key,
4359        external_login_password_mz_system,
4360        force_builtin_schema_migration,
4361    }: Config,
4362) -> BoxFuture<'static, Result<(Handle, Client), AdapterError>> {
4363    async move {
4364        let coord_start = Instant::now();
4365        info!("startup: coordinator init: beginning");
4366        info!("startup: coordinator init: preamble beginning");
4367
4368        // Initializing the builtins can be an expensive process and consume a lot of memory. We
4369        // forcibly initialize it early while the stack is relatively empty to avoid stack
4370        // overflows later.
4371        let _builtins = LazyLock::force(&BUILTINS_STATIC);
4372
4373        let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
4374        let (internal_cmd_tx, internal_cmd_rx) = mpsc::unbounded_channel();
4375        let (strict_serializable_reads_tx, strict_serializable_reads_rx) =
4376            mpsc::unbounded_channel();
4377
4378        // Validate and process availability zones.
4379        if !availability_zones.iter().all_unique() {
4380            coord_bail!("availability zones must be unique");
4381        }
4382
4383        let aws_principal_context = match (
4384            aws_account_id,
4385            connection_context.aws_external_id_prefix.clone(),
4386        ) {
4387            (Some(aws_account_id), Some(aws_external_id_prefix)) => Some(AwsPrincipalContext {
4388                aws_account_id,
4389                aws_external_id_prefix,
4390            }),
4391            _ => None,
4392        };
4393
4394        let aws_privatelink_availability_zones = aws_privatelink_availability_zones
4395            .map(|azs_vec| BTreeSet::from_iter(azs_vec.iter().cloned()));
4396
4397        info!(
4398            "startup: coordinator init: preamble complete in {:?}",
4399            coord_start.elapsed()
4400        );
4401        let oracle_init_start = Instant::now();
4402        info!("startup: coordinator init: timestamp oracle init beginning");
4403
4404        let timestamp_oracle_config = timestamp_oracle_url
4405            .map(|url| TimestampOracleConfig::from_url(&url, &metrics_registry))
4406            .transpose()?;
4407        let mut initial_timestamps =
4408            get_initial_oracle_timestamps(&timestamp_oracle_config).await?;
4409
4410        // Insert an entry for the `EpochMilliseconds` timeline if one doesn't exist,
4411        // which will ensure that the timeline is initialized since it's required
4412        // by the system.
4413        initial_timestamps
4414            .entry(Timeline::EpochMilliseconds)
4415            .or_insert_with(mz_repr::Timestamp::minimum);
4416        let mut timestamp_oracles = BTreeMap::new();
4417        for (timeline, initial_timestamp) in initial_timestamps {
4418            Coordinator::ensure_timeline_state_with_initial_time(
4419                &timeline,
4420                initial_timestamp,
4421                now.clone(),
4422                timestamp_oracle_config.clone(),
4423                &mut timestamp_oracles,
4424                read_only_controllers,
4425            )
4426            .await;
4427        }
4428
4429        // Opening the durable catalog uses one or more timestamps without communicating with
4430        // the timestamp oracle. Here we make sure to apply the catalog upper with the timestamp
4431        // oracle to linearize future operations with opening the catalog.
4432        let catalog_upper = storage.current_upper().await;
4433        // Choose a time at which to boot. This is used, for example, to prune
4434        // old storage usage data or migrate audit log entries.
4435        //
4436        // This time is usually the current system time, but with protection
4437        // against backwards time jumps, even across restarts.
4438        let epoch_millis_oracle = &timestamp_oracles
4439            .get(&Timeline::EpochMilliseconds)
4440            .expect("inserted above")
4441            .oracle;
4442
4443        let mut boot_ts = if read_only_controllers {
4444            let read_ts = epoch_millis_oracle.read_ts().await;
4445            std::cmp::max(read_ts, catalog_upper)
4446        } else {
4447            // Getting/applying a write timestamp bumps the write timestamp in the
4448            // oracle, which we're not allowed in read-only mode.
4449            epoch_millis_oracle.apply_write(catalog_upper).await;
4450            epoch_millis_oracle.write_ts().await.timestamp
4451        };
4452
4453        info!(
4454            "startup: coordinator init: timestamp oracle init complete in {:?}",
4455            oracle_init_start.elapsed()
4456        );
4457
4458        let catalog_open_start = Instant::now();
4459        info!("startup: coordinator init: catalog open beginning");
4460        let persist_client = controller_config
4461            .persist_clients
4462            .open(controller_config.persist_location.clone())
4463            .await
4464            .context("opening persist client")?;
4465        let builtin_item_migration_config =
4466            BuiltinItemMigrationConfig {
4467                persist_client: persist_client.clone(),
4468                read_only: read_only_controllers,
4469                force_migration: force_builtin_schema_migration,
4470            }
4471        ;
4472        let OpenCatalogResult {
4473            mut catalog,
4474            migrated_storage_collections_0dt,
4475            new_builtin_collections,
4476            builtin_table_updates,
4477            cached_global_exprs,
4478            uncached_local_exprs,
4479        } = Catalog::open(mz_catalog::config::Config {
4480            storage,
4481            metrics_registry: &metrics_registry,
4482            state: mz_catalog::config::StateConfig {
4483                unsafe_mode,
4484                all_features,
4485                build_info,
4486                environment_id: environment_id.clone(),
4487                read_only: read_only_controllers,
4488                now: now.clone(),
4489                boot_ts: boot_ts.clone(),
4490                skip_migrations: false,
4491                cluster_replica_sizes,
4492                builtin_system_cluster_config,
4493                builtin_catalog_server_cluster_config,
4494                builtin_probe_cluster_config,
4495                builtin_support_cluster_config,
4496                builtin_analytics_cluster_config,
4497                system_parameter_defaults,
4498                remote_system_parameters,
4499                availability_zones,
4500                egress_addresses,
4501                aws_principal_context,
4502                aws_privatelink_availability_zones,
4503                connection_context,
4504                http_host_name,
4505                builtin_item_migration_config,
4506                persist_client: persist_client.clone(),
4507                enable_expression_cache_override: None,
4508                helm_chart_version,
4509                external_login_password_mz_system,
4510                license_key: license_key.clone(),
4511            },
4512        })
4513        .await?;
4514
4515        // Opening the catalog uses one or more timestamps, so push the boot timestamp up to the
4516        // current catalog upper.
4517        let catalog_upper = catalog.current_upper().await;
4518        boot_ts = std::cmp::max(boot_ts, catalog_upper);
4519
4520        if !read_only_controllers {
4521            epoch_millis_oracle.apply_write(boot_ts).await;
4522        }
4523
4524        info!(
4525            "startup: coordinator init: catalog open complete in {:?}",
4526            catalog_open_start.elapsed()
4527        );
4528
4529        let coord_thread_start = Instant::now();
4530        info!("startup: coordinator init: coordinator thread start beginning");
4531
4532        let session_id = catalog.config().session_id;
4533        let start_instant = catalog.config().start_instant;
4534
4535        // In order for the coordinator to support Rc and Refcell types, it cannot be
4536        // sent across threads. Spawn it in a thread and have this parent thread wait
4537        // for bootstrap completion before proceeding.
4538        let (bootstrap_tx, bootstrap_rx) = oneshot::channel();
4539        let handle = TokioHandle::current();
4540
4541        let metrics = Metrics::register_into(&metrics_registry);
4542        let metrics_clone = metrics.clone();
4543        let optimizer_metrics = OptimizerMetrics::register_into(
4544            &metrics_registry,
4545            catalog.system_config().optimizer_e2e_latency_warning_threshold(),
4546        );
4547        let segment_client_clone = segment_client.clone();
4548        let coord_now = now.clone();
4549        let advance_timelines_interval =
4550            tokio::time::interval(catalog.system_config().default_timestamp_interval());
4551        let mut check_scheduling_policies_interval = tokio::time::interval(
4552            catalog
4553                .system_config()
4554                .cluster_check_scheduling_policies_interval(),
4555        );
4556        check_scheduling_policies_interval.set_missed_tick_behavior(MissedTickBehavior::Delay);
4557
4558        let clusters_caught_up_check_interval = if read_only_controllers {
4559            let dyncfgs = catalog.system_config().dyncfgs();
4560            let interval = WITH_0DT_DEPLOYMENT_CAUGHT_UP_CHECK_INTERVAL.get(dyncfgs);
4561
4562            let mut interval = tokio::time::interval(interval);
4563            interval.set_missed_tick_behavior(MissedTickBehavior::Skip);
4564            interval
4565        } else {
4566            // When not in read-only mode, we don't do hydration checks. But we
4567            // still have to provide _some_ interval. This is large enough that
4568            // it doesn't matter.
4569            //
4570            // TODO(aljoscha): We cannot use Duration::MAX right now because of
4571            // https://github.com/tokio-rs/tokio/issues/6634. Use that once it's
4572            // fixed for good.
4573            let mut interval = tokio::time::interval(Duration::from_secs(60 * 60));
4574            interval.set_missed_tick_behavior(MissedTickBehavior::Skip);
4575            interval
4576        };
4577
4578        let clusters_caught_up_check =
4579            clusters_caught_up_trigger.map(|trigger| {
4580                let mut exclude_collections: BTreeSet<GlobalId> =
4581                    new_builtin_collections.into_iter().collect();
4582
4583                // Migrated MVs can't make progress in read-only mode. Exclude them and all their
4584                // transitive dependents.
4585                //
4586                // TODO: Consider sending `allow_writes` for the dataflows of migrated MVs, which
4587                //       would allow them to make progress even in read-only mode. This doesn't
4588                //       work for MVs based on `mz_catalog_raw`, if the leader's version is less
4589                //       than v26.17, since before that version the catalog shard's frontier wasn't
4590                //       kept up-to-date with the current time. So this workaround has to remain in
4591                //       place upgrades from a version less than v26.17 are no longer supported.
4592                let mut todo: Vec<_> = migrated_storage_collections_0dt
4593                    .iter()
4594                    .filter(|id| {
4595                        catalog.state().get_entry(id).is_materialized_view()
4596                    })
4597                    .copied()
4598                    .collect();
4599                while let Some(item_id) = todo.pop() {
4600                    let entry = catalog.state().get_entry(&item_id);
4601                    exclude_collections.extend(entry.global_ids());
4602                    todo.extend_from_slice(entry.used_by());
4603                }
4604
4605                CaughtUpCheckContext {
4606                    trigger,
4607                    exclude_collections,
4608                }
4609            });
4610
4611        if let Some(TimestampOracleConfig::Postgres(pg_config)) =
4612            timestamp_oracle_config.as_ref()
4613        {
4614            // Apply settings from system vars as early as possible because some
4615            // of them are locked in right when an oracle is first opened!
4616            let pg_timestamp_oracle_params =
4617                flags::timestamp_oracle_config(catalog.system_config());
4618            pg_timestamp_oracle_params.apply(pg_config);
4619        }
4620
4621        // Register a callback so whenever the MAX_CONNECTIONS or SUPERUSER_RESERVED_CONNECTIONS
4622        // system variables change, we update our connection limits.
4623        let connection_limit_callback: Arc<dyn Fn(&SystemVars) + Send + Sync> =
4624            Arc::new(move |system_vars: &SystemVars| {
4625                let limit: u64 = system_vars.max_connections().cast_into();
4626                let superuser_reserved: u64 =
4627                    system_vars.superuser_reserved_connections().cast_into();
4628
4629                // If superuser_reserved > max_connections, prefer max_connections.
4630                //
4631                // In this scenario all normal users would be locked out because all connections
4632                // would be reserved for superusers so complain if this is the case.
4633                let superuser_reserved = if superuser_reserved >= limit {
4634                    tracing::warn!(
4635                        "superuser_reserved ({superuser_reserved}) is greater than max connections ({limit})!"
4636                    );
4637                    limit
4638                } else {
4639                    superuser_reserved
4640                };
4641
4642                (connection_limit_callback)(limit, superuser_reserved);
4643            });
4644        catalog.system_config_mut().register_callback(
4645            &mz_sql::session::vars::MAX_CONNECTIONS,
4646            Arc::clone(&connection_limit_callback),
4647        );
4648        catalog.system_config_mut().register_callback(
4649            &mz_sql::session::vars::SUPERUSER_RESERVED_CONNECTIONS,
4650            connection_limit_callback,
4651        );
4652
4653        let (group_commit_tx, group_commit_rx) = appends::notifier();
4654
4655        let parent_span = tracing::Span::current();
4656        let thread = thread::Builder::new()
4657            // The Coordinator thread tends to keep a lot of data on its stack. To
4658            // prevent a stack overflow we allocate a stack three times as big as the default
4659            // stack.
4660            .stack_size(3 * stack::STACK_SIZE)
4661            .name("coordinator".to_string())
4662            .spawn(move || {
4663                let span = info_span!(parent: parent_span, "coord::coordinator").entered();
4664
4665                let controller = handle
4666                    .block_on({
4667                        catalog.initialize_controller(
4668                            controller_config,
4669                            controller_envd_epoch,
4670                            read_only_controllers,
4671                        )
4672                    })
4673                    .unwrap_or_terminate("failed to initialize storage_controller");
4674                // Initializing the controller uses one or more timestamps, so push the boot timestamp up to the
4675                // current catalog upper.
4676                let catalog_upper = handle.block_on(catalog.current_upper());
4677                boot_ts = std::cmp::max(boot_ts, catalog_upper);
4678                if !read_only_controllers {
4679                    let epoch_millis_oracle = &timestamp_oracles
4680                        .get(&Timeline::EpochMilliseconds)
4681                        .expect("inserted above")
4682                        .oracle;
4683                    handle.block_on(epoch_millis_oracle.apply_write(boot_ts));
4684                }
4685
4686                let catalog = Arc::new(catalog);
4687
4688                let caching_secrets_reader = CachingSecretsReader::new(secrets_controller.reader());
4689                let mut coord = Coordinator {
4690                    controller,
4691                    catalog,
4692                    internal_cmd_tx,
4693                    group_commit_tx,
4694                    strict_serializable_reads_tx,
4695                    global_timelines: timestamp_oracles,
4696                    transient_id_gen: Arc::new(TransientIdGen::new()),
4697                    active_conns: BTreeMap::new(),
4698                    txn_read_holds: Default::default(),
4699                    pending_peeks: BTreeMap::new(),
4700                    client_pending_peeks: BTreeMap::new(),
4701                    pending_linearize_read_txns: BTreeMap::new(),
4702                    serialized_ddl: LockedVecDeque::new(),
4703                    active_compute_sinks: BTreeMap::new(),
4704                    active_webhooks: BTreeMap::new(),
4705                    active_copies: BTreeMap::new(),
4706                    staged_cancellation: BTreeMap::new(),
4707                    introspection_subscribes: BTreeMap::new(),
4708                    write_locks: BTreeMap::new(),
4709                    deferred_write_ops: BTreeMap::new(),
4710                    pending_writes: Vec::new(),
4711                    advance_timelines_interval,
4712                    secrets_controller,
4713                    caching_secrets_reader,
4714                    cloud_resource_controller,
4715                    storage_usage_client,
4716                    storage_usage_collection_interval,
4717                    segment_client,
4718                    metrics,
4719                    optimizer_metrics,
4720                    tracing_handle,
4721                    statement_logging: StatementLogging::new(coord_now.clone()),
4722                    webhook_concurrency_limit,
4723                    timestamp_oracle_config,
4724                    check_cluster_scheduling_policies_interval: check_scheduling_policies_interval,
4725                    cluster_scheduling_decisions: BTreeMap::new(),
4726                    caught_up_check_interval: clusters_caught_up_check_interval,
4727                    caught_up_check: clusters_caught_up_check,
4728                    installed_watch_sets: BTreeMap::new(),
4729                    connection_watch_sets: BTreeMap::new(),
4730                    cluster_replica_statuses: ClusterReplicaStatuses::new(),
4731                    read_only_controllers,
4732                    buffered_builtin_table_updates: Some(Vec::new()),
4733                    license_key,
4734                    user_id_pool: IdPool::empty(),
4735                    persist_client,
4736                };
4737                let bootstrap = handle.block_on(async {
4738                    coord
4739                        .bootstrap(
4740                            boot_ts,
4741                            migrated_storage_collections_0dt,
4742                            builtin_table_updates,
4743                            cached_global_exprs,
4744                            uncached_local_exprs,
4745                            audit_logs_iterator,
4746                        )
4747                        .await?;
4748                    coord
4749                        .controller
4750                        .remove_orphaned_replicas(
4751                            coord.catalog().get_next_user_replica_id().await?,
4752                            coord.catalog().get_next_system_replica_id().await?,
4753                        )
4754                        .await
4755                        .map_err(AdapterError::Orchestrator)?;
4756
4757                    if let Some(retention_period) = storage_usage_retention_period {
4758                        coord
4759                            .prune_storage_usage_events_on_startup(retention_period)
4760                            .await;
4761                    }
4762
4763                    Ok(())
4764                });
4765                let ok = bootstrap.is_ok();
4766                drop(span);
4767                bootstrap_tx
4768                    .send(bootstrap)
4769                    .expect("bootstrap_rx is not dropped until it receives this message");
4770                if ok {
4771                    handle.block_on(coord.serve(
4772                        internal_cmd_rx,
4773                        strict_serializable_reads_rx,
4774                        cmd_rx,
4775                        group_commit_rx,
4776                    ));
4777                }
4778            })
4779            .expect("failed to create coordinator thread");
4780        match bootstrap_rx
4781            .await
4782            .expect("bootstrap_tx always sends a message or panics/halts")
4783        {
4784            Ok(()) => {
4785                info!(
4786                    "startup: coordinator init: coordinator thread start complete in {:?}",
4787                    coord_thread_start.elapsed()
4788                );
4789                info!(
4790                    "startup: coordinator init: complete in {:?}",
4791                    coord_start.elapsed()
4792                );
4793                let handle = Handle {
4794                    session_id,
4795                    start_instant,
4796                    _thread: thread.join_on_drop(),
4797                };
4798                let client = Client::new(
4799                    build_info,
4800                    cmd_tx,
4801                    metrics_clone,
4802                    now,
4803                    environment_id,
4804                    segment_client_clone,
4805                );
4806                Ok((handle, client))
4807            }
4808            Err(e) => Err(e),
4809        }
4810    }
4811    .boxed()
4812}
4813
4814// Determines and returns the highest timestamp for each timeline, for all known
4815// timestamp oracle implementations.
4816//
4817// Initially, we did this so that we can switch between implementations of
4818// timestamp oracle, but now we also do this to determine a monotonic boot
4819// timestamp, a timestamp that does not regress across reboots.
4820//
4821// This mostly works, but there can be linearizability violations, because there
4822// is no central moment where we do distributed coordination for all oracle
4823// types. Working around this seems prohibitively hard, maybe even impossible so
4824// we have to live with this window of potential violations during the upgrade
4825// window (which is the only point where we should switch oracle
4826// implementations).
4827async fn get_initial_oracle_timestamps(
4828    timestamp_oracle_config: &Option<TimestampOracleConfig>,
4829) -> Result<BTreeMap<Timeline, Timestamp>, AdapterError> {
4830    let mut initial_timestamps = BTreeMap::new();
4831
4832    if let Some(config) = timestamp_oracle_config {
4833        let oracle_timestamps = config.get_all_timelines().await?;
4834
4835        let debug_msg = || {
4836            oracle_timestamps
4837                .iter()
4838                .map(|(timeline, ts)| format!("{:?} -> {}", timeline, ts))
4839                .join(", ")
4840        };
4841        info!(
4842            "current timestamps from the timestamp oracle: {}",
4843            debug_msg()
4844        );
4845
4846        for (timeline, ts) in oracle_timestamps {
4847            let entry = initial_timestamps
4848                .entry(Timeline::from_str(&timeline).expect("could not parse timeline"));
4849
4850            entry
4851                .and_modify(|current_ts| *current_ts = std::cmp::max(*current_ts, ts))
4852                .or_insert(ts);
4853        }
4854    } else {
4855        info!("no timestamp oracle configured!");
4856    };
4857
4858    let debug_msg = || {
4859        initial_timestamps
4860            .iter()
4861            .map(|(timeline, ts)| format!("{:?}: {}", timeline, ts))
4862            .join(", ")
4863    };
4864    info!("initial oracle timestamps: {}", debug_msg());
4865
4866    Ok(initial_timestamps)
4867}
4868
4869#[instrument]
4870pub async fn load_remote_system_parameters(
4871    storage: &mut Box<dyn OpenableDurableCatalogState>,
4872    system_parameter_sync_config: Option<SystemParameterSyncConfig>,
4873    system_parameter_sync_timeout: Duration,
4874) -> Result<Option<BTreeMap<String, String>>, AdapterError> {
4875    if let Some(system_parameter_sync_config) = system_parameter_sync_config {
4876        tracing::info!("parameter sync on boot: start sync");
4877
4878        // We intentionally block initial startup, potentially forever,
4879        // on initializing LaunchDarkly. This may seem scary, but the
4880        // alternative is even scarier. Over time, we expect that the
4881        // compiled-in default values for the system parameters will
4882        // drift substantially from the defaults configured in
4883        // LaunchDarkly, to the point that starting an environment
4884        // without loading the latest values from LaunchDarkly will
4885        // result in running an untested configuration.
4886        //
4887        // Note this only applies during initial startup. Restarting
4888        // after we've synced once only blocks for a maximum of
4889        // `FRONTEND_SYNC_TIMEOUT` on LaunchDarkly, as it seems
4890        // reasonable to assume that the last-synced configuration was
4891        // valid enough.
4892        //
4893        // This philosophy appears to provide a good balance between not
4894        // running untested configurations in production while also not
4895        // making LaunchDarkly a "tier 1" dependency for existing
4896        // environments.
4897        //
4898        // If this proves to be an issue, we could seek to address the
4899        // configuration drift in a different way--for example, by
4900        // writing a script that runs in CI nightly and checks for
4901        // deviation between the compiled Rust code and LaunchDarkly.
4902        //
4903        // If it is absolutely necessary to bring up a new environment
4904        // while LaunchDarkly is down, the following manual mitigation
4905        // can be performed:
4906        //
4907        //    1. Edit the environmentd startup parameters to omit the
4908        //       LaunchDarkly configuration.
4909        //    2. Boot environmentd.
4910        //    3. Use the catalog-debug tool to run `edit config "{\"key\":\"system_config_synced\"}" "{\"value\": 1}"`.
4911        //    4. Adjust any other parameters as necessary to avoid
4912        //       running a nonstandard configuration in production.
4913        //    5. Edit the environmentd startup parameters to restore the
4914        //       LaunchDarkly configuration, for when LaunchDarkly comes
4915        //       back online.
4916        //    6. Reboot environmentd.
4917        let mut params = SynchronizedParameters::new(SystemVars::default());
4918        let frontend_sync = async {
4919            let frontend = SystemParameterFrontend::from(&system_parameter_sync_config).await?;
4920            frontend.pull(&mut params);
4921            let ops = params
4922                .modified()
4923                .into_iter()
4924                .map(|param| {
4925                    let name = param.name;
4926                    let value = param.value;
4927                    tracing::info!(name, value, initial = true, "sync parameter");
4928                    (name, value)
4929                })
4930                .collect();
4931            tracing::info!("parameter sync on boot: end sync");
4932            Ok(Some(ops))
4933        };
4934        if !storage.has_system_config_synced_once().await? {
4935            frontend_sync.await
4936        } else {
4937            match mz_ore::future::timeout(system_parameter_sync_timeout, frontend_sync).await {
4938                Ok(ops) => Ok(ops),
4939                Err(TimeoutError::Inner(e)) => Err(e),
4940                Err(TimeoutError::DeadlineElapsed) => {
4941                    tracing::info!("parameter sync on boot: sync has timed out");
4942                    Ok(None)
4943                }
4944            }
4945        }
4946    } else {
4947        Ok(None)
4948    }
4949}
4950
4951#[derive(Debug)]
4952pub enum WatchSetResponse {
4953    StatementDependenciesReady(StatementLoggingId, StatementLifecycleEvent),
4954    AlterSinkReady(AlterSinkReadyContext),
4955    AlterMaterializedViewReady(AlterMaterializedViewReadyContext),
4956}
4957
4958#[derive(Debug)]
4959pub struct AlterSinkReadyContext {
4960    ctx: Option<ExecuteContext>,
4961    otel_ctx: OpenTelemetryContext,
4962    plan: AlterSinkPlan,
4963    plan_validity: PlanValidity,
4964    read_hold: ReadHolds,
4965}
4966
4967impl AlterSinkReadyContext {
4968    fn ctx(&mut self) -> &mut ExecuteContext {
4969        self.ctx.as_mut().expect("only cleared on drop")
4970    }
4971
4972    fn retire(mut self, result: Result<ExecuteResponse, AdapterError>) {
4973        self.ctx
4974            .take()
4975            .expect("only cleared on drop")
4976            .retire(result);
4977    }
4978}
4979
4980impl Drop for AlterSinkReadyContext {
4981    fn drop(&mut self) {
4982        if let Some(ctx) = self.ctx.take() {
4983            ctx.retire(Err(AdapterError::Canceled));
4984        }
4985    }
4986}
4987
4988#[derive(Debug)]
4989pub struct AlterMaterializedViewReadyContext {
4990    ctx: Option<ExecuteContext>,
4991    otel_ctx: OpenTelemetryContext,
4992    plan: plan::AlterMaterializedViewApplyReplacementPlan,
4993    plan_validity: PlanValidity,
4994}
4995
4996impl AlterMaterializedViewReadyContext {
4997    fn ctx(&mut self) -> &mut ExecuteContext {
4998        self.ctx.as_mut().expect("only cleared on drop")
4999    }
5000
5001    fn retire(mut self, result: Result<ExecuteResponse, AdapterError>) {
5002        self.ctx
5003            .take()
5004            .expect("only cleared on drop")
5005            .retire(result);
5006    }
5007}
5008
5009impl Drop for AlterMaterializedViewReadyContext {
5010    fn drop(&mut self) {
5011        if let Some(ctx) = self.ctx.take() {
5012            ctx.retire(Err(AdapterError::Canceled));
5013        }
5014    }
5015}
5016
5017/// A struct for tracking the ownership of a lock and a VecDeque to store to-be-done work after the
5018/// lock is freed.
5019#[derive(Debug)]
5020struct LockedVecDeque<T> {
5021    items: VecDeque<T>,
5022    lock: Arc<tokio::sync::Mutex<()>>,
5023}
5024
5025impl<T> LockedVecDeque<T> {
5026    pub fn new() -> Self {
5027        Self {
5028            items: VecDeque::new(),
5029            lock: Arc::new(tokio::sync::Mutex::new(())),
5030        }
5031    }
5032
5033    pub fn try_lock_owned(&self) -> Result<OwnedMutexGuard<()>, tokio::sync::TryLockError> {
5034        Arc::clone(&self.lock).try_lock_owned()
5035    }
5036
5037    pub fn is_empty(&self) -> bool {
5038        self.items.is_empty()
5039    }
5040
5041    pub fn push_back(&mut self, value: T) {
5042        self.items.push_back(value)
5043    }
5044
5045    pub fn pop_front(&mut self) -> Option<T> {
5046        self.items.pop_front()
5047    }
5048
5049    pub fn remove(&mut self, index: usize) -> Option<T> {
5050        self.items.remove(index)
5051    }
5052
5053    pub fn iter(&self) -> std::collections::vec_deque::Iter<'_, T> {
5054        self.items.iter()
5055    }
5056}
5057
5058#[derive(Debug)]
5059struct DeferredPlanStatement {
5060    ctx: ExecuteContext,
5061    ps: PlanStatement,
5062}
5063
5064#[derive(Debug)]
5065enum PlanStatement {
5066    Statement {
5067        stmt: Arc<Statement<Raw>>,
5068        params: Params,
5069    },
5070    Plan {
5071        plan: mz_sql::plan::Plan,
5072        resolved_ids: ResolvedIds,
5073    },
5074}
5075
5076#[derive(Debug, Error)]
5077pub enum NetworkPolicyError {
5078    #[error("Access denied for address {0}")]
5079    AddressDenied(IpAddr),
5080    #[error("Access denied missing IP address")]
5081    MissingIp,
5082}
5083
5084pub(crate) fn validate_ip_with_policy_rules(
5085    ip: &IpAddr,
5086    rules: &Vec<NetworkPolicyRule>,
5087) -> Result<(), NetworkPolicyError> {
5088    // At the moment we're not handling action or direction
5089    // as those are only able to be "allow" and "ingress" respectively
5090    if rules.iter().any(|r| r.address.0.contains(ip)) {
5091        Ok(())
5092    } else {
5093        Err(NetworkPolicyError::AddressDenied(ip.clone()))
5094    }
5095}
5096
5097pub(crate) fn infer_sql_type_for_catalog(
5098    hir_expr: &HirRelationExpr,
5099    mir_expr: &MirRelationExpr,
5100) -> SqlRelationType {
5101    let mut typ = hir_expr.top_level_typ();
5102    typ.backport_nullability_and_keys(&mir_expr.typ());
5103    typ
5104}
5105
5106#[cfg(test)]
5107mod id_pool_tests {
5108    use super::IdPool;
5109
5110    #[mz_ore::test]
5111    fn test_empty_pool() {
5112        let mut pool = IdPool::empty();
5113        assert_eq!(pool.remaining(), 0);
5114        assert_eq!(pool.allocate(), None);
5115        assert_eq!(pool.allocate_many(1), None);
5116    }
5117
5118    #[mz_ore::test]
5119    fn test_allocate_single() {
5120        let mut pool = IdPool::empty();
5121        pool.refill(10, 13);
5122        assert_eq!(pool.remaining(), 3);
5123        assert_eq!(pool.allocate(), Some(10));
5124        assert_eq!(pool.allocate(), Some(11));
5125        assert_eq!(pool.allocate(), Some(12));
5126        assert_eq!(pool.remaining(), 0);
5127        assert_eq!(pool.allocate(), None);
5128    }
5129
5130    #[mz_ore::test]
5131    fn test_allocate_many() {
5132        let mut pool = IdPool::empty();
5133        pool.refill(100, 105);
5134        assert_eq!(pool.allocate_many(3), Some(vec![100, 101, 102]));
5135        assert_eq!(pool.remaining(), 2);
5136        // Not enough remaining for 3 more.
5137        assert_eq!(pool.allocate_many(3), None);
5138        // But 2 works.
5139        assert_eq!(pool.allocate_many(2), Some(vec![103, 104]));
5140        assert_eq!(pool.remaining(), 0);
5141    }
5142
5143    #[mz_ore::test]
5144    fn test_allocate_many_zero() {
5145        let mut pool = IdPool::empty();
5146        pool.refill(1, 5);
5147        assert_eq!(pool.allocate_many(0), Some(vec![]));
5148        assert_eq!(pool.remaining(), 4);
5149    }
5150
5151    #[mz_ore::test]
5152    fn test_refill_resets_pool() {
5153        let mut pool = IdPool::empty();
5154        pool.refill(0, 2);
5155        assert_eq!(pool.allocate(), Some(0));
5156        // Refill before exhaustion replaces the range.
5157        pool.refill(50, 52);
5158        assert_eq!(pool.allocate(), Some(50));
5159        assert_eq!(pool.allocate(), Some(51));
5160        assert_eq!(pool.allocate(), None);
5161    }
5162
5163    #[mz_ore::test]
5164    fn test_mixed_allocate_and_allocate_many() {
5165        let mut pool = IdPool::empty();
5166        pool.refill(0, 10);
5167        assert_eq!(pool.allocate(), Some(0));
5168        assert_eq!(pool.allocate_many(3), Some(vec![1, 2, 3]));
5169        assert_eq!(pool.allocate(), Some(4));
5170        assert_eq!(pool.remaining(), 5);
5171    }
5172
5173    #[mz_ore::test]
5174    #[should_panic(expected = "invalid pool range")]
5175    fn test_refill_invalid_range_panics() {
5176        let mut pool = IdPool::empty();
5177        pool.refill(10, 5);
5178    }
5179}