Skip to main content

mz_storage_controller/
lib.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//! Implementation of the storage controller trait.
11
12use std::any::Any;
13use std::collections::btree_map;
14use std::collections::{BTreeMap, BTreeSet};
15use std::fmt::Debug;
16use std::str::FromStr;
17use std::sync::{Arc, Mutex};
18use std::time::Duration;
19
20use crate::collection_mgmt::{
21    AppendOnlyIntrospectionConfig, CollectionManagerKind, DifferentialIntrospectionConfig,
22};
23use crate::instance::{Instance, ReplicaConfig};
24use async_trait::async_trait;
25use chrono::{DateTime, DurationRound, TimeDelta, Utc};
26use derivative::Derivative;
27use differential_dataflow::lattice::Lattice;
28use futures::FutureExt;
29use futures::StreamExt;
30use itertools::Itertools;
31use mz_build_info::BuildInfo;
32use mz_cluster_client::client::ClusterReplicaLocation;
33use mz_cluster_client::metrics::{ControllerMetrics, WallclockLagMetrics};
34use mz_cluster_client::{ReplicaId, WallclockLagFn};
35use mz_controller_types::dyncfgs::{
36    ENABLE_0DT_DEPLOYMENT_SOURCES, WALLCLOCK_LAG_RECORDING_INTERVAL,
37};
38use mz_dyncfg::ConfigUpdates;
39use mz_ore::collections::CollectionExt;
40use mz_ore::metrics::MetricsRegistry;
41use mz_ore::now::NowFn;
42use mz_ore::task::AbortOnDropHandle;
43use mz_ore::{assert_none, halt, instrument, restart_in_place, soft_panic_or_log};
44use mz_persist_client::batch::ProtoBatch;
45use mz_persist_client::cache::PersistClientCache;
46use mz_persist_client::cfg::USE_CRITICAL_SINCE_SNAPSHOT;
47use mz_persist_client::critical::Opaque;
48use mz_persist_client::read::ReadHandle;
49use mz_persist_client::schema::CaESchema;
50use mz_persist_client::write::WriteHandle;
51use mz_persist_client::{Diagnostics, PersistClient, PersistLocation, ShardId};
52use mz_persist_types::codec_impls::UnitSchema;
53use mz_repr::adt::timestamp::CheckedTimestamp;
54use mz_repr::{Datum, Diff, GlobalId, RelationDesc, RelationVersion, Row, Timestamp};
55use mz_storage_client::client::{
56    AppendOnlyUpdate, RunIngestionCommand, RunOneshotIngestion, RunSinkCommand, Status,
57    StatusUpdate, StorageCommand, StorageResponse, TableData,
58};
59use mz_storage_client::controller::{
60    BoxFuture, CollectionDescription, DataSource, ExportDescription, ExportState,
61    IntrospectionType, MonotonicAppender, PersistEpoch, Response, StorageController,
62    StorageMetadata, StorageTxn, StorageWriteOp, TableRegistration, WallclockLag,
63    WallclockLagHistogramPeriod,
64};
65use mz_storage_client::healthcheck::{
66    MZ_AWS_PRIVATELINK_CONNECTION_STATUS_HISTORY_DESC, MZ_SINK_STATUS_HISTORY_DESC,
67    MZ_SOURCE_STATUS_HISTORY_DESC, REPLICA_STATUS_HISTORY_DESC,
68};
69use mz_storage_client::metrics::StorageControllerMetrics;
70use mz_storage_client::statistics::{
71    ControllerSinkStatistics, ControllerSourceStatistics, WebhookStatistics,
72};
73use mz_storage_client::storage_collections::{StorageCollections, shard_has_no_updates};
74use mz_storage_types::configuration::StorageConfiguration;
75use mz_storage_types::connections::ConnectionContext;
76use mz_storage_types::connections::inline::InlinedConnection;
77use mz_storage_types::controller::{AlterError, CollectionMetadata, StorageError, TxnsCodecRow};
78use mz_storage_types::errors::CollectionMissing;
79use mz_storage_types::instances::StorageInstanceId;
80use mz_storage_types::oneshot_sources::{OneshotIngestionRequest, OneshotResultCallback};
81use mz_storage_types::parameters::StorageParameters;
82use mz_storage_types::read_holds::ReadHold;
83use mz_storage_types::read_policy::ReadPolicy;
84use mz_storage_types::sinks::{StorageSinkConnection, StorageSinkDesc};
85use mz_storage_types::sources::{
86    GenericSourceConnection, IngestionDescription, SourceConnection, SourceData, SourceDesc,
87    SourceExport, SourceExportDataConfig,
88};
89use mz_storage_types::{AlterCompatible, StorageDiff, dyncfgs};
90use mz_txn_wal::metrics::Metrics as TxnMetrics;
91use mz_txn_wal::txn_read::TxnsRead;
92use mz_txn_wal::txns::TxnsHandle;
93use timely::order::PartialOrder;
94use timely::progress::frontier::MutableAntichain;
95use timely::progress::{Antichain, ChangeBatch};
96use tokio::sync::watch::{Sender, channel};
97use tokio::sync::{mpsc, oneshot};
98use tokio::time::MissedTickBehavior;
99use tokio::time::error::Elapsed;
100use tracing::{debug, info, warn};
101
102mod collection_mgmt;
103mod history;
104mod instance;
105mod persist_handles;
106mod rtr;
107mod statistics;
108
109#[derive(Derivative)]
110#[derivative(Debug)]
111struct PendingOneshotIngestion {
112    /// Callback used to provide results of the ingestion.
113    #[derivative(Debug = "ignore")]
114    result_tx: OneshotResultCallback<ProtoBatch>,
115    /// Cluster currently running this ingestion
116    cluster_id: StorageInstanceId,
117}
118
119impl PendingOneshotIngestion {
120    /// Consume the pending ingestion, responding with a cancelation message.
121    ///
122    /// TODO(cf2): Refine these error messages so they're not stringly typed.
123    pub(crate) fn cancel(self) {
124        (self.result_tx)(vec![Err("canceled".to_string())])
125    }
126}
127
128/// A storage controller for a storage instance.
129#[derive(Derivative)]
130#[derivative(Debug)]
131pub struct Controller {
132    /// The build information for this process.
133    build_info: &'static BuildInfo,
134    /// A function that returns the current time.
135    now: NowFn,
136
137    /// Whether or not this controller is in read-only mode.
138    ///
139    /// When in read-only mode, neither this controller nor the instances
140    /// controlled by it are allowed to affect changes to external systems
141    /// (largely persist).
142    read_only: bool,
143
144    /// Collections maintained by the storage controller.
145    ///
146    /// This collection only grows, although individual collections may be rendered unusable.
147    /// This is to prevent the re-binding of identifiers to other descriptions.
148    pub(crate) collections: BTreeMap<GlobalId, CollectionState>,
149
150    /// Map from IDs of objects that have been dropped to replicas we are still
151    /// expecting DroppedId messages from. This is cleared out once all replicas
152    /// have responded.
153    ///
154    /// We use this only to catch problems in the protocol between controller
155    /// and replicas, for example we can differentiate between late messages for
156    /// objects that have already been dropped and unexpected (read erroneous)
157    /// messages from the replica.
158    dropped_objects: BTreeMap<GlobalId, BTreeSet<ReplicaId>>,
159
160    /// Write handle for table shards.
161    pub(crate) persist_table_worker: persist_handles::PersistTableWriteWorker,
162    /// A shared TxnsCache running in a task and communicated with over a channel.
163    txns_read: TxnsRead<Timestamp>,
164    txns_metrics: Arc<TxnMetrics>,
165    stashed_responses: Vec<(Option<ReplicaId>, StorageResponse)>,
166    /// Channel for sending table handle drops.
167    #[derivative(Debug = "ignore")]
168    pending_table_handle_drops_tx: mpsc::UnboundedSender<GlobalId>,
169    /// Channel for receiving table handle drops.
170    #[derivative(Debug = "ignore")]
171    pending_table_handle_drops_rx: mpsc::UnboundedReceiver<GlobalId>,
172    /// Closures that can be used to send responses from oneshot ingestions.
173    #[derivative(Debug = "ignore")]
174    pending_oneshot_ingestions: BTreeMap<uuid::Uuid, PendingOneshotIngestion>,
175
176    /// Interface for managed collections
177    pub(crate) collection_manager: collection_mgmt::CollectionManager,
178
179    /// Tracks which collection is responsible for which [`IntrospectionType`].
180    pub(crate) introspection_ids: BTreeMap<IntrospectionType, GlobalId>,
181    /// Tokens for tasks that drive updating introspection collections. Dropping
182    /// this will make sure that any tasks (or other resources) will stop when
183    /// needed.
184    // TODO(aljoscha): Should these live somewhere else?
185    introspection_tokens: Arc<Mutex<BTreeMap<GlobalId, Box<dyn Any + Send + Sync>>>>,
186
187    // The following two fields must always be locked in order.
188    /// Consolidated metrics updates to periodically write. We do not eagerly initialize this,
189    /// and its contents are entirely driven by `StorageResponse::StatisticsUpdates`'s, as well
190    /// as webhook statistics.
191    source_statistics: Arc<Mutex<statistics::SourceStatistics>>,
192    /// Consolidated metrics updates to periodically write. We do not eagerly initialize this,
193    /// and its contents are entirely driven by `StorageResponse::StatisticsUpdates`'s.
194    sink_statistics: Arc<Mutex<BTreeMap<(GlobalId, Option<ReplicaId>), ControllerSinkStatistics>>>,
195    /// A way to update the statistics interval in the statistics tasks.
196    statistics_interval_sender: Sender<Duration>,
197
198    /// Clients for all known storage instances.
199    instances: BTreeMap<StorageInstanceId, Instance>,
200    /// Per-replica dyncfg overrides, consulted when a replica connects. The
201    /// overrides for a replica created by DDL are committed in the same
202    /// transaction that creates it, so they are installed before the replica
203    /// connects.
204    replica_dyncfg_overrides: BTreeMap<ReplicaId, ConfigUpdates>,
205    /// Set to `true` once `initialization_complete` has been called.
206    initialized: bool,
207    /// Storage configuration to apply to newly provisioned instances, and use during purification.
208    config: StorageConfiguration,
209    /// The persist location where all storage collections are being written to
210    persist_location: PersistLocation,
211    /// A persist client used to write to storage collections
212    persist: Arc<PersistClientCache>,
213    /// Metrics of the Storage controller
214    metrics: StorageControllerMetrics,
215    /// `(read, write)` frontiers that have been recorded in the `Frontiers` collection, kept to be
216    /// able to retract old rows.
217    recorded_frontiers: BTreeMap<GlobalId, (Antichain<Timestamp>, Antichain<Timestamp>)>,
218    /// Write frontiers that have been recorded in the `ReplicaFrontiers` collection, kept to be
219    /// able to retract old rows.
220    recorded_replica_frontiers: BTreeMap<(GlobalId, ReplicaId), Antichain<Timestamp>>,
221
222    /// A function that computes the lag between the given time and wallclock time.
223    #[derivative(Debug = "ignore")]
224    wallclock_lag: WallclockLagFn<Timestamp>,
225    /// The last time wallclock lag introspection was recorded.
226    wallclock_lag_last_recorded: DateTime<Utc>,
227
228    /// Handle to a [StorageCollections].
229    storage_collections: Arc<dyn StorageCollections + Send + Sync>,
230    /// Migrated storage collections that can be written even in read only mode.
231    migrated_storage_collections: BTreeSet<GlobalId>,
232
233    /// Ticker for scheduling periodic maintenance work.
234    maintenance_ticker: tokio::time::Interval,
235    /// Whether maintenance work was scheduled.
236    maintenance_scheduled: bool,
237
238    /// Shared transmit channel for replicas to send responses.
239    instance_response_tx: mpsc::UnboundedSender<(Option<ReplicaId>, StorageResponse)>,
240    /// Receive end for replica responses.
241    instance_response_rx: mpsc::UnboundedReceiver<(Option<ReplicaId>, StorageResponse)>,
242
243    /// Background task run at startup to warm persist state.
244    persist_warm_task: Option<AbortOnDropHandle<Box<dyn Debug + Send>>>,
245}
246
247/// Warm up persist state for `shard_ids` in a background task.
248///
249/// With better parallelism during startup this would likely be unnecessary, but empirically we see
250/// some nice speedups with this relatively simple function.
251/// What `create_collections_for_bootstrap` opens per collection: a write handle for collections
252/// the controller writes directly, or just a recent, linearized upper for txns-managed tables,
253/// whose writes go through the table-write worker (which opens its own handles per
254/// registration).
255enum WriteHandleOrUpper {
256    Handle(WriteHandle<SourceData, (), Timestamp, StorageDiff>),
257    Upper(Antichain<Timestamp>),
258}
259
260impl WriteHandleOrUpper {
261    fn upper(&self) -> Antichain<Timestamp> {
262        match self {
263            Self::Handle(handle) => handle.upper().clone(),
264            Self::Upper(upper) => upper.clone(),
265        }
266    }
267
268    /// Returns the write handle, panicking for the `Upper` variant. Only call for data sources
269    /// that are never tables.
270    fn expect_handle(self, context: &str) -> WriteHandle<SourceData, (), Timestamp, StorageDiff> {
271        match self {
272            Self::Handle(handle) => handle,
273            Self::Upper(_) => panic!("write handle required: {context}"),
274        }
275    }
276}
277
278fn warm_persist_state_in_background(
279    client: PersistClient,
280    shard_ids: impl Iterator<Item = ShardId> + Send + 'static,
281) -> mz_ore::task::JoinHandle<Box<dyn Debug + Send>> {
282    /// Bound the number of shards that we warm at a single time, to limit our overall resource use.
283    const MAX_CONCURRENT_WARMS: usize = 16;
284    let logic = async move {
285        let fetchers: Vec<_> = tokio_stream::iter(shard_ids)
286            .map(|shard_id| {
287                let client = client.clone();
288                async move {
289                    client
290                        .create_batch_fetcher::<SourceData, (), mz_repr::Timestamp, StorageDiff>(
291                            shard_id,
292                            Arc::new(RelationDesc::empty()),
293                            Arc::new(UnitSchema),
294                            true,
295                            Diagnostics::from_purpose("warm persist load state"),
296                        )
297                        .await
298                }
299            })
300            .buffer_unordered(MAX_CONCURRENT_WARMS)
301            .collect()
302            .await;
303        let fetchers: Box<dyn Debug + Send> = Box::new(fetchers);
304        fetchers
305    };
306    mz_ore::task::spawn(|| "warm_persist_load_state", logic)
307}
308
309#[async_trait(?Send)]
310impl StorageController for Controller {
311    fn initialization_complete(&mut self) {
312        self.reconcile_dangling_statistics();
313        self.initialized = true;
314
315        for instance in self.instances.values_mut() {
316            instance.send(StorageCommand::InitializationComplete);
317        }
318    }
319
320    fn update_parameters(&mut self, config_params: StorageParameters) {
321        self.storage_collections
322            .update_parameters(config_params.clone());
323
324        // We serialize the dyncfg updates in StorageParameters, but configure
325        // persist separately.
326        self.persist.cfg().apply_from(&config_params.dyncfg_updates);
327
328        for instance in self.instances.values_mut() {
329            let params = Box::new(config_params.clone());
330            instance.send(StorageCommand::UpdateConfiguration(params));
331        }
332        self.config.update(config_params);
333        self.statistics_interval_sender
334            .send_replace(self.config.parameters.statistics_interval);
335        self.collection_manager.update_user_batch_duration(
336            self.config
337                .parameters
338                .user_storage_managed_collections_batch_duration,
339        );
340    }
341
342    fn update_replica_dyncfg_overrides(
343        &mut self,
344        mut overrides: BTreeMap<StorageInstanceId, BTreeMap<ReplicaId, ConfigUpdates>>,
345    ) {
346        self.replica_dyncfg_overrides = overrides
347            .values()
348            .flat_map(|replicas| replicas.iter())
349            .map(|(replica_id, updates)| (*replica_id, updates.clone()))
350            .collect();
351        for (id, instance) in self.instances.iter_mut() {
352            let instance_overrides = overrides.remove(id).unwrap_or_default();
353            instance.update_replica_dyncfg_overrides(instance_overrides);
354        }
355    }
356
357    /// Get the current configuration
358    fn config(&self) -> &StorageConfiguration {
359        &self.config
360    }
361
362    fn collection_metadata(&self, id: GlobalId) -> Result<CollectionMetadata, CollectionMissing> {
363        self.storage_collections.collection_metadata(id)
364    }
365
366    fn collection_hydrated(&self, collection_id: GlobalId) -> Result<bool, StorageError> {
367        let collection = self.collection(collection_id)?;
368
369        let instance_id = match &collection.data_source {
370            DataSource::Ingestion(ingestion_description) => ingestion_description.instance_id,
371            DataSource::IngestionExport { ingestion_id, .. } => {
372                let ingestion_state = self.collections.get(ingestion_id).expect("known to exist");
373
374                let instance_id = match &ingestion_state.data_source {
375                    DataSource::Ingestion(ingestion_desc) => ingestion_desc.instance_id,
376                    _ => unreachable!("SourceExport must only refer to primary source"),
377                };
378
379                instance_id
380            }
381            _ => return Ok(true),
382        };
383
384        let instance = self.instances.get(&instance_id).ok_or_else(|| {
385            StorageError::IngestionInstanceMissing {
386                storage_instance_id: instance_id,
387                ingestion_id: collection_id,
388            }
389        })?;
390
391        if instance.replica_ids().next().is_none() {
392            // Ingestions on zero-replica clusters are always considered
393            // hydrated.
394            return Ok(true);
395        }
396
397        match &collection.extra_state {
398            CollectionStateExtra::Ingestion(ingestion_state) => {
399                // An ingestion is hydrated if it is hydrated on at least one replica.
400                Ok(ingestion_state.hydrated_on.len() >= 1)
401            }
402            CollectionStateExtra::Export(_) => {
403                // For now, sinks are always considered hydrated. We rely on
404                // them starting up "instantly" and don't wait for them when
405                // checking hydration status of a replica.  TODO(sinks): base
406                // this off of the sink shard's frontier?
407                Ok(true)
408            }
409            CollectionStateExtra::None => {
410                // For now, objects that are not ingestions are always
411                // considered hydrated. This is tables and webhooks, as of
412                // today.
413                Ok(true)
414            }
415        }
416    }
417
418    #[mz_ore::instrument(level = "debug")]
419    fn collections_hydrated_on_replicas(
420        &self,
421        target_replica_ids: Option<Vec<ReplicaId>>,
422        target_cluster_id: &StorageInstanceId,
423        exclude_collections: &BTreeSet<GlobalId>,
424    ) -> Result<bool, StorageError> {
425        // If an empty set of replicas is provided there can be
426        // no collections on them, we'll count this as hydrated.
427        if target_replica_ids.as_ref().is_some_and(|v| v.is_empty()) {
428            return Ok(true);
429        }
430
431        // If target_replica_ids is provided, use it as the set of target
432        // replicas. Otherwise check for hydration on any replica.
433        let target_replicas: Option<BTreeSet<ReplicaId>> =
434            target_replica_ids.map(|ids| ids.into_iter().collect());
435
436        let instance = self.instances.get(target_cluster_id);
437
438        let mut all_hydrated = true;
439        for (collection_id, collection_state) in self.collections.iter() {
440            if collection_id.is_transient() || exclude_collections.contains(collection_id) {
441                continue;
442            }
443            let hydrated = match &collection_state.extra_state {
444                CollectionStateExtra::Ingestion(state) => {
445                    if &state.instance_id != target_cluster_id {
446                        continue;
447                    }
448                    match &target_replicas {
449                        Some(target_replicas) => {
450                            // Not scheduled on any target replica means it can
451                            // never hydrate there, so it does not count (see
452                            // the trait docs). If the instance is unknown (the
453                            // cluster is being dropped concurrently) the
454                            // scheduled set is empty and every ingestion is
455                            // skipped. Readiness callers gate on replica health
456                            // separately, which covers that window.
457                            let scheduled_on = instance
458                                .map(|i| i.get_active_replicas_for_object(collection_id))
459                                .unwrap_or_default();
460                            if scheduled_on.is_disjoint(target_replicas) {
461                                true
462                            } else {
463                                !state.hydrated_on.is_disjoint(target_replicas)
464                            }
465                        }
466                        None => {
467                            // Not target replicas, so check that it's hydrated
468                            // on at least one replica.
469                            state.hydrated_on.len() >= 1
470                        }
471                    }
472                }
473                CollectionStateExtra::Export(_) => {
474                    // For now, sinks are always considered hydrated. We rely on
475                    // them starting up "instantly" and don't wait for them when
476                    // checking hydration status of a replica.  TODO(sinks):
477                    // base this off of the sink shard's frontier?
478                    true
479                }
480                CollectionStateExtra::None => {
481                    // For now, objects that are not ingestions are always
482                    // considered hydrated. This is tables and webhooks, as of
483                    // today.
484                    true
485                }
486            };
487            if !hydrated {
488                tracing::info!(%collection_id, "collection is not hydrated on any replica");
489                all_hydrated = false;
490                // We continue with our loop instead of breaking out early, so
491                // that we log all non-hydrated replicas.
492            }
493        }
494        Ok(all_hydrated)
495    }
496
497    fn collection_frontiers(
498        &self,
499        id: GlobalId,
500    ) -> Result<(Antichain<Timestamp>, Antichain<Timestamp>), CollectionMissing> {
501        let frontiers = self.storage_collections.collection_frontiers(id)?;
502        Ok((frontiers.implied_capability, frontiers.write_frontier))
503    }
504
505    fn collections_frontiers(
506        &self,
507        mut ids: Vec<GlobalId>,
508    ) -> Result<Vec<(GlobalId, Antichain<Timestamp>, Antichain<Timestamp>)>, CollectionMissing>
509    {
510        let mut result = vec![];
511        // In theory, we could pull all our frontiers from storage collections...
512        // but in practice those frontiers may not be identical. For historical reasons, we use the
513        // locally-tracked frontier for sinks but the storage-collections-maintained frontier for
514        // sources.
515        ids.retain(|&id| match self.export(id) {
516            Ok(export) => {
517                result.push((
518                    id,
519                    export.input_hold().since().clone(),
520                    export.write_frontier.clone(),
521                ));
522                false
523            }
524            Err(_) => true,
525        });
526        result.extend(
527            self.storage_collections
528                .collections_frontiers(ids)?
529                .into_iter()
530                .map(|frontiers| {
531                    (
532                        frontiers.id,
533                        frontiers.implied_capability,
534                        frontiers.write_frontier,
535                    )
536                }),
537        );
538
539        Ok(result)
540    }
541
542    fn active_collection_metadatas(&self) -> Vec<(GlobalId, CollectionMetadata)> {
543        self.storage_collections.active_collection_metadatas()
544    }
545
546    fn active_ingestion_exports(
547        &self,
548        instance_id: StorageInstanceId,
549    ) -> Box<dyn Iterator<Item = &GlobalId> + '_> {
550        let active_storage_collections: BTreeMap<_, _> = self
551            .storage_collections
552            .active_collection_frontiers()
553            .into_iter()
554            .map(|c| (c.id, c))
555            .collect();
556
557        let active_exports = self.instances[&instance_id]
558            .active_ingestion_exports()
559            .filter(move |id| {
560                let frontiers = active_storage_collections.get(id);
561                match frontiers {
562                    Some(frontiers) => !frontiers.write_frontier.is_empty(),
563                    None => {
564                        // Not "active", so we don't care here.
565                        false
566                    }
567                }
568            });
569
570        Box::new(active_exports)
571    }
572
573    fn check_exists(&self, id: GlobalId) -> Result<(), StorageError> {
574        self.storage_collections.check_exists(id)
575    }
576
577    fn create_instance(&mut self, id: StorageInstanceId, workload_class: Option<String>) {
578        let metrics = self.metrics.for_instance(id);
579        let mut instance = Instance::new(
580            workload_class,
581            metrics,
582            self.now.clone(),
583            self.instance_response_tx.clone(),
584        );
585        if self.initialized {
586            instance.send(StorageCommand::InitializationComplete);
587        }
588        if !self.read_only {
589            instance.send(StorageCommand::AllowWrites);
590        }
591
592        let params = Box::new(self.config.parameters.clone());
593        instance.send(StorageCommand::UpdateConfiguration(params));
594
595        let old_instance = self.instances.insert(id, instance);
596        assert_none!(old_instance, "storage instance {id} already exists");
597    }
598
599    fn drop_instance(&mut self, id: StorageInstanceId) {
600        let instance = self.instances.remove(&id);
601        assert!(instance.is_some(), "storage instance {id} does not exist");
602    }
603
604    fn update_instance_workload_class(
605        &mut self,
606        id: StorageInstanceId,
607        workload_class: Option<String>,
608    ) {
609        let instance = self
610            .instances
611            .get_mut(&id)
612            .unwrap_or_else(|| panic!("instance {id} does not exist"));
613
614        instance.workload_class = workload_class;
615    }
616
617    fn connect_replica(
618        &mut self,
619        instance_id: StorageInstanceId,
620        replica_id: ReplicaId,
621        location: ClusterReplicaLocation,
622    ) {
623        let instance = self
624            .instances
625            .get_mut(&instance_id)
626            .unwrap_or_else(|| panic!("instance {instance_id} does not exist"));
627
628        let config = ReplicaConfig {
629            build_info: self.build_info,
630            location,
631            grpc_client: self.config.parameters.grpc_client.clone(),
632        };
633        let dyncfg_override = self
634            .replica_dyncfg_overrides
635            .get(&replica_id)
636            .cloned()
637            .unwrap_or_default();
638        instance.add_replica(replica_id, config, dyncfg_override);
639    }
640
641    fn drop_replica(&mut self, instance_id: StorageInstanceId, replica_id: ReplicaId) {
642        // The coordinator only re-pushes the override map when the scoped
643        // configuration itself changes, so a dropped replica's entry would
644        // otherwise be retained until the next such change.
645        self.replica_dyncfg_overrides.remove(&replica_id);
646
647        let instance = self
648            .instances
649            .get_mut(&instance_id)
650            .unwrap_or_else(|| panic!("instance {instance_id} does not exist"));
651
652        let status_now = mz_ore::now::to_datetime((self.now)());
653        let mut source_status_updates = vec![];
654        let mut sink_status_updates = vec![];
655
656        // NOTE: mz_source_statuses and mz_sink_statuses rely on per-replica `paused` meaning
657        // "replica dropped"
658        let make_update = |id, object_type| StatusUpdate {
659            id,
660            status: Status::Paused,
661            timestamp: status_now,
662            error: None,
663            hints: BTreeSet::from([format!(
664                "The replica running this {object_type} has been dropped"
665            )]),
666            namespaced_errors: Default::default(),
667            replica_id: Some(replica_id),
668        };
669
670        for ingestion_id in instance.active_ingestions() {
671            if let Some(active_replicas) = self.dropped_objects.get_mut(ingestion_id) {
672                active_replicas.remove(&replica_id);
673                if active_replicas.is_empty() {
674                    self.dropped_objects.remove(ingestion_id);
675                }
676            }
677
678            let ingestion = self
679                .collections
680                .get_mut(ingestion_id)
681                .expect("instance contains unknown ingestion");
682
683            let ingestion_description = match &ingestion.data_source {
684                DataSource::Ingestion(ingestion_description) => ingestion_description.clone(),
685                _ => panic!(
686                    "unexpected data source for ingestion: {:?}",
687                    ingestion.data_source
688                ),
689            };
690
691            let old_style_ingestion = *ingestion_id != ingestion_description.remap_collection_id;
692            let subsource_ids = ingestion_description.collection_ids().filter(|id| {
693                // NOTE(aljoscha): We filter out the remap collection for old style
694                // ingestions because it doesn't get any status updates about it from the
695                // replica side. So we don't want to synthesize a 'paused' status here.
696                // New style ingestion do, since the source itself contains the remap data.
697                let should_discard =
698                    old_style_ingestion && id == &ingestion_description.remap_collection_id;
699                !should_discard
700            });
701            for id in subsource_ids {
702                source_status_updates.push(make_update(id, "source"));
703            }
704        }
705
706        for id in instance.active_exports() {
707            if let Some(active_replicas) = self.dropped_objects.get_mut(id) {
708                active_replicas.remove(&replica_id);
709                if active_replicas.is_empty() {
710                    self.dropped_objects.remove(id);
711                }
712            }
713
714            sink_status_updates.push(make_update(*id, "sink"));
715        }
716
717        instance.drop_replica(replica_id);
718
719        if !self.read_only {
720            if !source_status_updates.is_empty() {
721                self.append_status_introspection_updates(
722                    IntrospectionType::SourceStatusHistory,
723                    source_status_updates,
724                );
725            }
726            if !sink_status_updates.is_empty() {
727                self.append_status_introspection_updates(
728                    IntrospectionType::SinkStatusHistory,
729                    sink_status_updates,
730                );
731            }
732        }
733    }
734
735    async fn evolve_nullability_for_bootstrap(
736        &mut self,
737        storage_metadata: &StorageMetadata,
738        collections: Vec<(GlobalId, RelationDesc)>,
739    ) -> Result<(), StorageError> {
740        use futures::TryStreamExt;
741
742        let persist_client = self
743            .persist
744            .open(self.persist_location.clone())
745            .await
746            .unwrap();
747        let persist_client = &persist_client;
748
749        let evolve = |shard_id, global_id: GlobalId, relation_desc: RelationDesc| async move {
750            let diagnostics = Diagnostics {
751                shard_name: global_id.to_string(),
752                handle_purpose: "evolve nullability for bootstrap".to_string(),
753            };
754            let latest_schema = persist_client
755                .latest_schema::<SourceData, (), Timestamp, StorageDiff>(shard_id, diagnostics)
756                .await
757                .expect("invalid persist usage");
758            let Some((schema_id, current_schema, _)) = latest_schema else {
759                tracing::debug!(?global_id, "no schema registered");
760                return Ok(());
761            };
762            tracing::debug!(?global_id, ?current_schema, new_schema = ?relation_desc, "migrating schema");
763
764            let diagnostics = Diagnostics {
765                shard_name: global_id.to_string(),
766                handle_purpose: "evolve nullability for bootstrap".to_string(),
767            };
768            let evolve_result = persist_client
769                .compare_and_evolve_schema::<SourceData, (), Timestamp, StorageDiff>(
770                    shard_id,
771                    schema_id,
772                    &relation_desc,
773                    &UnitSchema,
774                    diagnostics,
775                )
776                .await
777                .expect("invalid persist usage");
778            match evolve_result {
779                CaESchema::Ok(_) => (),
780                CaESchema::ExpectedMismatch {
781                    schema_id,
782                    key,
783                    val: _,
784                } => {
785                    return Err(StorageError::PersistSchemaEvolveRace {
786                        global_id,
787                        shard_id,
788                        schema_id,
789                        relation_desc: key,
790                    });
791                }
792                CaESchema::Incompatible => {
793                    return Err(StorageError::PersistInvalidSchemaEvolve {
794                        global_id,
795                        shard_id,
796                    });
797                }
798            };
799            Ok(())
800        };
801
802        // A replacement materialized view writes to the shard of its target. The collections of
803        // a shard evolve in order, each seeing the schema the previous one registered.
804        let mut by_shard: BTreeMap<_, Vec<_>> = BTreeMap::new();
805        for (global_id, relation_desc) in collections {
806            let shard_id = storage_metadata.get_collection_shard(global_id)?;
807            by_shard
808                .entry(shard_id)
809                .or_default()
810                .push((global_id, relation_desc));
811        }
812
813        // Shards evolve concurrently. `latest_schema` initializes a shard that has never been
814        // used, with a blob write and a consensus write, and on the first boot of an environment
815        // that is every shard.
816        futures::stream::iter(by_shard)
817            .map(|(shard_id, collections)| async move {
818                for (global_id, relation_desc) in collections {
819                    evolve(shard_id, global_id, relation_desc).await?;
820                }
821                Ok(())
822            })
823            .buffer_unordered(50)
824            .try_collect()
825            .await
826    }
827
828    /// Create and "execute" the described collection.
829    ///
830    /// "Execute" is in scare quotes because what executing a collection means
831    /// varies widely based on the type of collection you're creating.
832    ///
833    /// The general process creating a collection undergoes is:
834    /// 1. Enrich the description we get from the user with the metadata only
835    ///    the storage controller's metadata. This is mostly a matter of
836    ///    separating concerns.
837    /// 2. Generate write and read persist handles for the collection.
838    /// 3. Store the collection's metadata in the appropriate field.
839    /// 4. "Execute" the collection. What that means is contingent on the type of
840    ///    collection. so consult the code for more details.
841    ///
842    // TODO(aljoscha): It would be swell if we could refactor this Leviathan of
843    // a method/move individual parts to their own methods. @guswynn observes
844    // that a number of these operations could be moved into fns on
845    // `DataSource`.
846    #[instrument(name = "storage::create_collections")]
847    async fn create_collections_for_bootstrap(
848        &mut self,
849        storage_metadata: &StorageMetadata,
850        register_ts: Option<Timestamp>,
851        mut collections: Vec<(GlobalId, CollectionDescription)>,
852        migrated_storage_collections: &BTreeSet<GlobalId>,
853    ) -> Result<(), StorageError> {
854        self.migrated_storage_collections
855            .extend(migrated_storage_collections.iter().cloned());
856
857        self.storage_collections
858            .create_collections_for_bootstrap(
859                storage_metadata,
860                register_ts,
861                collections.clone(),
862                migrated_storage_collections,
863            )
864            .await?;
865
866        // At this point we're connected to all the collection shards in persist. Our warming task
867        // is no longer useful, so abort it if it's still running.
868        drop(self.persist_warm_task.take());
869
870        // Validate first, to avoid corrupting state.
871        // 1. create a dropped identifier, or
872        // 2. create an existing identifier with a new description.
873        // Make sure to check for errors within `ingestions` as well.
874        collections.sort_by_key(|(id, _)| *id);
875        collections.dedup();
876        for pos in 1..collections.len() {
877            if collections[pos - 1].0 == collections[pos].0 {
878                return Err(StorageError::CollectionIdReused(collections[pos].0));
879            }
880        }
881
882        // We first enrich each collection description with some additional metadata...
883        let enriched_with_metadata = collections
884            .into_iter()
885            .map(|(id, description)| {
886                let data_shard = storage_metadata.get_collection_shard(id)?;
887
888                // If the shard is being managed by txn-wal (initially, tables), then we need to
889                // pass along the shard id for the txns shard to dataflow rendering.
890                let txns_shard = description
891                    .data_source
892                    .in_txns()
893                    .then(|| *self.txns_read.txns_id());
894
895                let metadata = CollectionMetadata {
896                    persist_location: self.persist_location.clone(),
897                    data_shard,
898                    relation_desc: description.desc.clone(),
899                    txns_shard,
900                };
901
902                Ok((id, description, metadata))
903            })
904            .collect_vec();
905
906        // So that we can open persist handles for each collections concurrently.
907        let persist_client = self
908            .persist
909            .open(self.persist_location.clone())
910            .await
911            .unwrap();
912        let persist_client = &persist_client;
913
914        // Reborrow the `&mut self` as immutable, as all the concurrent work to be processed in
915        // this stream cannot all have exclusive access.
916        use futures::stream::{StreamExt, TryStreamExt};
917        let this = &*self;
918        let mut to_register: Vec<_> = futures::stream::iter(enriched_with_metadata)
919            .map(|data: Result<_, StorageError>| {
920                async move {
921                    let (id, description, metadata) = data?;
922
923                    // should be replaced with real introspection (https://github.com/MaterializeInc/database-issues/issues/4078)
924                    // but for now, it's helpful to have this mapping written down somewhere
925                    debug!("mapping GlobalId={} to shard ({})", id, metadata.data_shard);
926
927                    // Tables are written through the txns table-write worker, which opens its
928                    // own write handles per registration, so opening one here would be pure
929                    // overhead (an extra persist open per table on the startup path). The
930                    // controller only needs a recent upper for them.
931                    let write = if matches!(description.data_source, DataSource::Table) {
932                        let diagnostics = Diagnostics {
933                            shard_name: id.to_string(),
934                            handle_purpose: format!("controller data for {}", id),
935                        };
936                        let upper = persist_client
937                            .recent_upper::<SourceData, (), Timestamp, StorageDiff>(
938                                metadata.data_shard,
939                                diagnostics,
940                            )
941                            .await
942                            .expect("invalid persist usage");
943                        WriteHandleOrUpper::Upper(upper)
944                    } else {
945                        let write = this
946                            .open_data_handles(
947                                &id,
948                                metadata.data_shard,
949                                metadata.relation_desc.clone(),
950                                persist_client,
951                            )
952                            .await;
953                        WriteHandleOrUpper::Handle(write)
954                    };
955
956                    Ok::<_, StorageError>((id, description, write, metadata))
957                }
958            })
959            // Poll each future for each collection concurrently, maximum of 50 at a time.
960            .buffer_unordered(50)
961            // HERE BE DRAGONS:
962            //
963            // There are at least 2 subtleties in using `FuturesUnordered` (which
964            // `buffer_unordered` uses underneath:
965            // - One is captured here <https://github.com/rust-lang/futures-rs/issues/2387>
966            // - And the other is deadlocking if processing an OUTPUT of a `FuturesUnordered`
967            // stream attempts to obtain an async mutex that is also obtained in the futures
968            // being polled.
969            //
970            // Both of these could potentially be issues in all usages of `buffer_unordered` in
971            // this method, so we stick the standard advice: only use `try_collect` or
972            // `collect`!
973            .try_collect()
974            .await?;
975
976        // The set of collections that we should render at the end of this
977        // function.
978        let mut to_execute = BTreeSet::new();
979        // New collections that are being created; this is distinct from the set
980        // of collections we plan to execute because
981        // `DataSource::IngestionExport` is added as a new collection, but is
982        // not executed directly.
983        let mut new_collections = BTreeSet::new();
984
985        // Reorder in dependency order.
986        to_register.sort_by_key(|(id, ..)| *id);
987
988        // Register tables first, but register them in reverse order since earlier tables
989        // can depend on later tables.
990        //
991        // Note: We could do more complex sorting to avoid the allocations, but IMO it's
992        // easier to reason about it this way.
993        let (tables_to_register, collections_to_register): (Vec<_>, Vec<_>) = to_register
994            .into_iter()
995            .partition(|(_id, desc, ..)| desc.data_source == DataSource::Table);
996        let to_register = tables_to_register
997            .into_iter()
998            .rev()
999            .chain(collections_to_register.into_iter());
1000
1001        // Statistics need a level of indirection so we can mutably borrow
1002        // `self` when registering collections and when we are inserting
1003        // statistics.
1004        let mut new_webhook_statistic_entries = BTreeSet::new();
1005
1006        for (id, description, write, metadata) in to_register {
1007            let is_in_txns = |id, metadata: &CollectionMetadata| {
1008                metadata.txns_shard.is_some()
1009                    && !(self.read_only && migrated_storage_collections.contains(&id))
1010            };
1011
1012            to_execute.insert(id);
1013            new_collections.insert(id);
1014
1015            let write_frontier = write.upper();
1016
1017            // Determine if this collection has another dependency.
1018            let storage_dependencies = self.determine_collection_dependencies(id, &description)?;
1019
1020            let dependency_read_holds = self
1021                .storage_collections
1022                .acquire_read_holds(storage_dependencies)
1023                .expect("can acquire read holds");
1024
1025            let mut dependency_since = Antichain::from_elem(Timestamp::MIN);
1026            for read_hold in dependency_read_holds.iter() {
1027                dependency_since.join_assign(read_hold.since());
1028            }
1029
1030            let data_source = description.data_source;
1031
1032            // Assert some invariants.
1033            //
1034            // TODO(alter_table): Include Tables (is_in_txns) in this check. After
1035            // supporting ALTER TABLE, it's now possible for a table to have a dependency
1036            // and thus run this check. But tables are managed by txn-wal and thus the
1037            // upper of the shard's `write_handle` generally isn't the logical upper of
1038            // the shard. Instead we need to thread through the upper of the `txn` shard
1039            // here so we can check this invariant.
1040            if !dependency_read_holds.is_empty()
1041                && !is_in_txns(id, &metadata)
1042                && !matches!(&data_source, DataSource::Sink { .. })
1043            {
1044                // As the halt message says, this can happen when trying to come
1045                // up in read-only mode and the current read-write
1046                // environmentd/controller deletes a collection. We exit
1047                // gracefully, which means we'll get restarted and get to try
1048                // again.
1049                //
1050                // We only do this when our own upper is not empty. An empty
1051                // upper means the collection is sealed and no-one can write to
1052                // it anymore, so an empty dependency since cannot hurt us. And
1053                // a sealed collection is durable state rather than a race, so
1054                // halting on it would wedge bootstrap forever instead of
1055                // resolving on the next attempt.
1056                if dependency_since.is_empty() && !write_frontier.is_empty() {
1057                    let reason = format!(
1058                        "dependency since frontier is empty while dependent upper \
1059                        is not empty (dependent id={id}, write_frontier={:?}, dependency_read_holds={:?}), \
1060                        this indicates concurrent deletion of a collection",
1061                        write_frontier, dependency_read_holds,
1062                    );
1063                    // A read-only controller can restart without Kubernetes
1064                    // crash backoff. If its generation has been promoted
1065                    // meanwhile, by a replacement pod or by this process after
1066                    // a skipped catch-up, `preflight_0dt` halts the restarted
1067                    // process.
1068                    if self.read_only {
1069                        restart_in_place!("{}", reason);
1070                    } else {
1071                        halt!("{}", reason);
1072                    }
1073                }
1074
1075                // If the dependency is between a remap shard and a source (and
1076                // not a "primary" dependency), the dependency since cannot be
1077                // beyond the dependent (our) upper unless the collection is
1078                // new. If the since is allowed to "catch up" to the upper, that
1079                // is `upper <= since`, a restarting ingestion cannot
1080                // differentiate between updates that have already been written
1081                // out to the backing persist shard and updates that have yet to
1082                // be written. We would write duplicate updates.
1083                //
1084                // If this check fails, it means that the read hold installed on
1085                // the dependency was probably not upheld –– if it were, the
1086                // dependency's since could not have advanced as far the
1087                // dependent's upper.
1088                //
1089                // We don't care about the dependency since when the write
1090                // frontier is empty. In that case, no-one can write down any
1091                // more updates.
1092                //
1093                // An ingestion export whose shard holds no updates is exempt,
1094                // see `StorageCollectionsImpl::create_collections_for_bootstrap`.
1095                if description.primary.is_none()
1096                    && write_frontier.elements() != &[Timestamp::MIN]
1097                    && !write_frontier.is_empty()
1098                    && !PartialOrder::less_than(&dependency_since, &write_frontier)
1099                    && !(matches!(data_source, DataSource::IngestionExport { .. })
1100                        && shard_has_no_updates(persist_client, id, &metadata).await)
1101                {
1102                    mz_ore::soft_panic_or_log!(
1103                        "dependency since has advanced past dependent ({id}) upper \n
1104                            dependent ({id}): upper {:?} \n
1105                            dependency since {:?} \n
1106                            dependency read holds: {:?}",
1107                        write_frontier,
1108                        dependency_since,
1109                        dependency_read_holds,
1110                    );
1111                }
1112            }
1113
1114            // Perform data source-specific setup.
1115            let mut extra_state = CollectionStateExtra::None;
1116            let mut maybe_instance_id = None;
1117            match &data_source {
1118                DataSource::Introspection(typ) => {
1119                    debug!(
1120                        ?data_source, meta = ?metadata,
1121                        "registering {id} with persist monotonic worker",
1122                    );
1123                    // We always register the collection with the collection manager,
1124                    // regardless of read-only mode. The CollectionManager itself is
1125                    // aware of read-only mode and will not attempt to write before told
1126                    // to do so.
1127                    //
1128                    self.register_introspection_collection(
1129                        id,
1130                        *typ,
1131                        write.expect_handle("introspection collections are not tables"),
1132                        persist_client.clone(),
1133                    )?;
1134                }
1135                DataSource::Webhook => {
1136                    debug!(
1137                        ?data_source, meta = ?metadata,
1138                        "registering {id} with persist monotonic worker",
1139                    );
1140                    // This collection of statistics is periodically aggregated into
1141                    // `source_statistics`.
1142                    new_webhook_statistic_entries.insert(id);
1143                    // Register the collection so our manager knows about it.
1144                    //
1145                    // NOTE: Maybe this shouldn't be in the collection manager,
1146                    // and collection manager should only be responsible for
1147                    // built-in introspection collections?
1148                    self.collection_manager.register_append_only_collection(
1149                        id,
1150                        write.expect_handle("webhook collections are not tables"),
1151                        false,
1152                        None,
1153                    );
1154                }
1155                DataSource::IngestionExport {
1156                    ingestion_id,
1157                    details,
1158                    data_config,
1159                } => {
1160                    debug!(
1161                        ?data_source, meta = ?metadata,
1162                        "not registering {id} with a controller persist worker",
1163                    );
1164                    // Adjust the source to contain this export.
1165                    let ingestion_state = self
1166                        .collections
1167                        .get_mut(ingestion_id)
1168                        .expect("known to exist");
1169
1170                    let instance_id = match &mut ingestion_state.data_source {
1171                        DataSource::Ingestion(ingestion_desc) => {
1172                            ingestion_desc.source_exports.insert(
1173                                id,
1174                                SourceExport {
1175                                    storage_metadata: (),
1176                                    details: details.clone(),
1177                                    data_config: data_config.clone(),
1178                                },
1179                            );
1180
1181                            // Record the ingestion's cluster ID for the
1182                            // ingestion export. This way we always have a
1183                            // record of it, even if the ingestion's collection
1184                            // description disappears.
1185                            ingestion_desc.instance_id
1186                        }
1187                        _ => unreachable!(
1188                            "SourceExport must only refer to primary sources that already exist"
1189                        ),
1190                    };
1191
1192                    // Executing the source export doesn't do anything, ensure we execute the source instead.
1193                    to_execute.remove(&id);
1194                    to_execute.insert(*ingestion_id);
1195
1196                    let ingestion_state = IngestionState {
1197                        read_capabilities: MutableAntichain::from(dependency_since.clone()),
1198                        dependency_read_holds,
1199                        derived_since: dependency_since,
1200                        write_frontier: Antichain::from_elem(Timestamp::MIN),
1201                        hold_policy: ReadPolicy::step_back(),
1202                        instance_id,
1203                        hydrated_on: BTreeSet::new(),
1204                    };
1205
1206                    extra_state = CollectionStateExtra::Ingestion(ingestion_state);
1207                    maybe_instance_id = Some(instance_id);
1208                }
1209                DataSource::Table => {
1210                    debug!(
1211                        ?data_source, meta = ?metadata,
1212                        "not registering {id} with the txns shard here; the caller does that \
1213                         through the group committer",
1214                    );
1215                }
1216                DataSource::Progress | DataSource::Other => {
1217                    debug!(
1218                        ?data_source, meta = ?metadata,
1219                        "not registering {id} with a controller persist worker",
1220                    );
1221                }
1222                DataSource::Ingestion(ingestion_desc) => {
1223                    debug!(
1224                        ?data_source, meta = ?metadata,
1225                        "not registering {id} with a controller persist worker",
1226                    );
1227
1228                    let mut dependency_since = Antichain::from_elem(Timestamp::MIN);
1229                    for read_hold in dependency_read_holds.iter() {
1230                        dependency_since.join_assign(read_hold.since());
1231                    }
1232
1233                    let ingestion_state = IngestionState {
1234                        read_capabilities: MutableAntichain::from(dependency_since.clone()),
1235                        dependency_read_holds,
1236                        derived_since: dependency_since,
1237                        write_frontier: Antichain::from_elem(Timestamp::MIN),
1238                        hold_policy: ReadPolicy::step_back(),
1239                        instance_id: ingestion_desc.instance_id,
1240                        hydrated_on: BTreeSet::new(),
1241                    };
1242
1243                    extra_state = CollectionStateExtra::Ingestion(ingestion_state);
1244                    maybe_instance_id = Some(ingestion_desc.instance_id);
1245                }
1246                DataSource::Sink { desc } => {
1247                    let mut dependency_since = Antichain::from_elem(Timestamp::MIN);
1248                    for read_hold in dependency_read_holds.iter() {
1249                        dependency_since.join_assign(read_hold.since());
1250                    }
1251
1252                    let [self_hold, read_hold] =
1253                        dependency_read_holds.try_into().expect("two holds");
1254
1255                    let state = ExportState::new(
1256                        desc.instance_id,
1257                        read_hold,
1258                        self_hold,
1259                        write_frontier.clone(),
1260                        ReadPolicy::step_back(),
1261                    );
1262                    maybe_instance_id = Some(state.cluster_id);
1263                    extra_state = CollectionStateExtra::Export(state);
1264                }
1265            }
1266
1267            let wallclock_lag_metrics = self.metrics.wallclock_lag_metrics(id, maybe_instance_id);
1268            let collection_state =
1269                CollectionState::new(data_source, metadata, extra_state, wallclock_lag_metrics);
1270
1271            self.collections.insert(id, collection_state);
1272        }
1273
1274        {
1275            let mut source_statistics = self.source_statistics.lock().expect("poisoned");
1276
1277            // Webhooks don't run on clusters/replicas, so we initialize their
1278            // statistics collection here.
1279            for id in new_webhook_statistic_entries {
1280                source_statistics.webhook_statistics.entry(id).or_default();
1281            }
1282
1283            // Sources and sinks only have statistics in the collection when
1284            // there is a replica that is reporting them. No need to initialize
1285            // here.
1286        }
1287
1288        self.append_shard_mappings(new_collections.into_iter(), Diff::ONE);
1289
1290        // TODO(guswynn): perform the io in this final section concurrently.
1291        for id in to_execute {
1292            match &self.collection(id)?.data_source {
1293                DataSource::Ingestion(ingestion) => {
1294                    if !self.read_only
1295                        || (ENABLE_0DT_DEPLOYMENT_SOURCES.get(self.config.config_set())
1296                            && ingestion.desc.connection.supports_read_only())
1297                    {
1298                        self.run_ingestion(id)?;
1299                    }
1300                }
1301                DataSource::IngestionExport { .. } => unreachable!(
1302                    "ingestion exports do not execute directly, but instead schedule their source to be re-executed"
1303                ),
1304                DataSource::Introspection(_)
1305                | DataSource::Webhook
1306                | DataSource::Table
1307                | DataSource::Progress
1308                | DataSource::Other => {}
1309                DataSource::Sink { .. } => {
1310                    if !self.read_only {
1311                        self.run_export(id)?;
1312                    }
1313                }
1314            };
1315        }
1316
1317        Ok(())
1318    }
1319
1320    fn check_alter_ingestion_source_desc(
1321        &mut self,
1322        ingestion_id: GlobalId,
1323        source_desc: &SourceDesc,
1324    ) -> Result<(), StorageError> {
1325        let source_collection = self.collection(ingestion_id)?;
1326        let data_source = &source_collection.data_source;
1327        match &data_source {
1328            DataSource::Ingestion(cur_ingestion) => {
1329                cur_ingestion
1330                    .desc
1331                    .alter_compatible(ingestion_id, source_desc)?;
1332            }
1333            o => {
1334                tracing::info!(
1335                    "{ingestion_id} inalterable because its data source is {:?} and not an ingestion",
1336                    o
1337                );
1338                Err(AlterError { id: ingestion_id })?
1339            }
1340        }
1341
1342        Ok(())
1343    }
1344
1345    async fn alter_ingestion_source_desc(
1346        &mut self,
1347        ingestion_ids: BTreeMap<GlobalId, SourceDesc>,
1348    ) -> Result<(), StorageError> {
1349        let mut ingestions_to_run = BTreeSet::new();
1350
1351        for (id, new_desc) in ingestion_ids {
1352            let collection = self
1353                .collections
1354                .get_mut(&id)
1355                .ok_or_else(|| StorageError::IdentifierMissing(id))?;
1356
1357            match &mut collection.data_source {
1358                DataSource::Ingestion(ingestion) => {
1359                    if ingestion.desc != new_desc {
1360                        tracing::info!(
1361                            from = ?ingestion.desc,
1362                            to = ?new_desc,
1363                            "alter_ingestion_source_desc, updating"
1364                        );
1365                        ingestion.desc = new_desc;
1366                        ingestions_to_run.insert(id);
1367                    }
1368                }
1369                o => {
1370                    tracing::warn!("alter_ingestion_source_desc called on {:?}", o);
1371                    Err(StorageError::IdentifierInvalid(id))?;
1372                }
1373            }
1374        }
1375
1376        for id in ingestions_to_run {
1377            self.run_ingestion(id)?;
1378        }
1379        Ok(())
1380    }
1381
1382    async fn alter_ingestion_connections(
1383        &mut self,
1384        source_connections: BTreeMap<GlobalId, GenericSourceConnection<InlinedConnection>>,
1385    ) -> Result<(), StorageError> {
1386        let mut ingestions_to_run = BTreeSet::new();
1387
1388        for (id, conn) in source_connections {
1389            let collection = self
1390                .collections
1391                .get_mut(&id)
1392                .ok_or_else(|| StorageError::IdentifierMissing(id))?;
1393
1394            match &mut collection.data_source {
1395                DataSource::Ingestion(ingestion) => {
1396                    // If the connection hasn't changed, there's no sense in
1397                    // re-rendering the dataflow.
1398                    if ingestion.desc.connection != conn {
1399                        tracing::info!(from = ?ingestion.desc.connection, to = ?conn, "alter_ingestion_connections, updating");
1400                        ingestion.desc.connection = conn;
1401                        ingestions_to_run.insert(id);
1402                    } else {
1403                        tracing::warn!(
1404                            "update_source_connection called on {id} but the \
1405                            connection was the same"
1406                        );
1407                    }
1408                }
1409                o => {
1410                    tracing::warn!("update_source_connection called on {:?}", o);
1411                    Err(StorageError::IdentifierInvalid(id))?;
1412                }
1413            }
1414        }
1415
1416        for id in ingestions_to_run {
1417            self.run_ingestion(id)?;
1418        }
1419        Ok(())
1420    }
1421
1422    async fn alter_ingestion_export_data_configs(
1423        &mut self,
1424        source_exports: BTreeMap<GlobalId, SourceExportDataConfig>,
1425    ) -> Result<(), StorageError> {
1426        let mut ingestions_to_run = BTreeSet::new();
1427
1428        for (source_export_id, new_data_config) in source_exports {
1429            // We need to adjust the data config on the CollectionState for
1430            // the source export collection directly
1431            let source_export_collection = self
1432                .collections
1433                .get_mut(&source_export_id)
1434                .ok_or_else(|| StorageError::IdentifierMissing(source_export_id))?;
1435            let ingestion_id = match &mut source_export_collection.data_source {
1436                DataSource::IngestionExport {
1437                    ingestion_id,
1438                    details: _,
1439                    data_config,
1440                } => {
1441                    *data_config = new_data_config.clone();
1442                    *ingestion_id
1443                }
1444                o => {
1445                    tracing::warn!("alter_ingestion_export_data_configs called on {:?}", o);
1446                    Err(StorageError::IdentifierInvalid(source_export_id))?
1447                }
1448            };
1449            // We also need to adjust the data config on the CollectionState of the
1450            // Ingestion that the export is associated with.
1451            let ingestion_collection = self
1452                .collections
1453                .get_mut(&ingestion_id)
1454                .ok_or_else(|| StorageError::IdentifierMissing(ingestion_id))?;
1455
1456            match &mut ingestion_collection.data_source {
1457                DataSource::Ingestion(ingestion_desc) => {
1458                    let source_export = ingestion_desc
1459                        .source_exports
1460                        .get_mut(&source_export_id)
1461                        .ok_or_else(|| StorageError::IdentifierMissing(source_export_id))?;
1462
1463                    // If the data config hasn't changed, there's no sense in
1464                    // re-rendering the dataflow.
1465                    if source_export.data_config != new_data_config {
1466                        tracing::info!(?source_export_id, from = ?source_export.data_config, to = ?new_data_config, "alter_ingestion_export_data_configs, updating");
1467                        source_export.data_config = new_data_config;
1468
1469                        ingestions_to_run.insert(ingestion_id);
1470                    } else {
1471                        tracing::warn!(
1472                            "alter_ingestion_export_data_configs called on \
1473                                    export {source_export_id} of {ingestion_id} but \
1474                                    the data config was the same"
1475                        );
1476                    }
1477                }
1478                o => {
1479                    tracing::warn!("alter_ingestion_export_data_configs called on {:?}", o);
1480                    Err(StorageError::IdentifierInvalid(ingestion_id))?
1481                }
1482            }
1483        }
1484
1485        for id in ingestions_to_run {
1486            self.run_ingestion(id)?;
1487        }
1488        Ok(())
1489    }
1490
1491    async fn alter_table_desc(
1492        &mut self,
1493        existing_collection: GlobalId,
1494        new_collection: GlobalId,
1495        new_desc: RelationDesc,
1496        expected_version: RelationVersion,
1497    ) -> Result<(), StorageError> {
1498        let data_shard = {
1499            let Controller {
1500                collections,
1501                storage_collections,
1502                ..
1503            } = self;
1504
1505            let existing = collections
1506                .get(&existing_collection)
1507                .ok_or(StorageError::IdentifierMissing(existing_collection))?;
1508            if existing.data_source != DataSource::Table {
1509                return Err(StorageError::IdentifierInvalid(existing_collection));
1510            }
1511
1512            // Let StorageCollections know!
1513            storage_collections
1514                .alter_table_desc(
1515                    existing_collection,
1516                    new_collection,
1517                    new_desc.clone(),
1518                    expected_version,
1519                )
1520                .await?;
1521
1522            existing.collection_metadata.data_shard.clone()
1523        };
1524
1525        let collection_meta = CollectionMetadata {
1526            persist_location: self.persist_location.clone(),
1527            data_shard,
1528            relation_desc: new_desc.clone(),
1529            // TODO(alter_table): Support schema evolution on sources.
1530            txns_shard: Some(self.txns_read.txns_id().clone()),
1531        };
1532        // TODO(alter_table): Support schema evolution on sources.
1533        let wallclock_lag_metrics = self.metrics.wallclock_lag_metrics(new_collection, None);
1534        let collection_state = CollectionState::new(
1535            DataSource::Table,
1536            collection_meta,
1537            CollectionStateExtra::None,
1538            wallclock_lag_metrics,
1539        );
1540
1541        // Great! We have successfully evolved the schema of our Table, now we need to update our
1542        // in-memory data structures.
1543        self.collections.insert(new_collection, collection_state);
1544
1545        self.append_shard_mappings([new_collection].into_iter(), Diff::ONE);
1546
1547        Ok(())
1548    }
1549
1550    async fn register_table_collections(
1551        &mut self,
1552        register_ts: Timestamp,
1553        ids: Vec<GlobalId>,
1554    ) -> Result<(), StorageError> {
1555        let mut tables = self.table_registrations(ids)?;
1556
1557        // A read-only deployment only writes its migrated builtin tables.
1558        if self.read_only {
1559            tables.retain(|table| self.migrated_storage_collections.contains(&table.id));
1560        }
1561        if tables.is_empty() {
1562            return Ok(());
1563        }
1564
1565        match self
1566            .persist_table_worker
1567            .register(register_ts, tables)
1568            .await
1569        {
1570            Ok(res) => res,
1571            Err(_recv) => Err(StorageError::ShuttingDown("persist_table_worker")),
1572        }
1573    }
1574
1575    fn table_registrations(
1576        &self,
1577        ids: Vec<GlobalId>,
1578    ) -> Result<Vec<TableRegistration>, StorageError> {
1579        // The storage data source decides which table catalog items use txn-wal.
1580        let mut tables = Vec::with_capacity(ids.len());
1581        for id in ids {
1582            let collection = self.collection(id)?;
1583            if matches!(collection.data_source, DataSource::Table) {
1584                let metadata = &collection.collection_metadata;
1585                tables.push(TableRegistration {
1586                    id,
1587                    data_shard: metadata.data_shard,
1588                    relation_desc: metadata.relation_desc.clone(),
1589                });
1590            }
1591        }
1592        Ok(tables)
1593    }
1594
1595    fn txns_table_ids(&self, ids: Vec<GlobalId>) -> Result<Vec<GlobalId>, StorageError> {
1596        let mut tables = Vec::with_capacity(ids.len());
1597        for id in ids {
1598            let collection = self.collection(id)?;
1599            if matches!(collection.data_source, DataSource::Table) {
1600                tables.push(id);
1601            }
1602        }
1603        Ok(tables)
1604    }
1605
1606    fn export(&self, id: GlobalId) -> Result<&ExportState, StorageError> {
1607        self.collections
1608            .get(&id)
1609            .and_then(|c| match &c.extra_state {
1610                CollectionStateExtra::Export(state) => Some(state),
1611                _ => None,
1612            })
1613            .ok_or(StorageError::IdentifierMissing(id))
1614    }
1615
1616    fn export_mut(&mut self, id: GlobalId) -> Result<&mut ExportState, StorageError> {
1617        self.collections
1618            .get_mut(&id)
1619            .and_then(|c| match &mut c.extra_state {
1620                CollectionStateExtra::Export(state) => Some(state),
1621                _ => None,
1622            })
1623            .ok_or(StorageError::IdentifierMissing(id))
1624    }
1625
1626    /// Create a oneshot ingestion.
1627    async fn create_oneshot_ingestion(
1628        &mut self,
1629        ingestion_id: uuid::Uuid,
1630        collection_id: GlobalId,
1631        instance_id: StorageInstanceId,
1632        request: OneshotIngestionRequest,
1633        result_tx: OneshotResultCallback<ProtoBatch>,
1634    ) -> Result<(), StorageError> {
1635        let collection_meta = self
1636            .collections
1637            .get(&collection_id)
1638            .ok_or_else(|| StorageError::IdentifierMissing(collection_id))?
1639            .collection_metadata
1640            .clone();
1641        let instance = self.instances.get_mut(&instance_id).ok_or_else(|| {
1642            // TODO(cf2): Refine this error.
1643            StorageError::Generic(anyhow::anyhow!("missing cluster {instance_id}"))
1644        })?;
1645        let oneshot_cmd = RunOneshotIngestion {
1646            ingestion_id,
1647            collection_id,
1648            collection_meta,
1649            request,
1650        };
1651
1652        if !self.read_only {
1653            instance.send(StorageCommand::RunOneshotIngestion(Box::new(oneshot_cmd)));
1654            let pending = PendingOneshotIngestion {
1655                result_tx,
1656                cluster_id: instance_id,
1657            };
1658            let novel = self
1659                .pending_oneshot_ingestions
1660                .insert(ingestion_id, pending);
1661            assert_none!(novel);
1662            Ok(())
1663        } else {
1664            Err(StorageError::ReadOnly)
1665        }
1666    }
1667
1668    fn cancel_oneshot_ingestion(&mut self, ingestion_id: uuid::Uuid) -> Result<(), StorageError> {
1669        if self.read_only {
1670            return Err(StorageError::ReadOnly);
1671        }
1672
1673        let pending = self
1674            .pending_oneshot_ingestions
1675            .remove(&ingestion_id)
1676            .ok_or_else(|| {
1677                // TODO(cf2): Refine this error.
1678                StorageError::Generic(anyhow::anyhow!("missing oneshot ingestion {ingestion_id}"))
1679            })?;
1680
1681        match self.instances.get_mut(&pending.cluster_id) {
1682            Some(instance) => {
1683                instance.send(StorageCommand::CancelOneshotIngestion(ingestion_id));
1684            }
1685            None => {
1686                mz_ore::soft_panic_or_log!(
1687                    "canceling oneshot ingestion on non-existent cluster, ingestion {:?}, instance {}",
1688                    ingestion_id,
1689                    pending.cluster_id,
1690                );
1691            }
1692        }
1693        // Respond to the user that the request has been canceled.
1694        pending.cancel();
1695
1696        Ok(())
1697    }
1698
1699    async fn alter_export(
1700        &mut self,
1701        id: GlobalId,
1702        new_description: ExportDescription,
1703    ) -> Result<(), StorageError> {
1704        let from_id = new_description.sink.from;
1705
1706        // Acquire read holds at StorageCollections to ensure that the
1707        // sinked collection is not dropped while we're sinking it.
1708        let desired_read_holds = vec![from_id.clone(), id.clone()];
1709        let [input_hold, self_hold] = self
1710            .storage_collections
1711            .acquire_read_holds(desired_read_holds)
1712            .expect("missing dependency")
1713            .try_into()
1714            .expect("expected number of holds");
1715        let from_storage_metadata = self.storage_collections.collection_metadata(from_id)?;
1716        let to_storage_metadata = self.storage_collections.collection_metadata(id)?;
1717
1718        // Check whether the sink's write frontier is beyond the read hold we got
1719        let cur_export = self.export_mut(id)?;
1720        let input_readable = cur_export
1721            .write_frontier
1722            .iter()
1723            .all(|t| input_hold.since().less_than(t));
1724        if !input_readable {
1725            return Err(StorageError::ReadBeforeSince(from_id));
1726        }
1727
1728        let new_export = ExportState {
1729            read_capabilities: cur_export.read_capabilities.clone(),
1730            cluster_id: new_description.instance_id,
1731            derived_since: cur_export.derived_since.clone(),
1732            read_holds: [input_hold, self_hold],
1733            read_policy: cur_export.read_policy.clone(),
1734            write_frontier: cur_export.write_frontier.clone(),
1735        };
1736        *cur_export = new_export;
1737
1738        // For `ALTER SINK`, the snapshot should only occur if the sink has not made any progress.
1739        // This prevents unnecessary decoding in the sink.
1740        // If the write frontier of the sink is strictly larger than its read hold, it must have at
1741        // least written out its snapshot, and we can skip reading it; otherwise assume we may have
1742        // to replay from the beginning.
1743        // TODO(SS-513): unify this with run_export, if possible
1744        let with_snapshot = new_description.sink.with_snapshot
1745            && !PartialOrder::less_than(&new_description.sink.as_of, &cur_export.write_frontier);
1746
1747        let cmd = RunSinkCommand {
1748            id,
1749            description: StorageSinkDesc {
1750                from: from_id,
1751                from_desc: new_description.sink.from_desc.clone(),
1752                connection: new_description.sink.connection.clone(),
1753                envelope: new_description.sink.envelope,
1754                as_of: new_description.sink.as_of.clone(),
1755                version: new_description.sink.version,
1756                from_storage_metadata,
1757                with_snapshot,
1758                to_storage_metadata,
1759                commit_interval: new_description.sink.commit_interval,
1760            },
1761        };
1762
1763        // Fetch the client for this export's cluster.
1764        let instance = self
1765            .instances
1766            .get_mut(&new_description.instance_id)
1767            .ok_or_else(|| StorageError::ExportInstanceMissing {
1768                storage_instance_id: new_description.instance_id,
1769                export_id: id,
1770            })?;
1771
1772        instance.send(StorageCommand::RunSink(Box::new(cmd)));
1773
1774        // alter_export_connections rebuilds the sink from this description and
1775        // checks new connections against it with alter_compatible, so it must
1776        // describe the sink we just told the cluster to run.
1777        let state = self
1778            .collections
1779            .get_mut(&id)
1780            .expect("export known to exist");
1781        let DataSource::Sink { desc } = &mut state.data_source else {
1782            panic!("export known to exist")
1783        };
1784        *desc = new_description;
1785
1786        Ok(())
1787    }
1788
1789    /// Create the sinks described by the `ExportDescription`.
1790    async fn alter_export_connections(
1791        &mut self,
1792        exports: BTreeMap<GlobalId, StorageSinkConnection>,
1793    ) -> Result<(), StorageError> {
1794        let mut updates_by_instance =
1795            BTreeMap::<StorageInstanceId, Vec<(RunSinkCommand, ExportDescription)>>::new();
1796
1797        for (id, connection) in exports {
1798            // We stage changes in new_export_description and then apply all
1799            // updates to exports at the end.
1800            //
1801            // We don't just go ahead and clone the `ExportState` itself and
1802            // update that because `ExportState` is not clone, because it holds
1803            // a `ReadHandle` and cloning that would cause additional work for
1804            // whoever guarantees those read holds.
1805            let (current_export_description, as_of): (ExportDescription, _) = {
1806                let export = &self.collections[&id];
1807                let DataSource::Sink { desc } = &export.data_source else {
1808                    panic!("export exists")
1809                };
1810                let CollectionStateExtra::Export(state) = &export.extra_state else {
1811                    panic!("export exists")
1812                };
1813                let export_description = desc.clone();
1814                let as_of = state.input_hold().since().clone();
1815
1816                (export_description, as_of)
1817            };
1818
1819            let mut new_export_description = current_export_description.clone();
1820
1821            new_export_description.sink.connection = connection;
1822
1823            // Ensure compatibility
1824            current_export_description
1825                .sink
1826                .alter_compatible(id, &new_export_description.sink)?;
1827
1828            let from_storage_metadata = self
1829                .storage_collections
1830                .collection_metadata(new_export_description.sink.from)?;
1831            let to_storage_metadata = self.storage_collections.collection_metadata(id)?;
1832
1833            let cmd = RunSinkCommand {
1834                id,
1835                description: StorageSinkDesc {
1836                    from: new_export_description.sink.from,
1837                    from_desc: new_export_description.sink.from_desc.clone(),
1838                    connection: new_export_description.sink.connection.clone(),
1839                    envelope: new_export_description.sink.envelope,
1840                    with_snapshot: new_export_description.sink.with_snapshot,
1841                    version: new_export_description.sink.version,
1842                    // Here we are about to send a RunSinkCommand with the current read capaibility
1843                    // held by this sink. However, clusters are already running a version of the
1844                    // sink and nothing guarantees that by the time this command arrives at the
1845                    // clusters they won't have made additional progress such that this read
1846                    // capability is invalidated.
1847                    // The solution to this problem is for the controller to track specific
1848                    // executions of dataflows such that it can track the shutdown of the current
1849                    // instance and the initialization of the new instance separately and ensure
1850                    // read holds are held for the correct amount of time.
1851                    // TODO(petrosagg): change the controller to explicitly track dataflow executions
1852                    as_of: as_of.to_owned(),
1853                    from_storage_metadata,
1854                    to_storage_metadata,
1855                    commit_interval: new_export_description.sink.commit_interval,
1856                },
1857            };
1858
1859            let update = updates_by_instance
1860                .entry(new_export_description.instance_id)
1861                .or_default();
1862            update.push((cmd, new_export_description));
1863        }
1864
1865        for (instance_id, updates) in updates_by_instance {
1866            let mut export_updates = BTreeMap::new();
1867            let mut cmds = Vec::with_capacity(updates.len());
1868
1869            for (cmd, export_state) in updates {
1870                export_updates.insert(cmd.id, export_state);
1871                cmds.push(cmd);
1872            }
1873
1874            // Fetch the client for this exports's cluster.
1875            let instance = self.instances.get_mut(&instance_id).ok_or_else(|| {
1876                StorageError::ExportInstanceMissing {
1877                    storage_instance_id: instance_id,
1878                    export_id: *export_updates
1879                        .keys()
1880                        .next()
1881                        .expect("set of exports not empty"),
1882                }
1883            })?;
1884
1885            for cmd in cmds {
1886                instance.send(StorageCommand::RunSink(Box::new(cmd)));
1887            }
1888
1889            // Update state only after all possible errors have occurred.
1890            for (id, new_export_description) in export_updates {
1891                let Some(state) = self.collections.get_mut(&id) else {
1892                    panic!("export known to exist")
1893                };
1894                let DataSource::Sink { desc } = &mut state.data_source else {
1895                    panic!("export known to exist")
1896                };
1897                *desc = new_export_description;
1898            }
1899        }
1900
1901        Ok(())
1902    }
1903
1904    fn drop_tables(
1905        &mut self,
1906        storage_metadata: &StorageMetadata,
1907        identifiers: Vec<GlobalId>,
1908    ) -> Result<(), StorageError> {
1909        let (table_write_ids, data_source_ids): (Vec<_>, Vec<_>) = identifiers
1910            .into_iter()
1911            .partition(|id| match self.collections[id].data_source {
1912                DataSource::Table => true,
1913                DataSource::IngestionExport { .. } | DataSource::Webhook => false,
1914                _ => panic!("identifier is not a table: {}", id),
1915            });
1916
1917        if table_write_ids.len() > 0 {
1918            let tx = self.pending_table_handle_drops_tx.clone();
1919            for identifier in table_write_ids {
1920                let _ = tx.send(identifier);
1921            }
1922        }
1923
1924        if data_source_ids.len() > 0 {
1925            self.validate_collection_ids(data_source_ids.iter().cloned())?;
1926            self.drop_sources_unvalidated(storage_metadata, data_source_ids)?;
1927        }
1928
1929        Ok(())
1930    }
1931
1932    fn drop_sources(
1933        &mut self,
1934        storage_metadata: &StorageMetadata,
1935        identifiers: Vec<GlobalId>,
1936    ) -> Result<(), StorageError> {
1937        self.validate_collection_ids(identifiers.iter().cloned())?;
1938        self.drop_sources_unvalidated(storage_metadata, identifiers)
1939    }
1940
1941    fn drop_sources_unvalidated(
1942        &mut self,
1943        storage_metadata: &StorageMetadata,
1944        ids: Vec<GlobalId>,
1945    ) -> Result<(), StorageError> {
1946        // Keep track of which ingestions we have to execute still, and which we
1947        // have to change because of dropped subsources.
1948        let mut ingestions_to_execute = BTreeSet::new();
1949        let mut ingestions_to_drop = BTreeSet::new();
1950        let mut source_statistics_to_drop = Vec::new();
1951
1952        // Ingestions (and their exports) are also collections, but we keep
1953        // track of non-ingestion collections separately, because they have
1954        // slightly different cleanup logic below.
1955        let mut collections_to_drop = Vec::new();
1956
1957        for id in ids.iter() {
1958            let collection_state = self.collections.get(id);
1959
1960            if let Some(collection_state) = collection_state {
1961                match collection_state.data_source {
1962                    DataSource::Webhook => {
1963                        // TODO(parkmycar): The Collection Manager and PersistMonotonicWriter
1964                        // could probably use some love and maybe get merged together?
1965                        let fut = self.collection_manager.unregister_collection(*id);
1966                        mz_ore::task::spawn(|| format!("storage-webhook-cleanup-{id}"), fut);
1967
1968                        collections_to_drop.push(*id);
1969                        source_statistics_to_drop.push(*id);
1970                    }
1971                    DataSource::Ingestion(_) => {
1972                        ingestions_to_drop.insert(*id);
1973                        source_statistics_to_drop.push(*id);
1974                    }
1975                    DataSource::IngestionExport { ingestion_id, .. } => {
1976                        // If we are dropping source exports, we need to modify the
1977                        // ingestion that it runs on.
1978                        //
1979                        // If we remove this export, we need to stop producing data to
1980                        // it, so plan to re-execute the ingestion with the amended
1981                        // description.
1982                        ingestions_to_execute.insert(ingestion_id);
1983
1984                        // Adjust the source to remove this export.
1985                        let ingestion_state = match self.collections.get_mut(&ingestion_id) {
1986                            Some(ingestion_collection) => ingestion_collection,
1987                            // Primary ingestion already dropped.
1988                            None => {
1989                                tracing::error!(
1990                                    "primary source {ingestion_id} seemingly dropped before subsource {id}"
1991                                );
1992                                continue;
1993                            }
1994                        };
1995
1996                        match &mut ingestion_state.data_source {
1997                            DataSource::Ingestion(ingestion_desc) => {
1998                                let removed = ingestion_desc.source_exports.remove(id);
1999                                mz_ore::soft_assert_or_log!(
2000                                    removed.is_some(),
2001                                    "dropped subsource {id} already removed from source exports"
2002                                );
2003                            }
2004                            _ => unreachable!(
2005                                "SourceExport must only refer to primary sources that already exist"
2006                            ),
2007                        };
2008
2009                        // Ingestion exports also have ReadHolds that we need to
2010                        // downgrade, and much of their drop machinery is the
2011                        // same as for the "main" ingestion.
2012                        ingestions_to_drop.insert(*id);
2013                        source_statistics_to_drop.push(*id);
2014                    }
2015                    DataSource::Progress | DataSource::Table | DataSource::Other => {
2016                        collections_to_drop.push(*id);
2017                    }
2018                    DataSource::Introspection(_) | DataSource::Sink { .. } => {
2019                        // Collections of these types are either not sources and should be dropped
2020                        // through other means, or are sources but should never be dropped.
2021                        soft_panic_or_log!(
2022                            "drop_sources called on a {:?} (id={id}))",
2023                            collection_state.data_source,
2024                        );
2025                    }
2026                }
2027            }
2028        }
2029
2030        // Do not bother re-executing ingestions we know we plan to drop.
2031        ingestions_to_execute.retain(|id| !ingestions_to_drop.contains(id));
2032        for ingestion_id in ingestions_to_execute {
2033            self.run_ingestion(ingestion_id)?;
2034        }
2035
2036        // For ingestions, we fabricate a new hold that will propagate through
2037        // the cluster and then back to us.
2038
2039        // We don't explicitly remove read capabilities! Downgrading the
2040        // frontier of the source to `[]` (the empty Antichain), will propagate
2041        // to the storage dependencies.
2042        let ingestion_policies = ingestions_to_drop
2043            .iter()
2044            .map(|id| (*id, ReadPolicy::ValidFrom(Antichain::new())))
2045            .collect();
2046
2047        tracing::debug!(
2048            ?ingestion_policies,
2049            "dropping sources by setting read hold policies"
2050        );
2051        self.set_hold_policies(ingestion_policies);
2052
2053        // Delete all collection->shard mappings
2054        let shards_to_update: BTreeSet<_> = ingestions_to_drop
2055            .iter()
2056            .chain(collections_to_drop.iter())
2057            .cloned()
2058            .collect();
2059        self.append_shard_mappings(shards_to_update.into_iter(), Diff::MINUS_ONE);
2060
2061        let status_now = mz_ore::now::to_datetime((self.now)());
2062        let mut status_updates = vec![];
2063        for id in ingestions_to_drop.iter() {
2064            status_updates.push(StatusUpdate::new(*id, status_now, Status::Dropped));
2065        }
2066
2067        if !self.read_only {
2068            self.append_status_introspection_updates(
2069                IntrospectionType::SourceStatusHistory,
2070                status_updates,
2071            );
2072        }
2073
2074        {
2075            let mut source_statistics = self.source_statistics.lock().expect("poisoned");
2076            for id in source_statistics_to_drop {
2077                source_statistics
2078                    .source_statistics
2079                    .retain(|(stats_id, _), _| stats_id != &id);
2080                source_statistics
2081                    .webhook_statistics
2082                    .retain(|stats_id, _| stats_id != &id);
2083            }
2084        }
2085
2086        // Remove collection state
2087        for id in ingestions_to_drop.iter().chain(collections_to_drop.iter()) {
2088            tracing::info!(%id, "dropping collection state");
2089            let collection = self
2090                .collections
2091                .remove(id)
2092                .expect("list populated after checking that self.collections contains it");
2093
2094            let instance = match &collection.extra_state {
2095                CollectionStateExtra::Ingestion(ingestion) => Some(ingestion.instance_id),
2096                CollectionStateExtra::Export(export) => Some(export.cluster_id()),
2097                CollectionStateExtra::None => None,
2098            }
2099            .and_then(|i| self.instances.get(&i));
2100
2101            // Record which replicas were running a collection, so that we can
2102            // match DroppedId messages against them and eventually remove state
2103            // from self.dropped_objects
2104            if let Some(instance) = instance {
2105                let active_replicas = instance.get_active_replicas_for_object(id);
2106                if !active_replicas.is_empty() {
2107                    // The remap collection of an ingestion doesn't have extra
2108                    // state and doesn't have an instance_id, but we still get
2109                    // upper updates for them, so want to make sure to populate
2110                    // dropped_ids.
2111                    // TODO(aljoscha): All this is a bit icky. But here we are
2112                    // for now...
2113                    match &collection.data_source {
2114                        DataSource::Ingestion(ingestion_desc) => {
2115                            if *id != ingestion_desc.remap_collection_id {
2116                                self.dropped_objects.insert(
2117                                    ingestion_desc.remap_collection_id,
2118                                    active_replicas.clone(),
2119                                );
2120                            }
2121                        }
2122                        _ => {}
2123                    }
2124
2125                    self.dropped_objects.insert(*id, active_replicas);
2126                }
2127            }
2128        }
2129
2130        // Also let StorageCollections know!
2131        self.storage_collections
2132            .drop_collections_unvalidated(storage_metadata, ids);
2133
2134        Ok(())
2135    }
2136
2137    /// Drops the read capability for the sinks and allows their resources to be reclaimed.
2138    fn drop_sinks(
2139        &mut self,
2140        storage_metadata: &StorageMetadata,
2141        identifiers: Vec<GlobalId>,
2142    ) -> Result<(), StorageError> {
2143        self.validate_export_ids(identifiers.iter().cloned())?;
2144        self.drop_sinks_unvalidated(storage_metadata, identifiers);
2145        Ok(())
2146    }
2147
2148    fn drop_sinks_unvalidated(
2149        &mut self,
2150        storage_metadata: &StorageMetadata,
2151        mut sinks_to_drop: Vec<GlobalId>,
2152    ) {
2153        // Ignore exports that have already been removed.
2154        sinks_to_drop.retain(|id| self.export(*id).is_ok());
2155
2156        // TODO: ideally we'd advance the write frontier ourselves here, but this function's
2157        // not yet marked async.
2158
2159        // We don't explicitly remove read capabilities! Downgrading the
2160        // frontier of the source to `[]` (the empty Antichain), will propagate
2161        // to the storage dependencies.
2162        let drop_policy = sinks_to_drop
2163            .iter()
2164            .map(|id| (*id, ReadPolicy::ValidFrom(Antichain::new())))
2165            .collect();
2166
2167        tracing::debug!(
2168            ?drop_policy,
2169            "dropping sources by setting read hold policies"
2170        );
2171        self.set_hold_policies(drop_policy);
2172
2173        // Record the drop status for all sink drops.
2174        //
2175        // We also delete the items' statistics objects.
2176        //
2177        // The locks are held for a short time, only while we do some removals from a map.
2178
2179        let status_now = mz_ore::now::to_datetime((self.now)());
2180
2181        // Record the drop status for all pending sink drops.
2182        let mut status_updates = vec![];
2183        {
2184            let mut sink_statistics = self.sink_statistics.lock().expect("poisoned");
2185            for id in sinks_to_drop.iter() {
2186                status_updates.push(StatusUpdate::new(*id, status_now, Status::Dropped));
2187                sink_statistics.retain(|(stats_id, _), _| stats_id != id);
2188            }
2189        }
2190
2191        if !self.read_only {
2192            self.append_status_introspection_updates(
2193                IntrospectionType::SinkStatusHistory,
2194                status_updates,
2195            );
2196        }
2197
2198        // Remove collection/export state
2199        for id in sinks_to_drop.iter() {
2200            tracing::info!(%id, "dropping export state");
2201            let collection = self
2202                .collections
2203                .remove(id)
2204                .expect("list populated after checking that self.collections contains it");
2205
2206            let instance = match &collection.extra_state {
2207                CollectionStateExtra::Ingestion(ingestion) => Some(ingestion.instance_id),
2208                CollectionStateExtra::Export(export) => Some(export.cluster_id()),
2209                CollectionStateExtra::None => None,
2210            }
2211            .and_then(|i| self.instances.get(&i));
2212
2213            // Record how many replicas were running an export, so that we can
2214            // match `DroppedId` messages against it and eventually remove state
2215            // from `self.dropped_objects`.
2216            if let Some(instance) = instance {
2217                let active_replicas = instance.get_active_replicas_for_object(id);
2218                if !active_replicas.is_empty() {
2219                    self.dropped_objects.insert(*id, active_replicas);
2220                }
2221            }
2222        }
2223
2224        // Also let StorageCollections know!
2225        self.storage_collections
2226            .drop_collections_unvalidated(storage_metadata, sinks_to_drop);
2227    }
2228
2229    #[instrument(level = "debug")]
2230    fn append_table(
2231        &mut self,
2232        write_ts: Timestamp,
2233        advance_to: Timestamp,
2234        commands: Vec<(GlobalId, Vec<TableData>)>,
2235    ) -> Result<tokio::sync::oneshot::Receiver<Result<(), StorageError>>, StorageError> {
2236        if self.read_only {
2237            // While in read only mode, ONLY collections that have been migrated
2238            // and need to be re-hydrated in read only mode can be written to.
2239            if !commands
2240                .iter()
2241                .all(|(id, _)| id.is_system() && self.migrated_storage_collections.contains(id))
2242            {
2243                return Err(StorageError::ReadOnly);
2244            }
2245        }
2246
2247        // TODO(petrosagg): validate appends against the expected RelationDesc of the collection
2248        for (id, updates) in commands.iter() {
2249            if !updates.is_empty() {
2250                if !write_ts.less_than(&advance_to) {
2251                    return Err(StorageError::UpdateBeyondUpper(*id));
2252                }
2253            }
2254        }
2255
2256        Ok(self
2257            .persist_table_worker
2258            .append(write_ts, advance_to, commands))
2259    }
2260
2261    fn table_write_handle(&self) -> Arc<dyn mz_storage_client::controller::TableWriteHandle> {
2262        Arc::new(persist_handles::TableWriteWorkerHandle(
2263            self.persist_table_worker.clone(),
2264        ))
2265    }
2266
2267    fn monotonic_appender(&self, id: GlobalId) -> Result<MonotonicAppender, StorageError> {
2268        self.collection_manager.monotonic_appender(id)
2269    }
2270
2271    fn webhook_statistics(&self, id: GlobalId) -> Result<Arc<WebhookStatistics>, StorageError> {
2272        // Call to this method are usually cached so the lock is not in the critical path.
2273        let source_statistics = self.source_statistics.lock().expect("poisoned");
2274        source_statistics
2275            .webhook_statistics
2276            .get(&id)
2277            .cloned()
2278            .ok_or(StorageError::IdentifierMissing(id))
2279    }
2280
2281    async fn ready(&mut self) {
2282        if self.maintenance_scheduled {
2283            return;
2284        }
2285
2286        if !self.pending_table_handle_drops_rx.is_empty() {
2287            return;
2288        }
2289
2290        tokio::select! {
2291            Some(m) = self.instance_response_rx.recv() => {
2292                self.stashed_responses.push(m);
2293                while let Ok(m) = self.instance_response_rx.try_recv() {
2294                    self.stashed_responses.push(m);
2295                }
2296            }
2297            _ = self.maintenance_ticker.tick() => {
2298                self.maintenance_scheduled = true;
2299            },
2300        };
2301    }
2302
2303    #[instrument(level = "debug")]
2304    fn process(
2305        &mut self,
2306        storage_metadata: &StorageMetadata,
2307    ) -> Result<Option<Response>, anyhow::Error> {
2308        // Perform periodic maintenance work.
2309        if self.maintenance_scheduled {
2310            self.maintain();
2311            self.maintenance_scheduled = false;
2312        }
2313
2314        for instance in self.instances.values_mut() {
2315            instance.rehydrate_failed_replicas();
2316        }
2317
2318        let mut status_updates = vec![];
2319        let mut updated_frontiers = BTreeMap::new();
2320
2321        // Take the currently stashed responses so that we can call mut receiver functions in the loop.
2322        let stashed_responses = std::mem::take(&mut self.stashed_responses);
2323        for resp in stashed_responses {
2324            match resp {
2325                (_replica_id, StorageResponse::FrontierUpper(id, upper)) => {
2326                    self.update_write_frontier(id, &upper);
2327                    updated_frontiers.insert(id, upper);
2328                }
2329                (replica_id, StorageResponse::DroppedId(id)) => {
2330                    let replica_id = replica_id.expect("DroppedId from unknown replica");
2331                    if let Some(remaining_replicas) = self.dropped_objects.get_mut(&id) {
2332                        remaining_replicas.remove(&replica_id);
2333                        if remaining_replicas.is_empty() {
2334                            self.dropped_objects.remove(&id);
2335                        }
2336                    } else {
2337                        soft_panic_or_log!("unexpected DroppedId for {id}");
2338                    }
2339                }
2340                (replica_id, StorageResponse::StatisticsUpdates(source_stats, sink_stats)) => {
2341                    // Note we only hold the locks while moving some plain-old-data around here.
2342                    {
2343                        // NOTE(aljoscha): We explicitly unwrap the `Option`,
2344                        // because we expect that stats coming from replicas
2345                        // have a replica id.
2346                        //
2347                        // If this is `None` and we would use that to access
2348                        // state below we might clobber something unexpectedly.
2349                        let replica_id = if let Some(replica_id) = replica_id {
2350                            replica_id
2351                        } else {
2352                            tracing::error!(
2353                                ?source_stats,
2354                                "missing replica_id for source statistics update"
2355                            );
2356                            continue;
2357                        };
2358
2359                        let mut shared_stats = self.source_statistics.lock().expect("poisoned");
2360
2361                        for stat in source_stats {
2362                            let collection_id = stat.id.clone();
2363
2364                            if self.collection(collection_id).is_err() {
2365                                // We can get updates for collections that have
2366                                // already been deleted, ignore those.
2367                                continue;
2368                            }
2369
2370                            let entry = shared_stats
2371                                .source_statistics
2372                                .entry((stat.id, Some(replica_id)));
2373
2374                            match entry {
2375                                btree_map::Entry::Vacant(vacant_entry) => {
2376                                    let mut stats = ControllerSourceStatistics::new(
2377                                        collection_id,
2378                                        Some(replica_id),
2379                                    );
2380                                    stats.incorporate(stat);
2381                                    vacant_entry.insert(stats);
2382                                }
2383                                btree_map::Entry::Occupied(mut occupied_entry) => {
2384                                    occupied_entry.get_mut().incorporate(stat);
2385                                }
2386                            }
2387                        }
2388                    }
2389
2390                    {
2391                        // NOTE(aljoscha); Same as above. We want to be
2392                        // explicit.
2393                        //
2394                        // Also, technically for sinks there is no webhook
2395                        // "sources" that would force us to use an `Option`. But
2396                        // we still have to use an option for other reasons: the
2397                        // scraper expects a trait for working with stats, and
2398                        // that in the end forces the sink stats map to also
2399                        // have `Option` in the key. Do I like that? No, but
2400                        // here we are.
2401                        let replica_id = if let Some(replica_id) = replica_id {
2402                            replica_id
2403                        } else {
2404                            tracing::error!(
2405                                ?sink_stats,
2406                                "missing replica_id for sink statistics update"
2407                            );
2408                            continue;
2409                        };
2410
2411                        let mut shared_stats = self.sink_statistics.lock().expect("poisoned");
2412
2413                        for stat in sink_stats {
2414                            let collection_id = stat.id.clone();
2415
2416                            if self.collection(collection_id).is_err() {
2417                                // We can get updates for collections that have
2418                                // already been deleted, ignore those.
2419                                continue;
2420                            }
2421
2422                            let entry = shared_stats.entry((stat.id, Some(replica_id)));
2423
2424                            match entry {
2425                                btree_map::Entry::Vacant(vacant_entry) => {
2426                                    let mut stats =
2427                                        ControllerSinkStatistics::new(collection_id, replica_id);
2428                                    stats.incorporate(stat);
2429                                    vacant_entry.insert(stats);
2430                                }
2431                                btree_map::Entry::Occupied(mut occupied_entry) => {
2432                                    occupied_entry.get_mut().incorporate(stat);
2433                                }
2434                            }
2435                        }
2436                    }
2437                }
2438                (replica_id, StorageResponse::StatusUpdate(mut status_update)) => {
2439                    // NOTE(aljoscha): We sniff out the hydration status for
2440                    // ingestions from status updates. This is the easiest we
2441                    // can do right now, without going deeper into changing the
2442                    // comms protocol between controller and cluster. We cannot,
2443                    // for example use `StorageResponse::FrontierUpper`,
2444                    // because those will already get sent when the ingestion is
2445                    // just being created.
2446                    //
2447                    // Sources differ in when they will report as Running. Kafka
2448                    // UPSERT sources will only switch to `Running` once their
2449                    // state has been initialized from persist, which is the
2450                    // first case that we care about right now.
2451                    //
2452                    // I wouldn't say it's ideal, but it's workable until we
2453                    // find something better.
2454                    match status_update.status {
2455                        Status::Running => {
2456                            let collection = self.collections.get_mut(&status_update.id);
2457                            match collection {
2458                                Some(collection) => {
2459                                    match collection.extra_state {
2460                                        CollectionStateExtra::Ingestion(
2461                                            ref mut ingestion_state,
2462                                        ) => {
2463                                            if ingestion_state.hydrated_on.is_empty() {
2464                                                tracing::debug!(ingestion_id = %status_update.id, "ingestion is hydrated");
2465                                            }
2466                                            ingestion_state.hydrated_on.insert(replica_id.expect(
2467                                                "replica id should be present for status running",
2468                                            ));
2469                                        }
2470                                        CollectionStateExtra::Export(_) => {
2471                                            // TODO(sinks): track sink hydration?
2472                                        }
2473                                        CollectionStateExtra::None => {
2474                                            // Nothing to do
2475                                        }
2476                                    }
2477                                }
2478                                None => (), // no collection, let's say that's fine
2479                                            // here
2480                            }
2481                        }
2482                        Status::Paused => {
2483                            let collection = self.collections.get_mut(&status_update.id);
2484                            match collection {
2485                                Some(collection) => {
2486                                    match collection.extra_state {
2487                                        CollectionStateExtra::Ingestion(
2488                                            ref mut ingestion_state,
2489                                        ) => {
2490                                            // TODO: Paused gets send when there
2491                                            // are no active replicas. We should
2492                                            // change this to send a targeted
2493                                            // Pause for each replica, and do
2494                                            // more fine-grained hydration
2495                                            // tracking here.
2496                                            tracing::debug!(ingestion_id = %status_update.id, "ingestion is now paused");
2497                                            ingestion_state.hydrated_on.clear();
2498                                        }
2499                                        CollectionStateExtra::Export(_) => {
2500                                            // TODO(sinks): track sink hydration?
2501                                        }
2502                                        CollectionStateExtra::None => {
2503                                            // Nothing to do
2504                                        }
2505                                    }
2506                                }
2507                                None => (), // no collection, let's say that's fine
2508                                            // here
2509                            }
2510                        }
2511                        _ => (),
2512                    }
2513
2514                    // Set replica_id in the status update if available
2515                    if let Some(id) = replica_id {
2516                        status_update.replica_id = Some(id);
2517                    }
2518                    status_updates.push(status_update);
2519                }
2520                (_replica_id, StorageResponse::StagedBatches(batches)) => {
2521                    for (ingestion_id, batches) in batches {
2522                        match self.pending_oneshot_ingestions.remove(&ingestion_id) {
2523                            Some(pending) => {
2524                                // Send a cancel command so our command history is correct. And to
2525                                // avoid duplicate work once we have active replication.
2526                                if let Some(instance) = self.instances.get_mut(&pending.cluster_id)
2527                                {
2528                                    instance
2529                                        .send(StorageCommand::CancelOneshotIngestion(ingestion_id));
2530                                }
2531                                // Send the results down our channel.
2532                                (pending.result_tx)(batches)
2533                            }
2534                            None => {
2535                                // We might not be tracking this oneshot ingestion anymore because
2536                                // it was canceled.
2537                            }
2538                        }
2539                    }
2540                }
2541            }
2542        }
2543
2544        self.record_status_updates(status_updates);
2545
2546        // Process dropped tables in a single batch.
2547        let mut dropped_table_ids = Vec::new();
2548        while let Ok(dropped_id) = self.pending_table_handle_drops_rx.try_recv() {
2549            dropped_table_ids.push(dropped_id);
2550        }
2551        if !dropped_table_ids.is_empty() {
2552            self.drop_sources(storage_metadata, dropped_table_ids)?;
2553        }
2554
2555        if updated_frontiers.is_empty() {
2556            Ok(None)
2557        } else {
2558            Ok(Some(Response::FrontierUpdates(
2559                updated_frontiers.into_iter().collect(),
2560            )))
2561        }
2562    }
2563
2564    async fn inspect_persist_state(
2565        &self,
2566        id: GlobalId,
2567    ) -> Result<serde_json::Value, anyhow::Error> {
2568        let collection = &self.storage_collections.collection_metadata(id)?;
2569        let client = self
2570            .persist
2571            .open(collection.persist_location.clone())
2572            .await?;
2573        let shard_state = client
2574            .inspect_shard::<Timestamp>(&collection.data_shard)
2575            .await?;
2576        let json_state = serde_json::to_value(shard_state)?;
2577        Ok(json_state)
2578    }
2579
2580    fn append_introspection_updates(
2581        &mut self,
2582        type_: IntrospectionType,
2583        updates: Vec<(Row, Diff)>,
2584    ) {
2585        let id = self.introspection_ids[&type_];
2586        let updates = updates.into_iter().map(|update| update.into()).collect();
2587        self.collection_manager.blind_write(id, updates);
2588    }
2589
2590    fn append_status_introspection_updates(
2591        &mut self,
2592        type_: IntrospectionType,
2593        updates: Vec<StatusUpdate>,
2594    ) {
2595        let id = self.introspection_ids[&type_];
2596        let updates: Vec<_> = updates.into_iter().map(|update| update.into()).collect();
2597        if !updates.is_empty() {
2598            self.collection_manager.blind_write(id, updates);
2599        }
2600    }
2601
2602    fn update_introspection_collection(&mut self, type_: IntrospectionType, op: StorageWriteOp) {
2603        let id = self.introspection_ids[&type_];
2604        self.collection_manager.differential_write(id, op);
2605    }
2606
2607    fn append_only_introspection_tx(
2608        &self,
2609        type_: IntrospectionType,
2610    ) -> mpsc::UnboundedSender<(
2611        Vec<AppendOnlyUpdate>,
2612        oneshot::Sender<Result<(), StorageError>>,
2613    )> {
2614        let id = self.introspection_ids[&type_];
2615        self.collection_manager.append_only_write_sender(id)
2616    }
2617
2618    fn differential_introspection_tx(
2619        &self,
2620        type_: IntrospectionType,
2621    ) -> mpsc::UnboundedSender<(StorageWriteOp, oneshot::Sender<Result<(), StorageError>>)> {
2622        let id = self.introspection_ids[&type_];
2623        self.collection_manager.differential_write_sender(id)
2624    }
2625
2626    async fn real_time_recent_timestamp(
2627        &self,
2628        timestamp_objects: BTreeSet<GlobalId>,
2629        timeout: Duration,
2630    ) -> Result<BoxFuture<Result<Timestamp, StorageError>>, StorageError> {
2631        use mz_storage_types::sources::GenericSourceConnection;
2632
2633        let mut rtr_futures = BTreeMap::new();
2634
2635        // Only user sources can be read from w/ RTR.
2636        for id in timestamp_objects.into_iter().filter(GlobalId::is_user) {
2637            let collection = match self.collection(id) {
2638                Ok(c) => c,
2639                // Not a storage item, which we accept.
2640                Err(_) => continue,
2641            };
2642
2643            let (source_conn, remap_id) = match &collection.data_source {
2644                DataSource::Ingestion(IngestionDescription {
2645                    desc: SourceDesc { connection, .. },
2646                    remap_collection_id,
2647                    ..
2648                }) => match connection {
2649                    GenericSourceConnection::Kafka(_)
2650                    | GenericSourceConnection::Postgres(_)
2651                    | GenericSourceConnection::MySql(_)
2652                    | GenericSourceConnection::SqlServer(_) => {
2653                        (connection.clone(), *remap_collection_id)
2654                    }
2655
2656                    // These internal sources do not yet (and might never)
2657                    // support RTR. However, erroring if they're selected from
2658                    // poses an annoying user experience, so instead just skip
2659                    // over them.
2660                    GenericSourceConnection::LoadGenerator(_) => continue,
2661                },
2662                // Skip over all other objects
2663                _ => {
2664                    continue;
2665                }
2666            };
2667
2668            // Prepare for getting the external system's frontier.
2669            let config = self.config().clone();
2670
2671            // Determine the remap collection we plan to read from.
2672            //
2673            // Note that the process of reading from the remap shard is the same
2674            // as other areas in this code that do the same thing, but we inline
2675            // it here because we must prove that we have not taken ownership of
2676            // `self` to move the stream of data from the remap shard into a
2677            // future.
2678            let read_handle = self.read_handle_for_snapshot(remap_id).await?;
2679
2680            // Have to acquire a read hold to prevent the since from advancing
2681            // while we read.
2682            let remap_read_hold = self
2683                .storage_collections
2684                .acquire_read_holds(vec![remap_id])
2685                .map_err(|_e| StorageError::ReadBeforeSince(remap_id))?
2686                .expect_element(|| "known to be exactly one");
2687
2688            let remap_as_of = remap_read_hold
2689                .since()
2690                .to_owned()
2691                .into_option()
2692                .ok_or(StorageError::ReadBeforeSince(remap_id))?;
2693
2694            rtr_futures.insert(
2695                id,
2696                tokio::time::timeout(timeout, async move {
2697                    use mz_storage_types::sources::SourceConnection as _;
2698
2699                    // Fetch the remap shard's contents; we must do this first so
2700                    // that the `as_of` doesn't change.
2701                    let as_of = Antichain::from_elem(remap_as_of);
2702                    let remap_subscribe = read_handle
2703                        .subscribe(as_of.clone())
2704                        .await
2705                        .map_err(|_| StorageError::ReadBeforeSince(remap_id))?;
2706
2707                    tracing::debug!(?id, type_ = source_conn.name(), upstream = ?source_conn.external_reference(), "fetching real time recency");
2708
2709                    let result = rtr::real_time_recency_ts(
2710                        source_conn,
2711                        id,
2712                        config,
2713                        as_of,
2714                        remap_subscribe,
2715                    )
2716                    .await
2717                    .map_err(|e| {
2718                            tracing::debug!(?id, "real time recency error: {:?}", e);
2719                            e
2720                        });
2721
2722                    // Drop once we have read succesfully.
2723                    drop(remap_read_hold);
2724
2725                    result
2726                }),
2727            );
2728        }
2729
2730        Ok(Box::pin(async move {
2731            let (ids, futs): (Vec<_>, Vec<_>) = rtr_futures.into_iter().unzip();
2732            ids.into_iter()
2733                .zip_eq(futures::future::join_all(futs).await)
2734                .try_fold(Timestamp::MIN, |curr, (id, per_source_res)| {
2735                    let new =
2736                        per_source_res.map_err(|_e: Elapsed| StorageError::RtrTimeout(id))??;
2737                    Ok::<_, StorageError>(std::cmp::max(curr, new))
2738                })
2739        }))
2740    }
2741
2742    fn dump(&self) -> Result<serde_json::Value, anyhow::Error> {
2743        // Destructure `self` here so we don't forget to consider dumping newly added fields.
2744        let Self {
2745            build_info: _,
2746            now: _,
2747            read_only,
2748            collections,
2749            dropped_objects,
2750            persist_table_worker: _,
2751            txns_read: _,
2752            txns_metrics: _,
2753            stashed_responses,
2754            pending_table_handle_drops_tx: _,
2755            pending_table_handle_drops_rx: _,
2756            pending_oneshot_ingestions,
2757            collection_manager: _,
2758            introspection_ids,
2759            introspection_tokens: _,
2760            source_statistics: _,
2761            sink_statistics: _,
2762            statistics_interval_sender: _,
2763            instances,
2764            replica_dyncfg_overrides: _,
2765            initialized,
2766            config,
2767            persist_location,
2768            persist: _,
2769            metrics: _,
2770            recorded_frontiers,
2771            recorded_replica_frontiers,
2772            wallclock_lag: _,
2773            wallclock_lag_last_recorded,
2774            storage_collections: _,
2775            migrated_storage_collections,
2776            maintenance_ticker: _,
2777            maintenance_scheduled,
2778            instance_response_tx: _,
2779            instance_response_rx: _,
2780            persist_warm_task: _,
2781        } = self;
2782
2783        let collections: BTreeMap<_, _> = collections
2784            .iter()
2785            .map(|(id, c)| (id.to_string(), format!("{c:?}")))
2786            .collect();
2787        let dropped_objects: BTreeMap<_, _> = dropped_objects
2788            .iter()
2789            .map(|(id, rs)| (id.to_string(), format!("{rs:?}")))
2790            .collect();
2791        let stashed_responses: Vec<_> =
2792            stashed_responses.iter().map(|r| format!("{r:?}")).collect();
2793        let pending_oneshot_ingestions: BTreeMap<_, _> = pending_oneshot_ingestions
2794            .iter()
2795            .map(|(uuid, i)| (uuid.to_string(), format!("{i:?}")))
2796            .collect();
2797        let introspection_ids: BTreeMap<_, _> = introspection_ids
2798            .iter()
2799            .map(|(typ, id)| (format!("{typ:?}"), id.to_string()))
2800            .collect();
2801        let instances: BTreeMap<_, _> = instances
2802            .iter()
2803            .map(|(id, i)| (id.to_string(), format!("{i:?}")))
2804            .collect();
2805        let recorded_frontiers: BTreeMap<_, _> = recorded_frontiers
2806            .iter()
2807            .map(|(id, fs)| (id.to_string(), format!("{fs:?}")))
2808            .collect();
2809        let recorded_replica_frontiers: Vec<_> = recorded_replica_frontiers
2810            .iter()
2811            .map(|((gid, rid), f)| (gid.to_string(), rid.to_string(), format!("{f:?}")))
2812            .collect();
2813        let migrated_storage_collections: Vec<_> = migrated_storage_collections
2814            .iter()
2815            .map(|id| id.to_string())
2816            .collect();
2817
2818        Ok(serde_json::json!({
2819            "read_only": read_only,
2820            "collections": collections,
2821            "dropped_objects": dropped_objects,
2822            "stashed_responses": stashed_responses,
2823            "pending_oneshot_ingestions": pending_oneshot_ingestions,
2824            "introspection_ids": introspection_ids,
2825            "instances": instances,
2826            "initialized": initialized,
2827            "config": format!("{config:?}"),
2828            "persist_location": format!("{persist_location:?}"),
2829            "recorded_frontiers": recorded_frontiers,
2830            "recorded_replica_frontiers": recorded_replica_frontiers,
2831            "wallclock_lag_last_recorded": format!("{wallclock_lag_last_recorded:?}"),
2832            "migrated_storage_collections": migrated_storage_collections,
2833            "maintenance_scheduled": maintenance_scheduled,
2834        }))
2835    }
2836}
2837
2838/// Seed [`StorageTxn`] with any state required to instantiate a
2839/// [`StorageController`].
2840///
2841/// This cannot be a member of [`StorageController`] because it cannot take a
2842/// `self` parameter.
2843///
2844pub fn prepare_initialization(txn: &mut dyn StorageTxn) -> Result<(), StorageError> {
2845    if txn.get_txn_wal_shard().is_none() {
2846        let txns_id = ShardId::new();
2847        txn.write_txn_wal_shard(txns_id)?;
2848    }
2849
2850    Ok(())
2851}
2852
2853impl Controller
2854where
2855    Self: StorageController,
2856{
2857    /// Create a new storage controller from a client it should wrap.
2858    ///
2859    /// Note that when creating a new storage controller, you must also
2860    /// reconcile it with the previous state.
2861    ///
2862    /// # Panics
2863    /// If this function is called before [`prepare_initialization`].
2864    pub async fn new(
2865        build_info: &'static BuildInfo,
2866        persist_location: PersistLocation,
2867        persist_clients: Arc<PersistClientCache>,
2868        now: NowFn,
2869        wallclock_lag: WallclockLagFn<Timestamp>,
2870        txns_metrics: Arc<TxnMetrics>,
2871        read_only: bool,
2872        metrics_registry: &MetricsRegistry,
2873        controller_metrics: ControllerMetrics,
2874        connection_context: ConnectionContext,
2875        txn: &dyn StorageTxn,
2876        storage_collections: Arc<dyn StorageCollections + Send + Sync>,
2877    ) -> Self {
2878        let txns_client = persist_clients
2879            .open(persist_location.clone())
2880            .await
2881            .expect("location should be valid");
2882
2883        let persist_warm_task = warm_persist_state_in_background(
2884            txns_client.clone(),
2885            txn.get_collection_metadata().into_values(),
2886        );
2887        let persist_warm_task = Some(persist_warm_task.abort_on_drop());
2888
2889        // This value must be already installed because we must ensure it's
2890        // durably recorded before it is used, otherwise we risk leaking persist
2891        // state.
2892        let txns_id = txn
2893            .get_txn_wal_shard()
2894            .expect("must call prepare initialization before creating storage controller");
2895
2896        let persist_table_worker = if read_only {
2897            let txns_write = txns_client
2898                .open_writer(
2899                    txns_id,
2900                    Arc::new(TxnsCodecRow::desc()),
2901                    Arc::new(UnitSchema),
2902                    Diagnostics {
2903                        shard_name: "txns".to_owned(),
2904                        handle_purpose: "follow txns upper".to_owned(),
2905                    },
2906                )
2907                .await
2908                .expect("txns schema shouldn't change");
2909            persist_handles::PersistTableWriteWorker::new_read_only_mode(
2910                txns_write,
2911                txns_client.clone(),
2912            )
2913        } else {
2914            let mut txns = TxnsHandle::open(
2915                Timestamp::MIN,
2916                txns_client.clone(),
2917                txns_client.dyncfgs().clone(),
2918                Arc::clone(&txns_metrics),
2919                txns_id,
2920                Opaque::encode(&PersistEpoch::default()),
2921            )
2922            .await;
2923            txns.upgrade_version().await;
2924            persist_handles::PersistTableWriteWorker::new_txns(txns, txns_client.clone())
2925        };
2926        let txns_read = TxnsRead::start::<TxnsCodecRow>(txns_client.clone(), txns_id).await;
2927
2928        let collection_manager = collection_mgmt::CollectionManager::new(read_only, now.clone());
2929
2930        let introspection_ids = BTreeMap::new();
2931        let introspection_tokens = Arc::new(Mutex::new(BTreeMap::new()));
2932
2933        let (statistics_interval_sender, _) =
2934            channel(mz_storage_types::parameters::STATISTICS_INTERVAL_DEFAULT);
2935
2936        let (pending_table_handle_drops_tx, pending_table_handle_drops_rx) =
2937            tokio::sync::mpsc::unbounded_channel();
2938
2939        let mut maintenance_ticker = tokio::time::interval(Duration::from_secs(1));
2940        maintenance_ticker.set_missed_tick_behavior(MissedTickBehavior::Skip);
2941
2942        let (instance_response_tx, instance_response_rx) = mpsc::unbounded_channel();
2943
2944        let metrics = StorageControllerMetrics::new(metrics_registry, controller_metrics);
2945
2946        let now_dt = mz_ore::now::to_datetime(now());
2947
2948        Self {
2949            build_info,
2950            collections: BTreeMap::default(),
2951            dropped_objects: Default::default(),
2952            persist_table_worker,
2953            txns_read,
2954            txns_metrics,
2955            stashed_responses: vec![],
2956            pending_table_handle_drops_tx,
2957            pending_table_handle_drops_rx,
2958            pending_oneshot_ingestions: BTreeMap::default(),
2959            collection_manager,
2960            introspection_ids,
2961            introspection_tokens,
2962            now,
2963            read_only,
2964            source_statistics: Arc::new(Mutex::new(statistics::SourceStatistics {
2965                source_statistics: BTreeMap::new(),
2966                webhook_statistics: BTreeMap::new(),
2967            })),
2968            sink_statistics: Arc::new(Mutex::new(BTreeMap::new())),
2969            statistics_interval_sender,
2970            instances: BTreeMap::new(),
2971            replica_dyncfg_overrides: BTreeMap::new(),
2972            initialized: false,
2973            config: StorageConfiguration::new(connection_context, mz_dyncfgs::all_dyncfgs()),
2974            persist_location,
2975            persist: persist_clients,
2976            metrics,
2977            recorded_frontiers: BTreeMap::new(),
2978            recorded_replica_frontiers: BTreeMap::new(),
2979            wallclock_lag,
2980            wallclock_lag_last_recorded: now_dt,
2981            storage_collections,
2982            migrated_storage_collections: BTreeSet::new(),
2983            maintenance_ticker,
2984            maintenance_scheduled: false,
2985            instance_response_rx,
2986            instance_response_tx,
2987            persist_warm_task,
2988        }
2989    }
2990
2991    // This is different from `set_read_policies`, which is for external users.
2992    // This method is for setting the policy that the controller uses when
2993    // maintaining the read holds that it has for collections/exports at the
2994    // StorageCollections.
2995    //
2996    // This is really only used when dropping things, where we set the
2997    // ReadPolicy to the empty Antichain.
2998    #[instrument(level = "debug")]
2999    fn set_hold_policies(&mut self, policies: Vec<(GlobalId, ReadPolicy)>) {
3000        let mut read_capability_changes = BTreeMap::default();
3001
3002        for (id, policy) in policies.into_iter() {
3003            if let Some(collection) = self.collections.get_mut(&id) {
3004                let (write_frontier, derived_since, hold_policy) = match &mut collection.extra_state
3005                {
3006                    CollectionStateExtra::Ingestion(ingestion) => (
3007                        ingestion.write_frontier.borrow(),
3008                        &mut ingestion.derived_since,
3009                        &mut ingestion.hold_policy,
3010                    ),
3011                    CollectionStateExtra::None => {
3012                        unreachable!("set_hold_policies is only called for ingestions");
3013                    }
3014                    CollectionStateExtra::Export(export) => (
3015                        export.write_frontier.borrow(),
3016                        &mut export.derived_since,
3017                        &mut export.read_policy,
3018                    ),
3019                };
3020
3021                let new_derived_since = policy.frontier(write_frontier);
3022                let mut update = swap_updates(derived_since, new_derived_since);
3023                if !update.is_empty() {
3024                    read_capability_changes.insert(id, update);
3025                }
3026
3027                *hold_policy = policy;
3028            }
3029        }
3030
3031        if !read_capability_changes.is_empty() {
3032            self.update_hold_capabilities(&mut read_capability_changes);
3033        }
3034    }
3035
3036    #[instrument(level = "debug", fields(updates))]
3037    fn update_write_frontier(&mut self, id: GlobalId, new_upper: &Antichain<Timestamp>) {
3038        let mut read_capability_changes = BTreeMap::default();
3039
3040        if let Some(collection) = self.collections.get_mut(&id) {
3041            let (write_frontier, derived_since, hold_policy) = match &mut collection.extra_state {
3042                CollectionStateExtra::Ingestion(ingestion) => (
3043                    &mut ingestion.write_frontier,
3044                    &mut ingestion.derived_since,
3045                    &ingestion.hold_policy,
3046                ),
3047                CollectionStateExtra::None => {
3048                    if matches!(collection.data_source, DataSource::Progress) {
3049                        // We do get these, but can't do anything with it!
3050                    } else {
3051                        tracing::error!(
3052                            ?collection,
3053                            ?new_upper,
3054                            "updated write frontier for collection which is not an ingestion"
3055                        );
3056                    }
3057                    return;
3058                }
3059                CollectionStateExtra::Export(export) => (
3060                    &mut export.write_frontier,
3061                    &mut export.derived_since,
3062                    &export.read_policy,
3063                ),
3064            };
3065
3066            if PartialOrder::less_than(write_frontier, new_upper) {
3067                write_frontier.clone_from(new_upper);
3068            }
3069
3070            let new_derived_since = hold_policy.frontier(write_frontier.borrow());
3071            let mut update = swap_updates(derived_since, new_derived_since);
3072            if !update.is_empty() {
3073                read_capability_changes.insert(id, update);
3074            }
3075        } else if self.dropped_objects.contains_key(&id) {
3076            // We dropped an object but might still get updates from cluster
3077            // side, before it notices the drop. This is expected and fine.
3078        } else {
3079            soft_panic_or_log!("spurious upper update for {id}: {new_upper:?}");
3080        }
3081
3082        if !read_capability_changes.is_empty() {
3083            self.update_hold_capabilities(&mut read_capability_changes);
3084        }
3085    }
3086
3087    // This is different from `update_read_capabilities`, which is for external users.
3088    // This method is for maintaining the read holds that the controller has at
3089    // the StorageCollections, for storage dependencies.
3090    #[instrument(level = "debug", fields(updates))]
3091    fn update_hold_capabilities(
3092        &mut self,
3093        updates: &mut BTreeMap<GlobalId, ChangeBatch<Timestamp>>,
3094    ) {
3095        // Location to record consequences that we need to act on.
3096        let mut collections_net = BTreeMap::new();
3097
3098        // We must not rely on any specific relative ordering of `GlobalId`s.
3099        // That said, it is reasonable to assume that collections generally have
3100        // greater IDs than their dependencies, so starting with the largest is
3101        // a useful optimization.
3102        while let Some(key) = updates.keys().rev().next().cloned() {
3103            let mut update = updates.remove(&key).unwrap();
3104
3105            if key.is_user() {
3106                debug!(id = %key, ?update, "update_hold_capability");
3107            }
3108
3109            if let Some(collection) = self.collections.get_mut(&key) {
3110                match &mut collection.extra_state {
3111                    CollectionStateExtra::Ingestion(ingestion) => {
3112                        let changes = ingestion.read_capabilities.update_iter(update.drain());
3113                        update.extend(changes);
3114
3115                        let (changes, frontier, _cluster_id) =
3116                            collections_net.entry(key).or_insert_with(|| {
3117                                (
3118                                    <ChangeBatch<_>>::new(),
3119                                    Antichain::new(),
3120                                    ingestion.instance_id,
3121                                )
3122                            });
3123
3124                        changes.extend(update.drain());
3125                        *frontier = ingestion.read_capabilities.frontier().to_owned();
3126                    }
3127                    CollectionStateExtra::None => {
3128                        // WIP: See if this ever panics in ci.
3129                        soft_panic_or_log!(
3130                            "trying to update holds for collection {collection:?} which is not \
3131                             an ingestion: {update:?}"
3132                        );
3133                        continue;
3134                    }
3135                    CollectionStateExtra::Export(export) => {
3136                        let changes = export.read_capabilities.update_iter(update.drain());
3137                        update.extend(changes);
3138
3139                        let (changes, frontier, _cluster_id) =
3140                            collections_net.entry(key).or_insert_with(|| {
3141                                (<ChangeBatch<_>>::new(), Antichain::new(), export.cluster_id)
3142                            });
3143
3144                        changes.extend(update.drain());
3145                        *frontier = export.read_capabilities.frontier().to_owned();
3146                    }
3147                }
3148            } else {
3149                // This is confusing and we should probably error.
3150                tracing::warn!(id = ?key, ?update, "update_hold_capabilities for unknown object");
3151            }
3152        }
3153
3154        // Translate our net compute actions into `AllowCompaction` commands and
3155        // downgrade persist sinces.
3156        for (key, (mut changes, frontier, cluster_id)) in collections_net {
3157            if !changes.is_empty() {
3158                if key.is_user() {
3159                    debug!(id = %key, ?frontier, "downgrading ingestion read holds!");
3160                }
3161
3162                let collection = self
3163                    .collections
3164                    .get_mut(&key)
3165                    .expect("missing collection state");
3166
3167                let read_holds = match &mut collection.extra_state {
3168                    CollectionStateExtra::Ingestion(ingestion) => {
3169                        ingestion.dependency_read_holds.as_mut_slice()
3170                    }
3171                    CollectionStateExtra::Export(export) => export.read_holds.as_mut_slice(),
3172                    CollectionStateExtra::None => {
3173                        soft_panic_or_log!(
3174                            "trying to downgrade read holds for collection which is not an \
3175                             ingestion: {collection:?}"
3176                        );
3177                        continue;
3178                    }
3179                };
3180
3181                for read_hold in read_holds.iter_mut() {
3182                    read_hold
3183                        .try_downgrade(frontier.clone())
3184                        .expect("we only advance the frontier");
3185                }
3186
3187                // Send AllowCompaction command directly to the instance
3188                if let Some(instance) = self.instances.get_mut(&cluster_id) {
3189                    instance.send(StorageCommand::AllowCompaction(key, frontier.clone()));
3190                } else {
3191                    soft_panic_or_log!(
3192                        "missing instance client for cluster {cluster_id} while we still have outstanding AllowCompaction command {frontier:?} for {key}"
3193                    );
3194                }
3195            }
3196        }
3197    }
3198
3199    /// Validate that a collection exists for all identifiers, and error if any do not.
3200    fn validate_collection_ids(
3201        &self,
3202        ids: impl Iterator<Item = GlobalId>,
3203    ) -> Result<(), StorageError> {
3204        for id in ids {
3205            self.storage_collections.check_exists(id)?;
3206        }
3207        Ok(())
3208    }
3209
3210    /// Validate that a collection exists for all identifiers, and error if any do not.
3211    fn validate_export_ids(&self, ids: impl Iterator<Item = GlobalId>) -> Result<(), StorageError> {
3212        for id in ids {
3213            self.export(id)?;
3214        }
3215        Ok(())
3216    }
3217
3218    /// Opens a write handle and synchronizes its cached upper.
3219    async fn open_data_handles(
3220        &self,
3221        id: &GlobalId,
3222        shard: ShardId,
3223        relation_desc: RelationDesc,
3224        persist_client: &PersistClient,
3225    ) -> WriteHandle<SourceData, (), Timestamp, StorageDiff> {
3226        let diagnostics = Diagnostics {
3227            shard_name: id.to_string(),
3228            handle_purpose: format!("controller data for {}", id),
3229        };
3230
3231        let mut write = persist_client
3232            .open_writer(
3233                shard,
3234                Arc::new(relation_desc),
3235                Arc::new(UnitSchema),
3236                diagnostics.clone(),
3237            )
3238            .await
3239            .expect("invalid persist usage");
3240
3241        // Synchronize the cached upper before it initializes collection state.
3242        write.fetch_recent_upper().await;
3243
3244        write
3245    }
3246
3247    /// Registers the given introspection collection and does any preparatory
3248    /// work that we have to do before we start writing to it. This
3249    /// preparatory work will include partial truncation or other cleanup
3250    /// schemes, depending on introspection type.
3251    fn register_introspection_collection(
3252        &mut self,
3253        id: GlobalId,
3254        introspection_type: IntrospectionType,
3255        write_handle: WriteHandle<SourceData, (), Timestamp, StorageDiff>,
3256        persist_client: PersistClient,
3257    ) -> Result<(), StorageError> {
3258        tracing::info!(%id, ?introspection_type, "registering introspection collection");
3259
3260        // In read-only mode we create a new shard for all migrated storage collections. So we
3261        // "trick" the write task into thinking that it's not in read-only mode so something is
3262        // advancing this new shard.
3263        //
3264        // This is the storage-side of forcing writes to a self-owned replacement shard while
3265        // read-only. Migrated builtin MVs need the same treatment on their own write path; see
3266        // `ComputeController::allow_writes_in_read_only`.
3267        let force_writable = self.read_only && self.migrated_storage_collections.contains(&id);
3268        if force_writable {
3269            assert!(id.is_system(), "unexpected non-system global id: {id:?}");
3270            info!("writing to migrated storage collection {id} in read-only mode");
3271        }
3272
3273        let prev = self.introspection_ids.insert(introspection_type, id);
3274        assert!(
3275            prev.is_none(),
3276            "cannot have multiple IDs for introspection type"
3277        );
3278
3279        let metadata = self.storage_collections.collection_metadata(id)?.clone();
3280
3281        let read_handle_fn = move || {
3282            let persist_client = persist_client.clone();
3283            let metadata = metadata.clone();
3284
3285            let fut = async move {
3286                let read_handle = persist_client
3287                    .open_leased_reader::<SourceData, (), Timestamp, StorageDiff>(
3288                        metadata.data_shard,
3289                        Arc::new(metadata.relation_desc.clone()),
3290                        Arc::new(UnitSchema),
3291                        Diagnostics {
3292                            shard_name: id.to_string(),
3293                            handle_purpose: format!("snapshot {}", id),
3294                        },
3295                        USE_CRITICAL_SINCE_SNAPSHOT.get(persist_client.dyncfgs()),
3296                    )
3297                    .await
3298                    .expect("invalid persist usage");
3299                read_handle
3300            };
3301
3302            fut.boxed()
3303        };
3304
3305        let recent_upper = write_handle.shared_upper();
3306
3307        match CollectionManagerKind::from(&introspection_type) {
3308            // For these, we first register the collection and then prepare it,
3309            // because the code that prepares differential collection expects to
3310            // be able to update desired state via the collection manager
3311            // already.
3312            CollectionManagerKind::Differential => {
3313                let statistics_retention_duration =
3314                    dyncfgs::STATISTICS_RETENTION_DURATION.get(self.config().config_set());
3315
3316                // These do a shallow copy.
3317                let introspection_config = DifferentialIntrospectionConfig {
3318                    recent_upper,
3319                    introspection_type,
3320                    storage_collections: Arc::clone(&self.storage_collections),
3321                    collection_manager: self.collection_manager.clone(),
3322                    source_statistics: Arc::clone(&self.source_statistics),
3323                    sink_statistics: Arc::clone(&self.sink_statistics),
3324                    statistics_interval: self.config.parameters.statistics_interval.clone(),
3325                    statistics_interval_receiver: self.statistics_interval_sender.subscribe(),
3326                    statistics_retention_duration,
3327                    metrics: self.metrics.clone(),
3328                    introspection_tokens: Arc::clone(&self.introspection_tokens),
3329                };
3330                self.collection_manager.register_differential_collection(
3331                    id,
3332                    write_handle,
3333                    read_handle_fn,
3334                    force_writable,
3335                    introspection_config,
3336                );
3337            }
3338            // For these, we first have to prepare and then register with
3339            // collection manager, because the preparation logic wants to read
3340            // the shard's contents and then do uncontested writes.
3341            //
3342            // TODO(aljoscha): We should make the truncation/cleanup work that
3343            // happens when we take over instead be a periodic thing, and make
3344            // it resilient to the upper moving concurrently.
3345            CollectionManagerKind::AppendOnly => {
3346                let introspection_config = AppendOnlyIntrospectionConfig {
3347                    introspection_type,
3348                    config_set: Arc::clone(self.config.config_set()),
3349                    parameters: self.config.parameters.clone(),
3350                    storage_collections: Arc::clone(&self.storage_collections),
3351                };
3352                self.collection_manager.register_append_only_collection(
3353                    id,
3354                    write_handle,
3355                    force_writable,
3356                    Some(introspection_config),
3357                );
3358            }
3359        }
3360
3361        Ok(())
3362    }
3363
3364    /// Remove statistics for sources/sinks that were dropped but still have statistics rows
3365    /// hanging around.
3366    fn reconcile_dangling_statistics(&self) {
3367        self.source_statistics
3368            .lock()
3369            .expect("poisoned")
3370            .source_statistics
3371            // collections should also contain subsources.
3372            .retain(|(k, _replica_id), _| self.storage_collections.check_exists(*k).is_ok());
3373        self.sink_statistics
3374            .lock()
3375            .expect("poisoned")
3376            .retain(|(k, _replica_id), _| self.export(*k).is_ok());
3377    }
3378
3379    /// Appends a new global ID, shard ID pair to the appropriate collection.
3380    /// Use a `diff` of 1 to append a new entry; -1 to retract an existing
3381    /// entry.
3382    ///
3383    /// # Panics
3384    /// - If `self.collections` does not have an entry for `global_id`.
3385    /// - If `IntrospectionType::ShardMapping`'s `GlobalId` is not registered as
3386    ///   a managed collection.
3387    /// - If diff is any value other than `1` or `-1`.
3388    #[instrument(level = "debug")]
3389    fn append_shard_mappings<I>(&self, global_ids: I, diff: Diff)
3390    where
3391        I: Iterator<Item = GlobalId>,
3392    {
3393        mz_ore::soft_assert_or_log!(
3394            diff == Diff::MINUS_ONE || diff == Diff::ONE,
3395            "use 1 for insert or -1 for delete"
3396        );
3397
3398        let id = *self
3399            .introspection_ids
3400            .get(&IntrospectionType::ShardMapping)
3401            .expect("should be registered before this call");
3402
3403        let mut updates = vec![];
3404        // Pack updates into rows
3405        let mut row_buf = Row::default();
3406
3407        for global_id in global_ids {
3408            let shard_id = if let Some(collection) = self.collections.get(&global_id) {
3409                collection.collection_metadata.data_shard.clone()
3410            } else {
3411                panic!("unknown global id: {}", global_id);
3412            };
3413
3414            let mut packer = row_buf.packer();
3415            packer.push(Datum::from(global_id.to_string().as_str()));
3416            packer.push(Datum::from(shard_id.to_string().as_str()));
3417            updates.push((row_buf.clone(), diff));
3418        }
3419
3420        self.collection_manager.differential_append(id, updates);
3421    }
3422
3423    /// Determines and returns this collection's dependencies, if any.
3424    fn determine_collection_dependencies(
3425        &self,
3426        self_id: GlobalId,
3427        collection_desc: &CollectionDescription,
3428    ) -> Result<Vec<GlobalId>, StorageError> {
3429        let mut dependencies = Vec::new();
3430
3431        if let Some(id) = collection_desc.primary {
3432            dependencies.push(id);
3433        }
3434
3435        match &collection_desc.data_source {
3436            DataSource::Introspection(_)
3437            | DataSource::Webhook
3438            | DataSource::Table
3439            | DataSource::Progress
3440            | DataSource::Other => (),
3441            DataSource::IngestionExport { ingestion_id, .. } => {
3442                // Ingestion exports depend on their primary source's remap
3443                // collection.
3444                let source_collection = self.collection(*ingestion_id)?;
3445                let ingestion_remap_collection_id = match &source_collection.data_source {
3446                    DataSource::Ingestion(ingestion) => ingestion.remap_collection_id,
3447                    _ => unreachable!(
3448                        "SourceExport must only refer to primary sources that already exist"
3449                    ),
3450                };
3451
3452                // Ingestion exports (aka. subsources) must make sure that 1)
3453                // their own collection's since stays one step behind the upper,
3454                // and, 2) that the remap shard's since stays one step behind
3455                // their upper. Hence they track themselves and the remap shard
3456                // as dependencies.
3457                dependencies.extend([self_id, ingestion_remap_collection_id]);
3458            }
3459            // Ingestions depend on their remap collection.
3460            DataSource::Ingestion(ingestion) => {
3461                // Ingestions must make sure that 1) their own collection's
3462                // since stays one step behind the upper, and, 2) that the remap
3463                // shard's since stays one step behind their upper. Hence they
3464                // track themselves and the remap shard as dependencies.
3465                dependencies.push(self_id);
3466                if self_id != ingestion.remap_collection_id {
3467                    dependencies.push(ingestion.remap_collection_id);
3468                }
3469            }
3470            DataSource::Sink { desc } => {
3471                // Sinks hold back their own frontier and the frontier of their input.
3472                dependencies.extend([self_id, desc.sink.from]);
3473            }
3474        };
3475
3476        Ok(dependencies)
3477    }
3478
3479    async fn read_handle_for_snapshot(
3480        &self,
3481        id: GlobalId,
3482    ) -> Result<ReadHandle<SourceData, (), Timestamp, StorageDiff>, StorageError> {
3483        let metadata = self.storage_collections.collection_metadata(id)?;
3484        read_handle_for_snapshot(&self.persist, id, &metadata).await
3485    }
3486
3487    /// Handles writing of status updates for sources/sinks to the appropriate
3488    /// status relation
3489    fn record_status_updates(&mut self, updates: Vec<StatusUpdate>) {
3490        if self.read_only {
3491            return;
3492        }
3493
3494        let mut sink_status_updates = vec![];
3495        let mut source_status_updates = vec![];
3496
3497        for update in updates {
3498            let id = update.id;
3499            if self.export(id).is_ok() {
3500                sink_status_updates.push(update);
3501            } else if self.storage_collections.check_exists(id).is_ok() {
3502                source_status_updates.push(update);
3503            }
3504        }
3505
3506        self.append_status_introspection_updates(
3507            IntrospectionType::SourceStatusHistory,
3508            source_status_updates,
3509        );
3510        self.append_status_introspection_updates(
3511            IntrospectionType::SinkStatusHistory,
3512            sink_status_updates,
3513        );
3514    }
3515
3516    fn collection(&self, id: GlobalId) -> Result<&CollectionState, StorageError> {
3517        self.collections
3518            .get(&id)
3519            .ok_or(StorageError::IdentifierMissing(id))
3520    }
3521
3522    /// Runs the identified ingestion using the current definition of the
3523    /// ingestion in-memory.
3524    fn run_ingestion(&mut self, id: GlobalId) -> Result<(), StorageError> {
3525        tracing::info!(%id, "starting ingestion");
3526
3527        let collection = self.collection(id)?;
3528        let ingestion_description = match &collection.data_source {
3529            DataSource::Ingestion(i) => i.clone(),
3530            _ => {
3531                tracing::warn!("run_ingestion called on non-ingestion ID {}", id);
3532                Err(StorageError::IdentifierInvalid(id))?
3533            }
3534        };
3535
3536        // Enrich all of the exports with their metadata
3537        let mut source_exports = BTreeMap::new();
3538        for (export_id, export) in ingestion_description.source_exports.clone() {
3539            let export_storage_metadata = self.collection(export_id)?.collection_metadata.clone();
3540            source_exports.insert(
3541                export_id,
3542                SourceExport {
3543                    storage_metadata: export_storage_metadata,
3544                    details: export.details,
3545                    data_config: export.data_config,
3546                },
3547            );
3548        }
3549
3550        let remap_collection = self.collection(ingestion_description.remap_collection_id)?;
3551
3552        let description = IngestionDescription::<CollectionMetadata> {
3553            source_exports,
3554            remap_metadata: remap_collection.collection_metadata.clone(),
3555            // The rest of the fields are identical
3556            desc: ingestion_description.desc.clone(),
3557            instance_id: ingestion_description.instance_id,
3558            remap_collection_id: ingestion_description.remap_collection_id,
3559        };
3560
3561        let storage_instance_id = description.instance_id;
3562        // Fetch the client for this ingestion's instance.
3563        let instance = self
3564            .instances
3565            .get_mut(&storage_instance_id)
3566            .ok_or_else(|| StorageError::IngestionInstanceMissing {
3567                storage_instance_id,
3568                ingestion_id: id,
3569            })?;
3570
3571        let augmented_ingestion = Box::new(RunIngestionCommand { id, description });
3572        instance.send(StorageCommand::RunIngestion(augmented_ingestion));
3573
3574        Ok(())
3575    }
3576
3577    /// Runs the identified export using the current definition of the export
3578    /// that we have in memory.
3579    fn run_export(&mut self, id: GlobalId) -> Result<(), StorageError> {
3580        let DataSource::Sink { desc: description } = &self.collections[&id].data_source else {
3581            return Err(StorageError::IdentifierMissing(id));
3582        };
3583
3584        let from_storage_metadata = self
3585            .storage_collections
3586            .collection_metadata(description.sink.from)?;
3587        let to_storage_metadata = self.storage_collections.collection_metadata(id)?;
3588
3589        // Choose an as-of frontier for this execution of the sink. If the write frontier of the sink
3590        // is strictly larger than its read hold, it must have at least written out its snapshot, and we can skip
3591        // reading it; otherwise assume we may have to replay from the beginning.
3592        let export_state = self.storage_collections.collection_frontiers(id)?;
3593        let mut as_of = description.sink.as_of.clone();
3594        as_of.join_assign(&export_state.implied_capability);
3595        let with_snapshot = description.sink.with_snapshot
3596            && !PartialOrder::less_than(&as_of, &export_state.write_frontier);
3597
3598        info!(
3599            sink_id = %id,
3600            from_id = %description.sink.from,
3601            write_frontier = ?export_state.write_frontier,
3602            ?as_of,
3603            ?with_snapshot,
3604            "run_export"
3605        );
3606
3607        let cmd = RunSinkCommand {
3608            id,
3609            description: StorageSinkDesc {
3610                from: description.sink.from,
3611                from_desc: description.sink.from_desc.clone(),
3612                connection: description.sink.connection.clone(),
3613                envelope: description.sink.envelope,
3614                as_of,
3615                version: description.sink.version,
3616                from_storage_metadata,
3617                with_snapshot,
3618                to_storage_metadata,
3619                commit_interval: description.sink.commit_interval,
3620            },
3621        };
3622
3623        let storage_instance_id = description.instance_id.clone();
3624
3625        let instance = self
3626            .instances
3627            .get_mut(&storage_instance_id)
3628            .ok_or_else(|| StorageError::ExportInstanceMissing {
3629                storage_instance_id,
3630                export_id: id,
3631            })?;
3632
3633        instance.send(StorageCommand::RunSink(Box::new(cmd)));
3634
3635        Ok(())
3636    }
3637
3638    /// Update introspection with the current frontiers of storage objects.
3639    ///
3640    /// This method is invoked by `Controller::maintain`, which we expect to be called once per
3641    /// second during normal operation.
3642    fn update_frontier_introspection(&mut self) {
3643        let mut global_frontiers = BTreeMap::new();
3644        let mut replica_frontiers = BTreeMap::new();
3645
3646        for collection_frontiers in self.storage_collections.active_collection_frontiers() {
3647            let id = collection_frontiers.id;
3648            let since = collection_frontiers.read_capabilities;
3649            let upper = collection_frontiers.write_frontier;
3650
3651            let instance = self
3652                .collections
3653                .get(&id)
3654                .and_then(|collection_state| match &collection_state.extra_state {
3655                    CollectionStateExtra::Ingestion(ingestion) => Some(ingestion.instance_id),
3656                    CollectionStateExtra::Export(export) => Some(export.cluster_id()),
3657                    CollectionStateExtra::None => None,
3658                })
3659                .and_then(|i| self.instances.get(&i));
3660
3661            if let Some(instance) = instance {
3662                for replica_id in instance.replica_ids() {
3663                    replica_frontiers.insert((id, replica_id), upper.clone());
3664                }
3665            }
3666
3667            global_frontiers.insert(id, (since, upper));
3668        }
3669
3670        let mut global_updates = Vec::new();
3671        let mut replica_updates = Vec::new();
3672
3673        let mut push_global_update =
3674            |id: GlobalId,
3675             (since, upper): (Antichain<Timestamp>, Antichain<Timestamp>),
3676             diff: Diff| {
3677                let read_frontier = since.into_option().map_or(Datum::Null, |t| t.into());
3678                let write_frontier = upper.into_option().map_or(Datum::Null, |t| t.into());
3679                let row = Row::pack_slice(&[
3680                    Datum::String(&id.to_string()),
3681                    read_frontier,
3682                    write_frontier,
3683                ]);
3684                global_updates.push((row, diff));
3685            };
3686
3687        let mut push_replica_update =
3688            |(id, replica_id): (GlobalId, ReplicaId), upper: Antichain<Timestamp>, diff: Diff| {
3689                let write_frontier = upper.into_option().map_or(Datum::Null, |t| t.into());
3690                let row = Row::pack_slice(&[
3691                    Datum::String(&id.to_string()),
3692                    Datum::String(&replica_id.to_string()),
3693                    write_frontier,
3694                ]);
3695                replica_updates.push((row, diff));
3696            };
3697
3698        let mut old_global_frontiers =
3699            std::mem::replace(&mut self.recorded_frontiers, global_frontiers);
3700        for (&id, new) in &self.recorded_frontiers {
3701            match old_global_frontiers.remove(&id) {
3702                Some(old) if &old != new => {
3703                    push_global_update(id, new.clone(), Diff::ONE);
3704                    push_global_update(id, old, Diff::MINUS_ONE);
3705                }
3706                Some(_) => (),
3707                None => push_global_update(id, new.clone(), Diff::ONE),
3708            }
3709        }
3710        for (id, old) in old_global_frontiers {
3711            push_global_update(id, old, Diff::MINUS_ONE);
3712        }
3713
3714        let mut old_replica_frontiers =
3715            std::mem::replace(&mut self.recorded_replica_frontiers, replica_frontiers);
3716        for (&key, new) in &self.recorded_replica_frontiers {
3717            match old_replica_frontiers.remove(&key) {
3718                Some(old) if &old != new => {
3719                    push_replica_update(key, new.clone(), Diff::ONE);
3720                    push_replica_update(key, old, Diff::MINUS_ONE);
3721                }
3722                Some(_) => (),
3723                None => push_replica_update(key, new.clone(), Diff::ONE),
3724            }
3725        }
3726        for (key, old) in old_replica_frontiers {
3727            push_replica_update(key, old, Diff::MINUS_ONE);
3728        }
3729
3730        let id = self.introspection_ids[&IntrospectionType::Frontiers];
3731        self.collection_manager
3732            .differential_append(id, global_updates);
3733
3734        let id = self.introspection_ids[&IntrospectionType::ReplicaFrontiers];
3735        self.collection_manager
3736            .differential_append(id, replica_updates);
3737    }
3738
3739    /// Refresh the wallclock lag introspection and metrics with the current lag values.
3740    ///
3741    /// This method produces wallclock lag metrics of two different shapes:
3742    ///
3743    /// * Histories: For each replica and each collection, we measure the lag of the write frontier
3744    ///   behind the wallclock time every second. Every minute we emit the maximum lag observed
3745    ///   over the last minute, together with the current time.
3746    /// * Histograms: For each collection, we measure the lag of the write frontier behind
3747    ///   wallclock time every second. Every minute we emit all lags observed over the last minute,
3748    ///   together with the current histogram period.
3749    ///
3750    /// Histories are emitted to both Mz introspection and Prometheus, histograms only to
3751    /// introspection. We treat lags of unreadable collections (i.e. collections that contain no
3752    /// readable times) as undefined and set them to NULL in introspection and `u64::MAX` in
3753    /// Prometheus.
3754    ///
3755    /// This method is invoked by `Controller::maintain`, which we expect to be called once per
3756    /// second during normal operation.
3757    fn refresh_wallclock_lag(&mut self) {
3758        let now_ms = (self.now)();
3759        let histogram_period =
3760            WallclockLagHistogramPeriod::from_epoch_millis(now_ms, self.config.config_set());
3761
3762        let frontier_lag = |frontier: &Antichain<Timestamp>| match frontier.as_option() {
3763            Some(ts) => (self.wallclock_lag)(*ts),
3764            None => Duration::ZERO,
3765        };
3766
3767        for frontiers in self.storage_collections.active_collection_frontiers() {
3768            let id = frontiers.id;
3769            let Some(collection) = self.collections.get_mut(&id) else {
3770                continue;
3771            };
3772
3773            let collection_unreadable =
3774                PartialOrder::less_equal(&frontiers.write_frontier, &frontiers.read_capabilities);
3775            let lag = if collection_unreadable {
3776                WallclockLag::Undefined
3777            } else {
3778                let lag = frontier_lag(&frontiers.write_frontier);
3779                WallclockLag::Seconds(lag.as_secs())
3780            };
3781
3782            collection.wallclock_lag_max = collection.wallclock_lag_max.max(lag);
3783
3784            // No way to specify values as undefined in Prometheus metrics, so we use the
3785            // maximum value instead.
3786            let secs = lag.unwrap_seconds_or(u64::MAX);
3787            collection.wallclock_lag_metrics.observe(secs);
3788
3789            if let Some(stash) = &mut collection.wallclock_lag_histogram_stash {
3790                let bucket = lag.map_seconds(|secs| secs.next_power_of_two());
3791
3792                let instance_id = match &collection.extra_state {
3793                    CollectionStateExtra::Ingestion(i) => Some(i.instance_id),
3794                    CollectionStateExtra::Export(e) => Some(e.cluster_id()),
3795                    CollectionStateExtra::None => None,
3796                };
3797                let workload_class = instance_id
3798                    .and_then(|id| self.instances.get(&id))
3799                    .and_then(|i| i.workload_class.clone());
3800                let labels = match workload_class {
3801                    Some(wc) => [("workload_class", wc.clone())].into(),
3802                    None => BTreeMap::new(),
3803                };
3804
3805                let key = (histogram_period, bucket, labels);
3806                *stash.entry(key).or_default() += Diff::ONE;
3807            }
3808        }
3809
3810        // Record lags to persist, if it's time.
3811        self.maybe_record_wallclock_lag();
3812    }
3813
3814    /// Produce new wallclock lag introspection updates, provided enough time has passed since the
3815    /// last recording.
3816    ///
3817    /// We emit new introspection updates if the system time has passed into a new multiple of the
3818    /// recording interval (typically 1 minute) since the last refresh. The compute controller uses
3819    /// the same approach, ensuring that both controllers commit their lags at roughly the same
3820    /// time, avoiding confusion caused by inconsistencies.
3821    fn maybe_record_wallclock_lag(&mut self) {
3822        if self.read_only {
3823            return;
3824        }
3825
3826        let duration_trunc = |datetime: DateTime<_>, interval| {
3827            let td = TimeDelta::from_std(interval).ok()?;
3828            datetime.duration_trunc(td).ok()
3829        };
3830
3831        let interval = WALLCLOCK_LAG_RECORDING_INTERVAL.get(self.config.config_set());
3832        let now_dt = mz_ore::now::to_datetime((self.now)());
3833        let now_trunc = duration_trunc(now_dt, interval).unwrap_or_else(|| {
3834            soft_panic_or_log!("excessive wallclock lag recording interval: {interval:?}");
3835            let default = WALLCLOCK_LAG_RECORDING_INTERVAL.default();
3836            duration_trunc(now_dt, *default).unwrap()
3837        });
3838        if now_trunc <= self.wallclock_lag_last_recorded {
3839            return;
3840        }
3841
3842        let now_ts: CheckedTimestamp<_> = now_trunc.try_into().expect("must fit");
3843
3844        let mut history_updates = Vec::new();
3845        let mut histogram_updates = Vec::new();
3846        let mut row_buf = Row::default();
3847        for frontiers in self.storage_collections.active_collection_frontiers() {
3848            let id = frontiers.id;
3849            let Some(collection) = self.collections.get_mut(&id) else {
3850                continue;
3851            };
3852
3853            let max_lag = std::mem::replace(&mut collection.wallclock_lag_max, WallclockLag::MIN);
3854            let row = Row::pack_slice(&[
3855                Datum::String(&id.to_string()),
3856                Datum::Null,
3857                max_lag.into_interval_datum(),
3858                Datum::TimestampTz(now_ts),
3859            ]);
3860            history_updates.push((row, Diff::ONE));
3861
3862            let Some(stash) = &mut collection.wallclock_lag_histogram_stash else {
3863                continue;
3864            };
3865
3866            for ((period, lag, labels), count) in std::mem::take(stash) {
3867                let mut packer = row_buf.packer();
3868                packer.extend([
3869                    Datum::TimestampTz(period.start),
3870                    Datum::TimestampTz(period.end),
3871                    Datum::String(&id.to_string()),
3872                    lag.into_uint64_datum(),
3873                ]);
3874                let labels = labels.iter().map(|(k, v)| (*k, Datum::String(v)));
3875                packer.push_dict(labels);
3876
3877                histogram_updates.push((row_buf.clone(), count));
3878            }
3879        }
3880
3881        if !history_updates.is_empty() {
3882            self.append_introspection_updates(
3883                IntrospectionType::WallclockLagHistory,
3884                history_updates,
3885            );
3886        }
3887        if !histogram_updates.is_empty() {
3888            self.append_introspection_updates(
3889                IntrospectionType::WallclockLagHistogram,
3890                histogram_updates,
3891            );
3892        }
3893
3894        self.wallclock_lag_last_recorded = now_trunc;
3895    }
3896
3897    /// Run periodic tasks.
3898    ///
3899    /// This method is invoked roughly once per second during normal operation. It is a good place
3900    /// for tasks that need to run periodically, such as state cleanup or updating of metrics.
3901    fn maintain(&mut self) {
3902        self.update_frontier_introspection();
3903        self.refresh_wallclock_lag();
3904
3905        // Perform instance maintenance work.
3906        for instance in self.instances.values_mut() {
3907            instance.refresh_state_metrics();
3908        }
3909    }
3910}
3911
3912impl From<&IntrospectionType> for CollectionManagerKind {
3913    fn from(value: &IntrospectionType) -> Self {
3914        match value {
3915            IntrospectionType::ShardMapping
3916            | IntrospectionType::Frontiers
3917            | IntrospectionType::ReplicaFrontiers
3918            | IntrospectionType::StorageSourceStatistics
3919            | IntrospectionType::StorageSinkStatistics
3920            | IntrospectionType::ComputeDependencies
3921            | IntrospectionType::ComputeOperatorHydrationStatus
3922            | IntrospectionType::ComputeMaterializedViewRefreshes
3923            | IntrospectionType::ComputeErrorCounts
3924            | IntrospectionType::ComputeHydrationTimes
3925            | IntrospectionType::ComputeObjectArrangementSizes => {
3926                CollectionManagerKind::Differential
3927            }
3928
3929            IntrospectionType::SourceStatusHistory
3930            | IntrospectionType::SinkStatusHistory
3931            | IntrospectionType::PrivatelinkConnectionStatusHistory
3932            | IntrospectionType::ReplicaStatusHistory
3933            | IntrospectionType::ReplicaMetricsHistory
3934            | IntrospectionType::WallclockLagHistory
3935            | IntrospectionType::WallclockLagHistogram
3936            | IntrospectionType::PreparedStatementHistory
3937            | IntrospectionType::StatementExecutionHistory
3938            | IntrospectionType::SessionHistory
3939            | IntrospectionType::StatementLifecycleHistory
3940            | IntrospectionType::SqlText => CollectionManagerKind::AppendOnly,
3941        }
3942    }
3943}
3944
3945/// Get the current rows in the given statistics table. This is used to bootstrap
3946/// the statistics tasks.
3947///
3948// TODO(guswynn): we need to be more careful about the update time we get here:
3949// <https://github.com/MaterializeInc/database-issues/issues/7564>
3950async fn snapshot_statistics(
3951    id: GlobalId,
3952    upper: Antichain<Timestamp>,
3953    storage_collections: &Arc<dyn StorageCollections + Send + Sync>,
3954) -> Vec<Row> {
3955    match upper.as_option() {
3956        Some(f) if f > &Timestamp::MIN => {
3957            let as_of = f.step_back().unwrap();
3958
3959            let snapshot = storage_collections.snapshot(id, as_of).await.unwrap();
3960            snapshot
3961                .into_iter()
3962                .map(|(row, diff)| {
3963                    assert_eq!(diff, 1);
3964                    row
3965                })
3966                .collect()
3967        }
3968        // If collection is closed or the frontier is the minimum, we cannot
3969        // or don't need to truncate (respectively).
3970        _ => Vec::new(),
3971    }
3972}
3973
3974async fn read_handle_for_snapshot(
3975    persist: &PersistClientCache,
3976    id: GlobalId,
3977    metadata: &CollectionMetadata,
3978) -> Result<ReadHandle<SourceData, (), Timestamp, StorageDiff>, StorageError> {
3979    let persist_client = persist
3980        .open(metadata.persist_location.clone())
3981        .await
3982        .unwrap();
3983
3984    // We create a new read handle every time someone requests a snapshot and then immediately
3985    // expire it instead of keeping a read handle permanently in our state to avoid having it
3986    // heartbeat continously. The assumption is that calls to snapshot are rare and therefore
3987    // worth it to always create a new handle.
3988    let read_handle = persist_client
3989        .open_leased_reader::<SourceData, (), _, _>(
3990            metadata.data_shard,
3991            Arc::new(metadata.relation_desc.clone()),
3992            Arc::new(UnitSchema),
3993            Diagnostics {
3994                shard_name: id.to_string(),
3995                handle_purpose: format!("snapshot {}", id),
3996            },
3997            USE_CRITICAL_SINCE_SNAPSHOT.get(persist_client.dyncfgs()),
3998        )
3999        .await
4000        .expect("invalid persist usage");
4001    Ok(read_handle)
4002}
4003
4004/// State maintained about individual collections.
4005#[derive(Debug)]
4006struct CollectionState {
4007    /// The source of this collection's data.
4008    pub data_source: DataSource,
4009
4010    pub collection_metadata: CollectionMetadata,
4011
4012    pub extra_state: CollectionStateExtra,
4013
4014    /// Maximum frontier wallclock lag since the last `WallclockLagHistory` introspection update.
4015    wallclock_lag_max: WallclockLag,
4016    /// Frontier wallclock lag measurements stashed until the next `WallclockLagHistogram`
4017    /// introspection update.
4018    ///
4019    /// Keys are `(period, lag, labels)` triples, values are counts.
4020    ///
4021    /// If this is `None`, wallclock lag is not tracked for this collection.
4022    wallclock_lag_histogram_stash: Option<
4023        BTreeMap<
4024            (
4025                WallclockLagHistogramPeriod,
4026                WallclockLag,
4027                BTreeMap<&'static str, String>,
4028            ),
4029            Diff,
4030        >,
4031    >,
4032    /// Frontier wallclock lag metrics tracked for this collection.
4033    wallclock_lag_metrics: WallclockLagMetrics,
4034}
4035
4036impl CollectionState {
4037    fn new(
4038        data_source: DataSource,
4039        collection_metadata: CollectionMetadata,
4040        extra_state: CollectionStateExtra,
4041        wallclock_lag_metrics: WallclockLagMetrics,
4042    ) -> Self {
4043        // Only collect wallclock lag histogram data for collections written by storage, to avoid
4044        // duplicate measurements. Collections written by other components (e.g. compute) have
4045        // their wallclock lags recorded by these components.
4046        let wallclock_lag_histogram_stash = match &data_source {
4047            DataSource::Other => None,
4048            _ => Some(Default::default()),
4049        };
4050
4051        Self {
4052            data_source,
4053            collection_metadata,
4054            extra_state,
4055            wallclock_lag_max: WallclockLag::MIN,
4056            wallclock_lag_histogram_stash,
4057            wallclock_lag_metrics,
4058        }
4059    }
4060}
4061
4062/// Additional state that the controller maintains for select collection types.
4063#[derive(Debug)]
4064enum CollectionStateExtra {
4065    Ingestion(IngestionState),
4066    Export(ExportState),
4067    None,
4068}
4069
4070/// State maintained about ingestions and ingestion exports
4071#[derive(Debug)]
4072struct IngestionState {
4073    /// Really only for keeping track of changes to the `derived_since`.
4074    pub read_capabilities: MutableAntichain<Timestamp>,
4075
4076    /// The current since frontier, derived from `write_frontier` using
4077    /// `hold_policy`.
4078    pub derived_since: Antichain<Timestamp>,
4079
4080    /// Holds that this ingestion (or ingestion export) has on its dependencies.
4081    pub dependency_read_holds: Vec<ReadHold>,
4082
4083    /// Reported write frontier.
4084    pub write_frontier: Antichain<Timestamp>,
4085
4086    /// The policy that drives how we downgrade our read hold. That is how we
4087    /// derive our since from our upper.
4088    ///
4089    /// This is a _storage-controller-internal_ policy used to derive its
4090    /// personal read hold on the collection. It should not be confused with any
4091    /// read policies that the adapter might install at [StorageCollections].
4092    pub hold_policy: ReadPolicy,
4093
4094    /// The ID of the instance in which the ingestion is running.
4095    pub instance_id: StorageInstanceId,
4096
4097    /// Set of replica IDs on which this ingestion is hydrated.
4098    pub hydrated_on: BTreeSet<ReplicaId>,
4099}
4100
4101/// A description of a status history collection.
4102///
4103/// Used to inform partial truncation, see
4104/// [`collection_mgmt::partially_truncate_status_history`].
4105struct StatusHistoryDesc<K> {
4106    retention_policy: StatusHistoryRetentionPolicy,
4107    extract_key: Box<dyn Fn(&[Datum]) -> K + Send>,
4108    extract_time: Box<dyn Fn(&[Datum]) -> CheckedTimestamp<DateTime<Utc>> + Send>,
4109}
4110enum StatusHistoryRetentionPolicy {
4111    // Truncates everything but the last N updates for each key.
4112    LastN(usize),
4113    // Truncates everything past the time window for each key.
4114    TimeWindow(Duration),
4115}
4116
4117fn source_status_history_desc(
4118    params: &StorageParameters,
4119) -> StatusHistoryDesc<(GlobalId, Option<ReplicaId>)> {
4120    let desc = &MZ_SOURCE_STATUS_HISTORY_DESC;
4121    let (source_id_idx, _) = desc.get_by_name(&"source_id".into()).expect("exists");
4122    let (replica_id_idx, _) = desc.get_by_name(&"replica_id".into()).expect("exists");
4123    let (time_idx, _) = desc.get_by_name(&"occurred_at".into()).expect("exists");
4124
4125    StatusHistoryDesc {
4126        retention_policy: StatusHistoryRetentionPolicy::LastN(
4127            params.keep_n_source_status_history_entries,
4128        ),
4129        extract_key: Box::new(move |datums| {
4130            (
4131                GlobalId::from_str(datums[source_id_idx].unwrap_str()).expect("GlobalId column"),
4132                if datums[replica_id_idx].is_null() {
4133                    None
4134                } else {
4135                    Some(
4136                        ReplicaId::from_str(datums[replica_id_idx].unwrap_str())
4137                            .expect("ReplicaId column"),
4138                    )
4139                },
4140            )
4141        }),
4142        extract_time: Box::new(move |datums| datums[time_idx].unwrap_timestamptz()),
4143    }
4144}
4145
4146fn sink_status_history_desc(
4147    params: &StorageParameters,
4148) -> StatusHistoryDesc<(GlobalId, Option<ReplicaId>)> {
4149    let desc = &MZ_SINK_STATUS_HISTORY_DESC;
4150    let (sink_id_idx, _) = desc.get_by_name(&"sink_id".into()).expect("exists");
4151    let (replica_id_idx, _) = desc.get_by_name(&"replica_id".into()).expect("exists");
4152    let (time_idx, _) = desc.get_by_name(&"occurred_at".into()).expect("exists");
4153
4154    StatusHistoryDesc {
4155        retention_policy: StatusHistoryRetentionPolicy::LastN(
4156            params.keep_n_sink_status_history_entries,
4157        ),
4158        extract_key: Box::new(move |datums| {
4159            (
4160                GlobalId::from_str(datums[sink_id_idx].unwrap_str()).expect("GlobalId column"),
4161                if datums[replica_id_idx].is_null() {
4162                    None
4163                } else {
4164                    Some(
4165                        ReplicaId::from_str(datums[replica_id_idx].unwrap_str())
4166                            .expect("ReplicaId column"),
4167                    )
4168                },
4169            )
4170        }),
4171        extract_time: Box::new(move |datums| datums[time_idx].unwrap_timestamptz()),
4172    }
4173}
4174
4175fn privatelink_status_history_desc(params: &StorageParameters) -> StatusHistoryDesc<GlobalId> {
4176    let desc = &MZ_AWS_PRIVATELINK_CONNECTION_STATUS_HISTORY_DESC;
4177    let (key_idx, _) = desc.get_by_name(&"connection_id".into()).expect("exists");
4178    let (time_idx, _) = desc.get_by_name(&"occurred_at".into()).expect("exists");
4179
4180    StatusHistoryDesc {
4181        retention_policy: StatusHistoryRetentionPolicy::LastN(
4182            params.keep_n_privatelink_status_history_entries,
4183        ),
4184        extract_key: Box::new(move |datums| {
4185            GlobalId::from_str(datums[key_idx].unwrap_str()).expect("GlobalId column")
4186        }),
4187        extract_time: Box::new(move |datums| datums[time_idx].unwrap_timestamptz()),
4188    }
4189}
4190
4191fn replica_status_history_desc(params: &StorageParameters) -> StatusHistoryDesc<(GlobalId, u64)> {
4192    let desc = &REPLICA_STATUS_HISTORY_DESC;
4193    let (replica_idx, _) = desc.get_by_name(&"replica_id".into()).expect("exists");
4194    let (process_idx, _) = desc.get_by_name(&"process_id".into()).expect("exists");
4195    let (time_idx, _) = desc.get_by_name(&"occurred_at".into()).expect("exists");
4196
4197    StatusHistoryDesc {
4198        retention_policy: StatusHistoryRetentionPolicy::TimeWindow(
4199            params.replica_status_history_retention_window,
4200        ),
4201        extract_key: Box::new(move |datums| {
4202            (
4203                GlobalId::from_str(datums[replica_idx].unwrap_str()).expect("GlobalId column"),
4204                datums[process_idx].unwrap_uint64(),
4205            )
4206        }),
4207        extract_time: Box::new(move |datums| datums[time_idx].unwrap_timestamptz()),
4208    }
4209}
4210
4211/// Replace one antichain with another, tracking the overall changes in the returned `ChangeBatch`.
4212fn swap_updates(
4213    from: &mut Antichain<Timestamp>,
4214    mut replace_with: Antichain<Timestamp>,
4215) -> ChangeBatch<Timestamp> {
4216    let mut update = ChangeBatch::new();
4217    if PartialOrder::less_equal(from, &replace_with) {
4218        update.extend(replace_with.iter().map(|time| (*time, 1)));
4219        std::mem::swap(from, &mut replace_with);
4220        update.extend(replace_with.iter().map(|time| (*time, -1)));
4221    }
4222    update
4223}