Skip to main content

mz_storage_client/
storage_collections.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//! An abstraction for dealing with storage collections.
11
12use std::cmp::Reverse;
13use std::collections::{BTreeMap, BTreeSet};
14use std::fmt::Debug;
15use std::iter;
16use std::num::NonZeroI64;
17use std::sync::{Arc, Mutex};
18use std::time::Duration;
19
20use async_trait::async_trait;
21use differential_dataflow::lattice::Lattice;
22use futures::future::BoxFuture;
23use futures::stream::{BoxStream, FuturesUnordered};
24use futures::{Future, FutureExt, StreamExt};
25use itertools::Itertools;
26use mz_ore::collections::CollectionExt;
27use mz_ore::metrics::MetricsRegistry;
28use mz_ore::now::NowFn;
29use mz_ore::task::AbortOnDropHandle;
30use mz_ore::{assert_none, instrument, soft_assert_or_log};
31use mz_persist_client::cache::PersistClientCache;
32use mz_persist_client::cfg::USE_CRITICAL_SINCE_SNAPSHOT;
33use mz_persist_client::critical::{Opaque, SinceHandle};
34use mz_persist_client::read::{Cursor, ReadHandle};
35use mz_persist_client::schema::CaESchema;
36use mz_persist_client::stats::{SnapshotPartsStats, SnapshotStats};
37use mz_persist_client::write::WriteHandle;
38use mz_persist_client::{Diagnostics, PersistClient, PersistLocation, ShardId};
39use mz_persist_types::codec_impls::UnitSchema;
40use mz_persist_types::txn::TxnsCodec;
41use mz_repr::{GlobalId, RelationDesc, RelationVersion, Row, Timestamp};
42use mz_storage_types::StorageDiff;
43use mz_storage_types::configuration::StorageConfiguration;
44use mz_storage_types::connections::ConnectionContext;
45use mz_storage_types::controller::{CollectionMetadata, StorageError, TxnsCodecRow};
46use mz_storage_types::dyncfgs::STORAGE_DOWNGRADE_SINCE_DURING_FINALIZATION;
47use mz_storage_types::errors::CollectionMissing;
48use mz_storage_types::parameters::StorageParameters;
49use mz_storage_types::read_holds::ReadHold;
50use mz_storage_types::read_policy::ReadPolicy;
51use mz_storage_types::sources::{GenericSourceConnection, SourceData, SourceEnvelope, Timeline};
52use mz_storage_types::time_dependence::{TimeDependence, TimeDependenceError};
53use mz_txn_wal::metrics::Metrics as TxnMetrics;
54use mz_txn_wal::txn_read::{DataSnapshot, TxnsRead};
55use mz_txn_wal::txns::TxnsHandle;
56use timely::PartialOrder;
57use timely::progress::frontier::MutableAntichain;
58use timely::progress::{Antichain, ChangeBatch};
59use tokio::sync::{mpsc, oneshot};
60use tokio::time::MissedTickBehavior;
61use tracing::{debug, info, trace, warn};
62
63use crate::client::TimestamplessUpdateBuilder;
64use crate::controller::{
65    CollectionDescription, DataSource, PersistEpoch, StorageMetadata, StorageTxn,
66};
67use crate::storage_collections::metrics::{ShardIdSet, StorageCollectionsMetrics};
68
69mod metrics;
70
71/// An abstraction for keeping track of storage collections and managing access
72/// to them.
73///
74/// Responsibilities:
75///
76/// - Keeps a critical persist handle for holding the since of collections
77///   where it need to be.
78///
79/// - Drives the since forward based on the upper of a collection and a
80///   [ReadPolicy].
81///
82/// - Hands out [ReadHolds](ReadHold) that prevent a collection's since from
83/// advancing while it needs to be read at a specific time.
84#[async_trait]
85pub trait StorageCollections: Debug + Sync {
86    /// On boot, reconcile this [StorageCollections] with outside state. We get
87    /// a [StorageTxn] where we can record any durable state that we need.
88    ///
89    /// We get `init_ids`, which tells us about all collections that currently
90    /// exist, so that we can record durable state for those that _we_ don't
91    /// know yet about.
92    async fn initialize_state(
93        &self,
94        txn: &mut (dyn StorageTxn + Send),
95        init_ids: BTreeSet<GlobalId>,
96    ) -> Result<(), StorageError>;
97
98    /// Update storage configuration with new parameters.
99    fn update_parameters(&self, config_params: StorageParameters);
100
101    /// Returns the [CollectionMetadata] of the collection identified by `id`.
102    fn collection_metadata(&self, id: GlobalId) -> Result<CollectionMetadata, CollectionMissing>;
103
104    /// Acquire an iterator over [CollectionMetadata] for all active
105    /// collections.
106    ///
107    /// A collection is "active" when it has a non empty frontier of read
108    /// capabilties.
109    fn active_collection_metadatas(&self) -> Vec<(GlobalId, CollectionMetadata)>;
110
111    /// Returns the frontiers of the identified collection.
112    fn collection_frontiers(&self, id: GlobalId) -> Result<CollectionFrontiers, CollectionMissing> {
113        let frontiers = self
114            .collections_frontiers(vec![id])?
115            .expect_element(|| "known to exist");
116
117        Ok(frontiers)
118    }
119
120    /// Atomically gets and returns the frontiers of all the identified
121    /// collections.
122    fn collections_frontiers(
123        &self,
124        id: Vec<GlobalId>,
125    ) -> Result<Vec<CollectionFrontiers>, CollectionMissing>;
126
127    /// Atomically gets and returns the frontiers of all active collections.
128    ///
129    /// A collection is "active" when it has a non-empty frontier of read
130    /// capabilities.
131    fn active_collection_frontiers(&self) -> Vec<CollectionFrontiers>;
132
133    /// Checks whether a collection exists under the given `GlobalId`. Returns
134    /// an error if the collection does not exist.
135    fn check_exists(&self, id: GlobalId) -> Result<(), StorageError>;
136
137    /// Returns aggregate statistics about the contents of the local input named
138    /// `id` at `as_of`.
139    async fn snapshot_stats(
140        &self,
141        id: GlobalId,
142        as_of: Antichain<Timestamp>,
143    ) -> Result<SnapshotStats, StorageError>;
144
145    /// Returns aggregate statistics about the contents of the local input named
146    /// `id` at `as_of`.
147    ///
148    /// Note that this async function itself returns a future. We may
149    /// need to block on the stats being available, but don't want to hold a reference
150    /// to the controller for too long... so the outer future holds a reference to the
151    /// controller but returns quickly, and the inner future is slow but does not
152    /// reference the controller.
153    async fn snapshot_parts_stats(
154        &self,
155        id: GlobalId,
156        as_of: Antichain<Timestamp>,
157    ) -> BoxFuture<'static, Result<SnapshotPartsStats, StorageError>>;
158
159    /// Returns a snapshot of the contents of collection `id` at `as_of`.
160    fn snapshot(
161        &self,
162        id: GlobalId,
163        as_of: Timestamp,
164    ) -> BoxFuture<'static, Result<Vec<(Row, StorageDiff)>, StorageError>>;
165
166    /// Returns a snapshot of the contents of collection `id` at the largest readable `as_of`.
167    /// The collection must consolidate to a set, i.e., the multiplicity of every row must be 1!
168    ///
169    /// # Errors
170    ///
171    /// - Returns `StorageError::InvalidUsage` if the collection is closed.
172    /// - Propagates the error if the underlying `snapshot` call errors.
173    ///
174    /// # Panics
175    ///
176    /// Panics if the collection does not consolidate to a set at that `as_of`
177    /// (i.e., if any row survives with a multiplicity other than `+1`). Only
178    /// safe to call on collections whose producer guarantees set semantics;
179    /// not safe on arbitrary user collections.
180    async fn snapshot_latest(&self, id: GlobalId) -> Result<Vec<Row>, StorageError>;
181
182    /// Returns a snapshot of the contents of collection `id` at `as_of`.
183    fn snapshot_cursor(
184        &self,
185        id: GlobalId,
186        as_of: Timestamp,
187    ) -> BoxFuture<'static, Result<SnapshotCursor, StorageError>>;
188
189    /// Generates a snapshot of the contents of collection `id` at `as_of` and
190    /// streams out all of the updates in bounded memory.
191    ///
192    /// The output is __not__ consolidated.
193    fn snapshot_and_stream(
194        &self,
195        id: GlobalId,
196        as_of: Timestamp,
197    ) -> BoxFuture<
198        'static,
199        Result<BoxStream<'static, (SourceData, Timestamp, StorageDiff)>, StorageError>,
200    >;
201
202    /// Create a [`TimestamplessUpdateBuilder`] that can be used to stage
203    /// updates for the provided [`GlobalId`].
204    fn create_update_builder(
205        &self,
206        id: GlobalId,
207    ) -> BoxFuture<
208        'static,
209        Result<TimestamplessUpdateBuilder<SourceData, (), StorageDiff>, StorageError>,
210    >;
211
212    /// Update the given [`StorageTxn`] with the appropriate metadata given the
213    /// IDs to add and drop.
214    ///
215    /// The data modified in the `StorageTxn` must be made available in all
216    /// subsequent calls that require [`StorageMetadata`] as a parameter.
217    async fn prepare_state(
218        &self,
219        txn: &mut (dyn StorageTxn + Send),
220        ids_to_add: BTreeSet<GlobalId>,
221        ids_to_drop: BTreeSet<GlobalId>,
222        ids_to_register: BTreeMap<GlobalId, ShardId>,
223    ) -> Result<(), StorageError>;
224
225    /// Create the collections described by the individual
226    /// [CollectionDescriptions](CollectionDescription).
227    ///
228    /// Each command carries the source id, the source description, and any
229    /// associated metadata needed to ingest the particular source.
230    ///
231    /// This command installs collection state for the indicated sources, and
232    /// they are now valid to use in queries at times beyond the initial `since`
233    /// frontiers. Each collection also acquires a read capability at this
234    /// frontier, which will need to be repeatedly downgraded with
235    /// `allow_compaction()` to permit compaction.
236    ///
237    /// This method is NOT idempotent; It can fail between processing of
238    /// different collections and leave the [StorageCollections] in an
239    /// inconsistent state. It is almost always wrong to do anything but abort
240    /// the process on `Err`.
241    ///
242    /// The `register_ts` is used as the initial timestamp that tables are
243    /// available for reads. (We might later give non-tables the same treatment,
244    /// but hold off on that initially.) Callers must provide a Some if any of
245    /// the collections is a table. A None may be given if none of the
246    /// collections are a table (i.e. all materialized views, sources, etc).
247    ///
248    /// `migrated_storage_collections` is a set of migrated storage collections to be excluded
249    /// from the txn-wal sub-system.
250    async fn create_collections_for_bootstrap(
251        &self,
252        storage_metadata: &StorageMetadata,
253        register_ts: Option<Timestamp>,
254        collections: Vec<(GlobalId, CollectionDescription)>,
255        migrated_storage_collections: &BTreeSet<GlobalId>,
256    ) -> Result<(), StorageError>;
257
258    /// Updates the [`RelationDesc`] for the specified table.
259    async fn alter_table_desc(
260        &self,
261        existing_collection: GlobalId,
262        new_collection: GlobalId,
263        new_desc: RelationDesc,
264        expected_version: RelationVersion,
265    ) -> Result<(), StorageError>;
266
267    /// Drops the read capability for the sources and allows their resources to
268    /// be reclaimed.
269    ///
270    /// TODO(jkosh44): This method does not validate the provided identifiers.
271    /// Currently when the controller starts/restarts it has no durable state.
272    /// That means that it has no way of remembering any past commands sent. In
273    /// the future we plan on persisting state for the controller so that it is
274    /// aware of past commands. Therefore this method is for dropping sources
275    /// that we know to have been previously created, but have been forgotten by
276    /// the controller due to a restart. Once command history becomes durable we
277    /// can remove this method and use the normal `drop_sources`.
278    fn drop_collections_unvalidated(
279        &self,
280        storage_metadata: &StorageMetadata,
281        identifiers: Vec<GlobalId>,
282    );
283
284    /// Assigns a read policy to specific identifiers.
285    ///
286    /// The policies are assigned in the order presented, and repeated
287    /// identifiers should conclude with the last policy. Changing a policy will
288    /// immediately downgrade the read capability if appropriate, but it will
289    /// not "recover" the read capability if the prior capability is already
290    /// ahead of it.
291    ///
292    /// This [StorageCollections] may include its own overrides on these
293    /// policies.
294    ///
295    /// Identifiers not present in `policies` retain their existing read
296    /// policies.
297    fn set_read_policies(&self, policies: Vec<(GlobalId, ReadPolicy)>);
298
299    /// Acquires and returns the earliest possible read holds for the specified
300    /// collections.
301    fn acquire_read_holds(
302        &self,
303        desired_holds: Vec<GlobalId>,
304    ) -> Result<Vec<ReadHold>, CollectionMissing>;
305
306    /// Get the time dependence for a storage collection. Returns no value if unknown or if
307    /// the object isn't managed by storage.
308    fn determine_time_dependence(
309        &self,
310        id: GlobalId,
311    ) -> Result<Option<TimeDependence>, TimeDependenceError>;
312
313    /// Returns the state of [`StorageCollections`] formatted as JSON.
314    fn dump(&self) -> Result<serde_json::Value, anyhow::Error>;
315}
316
317/// A cursor over a snapshot, allowing us to read just part of a snapshot in its
318/// consolidated form.
319pub struct SnapshotCursor {
320    // We allocate a temporary read handle for each snapshot, and that handle needs to live at
321    // least as long as the cursor itself, which holds part leases. Bundling them together!
322    pub _read_handle: ReadHandle<SourceData, (), Timestamp, StorageDiff>,
323    pub cursor: Cursor<SourceData, (), Timestamp, StorageDiff>,
324}
325
326impl SnapshotCursor {
327    pub async fn next(
328        &mut self,
329    ) -> Option<impl Iterator<Item = (SourceData, Timestamp, StorageDiff)> + Sized + '_> {
330        let iter = self.cursor.next().await?;
331        Some(iter.map(|((k, ()), t, d)| (k, t, d)))
332    }
333}
334
335/// Frontiers of the collection identified by `id`.
336#[derive(Debug)]
337pub struct CollectionFrontiers {
338    /// The [GlobalId] of the collection that these frontiers belong to.
339    pub id: GlobalId,
340
341    /// The upper/write frontier of the collection.
342    pub write_frontier: Antichain<Timestamp>,
343
344    /// The since frontier that is implied by the collection's existence,
345    /// disregarding any read holds.
346    ///
347    /// Concretely, it is the since frontier that is implied by the combination
348    /// of the `write_frontier` and a [ReadPolicy]. The implied capability is
349    /// derived from the write frontier using the [ReadPolicy].
350    pub implied_capability: Antichain<Timestamp>,
351
352    /// The frontier of all oustanding [ReadHolds](ReadHold). This includes the
353    /// implied capability.
354    pub read_capabilities: Antichain<Timestamp>,
355}
356
357/// Implementation of [StorageCollections] that is shallow-cloneable and uses a
358/// background task for doing work concurrently, in the background.
359#[derive(Debug, Clone)]
360pub struct StorageCollectionsImpl {
361    /// The fencing token for this instance of [StorageCollections], and really
362    /// all of the controllers and Coordinator.
363    envd_epoch: NonZeroI64,
364
365    /// Whether or not this [StorageCollections] is in read-only mode.
366    ///
367    /// When in read-only mode, we are not allowed to affect changes to external
368    /// systems, including, for example, acquiring and downgrading critical
369    /// [SinceHandles](SinceHandle)
370    read_only: bool,
371
372    /// The set of [ShardIds](ShardId) that we have to finalize. These will have
373    /// been persisted by the caller of [StorageCollections::prepare_state].
374    finalizable_shards: Arc<ShardIdSet>,
375
376    /// The set of [ShardIds](ShardId) that we have finalized. We keep track of
377    /// shards here until we are given a chance to let our callers know that
378    /// these have been finalized, for example via
379    /// [StorageCollections::prepare_state].
380    finalized_shards: Arc<ShardIdSet>,
381
382    /// Collections maintained by this [StorageCollections].
383    collections: Arc<std::sync::Mutex<BTreeMap<GlobalId, CollectionState>>>,
384
385    /// A shared TxnsCache running in a task and communicated with over a channel.
386    txns_read: TxnsRead<Timestamp>,
387
388    /// Storage configuration parameters.
389    config: Arc<Mutex<StorageConfiguration>>,
390
391    /// The upper of the txn shard as it was when we booted. We forward the
392    /// upper of created/registered tables to make sure that their uppers are
393    /// not less than the initially known txn upper.
394    ///
395    /// NOTE: This works around a quirk in how the adapter chooses the as_of of
396    /// existing indexes when bootstrapping, where tables that have an upper
397    /// that is less than the initially known txn upper can lead to indexes that
398    /// cannot hydrate in read-only mode.
399    initial_txn_upper: Antichain<Timestamp>,
400
401    /// The persist location where all storage collections are being written to
402    persist_location: PersistLocation,
403
404    /// A persist client used to write to storage collections
405    persist: Arc<PersistClientCache>,
406
407    /// For sending commands to our internal task.
408    cmd_tx: mpsc::UnboundedSender<BackgroundCmd>,
409
410    /// For sending updates about read holds to our internal task.
411    holds_tx: mpsc::UnboundedSender<(GlobalId, ChangeBatch<Timestamp>)>,
412
413    /// Handles to tasks we own, making sure they're dropped when we are.
414    _background_task: Arc<AbortOnDropHandle<()>>,
415    _finalize_shards_task: Arc<AbortOnDropHandle<()>>,
416}
417
418// Supporting methods for implementing [StorageCollections].
419//
420// Almost all internal methods that are the backing implementation for a trait
421// method have the `_inner` suffix.
422//
423// We follow a pattern where `_inner` methods get a mutable reference to the
424// shared collections state, and it's the public-facing method that locks the
425/// A boxed stream of source data with timestamps and diffs.
426type SourceDataStream = BoxStream<'static, (SourceData, Timestamp, StorageDiff)>;
427
428// state for the duration of its invocation. This allows calling other `_inner`
429// methods from within `_inner` methods.
430impl StorageCollectionsImpl {
431    /// Creates and returns a new [StorageCollections].
432    ///
433    /// Note that when creating a new [StorageCollections], you must also
434    /// reconcile it with the previous state using
435    /// [StorageCollections::initialize_state],
436    /// [StorageCollections::prepare_state], and
437    /// [StorageCollections::create_collections_for_bootstrap].
438    pub async fn new(
439        persist_location: PersistLocation,
440        persist_clients: Arc<PersistClientCache>,
441        metrics_registry: &MetricsRegistry,
442        _now: NowFn,
443        txns_metrics: Arc<TxnMetrics>,
444        envd_epoch: NonZeroI64,
445        read_only: bool,
446        connection_context: ConnectionContext,
447        txn: &dyn StorageTxn,
448    ) -> Self {
449        let metrics = StorageCollectionsMetrics::register_into(metrics_registry);
450
451        // This value must be already installed because we must ensure it's
452        // durably recorded before it is used, otherwise we risk leaking persist
453        // state.
454        let txns_id = txn
455            .get_txn_wal_shard()
456            .expect("must call prepare initialization before creating StorageCollections");
457
458        let txns_client = persist_clients
459            .open(persist_location.clone())
460            .await
461            .expect("location should be valid");
462
463        // We have to initialize, so that TxnsRead::start() below does not
464        // block.
465        let _txns_handle: TxnsHandle<SourceData, (), Timestamp, StorageDiff, TxnsCodecRow> =
466            TxnsHandle::open(
467                Timestamp::MIN,
468                txns_client.clone(),
469                txns_client.dyncfgs().clone(),
470                Arc::clone(&txns_metrics),
471                txns_id,
472                Opaque::encode(&PersistEpoch::default()),
473            )
474            .await;
475
476        // For handing to the background task, for listening to upper updates.
477        let (txns_key_schema, txns_val_schema) = TxnsCodecRow::schemas();
478        let mut txns_write = txns_client
479            .open_writer(
480                txns_id,
481                Arc::new(txns_key_schema),
482                Arc::new(txns_val_schema),
483                Diagnostics {
484                    shard_name: "txns".to_owned(),
485                    handle_purpose: "commit txns".to_owned(),
486                },
487            )
488            .await
489            .expect("txns schema shouldn't change");
490
491        let txns_read = TxnsRead::start::<TxnsCodecRow>(txns_client.clone(), txns_id).await;
492
493        let collections = Arc::new(std::sync::Mutex::new(BTreeMap::default()));
494        let finalizable_shards = Arc::new(ShardIdSet::new(if read_only {
495            // We use this gauge to see when it's taking too long for shards to be finalized.
496            // A read-only environment cannot finalize shards, so it never gets to decrement the gauge.
497            // The gauge stays elevated (triggering an alarm) until after the environment restarts in non-read-only mode.
498            //
499            // To avoid that false trigger, use an unregistered gauge for read-only envs.
500            mz_ore::metrics::UIntGauge::new(
501                "finalizable_shards",
502                "read-only env can't finalize shards. don't publish this gauge.",
503            )
504            .unwrap()
505        } else {
506            metrics.finalization_outstanding.clone()
507        }));
508        let finalized_shards =
509            Arc::new(ShardIdSet::new(metrics.finalization_pending_commit.clone()));
510        let config = Arc::new(Mutex::new(StorageConfiguration::new(
511            connection_context,
512            mz_dyncfgs::all_dyncfgs(),
513        )));
514
515        let initial_txn_upper = txns_write.fetch_recent_upper().await.to_owned();
516
517        let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
518        let (holds_tx, holds_rx) = mpsc::unbounded_channel();
519        let mut background_task = BackgroundTask {
520            config: Arc::clone(&config),
521            cmds_tx: cmd_tx.clone(),
522            cmds_rx: cmd_rx,
523            holds_rx,
524            collections: Arc::clone(&collections),
525            finalizable_shards: Arc::clone(&finalizable_shards),
526            shard_by_id: BTreeMap::new(),
527            since_handles: BTreeMap::new(),
528            txns_handle: Some(txns_write),
529            txns_shards: Default::default(),
530        };
531
532        let background_task =
533            mz_ore::task::spawn(|| "storage_collections::background_task", async move {
534                background_task.run().await
535            });
536
537        let finalize_shards_task = mz_ore::task::spawn(
538            || "storage_collections::finalize_shards_task",
539            finalize_shards_task(FinalizeShardsTaskConfig {
540                envd_epoch: envd_epoch.clone(),
541                config: Arc::clone(&config),
542                metrics,
543                finalizable_shards: Arc::clone(&finalizable_shards),
544                finalized_shards: Arc::clone(&finalized_shards),
545                persist_location: persist_location.clone(),
546                persist: Arc::clone(&persist_clients),
547                read_only,
548            }),
549        );
550
551        Self {
552            finalizable_shards,
553            finalized_shards,
554            collections,
555            txns_read,
556            envd_epoch,
557            read_only,
558            config,
559            initial_txn_upper,
560            persist_location,
561            persist: persist_clients,
562            cmd_tx,
563            holds_tx,
564            _background_task: Arc::new(background_task.abort_on_drop()),
565            _finalize_shards_task: Arc::new(finalize_shards_task.abort_on_drop()),
566        }
567    }
568
569    /// Opens a [WriteHandle] and a [SinceHandleWrapper], for holding back the since.
570    ///
571    /// `since` is an optional since that the read handle will be forwarded to
572    /// if it is less than its current since.
573    ///
574    /// This will `halt!` the process if we cannot successfully acquire a
575    /// critical handle with our current epoch.
576    async fn open_data_handles(
577        &self,
578        id: &GlobalId,
579        shard: ShardId,
580        since: Option<&Antichain<Timestamp>>,
581        relation_desc: RelationDesc,
582        persist_client: &PersistClient,
583    ) -> (
584        WriteHandle<SourceData, (), Timestamp, StorageDiff>,
585        SinceHandleWrapper,
586    ) {
587        let since_handle = if self.read_only {
588            let read_handle = self
589                .open_leased_handle(id, shard, relation_desc.clone(), since, persist_client)
590                .await;
591            SinceHandleWrapper::Leased(read_handle)
592        } else {
593            // We're managing the data for this shard in read-write mode, which would fence out other
594            // processes in read-only mode; it's safe to upgrade the metadata version.
595            persist_client
596                .upgrade_version::<SourceData, (), Timestamp, StorageDiff>(
597                    shard,
598                    Diagnostics {
599                        shard_name: id.to_string(),
600                        handle_purpose: format!("controller data for {}", id),
601                    },
602                )
603                .await
604                .expect("invalid persist usage");
605
606            let since_handle = self
607                .open_critical_handle(id, shard, since, persist_client)
608                .await;
609
610            SinceHandleWrapper::Critical(since_handle)
611        };
612
613        let mut write_handle = self
614            .open_write_handle(id, shard, relation_desc, persist_client)
615            .await;
616
617        // N.B.
618        // Fetch the most recent upper for the write handle. Otherwise, this may
619        // be behind the since of the since handle. Its vital this happens AFTER
620        // we create the since handle as it needs to be linearized with that
621        // operation. It may be true that creating the write handle after the
622        // since handle already ensures this, but we do this out of an abundance
623        // of caution.
624        //
625        // Note that this returns the upper, but also sets it on the handle to
626        // be fetched later.
627        write_handle.fetch_recent_upper().await;
628
629        (write_handle, since_handle)
630    }
631
632    /// Opens a write handle for the given `shard`.
633    async fn open_write_handle(
634        &self,
635        id: &GlobalId,
636        shard: ShardId,
637        relation_desc: RelationDesc,
638        persist_client: &PersistClient,
639    ) -> WriteHandle<SourceData, (), Timestamp, StorageDiff> {
640        let diagnostics = Diagnostics {
641            shard_name: id.to_string(),
642            handle_purpose: format!("controller data for {}", id),
643        };
644
645        let write = persist_client
646            .open_writer(
647                shard,
648                Arc::new(relation_desc),
649                Arc::new(UnitSchema),
650                diagnostics.clone(),
651            )
652            .await
653            .expect("invalid persist usage");
654
655        write
656    }
657
658    /// Opens a critical since handle for the given `shard`.
659    ///
660    /// `since` is an optional since that the read handle will be forwarded to
661    /// if it is less than its current since.
662    ///
663    /// This will `halt!` the process if we cannot successfully acquire a
664    /// critical handle with our current epoch.
665    async fn open_critical_handle(
666        &self,
667        id: &GlobalId,
668        shard: ShardId,
669        since: Option<&Antichain<Timestamp>>,
670        persist_client: &PersistClient,
671    ) -> SinceHandle<SourceData, (), Timestamp, StorageDiff> {
672        tracing::debug!(%id, ?since, "opening critical handle");
673
674        assert!(
675            !self.read_only,
676            "attempting to open critical SinceHandle in read-only mode"
677        );
678
679        let diagnostics = Diagnostics {
680            shard_name: id.to_string(),
681            handle_purpose: format!("controller data for {}", id),
682        };
683
684        // Construct the handle in a separate block to ensure all error paths
685        // are diverging
686        let since_handle = {
687            // This block's aim is to ensure the handle is in terms of our epoch
688            // by the time we return it.
689            let mut handle = persist_client
690                .open_critical_since(
691                    shard,
692                    PersistClient::CONTROLLER_CRITICAL_SINCE,
693                    Opaque::encode(&PersistEpoch::default()),
694                    diagnostics.clone(),
695                )
696                .await
697                .expect("invalid persist usage");
698
699            // Take the join of the handle's since and the provided `since`;
700            // this lets materialized views express the since at which their
701            // read handles "start."
702            let provided_since = match since {
703                Some(since) => since,
704                None => &Antichain::from_elem(Timestamp::MIN),
705            };
706            let since = handle.since().join(provided_since);
707
708            let our_epoch = self.envd_epoch;
709
710            loop {
711                let current_epoch: PersistEpoch = handle.opaque().decode();
712
713                // Ensure the current epoch is <= our epoch.
714                let unchecked_success = current_epoch.0.map(|e| e <= our_epoch).unwrap_or(true);
715
716                if unchecked_success {
717                    // Update the handle's state so that it is in terms of our
718                    // epoch.
719                    let checked_success = handle
720                        .compare_and_downgrade_since(
721                            &Opaque::encode(&current_epoch),
722                            (&Opaque::encode(&PersistEpoch::from(our_epoch)), &since),
723                        )
724                        .await
725                        .is_ok();
726                    if checked_success {
727                        break handle;
728                    }
729                } else {
730                    mz_ore::halt!("fenced by envd @ {current_epoch:?}. ours = {our_epoch}");
731                }
732            }
733        };
734
735        since_handle
736    }
737
738    /// Opens a leased [ReadHandle], for the purpose of holding back a since,
739    /// for the given `shard`.
740    ///
741    /// `since` is an optional since that the read handle will be forwarded to
742    /// if it is less than its current since.
743    async fn open_leased_handle(
744        &self,
745        id: &GlobalId,
746        shard: ShardId,
747        relation_desc: RelationDesc,
748        since: Option<&Antichain<Timestamp>>,
749        persist_client: &PersistClient,
750    ) -> ReadHandle<SourceData, (), Timestamp, StorageDiff> {
751        tracing::debug!(%id, ?since, "opening leased handle");
752
753        let diagnostics = Diagnostics {
754            shard_name: id.to_string(),
755            handle_purpose: format!("controller data for {}", id),
756        };
757
758        let use_critical_since = false;
759        let mut handle: ReadHandle<_, _, _, _> = persist_client
760            .open_leased_reader(
761                shard,
762                Arc::new(relation_desc),
763                Arc::new(UnitSchema),
764                diagnostics.clone(),
765                use_critical_since,
766            )
767            .await
768            .expect("invalid persist usage");
769
770        // Take the join of the handle's since and the provided `since`;
771        // this lets materialized views express the since at which their
772        // read handles "start."
773        let provided_since = match since {
774            Some(since) => since,
775            None => &Antichain::from_elem(Timestamp::MIN),
776        };
777        let since = handle.since().join(provided_since);
778
779        handle.downgrade_since(&since).await;
780
781        handle
782    }
783
784    fn register_handles(
785        &self,
786        id: GlobalId,
787        is_in_txns: bool,
788        since_handle: SinceHandleWrapper,
789        write_handle: WriteHandle<SourceData, (), Timestamp, StorageDiff>,
790    ) {
791        self.send(BackgroundCmd::Register {
792            id,
793            is_in_txns,
794            since_handle,
795            write_handle,
796        });
797    }
798
799    fn send(&self, cmd: BackgroundCmd) {
800        let _ = self.cmd_tx.send(cmd);
801    }
802
803    async fn snapshot_stats_inner(
804        &self,
805        id: GlobalId,
806        as_of: SnapshotStatsAsOf,
807    ) -> Result<SnapshotStats, StorageError> {
808        // TODO: Pull this out of BackgroundTask. Unlike the other methods, the
809        // caller of this one drives it to completion.
810        //
811        // We'd need to either share the critical handle somehow or maybe have
812        // two instances around, one in the worker and one in the
813        // StorageCollections.
814        let (tx, rx) = oneshot::channel();
815        self.send(BackgroundCmd::SnapshotStats(id, as_of, tx));
816        rx.await.expect("BackgroundTask should be live").0.await
817    }
818
819    /// If this identified collection has a dependency, install a read hold on
820    /// it.
821    ///
822    /// This is necessary to ensure that the dependency's since does not advance
823    /// beyond its dependents'.
824    fn install_collection_dependency_read_holds_inner(
825        &self,
826        self_collections: &mut BTreeMap<GlobalId, CollectionState>,
827        id: GlobalId,
828    ) -> Result<(), StorageError> {
829        let (deps, collection_implied_capability) = match self_collections.get(&id) {
830            Some(CollectionState {
831                storage_dependencies: deps,
832                implied_capability,
833                ..
834            }) => (deps.clone(), implied_capability),
835            _ => return Ok(()),
836        };
837
838        for dep in deps.iter() {
839            let dep_collection = self_collections
840                .get(dep)
841                .ok_or(StorageError::IdentifierMissing(id))?;
842
843            mz_ore::soft_assert_or_log!(
844                PartialOrder::less_equal(
845                    &dep_collection.implied_capability,
846                    collection_implied_capability
847                ),
848                "dependency since ({dep}@{:?}) cannot be in advance of dependent's since ({id}@{:?})",
849                dep_collection.implied_capability,
850                collection_implied_capability,
851            );
852        }
853
854        self.install_read_capabilities_inner(
855            self_collections,
856            id,
857            &deps,
858            collection_implied_capability.clone(),
859        )?;
860
861        Ok(())
862    }
863
864    /// Returns the given collection's dependencies.
865    fn determine_collection_dependencies(
866        self_collections: &BTreeMap<GlobalId, CollectionState>,
867        source_id: GlobalId,
868        collection_desc: &CollectionDescription,
869    ) -> Result<Vec<GlobalId>, StorageError> {
870        let mut dependencies = Vec::new();
871
872        if let Some(id) = collection_desc.primary {
873            dependencies.push(id);
874        }
875
876        match &collection_desc.data_source {
877            DataSource::Introspection(_)
878            | DataSource::Webhook
879            | DataSource::Table
880            | DataSource::Progress
881            | DataSource::Other => (),
882            DataSource::IngestionExport {
883                ingestion_id,
884                data_config,
885                ..
886            } => {
887                // Ingestion exports depend on their primary source's remap
888                // collection, except when they use a CDCv2 envelope.
889                let source = self_collections
890                    .get(ingestion_id)
891                    .ok_or(StorageError::IdentifierMissing(*ingestion_id))?;
892                let Some(remap_collection_id) = &source.ingestion_remap_collection_id else {
893                    panic!("SourceExport must refer to a primary source that already exists");
894                };
895
896                match data_config.envelope {
897                    SourceEnvelope::CdcV2 => (),
898                    _ => dependencies.push(*remap_collection_id),
899                }
900            }
901            // Ingestions depend on their remap collection.
902            DataSource::Ingestion(ingestion) => {
903                if ingestion.remap_collection_id != source_id {
904                    dependencies.push(ingestion.remap_collection_id);
905                }
906            }
907            DataSource::Sink { desc } => dependencies.push(desc.sink.from),
908        }
909
910        Ok(dependencies)
911    }
912
913    /// Install read capabilities on the given `storage_dependencies`.
914    #[instrument(level = "debug")]
915    fn install_read_capabilities_inner(
916        &self,
917        self_collections: &mut BTreeMap<GlobalId, CollectionState>,
918        from_id: GlobalId,
919        storage_dependencies: &[GlobalId],
920        read_capability: Antichain<Timestamp>,
921    ) -> Result<(), StorageError> {
922        let mut changes = ChangeBatch::new();
923        for time in read_capability.iter() {
924            changes.update(*time, 1);
925        }
926
927        if tracing::span_enabled!(tracing::Level::TRACE) {
928            // Collecting `user_capabilities` is potentially slow, thus only do it when needed.
929            let user_capabilities = self_collections
930                .iter_mut()
931                .filter(|(id, _c)| id.is_user())
932                .map(|(id, c)| {
933                    let updates = c.read_capabilities.updates().cloned().collect_vec();
934                    (*id, c.implied_capability.clone(), updates)
935                })
936                .collect_vec();
937
938            trace!(
939                %from_id,
940                ?storage_dependencies,
941                ?read_capability,
942                ?user_capabilities,
943                "install_read_capabilities_inner");
944        }
945
946        let mut storage_read_updates = storage_dependencies
947            .iter()
948            .map(|id| (*id, changes.clone()))
949            .collect();
950
951        StorageCollectionsImpl::update_read_capabilities_inner(
952            &self.cmd_tx,
953            self_collections,
954            &mut storage_read_updates,
955        );
956
957        if tracing::span_enabled!(tracing::Level::TRACE) {
958            // Collecting `user_capabilities` is potentially slow, thus only do it when needed.
959            let user_capabilities = self_collections
960                .iter_mut()
961                .filter(|(id, _c)| id.is_user())
962                .map(|(id, c)| {
963                    let updates = c.read_capabilities.updates().cloned().collect_vec();
964                    (*id, c.implied_capability.clone(), updates)
965                })
966                .collect_vec();
967
968            trace!(
969                %from_id,
970                ?storage_dependencies,
971                ?read_capability,
972                ?user_capabilities,
973                "after install_read_capabilities_inner!");
974        }
975
976        Ok(())
977    }
978
979    async fn recent_upper(&self, id: GlobalId) -> Result<Antichain<Timestamp>, StorageError> {
980        let metadata = &self.collection_metadata(id)?;
981        let persist_client = self
982            .persist
983            .open(metadata.persist_location.clone())
984            .await
985            .unwrap();
986        // Duplicate part of open_data_handles here because we don't need the
987        // fetch_recent_upper call. The pubsub-updated shared_upper is enough.
988        let diagnostics = Diagnostics {
989            shard_name: id.to_string(),
990            handle_purpose: format!("controller data for {}", id),
991        };
992        // NB: Opening a WriteHandle is cheap if it's never used in a
993        // compare_and_append operation.
994        let write = persist_client
995            .open_writer::<SourceData, (), Timestamp, StorageDiff>(
996                metadata.data_shard,
997                Arc::new(metadata.relation_desc.clone()),
998                Arc::new(UnitSchema),
999                diagnostics.clone(),
1000            )
1001            .await
1002            .expect("invalid persist usage");
1003        Ok(write.shared_upper())
1004    }
1005
1006    async fn read_handle_for_snapshot(
1007        persist: Arc<PersistClientCache>,
1008        metadata: &CollectionMetadata,
1009        id: GlobalId,
1010    ) -> Result<ReadHandle<SourceData, (), Timestamp, StorageDiff>, StorageError> {
1011        let persist_client = persist
1012            .open(metadata.persist_location.clone())
1013            .await
1014            .unwrap();
1015
1016        // We create a new read handle every time someone requests a snapshot
1017        // and then immediately expire it instead of keeping a read handle
1018        // permanently in our state to avoid having it heartbeat continually.
1019        // The assumption is that calls to snapshot are rare and therefore worth
1020        // it to always create a new handle.
1021        let read_handle = persist_client
1022            .open_leased_reader::<SourceData, (), _, _>(
1023                metadata.data_shard,
1024                Arc::new(metadata.relation_desc.clone()),
1025                Arc::new(UnitSchema),
1026                Diagnostics {
1027                    shard_name: id.to_string(),
1028                    handle_purpose: format!("snapshot {}", id),
1029                },
1030                USE_CRITICAL_SINCE_SNAPSHOT.get(&persist.cfg),
1031            )
1032            .await
1033            .expect("invalid persist usage");
1034        Ok(read_handle)
1035    }
1036
1037    fn snapshot(
1038        &self,
1039        id: GlobalId,
1040        as_of: Timestamp,
1041        txns_read: &TxnsRead<Timestamp>,
1042    ) -> BoxFuture<'static, Result<Vec<(Row, StorageDiff)>, StorageError>> {
1043        let metadata = match self.collection_metadata(id) {
1044            Ok(metadata) => metadata.clone(),
1045            Err(e) => return async { Err(e.into()) }.boxed(),
1046        };
1047        let txns_read = metadata.txns_shard.as_ref().map(|txns_id| {
1048            assert_eq!(txns_id, txns_read.txns_id());
1049            txns_read.clone()
1050        });
1051        let persist = Arc::clone(&self.persist);
1052        async move {
1053            let mut read_handle = Self::read_handle_for_snapshot(persist, &metadata, id).await?;
1054            let contents = match txns_read {
1055                None => {
1056                    // We're not using txn-wal for tables, so we can take a snapshot directly.
1057                    read_handle
1058                        .snapshot_and_fetch(Antichain::from_elem(as_of))
1059                        .await
1060                }
1061                Some(txns_read) => {
1062                    // We _are_ using txn-wal for tables. It advances the physical upper of the
1063                    // shard lazily, so we need to ask it for the snapshot to ensure the read is
1064                    // unblocked.
1065                    //
1066                    // Consider the following scenario:
1067                    // - Table A is written to via txns at time 5
1068                    // - Tables other than A are written to via txns consuming timestamps up to 10
1069                    // - We'd like to read A at 7
1070                    // - The application process of A's txn has advanced the upper to 5+1, but we need
1071                    //   it to be past 7, but the txns shard knows that (5,10) is empty of writes to A
1072                    // - This branch allows it to handle that advancing the physical upper of Table A to
1073                    //   10 (NB but only once we see it get past the write at 5!)
1074                    // - Then we can read it normally.
1075                    txns_read.update_gt(as_of).await;
1076                    let data_snapshot = txns_read.data_snapshot(metadata.data_shard, as_of).await;
1077                    data_snapshot.snapshot_and_fetch(&mut read_handle).await
1078                }
1079            };
1080            match contents {
1081                Ok(contents) => {
1082                    let mut snapshot = Vec::with_capacity(contents.len());
1083                    for ((data, _), _, diff) in contents {
1084                        // TODO(petrosagg): We should accumulate the errors too and let the user
1085                        // interpret the result
1086                        let row = data.0?;
1087                        snapshot.push((row, diff));
1088                    }
1089                    Ok(snapshot)
1090                }
1091                Err(_) => Err(StorageError::ReadBeforeSince(id)),
1092            }
1093        }
1094        .boxed()
1095    }
1096
1097    fn snapshot_and_stream(
1098        &self,
1099        id: GlobalId,
1100        as_of: Timestamp,
1101        txns_read: &TxnsRead<Timestamp>,
1102    ) -> BoxFuture<'static, Result<SourceDataStream, StorageError>> {
1103        let metadata = match self.collection_metadata(id) {
1104            Ok(metadata) => metadata.clone(),
1105            Err(e) => return async { Err(e.into()) }.boxed(),
1106        };
1107        let txns_read = metadata.txns_shard.as_ref().map(|txns_id| {
1108            assert_eq!(txns_id, txns_read.txns_id());
1109            txns_read.clone()
1110        });
1111        let persist = Arc::clone(&self.persist);
1112        Self::snapshot_and_stream_inner(persist, metadata, id, as_of, txns_read)
1113    }
1114
1115    /// [Self::snapshot_and_stream] without `self`, so tests can call it.
1116    fn snapshot_and_stream_inner(
1117        persist: Arc<PersistClientCache>,
1118        metadata: CollectionMetadata,
1119        id: GlobalId,
1120        as_of: Timestamp,
1121        txns_read: Option<TxnsRead<Timestamp>>,
1122    ) -> BoxFuture<'static, Result<SourceDataStream, StorageError>> {
1123        use futures::stream::StreamExt;
1124
1125        async move {
1126            let mut read_handle = Self::read_handle_for_snapshot(persist, &metadata, id).await?;
1127            let stream = match txns_read {
1128                None => {
1129                    // We're not using txn-wal for tables, so we can take a snapshot directly.
1130                    read_handle
1131                        .snapshot_and_stream(Antichain::from_elem(as_of))
1132                        .await
1133                        .map_err(|_| StorageError::ReadBeforeSince(id))?
1134                        .boxed()
1135                }
1136                Some(txns_read) => {
1137                    txns_read.update_gt(as_of).await;
1138                    let data_snapshot = txns_read.data_snapshot(metadata.data_shard, as_of).await;
1139                    data_snapshot
1140                        .snapshot_and_stream(&mut read_handle)
1141                        .await
1142                        .map_err(|_| StorageError::ReadBeforeSince(id))?
1143                        .boxed()
1144                }
1145            };
1146
1147            // Map our stream, unwrapping Persist internal errors.
1148            //
1149            // The stream fetches parts lazily, after this function returns, so it
1150            // must own `read_handle`. Dropping the handle expires the reader, which
1151            // releases its seqno hold, and GC can then delete parts the stream has
1152            // yet to fetch. That fetch finds the reader gone and halts as a lost
1153            // lease. The closure only references `read_handle` to move it into the
1154            // stream: don't remove it as unused.
1155            let stream = stream
1156                .map(move |((data, _v), t, d)| {
1157                    let _read_handle = &read_handle;
1158                    (data, t, d)
1159                })
1160                .boxed();
1161            Ok(stream)
1162        }
1163        .boxed()
1164    }
1165
1166    fn set_read_policies_inner(
1167        &self,
1168        collections: &mut BTreeMap<GlobalId, CollectionState>,
1169        policies: Vec<(GlobalId, ReadPolicy)>,
1170    ) {
1171        trace!("set_read_policies: {:?}", policies);
1172
1173        let mut read_capability_changes = BTreeMap::default();
1174
1175        for (id, policy) in policies.into_iter() {
1176            let collection = match collections.get_mut(&id) {
1177                Some(c) => c,
1178                None => {
1179                    panic!("Reference to absent collection {id}");
1180                }
1181            };
1182
1183            let mut new_read_capability = policy.frontier(collection.write_frontier.borrow());
1184
1185            if PartialOrder::less_equal(&collection.implied_capability, &new_read_capability) {
1186                let mut update = ChangeBatch::new();
1187                update.extend(new_read_capability.iter().map(|time| (*time, 1)));
1188                std::mem::swap(&mut collection.implied_capability, &mut new_read_capability);
1189                update.extend(new_read_capability.iter().map(|time| (*time, -1)));
1190                if !update.is_empty() {
1191                    read_capability_changes.insert(id, update);
1192                }
1193            }
1194
1195            collection.read_policy = policy;
1196        }
1197
1198        for (id, changes) in read_capability_changes.iter() {
1199            if id.is_user() {
1200                trace!(%id, ?changes, "in set_read_policies, capability changes");
1201            }
1202        }
1203
1204        if !read_capability_changes.is_empty() {
1205            StorageCollectionsImpl::update_read_capabilities_inner(
1206                &self.cmd_tx,
1207                collections,
1208                &mut read_capability_changes,
1209            );
1210        }
1211    }
1212
1213    // This is not an associated function so that we can share it with the task
1214    // that updates the persist handles and also has a reference to the shared
1215    // collections state.
1216    fn update_read_capabilities_inner(
1217        cmd_tx: &mpsc::UnboundedSender<BackgroundCmd>,
1218        collections: &mut BTreeMap<GlobalId, CollectionState>,
1219        updates: &mut BTreeMap<GlobalId, ChangeBatch<Timestamp>>,
1220    ) {
1221        // Location to record consequences that we need to act on.
1222        let mut collections_net = BTreeMap::new();
1223
1224        // We must not rely on any specific relative ordering of `GlobalId`s.
1225        // That said, it is reasonable to assume that collections generally have
1226        // greater IDs than their dependencies, so starting with the largest is
1227        // a useful optimization.
1228        while let Some(id) = updates.keys().rev().next().cloned() {
1229            let mut update = updates.remove(&id).unwrap();
1230
1231            if id.is_user() {
1232                trace!(id = ?id, update = ?update, "update_read_capabilities");
1233            }
1234
1235            let collection = if let Some(c) = collections.get_mut(&id) {
1236                c
1237            } else {
1238                let has_positive_updates = update.iter().any(|(_ts, diff)| *diff > 0);
1239                if has_positive_updates {
1240                    panic!(
1241                        "reference to absent collection {id} but we have positive updates: {:?}",
1242                        update
1243                    );
1244                } else {
1245                    // Continue purely negative updates. Someone has probably
1246                    // already dropped this collection!
1247                    continue;
1248                }
1249            };
1250
1251            let current_read_capabilities = collection.read_capabilities.frontier().to_owned();
1252            for (time, diff) in update.iter() {
1253                assert!(
1254                    collection.read_capabilities.count_for(time) + diff >= 0,
1255                    "update {:?} for collection {id} would lead to negative \
1256                        read capabilities, read capabilities before applying: {:?}",
1257                    update,
1258                    collection.read_capabilities
1259                );
1260
1261                if collection.read_capabilities.count_for(time) + diff > 0 {
1262                    assert!(
1263                        current_read_capabilities.less_equal(time),
1264                        "update {:?} for collection {id} is trying to \
1265                            install read capabilities before the current \
1266                            frontier of read capabilities, read capabilities before applying: {:?}",
1267                        update,
1268                        collection.read_capabilities
1269                    );
1270                }
1271            }
1272
1273            let changes = collection.read_capabilities.update_iter(update.drain());
1274            update.extend(changes);
1275
1276            if id.is_user() {
1277                trace!(
1278                %id,
1279                ?collection.storage_dependencies,
1280                ?update,
1281                "forwarding update to storage dependencies");
1282            }
1283
1284            for id in collection.storage_dependencies.iter() {
1285                updates
1286                    .entry(*id)
1287                    .or_insert_with(ChangeBatch::new)
1288                    .extend(update.iter().cloned());
1289            }
1290
1291            let (changes, frontier) = collections_net
1292                .entry(id)
1293                .or_insert_with(|| (<ChangeBatch<_>>::new(), Antichain::new()));
1294
1295            changes.extend(update.drain());
1296            *frontier = collection.read_capabilities.frontier().to_owned();
1297        }
1298
1299        // Translate our net compute actions into downgrades of persist sinces.
1300        // The actual downgrades are performed by a Tokio task asynchronously.
1301        let mut persist_compaction_commands = Vec::with_capacity(collections_net.len());
1302        for (key, (mut changes, frontier)) in collections_net {
1303            if !changes.is_empty() {
1304                // If the collection has a "primary" collection, let that primary drive compaction.
1305                let collection = collections.get(&key).expect("must still exist");
1306                let should_emit_persist_compaction = collection.primary.is_none();
1307
1308                if frontier.is_empty() {
1309                    info!(id = %key, "removing collection state because the since advanced to []!");
1310                    collections.remove(&key).expect("must still exist");
1311                }
1312
1313                if should_emit_persist_compaction {
1314                    persist_compaction_commands.push((key, frontier));
1315                }
1316            }
1317        }
1318
1319        if !persist_compaction_commands.is_empty() {
1320            cmd_tx
1321                .send(BackgroundCmd::DowngradeSince(persist_compaction_commands))
1322                .expect("cannot fail to send");
1323        }
1324    }
1325
1326    /// Remove any shards that we know are finalized
1327    fn synchronize_finalized_shards(&self, storage_metadata: &StorageMetadata) {
1328        self.finalized_shards
1329            .lock()
1330            .retain(|shard| storage_metadata.unfinalized_shards.contains(shard));
1331    }
1332}
1333
1334/// Partitions the finalization WAL by whether an active collection references
1335/// each shard.
1336fn partition_finalizable_shards(
1337    collection_metadata: BTreeMap<GlobalId, ShardId>,
1338    active_collection_ids: &BTreeSet<GlobalId>,
1339    unfinalized_shards: BTreeSet<ShardId>,
1340) -> (BTreeSet<ShardId>, BTreeSet<ShardId>) {
1341    let active_shards: BTreeSet<_> = collection_metadata
1342        .into_iter()
1343        .filter_map(|(id, shard)| active_collection_ids.contains(&id).then_some(shard))
1344        .collect();
1345    let referenced_shards = unfinalized_shards
1346        .intersection(&active_shards)
1347        .copied()
1348        .collect();
1349    let finalizable_shards = unfinalized_shards
1350        .difference(&active_shards)
1351        .copied()
1352        .collect();
1353
1354    (referenced_shards, finalizable_shards)
1355}
1356
1357// See comments on the above impl for StorageCollectionsImpl.
1358#[async_trait]
1359impl StorageCollections for StorageCollectionsImpl {
1360    async fn initialize_state(
1361        &self,
1362        txn: &mut (dyn StorageTxn + Send),
1363        init_ids: BTreeSet<GlobalId>,
1364    ) -> Result<(), StorageError> {
1365        let metadata = txn.get_collection_metadata();
1366        let existing_metadata: BTreeSet<_> = metadata.into_iter().map(|(id, _)| id).collect();
1367
1368        // Determine which collections we do not yet have metadata for.
1369        let new_collections: BTreeSet<GlobalId> =
1370            init_ids.difference(&existing_metadata).cloned().collect();
1371
1372        self.prepare_state(
1373            txn,
1374            new_collections,
1375            BTreeSet::default(),
1376            BTreeMap::default(),
1377        )
1378        .await?;
1379
1380        // All unreferenced shards that belong to collections dropped in the
1381        // last epoch are eligible for finalization. Active collection metadata
1382        // is authoritative over stale finalization WAL entries.
1383        //
1384        // A dropped collection can still have a dataflow running on a worker.
1385        // Finalizing its shard on reboot can cause that worker to panic.
1386        let (referenced_shards, unfinalized_shards) = partition_finalizable_shards(
1387            txn.get_collection_metadata(),
1388            &init_ids,
1389            txn.get_unfinalized_shards(),
1390        );
1391        if !referenced_shards.is_empty() {
1392            warn!(
1393                ?referenced_shards,
1394                "removing active collection shards from the finalization WAL"
1395            );
1396            // Collection metadata is authoritative. Removing these entries in
1397            // the initialization transaction keeps them out of the finalizer
1398            // queue.
1399            txn.remove_unfinalized_shards(referenced_shards);
1400        }
1401
1402        info!(?unfinalized_shards, "initializing finalizable_shards");
1403
1404        self.finalizable_shards.lock().extend(unfinalized_shards);
1405
1406        Ok(())
1407    }
1408
1409    fn update_parameters(&self, config_params: StorageParameters) {
1410        // We serialize the dyncfg updates in StorageParameters, but configure
1411        // persist separately.
1412        config_params.dyncfg_updates.apply(self.persist.cfg());
1413
1414        self.config
1415            .lock()
1416            .expect("lock poisoned")
1417            .update(config_params);
1418    }
1419
1420    fn collection_metadata(&self, id: GlobalId) -> Result<CollectionMetadata, CollectionMissing> {
1421        let collections = self.collections.lock().expect("lock poisoned");
1422
1423        collections
1424            .get(&id)
1425            .map(|c| c.collection_metadata.clone())
1426            .ok_or(CollectionMissing(id))
1427    }
1428
1429    fn active_collection_metadatas(&self) -> Vec<(GlobalId, CollectionMetadata)> {
1430        let collections = self.collections.lock().expect("lock poisoned");
1431
1432        collections
1433            .iter()
1434            .filter(|(_id, c)| !c.is_dropped())
1435            .map(|(id, c)| (*id, c.collection_metadata.clone()))
1436            .collect()
1437    }
1438
1439    fn collections_frontiers(
1440        &self,
1441        ids: Vec<GlobalId>,
1442    ) -> Result<Vec<CollectionFrontiers>, CollectionMissing> {
1443        if ids.is_empty() {
1444            return Ok(vec![]);
1445        }
1446
1447        let collections = self.collections.lock().expect("lock poisoned");
1448
1449        let res = ids
1450            .into_iter()
1451            .map(|id| {
1452                collections
1453                    .get(&id)
1454                    .map(|c| CollectionFrontiers {
1455                        id: id.clone(),
1456                        write_frontier: c.write_frontier.clone(),
1457                        implied_capability: c.implied_capability.clone(),
1458                        read_capabilities: c.read_capabilities.frontier().to_owned(),
1459                    })
1460                    .ok_or(CollectionMissing(id))
1461            })
1462            .collect::<Result<Vec<_>, _>>()?;
1463
1464        Ok(res)
1465    }
1466
1467    fn active_collection_frontiers(&self) -> Vec<CollectionFrontiers> {
1468        let collections = self.collections.lock().expect("lock poisoned");
1469
1470        let res = collections
1471            .iter()
1472            .filter(|(_id, c)| !c.is_dropped())
1473            .map(|(id, c)| CollectionFrontiers {
1474                id: id.clone(),
1475                write_frontier: c.write_frontier.clone(),
1476                implied_capability: c.implied_capability.clone(),
1477                read_capabilities: c.read_capabilities.frontier().to_owned(),
1478            })
1479            .collect_vec();
1480
1481        res
1482    }
1483
1484    async fn snapshot_stats(
1485        &self,
1486        id: GlobalId,
1487        as_of: Antichain<Timestamp>,
1488    ) -> Result<SnapshotStats, StorageError> {
1489        let metadata = self.collection_metadata(id)?;
1490
1491        // See the comments in StorageController::snapshot for what's going on
1492        // here.
1493        let as_of = match metadata.txns_shard.as_ref() {
1494            None => SnapshotStatsAsOf::Direct(as_of),
1495            Some(txns_id) => {
1496                assert_eq!(txns_id, self.txns_read.txns_id());
1497                let as_of = as_of
1498                    .into_option()
1499                    .expect("cannot read as_of the empty antichain");
1500                self.txns_read.update_gt(as_of).await;
1501                let data_snapshot = self
1502                    .txns_read
1503                    .data_snapshot(metadata.data_shard, as_of)
1504                    .await;
1505                SnapshotStatsAsOf::Txns(data_snapshot)
1506            }
1507        };
1508        self.snapshot_stats_inner(id, as_of).await
1509    }
1510
1511    async fn snapshot_parts_stats(
1512        &self,
1513        id: GlobalId,
1514        as_of: Antichain<Timestamp>,
1515    ) -> BoxFuture<'static, Result<SnapshotPartsStats, StorageError>> {
1516        let metadata = {
1517            let self_collections = self.collections.lock().expect("lock poisoned");
1518
1519            let collection_metadata = self_collections
1520                .get(&id)
1521                .ok_or(StorageError::IdentifierMissing(id))
1522                .map(|c| c.collection_metadata.clone());
1523
1524            match collection_metadata {
1525                Ok(m) => m,
1526                Err(e) => return Box::pin(async move { Err(e) }),
1527            }
1528        };
1529
1530        // See the comments in StorageController::snapshot for what's going on
1531        // here.
1532        let persist = Arc::clone(&self.persist);
1533        let read_handle = Self::read_handle_for_snapshot(persist, &metadata, id).await;
1534
1535        let data_snapshot = match (metadata, as_of.as_option()) {
1536            (
1537                CollectionMetadata {
1538                    txns_shard: Some(txns_id),
1539                    data_shard,
1540                    ..
1541                },
1542                Some(as_of),
1543            ) => {
1544                assert_eq!(txns_id, *self.txns_read.txns_id());
1545                self.txns_read.update_gt(*as_of).await;
1546                let data_snapshot = self.txns_read.data_snapshot(data_shard, *as_of).await;
1547                Some(data_snapshot)
1548            }
1549            _ => None,
1550        };
1551
1552        Box::pin(async move {
1553            let read_handle = read_handle?;
1554            let result = match data_snapshot {
1555                Some(data_snapshot) => data_snapshot.snapshot_parts_stats(&read_handle).await,
1556                None => read_handle.snapshot_parts_stats(as_of).await,
1557            };
1558            read_handle.expire().await;
1559            result.map_err(|_| StorageError::ReadBeforeSince(id))
1560        })
1561    }
1562
1563    fn snapshot(
1564        &self,
1565        id: GlobalId,
1566        as_of: Timestamp,
1567    ) -> BoxFuture<'static, Result<Vec<(Row, StorageDiff)>, StorageError>> {
1568        self.snapshot(id, as_of, &self.txns_read)
1569    }
1570
1571    async fn snapshot_latest(&self, id: GlobalId) -> Result<Vec<Row>, StorageError> {
1572        let upper = self.recent_upper(id).await?;
1573        let res = match upper.as_option() {
1574            Some(f) if f > &Timestamp::MIN => {
1575                let as_of = f.step_back().expect("checked that f > &Timestamp::MIN");
1576
1577                let snapshot = self.snapshot(id, as_of, &self.txns_read).await?;
1578                snapshot
1579                    .into_iter()
1580                    .map(|(row, diff)| {
1581                        // See the trait doc: `snapshot_latest` is only meant for collections that
1582                        // consolidate to a set.
1583                        assert_eq!(diff, 1, "snapshot doesn't accumulate to set");
1584                        row
1585                    })
1586                    .collect()
1587            }
1588            Some(_min) => {
1589                // The collection must be empty!
1590                Vec::new()
1591            }
1592            // The collection is closed, we cannot determine a latest read
1593            // timestamp based on the upper.
1594            _ => {
1595                return Err(StorageError::InvalidUsage(
1596                    "collection closed, cannot determine a read timestamp based on the upper"
1597                        .to_string(),
1598                ));
1599            }
1600        };
1601
1602        Ok(res)
1603    }
1604
1605    fn snapshot_cursor(
1606        &self,
1607        id: GlobalId,
1608        as_of: Timestamp,
1609    ) -> BoxFuture<'static, Result<SnapshotCursor, StorageError>> {
1610        let metadata = match self.collection_metadata(id) {
1611            Ok(metadata) => metadata.clone(),
1612            Err(e) => return async { Err(e.into()) }.boxed(),
1613        };
1614        let txns_read = metadata.txns_shard.as_ref().map(|txns_id| {
1615            // Ensure the txn's shard the controller has is the same that this
1616            // collection is registered to.
1617            assert_eq!(txns_id, self.txns_read.txns_id());
1618            self.txns_read.clone()
1619        });
1620        let persist = Arc::clone(&self.persist);
1621
1622        // See the comments in Self::snapshot for what's going on here.
1623        async move {
1624            let mut handle = Self::read_handle_for_snapshot(persist, &metadata, id).await?;
1625            let cursor = match txns_read {
1626                None => {
1627                    let cursor = handle
1628                        .snapshot_cursor(Antichain::from_elem(as_of), |_| true)
1629                        .await
1630                        .map_err(|_| StorageError::ReadBeforeSince(id))?;
1631                    SnapshotCursor {
1632                        _read_handle: handle,
1633                        cursor,
1634                    }
1635                }
1636                Some(txns_read) => {
1637                    txns_read.update_gt(as_of).await;
1638                    let data_snapshot = txns_read.data_snapshot(metadata.data_shard, as_of).await;
1639                    let cursor = data_snapshot
1640                        .snapshot_cursor(&mut handle, |_| true)
1641                        .await
1642                        .map_err(|_| StorageError::ReadBeforeSince(id))?;
1643                    SnapshotCursor {
1644                        _read_handle: handle,
1645                        cursor,
1646                    }
1647                }
1648            };
1649
1650            Ok(cursor)
1651        }
1652        .boxed()
1653    }
1654
1655    fn snapshot_and_stream(
1656        &self,
1657        id: GlobalId,
1658        as_of: Timestamp,
1659    ) -> BoxFuture<
1660        'static,
1661        Result<BoxStream<'static, (SourceData, Timestamp, StorageDiff)>, StorageError>,
1662    > {
1663        self.snapshot_and_stream(id, as_of, &self.txns_read)
1664    }
1665
1666    fn create_update_builder(
1667        &self,
1668        id: GlobalId,
1669    ) -> BoxFuture<
1670        'static,
1671        Result<TimestamplessUpdateBuilder<SourceData, (), StorageDiff>, StorageError>,
1672    > {
1673        let metadata = match self.collection_metadata(id) {
1674            Ok(m) => m,
1675            Err(e) => return Box::pin(async move { Err(e.into()) }),
1676        };
1677        let persist = Arc::clone(&self.persist);
1678
1679        async move {
1680            let persist_client = persist
1681                .open(metadata.persist_location.clone())
1682                .await
1683                .expect("invalid persist usage");
1684            let write_handle = persist_client
1685                .open_writer::<SourceData, (), Timestamp, StorageDiff>(
1686                    metadata.data_shard,
1687                    Arc::new(metadata.relation_desc.clone()),
1688                    Arc::new(UnitSchema),
1689                    Diagnostics {
1690                        shard_name: id.to_string(),
1691                        handle_purpose: format!("create write batch {}", id),
1692                    },
1693                )
1694                .await
1695                .expect("invalid persist usage");
1696            let builder = TimestamplessUpdateBuilder::new(&write_handle);
1697
1698            Ok(builder)
1699        }
1700        .boxed()
1701    }
1702
1703    fn check_exists(&self, id: GlobalId) -> Result<(), StorageError> {
1704        let collections = self.collections.lock().expect("lock poisoned");
1705
1706        if collections.contains_key(&id) {
1707            Ok(())
1708        } else {
1709            Err(StorageError::IdentifierMissing(id))
1710        }
1711    }
1712
1713    async fn prepare_state(
1714        &self,
1715        txn: &mut (dyn StorageTxn + Send),
1716        ids_to_add: BTreeSet<GlobalId>,
1717        ids_to_drop: BTreeSet<GlobalId>,
1718        ids_to_register: BTreeMap<GlobalId, ShardId>,
1719    ) -> Result<(), StorageError> {
1720        // Durable metadata can outlive its collection. Reconcile it with live
1721        // collection state so orphaned mappings do not block finalization.
1722        let mut active_collection_ids: BTreeSet<_> = {
1723            let collections = self.collections.lock().expect("poisoned");
1724            collections
1725                .iter()
1726                .filter_map(|(id, collection)| {
1727                    (!ids_to_drop.contains(id) && !collection.is_dropped()).then_some(*id)
1728                })
1729                .collect()
1730        };
1731        active_collection_ids.extend(ids_to_add.iter().copied());
1732        active_collection_ids.extend(ids_to_register.keys().copied());
1733
1734        txn.insert_collection_metadata(
1735            ids_to_add
1736                .into_iter()
1737                .map(|id| (id, ShardId::new()))
1738                .collect(),
1739        )?;
1740        txn.insert_collection_metadata(ids_to_register)?;
1741
1742        // Delete the metadata for any dropped collections.
1743        let dropped_mappings = txn.delete_collection_metadata(ids_to_drop);
1744
1745        // Only finalize the shards of dropped collections that don't have a primary.
1746        // Otherwise the shard might still be in use by the primary.
1747        let mut dropped_shards = BTreeSet::new();
1748        {
1749            let collections = self.collections.lock().expect("poisoned");
1750            for (id, shard) in dropped_mappings {
1751                let coll = collections.get(&id).expect("must exist");
1752                if coll.primary.is_none() {
1753                    dropped_shards.insert(shard);
1754                }
1755            }
1756        }
1757        let remaining_metadata = txn.get_collection_metadata();
1758        let (referenced_shards, dropped_shards) = partition_finalizable_shards(
1759            remaining_metadata,
1760            &active_collection_ids,
1761            dropped_shards,
1762        );
1763        if !referenced_shards.is_empty() {
1764            mz_ore::soft_panic_or_log!(
1765                "dropped collections would finalize shards that active collections still use: \
1766                 {referenced_shards:?}"
1767            );
1768        }
1769        txn.insert_unfinalized_shards(dropped_shards)?;
1770
1771        // Reconcile any shards we've successfully finalized with the shard
1772        // finalization collection.
1773        let finalized_shards = self.finalized_shards.lock().iter().copied().collect();
1774        txn.remove_unfinalized_shards(finalized_shards);
1775
1776        Ok(())
1777    }
1778
1779    // TODO(aljoscha): It would be swell if we could refactor this Leviathan of
1780    // a method/move individual parts to their own methods.
1781    #[instrument(level = "debug")]
1782    async fn create_collections_for_bootstrap(
1783        &self,
1784        storage_metadata: &StorageMetadata,
1785        register_ts: Option<Timestamp>,
1786        mut collections: Vec<(GlobalId, CollectionDescription)>,
1787        migrated_storage_collections: &BTreeSet<GlobalId>,
1788    ) -> Result<(), StorageError> {
1789        let is_in_txns = |id, metadata: &CollectionMetadata| {
1790            metadata.txns_shard.is_some()
1791                && !(self.read_only && migrated_storage_collections.contains(&id))
1792        };
1793
1794        // Validate first, to avoid corrupting state.
1795        // 1. create a dropped identifier, or
1796        // 2. create an existing identifier with a new description.
1797        // Make sure to check for errors within `ingestions` as well.
1798        collections.sort_by_key(|(id, _)| *id);
1799        collections.dedup();
1800        for pos in 1..collections.len() {
1801            if collections[pos - 1].0 == collections[pos].0 {
1802                return Err(StorageError::CollectionIdReused(collections[pos].0));
1803            }
1804        }
1805
1806        // We first enrich each collection description with some additional
1807        // metadata...
1808        let enriched_with_metadata = collections
1809            .into_iter()
1810            .map(|(id, description)| {
1811                let data_shard = storage_metadata.get_collection_shard(id)?;
1812
1813                // If the shard is being managed by txn-wal (initially,
1814                // tables), then we need to pass along the shard id for the txns
1815                // shard to dataflow rendering.
1816                let txns_shard = description
1817                    .data_source
1818                    .in_txns()
1819                    .then(|| *self.txns_read.txns_id());
1820
1821                let metadata = CollectionMetadata {
1822                    persist_location: self.persist_location.clone(),
1823                    data_shard,
1824                    relation_desc: description.desc.clone(),
1825                    txns_shard,
1826                };
1827
1828                Ok((id, description, metadata))
1829            })
1830            .collect_vec();
1831
1832        // So that we can open `SinceHandle`s for each collections concurrently.
1833        let persist_client = self
1834            .persist
1835            .open(self.persist_location.clone())
1836            .await
1837            .unwrap();
1838        let persist_client = &persist_client;
1839        // Reborrow the `&mut self` as immutable, as all the concurrent work to
1840        // be processed in this stream cannot all have exclusive access.
1841        use futures::stream::{StreamExt, TryStreamExt};
1842        let this = &*self;
1843        let mut to_register: Vec<_> = futures::stream::iter(enriched_with_metadata)
1844            .map(|data: Result<_, StorageError>| {
1845                async move {
1846                    let (id, description, metadata) = data?;
1847
1848                    // should be replaced with real introspection
1849                    // (https://github.com/MaterializeInc/database-issues/issues/4078)
1850                    // but for now, it's helpful to have this mapping written down
1851                    // somewhere
1852                    debug!("mapping GlobalId={} to shard ({})", id, metadata.data_shard);
1853
1854                    // If this collection has a primary, the primary is responsible for downgrading
1855                    // the critical since and it would be an error if we did so here while opening
1856                    // the since handle.
1857                    let since = if description.primary.is_some() {
1858                        None
1859                    } else {
1860                        description.since.as_ref()
1861                    };
1862
1863                    let (write, mut since_handle) = this
1864                        .open_data_handles(
1865                            &id,
1866                            metadata.data_shard,
1867                            since,
1868                            metadata.relation_desc.clone(),
1869                            persist_client,
1870                        )
1871                        .await;
1872
1873                    // Present tables as springing into existence at the register_ts
1874                    // by advancing the since. Otherwise, we could end up in a
1875                    // situation where a table with a long compaction window appears
1876                    // to exist before the environment (and this the table) existed.
1877                    //
1878                    // We could potentially also do the same thing for other
1879                    // sources, in particular storage's internal sources and perhaps
1880                    // others, but leave them for now.
1881                    match description.data_source {
1882                        DataSource::Introspection(_)
1883                        | DataSource::IngestionExport { .. }
1884                        | DataSource::Webhook
1885                        | DataSource::Ingestion(_)
1886                        | DataSource::Progress
1887                        | DataSource::Other => {}
1888                        DataSource::Sink { .. } => {}
1889                        DataSource::Table => {
1890                            let register_ts = register_ts.expect(
1891                                "caller should have provided a register_ts when creating a table",
1892                            );
1893                            if since_handle.since().elements() == &[Timestamp::MIN]
1894                                && !migrated_storage_collections.contains(&id)
1895                            {
1896                                debug!("advancing {} to initial since of {:?}", id, register_ts);
1897                                let token = since_handle.opaque();
1898                                let _ = since_handle
1899                                    .compare_and_downgrade_since(
1900                                        &token,
1901                                        (&token, &Antichain::from_elem(register_ts)),
1902                                    )
1903                                    .await;
1904                            }
1905                        }
1906                    }
1907
1908                    Ok::<_, StorageError>((id, description, write, since_handle, metadata))
1909                }
1910            })
1911            // Poll each future for each collection concurrently, maximum of 50 at a time.
1912            .buffer_unordered(50)
1913            // HERE BE DRAGONS:
1914            //
1915            // There are at least 2 subtleties in using `FuturesUnordered`
1916            // (which `buffer_unordered` uses underneath:
1917            // - One is captured here
1918            //   <https://github.com/rust-lang/futures-rs/issues/2387>
1919            // - And the other is deadlocking if processing an OUTPUT of a
1920            //   `FuturesUnordered` stream attempts to obtain an async mutex that
1921            //   is also obtained in the futures being polled.
1922            //
1923            // Both of these could potentially be issues in all usages of
1924            // `buffer_unordered` in this method, so we stick the standard
1925            // advice: only use `try_collect` or `collect`!
1926            .try_collect()
1927            .await?;
1928
1929        // Reorder in dependency order.
1930        #[derive(Ord, PartialOrd, Eq, PartialEq)]
1931        enum DependencyOrder {
1932            /// Tables should always be registered first, and large ids before small ones.
1933            Table(Reverse<GlobalId>),
1934            /// For most collections the id order is the correct one.
1935            Collection(GlobalId),
1936            /// Sinks should always be registered last.
1937            Sink(GlobalId),
1938        }
1939        to_register.sort_by_key(|(id, desc, ..)| match &desc.data_source {
1940            DataSource::Table => DependencyOrder::Table(Reverse(*id)),
1941            DataSource::Sink { .. } => DependencyOrder::Sink(*id),
1942            _ => DependencyOrder::Collection(*id),
1943        });
1944
1945        // Reported after the lock is released, since an ingestion export's
1946        // violation needs a persist read to confirm.
1947        let dependency_violations = {
1948            // We hold this lock for a very short amount of time, just doing some
1949            // hashmap inserts and unbounded channel sends.
1950            let mut self_collections = self.collections.lock().expect("lock poisoned");
1951            let mut dependency_violations = Vec::new();
1952
1953            for (id, description, write_handle, since_handle, metadata) in to_register {
1954                let write_frontier = write_handle.upper();
1955                let data_shard_since = since_handle.since().clone();
1956
1957                // Determine if this collection has any dependencies.
1958                let storage_dependencies =
1959                    Self::determine_collection_dependencies(&*self_collections, id, &description)?;
1960
1961                // Determine the initial since of the collection.
1962                let initial_since = match storage_dependencies
1963                    .iter()
1964                    .at_most_one()
1965                    .expect("should have at most one dependency")
1966                {
1967                    Some(dep) => {
1968                        let dependency_collection = self_collections
1969                            .get(dep)
1970                            .ok_or(StorageError::IdentifierMissing(*dep))?;
1971                        let dependency_since = dependency_collection.implied_capability.clone();
1972
1973                        // If an item has a dependency, its initial since must be
1974                        // advanced as far as its dependency, i.e. a dependency's
1975                        // since may never be in advance of its dependents.
1976                        //
1977                        // We have to do this every time we initialize the
1978                        // collection, though––the invariant might have been upheld
1979                        // correctly in the previous epoch, but the
1980                        // `data_shard_since` might not have compacted and, on
1981                        // establishing a new persist connection, still have data we
1982                        // said _could_ be compacted.
1983                        if PartialOrder::less_than(&data_shard_since, &dependency_since) {
1984                            // The dependency since cannot be beyond the dependent
1985                            // (our) upper unless the collection is new. In
1986                            // practice, the depdenency is the remap shard of a
1987                            // source (export), and if the since is allowed to
1988                            // "catch up" to the upper, that is `upper <= since`, a
1989                            // restarting ingestion cannot differentiate between
1990                            // updates that have already been written out to the
1991                            // backing persist shard and updates that have yet to be
1992                            // written. We would write duplicate updates.
1993                            //
1994                            // If this check fails, it means that the read hold
1995                            // installed on the dependency was probably not upheld
1996                            // –– if it were, the dependency's since could not have
1997                            // advanced as far the dependent's upper.
1998                            //
1999                            // We don't care about the dependency since when the
2000                            // write frontier is empty. In that case, no-one can
2001                            // write down any more updates.
2002                            // This invariant applies to remap dependencies. A `primary`
2003                            // dependency is another version of the same shard, whose since can
2004                            // validly equal the dependent's upper.
2005                            if description.primary.is_none()
2006                                && write_frontier.elements() != &[Timestamp::MIN]
2007                                && !write_frontier.is_empty()
2008                                && !PartialOrder::less_than(&dependency_since, write_frontier)
2009                            {
2010                                dependency_violations.push(DependencyViolation {
2011                                    id,
2012                                    dependency: *dep,
2013                                    data_shard_since: data_shard_since.clone(),
2014                                    write_frontier: write_frontier.clone(),
2015                                    dependency_since: dependency_since.clone(),
2016                                    ingestion_export: matches!(
2017                                        description.data_source,
2018                                        DataSource::IngestionExport { .. }
2019                                    )
2020                                    .then(|| metadata.clone()),
2021                                });
2022                            }
2023
2024                            dependency_since
2025                        } else {
2026                            data_shard_since
2027                        }
2028                    }
2029                    None => data_shard_since,
2030                };
2031
2032                // Determine the time dependence of the collection.
2033                let time_dependence = {
2034                    use DataSource::*;
2035                    if let Some(timeline) = &description.timeline
2036                        && *timeline != Timeline::EpochMilliseconds
2037                    {
2038                        // Only the epoch timeline follows wall-clock.
2039                        None
2040                    } else {
2041                        match &description.data_source {
2042                            Ingestion(ingestion) => {
2043                                use GenericSourceConnection::*;
2044                                match ingestion.desc.connection {
2045                                    // Kafka, Postgres, MySql, and SQL Server sources all
2046                                    // follow wall clock.
2047                                    Kafka(_) | Postgres(_) | MySql(_) | SqlServer(_) => {
2048                                        Some(TimeDependence::default())
2049                                    }
2050                                    // Load generators not further specified.
2051                                    LoadGenerator(_) => None,
2052                                }
2053                            }
2054                            IngestionExport { ingestion_id, .. } => {
2055                                let c = self_collections.get(ingestion_id).expect("known to exist");
2056                                c.time_dependence.clone()
2057                            }
2058                            // Introspection, other, progress, table, and webhook sources follow wall clock.
2059                            Introspection(_) | Progress | Table { .. } | Webhook { .. } => {
2060                                Some(TimeDependence::default())
2061                            }
2062                            // Materialized views, etc, aren't managed by storage.
2063                            Other => None,
2064                            Sink { .. } => None,
2065                        }
2066                    }
2067                };
2068
2069                let ingestion_remap_collection_id = match &description.data_source {
2070                    DataSource::Ingestion(desc) => Some(desc.remap_collection_id),
2071                    _ => None,
2072                };
2073
2074                let mut collection_state = CollectionState::new(
2075                    description.primary,
2076                    time_dependence,
2077                    ingestion_remap_collection_id,
2078                    initial_since,
2079                    write_frontier.clone(),
2080                    storage_dependencies,
2081                    metadata.clone(),
2082                );
2083
2084                // Install the collection state in the appropriate spot.
2085                match &description.data_source {
2086                    DataSource::Introspection(_) => {
2087                        self_collections.insert(id, collection_state);
2088                    }
2089                    DataSource::Webhook => {
2090                        self_collections.insert(id, collection_state);
2091                    }
2092                    DataSource::IngestionExport { .. } => {
2093                        self_collections.insert(id, collection_state);
2094                    }
2095                    DataSource::Table => {
2096                        // See comment on self.initial_txn_upper on why we're doing
2097                        // this.
2098                        if is_in_txns(id, &metadata)
2099                            && PartialOrder::less_than(
2100                                &collection_state.write_frontier,
2101                                &self.initial_txn_upper,
2102                            )
2103                        {
2104                            // We could try and be cute and use the join of the txn
2105                            // upper and the table upper. But that has more
2106                            // complicated reasoning for why it is or isn't correct,
2107                            // and we're only dealing with totally ordered times
2108                            // here.
2109                            collection_state
2110                                .write_frontier
2111                                .clone_from(&self.initial_txn_upper);
2112                        }
2113                        self_collections.insert(id, collection_state);
2114                    }
2115                    DataSource::Progress | DataSource::Other => {
2116                        self_collections.insert(id, collection_state);
2117                    }
2118                    DataSource::Ingestion(_) => {
2119                        self_collections.insert(id, collection_state);
2120                    }
2121                    DataSource::Sink { .. } => {
2122                        self_collections.insert(id, collection_state);
2123                    }
2124                }
2125
2126                self.register_handles(id, is_in_txns(id, &metadata), since_handle, write_handle);
2127
2128                // If this collection has a dependency, install a read hold on it.
2129                self.install_collection_dependency_read_holds_inner(&mut *self_collections, id)?;
2130            }
2131            dependency_violations
2132        };
2133
2134        for violation in dependency_violations {
2135            // For an ingestion export, this violation means the remap's read
2136            // frontier has caught up to or passed the export's upper. The
2137            // export will snapshot again on its next render, and the concern
2138            // is that it duplicates updates it already wrote.
2139            //
2140            // That can't happen when the export's shard is still empty, and we
2141            // skip the check in that case. A newly added export stays empty
2142            // until its snapshot finishes, because the persist sink commits an
2143            // empty batch up to the snapshot's as_of before any snapshot data
2144            // arrives.
2145            //
2146            // Sinks don't get this exemption. A sink's shard only ever receives
2147            // empty appends, and an empty shard says nothing about what the
2148            // sink has already emitted.
2149            if let Some(metadata) = &violation.ingestion_export
2150                && shard_has_no_updates(persist_client, violation.id, metadata).await
2151            {
2152                continue;
2153            }
2154            let DependencyViolation {
2155                id,
2156                dependency,
2157                data_shard_since,
2158                write_frontier,
2159                dependency_since,
2160                ingestion_export: _,
2161            } = violation;
2162            mz_ore::soft_panic_or_log!(
2163                "dependency ({dependency}) since has advanced past dependent ({id}) upper \n
2164                dependent ({id}): since {:?}, upper {:?} \n
2165                dependency ({dependency}): since {:?}",
2166                data_shard_since,
2167                write_frontier,
2168                dependency_since
2169            );
2170        }
2171
2172        self.synchronize_finalized_shards(storage_metadata);
2173
2174        Ok(())
2175    }
2176
2177    async fn alter_table_desc(
2178        &self,
2179        existing_collection: GlobalId,
2180        new_collection: GlobalId,
2181        new_desc: RelationDesc,
2182        expected_version: RelationVersion,
2183    ) -> Result<(), StorageError> {
2184        let data_shard = {
2185            let self_collections = self.collections.lock().expect("lock poisoned");
2186            let existing = self_collections
2187                .get(&existing_collection)
2188                .ok_or_else(|| StorageError::IdentifierMissing(existing_collection))?;
2189
2190            existing.collection_metadata.data_shard
2191        };
2192
2193        let persist_client = self
2194            .persist
2195            .open(self.persist_location.clone())
2196            .await
2197            .unwrap();
2198
2199        // Evolve the schema of this shard.
2200        let diagnostics = Diagnostics {
2201            shard_name: existing_collection.to_string(),
2202            handle_purpose: "alter_table_desc".to_string(),
2203        };
2204        // We map the Adapter's RelationVersion 1:1 with SchemaId.
2205        let expected_schema = expected_version.into();
2206        let schema_result = persist_client
2207            .compare_and_evolve_schema::<SourceData, (), Timestamp, StorageDiff>(
2208                data_shard,
2209                expected_schema,
2210                &new_desc,
2211                &UnitSchema,
2212                diagnostics,
2213            )
2214            .await
2215            .map_err(|e| StorageError::InvalidUsage(e.to_string()))?;
2216        tracing::info!(
2217            ?existing_collection,
2218            ?new_collection,
2219            ?new_desc,
2220            "evolved schema"
2221        );
2222
2223        match schema_result {
2224            // id unused: the desc is re-derived below.
2225            CaESchema::Ok(_id) => {}
2226            // Not retried by design. compare_and_evolve_schema now absorbs a
2227            // committed-but-lost CaS, so an ExpectedMismatch here is a genuine
2228            // divergence (current matches neither the request nor `expected`)
2229            // that must surface rather than retry.
2230            CaESchema::ExpectedMismatch {
2231                schema_id,
2232                key,
2233                val,
2234            } => {
2235                mz_ore::soft_panic_or_log!(
2236                    "schema expectation mismatch, expected {expected_schema:?} \
2237                     but found {schema_id:?}, {key:?}, {val:?}"
2238                );
2239                return Err(StorageError::Generic(anyhow::anyhow!(
2240                    "schema expected mismatch, {existing_collection:?}",
2241                )));
2242            }
2243            CaESchema::Incompatible => {
2244                mz_ore::soft_panic_or_log!(
2245                    "incompatible schema! {existing_collection} {new_desc:?}"
2246                );
2247                return Err(StorageError::Generic(anyhow::anyhow!(
2248                    "schema incompatible, {existing_collection:?}"
2249                )));
2250            }
2251        };
2252
2253        // Once the new schema is registered we can open new data handles.
2254        let (write_handle, since_handle) = self
2255            .open_data_handles(
2256                &new_collection,
2257                data_shard,
2258                None,
2259                new_desc.clone(),
2260                &persist_client,
2261            )
2262            .await;
2263
2264        // TODO(alter_table): Do we need to advance the since of the table to match the time this
2265        // new version was registered with txn-wal?
2266
2267        // Great! Our new schema is registered with Persist, now we need to update our internal
2268        // data structures.
2269        {
2270            let mut self_collections = self.collections.lock().expect("lock poisoned");
2271
2272            // Update the existing collection so we know it's a "projection" of this new one.
2273            let existing = self_collections
2274                .get_mut(&existing_collection)
2275                .expect("existing collection missing");
2276
2277            // A higher level should already be asserting this, but let's make sure.
2278            assert_none!(existing.primary);
2279
2280            // The existing version of the table will depend on the new version.
2281            existing.primary = Some(new_collection);
2282            existing.storage_dependencies.push(new_collection);
2283
2284            // Copy over the frontiers from the previous version.
2285            // The new table starts with two holds - the implied capability, and the hold from
2286            // the previous version - both at the previous version's read frontier.
2287            let implied_capability = existing.read_capabilities.frontier().to_owned();
2288            let write_frontier = existing.write_frontier.clone();
2289
2290            // Determine the relevant read capabilities on the new collection.
2291            //
2292            // Note(parkmycar): Originally we used `install_collection_dependency_read_holds_inner`
2293            // here, but that only installed a ReadHold on the new collection for the implied
2294            // capability of the existing collection. This would cause runtime panics because it
2295            // would eventually result in negative read capabilities.
2296            let mut changes = ChangeBatch::new();
2297            changes.extend(implied_capability.iter().map(|t| (*t, 1)));
2298
2299            // Note: The new collection is now the "primary collection".
2300            let collection_meta = CollectionMetadata {
2301                persist_location: self.persist_location.clone(),
2302                relation_desc: new_desc.clone(),
2303                data_shard,
2304                txns_shard: Some(self.txns_read.txns_id().clone()),
2305            };
2306            let collection_state = CollectionState::new(
2307                None,
2308                existing.time_dependence.clone(),
2309                existing.ingestion_remap_collection_id.clone(),
2310                implied_capability,
2311                write_frontier,
2312                Vec::new(),
2313                collection_meta,
2314            );
2315
2316            // Add a record of the new collection.
2317            self_collections.insert(new_collection, collection_state);
2318
2319            let mut updates = BTreeMap::from([(new_collection, changes)]);
2320            StorageCollectionsImpl::update_read_capabilities_inner(
2321                &self.cmd_tx,
2322                &mut *self_collections,
2323                &mut updates,
2324            );
2325        };
2326
2327        // TODO(alter_table): Support changes to sources.
2328        self.register_handles(new_collection, true, since_handle, write_handle);
2329
2330        info!(%existing_collection, %new_collection, ?new_desc, "altered table");
2331
2332        Ok(())
2333    }
2334
2335    fn drop_collections_unvalidated(
2336        &self,
2337        storage_metadata: &StorageMetadata,
2338        identifiers: Vec<GlobalId>,
2339    ) {
2340        debug!(?identifiers, "drop_collections_unvalidated");
2341
2342        let mut self_collections = self.collections.lock().expect("lock poisoned");
2343        // Durable metadata can outlive its collection. Reconcile it with live
2344        // collection state so orphaned mappings do not block finalization.
2345        let dropping: BTreeSet<_> = identifiers.iter().copied().collect();
2346        let active_collection_ids: BTreeSet<_> = self_collections
2347            .iter()
2348            .filter_map(|(id, collection)| {
2349                (!dropping.contains(id) && !collection.is_dropped()).then_some(*id)
2350            })
2351            .collect();
2352        let shards_in_use: BTreeSet<_> = storage_metadata
2353            .collection_metadata
2354            .iter()
2355            .filter_map(|(id, shard)| active_collection_ids.contains(id).then_some(*shard))
2356            .collect();
2357
2358        // Policies that advance the since to the empty antichain. We do still
2359        // honor outstanding read holds, and collections will only be dropped
2360        // once those are removed as well.
2361        //
2362        // We don't explicitly remove read capabilities! Downgrading the
2363        // frontier of the source to `[]` (the empty Antichain), will propagate
2364        // to the storage dependencies.
2365        let mut finalized_policies = Vec::new();
2366
2367        for id in identifiers {
2368            // Make sure it's still there, might already have been deleted.
2369            let Some(collection) = self_collections.get(&id) else {
2370                continue;
2371            };
2372
2373            // Unless the collection has a primary, its shard must have been previously removed
2374            // by `StorageCollections::prepare_state`.
2375            if collection.primary.is_none() {
2376                let metadata = storage_metadata.get_collection_shard(id);
2377                mz_ore::soft_assert_or_log!(
2378                    matches!(metadata, Err(StorageError::IdentifierMissing(_))),
2379                    "dropping {id}, but drop was not synchronized with storage \
2380                     controller via `prepare_state`"
2381                );
2382
2383                // Releasing the owner's since can destroy a shared shard even if the
2384                // finalization WAL is guarded. Prefer leaking this collection state over
2385                // destroying data when durable metadata contradicts the primary links.
2386                let data_shard = collection.collection_metadata.data_shard;
2387                if shards_in_use.contains(&data_shard) {
2388                    mz_ore::soft_panic_or_log!(
2389                        "dropping {id} would release the since of shard {data_shard}, \
2390                         which an active collection still uses"
2391                    );
2392                    continue;
2393                }
2394            }
2395
2396            finalized_policies.push((id, ReadPolicy::ValidFrom(Antichain::new())));
2397        }
2398
2399        self.set_read_policies_inner(&mut self_collections, finalized_policies);
2400
2401        drop(self_collections);
2402
2403        self.synchronize_finalized_shards(storage_metadata);
2404    }
2405
2406    fn set_read_policies(&self, policies: Vec<(GlobalId, ReadPolicy)>) {
2407        let mut collections = self.collections.lock().expect("lock poisoned");
2408
2409        if tracing::enabled!(tracing::Level::TRACE) {
2410            let user_capabilities = collections
2411                .iter_mut()
2412                .filter(|(id, _c)| id.is_user())
2413                .map(|(id, c)| {
2414                    let updates = c.read_capabilities.updates().cloned().collect_vec();
2415                    (*id, c.implied_capability.clone(), updates)
2416                })
2417                .collect_vec();
2418
2419            trace!(?policies, ?user_capabilities, "set_read_policies");
2420        }
2421
2422        self.set_read_policies_inner(&mut collections, policies);
2423
2424        if tracing::enabled!(tracing::Level::TRACE) {
2425            let user_capabilities = collections
2426                .iter_mut()
2427                .filter(|(id, _c)| id.is_user())
2428                .map(|(id, c)| {
2429                    let updates = c.read_capabilities.updates().cloned().collect_vec();
2430                    (*id, c.implied_capability.clone(), updates)
2431                })
2432                .collect_vec();
2433
2434            trace!(?user_capabilities, "after! set_read_policies");
2435        }
2436    }
2437
2438    fn acquire_read_holds(
2439        &self,
2440        desired_holds: Vec<GlobalId>,
2441    ) -> Result<Vec<ReadHold>, CollectionMissing> {
2442        if desired_holds.is_empty() {
2443            return Ok(vec![]);
2444        }
2445
2446        let mut collections = self.collections.lock().expect("lock poisoned");
2447
2448        let mut advanced_holds = Vec::new();
2449        // We advance the holds by our current since frontier. Can't acquire
2450        // holds for times that have been compacted away!
2451        //
2452        // NOTE: We acquire read holds at the earliest possible time rather than
2453        // at the implied capability. This is so that, for example, adapter can
2454        // acquire a read hold to hold back the frontier, giving the COMPUTE
2455        // controller a chance to also acquire a read hold at that early
2456        // frontier. If/when we change the interplay between adapter and COMPUTE
2457        // to pass around ReadHold tokens, we might tighten this up and instead
2458        // acquire read holds at the implied capability.
2459        for id in desired_holds.iter() {
2460            let collection = collections.get(id).ok_or(CollectionMissing(*id))?;
2461            let since = collection.read_capabilities.frontier().to_owned();
2462            advanced_holds.push((*id, since));
2463        }
2464
2465        let mut updates = advanced_holds
2466            .iter()
2467            .map(|(id, hold)| {
2468                let mut changes = ChangeBatch::new();
2469                changes.extend(hold.iter().map(|time| (*time, 1)));
2470                (*id, changes)
2471            })
2472            .collect::<BTreeMap<_, _>>();
2473
2474        StorageCollectionsImpl::update_read_capabilities_inner(
2475            &self.cmd_tx,
2476            &mut collections,
2477            &mut updates,
2478        );
2479
2480        let acquired_holds = advanced_holds
2481            .into_iter()
2482            .map(|(id, since)| ReadHold::with_channel(id, since, self.holds_tx.clone()))
2483            .collect_vec();
2484
2485        trace!(?desired_holds, ?acquired_holds, "acquire_read_holds");
2486
2487        Ok(acquired_holds)
2488    }
2489
2490    /// Determine time dependence information for the object.
2491    fn determine_time_dependence(
2492        &self,
2493        id: GlobalId,
2494    ) -> Result<Option<TimeDependence>, TimeDependenceError> {
2495        use TimeDependenceError::CollectionMissing;
2496        let collections = self.collections.lock().expect("lock poisoned");
2497        let state = collections.get(&id).ok_or(CollectionMissing(id))?;
2498        Ok(state.time_dependence.clone())
2499    }
2500
2501    fn dump(&self) -> Result<serde_json::Value, anyhow::Error> {
2502        // Destructure `self` here so we don't forget to consider dumping newly added fields.
2503        let Self {
2504            envd_epoch,
2505            read_only,
2506            finalizable_shards,
2507            finalized_shards,
2508            collections,
2509            txns_read: _,
2510            config,
2511            initial_txn_upper,
2512            persist_location,
2513            persist: _,
2514            cmd_tx: _,
2515            holds_tx: _,
2516            _background_task: _,
2517            _finalize_shards_task: _,
2518        } = self;
2519
2520        let finalizable_shards: Vec<_> = finalizable_shards
2521            .lock()
2522            .iter()
2523            .map(ToString::to_string)
2524            .collect();
2525        let finalized_shards: Vec<_> = finalized_shards
2526            .lock()
2527            .iter()
2528            .map(ToString::to_string)
2529            .collect();
2530        let collections: BTreeMap<_, _> = collections
2531            .lock()
2532            .expect("poisoned")
2533            .iter()
2534            .map(|(id, c)| (id.to_string(), format!("{c:?}")))
2535            .collect();
2536        let config = format!("{:?}", config.lock().expect("poisoned"));
2537
2538        Ok(serde_json::json!({
2539            "envd_epoch": envd_epoch,
2540            "read_only": read_only,
2541            "finalizable_shards": finalizable_shards,
2542            "finalized_shards": finalized_shards,
2543            "collections": collections,
2544            "config": config,
2545            "initial_txn_upper": initial_txn_upper,
2546            "persist_location": format!("{persist_location:?}"),
2547        }))
2548    }
2549}
2550
2551/// Wraps either a "critical" [SinceHandle] or a leased [ReadHandle].
2552///
2553/// When a [StorageCollections] is in read-only mode, we will only ever acquire
2554/// [ReadHandle], because acquiring the [SinceHandle] and driving forward its
2555/// since is considered a write. Conversely, when in read-write mode, we acquire
2556/// [SinceHandle].
2557#[derive(Debug)]
2558enum SinceHandleWrapper {
2559    Critical(SinceHandle<SourceData, (), Timestamp, StorageDiff>),
2560    Leased(ReadHandle<SourceData, (), Timestamp, StorageDiff>),
2561}
2562
2563impl SinceHandleWrapper {
2564    pub fn since(&self) -> &Antichain<Timestamp> {
2565        match self {
2566            Self::Critical(handle) => handle.since(),
2567            Self::Leased(handle) => handle.since(),
2568        }
2569    }
2570
2571    pub fn opaque(&self) -> PersistEpoch {
2572        match self {
2573            Self::Critical(handle) => handle.opaque().decode(),
2574            Self::Leased(_handle) => {
2575                // The opaque is expected to be used with
2576                // `compare_and_downgrade_since`, and the leased handle doesn't
2577                // have a notion of an opaque. We pretend here and in
2578                // `compare_and_downgrade_since`.
2579                PersistEpoch(None)
2580            }
2581        }
2582    }
2583
2584    pub async fn compare_and_downgrade_since(
2585        &mut self,
2586        expected: &PersistEpoch,
2587        (opaque, since): (&PersistEpoch, &Antichain<Timestamp>),
2588    ) -> Result<Antichain<Timestamp>, PersistEpoch> {
2589        match self {
2590            Self::Critical(handle) => handle
2591                .compare_and_downgrade_since(
2592                    &Opaque::encode(expected),
2593                    (&Opaque::encode(opaque), since),
2594                )
2595                .await
2596                .map_err(|e| e.decode()),
2597            Self::Leased(handle) => {
2598                assert_none!(opaque.0);
2599
2600                handle.downgrade_since(since).await;
2601
2602                Ok(since.clone())
2603            }
2604        }
2605    }
2606
2607    pub async fn maybe_compare_and_downgrade_since(
2608        &mut self,
2609        expected: &PersistEpoch,
2610        (opaque, since): (&PersistEpoch, &Antichain<Timestamp>),
2611    ) -> Option<Result<Antichain<Timestamp>, PersistEpoch>> {
2612        match self {
2613            Self::Critical(handle) => handle
2614                .maybe_compare_and_downgrade_since(
2615                    &Opaque::encode(expected),
2616                    (&Opaque::encode(opaque), since),
2617                )
2618                .await
2619                .map(|r| r.map_err(|o| o.decode())),
2620            Self::Leased(handle) => {
2621                assert_none!(opaque.0);
2622
2623                handle.maybe_downgrade_since(since).await;
2624
2625                Some(Ok(since.clone()))
2626            }
2627        }
2628    }
2629
2630    pub fn snapshot_stats(
2631        &self,
2632        id: GlobalId,
2633        as_of: Option<Antichain<Timestamp>>,
2634    ) -> BoxFuture<'static, Result<SnapshotStats, StorageError>> {
2635        match self {
2636            Self::Critical(handle) => {
2637                let res = handle
2638                    .snapshot_stats(as_of)
2639                    .map(move |x| x.map_err(|_| StorageError::ReadBeforeSince(id)));
2640                Box::pin(res)
2641            }
2642            Self::Leased(handle) => {
2643                let res = handle
2644                    .snapshot_stats(as_of)
2645                    .map(move |x| x.map_err(|_| StorageError::ReadBeforeSince(id)));
2646                Box::pin(res)
2647            }
2648        }
2649    }
2650
2651    pub fn snapshot_stats_from_txn(
2652        &self,
2653        id: GlobalId,
2654        data_snapshot: DataSnapshot<Timestamp>,
2655    ) -> BoxFuture<'static, Result<SnapshotStats, StorageError>> {
2656        match self {
2657            Self::Critical(handle) => Box::pin(
2658                data_snapshot
2659                    .snapshot_stats_from_critical(handle)
2660                    .map(move |x| x.map_err(|_| StorageError::ReadBeforeSince(id))),
2661            ),
2662            Self::Leased(handle) => Box::pin(
2663                data_snapshot
2664                    .snapshot_stats_from_leased(handle)
2665                    .map(move |x| x.map_err(|_| StorageError::ReadBeforeSince(id))),
2666            ),
2667        }
2668    }
2669}
2670
2671/// State maintained about individual collections.
2672#[derive(Debug, Clone)]
2673struct CollectionState {
2674    /// The primary of this collections.
2675    ///
2676    /// Multiple storage collections can point to the same persist shard,
2677    /// possibly with different schemas. In such a configuration, we select one
2678    /// of the involved collections as the primary, who "owns" the persist
2679    /// shard. All other involved collections have a dependency on the primary.
2680    primary: Option<GlobalId>,
2681
2682    /// Description of how this collection's frontier follows time.
2683    time_dependence: Option<TimeDependence>,
2684    /// The ID of the source remap/progress collection, if this is an ingestion.
2685    ingestion_remap_collection_id: Option<GlobalId>,
2686
2687    /// Accumulation of read capabilities for the collection.
2688    ///
2689    /// This accumulation will always contain `self.implied_capability`, but may
2690    /// also contain capabilities held by others who have read dependencies on
2691    /// this collection.
2692    pub read_capabilities: MutableAntichain<Timestamp>,
2693
2694    /// The implicit capability associated with collection creation.  This
2695    /// should never be less than the since of the associated persist
2696    /// collection.
2697    pub implied_capability: Antichain<Timestamp>,
2698
2699    /// The policy to use to downgrade `self.implied_capability`.
2700    pub read_policy: ReadPolicy,
2701
2702    /// Storage identifiers on which this collection depends.
2703    pub storage_dependencies: Vec<GlobalId>,
2704
2705    /// Reported write frontier.
2706    pub write_frontier: Antichain<Timestamp>,
2707
2708    pub collection_metadata: CollectionMetadata,
2709}
2710
2711impl CollectionState {
2712    /// Creates a new collection state, with an initial read policy valid from
2713    /// `since`.
2714    pub fn new(
2715        primary: Option<GlobalId>,
2716        time_dependence: Option<TimeDependence>,
2717        ingestion_remap_collection_id: Option<GlobalId>,
2718        since: Antichain<Timestamp>,
2719        write_frontier: Antichain<Timestamp>,
2720        storage_dependencies: Vec<GlobalId>,
2721        metadata: CollectionMetadata,
2722    ) -> Self {
2723        let mut read_capabilities = MutableAntichain::new();
2724        read_capabilities.update_iter(since.iter().map(|time| (*time, 1)));
2725        Self {
2726            primary,
2727            time_dependence,
2728            ingestion_remap_collection_id,
2729            read_capabilities,
2730            implied_capability: since.clone(),
2731            read_policy: ReadPolicy::NoPolicy {
2732                initial_since: since,
2733            },
2734            storage_dependencies,
2735            write_frontier,
2736            collection_metadata: metadata,
2737        }
2738    }
2739
2740    /// Returns whether the collection was dropped.
2741    pub fn is_dropped(&self) -> bool {
2742        self.read_capabilities.is_empty()
2743    }
2744}
2745
2746/// A task that keeps persist handles, downgrades sinces when asked,
2747/// periodically gets recent uppers from them, and updates the shard collection
2748/// state when needed.
2749///
2750/// This shares state with [StorageCollectionsImpl] via `Arcs` and channels.
2751#[derive(Debug)]
2752struct BackgroundTask {
2753    config: Arc<Mutex<StorageConfiguration>>,
2754    cmds_tx: mpsc::UnboundedSender<BackgroundCmd>,
2755    cmds_rx: mpsc::UnboundedReceiver<BackgroundCmd>,
2756    holds_rx: mpsc::UnboundedReceiver<(GlobalId, ChangeBatch<Timestamp>)>,
2757    finalizable_shards: Arc<ShardIdSet>,
2758    collections: Arc<std::sync::Mutex<BTreeMap<GlobalId, CollectionState>>>,
2759    // So we know what shard ID corresponds to what global ID, which we need
2760    // when re-enqueing futures for determining the next upper update.
2761    shard_by_id: BTreeMap<GlobalId, ShardId>,
2762    since_handles: BTreeMap<GlobalId, SinceHandleWrapper>,
2763    txns_handle: Option<WriteHandle<SourceData, (), Timestamp, StorageDiff>>,
2764    txns_shards: BTreeSet<GlobalId>,
2765}
2766
2767#[derive(Debug)]
2768enum BackgroundCmd {
2769    Register {
2770        id: GlobalId,
2771        is_in_txns: bool,
2772        write_handle: WriteHandle<SourceData, (), Timestamp, StorageDiff>,
2773        since_handle: SinceHandleWrapper,
2774    },
2775    DowngradeSince(Vec<(GlobalId, Antichain<Timestamp>)>),
2776    SnapshotStats(
2777        GlobalId,
2778        SnapshotStatsAsOf,
2779        oneshot::Sender<SnapshotStatsRes>,
2780    ),
2781}
2782
2783/// A newtype wrapper to hang a Debug impl off of.
2784pub(crate) struct SnapshotStatsRes(BoxFuture<'static, Result<SnapshotStats, StorageError>>);
2785
2786impl Debug for SnapshotStatsRes {
2787    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2788        f.debug_struct("SnapshotStatsRes").finish_non_exhaustive()
2789    }
2790}
2791
2792impl BackgroundTask {
2793    async fn run(&mut self) {
2794        // Futures that fetch the recent upper from all other shards.
2795        let mut upper_futures: FuturesUnordered<
2796            std::pin::Pin<
2797                Box<
2798                    dyn Future<
2799                            Output = (
2800                                GlobalId,
2801                                WriteHandle<SourceData, (), Timestamp, StorageDiff>,
2802                                Antichain<Timestamp>,
2803                            ),
2804                        > + Send,
2805                >,
2806            >,
2807        > = FuturesUnordered::new();
2808
2809        let gen_upper_future =
2810            |id, mut handle: WriteHandle<_, _, _, _>, prev_upper: Antichain<Timestamp>| {
2811                let fut = async move {
2812                    soft_assert_or_log!(
2813                        !prev_upper.is_empty(),
2814                        "cannot await progress when upper is already empty"
2815                    );
2816                    handle.wait_for_upper_past(&prev_upper).await;
2817                    let new_upper = handle.shared_upper();
2818                    (id, handle, new_upper)
2819                };
2820
2821                fut
2822            };
2823
2824        let mut txns_upper_future = match self.txns_handle.take() {
2825            Some(txns_handle) => {
2826                let upper = txns_handle.upper().clone();
2827                let txns_upper_future =
2828                    gen_upper_future(GlobalId::Transient(1), txns_handle, upper);
2829                txns_upper_future.boxed()
2830            }
2831            None => async { std::future::pending().await }.boxed(),
2832        };
2833
2834        loop {
2835            tokio::select! {
2836                (id, handle, upper) = &mut txns_upper_future => {
2837                    trace!("new upper from txns shard: {:?}", upper);
2838                    let mut uppers = Vec::new();
2839                    for id in self.txns_shards.iter() {
2840                        uppers.push((*id, &upper));
2841                    }
2842                    self.update_write_frontiers(&uppers).await;
2843
2844                    let fut = gen_upper_future(id, handle, upper);
2845                    txns_upper_future = fut.boxed();
2846                }
2847                Some((id, handle, upper)) = upper_futures.next() => {
2848                    if id.is_user() {
2849                        trace!("new upper for collection {id}: {:?}", upper);
2850                    }
2851                    let current_shard = self.shard_by_id.get(&id);
2852                    if let Some(shard_id) = current_shard {
2853                        if shard_id == &handle.shard_id() {
2854                            // Still current, so process the update and enqueue
2855                            // again!
2856                            let uppers = &[(id, &upper)];
2857                            self.update_write_frontiers(uppers).await;
2858                            if !upper.is_empty() {
2859                                let fut = gen_upper_future(id, handle, upper);
2860                                upper_futures.push(fut.boxed());
2861                            }
2862                        } else {
2863                            // Be polite and expire the write handle. This can
2864                            // happen when we get an upper update for a write
2865                            // handle that has since been replaced via Update.
2866                            handle.expire().await;
2867                        }
2868                    }
2869                }
2870                cmd = self.cmds_rx.recv() => {
2871                    let Some(cmd) = cmd else {
2872                        // We're done!
2873                        break;
2874                    };
2875
2876                    // Drain all commands so we can merge `DowngradeSince` requests. Without this
2877                    // optimization, downgrading sinces could fall behind in the face of a large
2878                    // amount of storage collections.
2879                    let commands = iter::once(cmd).chain(
2880                        iter::from_fn(|| self.cmds_rx.try_recv().ok())
2881                    );
2882                    let mut downgrades = BTreeMap::<_, Antichain<_>>::new();
2883                    for cmd in commands {
2884                        match cmd {
2885                            BackgroundCmd::Register{
2886                                id,
2887                                is_in_txns,
2888                                write_handle,
2889                                since_handle
2890                            } => {
2891                                debug!("registering handles for {}", id);
2892                                let previous = self.shard_by_id.insert(id, write_handle.shard_id());
2893                                if previous.is_some() {
2894                                    panic!("already registered a WriteHandle for collection {id}");
2895                                }
2896
2897                                let previous = self.since_handles.insert(id, since_handle);
2898                                if previous.is_some() {
2899                                    panic!("already registered a SinceHandle for collection {id}");
2900                                }
2901
2902                                if is_in_txns {
2903                                    self.txns_shards.insert(id);
2904                                } else {
2905                                    let upper = write_handle.upper().clone();
2906                                    if !upper.is_empty() {
2907                                        let fut = gen_upper_future(id, write_handle, upper);
2908                                        upper_futures.push(fut.boxed());
2909                                    }
2910                                }
2911                            }
2912                            BackgroundCmd::DowngradeSince(cmds) => {
2913                                for (id, new) in cmds {
2914                                    downgrades.entry(id)
2915                                        .and_modify(|since| since.join_assign(&new))
2916                                        .or_insert(new);
2917                                }
2918                            }
2919                            BackgroundCmd::SnapshotStats(id, as_of, tx) => {
2920                                // NB: The requested as_of could be arbitrarily far
2921                                // in the future. So, in order to avoid blocking
2922                                // this loop until it's available and the
2923                                // `snapshot_stats` call resolves, instead return
2924                                // the future to the caller and await it there.
2925                                let res = match self.since_handles.get(&id) {
2926                                    Some(x) => {
2927                                        let fut: BoxFuture<
2928                                            'static,
2929                                            Result<SnapshotStats, StorageError>,
2930                                        > = match as_of {
2931                                            SnapshotStatsAsOf::Direct(as_of) => {
2932                                                x.snapshot_stats(id, Some(as_of))
2933                                            }
2934                                            SnapshotStatsAsOf::Txns(data_snapshot) => {
2935                                                x.snapshot_stats_from_txn(id, data_snapshot)
2936                                            }
2937                                        };
2938                                        SnapshotStatsRes(fut)
2939                                    }
2940                                    None => SnapshotStatsRes(Box::pin(futures::future::ready(Err(
2941                                        StorageError::IdentifierMissing(id),
2942                                    )))),
2943                                };
2944                                // It's fine if the listener hung up.
2945                                let _ = tx.send(res);
2946                            }
2947                        }
2948                    }
2949
2950                    if !downgrades.is_empty() {
2951                        self.downgrade_sinces(downgrades).await;
2952                    }
2953                }
2954                Some(holds_changes) = self.holds_rx.recv() => {
2955                    let mut batched_changes = BTreeMap::new();
2956                    batched_changes.insert(holds_changes.0, holds_changes.1);
2957
2958                    while let Ok(mut holds_changes) = self.holds_rx.try_recv() {
2959                        let entry = batched_changes.entry(holds_changes.0);
2960                        entry
2961                            .and_modify(|existing| existing.extend(holds_changes.1.drain()))
2962                            .or_insert_with(|| holds_changes.1);
2963                    }
2964
2965                    let mut collections = self.collections.lock().expect("lock poisoned");
2966
2967                    let user_changes = batched_changes
2968                        .iter()
2969                        .filter(|(id, _c)| id.is_user())
2970                        .map(|(id, c)| {
2971                            (id.clone(), c.clone())
2972                        })
2973                        .collect_vec();
2974
2975                    if !user_changes.is_empty() {
2976                        trace!(?user_changes, "applying holds changes from channel");
2977                    }
2978
2979                    StorageCollectionsImpl::update_read_capabilities_inner(
2980                        &self.cmds_tx,
2981                        &mut collections,
2982                        &mut batched_changes,
2983                    );
2984                }
2985            }
2986        }
2987
2988        warn!("BackgroundTask shutting down");
2989    }
2990
2991    #[instrument(level = "debug")]
2992    async fn update_write_frontiers(&self, updates: &[(GlobalId, &Antichain<Timestamp>)]) {
2993        let mut read_capability_changes = BTreeMap::default();
2994
2995        let mut self_collections = self.collections.lock().expect("lock poisoned");
2996
2997        for (id, new_upper) in updates.iter() {
2998            let collection = if let Some(c) = self_collections.get_mut(id) {
2999                c
3000            } else {
3001                trace!(
3002                    "Reference to absent collection {id}, due to concurrent removal of that collection"
3003                );
3004                continue;
3005            };
3006
3007            if PartialOrder::less_than(&collection.write_frontier, *new_upper) {
3008                collection.write_frontier.clone_from(new_upper);
3009            }
3010
3011            let mut new_read_capability = collection
3012                .read_policy
3013                .frontier(collection.write_frontier.borrow());
3014
3015            if id.is_user() {
3016                trace!(
3017                    %id,
3018                    implied_capability = ?collection.implied_capability,
3019                    policy = ?collection.read_policy,
3020                    write_frontier = ?collection.write_frontier,
3021                    ?new_read_capability,
3022                    "update_write_frontiers");
3023            }
3024
3025            if PartialOrder::less_equal(&collection.implied_capability, &new_read_capability) {
3026                let mut update = ChangeBatch::new();
3027                update.extend(new_read_capability.iter().map(|time| (*time, 1)));
3028                std::mem::swap(&mut collection.implied_capability, &mut new_read_capability);
3029                update.extend(new_read_capability.iter().map(|time| (*time, -1)));
3030
3031                if !update.is_empty() {
3032                    read_capability_changes.insert(*id, update);
3033                }
3034            }
3035        }
3036
3037        if !read_capability_changes.is_empty() {
3038            StorageCollectionsImpl::update_read_capabilities_inner(
3039                &self.cmds_tx,
3040                &mut self_collections,
3041                &mut read_capability_changes,
3042            );
3043        }
3044    }
3045
3046    async fn downgrade_sinces(&mut self, cmds: BTreeMap<GlobalId, Antichain<Timestamp>>) {
3047        // Process all persist calls concurrently.
3048        let mut futures = Vec::with_capacity(cmds.len());
3049        for (id, new_since) in cmds {
3050            // We need to take the since handles here, to satisfy the borrow checker.
3051            // We make sure to always put them back below.
3052            let Some(mut since_handle) = self.since_handles.remove(&id) else {
3053                // This can happen when someone concurrently drops a collection.
3054                trace!("downgrade_sinces: reference to absent collection {id}");
3055                continue;
3056            };
3057
3058            let fut = async move {
3059                if id.is_user() {
3060                    trace!("downgrading since of {} to {:?}", id, new_since);
3061                }
3062
3063                let epoch = since_handle.opaque().clone();
3064                let result = if new_since.is_empty() {
3065                    // A shard's since reaching the empty frontier is a prereq for
3066                    // being able to finalize a shard, so the final downgrade should
3067                    // never be rate-limited.
3068                    Some(
3069                        since_handle
3070                            .compare_and_downgrade_since(&epoch, (&epoch, &new_since))
3071                            .await,
3072                    )
3073                } else {
3074                    since_handle
3075                        .maybe_compare_and_downgrade_since(&epoch, (&epoch, &new_since))
3076                        .await
3077                };
3078                (id, since_handle, result)
3079            };
3080            futures.push(fut);
3081        }
3082
3083        for (id, since_handle, result) in futures::future::join_all(futures).await {
3084            let new_since = match result {
3085                Some(Ok(since)) => Some(since),
3086                Some(Err(other_epoch)) => mz_ore::halt!(
3087                    "fenced by envd @ {other_epoch:?}. ours = {:?}",
3088                    since_handle.opaque(),
3089                ),
3090                None => None,
3091            };
3092
3093            self.since_handles.insert(id, since_handle);
3094
3095            if new_since.is_some_and(|s| s.is_empty()) {
3096                info!(%id, "removing persist handles because the since advanced to []!");
3097
3098                let _since_handle = self.since_handles.remove(&id).expect("known to exist");
3099                let Some(dropped_shard_id) = self.shard_by_id.remove(&id) else {
3100                    panic!("missing GlobalId -> ShardId mapping for id {id}");
3101                };
3102
3103                // We're not responsible for writes to tables, so we also don't
3104                // de-register them from the txn system. Whoever is responsible
3105                // will remove them. We only make sure to remove the table from
3106                // our tracking.
3107                self.txns_shards.remove(&id);
3108
3109                if self
3110                    .config
3111                    .lock()
3112                    .expect("lock poisoned")
3113                    .parameters
3114                    .finalize_shards
3115                {
3116                    info!(
3117                        %id, %dropped_shard_id,
3118                        "enqueuing shard finalization due to dropped collection and dropped \
3119                         persist handle",
3120                    );
3121                    self.finalizable_shards.lock().insert(dropped_shard_id);
3122                } else {
3123                    info!(
3124                        "not triggering shard finalization due to dropped storage object \
3125                         because enable_storage_shard_finalization parameter is false"
3126                    );
3127                }
3128            }
3129        }
3130    }
3131}
3132
3133struct FinalizeShardsTaskConfig {
3134    envd_epoch: NonZeroI64,
3135    config: Arc<Mutex<StorageConfiguration>>,
3136    metrics: StorageCollectionsMetrics,
3137    finalizable_shards: Arc<ShardIdSet>,
3138    finalized_shards: Arc<ShardIdSet>,
3139    persist_location: PersistLocation,
3140    persist: Arc<PersistClientCache>,
3141    read_only: bool,
3142}
3143
3144async fn finalize_shards_task(
3145    FinalizeShardsTaskConfig {
3146        envd_epoch,
3147        config,
3148        metrics,
3149        finalizable_shards,
3150        finalized_shards,
3151        persist_location,
3152        persist,
3153        read_only,
3154    }: FinalizeShardsTaskConfig,
3155) {
3156    if read_only {
3157        info!("disabling shard finalization in read only mode");
3158        return;
3159    }
3160
3161    let mut interval = tokio::time::interval(Duration::from_secs(5));
3162    interval.set_missed_tick_behavior(MissedTickBehavior::Delay);
3163    loop {
3164        interval.tick().await;
3165
3166        if !config
3167            .lock()
3168            .expect("lock poisoned")
3169            .parameters
3170            .finalize_shards
3171        {
3172            debug!(
3173                "not triggering shard finalization due to dropped storage object because enable_storage_shard_finalization parameter is false"
3174            );
3175            continue;
3176        }
3177
3178        let current_finalizable_shards = {
3179            // We hold the lock for as short as possible and pull our cloned set
3180            // of shards.
3181            finalizable_shards.lock().iter().cloned().collect_vec()
3182        };
3183
3184        if current_finalizable_shards.is_empty() {
3185            debug!("no shards to finalize");
3186            continue;
3187        }
3188
3189        debug!(?current_finalizable_shards, "attempting to finalize shards");
3190
3191        // Open a persist client to delete unused shards.
3192        let persist_client = persist.open(persist_location.clone()).await.unwrap();
3193
3194        let metrics = &metrics;
3195        let finalizable_shards = &finalizable_shards;
3196        let finalized_shards = &finalized_shards;
3197        let persist_client = &persist_client;
3198        let diagnostics = &Diagnostics::from_purpose("finalizing shards");
3199
3200        let force_downgrade_since = STORAGE_DOWNGRADE_SINCE_DURING_FINALIZATION
3201            .get(config.lock().expect("lock poisoned").config_set());
3202
3203        let epoch = &PersistEpoch::from(envd_epoch);
3204
3205        futures::stream::iter(current_finalizable_shards.clone())
3206            .map(|shard_id| async move {
3207                let persist_client = persist_client.clone();
3208                let diagnostics = diagnostics.clone();
3209                let epoch = epoch.clone();
3210
3211                metrics.finalization_started.inc();
3212
3213                let is_finalized = persist_client
3214                    .is_finalized::<SourceData, (), Timestamp, StorageDiff>(shard_id, diagnostics)
3215                    .await
3216                    .expect("invalid persist usage");
3217
3218                if is_finalized {
3219                    debug!(%shard_id, "shard is already finalized!");
3220                    Some(shard_id)
3221                } else {
3222                    debug!(%shard_id, "finalizing shard");
3223                    let finalize = || async move {
3224                        // TODO: thread the global ID into the shard finalization WAL
3225                        let diagnostics = Diagnostics::from_purpose("finalizing shards");
3226
3227                        // We only use the writer to advance the upper, so using a dummy schema is
3228                        // fine.
3229                        let mut write_handle: WriteHandle<SourceData, (), Timestamp, StorageDiff> =
3230                            persist_client
3231                                .open_writer(
3232                                    shard_id,
3233                                    Arc::new(RelationDesc::empty()),
3234                                    Arc::new(UnitSchema),
3235                                    diagnostics,
3236                                )
3237                                .await
3238                                .expect("invalid persist usage");
3239                        write_handle.advance_upper(&Antichain::new()).await;
3240                        write_handle.expire().await;
3241
3242                        if force_downgrade_since {
3243                            let our_opaque = Opaque::encode(&epoch);
3244                            let mut since_handle: SinceHandle<
3245                                SourceData,
3246                                (),
3247                                Timestamp,
3248                                StorageDiff,
3249                            > = persist_client
3250                                .open_critical_since(
3251                                    shard_id,
3252                                    PersistClient::CONTROLLER_CRITICAL_SINCE,
3253                                    our_opaque.clone(),
3254                                    Diagnostics::from_purpose("finalizing shards"),
3255                                )
3256                                .await
3257                                .expect("invalid persist usage");
3258                            let handle_opaque = since_handle.opaque().clone();
3259                            let opaque = if our_opaque.codec_name() == handle_opaque.codec_name()
3260                                && epoch.0 > handle_opaque.decode::<PersistEpoch>().0
3261                            {
3262                                // We're newer, but it's fine to use the
3263                                // handle's old epoch to try and downgrade.
3264                                handle_opaque
3265                            } else {
3266                                // Good luck, buddy! The downgrade below will
3267                                // not succeed. There's a process with a newer
3268                                // epoch out there and someone at some juncture
3269                                // will fence out this process.
3270                                // TODO: consider applying the downgrade no matter what!
3271                                our_opaque
3272                            };
3273                            let new_since = Antichain::new();
3274                            let downgrade = since_handle
3275                                .compare_and_downgrade_since(&opaque, (&opaque, &new_since))
3276                                .await;
3277                            if let Err(e) = downgrade {
3278                                warn!("tried to finalize a shard with an advancing epoch: {e:?}");
3279                                return Ok(true);
3280                            }
3281                            // Not available now, so finalization is broken.
3282                            // since_handle.expire().await;
3283                        }
3284
3285                        persist_client
3286                            .finalize_shard::<SourceData, (), Timestamp, StorageDiff>(
3287                                shard_id,
3288                                Diagnostics::from_purpose("finalizing shards"),
3289                            )
3290                            .await
3291                    };
3292
3293                    match finalize().await {
3294                        Err(e) => {
3295                            // Rather than error, just leave this shard as
3296                            // one to finalize later.
3297                            warn!("error during finalization of shard {shard_id}: {e:?}");
3298                            None
3299                        }
3300                        Ok(true) => {
3301                            debug!(%shard_id, "finalize success!");
3302                            Some(shard_id)
3303                        }
3304                        Ok(false) => {
3305                            debug!(%shard_id, "finalize unfinished, retrying later");
3306                            None
3307                        }
3308                    }
3309                }
3310            })
3311            // Poll each future for each collection concurrently, maximum of 10
3312            // at a time.
3313            // TODO(benesch): the concurrency here should be configurable
3314            // via LaunchDarkly.
3315            .buffer_unordered(10)
3316            // HERE BE DRAGONS: see warning on other uses of buffer_unordered.
3317            // The closure passed to `for_each` must remain fast or we risk
3318            // starving the finalization futures of calls to `poll`.
3319            .for_each(|shard_id| async move {
3320                match shard_id {
3321                    None => metrics.finalization_failed.inc(),
3322                    Some(shard_id) => {
3323                        // We make successfully finalized shards available for
3324                        // removal from the finalization WAL one by one, so that
3325                        // a handful of stuck shards don't prevent us from
3326                        // removing the shards that have made progress. The
3327                        // overhead of repeatedly acquiring and releasing the
3328                        // locks is negligible.
3329                        {
3330                            let mut finalizable_shards = finalizable_shards.lock();
3331                            let mut finalized_shards = finalized_shards.lock();
3332                            finalizable_shards.remove(&shard_id);
3333                            finalized_shards.insert(shard_id);
3334                        }
3335
3336                        metrics.finalization_succeeded.inc();
3337                    }
3338                }
3339            })
3340            .await;
3341
3342        debug!("done finalizing shards");
3343    }
3344}
3345
3346/// A dependency whose since is not below its dependent's upper, found while
3347/// registering collections for bootstrap.
3348#[derive(Debug)]
3349struct DependencyViolation {
3350    id: GlobalId,
3351    dependency: GlobalId,
3352    data_shard_since: Antichain<Timestamp>,
3353    write_frontier: Antichain<Timestamp>,
3354    dependency_since: Antichain<Timestamp>,
3355    /// The dependent's metadata, if it is an ingestion export.
3356    ingestion_export: Option<CollectionMetadata>,
3357}
3358
3359/// Reports whether the data shard of collection `id` holds no updates, judged
3360/// from batch metadata alone.
3361pub async fn shard_has_no_updates(
3362    persist_client: &PersistClient,
3363    id: GlobalId,
3364    metadata: &CollectionMetadata,
3365) -> bool {
3366    let read_handle = persist_client
3367        .open_leased_reader::<SourceData, (), Timestamp, StorageDiff>(
3368            metadata.data_shard,
3369            Arc::new(metadata.relation_desc.clone()),
3370            Arc::new(UnitSchema),
3371            Diagnostics {
3372                shard_name: id.to_string(),
3373                handle_purpose: format!("checking {id} for updates"),
3374            },
3375            false,
3376        )
3377        .await
3378        .expect("invalid persist usage");
3379    let stats = read_handle
3380        .snapshot_stats(None)
3381        .await
3382        .expect("stats without an as_of cannot be behind the since");
3383    read_handle.expire().await;
3384    stats.num_updates == 0
3385}
3386
3387#[derive(Debug)]
3388pub(crate) enum SnapshotStatsAsOf {
3389    /// Stats for a shard with an "eager" upper (one that continually advances
3390    /// as time passes, even if no writes are coming in).
3391    Direct(Antichain<Timestamp>),
3392    /// Stats for a shard with a "lazy" upper (one that only physically advances
3393    /// in response to writes).
3394    Txns(DataSnapshot<Timestamp>),
3395}
3396
3397#[cfg(test)]
3398mod tests {
3399    use std::str::FromStr;
3400    use std::sync::Arc;
3401
3402    use mz_build_info::DUMMY_BUILD_INFO;
3403    use mz_dyncfg::ConfigSet;
3404    use mz_ore::assert_err;
3405    use mz_ore::metrics::{MetricsRegistry, UIntGauge};
3406    use mz_ore::now::SYSTEM_TIME;
3407    use mz_ore::url::SensitiveUrl;
3408    use mz_persist_client::cache::PersistClientCache;
3409    use mz_persist_client::cfg::PersistConfig;
3410    use mz_persist_client::rpc::PubSubClientConnection;
3411    use mz_persist_client::{Diagnostics, PersistClient, PersistLocation, ShardId};
3412    use mz_persist_types::codec_impls::UnitSchema;
3413    use mz_repr::{RelationDesc, Row};
3414    use mz_secrets::InMemorySecretsController;
3415
3416    use super::*;
3417
3418    #[mz_ore::test]
3419    fn test_partition_finalizable_shards() {
3420        let active_shard = ShardId::new();
3421        let dropped_shard = ShardId::new();
3422        let collection_metadata = BTreeMap::from([
3423            (GlobalId::User(1), active_shard),
3424            (GlobalId::User(2), active_shard),
3425            (GlobalId::User(3), dropped_shard),
3426        ]);
3427        let active_collection_ids = BTreeSet::from([GlobalId::User(1), GlobalId::User(2)]);
3428        let unfinalized_shards = BTreeSet::from([active_shard, dropped_shard]);
3429
3430        let (referenced_shards, finalizable_shards) = partition_finalizable_shards(
3431            collection_metadata,
3432            &active_collection_ids,
3433            unfinalized_shards,
3434        );
3435
3436        assert_eq!(referenced_shards, BTreeSet::from([active_shard]));
3437        assert_eq!(finalizable_shards, BTreeSet::from([dropped_shard]));
3438    }
3439
3440    #[mz_ore::test(tokio::test)]
3441    #[cfg_attr(miri, ignore)] // unsupported operation: integer-to-pointer casts and `ptr::from_exposed_addr`
3442    async fn test_snapshot_stats(&self) {
3443        let persist_location = PersistLocation {
3444            blob_uri: SensitiveUrl::from_str("mem://").expect("invalid URL"),
3445            consensus_uri: SensitiveUrl::from_str("mem://").expect("invalid URL"),
3446        };
3447        let persist_client = PersistClientCache::new(
3448            PersistConfig::new_default_configs(&DUMMY_BUILD_INFO, SYSTEM_TIME.clone()),
3449            &MetricsRegistry::new(),
3450            |_, _| PubSubClientConnection::noop(),
3451        );
3452        let persist_client = Arc::new(persist_client);
3453
3454        let (cmds_tx, mut background_task) =
3455            BackgroundTask::new_for_test(persist_location.clone(), Arc::clone(&persist_client));
3456        let background_task =
3457            mz_ore::task::spawn(|| "storage_collections::background_task", async move {
3458                background_task.run().await
3459            });
3460
3461        let persist = persist_client.open(persist_location).await.unwrap();
3462
3463        let shard_id = ShardId::new();
3464        let since_handle = persist
3465            .open_critical_since(
3466                shard_id,
3467                PersistClient::CONTROLLER_CRITICAL_SINCE,
3468                Opaque::encode(&PersistEpoch::default()),
3469                Diagnostics::for_tests(),
3470            )
3471            .await
3472            .unwrap();
3473        let write_handle = persist
3474            .open_writer::<SourceData, (), mz_repr::Timestamp, StorageDiff>(
3475                shard_id,
3476                Arc::new(RelationDesc::empty()),
3477                Arc::new(UnitSchema),
3478                Diagnostics::for_tests(),
3479            )
3480            .await
3481            .unwrap();
3482
3483        cmds_tx
3484            .send(BackgroundCmd::Register {
3485                id: GlobalId::User(1),
3486                is_in_txns: false,
3487                since_handle: SinceHandleWrapper::Critical(since_handle),
3488                write_handle,
3489            })
3490            .unwrap();
3491
3492        let mut write_handle = persist
3493            .open_writer::<SourceData, (), mz_repr::Timestamp, StorageDiff>(
3494                shard_id,
3495                Arc::new(RelationDesc::empty()),
3496                Arc::new(UnitSchema),
3497                Diagnostics::for_tests(),
3498            )
3499            .await
3500            .unwrap();
3501
3502        // No stats for unknown GlobalId.
3503        let stats =
3504            snapshot_stats(&cmds_tx, GlobalId::User(2), Antichain::from_elem(0.into())).await;
3505        assert_err!(stats);
3506
3507        // Stats don't resolve for as_of past the upper.
3508        let stats_fut = snapshot_stats(&cmds_tx, GlobalId::User(1), Antichain::from_elem(1.into()));
3509        assert_none!(stats_fut.now_or_never());
3510
3511        // // Call it again because now_or_never consumed our future and it's not clone-able.
3512        let stats_ts1_fut =
3513            snapshot_stats(&cmds_tx, GlobalId::User(1), Antichain::from_elem(1.into()));
3514
3515        // Write some data.
3516        let data = (
3517            (SourceData(Ok(Row::default())), ()),
3518            mz_repr::Timestamp::from(0),
3519            1i64,
3520        );
3521        let () = write_handle
3522            .compare_and_append(
3523                &[data],
3524                Antichain::from_elem(0.into()),
3525                Antichain::from_elem(1.into()),
3526            )
3527            .await
3528            .unwrap()
3529            .unwrap();
3530
3531        // Verify that we can resolve stats for ts 0 while the ts 1 stats call is outstanding.
3532        let stats = snapshot_stats(&cmds_tx, GlobalId::User(1), Antichain::from_elem(0.into()))
3533            .await
3534            .unwrap();
3535        assert_eq!(stats.num_updates, 1);
3536
3537        // Write more data and unblock the ts 1 call
3538        let data = (
3539            (SourceData(Ok(Row::default())), ()),
3540            mz_repr::Timestamp::from(1),
3541            1i64,
3542        );
3543        let () = write_handle
3544            .compare_and_append(
3545                &[data],
3546                Antichain::from_elem(1.into()),
3547                Antichain::from_elem(2.into()),
3548            )
3549            .await
3550            .unwrap()
3551            .unwrap();
3552
3553        let stats = stats_ts1_fut.await.unwrap();
3554        assert_eq!(stats.num_updates, 2);
3555
3556        // Make sure it runs until at least here.
3557        drop(background_task);
3558    }
3559
3560    // The snapshot's reader must outlive the call, or GC can delete parts the
3561    // stream has yet to read.
3562    #[mz_ore::test(tokio::test)]
3563    #[cfg_attr(miri, ignore)] // unsupported operation: integer-to-pointer casts and `ptr::from_exposed_addr`
3564    async fn test_snapshot_and_stream_keeps_reader() {
3565        let persist_clients = Arc::new(PersistClientCache::new_no_metrics());
3566        let location = PersistLocation::new_in_mem();
3567        let persist = persist_clients.open(location.clone()).await.unwrap();
3568        let metadata = CollectionMetadata {
3569            persist_location: location,
3570            data_shard: ShardId::new(),
3571            relation_desc: RelationDesc::empty(),
3572            txns_shard: None,
3573        };
3574
3575        let mut write_handle = persist
3576            .open_writer::<SourceData, (), mz_repr::Timestamp, StorageDiff>(
3577                metadata.data_shard,
3578                Arc::new(metadata.relation_desc.clone()),
3579                Arc::new(UnitSchema),
3580                Diagnostics::for_tests(),
3581            )
3582            .await
3583            .unwrap();
3584        let data = ((SourceData(Ok(Row::default())), ()), Timestamp::MIN, 1i64);
3585        let () = write_handle
3586            .compare_and_append(
3587                &[data],
3588                Antichain::from_elem(0.into()),
3589                Antichain::from_elem(1.into()),
3590            )
3591            .await
3592            .unwrap()
3593            .unwrap();
3594
3595        let readers = || async {
3596            let state = persist
3597                .inspect_shard::<mz_repr::Timestamp>(&metadata.data_shard)
3598                .await
3599                .unwrap();
3600            let state = serde_json::to_value(state).unwrap();
3601            state["leased_readers"].as_object().unwrap().len()
3602        };
3603
3604        let stream = StorageCollectionsImpl::snapshot_and_stream_inner(
3605            Arc::clone(&persist_clients),
3606            metadata.clone(),
3607            GlobalId::User(1),
3608            0.into(),
3609            None,
3610        )
3611        .await
3612        .unwrap();
3613        // A dropped handle's reader would be gone by now.
3614        tokio::time::sleep(Duration::from_secs(1)).await;
3615        assert_eq!(readers().await, 1);
3616
3617        assert_eq!(stream.collect::<Vec<_>>().await.len(), 1);
3618        tokio::time::timeout(Duration::from_secs(30), async {
3619            while readers().await > 0 {
3620                tokio::time::sleep(Duration::from_millis(100)).await;
3621            }
3622        })
3623        .await
3624        .expect("reader expires with the stream");
3625    }
3626
3627    async fn snapshot_stats(
3628        cmds_tx: &mpsc::UnboundedSender<BackgroundCmd>,
3629        id: GlobalId,
3630        as_of: Antichain<Timestamp>,
3631    ) -> Result<SnapshotStats, StorageError> {
3632        let (tx, rx) = oneshot::channel();
3633        cmds_tx
3634            .send(BackgroundCmd::SnapshotStats(
3635                id,
3636                SnapshotStatsAsOf::Direct(as_of),
3637                tx,
3638            ))
3639            .unwrap();
3640        let res = rx.await.expect("BackgroundTask should be live").0;
3641
3642        res.await
3643    }
3644
3645    impl BackgroundTask {
3646        fn new_for_test(
3647            _persist_location: PersistLocation,
3648            _persist_client: Arc<PersistClientCache>,
3649        ) -> (mpsc::UnboundedSender<BackgroundCmd>, Self) {
3650            let (cmds_tx, cmds_rx) = mpsc::unbounded_channel();
3651            let (_holds_tx, holds_rx) = mpsc::unbounded_channel();
3652            let connection_context =
3653                ConnectionContext::for_tests(Arc::new(InMemorySecretsController::new()));
3654
3655            let task = Self {
3656                config: Arc::new(Mutex::new(StorageConfiguration::new(
3657                    connection_context,
3658                    ConfigSet::default(),
3659                ))),
3660                cmds_tx: cmds_tx.clone(),
3661                cmds_rx,
3662                holds_rx,
3663                finalizable_shards: Arc::new(ShardIdSet::new(
3664                    UIntGauge::new("finalizable_shards", "dummy gauge for tests").unwrap(),
3665                )),
3666                collections: Arc::new(Mutex::new(BTreeMap::new())),
3667                shard_by_id: BTreeMap::new(),
3668                since_handles: BTreeMap::new(),
3669                txns_handle: None,
3670                txns_shards: BTreeSet::new(),
3671            };
3672
3673            (cmds_tx, task)
3674        }
3675    }
3676}