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