Skip to main content

mz_catalog/durable/
persist.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#[cfg(test)]
11mod tests;
12
13use std::cmp::max;
14use std::collections::{BTreeMap, VecDeque};
15use std::fmt::Debug;
16use std::str::FromStr;
17use std::sync::{Arc, LazyLock};
18use std::time::{Duration, Instant};
19
20use async_trait::async_trait;
21use differential_dataflow::lattice::Lattice;
22use futures::{FutureExt, StreamExt};
23use itertools::Itertools;
24use mz_audit_log::VersionedEvent;
25use mz_ore::cast::CastFrom;
26use mz_ore::metrics::MetricsFutureExt;
27use mz_ore::now::EpochMillis;
28use mz_ore::{
29    soft_assert_eq_no_log, soft_assert_eq_or_log, soft_assert_ne_or_log, soft_assert_no_log,
30    soft_assert_or_log, soft_panic_or_log,
31};
32use mz_persist_client::cfg::USE_CRITICAL_SINCE_CATALOG;
33use mz_persist_client::cli::admin::{CATALOG_FORCE_COMPACTION_FUEL, CATALOG_FORCE_COMPACTION_WAIT};
34use mz_persist_client::critical::{CriticalReaderId, Opaque, SinceHandle};
35use mz_persist_client::error::UpperMismatch;
36use mz_persist_client::read::{Listen, ListenEvent, ReadHandle};
37use mz_persist_client::write::WriteHandle;
38use mz_persist_client::{Diagnostics, PersistClient, ShardId};
39use mz_persist_types::codec_impls::UnitSchema;
40use mz_proto::TryFromProtoError;
41use mz_repr::Diff;
42use mz_storage_client::controller::PersistEpoch;
43use mz_storage_types::StorageDiff;
44use mz_storage_types::sources::SourceData;
45use sha2::Digest;
46use timely::progress::{Antichain, Timestamp as TimelyTimestamp};
47use tracing::{debug, info, warn};
48use uuid::Uuid;
49
50use crate::durable::debug::{Collection, CollectionType, DebugCatalogState, Trace};
51use crate::durable::error::FenceError;
52use crate::durable::initialize::{
53    ENABLE_0DT_DEPLOYMENT_PANIC_AFTER_TIMEOUT, SYSTEM_CONFIG_SYNCED_KEY, USER_VERSION_KEY,
54    WITH_0DT_DEPLOYMENT_DDL_CHECK_INTERVAL, WITH_0DT_DEPLOYMENT_MAX_WAIT,
55};
56use crate::durable::metrics::Metrics;
57use crate::durable::objects::serialization::RustType;
58use crate::durable::objects::state_update::{
59    IntoStateUpdateKindJson, StateUpdate, StateUpdateKind, StateUpdateKindJson,
60    TryIntoStateUpdateKind,
61};
62use crate::durable::objects::{AuditLogKey, FenceToken, Snapshot};
63use crate::durable::transaction::TransactionBatch;
64use crate::durable::upgrade::upgrade;
65use crate::durable::{
66    BootstrapArgs, CATALOG_CONTENT_VERSION_KEY, CatalogError, DryRunTransaction,
67    DurableCatalogError, DurableCatalogState, Epoch, OpenableDurableCatalogState,
68    ReadOnlyDurableCatalogState, Transaction, initialize, persist_desc,
69};
70use crate::memory;
71
72/// New-type used to represent timestamps in persist.
73pub(crate) type Timestamp = mz_repr::Timestamp;
74
75/// The minimum value of an epoch.
76const MIN_EPOCH: Epoch = Epoch::new(1).expect("1 is non-zero");
77
78/// Human readable catalog shard name.
79const CATALOG_SHARD_NAME: &str = "catalog";
80
81/// [`CriticalReaderId`] for the catalog shard's own since hold, separate from
82/// [`PersistClient::CONTROLLER_CRITICAL_SINCE`].
83static CATALOG_CRITICAL_SINCE: LazyLock<CriticalReaderId> = LazyLock::new(|| {
84    "c55555555-6666-7777-8888-999999999999"
85        .parse()
86        .expect("valid CriticalReaderId")
87});
88
89/// Seed used to generate the persist shard ID for the catalog.
90const CATALOG_SEED: usize = 1;
91/// Legacy seed used to generate the persist shard ID for the upgrade shard. DO NOT REUSE.
92const _UPGRADE_SEED: usize = 2;
93/// Legacy seed used to generate the persist shard ID for builtin table migrations. DO NOT REUSE.
94pub const _BUILTIN_MIGRATION_SEED: usize = 3;
95/// Legacy seed used to generate the persist shard ID for the expression cache. DO NOT REUSE.
96pub const _EXPRESSION_CACHE_SEED: usize = 4;
97
98/// Durable catalog mode that dictates the effect of mutable operations.
99#[derive(Debug, Copy, Clone, Eq, PartialEq)]
100pub(crate) enum Mode {
101    /// Mutable operations are prohibited.
102    Readonly,
103    /// Mutable operations have an effect in-memory, but aren't persisted durably.
104    Savepoint,
105    /// Mutable operations have an effect in-memory and durably.
106    Writable,
107}
108
109/// Enum representing the fenced state of the catalog.
110#[derive(Debug)]
111pub(crate) enum FenceableToken {
112    /// The catalog is still initializing and learning about previously written fence tokens. This
113    /// state can be fenced if it encounters a larger deploy generation.
114    Initializing {
115        /// The largest fence token durably written to the catalog, if any.
116        durable_token: Option<FenceToken>,
117        /// This process's deploy generation.
118        current_deploy_generation: Option<u64>,
119    },
120    /// The current token has not been fenced.
121    Unfenced { current_token: FenceToken },
122    /// The current token has been fenced.
123    Fenced {
124        current_token: FenceToken,
125        fence_token: FenceToken,
126    },
127}
128
129impl FenceableToken {
130    /// Returns a new token.
131    fn new(current_deploy_generation: Option<u64>) -> Self {
132        Self::Initializing {
133            durable_token: None,
134            current_deploy_generation,
135        }
136    }
137
138    /// Returns the current token if it is not fenced, otherwise returns an error.
139    fn validate(&self) -> Result<Option<FenceToken>, FenceError> {
140        match self {
141            FenceableToken::Initializing { durable_token, .. } => Ok(durable_token.clone()),
142            FenceableToken::Unfenced { current_token, .. } => Ok(Some(current_token.clone())),
143            FenceableToken::Fenced {
144                current_token,
145                fence_token,
146            } => {
147                assert!(
148                    fence_token > current_token,
149                    "must be fenced by higher token; current={current_token:?}, fence={fence_token:?}"
150                );
151                if fence_token.deploy_generation > current_token.deploy_generation {
152                    Err(FenceError::DeployGeneration {
153                        current_generation: current_token.deploy_generation,
154                        fence_generation: fence_token.deploy_generation,
155                    })
156                } else {
157                    assert!(
158                        fence_token.epoch > current_token.epoch,
159                        "must be fenced by higher token; current={current_token:?}, fence={fence_token:?}"
160                    );
161                    Err(FenceError::Epoch {
162                        current_epoch: current_token.epoch,
163                        fence_epoch: fence_token.epoch,
164                    })
165                }
166            }
167        }
168    }
169
170    /// Returns the current token.
171    fn token(&self) -> Option<FenceToken> {
172        match self {
173            FenceableToken::Initializing { durable_token, .. } => durable_token.clone(),
174            FenceableToken::Unfenced { current_token, .. } => Some(current_token.clone()),
175            FenceableToken::Fenced { current_token, .. } => Some(current_token.clone()),
176        }
177    }
178
179    /// Returns `Err` if `token` fences out `self`, `Ok` otherwise.
180    fn maybe_fence(&mut self, token: FenceToken) -> Result<(), FenceError> {
181        match self {
182            FenceableToken::Initializing {
183                durable_token,
184                current_deploy_generation,
185                ..
186            } => {
187                match durable_token {
188                    Some(durable_token) => {
189                        *durable_token = max(durable_token.clone(), token.clone());
190                    }
191                    None => {
192                        *durable_token = Some(token.clone());
193                    }
194                }
195                if let Some(current_deploy_generation) = current_deploy_generation {
196                    if *current_deploy_generation < token.deploy_generation {
197                        *self = FenceableToken::Fenced {
198                            current_token: FenceToken {
199                                deploy_generation: *current_deploy_generation,
200                                epoch: token.epoch,
201                            },
202                            fence_token: token,
203                        };
204                        self.validate()?;
205                    }
206                }
207            }
208            FenceableToken::Unfenced { current_token } => {
209                if *current_token < token {
210                    *self = FenceableToken::Fenced {
211                        current_token: current_token.clone(),
212                        fence_token: token,
213                    };
214                    self.validate()?;
215                }
216            }
217            FenceableToken::Fenced { .. } => {
218                self.validate()?;
219            }
220        }
221
222        Ok(())
223    }
224
225    /// Returns a [`FenceableToken::Unfenced`] token and the updates to the catalog required to
226    /// transition to the `Unfenced` state if `self` is [`FenceableToken::Initializing`], otherwise
227    /// returns `None`.
228    fn generate_unfenced_token(
229        &self,
230        mode: Mode,
231    ) -> Result<Option<(Vec<(StateUpdateKind, Diff)>, FenceableToken)>, DurableCatalogError> {
232        let (durable_token, current_deploy_generation) = match self {
233            FenceableToken::Initializing {
234                durable_token,
235                current_deploy_generation,
236            } => (durable_token.clone(), current_deploy_generation.clone()),
237            FenceableToken::Unfenced { .. } | FenceableToken::Fenced { .. } => return Ok(None),
238        };
239
240        let mut fence_updates = Vec::with_capacity(2);
241
242        if let Some(durable_token) = &durable_token {
243            fence_updates.push((
244                StateUpdateKind::FenceToken(durable_token.clone()),
245                Diff::MINUS_ONE,
246            ));
247        }
248
249        let current_deploy_generation = current_deploy_generation
250            .or_else(|| durable_token.as_ref().map(|token| token.deploy_generation))
251            // We cannot initialize a catalog without a deploy generation.
252            .ok_or(DurableCatalogError::Uninitialized)?;
253        let mut current_epoch = durable_token
254            .map(|token| token.epoch)
255            .unwrap_or(MIN_EPOCH)
256            .get();
257        // Only writable catalogs attempt to increment the epoch.
258        if matches!(mode, Mode::Writable) {
259            current_epoch = current_epoch + 1;
260        }
261        let current_epoch = Epoch::new(current_epoch).expect("known to be non-zero");
262        let current_token = FenceToken {
263            deploy_generation: current_deploy_generation,
264            epoch: current_epoch,
265        };
266
267        fence_updates.push((
268            StateUpdateKind::FenceToken(current_token.clone()),
269            Diff::ONE,
270        ));
271
272        let current_fenceable_token = FenceableToken::Unfenced { current_token };
273
274        Ok(Some((fence_updates, current_fenceable_token)))
275    }
276}
277
278/// An error that can occur while executing [`PersistHandle::compare_and_append`].
279#[derive(Debug, thiserror::Error)]
280pub(crate) enum CompareAndAppendError {
281    #[error(transparent)]
282    Fence(#[from] FenceError),
283    /// Catalog encountered an upper mismatch when trying to write to the catalog: another
284    /// writer moved the upper between our snapshot of it and the write. Handled by the conflict
285    /// classification in the commit and advance paths (rebase over empty progress, surface
286    /// content conflicts as out-of-sync).
287    #[error(
288        "expected catalog upper {expected_upper:?} did not match actual catalog upper {actual_upper:?}"
289    )]
290    UpperMismatch {
291        expected_upper: Timestamp,
292        actual_upper: Timestamp,
293    },
294}
295
296impl CompareAndAppendError {
297    pub(crate) fn unwrap_fence_error(self) -> FenceError {
298        match self {
299            CompareAndAppendError::Fence(e) => e,
300            e @ CompareAndAppendError::UpperMismatch { .. } => {
301                panic!("unexpected upper mismatch: {e:?}")
302            }
303        }
304    }
305}
306
307impl From<UpperMismatch<Timestamp>> for CompareAndAppendError {
308    fn from(upper_mismatch: UpperMismatch<Timestamp>) -> Self {
309        Self::UpperMismatch {
310            expected_upper: antichain_to_timestamp(upper_mismatch.expected),
311            actual_upper: antichain_to_timestamp(upper_mismatch.current),
312        }
313    }
314}
315
316pub(crate) trait ApplyUpdate<T: IntoStateUpdateKindJson> {
317    /// Process and apply `update`.
318    ///
319    /// Returns `Some` if `update` should be cached in memory and `None` otherwise.
320    fn apply_update(
321        &mut self,
322        update: StateUpdate<T>,
323        current_fence_token: &mut FenceableToken,
324        metrics: &Arc<Metrics>,
325    ) -> Result<Option<StateUpdate<T>>, FenceError>;
326}
327
328/// A handle for interacting with the persist catalog shard.
329///
330/// The catalog shard is used in multiple different contexts, for example pre-open and post-open,
331/// but for all contexts the majority of the durable catalog's behavior is identical. This struct
332/// implements those behaviors that are identical while allowing the user to specify the different
333/// behaviors via generic parameters.
334///
335/// The behavior of the durable catalog can be different along one of two axes. The first is the
336/// format of each individual update, i.e. raw binary, the current protobuf version, previous
337/// protobuf versions, etc. The second axis is what to do with each individual update, for example
338/// before opening we cache all config updates but don't cache them after opening. These behaviors
339/// are customizable via the `T: TryIntoStateUpdateKind` and `U: ApplyUpdate<T>` generic parameters
340/// respectively.
341#[derive(Debug)]
342pub(crate) struct PersistHandle<T: TryIntoStateUpdateKind, U: ApplyUpdate<T>> {
343    /// The [`Mode`] that this catalog was opened in.
344    pub(crate) mode: Mode,
345    /// Since handle to control compaction.
346    since_handle: SinceHandle<SourceData, (), Timestamp, StorageDiff>,
347    /// Write handle to persist.
348    write_handle: WriteHandle<SourceData, (), Timestamp, StorageDiff>,
349    /// Listener to catalog changes.
350    listen: Listen<SourceData, (), Timestamp, StorageDiff>,
351    /// Handle for connecting to persist.
352    persist_client: PersistClient,
353    /// Catalog shard ID.
354    shard_id: ShardId,
355    /// Cache of the most recent catalog snapshot.
356    ///
357    /// We use a tuple instead of [`StateUpdate`] to make consolidation easier.
358    pub(crate) snapshot: Vec<(T, Timestamp, Diff)>,
359    /// Applies custom processing, filtering, and fencing for each individual update.
360    update_applier: U,
361    /// The current upper of the persist shard.
362    pub(crate) upper: Timestamp,
363    /// The fence token of the catalog, if one exists.
364    fenceable_token: FenceableToken,
365    /// The semantic version of the current binary.
366    catalog_content_version: semver::Version,
367    /// Flag to indicate if bootstrap is complete.
368    bootstrap_complete: bool,
369    /// Metrics for the persist catalog.
370    metrics: Arc<Metrics>,
371    /// Snapshot size at the last amortized consolidation, used by
372    /// [`Self::maybe_consolidate`] to decide when to consolidate. Initialized
373    /// lazily on the first call.
374    size_at_last_consolidation: Option<usize>,
375    /// Counts raw updates applied to this handle.
376    ///
377    /// This distinguishes empty upper progress from content. Memory updates are insufficient
378    /// because kinds such as ID allocators do not produce them.
379    updates_applied: u64,
380}
381
382impl<T: TryIntoStateUpdateKind, U: ApplyUpdate<T>> PersistHandle<T, U> {
383    /// Fetch the current upper of the catalog state.
384    #[mz_ore::instrument]
385    async fn current_upper(&mut self) -> Timestamp {
386        match self.mode {
387            Mode::Writable | Mode::Readonly => {
388                let upper = self.write_handle.fetch_recent_upper().await;
389                antichain_to_timestamp(upper.clone())
390            }
391            Mode::Savepoint => self.upper,
392        }
393    }
394
395    /// Appends `updates` iff the current global upper of the catalog is `self.upper`.
396    ///
397    /// Returns the next upper used to commit the transaction.
398    #[mz_ore::instrument]
399    pub(crate) async fn compare_and_append<S: IntoStateUpdateKindJson>(
400        &mut self,
401        updates: Vec<(S, Diff)>,
402        commit_ts: Timestamp,
403    ) -> Result<Timestamp, CompareAndAppendError> {
404        let updates = updates.into_iter().map(|(kind, diff)| {
405            let kind: StateUpdateKindJson = kind.into();
406            (
407                (Into::<SourceData>::into(kind), ()),
408                commit_ts,
409                diff.into_inner(),
410            )
411        });
412        let next_upper = commit_ts.step_forward();
413        // Upper mismatches are classified by the commit and advance callers.
414        self.compare_and_append_inner(updates, next_upper).await?;
415
416        self.sync(next_upper).await?;
417        Ok(next_upper)
418    }
419
420    /// Compare-and-append `updates` to the catalog shard, advancing the upper to `next_upper`.
421    ///
422    /// On success, updating `self.upper` is left to the caller. The caller can thus decide whether
423    /// or not it needs to sync the catalog.
424    ///
425    /// # Panics
426    ///
427    /// Panics if not in `Writable` mode.
428    /// Panics if `next_upper` is not greater than `self.upper`.
429    async fn compare_and_append_inner(
430        &mut self,
431        updates: impl IntoIterator<Item = ((SourceData, ()), Timestamp, StorageDiff)>,
432        next_upper: Timestamp,
433    ) -> Result<(), CompareAndAppendError> {
434        assert_eq!(self.mode, Mode::Writable);
435        assert!(
436            next_upper > self.upper,
437            "next_upper ({next_upper}) not greater than current upper ({})",
438            self.upper,
439        );
440
441        let res = self
442            .write_handle
443            .compare_and_append(
444                updates,
445                Antichain::from_elem(self.upper),
446                Antichain::from_elem(next_upper),
447            )
448            .await
449            .expect("invalid usage");
450
451        if let Err(e @ UpperMismatch { .. }) = res {
452            // Most likely we were fenced out.
453            // Sync to the current upper to detect that.
454            self.sync_to_current_upper().await?;
455            return Err(e.into());
456        }
457
458        // Lag the shard's upper by 1 to keep it readable.
459        let downgrade_to = Antichain::from_elem(next_upper.saturating_sub(1));
460
461        // The since handle gives us the ability to fence out other downgraders using an opaque token.
462        // (See the method documentation for details.)
463        // That's not needed here, so we use the since handle's opaque token to avoid any comparison
464        // failures.
465        let opaque = self.since_handle.opaque().clone();
466        let downgrade = self
467            .since_handle
468            .maybe_compare_and_downgrade_since(&opaque, (&opaque, &downgrade_to))
469            .await;
470        if let Some(Err(e)) = downgrade {
471            soft_panic_or_log!("found opaque value {e:?}, but expected {opaque:?}");
472        }
473
474        Ok(())
475    }
476
477    /// Accepts an upper mismatch caused only by empty progress.
478    ///
479    /// `updates_applied_before` must be captured before the compare-and-append, which synchronizes
480    /// this handle on mismatch.
481    fn classify_upper_mismatch(
482        &self,
483        updates_applied_before: u64,
484        actual_upper: Timestamp,
485    ) -> Result<(), DurableCatalogError> {
486        if self.updates_applied != updates_applied_before {
487            Err(DurableCatalogError::CatalogOutOfSync {
488                update_count: usize::cast_from(self.updates_applied - updates_applied_before),
489                upper: actual_upper,
490            })
491        } else {
492            Ok(())
493        }
494    }
495
496    /// Generates an iterator of [`StateUpdate`] that contain all unconsolidated updates to the
497    /// catalog state up to, and including, `as_of`.
498    #[mz_ore::instrument]
499    async fn snapshot_unconsolidated(&mut self) -> Vec<StateUpdate<StateUpdateKind>> {
500        let current_upper = self.current_upper().await;
501
502        let mut snapshot = Vec::new();
503        let mut read_handle = self.read_handle().await;
504        let as_of = as_of(&read_handle, current_upper);
505        let mut stream = Box::pin(
506            // We use `snapshot_and_stream` because it guarantees unconsolidated output.
507            read_handle
508                .snapshot_and_stream(Antichain::from_elem(as_of))
509                .await
510                .expect("we have advanced the restart_as_of by the since"),
511        );
512        while let Some(update) = stream.next().await {
513            snapshot.push(update)
514        }
515        read_handle.expire().await;
516        snapshot
517            .into_iter()
518            .map(Into::<StateUpdate<StateUpdateKindJson>>::into)
519            .map(|state_update| state_update.try_into().expect("kind decoding error"))
520            .collect()
521    }
522
523    /// Listen and apply all updates that are currently in persist.
524    ///
525    /// Returns an error if this instance has been fenced out.
526    #[mz_ore::instrument]
527    pub(crate) async fn sync_to_current_upper(&mut self) -> Result<(), FenceError> {
528        let upper = self.current_upper().await;
529        self.sync(upper).await
530    }
531
532    /// Listen and apply all updates up to `target_upper`.
533    ///
534    /// Returns an error if this instance has been fenced out.
535    #[mz_ore::instrument(level = "debug")]
536    pub(crate) async fn sync(&mut self, target_upper: Timestamp) -> Result<(), FenceError> {
537        self.metrics.syncs.inc();
538        let histogram = self.metrics.sync_latency_seconds.clone();
539        self.sync_inner(target_upper)
540            .wall_time()
541            .observe(histogram)
542            .await
543    }
544
545    #[mz_ore::instrument(level = "debug")]
546    async fn sync_inner(&mut self, target_upper: Timestamp) -> Result<(), FenceError> {
547        self.fenceable_token.validate()?;
548
549        // Savepoint catalogs do not yet know how to update themselves in response to concurrent
550        // writes from writer catalogs.
551        if self.mode == Mode::Savepoint {
552            self.upper = max(self.upper, target_upper);
553            return Ok(());
554        }
555
556        let mut updates: BTreeMap<_, Vec<_>> = BTreeMap::new();
557        let updates_applied_before = self.updates_applied;
558
559        // Reset the amortized consolidation tracker so it picks up the
560        // current snapshot size as its baseline.
561        self.size_at_last_consolidation = None;
562
563        while self.upper < target_upper {
564            let listen_events = self.listen.fetch_next().await;
565            for listen_event in listen_events {
566                match listen_event {
567                    ListenEvent::Progress(upper) => {
568                        debug!("synced up to {upper:?}");
569                        self.upper = antichain_to_timestamp(upper);
570                        // Attempt to apply updates in batches of a single timestamp. If another
571                        // catalog wrote a fence token at one timestamp and then updates in a new
572                        // format at a later timestamp, then we want to apply the fence token
573                        // before attempting to deserialize the new updates.
574                        while let Some((ts, updates)) = updates.pop_first() {
575                            assert!(ts < self.upper, "expected {} < {}", ts, self.upper);
576                            let updates = updates.into_iter().map(
577                                |update: StateUpdate<StateUpdateKindJson>| {
578                                    let kind =
579                                        T::try_from(update.kind).expect("kind decoding error");
580                                    StateUpdate {
581                                        kind,
582                                        ts: update.ts,
583                                        diff: update.diff,
584                                    }
585                                },
586                            );
587                            self.apply_updates(updates)?;
588                            self.maybe_consolidate();
589                        }
590                    }
591                    ListenEvent::Updates(batch_updates) => {
592                        for update in batch_updates {
593                            let update: StateUpdate<StateUpdateKindJson> = update.into();
594                            updates.entry(update.ts).or_default().push(update);
595                        }
596                    }
597                }
598            }
599        }
600        assert_eq!(updates, BTreeMap::new(), "all updates should be applied");
601        // Only consolidate when there are actual updates.
602        if self.updates_applied != updates_applied_before {
603            self.consolidate();
604        }
605        Ok(())
606    }
607
608    /// Apply a batch of updates and then consolidate the snapshot. This is the
609    /// typical entry point for callers that apply updates in a single batch.
610    ///
611    /// For hot loops that apply updates across many timestamps (e.g., `sync_inner`),
612    /// use `apply_updates` directly and call `consolidate()` periodically (e.g.,
613    /// on snapshot doubling) to bound memory while staying amortized O(N log N).
614    pub(crate) fn apply_updates_and_consolidate(
615        &mut self,
616        updates: impl IntoIterator<Item = StateUpdate<T>>,
617    ) -> Result<(), FenceError> {
618        self.apply_updates(updates)?;
619        self.consolidate();
620        Ok(())
621    }
622
623    /// Apply a batch of updates to the catalog state without consolidating.
624    ///
625    /// Does NOT consolidate the snapshot afterward. If you are calling this once,
626    /// prefer `apply_updates_and_consolidate`. This method exists for loops that
627    /// call it many times — consolidating per call would be O(K * N log N) instead
628    /// of O(N log N). Callers should consolidate periodically (e.g., on snapshot
629    /// doubling) to bound memory.
630    #[mz_ore::instrument(level = "debug")]
631    fn apply_updates(
632        &mut self,
633        updates: impl IntoIterator<Item = StateUpdate<T>>,
634    ) -> Result<(), FenceError> {
635        let mut updates: Vec<_> = updates
636            .into_iter()
637            .map(|StateUpdate { kind, ts, diff }| (kind, ts, diff))
638            .collect();
639
640        // This helps guarantee that for a single key, there is at most a single retraction and a
641        // single insertion per timestamp. Otherwise, we would need to match the retractions and
642        // insertions up by value and manually figure out what the end value should be.
643        differential_dataflow::consolidation::consolidate_updates(&mut updates);
644
645        // Updates must be applied in timestamp order. Within a timestamp retractions must be
646        // applied before insertions, or we might end up retracting the wrong value.
647        updates.sort_by(|(_, ts1, diff1), (_, ts2, diff2)| ts1.cmp(ts2).then(diff1.cmp(diff2)));
648
649        let mut errors = Vec::new();
650
651        for (kind, ts, diff) in updates {
652            if diff != Diff::ONE && diff != Diff::MINUS_ONE {
653                panic!("invalid update in consolidated trace: ({kind:?}, {ts:?}, {diff:?})");
654            }
655            self.updates_applied += 1;
656
657            match self.update_applier.apply_update(
658                StateUpdate { kind, ts, diff },
659                &mut self.fenceable_token,
660                &self.metrics,
661            ) {
662                Ok(Some(StateUpdate { kind, ts, diff })) => self.snapshot.push((kind, ts, diff)),
663                Ok(None) => {}
664                // Instead of returning immediately, we accumulate all the errors and return the one
665                // with the most information.
666                Err(err) => errors.push(err),
667            }
668        }
669
670        // Track the high-water mark of the unconsolidated snapshot size.
671        let len = i64::try_from(self.snapshot.len()).unwrap_or(i64::MAX);
672        if len > self.metrics.snapshot_max_entries.get() {
673            self.metrics.snapshot_max_entries.set(len);
674        }
675
676        errors.sort();
677        if let Some(err) = errors.into_iter().next() {
678            return Err(err);
679        }
680
681        Ok(())
682    }
683
684    /// Consolidate the snapshot if it has at least doubled in size since the
685    /// last consolidation. This amortizes the O(N log N) consolidation cost
686    /// over many small updates, keeping the total work O(N log N) rather than
687    /// O(K * N log N) for K timestamps.
688    fn maybe_consolidate(&mut self) {
689        let threshold = *self
690            .size_at_last_consolidation
691            // Use a minimum of 8 to avoid consolidating on every update when
692            // the snapshot is small or empty (since 0 * 2 = 0).
693            .get_or_insert_with(|| max(self.snapshot.len(), 8));
694        if self.snapshot.len() >= threshold * 2 {
695            self.consolidate();
696            self.size_at_last_consolidation = Some(self.snapshot.len());
697        }
698    }
699
700    #[mz_ore::instrument]
701    pub(crate) fn consolidate(&mut self) {
702        self.metrics.snapshot_consolidations.inc();
703        soft_assert_no_log!(
704            self.snapshot
705                .windows(2)
706                .all(|updates| updates[0].1 <= updates[1].1),
707            "snapshot should be sorted by timestamp, {:#?}",
708            self.snapshot
709        );
710
711        let new_ts = self
712            .snapshot
713            .last()
714            .map(|(_, ts, _)| *ts)
715            .unwrap_or_else(Timestamp::minimum);
716        for (_, ts, _) in &mut self.snapshot {
717            *ts = new_ts;
718        }
719        differential_dataflow::consolidation::consolidate_updates(&mut self.snapshot);
720    }
721
722    /// Execute and return the results of `f` on the current catalog trace.
723    ///
724    /// Will return an error if the catalog has been fenced out.
725    async fn with_trace<R>(
726        &mut self,
727        f: impl FnOnce(&Vec<(T, Timestamp, Diff)>) -> Result<R, CatalogError>,
728    ) -> Result<R, CatalogError> {
729        self.sync_to_current_upper().await?;
730        f(&self.snapshot)
731    }
732
733    /// Open a read handle to the catalog.
734    async fn read_handle(&self) -> ReadHandle<SourceData, (), Timestamp, StorageDiff> {
735        self.persist_client
736            .open_leased_reader(
737                self.shard_id,
738                Arc::new(persist_desc()),
739                Arc::new(UnitSchema::default()),
740                Diagnostics {
741                    shard_name: CATALOG_SHARD_NAME.to_string(),
742                    handle_purpose: "openable durable catalog state temporary reader".to_string(),
743                },
744                USE_CRITICAL_SINCE_CATALOG.get(self.persist_client.dyncfgs()),
745            )
746            .await
747            .expect("invalid usage")
748    }
749
750    /// Politely releases all external resources that can only be released in an async context.
751    async fn expire(self: Box<Self>) {
752        self.write_handle.expire().await;
753        self.listen.expire().await;
754    }
755}
756
757impl<U: ApplyUpdate<StateUpdateKind>> PersistHandle<StateUpdateKind, U> {
758    /// Execute and return the results of `f` on the current catalog snapshot.
759    ///
760    /// Will return an error if the catalog has been fenced out.
761    async fn with_snapshot<T>(
762        &mut self,
763        f: impl FnOnce(Snapshot) -> Result<T, CatalogError>,
764    ) -> Result<T, CatalogError> {
765        fn apply<K, V>(map: &mut BTreeMap<K, V>, key: &K, value: &V, diff: Diff)
766        where
767            K: Ord + Clone,
768            V: Ord + Clone + Debug,
769        {
770            let key = key.clone();
771            let value = value.clone();
772            if diff == Diff::ONE {
773                let prev = map.insert(key, value);
774                assert_eq!(
775                    prev, None,
776                    "values must be explicitly retracted before inserting a new value"
777                );
778            } else if diff == Diff::MINUS_ONE {
779                let prev = map.remove(&key);
780                assert_eq!(
781                    prev,
782                    Some(value),
783                    "retraction does not match existing value"
784                );
785            }
786        }
787
788        self.with_trace(|trace| {
789            let mut snapshot = Snapshot::empty();
790            for (kind, ts, diff) in trace {
791                let diff = *diff;
792                if diff != Diff::ONE && diff != Diff::MINUS_ONE {
793                    panic!("invalid update in consolidated trace: ({kind:?}, {ts:?}, {diff:?})");
794                }
795
796                match kind {
797                    StateUpdateKind::AuditLog(_key, ()) => {
798                        // Ignore for snapshots.
799                    }
800                    StateUpdateKind::Cluster(key, value) => {
801                        apply(&mut snapshot.clusters, key, value, diff);
802                    }
803                    StateUpdateKind::ClusterReplica(key, value) => {
804                        apply(&mut snapshot.cluster_replicas, key, value, diff);
805                    }
806                    StateUpdateKind::ClusterReplicaSize(key, value) => {
807                        apply(&mut snapshot.cluster_replica_sizes, key, value, diff);
808                    }
809                    StateUpdateKind::Comment(key, value) => {
810                        apply(&mut snapshot.comments, key, value, diff);
811                    }
812                    StateUpdateKind::IndexColumns(key, value) => {
813                        apply(&mut snapshot.index_columns, key, value, diff);
814                    }
815                    StateUpdateKind::ItemColumns(key, value) => {
816                        apply(&mut snapshot.item_columns, key, value, diff);
817                    }
818                    StateUpdateKind::Config(key, value) => {
819                        apply(&mut snapshot.configs, key, value, diff);
820                    }
821                    StateUpdateKind::Database(key, value) => {
822                        apply(&mut snapshot.databases, key, value, diff);
823                    }
824                    StateUpdateKind::DefaultPrivilege(key, value) => {
825                        apply(&mut snapshot.default_privileges, key, value, diff);
826                    }
827                    StateUpdateKind::FenceToken(_token) => {
828                        // Ignore for snapshots.
829                    }
830                    StateUpdateKind::IdAllocator(key, value) => {
831                        apply(&mut snapshot.id_allocator, key, value, diff);
832                    }
833                    StateUpdateKind::IntrospectionSourceIndex(key, value) => {
834                        apply(&mut snapshot.introspection_sources, key, value, diff);
835                    }
836                    StateUpdateKind::Item(key, value) => {
837                        apply(&mut snapshot.items, key, value, diff);
838                    }
839                    StateUpdateKind::NetworkPolicy(key, value) => {
840                        apply(&mut snapshot.network_policies, key, value, diff);
841                    }
842                    StateUpdateKind::QueryPolicy(key, value) => {
843                        apply(&mut snapshot.query_policies, key, value, diff);
844                    }
845                    StateUpdateKind::Role(key, value) => {
846                        apply(&mut snapshot.roles, key, value, diff);
847                    }
848                    StateUpdateKind::Schema(key, value) => {
849                        apply(&mut snapshot.schemas, key, value, diff);
850                    }
851                    StateUpdateKind::Setting(key, value) => {
852                        apply(&mut snapshot.settings, key, value, diff);
853                    }
854                    StateUpdateKind::SourceReferences(key, value) => {
855                        apply(&mut snapshot.source_references, key, value, diff);
856                    }
857                    StateUpdateKind::SystemConfiguration(key, value) => {
858                        apply(&mut snapshot.system_configurations, key, value, diff);
859                    }
860                    StateUpdateKind::ClusterSystemConfiguration(key, value) => {
861                        apply(
862                            &mut snapshot.cluster_system_configurations,
863                            key,
864                            value,
865                            diff,
866                        );
867                    }
868                    StateUpdateKind::ReplicaSystemConfiguration(key, value) => {
869                        apply(
870                            &mut snapshot.replica_system_configurations,
871                            key,
872                            value,
873                            diff,
874                        );
875                    }
876                    StateUpdateKind::SystemObjectMapping(key, value) => {
877                        apply(&mut snapshot.system_object_mappings, key, value, diff);
878                    }
879                    StateUpdateKind::SystemPrivilege(key, value) => {
880                        apply(&mut snapshot.system_privileges, key, value, diff);
881                    }
882                    StateUpdateKind::StorageCollectionMetadata(key, value) => {
883                        apply(&mut snapshot.storage_collection_metadata, key, value, diff);
884                    }
885                    StateUpdateKind::UnfinalizedShard(key, ()) => {
886                        apply(&mut snapshot.unfinalized_shards, key, &(), diff);
887                    }
888                    StateUpdateKind::TxnWalShard((), value) => {
889                        apply(&mut snapshot.txn_wal_shard, &(), value, diff);
890                    }
891                    StateUpdateKind::RoleAuth(key, value) => {
892                        apply(&mut snapshot.role_auth, key, value, diff);
893                    }
894                }
895            }
896            f(snapshot)
897        })
898        .await
899    }
900
901    /// Generates an iterator of [`StateUpdate`] that contain all updates to the catalog
902    /// state.
903    ///
904    /// The output is fetched directly from persist instead of the in-memory cache.
905    ///
906    /// The output is consolidated and sorted by timestamp in ascending order.
907    #[mz_ore::instrument(level = "debug")]
908    async fn persist_snapshot(&self) -> impl Iterator<Item = StateUpdate> + DoubleEndedIterator {
909        let mut read_handle = self.read_handle().await;
910        let as_of = as_of(&read_handle, self.upper);
911        let snapshot = snapshot_binary(&mut read_handle, as_of, &self.metrics)
912            .await
913            .map(|update| update.try_into().expect("kind decoding error"));
914        read_handle.expire().await;
915        snapshot
916    }
917}
918
919/// Applies updates for an unopened catalog.
920#[derive(Debug)]
921pub(crate) struct UnopenedCatalogStateInner {
922    /// A cache of the config collection of the catalog.
923    configs: BTreeMap<String, u64>,
924    /// A cache of the settings collection of the catalog.
925    settings: BTreeMap<String, String>,
926}
927
928impl UnopenedCatalogStateInner {
929    fn new() -> UnopenedCatalogStateInner {
930        UnopenedCatalogStateInner {
931            configs: BTreeMap::new(),
932            settings: BTreeMap::new(),
933        }
934    }
935}
936
937impl ApplyUpdate<StateUpdateKindJson> for UnopenedCatalogStateInner {
938    fn apply_update(
939        &mut self,
940        update: StateUpdate<StateUpdateKindJson>,
941        current_fence_token: &mut FenceableToken,
942        _metrics: &Arc<Metrics>,
943    ) -> Result<Option<StateUpdate<StateUpdateKindJson>>, FenceError> {
944        if !update.kind.is_audit_log() && update.kind.is_always_deserializable() {
945            let kind = TryInto::try_into(&update.kind).expect("kind is known to be deserializable");
946            match (kind, update.diff) {
947                (StateUpdateKind::Config(key, value), Diff::ONE) => {
948                    let prev = self.configs.insert(key.key, value.value);
949                    assert_eq!(
950                        prev, None,
951                        "values must be explicitly retracted before inserting a new value"
952                    );
953                }
954                (StateUpdateKind::Config(key, value), Diff::MINUS_ONE) => {
955                    let prev = self.configs.remove(&key.key);
956                    assert_eq!(
957                        prev,
958                        Some(value.value),
959                        "retraction does not match existing value"
960                    );
961                }
962                (StateUpdateKind::Setting(key, value), Diff::ONE) => {
963                    let prev = self.settings.insert(key.name, value.value);
964                    assert_eq!(
965                        prev, None,
966                        "values must be explicitly retracted before inserting a new value"
967                    );
968                }
969                (StateUpdateKind::Setting(key, value), Diff::MINUS_ONE) => {
970                    let prev = self.settings.remove(&key.name);
971                    assert_eq!(
972                        prev,
973                        Some(value.value),
974                        "retraction does not match existing value"
975                    );
976                }
977                (StateUpdateKind::FenceToken(fence_token), Diff::ONE) => {
978                    current_fence_token.maybe_fence(fence_token)?;
979                }
980                _ => {}
981            }
982        }
983
984        Ok(Some(update))
985    }
986}
987
988/// A Handle to an unopened catalog stored in persist. The unopened catalog can serve `Config` data,
989/// `Setting` data, or the current epoch. All other catalog data may be un-migrated and should not
990/// be read until the catalog has been opened. The [`UnopenedPersistCatalogState`] is responsible
991/// for opening the catalog, see [`OpenableDurableCatalogState::open`] for more details.
992///
993/// Production users should call [`Self::expire`] before dropping an [`UnopenedPersistCatalogState`]
994/// so that it can expire its leases. If/when rust gets AsyncDrop, this will be done automatically.
995pub(crate) type UnopenedPersistCatalogState =
996    PersistHandle<StateUpdateKindJson, UnopenedCatalogStateInner>;
997
998impl UnopenedPersistCatalogState {
999    /// Create a new [`UnopenedPersistCatalogState`] to the catalog state associated with
1000    /// `organization_id`.
1001    ///
1002    /// All usages of the persist catalog must go through this function. That includes the
1003    /// catalog-debug tool, the adapter's catalog, etc.
1004    #[mz_ore::instrument]
1005    pub(crate) async fn new(
1006        persist_client: PersistClient,
1007        organization_id: Uuid,
1008        version: semver::Version,
1009        deploy_generation: Option<u64>,
1010        metrics: Arc<Metrics>,
1011    ) -> Result<UnopenedPersistCatalogState, DurableCatalogError> {
1012        let catalog_shard_id = shard_id(organization_id, CATALOG_SEED);
1013        debug!(?catalog_shard_id, "new persist backed catalog state");
1014
1015        // Check the catalog shard version to ensure that we are compatible with the persist
1016        // data format. This lets us return an error gracefully, rather than panicking later in
1017        // persist.
1018        let version_in_catalog_shard =
1019            fetch_catalog_shard_version(&persist_client, catalog_shard_id).await;
1020        if let Some(version_in_catalog_shard) = version_in_catalog_shard {
1021            if !mz_persist_client::cfg::code_can_write_data(&version, &version_in_catalog_shard) {
1022                return Err(DurableCatalogError::IncompatiblePersistVersion {
1023                    found_version: version_in_catalog_shard,
1024                    catalog_version: version,
1025                });
1026            }
1027        }
1028
1029        let open_handles_start = Instant::now();
1030        info!("startup: envd serve: catalog init: open handles beginning");
1031        let since_handle = persist_client
1032            .open_critical_since(
1033                catalog_shard_id,
1034                CATALOG_CRITICAL_SINCE.clone(),
1035                Opaque::encode(&i64::MIN),
1036                Diagnostics {
1037                    shard_name: CATALOG_SHARD_NAME.to_string(),
1038                    handle_purpose: "durable catalog state critical since".to_string(),
1039                },
1040            )
1041            .await
1042            .expect("invalid usage");
1043
1044        let (mut write_handle, mut read_handle) = persist_client
1045            .open(
1046                catalog_shard_id,
1047                Arc::new(persist_desc()),
1048                Arc::new(UnitSchema::default()),
1049                Diagnostics {
1050                    shard_name: CATALOG_SHARD_NAME.to_string(),
1051                    handle_purpose: "durable catalog state handles".to_string(),
1052                },
1053                USE_CRITICAL_SINCE_CATALOG.get(persist_client.dyncfgs()),
1054            )
1055            .await
1056            .expect("invalid usage");
1057        info!(
1058            "startup: envd serve: catalog init: open handles complete in {:?}",
1059            open_handles_start.elapsed()
1060        );
1061
1062        // Commit an empty write at the minimum timestamp so the catalog is always readable.
1063        let upper = {
1064            const EMPTY_UPDATES: &[((SourceData, ()), Timestamp, StorageDiff)] = &[];
1065            let upper = Antichain::from_elem(Timestamp::minimum());
1066            let next_upper = Timestamp::minimum().step_forward();
1067            match write_handle
1068                .compare_and_append(EMPTY_UPDATES, upper, Antichain::from_elem(next_upper))
1069                .await
1070                .expect("invalid usage")
1071            {
1072                Ok(()) => next_upper,
1073                Err(mismatch) => antichain_to_timestamp(mismatch.current),
1074            }
1075        };
1076
1077        let snapshot_start = Instant::now();
1078        info!("startup: envd serve: catalog init: snapshot beginning");
1079        let as_of = as_of(&read_handle, upper);
1080        let snapshot: Vec<_> = snapshot_binary(&mut read_handle, as_of, &metrics)
1081            .await
1082            .map(|StateUpdate { kind, ts, diff }| (kind, ts, diff))
1083            .collect();
1084        let listen = read_handle
1085            .listen(Antichain::from_elem(as_of))
1086            .await
1087            .expect("invalid usage");
1088        info!(
1089            "startup: envd serve: catalog init: snapshot complete in {:?}",
1090            snapshot_start.elapsed()
1091        );
1092
1093        let mut handle = UnopenedPersistCatalogState {
1094            // Unopened catalogs are always writeable until they're opened in an explicit mode.
1095            mode: Mode::Writable,
1096            since_handle,
1097            write_handle,
1098            listen,
1099            persist_client,
1100            shard_id: catalog_shard_id,
1101            // Initialize empty in-memory state.
1102            snapshot: Vec::new(),
1103            update_applier: UnopenedCatalogStateInner::new(),
1104            upper,
1105            fenceable_token: FenceableToken::new(deploy_generation),
1106            catalog_content_version: version,
1107            bootstrap_complete: false,
1108            metrics,
1109            size_at_last_consolidation: None,
1110            updates_applied: 0,
1111        };
1112        // If the snapshot is not consolidated, and we see multiple epoch values while applying the
1113        // updates, then we might accidentally fence ourselves out.
1114        soft_assert_no_log!(
1115            snapshot.iter().all(|(_, _, diff)| *diff == Diff::ONE),
1116            "snapshot should be consolidated: {snapshot:#?}"
1117        );
1118
1119        let apply_start = Instant::now();
1120        info!("startup: envd serve: catalog init: apply updates beginning");
1121        let updates = snapshot
1122            .into_iter()
1123            .map(|(kind, ts, diff)| StateUpdate { kind, ts, diff });
1124        handle.apply_updates_and_consolidate(updates)?;
1125        info!(
1126            "startup: envd serve: catalog init: apply updates complete in {:?}",
1127            apply_start.elapsed()
1128        );
1129
1130        // Validate that the binary version of the current process is not less than any binary
1131        // version that has written to the catalog.
1132        // This condition is only checked once, right here. If a new process comes along with a
1133        // higher version, it must fence this process out with one of the existing fencing
1134        // mechanisms.
1135        if let Some(found_version) = handle.get_catalog_content_version().await? {
1136            // Use cmp_precedence() to ignore build metadata per SemVer 2.0.0 spec
1137            if handle
1138                .catalog_content_version
1139                .cmp_precedence(&found_version)
1140                == std::cmp::Ordering::Less
1141            {
1142                return Err(DurableCatalogError::IncompatiblePersistVersion {
1143                    found_version,
1144                    catalog_version: handle.catalog_content_version,
1145                });
1146            }
1147        }
1148
1149        Ok(handle)
1150    }
1151
1152    #[mz_ore::instrument]
1153    async fn open_inner(
1154        mut self,
1155        mode: Mode,
1156        initial_ts: Timestamp,
1157        bootstrap_args: &BootstrapArgs,
1158    ) -> Result<Box<dyn DurableCatalogState>, CatalogError> {
1159        // It would be nice to use `initial_ts` here, but it comes from the system clock, not the
1160        // timestamp oracle.
1161        let mut commit_ts = self.upper;
1162        self.mode = mode;
1163
1164        // Validate the current deploy generation.
1165        match (&self.mode, &self.fenceable_token) {
1166            (_, FenceableToken::Unfenced { .. } | FenceableToken::Fenced { .. }) => {
1167                return Err(DurableCatalogError::Internal(
1168                    "catalog should not have fenced before opening".to_string(),
1169                )
1170                .into());
1171            }
1172            (
1173                Mode::Writable | Mode::Savepoint,
1174                FenceableToken::Initializing {
1175                    current_deploy_generation: None,
1176                    ..
1177                },
1178            ) => {
1179                return Err(DurableCatalogError::Internal(format!(
1180                    "cannot open in mode '{:?}' without a deploy generation",
1181                    self.mode,
1182                ))
1183                .into());
1184            }
1185            _ => {}
1186        }
1187
1188        let read_only = matches!(self.mode, Mode::Readonly);
1189
1190        // Fence out previous catalogs.
1191        loop {
1192            self.sync_to_current_upper().await?;
1193            commit_ts = max(commit_ts, self.upper);
1194            let (fence_updates, current_fenceable_token) = self
1195                .fenceable_token
1196                .generate_unfenced_token(self.mode)?
1197                .ok_or_else(|| {
1198                    DurableCatalogError::Internal(
1199                        "catalog should not have fenced before opening".to_string(),
1200                    )
1201                })?;
1202            debug!(
1203                ?self.upper,
1204                ?self.fenceable_token,
1205                ?current_fenceable_token,
1206                "fencing previous catalogs"
1207            );
1208            if matches!(self.mode, Mode::Writable) {
1209                match self
1210                    .compare_and_append(fence_updates.clone(), commit_ts)
1211                    .await
1212                {
1213                    Ok(upper) => {
1214                        commit_ts = upper;
1215                    }
1216                    Err(CompareAndAppendError::Fence(e)) => return Err(e.into()),
1217                    Err(e @ CompareAndAppendError::UpperMismatch { .. }) => {
1218                        warn!("catalog write failed due to upper mismatch, retrying: {e:?}");
1219                        continue;
1220                    }
1221                }
1222            }
1223            self.fenceable_token = current_fenceable_token;
1224            break;
1225        }
1226
1227        if matches!(self.mode, Mode::Writable) {
1228            // One-time migration: The catalog previously used `CONTROLLER_CRITICAL_SINCE` for its
1229            // since handle. Now it uses its own `CATALOG_CRITICAL_SINCE`, to free
1230            // `CONTROLLER_CRITICAL_SINCE` up for the storage controller. The catalog and
1231            // controller handles differ in the `Opaque` codec, so we need a migration.
1232            //
1233            // TODO: Remove this once we don't support upgrading from v26 anymore.
1234            let mut controller_handle = self
1235                .persist_client
1236                .open_critical_since::<SourceData, (), Timestamp, StorageDiff>(
1237                    self.shard_id,
1238                    PersistClient::CONTROLLER_CRITICAL_SINCE,
1239                    Opaque::encode(&i64::MIN),
1240                    Diagnostics {
1241                        shard_name: CATALOG_SHARD_NAME.to_string(),
1242                        handle_purpose: "durable catalog state critical since (migration)"
1243                            .to_string(),
1244                    },
1245                )
1246                .await
1247                .expect("invalid usage");
1248
1249            let since = controller_handle.since().clone();
1250            let res = controller_handle
1251                .compare_and_downgrade_since(
1252                    &Opaque::encode(&i64::MIN),
1253                    (&Opaque::encode(&PersistEpoch::default()), &since),
1254                )
1255                .await;
1256            match res {
1257                Ok(_) => info!("migrated Opaque of catalog since handle"),
1258                Err(_) => { /* critical since was already migrated */ }
1259            }
1260        }
1261
1262        let is_initialized = self.is_initialized_inner();
1263        if !matches!(self.mode, Mode::Writable) && !is_initialized {
1264            return Err(CatalogError::Durable(DurableCatalogError::NotWritable(
1265                format!(
1266                    "catalog tables do not exist; will not create in {:?} mode",
1267                    self.mode
1268                ),
1269            )));
1270        }
1271        soft_assert_ne_or_log!(self.upper, Timestamp::minimum());
1272
1273        // Audit log entries are served from `mz_internal.mz_catalog_raw` via
1274        // the `mz_audit_events` materialized view, so they do not need to live
1275        // in the in-memory catalog snapshot. Drop them here and only keep the
1276        // count for metrics.
1277        let (audit_logs, snapshot): (Vec<_>, Vec<_>) = self
1278            .snapshot
1279            .into_iter()
1280            .partition(|(update, _, _)| update.is_audit_log());
1281        self.snapshot = snapshot;
1282        let audit_log_count = audit_logs.iter().map(|(_, _, diff)| diff).sum::<Diff>();
1283        drop(audit_logs);
1284
1285        // Perform data migrations.
1286        if is_initialized && !read_only {
1287            commit_ts =
1288                upgrade(&mut self, commit_ts, bootstrap_args.force_catalog_migration).await?;
1289        }
1290
1291        debug!(
1292            ?is_initialized,
1293            ?self.upper,
1294            "initializing catalog state"
1295        );
1296        let mut catalog = PersistCatalogState {
1297            mode: self.mode,
1298            since_handle: self.since_handle,
1299            write_handle: self.write_handle,
1300            listen: self.listen,
1301            persist_client: self.persist_client,
1302            shard_id: self.shard_id,
1303            upper: self.upper,
1304            fenceable_token: self.fenceable_token,
1305            // Initialize empty in-memory state.
1306            snapshot: Vec::new(),
1307            update_applier: CatalogStateInner::new(),
1308            catalog_content_version: self.catalog_content_version,
1309            bootstrap_complete: false,
1310            metrics: self.metrics,
1311            size_at_last_consolidation: None,
1312            updates_applied: 0,
1313        };
1314        catalog.metrics.collection_entries.reset();
1315        // Normally, `collection_entries` is updated in `apply_updates`. The audit log updates skip
1316        // over that function so we manually update it here.
1317        catalog
1318            .metrics
1319            .collection_entries
1320            .with_label_values(&[&CollectionType::AuditLog.to_string()])
1321            .add(audit_log_count.into_inner());
1322        let updates = self.snapshot.into_iter().map(|(kind, ts, diff)| {
1323            let kind = TryIntoStateUpdateKind::try_into(kind).expect("kind decoding error");
1324            StateUpdate { kind, ts, diff }
1325        });
1326        catalog.apply_updates_and_consolidate(updates)?;
1327
1328        let catalog_content_version = catalog.catalog_content_version.to_string();
1329        let txn = if is_initialized {
1330            let mut txn = catalog.transaction_unchecked().await?;
1331
1332            // Ad-hoc migration: Initialize the `migration_version` expected by adapter to be
1333            // present in existing catalogs.
1334            //
1335            // Note: Need to exclude read-only catalog mode here, because in that mode all
1336            // transactions are expected to be no-ops.
1337            // TODO: remove this once we only support upgrades from version >= 0.164
1338            if txn.get_setting("migration_version".into()).is_none() && mode != Mode::Readonly {
1339                let old_version = txn.get_catalog_content_version();
1340                txn.set_setting("migration_version".into(), old_version.map(Into::into))?;
1341            }
1342
1343            // Opening the catalog with write intent fences out every previous
1344            // catalog owner, so all sessions served by previous owners are
1345            // dead. Reclaim the temporary items they owned here, before
1346            // anything else reads the catalog.
1347            //
1348            // NOTE: This only reclaims on the fence, which covers a
1349            // single-writer world where every crash is followed by some
1350            // process's writable open. Once several serving envds run
1351            // concurrently, a peer crash triggers no fence here, so
1352            // reclaiming its sessions' items needs the durable
1353            // envd-heartbeat mechanism described in the durable temporary
1354            // objects design doc.
1355            if mode != Mode::Readonly {
1356                txn.remove_ephemeral_items();
1357            }
1358
1359            txn.set_catalog_content_version(catalog_content_version)?;
1360            txn
1361        } else {
1362            soft_assert_eq_no_log!(
1363                catalog
1364                    .snapshot
1365                    .iter()
1366                    .filter(|(kind, _, _)| !matches!(kind, StateUpdateKind::FenceToken(_)))
1367                    .count(),
1368                0,
1369                "trace should not contain any updates for an uninitialized catalog: {:#?}",
1370                catalog.snapshot
1371            );
1372
1373            let mut txn = catalog.transaction_unchecked().await?;
1374            initialize::initialize(
1375                &mut txn,
1376                bootstrap_args,
1377                initial_ts.into(),
1378                catalog_content_version,
1379            )
1380            .await?;
1381            txn
1382        };
1383
1384        if read_only {
1385            let (txn_batch, _) = txn.into_parts()?;
1386            // The upper here doesn't matter because we are only applying the updates in memory.
1387            let updates = StateUpdate::from_txn_batch_ts(txn_batch, catalog.upper);
1388            catalog.apply_updates_and_consolidate(updates)?;
1389        } else {
1390            txn.commit_internal(commit_ts).await?;
1391        }
1392
1393        if matches!(catalog.mode, Mode::Writable) {
1394            let write_handle = catalog
1395                .persist_client
1396                .open_writer::<SourceData, (), Timestamp, i64>(
1397                    catalog.write_handle.shard_id(),
1398                    Arc::new(persist_desc()),
1399                    Arc::new(UnitSchema::default()),
1400                    Diagnostics {
1401                        shard_name: CATALOG_SHARD_NAME.to_string(),
1402                        handle_purpose: "compact catalog".to_string(),
1403                    },
1404                )
1405                .await
1406                .expect("invalid usage");
1407            let fuel = CATALOG_FORCE_COMPACTION_FUEL.handle(catalog.persist_client.dyncfgs());
1408            let wait = CATALOG_FORCE_COMPACTION_WAIT.handle(catalog.persist_client.dyncfgs());
1409            // We're going to gradually turn this on via dyncfgs. Run it in a task so that it
1410            // doesn't block startup.
1411            let _task = mz_ore::task::spawn(|| "catalog::force_shard_compaction", async move {
1412                let () =
1413                    mz_persist_client::cli::admin::dangerous_force_compaction_and_break_pushdown(
1414                        &write_handle,
1415                        || fuel.get(),
1416                        || wait.get(),
1417                    )
1418                    .await;
1419            });
1420        }
1421
1422        Ok(Box::new(catalog))
1423    }
1424
1425    /// Reports if the catalog state has been initialized.
1426    ///
1427    /// NOTE: This is the answer as of the last call to [`PersistHandle::sync`] or [`PersistHandle::sync_to_current_upper`],
1428    /// not necessarily what is currently in persist.
1429    #[mz_ore::instrument]
1430    fn is_initialized_inner(&self) -> bool {
1431        !self.update_applier.configs.is_empty()
1432    }
1433
1434    /// Get the current value of config `key`.
1435    ///
1436    /// Some configs need to be read before the catalog is opened for bootstrapping.
1437    #[mz_ore::instrument]
1438    async fn get_current_config(&mut self, key: &str) -> Result<Option<u64>, DurableCatalogError> {
1439        self.sync_to_current_upper().await?;
1440        Ok(self.update_applier.configs.get(key).cloned())
1441    }
1442
1443    /// Get the user version of this instance.
1444    ///
1445    /// The user version is used to determine if a migration is needed.
1446    #[mz_ore::instrument]
1447    pub(crate) async fn get_user_version(&mut self) -> Result<Option<u64>, DurableCatalogError> {
1448        self.get_current_config(USER_VERSION_KEY).await
1449    }
1450
1451    /// Get the current value of setting `name`.
1452    ///
1453    /// Some settings need to be read before the catalog is opened for bootstrapping.
1454    #[mz_ore::instrument]
1455    async fn get_current_setting(
1456        &mut self,
1457        name: &str,
1458    ) -> Result<Option<String>, DurableCatalogError> {
1459        self.sync_to_current_upper().await?;
1460        Ok(self.update_applier.settings.get(name).cloned())
1461    }
1462
1463    /// Get the catalog content version.
1464    ///
1465    /// The catalog content version is the semantic version of the most recent binary that wrote to
1466    /// the catalog.
1467    #[mz_ore::instrument]
1468    async fn get_catalog_content_version(
1469        &mut self,
1470    ) -> Result<Option<semver::Version>, DurableCatalogError> {
1471        let version = self
1472            .get_current_setting(CATALOG_CONTENT_VERSION_KEY)
1473            .await?;
1474        let version = version.map(|version| version.parse().expect("invalid version persisted"));
1475        Ok(version)
1476    }
1477}
1478
1479#[async_trait]
1480impl OpenableDurableCatalogState for UnopenedPersistCatalogState {
1481    #[mz_ore::instrument]
1482    async fn open_savepoint(
1483        mut self: Box<Self>,
1484        initial_ts: Timestamp,
1485        bootstrap_args: &BootstrapArgs,
1486    ) -> Result<Box<dyn DurableCatalogState>, CatalogError> {
1487        self.open_inner(Mode::Savepoint, initial_ts, bootstrap_args)
1488            .boxed()
1489            .await
1490    }
1491
1492    #[mz_ore::instrument]
1493    async fn open_read_only(
1494        mut self: Box<Self>,
1495        bootstrap_args: &BootstrapArgs,
1496    ) -> Result<Box<dyn DurableCatalogState>, CatalogError> {
1497        self.open_inner(Mode::Readonly, EpochMillis::MIN.into(), bootstrap_args)
1498            .boxed()
1499            .await
1500    }
1501
1502    #[mz_ore::instrument]
1503    async fn open(
1504        mut self: Box<Self>,
1505        initial_ts: Timestamp,
1506        bootstrap_args: &BootstrapArgs,
1507    ) -> Result<Box<dyn DurableCatalogState>, CatalogError> {
1508        self.open_inner(Mode::Writable, initial_ts, bootstrap_args)
1509            .boxed()
1510            .await
1511    }
1512
1513    #[mz_ore::instrument(level = "debug")]
1514    async fn open_debug(mut self: Box<Self>) -> Result<DebugCatalogState, CatalogError> {
1515        Ok(DebugCatalogState(*self))
1516    }
1517
1518    #[mz_ore::instrument]
1519    async fn is_initialized(&mut self) -> Result<bool, CatalogError> {
1520        self.sync_to_current_upper().await?;
1521        Ok(self.is_initialized_inner())
1522    }
1523
1524    #[mz_ore::instrument]
1525    async fn epoch(&mut self) -> Result<Epoch, CatalogError> {
1526        self.sync_to_current_upper().await?;
1527        self.fenceable_token
1528            .validate()?
1529            .map(|token| token.epoch)
1530            .ok_or(CatalogError::Durable(DurableCatalogError::Uninitialized))
1531    }
1532
1533    #[mz_ore::instrument]
1534    async fn get_deployment_generation(&mut self) -> Result<u64, CatalogError> {
1535        self.sync_to_current_upper().await?;
1536        self.fenceable_token
1537            .token()
1538            .map(|token| token.deploy_generation)
1539            .ok_or(CatalogError::Durable(DurableCatalogError::Uninitialized))
1540    }
1541
1542    #[mz_ore::instrument(level = "debug")]
1543    async fn get_0dt_deployment_max_wait(&mut self) -> Result<Option<Duration>, CatalogError> {
1544        let value = self
1545            .get_current_config(WITH_0DT_DEPLOYMENT_MAX_WAIT)
1546            .await?;
1547        match value {
1548            None => Ok(None),
1549            Some(millis) => Ok(Some(Duration::from_millis(millis))),
1550        }
1551    }
1552
1553    #[mz_ore::instrument(level = "debug")]
1554    async fn get_0dt_deployment_ddl_check_interval(
1555        &mut self,
1556    ) -> Result<Option<Duration>, CatalogError> {
1557        let value = self
1558            .get_current_config(WITH_0DT_DEPLOYMENT_DDL_CHECK_INTERVAL)
1559            .await?;
1560        match value {
1561            None => Ok(None),
1562            Some(millis) => Ok(Some(Duration::from_millis(millis))),
1563        }
1564    }
1565
1566    #[mz_ore::instrument(level = "debug")]
1567    async fn get_enable_0dt_deployment_panic_after_timeout(
1568        &mut self,
1569    ) -> Result<Option<bool>, CatalogError> {
1570        let value = self
1571            .get_current_config(ENABLE_0DT_DEPLOYMENT_PANIC_AFTER_TIMEOUT)
1572            .await?;
1573        match value {
1574            None => Ok(None),
1575            Some(0) => Ok(Some(false)),
1576            Some(1) => Ok(Some(true)),
1577            Some(v) => Err(
1578                DurableCatalogError::from(TryFromProtoError::UnknownEnumVariant(format!(
1579                    "{v} is not a valid boolean value"
1580                )))
1581                .into(),
1582            ),
1583        }
1584    }
1585
1586    #[mz_ore::instrument]
1587    async fn has_system_config_synced_once(&mut self) -> Result<bool, DurableCatalogError> {
1588        self.get_current_config(SYSTEM_CONFIG_SYNCED_KEY)
1589            .await
1590            .map(|value| value.map(|value| value > 0).unwrap_or(false))
1591    }
1592
1593    #[mz_ore::instrument]
1594    async fn trace_unconsolidated(&mut self) -> Result<Trace, CatalogError> {
1595        self.sync_to_current_upper().await?;
1596        if self.is_initialized_inner() {
1597            let snapshot = self.snapshot_unconsolidated().await;
1598            Ok(Trace::from_snapshot(snapshot))
1599        } else {
1600            Err(CatalogError::Durable(DurableCatalogError::Uninitialized))
1601        }
1602    }
1603
1604    #[mz_ore::instrument]
1605    async fn trace_consolidated(&mut self) -> Result<Trace, CatalogError> {
1606        self.sync_to_current_upper().await?;
1607        if self.is_initialized_inner() {
1608            let snapshot = self.current_snapshot().await?;
1609            Ok(Trace::from_snapshot(snapshot))
1610        } else {
1611            Err(CatalogError::Durable(DurableCatalogError::Uninitialized))
1612        }
1613    }
1614
1615    #[mz_ore::instrument(level = "debug")]
1616    async fn expire(self: Box<Self>) {
1617        self.expire().await
1618    }
1619}
1620
1621/// Applies updates for an opened catalog.
1622#[derive(Debug)]
1623struct CatalogStateInner {
1624    /// A trace of all catalog updates that can be consumed by some higher layer.
1625    updates: VecDeque<memory::objects::StateUpdate>,
1626}
1627
1628impl CatalogStateInner {
1629    fn new() -> CatalogStateInner {
1630        CatalogStateInner {
1631            updates: VecDeque::new(),
1632        }
1633    }
1634}
1635
1636impl ApplyUpdate<StateUpdateKind> for CatalogStateInner {
1637    fn apply_update(
1638        &mut self,
1639        update: StateUpdate<StateUpdateKind>,
1640        current_fence_token: &mut FenceableToken,
1641        metrics: &Arc<Metrics>,
1642    ) -> Result<Option<StateUpdate<StateUpdateKind>>, FenceError> {
1643        if let Some(collection_type) = update.kind.collection_type() {
1644            metrics
1645                .collection_entries
1646                .with_label_values(&[&collection_type.to_string()])
1647                .add(update.diff.into_inner());
1648        }
1649
1650        {
1651            let update: Option<memory::objects::StateUpdate> = (&update)
1652                .try_into()
1653                .expect("invalid persisted update: {update:#?}");
1654            if let Some(update) = update {
1655                self.updates.push_back(update);
1656            }
1657        }
1658
1659        match (update.kind, update.diff) {
1660            (StateUpdateKind::AuditLog(_, ()), _) => Ok(None),
1661            // Nothing to due for fence token retractions but wait for the next insertion.
1662            (StateUpdateKind::FenceToken(_), Diff::MINUS_ONE) => Ok(None),
1663            (StateUpdateKind::FenceToken(token), Diff::ONE) => {
1664                current_fence_token.maybe_fence(token)?;
1665                Ok(None)
1666            }
1667            (kind, diff) => Ok(Some(StateUpdate {
1668                kind,
1669                ts: update.ts,
1670                diff,
1671            })),
1672        }
1673    }
1674}
1675
1676/// A durable store of the catalog state using Persist as an implementation. The durable store can
1677/// serve any catalog data and transactionally modify catalog data.
1678///
1679/// Production users should call [`Self::expire`] before dropping a [`PersistCatalogState`]
1680/// so that it can expire its leases. If/when rust gets AsyncDrop, this will be done automatically.
1681type PersistCatalogState = PersistHandle<StateUpdateKind, CatalogStateInner>;
1682
1683impl PersistHandle<StateUpdateKind, CatalogStateInner> {
1684    /// Creates a transaction without validating pending catalog updates.
1685    async fn transaction_unchecked(&mut self) -> Result<Transaction<'_>, CatalogError> {
1686        self.metrics.transactions_started.inc();
1687        let snapshot = self.snapshot().await?;
1688        let commit_ts = self.upper;
1689        Transaction::new(self, snapshot, commit_ts)
1690    }
1691}
1692
1693#[async_trait]
1694impl ReadOnlyDurableCatalogState for PersistCatalogState {
1695    fn epoch(&self) -> Epoch {
1696        self.fenceable_token
1697            .token()
1698            .expect("opened catalog state must have an epoch")
1699            .epoch
1700    }
1701
1702    fn metrics(&self) -> &Metrics {
1703        &self.metrics
1704    }
1705
1706    #[mz_ore::instrument(level = "debug")]
1707    async fn expire(self: Box<Self>) {
1708        self.expire().await
1709    }
1710
1711    fn is_bootstrap_complete(&self) -> bool {
1712        self.bootstrap_complete
1713    }
1714
1715    async fn get_audit_logs(&mut self) -> Result<Vec<VersionedEvent>, CatalogError> {
1716        self.sync_to_current_upper().await?;
1717        let audit_logs: Vec<_> = self
1718            .persist_snapshot()
1719            .await
1720            .filter_map(
1721                |StateUpdate {
1722                     kind,
1723                     ts: _,
1724                     diff: _,
1725                 }| match kind {
1726                    StateUpdateKind::AuditLog(key, ()) => Some(key),
1727                    _ => None,
1728                },
1729            )
1730            .collect();
1731        let mut audit_logs: Vec<_> = audit_logs
1732            .into_iter()
1733            .map(RustType::from_proto)
1734            .map_ok(|key: AuditLogKey| key.event)
1735            .collect::<Result<_, _>>()?;
1736        audit_logs.sort_by(|a, b| a.sortable_id().cmp(&b.sortable_id()));
1737        Ok(audit_logs)
1738    }
1739
1740    #[mz_ore::instrument(level = "debug")]
1741    async fn get_next_id(&mut self, id_type: &str) -> Result<u64, CatalogError> {
1742        self.with_trace(|trace| {
1743            Ok(trace
1744                .into_iter()
1745                .rev()
1746                .filter_map(|(kind, _, _)| match kind {
1747                    StateUpdateKind::IdAllocator(key, value) if key.name == id_type => {
1748                        Some(value.next_id)
1749                    }
1750                    _ => None,
1751                })
1752                .next()
1753                .expect("must exist"))
1754        })
1755        .await
1756    }
1757
1758    #[mz_ore::instrument(level = "debug")]
1759    async fn get_deployment_generation(&mut self) -> Result<u64, CatalogError> {
1760        self.sync_to_current_upper().await?;
1761        Ok(self
1762            .fenceable_token
1763            .token()
1764            .expect("opened catalogs must have a token")
1765            .deploy_generation)
1766    }
1767
1768    #[mz_ore::instrument(level = "debug")]
1769    async fn snapshot(&mut self) -> Result<Snapshot, CatalogError> {
1770        self.with_snapshot(Ok).await
1771    }
1772
1773    #[mz_ore::instrument(level = "debug")]
1774    async fn sync_to_current_updates(
1775        &mut self,
1776    ) -> Result<Vec<memory::objects::StateUpdate>, CatalogError> {
1777        let upper = self.current_upper().await;
1778        self.sync_updates(upper).await
1779    }
1780
1781    #[mz_ore::instrument(level = "debug")]
1782    async fn sync_updates(
1783        &mut self,
1784        target_upper: mz_repr::Timestamp,
1785    ) -> Result<Vec<memory::objects::StateUpdate>, CatalogError> {
1786        self.sync(target_upper).await?;
1787        let mut updates = Vec::new();
1788        while let Some(update) = self.update_applier.updates.front() {
1789            if update.ts >= target_upper {
1790                break;
1791            }
1792
1793            let update = self
1794                .update_applier
1795                .updates
1796                .pop_front()
1797                .expect("peeked above");
1798            updates.push(update);
1799        }
1800        Ok(updates)
1801    }
1802
1803    #[mz_ore::instrument(level = "debug")]
1804    async fn ensure_not_out_of_sync(
1805        &mut self,
1806        target_upper: Timestamp,
1807    ) -> Result<(), CatalogError> {
1808        self.sync(target_upper).await?;
1809        let update_count = self
1810            .update_applier
1811            .updates
1812            .iter()
1813            .take_while(|update| update.ts < target_upper)
1814            .count();
1815        if update_count == 0 {
1816            Ok(())
1817        } else {
1818            Err(DurableCatalogError::CatalogOutOfSync {
1819                update_count,
1820                upper: target_upper,
1821            }
1822            .into())
1823        }
1824    }
1825
1826    async fn current_upper(&mut self) -> Timestamp {
1827        self.current_upper().await
1828    }
1829}
1830
1831#[async_trait]
1832#[allow(mismatched_lifetime_syntaxes)]
1833impl DurableCatalogState for PersistCatalogState {
1834    fn is_read_only(&self) -> bool {
1835        matches!(self.mode, Mode::Readonly)
1836    }
1837
1838    fn is_savepoint(&self) -> bool {
1839        matches!(self.mode, Mode::Savepoint)
1840    }
1841
1842    async fn mark_bootstrap_complete(&mut self) {
1843        self.bootstrap_complete = true;
1844        if matches!(self.mode, Mode::Writable) {
1845            self.since_handle
1846                .upgrade_version()
1847                .await
1848                .expect("invalid usage")
1849        }
1850    }
1851
1852    #[mz_ore::instrument(level = "debug")]
1853    async fn transaction(&mut self) -> Result<Transaction, CatalogError> {
1854        let mut txn = self.transaction_unchecked().await?;
1855        txn.ensure_not_out_of_sync().await?;
1856        Ok(txn)
1857    }
1858
1859    fn transaction_from_snapshot(
1860        &mut self,
1861        snapshot: Snapshot,
1862    ) -> Result<DryRunTransaction, CatalogError> {
1863        let commit_ts = self.upper;
1864        Transaction::new(self, snapshot, commit_ts).map(DryRunTransaction::new)
1865    }
1866
1867    #[mz_ore::instrument(level = "debug")]
1868    async fn allocate_id(
1869        &mut self,
1870        id_type: &str,
1871        amount: u64,
1872        commit_ts: Timestamp,
1873    ) -> Result<Vec<u64>, CatalogError> {
1874        let start = Instant::now();
1875        if amount == 0 {
1876            return Ok(Vec::new());
1877        }
1878        let mut txn = self.transaction_unchecked().await?;
1879        let ids = txn.get_and_increment_id_by(id_type.to_string(), amount)?;
1880        txn.commit_internal(commit_ts).await?;
1881        self.metrics
1882            .allocate_id_seconds
1883            .observe(start.elapsed().as_secs_f64());
1884        Ok(ids)
1885    }
1886
1887    #[mz_ore::instrument(level = "debug")]
1888    async fn commit_transaction(
1889        &mut self,
1890        txn_batch: TransactionBatch,
1891        commit_ts: Timestamp,
1892    ) -> Result<Timestamp, CatalogError> {
1893        async fn commit_transaction_inner(
1894            catalog: &mut PersistCatalogState,
1895            txn_batch: TransactionBatch,
1896            commit_ts: Timestamp,
1897        ) -> Result<Timestamp, CatalogError> {
1898            // If the transaction is empty then we don't error, even in read-only mode.
1899            // This is mostly for legacy reasons (i.e. with enough elbow grease this
1900            // behavior can be changed without breaking any fundamental assumptions).
1901            if catalog.mode == Mode::Readonly {
1902                let updates: Vec<_> = StateUpdate::from_txn_batch(txn_batch).collect();
1903                if !updates.is_empty() {
1904                    let collection_types: Vec<_> = updates
1905                        .iter()
1906                        .filter_map(|u| u.0.collection_type())
1907                        .collect();
1908                    return Err(DurableCatalogError::NotWritable(format!(
1909                        "cannot commit a transaction in a read-only catalog: \
1910                         {} updates across collections: {collection_types:?}",
1911                        updates.len(),
1912                    ))
1913                    .into());
1914                }
1915                return Ok(catalog.upper);
1916            }
1917
1918            // The handle is mutex-protected from transaction creation through commit, so only a
1919            // local programming error can change its cached upper here.
1920            assert_eq!(
1921                catalog.upper, txn_batch.upper,
1922                "the handle was mutated mid-transaction"
1923            );
1924
1925            let updates: Vec<_> = StateUpdate::from_txn_batch(txn_batch).collect();
1926            debug!("committing updates: {updates:?}");
1927
1928            // Empty upper progress does not invalidate the transaction.
1929            let mut commit_ts = max(commit_ts, catalog.upper);
1930
1931            let next_upper = match catalog.mode {
1932                Mode::Writable => loop {
1933                    let updates_applied_before = catalog.updates_applied;
1934                    match catalog.compare_and_append(updates.clone(), commit_ts).await {
1935                        Ok(next_upper) => break next_upper,
1936                        Err(CompareAndAppendError::Fence(e)) => return Err(e.into()),
1937                        Err(CompareAndAppendError::UpperMismatch { actual_upper, .. }) => {
1938                            // The mismatch synchronized the handle. Retry only if it applied no
1939                            // content.
1940                            catalog
1941                                .classify_upper_mismatch(updates_applied_before, actual_upper)?;
1942                            commit_ts = max(commit_ts, catalog.upper);
1943                        }
1944                    }
1945                },
1946                Mode::Savepoint => {
1947                    let updates = updates.into_iter().map(|(kind, diff)| StateUpdate {
1948                        kind,
1949                        ts: commit_ts,
1950                        diff,
1951                    });
1952                    catalog.apply_updates_and_consolidate(updates)?;
1953                    catalog.upper = commit_ts.step_forward();
1954                    catalog.upper
1955                }
1956                Mode::Readonly => unreachable!("handled above"),
1957            };
1958
1959            Ok(next_upper)
1960        }
1961        self.metrics.transaction_commits.inc();
1962        let histogram = self.metrics.transaction_commit_latency_seconds.clone();
1963        commit_transaction_inner(self, txn_batch, commit_ts)
1964            .wall_time()
1965            .observe(histogram)
1966            .await
1967    }
1968
1969    #[mz_ore::instrument(level = "debug")]
1970    async fn advance_upper(&mut self, new_upper: Timestamp) -> Result<(), CatalogError> {
1971        loop {
1972            if self.upper >= new_upper {
1973                // This does not consult Persist. It only revalidates a fence already cached by
1974                // this handle, since a sync can advance `upper` while recording the fence.
1975                self.fenceable_token.validate()?;
1976                return Ok(());
1977            }
1978
1979            match self.mode {
1980                Mode::Writable => {}
1981                Mode::Savepoint => {
1982                    self.upper = new_upper;
1983                    return Ok(());
1984                }
1985                Mode::Readonly => {
1986                    return Err(DurableCatalogError::NotWritable(
1987                        "cannot advance upper of a read-only catalog".into(),
1988                    )
1989                    .into());
1990                }
1991            }
1992
1993            let updates_applied_before = self.updates_applied;
1994            match self.compare_and_append_inner([], new_upper).await {
1995                Ok(()) => {
1996                    self.upper = new_upper;
1997                    // No sync needed since no data was written.
1998                    return Ok(());
1999                }
2000                Err(CompareAndAppendError::Fence(e)) => return Err(e.into()),
2001                Err(CompareAndAppendError::UpperMismatch { actual_upper, .. }) => {
2002                    // The mismatch synchronized the handle. Retry only if it applied no content.
2003                    self.classify_upper_mismatch(updates_applied_before, actual_upper)?;
2004                }
2005            }
2006        }
2007    }
2008
2009    fn shard_id(&self) -> ShardId {
2010        self.shard_id
2011    }
2012}
2013
2014/// Deterministically generate a shard ID for the given `organization_id` and `seed`.
2015pub fn shard_id(organization_id: Uuid, seed: usize) -> ShardId {
2016    let hash = sha2::Sha256::digest(format!("{organization_id}{seed}")).to_vec();
2017    soft_assert_eq_or_log!(hash.len(), 32, "SHA256 returns 32 bytes (256 bits)");
2018    let uuid = Uuid::from_slice(&hash[0..16]).expect("from_slice accepts exactly 16 bytes");
2019    ShardId::from_str(&format!("s{uuid}")).expect("known to be valid")
2020}
2021
2022/// Generates a timestamp for reading from `read_handle` that is as fresh as possible, given
2023/// `upper`.
2024fn as_of(
2025    read_handle: &ReadHandle<SourceData, (), Timestamp, StorageDiff>,
2026    upper: Timestamp,
2027) -> Timestamp {
2028    let since = read_handle.since().clone();
2029    let mut as_of = upper.checked_sub(1).unwrap_or_else(|| {
2030        panic!("catalog persist shard should be initialize, found upper: {upper:?}")
2031    });
2032    // We only downgrade the since after writing, and we always set the since to one less than the
2033    // upper.
2034    soft_assert_or_log!(
2035        since.less_equal(&as_of),
2036        "since={since:?}, as_of={as_of:?}; since must be less than or equal to as_of"
2037    );
2038    // This should be a no-op if the assert above passes, however if it doesn't then we'd like to
2039    // continue with a correct timestamp instead of entering a panic loop.
2040    as_of.advance_by(since.borrow());
2041    as_of
2042}
2043
2044/// Fetch the persist version of the catalog shard, if one exists. A version will not
2045/// exist if we are creating a brand-new environment.
2046async fn fetch_catalog_shard_version(
2047    persist_client: &PersistClient,
2048    catalog_shard_id: ShardId,
2049) -> Option<semver::Version> {
2050    let shard_state = persist_client
2051        .inspect_shard::<Timestamp>(&catalog_shard_id)
2052        .await
2053        .ok()?;
2054    let json_state = serde_json::to_value(shard_state).expect("state serialization error");
2055    let json_version = json_state
2056        .get("applier_version")
2057        .cloned()
2058        .expect("missing applier_version");
2059    let version = serde_json::from_value(json_version).expect("version deserialization error");
2060    Some(version)
2061}
2062
2063/// Generates an iterator of [`StateUpdate`] that contain all updates to the catalog
2064/// state up to, and including, `as_of`.
2065///
2066/// The output is consolidated and sorted by timestamp in ascending order.
2067#[mz_ore::instrument(level = "debug")]
2068async fn snapshot_binary(
2069    read_handle: &mut ReadHandle<SourceData, (), Timestamp, StorageDiff>,
2070    as_of: Timestamp,
2071    metrics: &Arc<Metrics>,
2072) -> impl Iterator<Item = StateUpdate<StateUpdateKindJson>> + DoubleEndedIterator + use<> {
2073    metrics.snapshots_taken.inc();
2074    let histogram = metrics.snapshot_latency_seconds.clone();
2075    snapshot_binary_inner(read_handle, as_of)
2076        .wall_time()
2077        .observe(histogram)
2078        .await
2079}
2080
2081/// Generates an iterator of [`StateUpdate`] that contain all updates to the catalog
2082/// state up to, and including, `as_of`.
2083///
2084/// The output is consolidated and sorted by timestamp in ascending order.
2085#[mz_ore::instrument(level = "debug")]
2086async fn snapshot_binary_inner(
2087    read_handle: &mut ReadHandle<SourceData, (), Timestamp, StorageDiff>,
2088    as_of: Timestamp,
2089) -> impl Iterator<Item = StateUpdate<StateUpdateKindJson>> + DoubleEndedIterator + use<> {
2090    let snapshot = read_handle
2091        .snapshot_and_fetch(Antichain::from_elem(as_of))
2092        .await
2093        .expect("we have advanced the restart_as_of by the since");
2094    soft_assert_no_log!(
2095        snapshot.iter().all(|(_, _, diff)| *diff == 1),
2096        "snapshot_and_fetch guarantees a consolidated result: {snapshot:#?}"
2097    );
2098    snapshot
2099        .into_iter()
2100        .map(Into::<StateUpdate<StateUpdateKindJson>>::into)
2101        .sorted_by(|a, b| Ord::cmp(&b.ts, &a.ts))
2102}
2103
2104/// Convert an [`Antichain<Timestamp>`] to a [`Timestamp`].
2105///
2106/// The correctness of this function relies on [`Timestamp`] being totally ordered and never
2107/// finalizing the catalog shard.
2108pub(crate) fn antichain_to_timestamp(antichain: Antichain<Timestamp>) -> Timestamp {
2109    antichain
2110        .into_option()
2111        .expect("we use a totally ordered time and never finalize the shard")
2112}
2113
2114// Debug methods used by the catalog-debug tool.
2115
2116impl Trace {
2117    /// Generates a [`Trace`] from snapshot.
2118    fn from_snapshot(snapshot: impl IntoIterator<Item = StateUpdate>) -> Trace {
2119        let mut trace = Trace::new();
2120        for StateUpdate { kind, ts, diff } in snapshot {
2121            match kind {
2122                StateUpdateKind::AuditLog(k, v) => trace.audit_log.values.push(((k, v), ts, diff)),
2123                StateUpdateKind::Cluster(k, v) => trace.clusters.values.push(((k, v), ts, diff)),
2124                StateUpdateKind::ClusterReplica(k, v) => {
2125                    trace.cluster_replicas.values.push(((k, v), ts, diff))
2126                }
2127                StateUpdateKind::ClusterReplicaSize(k, v) => {
2128                    trace.cluster_replica_sizes.values.push(((k, v), ts, diff))
2129                }
2130                StateUpdateKind::Comment(k, v) => trace.comments.values.push(((k, v), ts, diff)),
2131                StateUpdateKind::IndexColumns(k, v) => {
2132                    trace.index_columns.values.push(((k, v), ts, diff))
2133                }
2134                StateUpdateKind::ItemColumns(k, v) => {
2135                    trace.item_columns.values.push(((k, v), ts, diff))
2136                }
2137                StateUpdateKind::Config(k, v) => trace.configs.values.push(((k, v), ts, diff)),
2138                StateUpdateKind::Database(k, v) => trace.databases.values.push(((k, v), ts, diff)),
2139                StateUpdateKind::DefaultPrivilege(k, v) => {
2140                    trace.default_privileges.values.push(((k, v), ts, diff))
2141                }
2142                StateUpdateKind::FenceToken(_) => {
2143                    // Fence token not included in trace.
2144                }
2145                StateUpdateKind::IdAllocator(k, v) => {
2146                    trace.id_allocator.values.push(((k, v), ts, diff))
2147                }
2148                StateUpdateKind::IntrospectionSourceIndex(k, v) => {
2149                    trace.introspection_sources.values.push(((k, v), ts, diff))
2150                }
2151                StateUpdateKind::Item(k, v) => trace.items.values.push(((k, v), ts, diff)),
2152                StateUpdateKind::NetworkPolicy(k, v) => {
2153                    trace.network_policies.values.push(((k, v), ts, diff))
2154                }
2155                StateUpdateKind::QueryPolicy(k, v) => {
2156                    trace.query_policies.values.push(((k, v), ts, diff))
2157                }
2158                StateUpdateKind::Role(k, v) => trace.roles.values.push(((k, v), ts, diff)),
2159                StateUpdateKind::Schema(k, v) => trace.schemas.values.push(((k, v), ts, diff)),
2160                StateUpdateKind::Setting(k, v) => trace.settings.values.push(((k, v), ts, diff)),
2161                StateUpdateKind::SourceReferences(k, v) => {
2162                    trace.source_references.values.push(((k, v), ts, diff))
2163                }
2164                StateUpdateKind::SystemConfiguration(k, v) => {
2165                    trace.system_configurations.values.push(((k, v), ts, diff))
2166                }
2167                StateUpdateKind::ClusterSystemConfiguration(k, v) => trace
2168                    .cluster_system_configurations
2169                    .values
2170                    .push(((k, v), ts, diff)),
2171                StateUpdateKind::ReplicaSystemConfiguration(k, v) => trace
2172                    .replica_system_configurations
2173                    .values
2174                    .push(((k, v), ts, diff)),
2175                StateUpdateKind::SystemObjectMapping(k, v) => {
2176                    trace.system_object_mappings.values.push(((k, v), ts, diff))
2177                }
2178                StateUpdateKind::SystemPrivilege(k, v) => {
2179                    trace.system_privileges.values.push(((k, v), ts, diff))
2180                }
2181                StateUpdateKind::StorageCollectionMetadata(k, v) => trace
2182                    .storage_collection_metadata
2183                    .values
2184                    .push(((k, v), ts, diff)),
2185                StateUpdateKind::UnfinalizedShard(k, ()) => {
2186                    trace.unfinalized_shards.values.push(((k, ()), ts, diff))
2187                }
2188                StateUpdateKind::TxnWalShard((), v) => {
2189                    trace.txn_wal_shard.values.push((((), v), ts, diff))
2190                }
2191                StateUpdateKind::RoleAuth(k, v) => trace.role_auth.values.push(((k, v), ts, diff)),
2192            }
2193        }
2194        trace
2195    }
2196}
2197
2198impl UnopenedPersistCatalogState {
2199    /// Manually update value of `key` in collection `T` to `value`.
2200    #[mz_ore::instrument]
2201    pub(crate) async fn debug_edit<T: Collection>(
2202        &mut self,
2203        key: T::Key,
2204        value: T::Value,
2205    ) -> Result<Option<T::Value>, CatalogError>
2206    where
2207        T::Key: PartialEq + Eq + Debug + Clone,
2208        T::Value: Debug + Clone,
2209    {
2210        let prev_value = loop {
2211            let key = key.clone();
2212            let value = value.clone();
2213            let snapshot = self.current_snapshot().await?;
2214            let trace = Trace::from_snapshot(snapshot);
2215            let collection_trace = T::collection_trace(trace);
2216            let prev_values: Vec<_> = collection_trace
2217                .values
2218                .into_iter()
2219                .filter(|((k, _), _, diff)| {
2220                    soft_assert_eq_or_log!(*diff, Diff::ONE, "trace is consolidated");
2221                    &key == k
2222                })
2223                .collect();
2224
2225            let prev_value = match &prev_values[..] {
2226                [] => None,
2227                [((_, v), _, _)] => Some(v.clone()),
2228                prev_values => panic!("multiple values found for key {key:?}: {prev_values:?}"),
2229            };
2230
2231            let mut updates: Vec<_> = prev_values
2232                .into_iter()
2233                .map(|((k, v), _, _)| (T::update(k, v), Diff::MINUS_ONE))
2234                .collect();
2235            updates.push((T::update(key, value), Diff::ONE));
2236            // We must fence out all other catalogs, if we haven't already, since we are writing.
2237            match self.fenceable_token.generate_unfenced_token(self.mode)? {
2238                Some((fence_updates, current_fenceable_token)) => {
2239                    updates.extend(fence_updates.clone());
2240                    match self.compare_and_append(updates, self.upper).await {
2241                        Ok(_) => {
2242                            self.fenceable_token = current_fenceable_token;
2243                            break prev_value;
2244                        }
2245                        Err(CompareAndAppendError::Fence(e)) => return Err(e.into()),
2246                        Err(e @ CompareAndAppendError::UpperMismatch { .. }) => {
2247                            warn!("catalog write failed due to upper mismatch, retrying: {e:?}");
2248                            continue;
2249                        }
2250                    }
2251                }
2252                None => {
2253                    self.compare_and_append(updates, self.upper)
2254                        .await
2255                        .map_err(|e| e.unwrap_fence_error())?;
2256                    break prev_value;
2257                }
2258            }
2259        };
2260        Ok(prev_value)
2261    }
2262
2263    /// Manually delete `key` from collection `T`.
2264    #[mz_ore::instrument]
2265    pub(crate) async fn debug_delete<T: Collection>(
2266        &mut self,
2267        key: T::Key,
2268    ) -> Result<(), CatalogError>
2269    where
2270        T::Key: PartialEq + Eq + Debug + Clone,
2271        T::Value: Debug,
2272    {
2273        loop {
2274            let key = key.clone();
2275            let snapshot = self.current_snapshot().await?;
2276            let trace = Trace::from_snapshot(snapshot);
2277            let collection_trace = T::collection_trace(trace);
2278            let mut retractions: Vec<_> = collection_trace
2279                .values
2280                .into_iter()
2281                .filter(|((k, _), _, diff)| {
2282                    soft_assert_eq_or_log!(*diff, Diff::ONE, "trace is consolidated");
2283                    &key == k
2284                })
2285                .map(|((k, v), _, _)| (T::update(k, v), Diff::MINUS_ONE))
2286                .collect();
2287
2288            // We must fence out all other catalogs, if we haven't already, since we are writing.
2289            match self.fenceable_token.generate_unfenced_token(self.mode)? {
2290                Some((fence_updates, current_fenceable_token)) => {
2291                    retractions.extend(fence_updates.clone());
2292                    match self.compare_and_append(retractions, self.upper).await {
2293                        Ok(_) => {
2294                            self.fenceable_token = current_fenceable_token;
2295                            break;
2296                        }
2297                        Err(CompareAndAppendError::Fence(e)) => return Err(e.into()),
2298                        Err(e @ CompareAndAppendError::UpperMismatch { .. }) => {
2299                            warn!("catalog write failed due to upper mismatch, retrying: {e:?}");
2300                            continue;
2301                        }
2302                    }
2303                }
2304                None => {
2305                    self.compare_and_append(retractions, self.upper)
2306                        .await
2307                        .map_err(|e| e.unwrap_fence_error())?;
2308                    break;
2309                }
2310            }
2311        }
2312        Ok(())
2313    }
2314
2315    /// Generates a [`Vec<StateUpdate>`] that contain all updates to the catalog
2316    /// state.
2317    ///
2318    /// The output is consolidated and sorted by timestamp in ascending order and the current upper.
2319    async fn current_snapshot(
2320        &mut self,
2321    ) -> Result<impl IntoIterator<Item = StateUpdate> + '_, CatalogError> {
2322        self.sync_to_current_upper().await?;
2323        self.consolidate();
2324        Ok(self.snapshot.iter().cloned().map(|(kind, ts, diff)| {
2325            let kind = TryIntoStateUpdateKind::try_into(kind).expect("kind decoding error");
2326            StateUpdate { kind, ts, diff }
2327        }))
2328    }
2329}