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::Comment(key, value) => {
807                        apply(&mut snapshot.comments, key, value, diff);
808                    }
809                    StateUpdateKind::Config(key, value) => {
810                        apply(&mut snapshot.configs, key, value, diff);
811                    }
812                    StateUpdateKind::Database(key, value) => {
813                        apply(&mut snapshot.databases, key, value, diff);
814                    }
815                    StateUpdateKind::DefaultPrivilege(key, value) => {
816                        apply(&mut snapshot.default_privileges, key, value, diff);
817                    }
818                    StateUpdateKind::FenceToken(_token) => {
819                        // Ignore for snapshots.
820                    }
821                    StateUpdateKind::IdAllocator(key, value) => {
822                        apply(&mut snapshot.id_allocator, key, value, diff);
823                    }
824                    StateUpdateKind::IntrospectionSourceIndex(key, value) => {
825                        apply(&mut snapshot.introspection_sources, key, value, diff);
826                    }
827                    StateUpdateKind::Item(key, value) => {
828                        apply(&mut snapshot.items, key, value, diff);
829                    }
830                    StateUpdateKind::NetworkPolicy(key, value) => {
831                        apply(&mut snapshot.network_policies, key, value, diff);
832                    }
833                    StateUpdateKind::Role(key, value) => {
834                        apply(&mut snapshot.roles, key, value, diff);
835                    }
836                    StateUpdateKind::Schema(key, value) => {
837                        apply(&mut snapshot.schemas, key, value, diff);
838                    }
839                    StateUpdateKind::Setting(key, value) => {
840                        apply(&mut snapshot.settings, key, value, diff);
841                    }
842                    StateUpdateKind::SourceReferences(key, value) => {
843                        apply(&mut snapshot.source_references, key, value, diff);
844                    }
845                    StateUpdateKind::SystemConfiguration(key, value) => {
846                        apply(&mut snapshot.system_configurations, key, value, diff);
847                    }
848                    StateUpdateKind::ClusterSystemConfiguration(key, value) => {
849                        apply(
850                            &mut snapshot.cluster_system_configurations,
851                            key,
852                            value,
853                            diff,
854                        );
855                    }
856                    StateUpdateKind::ReplicaSystemConfiguration(key, value) => {
857                        apply(
858                            &mut snapshot.replica_system_configurations,
859                            key,
860                            value,
861                            diff,
862                        );
863                    }
864                    StateUpdateKind::SystemObjectMapping(key, value) => {
865                        apply(&mut snapshot.system_object_mappings, key, value, diff);
866                    }
867                    StateUpdateKind::SystemPrivilege(key, value) => {
868                        apply(&mut snapshot.system_privileges, key, value, diff);
869                    }
870                    StateUpdateKind::StorageCollectionMetadata(key, value) => {
871                        apply(&mut snapshot.storage_collection_metadata, key, value, diff);
872                    }
873                    StateUpdateKind::UnfinalizedShard(key, ()) => {
874                        apply(&mut snapshot.unfinalized_shards, key, &(), diff);
875                    }
876                    StateUpdateKind::TxnWalShard((), value) => {
877                        apply(&mut snapshot.txn_wal_shard, &(), value, diff);
878                    }
879                    StateUpdateKind::RoleAuth(key, value) => {
880                        apply(&mut snapshot.role_auth, key, value, diff);
881                    }
882                }
883            }
884            f(snapshot)
885        })
886        .await
887    }
888
889    /// Generates an iterator of [`StateUpdate`] that contain all updates to the catalog
890    /// state.
891    ///
892    /// The output is fetched directly from persist instead of the in-memory cache.
893    ///
894    /// The output is consolidated and sorted by timestamp in ascending order.
895    #[mz_ore::instrument(level = "debug")]
896    async fn persist_snapshot(&self) -> impl Iterator<Item = StateUpdate> + DoubleEndedIterator {
897        let mut read_handle = self.read_handle().await;
898        let as_of = as_of(&read_handle, self.upper);
899        let snapshot = snapshot_binary(&mut read_handle, as_of, &self.metrics)
900            .await
901            .map(|update| update.try_into().expect("kind decoding error"));
902        read_handle.expire().await;
903        snapshot
904    }
905}
906
907/// Applies updates for an unopened catalog.
908#[derive(Debug)]
909pub(crate) struct UnopenedCatalogStateInner {
910    /// A cache of the config collection of the catalog.
911    configs: BTreeMap<String, u64>,
912    /// A cache of the settings collection of the catalog.
913    settings: BTreeMap<String, String>,
914}
915
916impl UnopenedCatalogStateInner {
917    fn new() -> UnopenedCatalogStateInner {
918        UnopenedCatalogStateInner {
919            configs: BTreeMap::new(),
920            settings: BTreeMap::new(),
921        }
922    }
923}
924
925impl ApplyUpdate<StateUpdateKindJson> for UnopenedCatalogStateInner {
926    fn apply_update(
927        &mut self,
928        update: StateUpdate<StateUpdateKindJson>,
929        current_fence_token: &mut FenceableToken,
930        _metrics: &Arc<Metrics>,
931    ) -> Result<Option<StateUpdate<StateUpdateKindJson>>, FenceError> {
932        if !update.kind.is_audit_log() && update.kind.is_always_deserializable() {
933            let kind = TryInto::try_into(&update.kind).expect("kind is known to be deserializable");
934            match (kind, update.diff) {
935                (StateUpdateKind::Config(key, value), Diff::ONE) => {
936                    let prev = self.configs.insert(key.key, value.value);
937                    assert_eq!(
938                        prev, None,
939                        "values must be explicitly retracted before inserting a new value"
940                    );
941                }
942                (StateUpdateKind::Config(key, value), Diff::MINUS_ONE) => {
943                    let prev = self.configs.remove(&key.key);
944                    assert_eq!(
945                        prev,
946                        Some(value.value),
947                        "retraction does not match existing value"
948                    );
949                }
950                (StateUpdateKind::Setting(key, value), Diff::ONE) => {
951                    let prev = self.settings.insert(key.name, value.value);
952                    assert_eq!(
953                        prev, None,
954                        "values must be explicitly retracted before inserting a new value"
955                    );
956                }
957                (StateUpdateKind::Setting(key, value), Diff::MINUS_ONE) => {
958                    let prev = self.settings.remove(&key.name);
959                    assert_eq!(
960                        prev,
961                        Some(value.value),
962                        "retraction does not match existing value"
963                    );
964                }
965                (StateUpdateKind::FenceToken(fence_token), Diff::ONE) => {
966                    current_fence_token.maybe_fence(fence_token)?;
967                }
968                _ => {}
969            }
970        }
971
972        Ok(Some(update))
973    }
974}
975
976/// A Handle to an unopened catalog stored in persist. The unopened catalog can serve `Config` data,
977/// `Setting` data, or the current epoch. All other catalog data may be un-migrated and should not
978/// be read until the catalog has been opened. The [`UnopenedPersistCatalogState`] is responsible
979/// for opening the catalog, see [`OpenableDurableCatalogState::open`] for more details.
980///
981/// Production users should call [`Self::expire`] before dropping an [`UnopenedPersistCatalogState`]
982/// so that it can expire its leases. If/when rust gets AsyncDrop, this will be done automatically.
983pub(crate) type UnopenedPersistCatalogState =
984    PersistHandle<StateUpdateKindJson, UnopenedCatalogStateInner>;
985
986impl UnopenedPersistCatalogState {
987    /// Create a new [`UnopenedPersistCatalogState`] to the catalog state associated with
988    /// `organization_id`.
989    ///
990    /// All usages of the persist catalog must go through this function. That includes the
991    /// catalog-debug tool, the adapter's catalog, etc.
992    #[mz_ore::instrument]
993    pub(crate) async fn new(
994        persist_client: PersistClient,
995        organization_id: Uuid,
996        version: semver::Version,
997        deploy_generation: Option<u64>,
998        metrics: Arc<Metrics>,
999    ) -> Result<UnopenedPersistCatalogState, DurableCatalogError> {
1000        let catalog_shard_id = shard_id(organization_id, CATALOG_SEED);
1001        debug!(?catalog_shard_id, "new persist backed catalog state");
1002
1003        // Check the catalog shard version to ensure that we are compatible with the persist
1004        // data format. This lets us return an error gracefully, rather than panicking later in
1005        // persist.
1006        let version_in_catalog_shard =
1007            fetch_catalog_shard_version(&persist_client, catalog_shard_id).await;
1008        if let Some(version_in_catalog_shard) = version_in_catalog_shard {
1009            if !mz_persist_client::cfg::code_can_write_data(&version, &version_in_catalog_shard) {
1010                return Err(DurableCatalogError::IncompatiblePersistVersion {
1011                    found_version: version_in_catalog_shard,
1012                    catalog_version: version,
1013                });
1014            }
1015        }
1016
1017        let open_handles_start = Instant::now();
1018        info!("startup: envd serve: catalog init: open handles beginning");
1019        let since_handle = persist_client
1020            .open_critical_since(
1021                catalog_shard_id,
1022                CATALOG_CRITICAL_SINCE.clone(),
1023                Opaque::encode(&i64::MIN),
1024                Diagnostics {
1025                    shard_name: CATALOG_SHARD_NAME.to_string(),
1026                    handle_purpose: "durable catalog state critical since".to_string(),
1027                },
1028            )
1029            .await
1030            .expect("invalid usage");
1031
1032        let (mut write_handle, mut read_handle) = persist_client
1033            .open(
1034                catalog_shard_id,
1035                Arc::new(persist_desc()),
1036                Arc::new(UnitSchema::default()),
1037                Diagnostics {
1038                    shard_name: CATALOG_SHARD_NAME.to_string(),
1039                    handle_purpose: "durable catalog state handles".to_string(),
1040                },
1041                USE_CRITICAL_SINCE_CATALOG.get(persist_client.dyncfgs()),
1042            )
1043            .await
1044            .expect("invalid usage");
1045        info!(
1046            "startup: envd serve: catalog init: open handles complete in {:?}",
1047            open_handles_start.elapsed()
1048        );
1049
1050        // Commit an empty write at the minimum timestamp so the catalog is always readable.
1051        let upper = {
1052            const EMPTY_UPDATES: &[((SourceData, ()), Timestamp, StorageDiff)] = &[];
1053            let upper = Antichain::from_elem(Timestamp::minimum());
1054            let next_upper = Timestamp::minimum().step_forward();
1055            match write_handle
1056                .compare_and_append(EMPTY_UPDATES, upper, Antichain::from_elem(next_upper))
1057                .await
1058                .expect("invalid usage")
1059            {
1060                Ok(()) => next_upper,
1061                Err(mismatch) => antichain_to_timestamp(mismatch.current),
1062            }
1063        };
1064
1065        let snapshot_start = Instant::now();
1066        info!("startup: envd serve: catalog init: snapshot beginning");
1067        let as_of = as_of(&read_handle, upper);
1068        let snapshot: Vec<_> = snapshot_binary(&mut read_handle, as_of, &metrics)
1069            .await
1070            .map(|StateUpdate { kind, ts, diff }| (kind, ts, diff))
1071            .collect();
1072        let listen = read_handle
1073            .listen(Antichain::from_elem(as_of))
1074            .await
1075            .expect("invalid usage");
1076        info!(
1077            "startup: envd serve: catalog init: snapshot complete in {:?}",
1078            snapshot_start.elapsed()
1079        );
1080
1081        let mut handle = UnopenedPersistCatalogState {
1082            // Unopened catalogs are always writeable until they're opened in an explicit mode.
1083            mode: Mode::Writable,
1084            since_handle,
1085            write_handle,
1086            listen,
1087            persist_client,
1088            shard_id: catalog_shard_id,
1089            // Initialize empty in-memory state.
1090            snapshot: Vec::new(),
1091            update_applier: UnopenedCatalogStateInner::new(),
1092            upper,
1093            fenceable_token: FenceableToken::new(deploy_generation),
1094            catalog_content_version: version,
1095            bootstrap_complete: false,
1096            metrics,
1097            size_at_last_consolidation: None,
1098            updates_applied: 0,
1099        };
1100        // If the snapshot is not consolidated, and we see multiple epoch values while applying the
1101        // updates, then we might accidentally fence ourselves out.
1102        soft_assert_no_log!(
1103            snapshot.iter().all(|(_, _, diff)| *diff == Diff::ONE),
1104            "snapshot should be consolidated: {snapshot:#?}"
1105        );
1106
1107        let apply_start = Instant::now();
1108        info!("startup: envd serve: catalog init: apply updates beginning");
1109        let updates = snapshot
1110            .into_iter()
1111            .map(|(kind, ts, diff)| StateUpdate { kind, ts, diff });
1112        handle.apply_updates_and_consolidate(updates)?;
1113        info!(
1114            "startup: envd serve: catalog init: apply updates complete in {:?}",
1115            apply_start.elapsed()
1116        );
1117
1118        // Validate that the binary version of the current process is not less than any binary
1119        // version that has written to the catalog.
1120        // This condition is only checked once, right here. If a new process comes along with a
1121        // higher version, it must fence this process out with one of the existing fencing
1122        // mechanisms.
1123        if let Some(found_version) = handle.get_catalog_content_version().await? {
1124            // Use cmp_precedence() to ignore build metadata per SemVer 2.0.0 spec
1125            if handle
1126                .catalog_content_version
1127                .cmp_precedence(&found_version)
1128                == std::cmp::Ordering::Less
1129            {
1130                return Err(DurableCatalogError::IncompatiblePersistVersion {
1131                    found_version,
1132                    catalog_version: handle.catalog_content_version,
1133                });
1134            }
1135        }
1136
1137        Ok(handle)
1138    }
1139
1140    #[mz_ore::instrument]
1141    async fn open_inner(
1142        mut self,
1143        mode: Mode,
1144        initial_ts: Timestamp,
1145        bootstrap_args: &BootstrapArgs,
1146    ) -> Result<Box<dyn DurableCatalogState>, CatalogError> {
1147        // It would be nice to use `initial_ts` here, but it comes from the system clock, not the
1148        // timestamp oracle.
1149        let mut commit_ts = self.upper;
1150        self.mode = mode;
1151
1152        // Validate the current deploy generation.
1153        match (&self.mode, &self.fenceable_token) {
1154            (_, FenceableToken::Unfenced { .. } | FenceableToken::Fenced { .. }) => {
1155                return Err(DurableCatalogError::Internal(
1156                    "catalog should not have fenced before opening".to_string(),
1157                )
1158                .into());
1159            }
1160            (
1161                Mode::Writable | Mode::Savepoint,
1162                FenceableToken::Initializing {
1163                    current_deploy_generation: None,
1164                    ..
1165                },
1166            ) => {
1167                return Err(DurableCatalogError::Internal(format!(
1168                    "cannot open in mode '{:?}' without a deploy generation",
1169                    self.mode,
1170                ))
1171                .into());
1172            }
1173            _ => {}
1174        }
1175
1176        let read_only = matches!(self.mode, Mode::Readonly);
1177
1178        // Fence out previous catalogs.
1179        loop {
1180            self.sync_to_current_upper().await?;
1181            commit_ts = max(commit_ts, self.upper);
1182            let (fence_updates, current_fenceable_token) = self
1183                .fenceable_token
1184                .generate_unfenced_token(self.mode)?
1185                .ok_or_else(|| {
1186                    DurableCatalogError::Internal(
1187                        "catalog should not have fenced before opening".to_string(),
1188                    )
1189                })?;
1190            debug!(
1191                ?self.upper,
1192                ?self.fenceable_token,
1193                ?current_fenceable_token,
1194                "fencing previous catalogs"
1195            );
1196            if matches!(self.mode, Mode::Writable) {
1197                match self
1198                    .compare_and_append(fence_updates.clone(), commit_ts)
1199                    .await
1200                {
1201                    Ok(upper) => {
1202                        commit_ts = upper;
1203                    }
1204                    Err(CompareAndAppendError::Fence(e)) => return Err(e.into()),
1205                    Err(e @ CompareAndAppendError::UpperMismatch { .. }) => {
1206                        warn!("catalog write failed due to upper mismatch, retrying: {e:?}");
1207                        continue;
1208                    }
1209                }
1210            }
1211            self.fenceable_token = current_fenceable_token;
1212            break;
1213        }
1214
1215        if matches!(self.mode, Mode::Writable) {
1216            // One-time migration: The catalog previously used `CONTROLLER_CRITICAL_SINCE` for its
1217            // since handle. Now it uses its own `CATALOG_CRITICAL_SINCE`, to free
1218            // `CONTROLLER_CRITICAL_SINCE` up for the storage controller. The catalog and
1219            // controller handles differ in the `Opaque` codec, so we need a migration.
1220            //
1221            // TODO: Remove this once we don't support upgrading from v26 anymore.
1222            let mut controller_handle = self
1223                .persist_client
1224                .open_critical_since::<SourceData, (), Timestamp, StorageDiff>(
1225                    self.shard_id,
1226                    PersistClient::CONTROLLER_CRITICAL_SINCE,
1227                    Opaque::encode(&i64::MIN),
1228                    Diagnostics {
1229                        shard_name: CATALOG_SHARD_NAME.to_string(),
1230                        handle_purpose: "durable catalog state critical since (migration)"
1231                            .to_string(),
1232                    },
1233                )
1234                .await
1235                .expect("invalid usage");
1236
1237            let since = controller_handle.since().clone();
1238            let res = controller_handle
1239                .compare_and_downgrade_since(
1240                    &Opaque::encode(&i64::MIN),
1241                    (&Opaque::encode(&PersistEpoch::default()), &since),
1242                )
1243                .await;
1244            match res {
1245                Ok(_) => info!("migrated Opaque of catalog since handle"),
1246                Err(_) => { /* critical since was already migrated */ }
1247            }
1248        }
1249
1250        let is_initialized = self.is_initialized_inner();
1251        if !matches!(self.mode, Mode::Writable) && !is_initialized {
1252            return Err(CatalogError::Durable(DurableCatalogError::NotWritable(
1253                format!(
1254                    "catalog tables do not exist; will not create in {:?} mode",
1255                    self.mode
1256                ),
1257            )));
1258        }
1259        soft_assert_ne_or_log!(self.upper, Timestamp::minimum());
1260
1261        // Audit log entries are served from `mz_internal.mz_catalog_raw` via
1262        // the `mz_audit_events` materialized view, so they do not need to live
1263        // in the in-memory catalog snapshot. Drop them here and only keep the
1264        // count for metrics.
1265        let (audit_logs, snapshot): (Vec<_>, Vec<_>) = self
1266            .snapshot
1267            .into_iter()
1268            .partition(|(update, _, _)| update.is_audit_log());
1269        self.snapshot = snapshot;
1270        let audit_log_count = audit_logs.iter().map(|(_, _, diff)| diff).sum::<Diff>();
1271        drop(audit_logs);
1272
1273        // Perform data migrations.
1274        if is_initialized && !read_only {
1275            commit_ts = upgrade(&mut self, commit_ts).await?;
1276        }
1277
1278        debug!(
1279            ?is_initialized,
1280            ?self.upper,
1281            "initializing catalog state"
1282        );
1283        let mut catalog = PersistCatalogState {
1284            mode: self.mode,
1285            since_handle: self.since_handle,
1286            write_handle: self.write_handle,
1287            listen: self.listen,
1288            persist_client: self.persist_client,
1289            shard_id: self.shard_id,
1290            upper: self.upper,
1291            fenceable_token: self.fenceable_token,
1292            // Initialize empty in-memory state.
1293            snapshot: Vec::new(),
1294            update_applier: CatalogStateInner::new(),
1295            catalog_content_version: self.catalog_content_version,
1296            bootstrap_complete: false,
1297            metrics: self.metrics,
1298            size_at_last_consolidation: None,
1299            updates_applied: 0,
1300        };
1301        catalog.metrics.collection_entries.reset();
1302        // Normally, `collection_entries` is updated in `apply_updates`. The audit log updates skip
1303        // over that function so we manually update it here.
1304        catalog
1305            .metrics
1306            .collection_entries
1307            .with_label_values(&[&CollectionType::AuditLog.to_string()])
1308            .add(audit_log_count.into_inner());
1309        let updates = self.snapshot.into_iter().map(|(kind, ts, diff)| {
1310            let kind = TryIntoStateUpdateKind::try_into(kind).expect("kind decoding error");
1311            StateUpdate { kind, ts, diff }
1312        });
1313        catalog.apply_updates_and_consolidate(updates)?;
1314
1315        let catalog_content_version = catalog.catalog_content_version.to_string();
1316        let txn = if is_initialized {
1317            let mut txn = catalog.transaction_unchecked().await?;
1318
1319            // Ad-hoc migration: Initialize the `migration_version` expected by adapter to be
1320            // present in existing catalogs.
1321            //
1322            // Note: Need to exclude read-only catalog mode here, because in that mode all
1323            // transactions are expected to be no-ops.
1324            // TODO: remove this once we only support upgrades from version >= 0.164
1325            if txn.get_setting("migration_version".into()).is_none() && mode != Mode::Readonly {
1326                let old_version = txn.get_catalog_content_version();
1327                txn.set_setting("migration_version".into(), old_version.map(Into::into))?;
1328            }
1329
1330            // Opening the catalog with write intent fences out every previous
1331            // catalog owner, so all sessions served by previous owners are
1332            // dead. Reclaim the temporary items they owned here, before
1333            // anything else reads the catalog.
1334            //
1335            // NOTE: This only reclaims on the fence, which covers a
1336            // single-writer world where every crash is followed by some
1337            // process's writable open. Once several serving envds run
1338            // concurrently, a peer crash triggers no fence here, so
1339            // reclaiming its sessions' items needs the durable
1340            // envd-heartbeat mechanism described in the durable temporary
1341            // objects design doc.
1342            if mode != Mode::Readonly {
1343                txn.remove_ephemeral_items();
1344            }
1345
1346            txn.set_catalog_content_version(catalog_content_version)?;
1347            txn
1348        } else {
1349            soft_assert_eq_no_log!(
1350                catalog
1351                    .snapshot
1352                    .iter()
1353                    .filter(|(kind, _, _)| !matches!(kind, StateUpdateKind::FenceToken(_)))
1354                    .count(),
1355                0,
1356                "trace should not contain any updates for an uninitialized catalog: {:#?}",
1357                catalog.snapshot
1358            );
1359
1360            let mut txn = catalog.transaction_unchecked().await?;
1361            initialize::initialize(
1362                &mut txn,
1363                bootstrap_args,
1364                initial_ts.into(),
1365                catalog_content_version,
1366            )
1367            .await?;
1368            txn
1369        };
1370
1371        if read_only {
1372            let (txn_batch, _) = txn.into_parts()?;
1373            // The upper here doesn't matter because we are only applying the updates in memory.
1374            let updates = StateUpdate::from_txn_batch_ts(txn_batch, catalog.upper);
1375            catalog.apply_updates_and_consolidate(updates)?;
1376        } else {
1377            txn.commit_internal(commit_ts).await?;
1378        }
1379
1380        if matches!(catalog.mode, Mode::Writable) {
1381            let write_handle = catalog
1382                .persist_client
1383                .open_writer::<SourceData, (), Timestamp, i64>(
1384                    catalog.write_handle.shard_id(),
1385                    Arc::new(persist_desc()),
1386                    Arc::new(UnitSchema::default()),
1387                    Diagnostics {
1388                        shard_name: CATALOG_SHARD_NAME.to_string(),
1389                        handle_purpose: "compact catalog".to_string(),
1390                    },
1391                )
1392                .await
1393                .expect("invalid usage");
1394            let fuel = CATALOG_FORCE_COMPACTION_FUEL.handle(catalog.persist_client.dyncfgs());
1395            let wait = CATALOG_FORCE_COMPACTION_WAIT.handle(catalog.persist_client.dyncfgs());
1396            // We're going to gradually turn this on via dyncfgs. Run it in a task so that it
1397            // doesn't block startup.
1398            let _task = mz_ore::task::spawn(|| "catalog::force_shard_compaction", async move {
1399                let () =
1400                    mz_persist_client::cli::admin::dangerous_force_compaction_and_break_pushdown(
1401                        &write_handle,
1402                        || fuel.get(),
1403                        || wait.get(),
1404                    )
1405                    .await;
1406            });
1407        }
1408
1409        Ok(Box::new(catalog))
1410    }
1411
1412    /// Reports if the catalog state has been initialized.
1413    ///
1414    /// NOTE: This is the answer as of the last call to [`PersistHandle::sync`] or [`PersistHandle::sync_to_current_upper`],
1415    /// not necessarily what is currently in persist.
1416    #[mz_ore::instrument]
1417    fn is_initialized_inner(&self) -> bool {
1418        !self.update_applier.configs.is_empty()
1419    }
1420
1421    /// Get the current value of config `key`.
1422    ///
1423    /// Some configs need to be read before the catalog is opened for bootstrapping.
1424    #[mz_ore::instrument]
1425    async fn get_current_config(&mut self, key: &str) -> Result<Option<u64>, DurableCatalogError> {
1426        self.sync_to_current_upper().await?;
1427        Ok(self.update_applier.configs.get(key).cloned())
1428    }
1429
1430    /// Get the user version of this instance.
1431    ///
1432    /// The user version is used to determine if a migration is needed.
1433    #[mz_ore::instrument]
1434    pub(crate) async fn get_user_version(&mut self) -> Result<Option<u64>, DurableCatalogError> {
1435        self.get_current_config(USER_VERSION_KEY).await
1436    }
1437
1438    /// Get the current value of setting `name`.
1439    ///
1440    /// Some settings need to be read before the catalog is opened for bootstrapping.
1441    #[mz_ore::instrument]
1442    async fn get_current_setting(
1443        &mut self,
1444        name: &str,
1445    ) -> Result<Option<String>, DurableCatalogError> {
1446        self.sync_to_current_upper().await?;
1447        Ok(self.update_applier.settings.get(name).cloned())
1448    }
1449
1450    /// Get the catalog content version.
1451    ///
1452    /// The catalog content version is the semantic version of the most recent binary that wrote to
1453    /// the catalog.
1454    #[mz_ore::instrument]
1455    async fn get_catalog_content_version(
1456        &mut self,
1457    ) -> Result<Option<semver::Version>, DurableCatalogError> {
1458        let version = self
1459            .get_current_setting(CATALOG_CONTENT_VERSION_KEY)
1460            .await?;
1461        let version = version.map(|version| version.parse().expect("invalid version persisted"));
1462        Ok(version)
1463    }
1464}
1465
1466#[async_trait]
1467impl OpenableDurableCatalogState for UnopenedPersistCatalogState {
1468    #[mz_ore::instrument]
1469    async fn open_savepoint(
1470        mut self: Box<Self>,
1471        initial_ts: Timestamp,
1472        bootstrap_args: &BootstrapArgs,
1473    ) -> Result<Box<dyn DurableCatalogState>, CatalogError> {
1474        self.open_inner(Mode::Savepoint, initial_ts, bootstrap_args)
1475            .boxed()
1476            .await
1477    }
1478
1479    #[mz_ore::instrument]
1480    async fn open_read_only(
1481        mut self: Box<Self>,
1482        bootstrap_args: &BootstrapArgs,
1483    ) -> Result<Box<dyn DurableCatalogState>, CatalogError> {
1484        self.open_inner(Mode::Readonly, EpochMillis::MIN.into(), bootstrap_args)
1485            .boxed()
1486            .await
1487    }
1488
1489    #[mz_ore::instrument]
1490    async fn open(
1491        mut self: Box<Self>,
1492        initial_ts: Timestamp,
1493        bootstrap_args: &BootstrapArgs,
1494    ) -> Result<Box<dyn DurableCatalogState>, CatalogError> {
1495        self.open_inner(Mode::Writable, initial_ts, bootstrap_args)
1496            .boxed()
1497            .await
1498    }
1499
1500    #[mz_ore::instrument(level = "debug")]
1501    async fn open_debug(mut self: Box<Self>) -> Result<DebugCatalogState, CatalogError> {
1502        Ok(DebugCatalogState(*self))
1503    }
1504
1505    #[mz_ore::instrument]
1506    async fn is_initialized(&mut self) -> Result<bool, CatalogError> {
1507        self.sync_to_current_upper().await?;
1508        Ok(self.is_initialized_inner())
1509    }
1510
1511    #[mz_ore::instrument]
1512    async fn epoch(&mut self) -> Result<Epoch, CatalogError> {
1513        self.sync_to_current_upper().await?;
1514        self.fenceable_token
1515            .validate()?
1516            .map(|token| token.epoch)
1517            .ok_or(CatalogError::Durable(DurableCatalogError::Uninitialized))
1518    }
1519
1520    #[mz_ore::instrument]
1521    async fn get_deployment_generation(&mut self) -> Result<u64, CatalogError> {
1522        self.sync_to_current_upper().await?;
1523        self.fenceable_token
1524            .token()
1525            .map(|token| token.deploy_generation)
1526            .ok_or(CatalogError::Durable(DurableCatalogError::Uninitialized))
1527    }
1528
1529    #[mz_ore::instrument(level = "debug")]
1530    async fn get_0dt_deployment_max_wait(&mut self) -> Result<Option<Duration>, CatalogError> {
1531        let value = self
1532            .get_current_config(WITH_0DT_DEPLOYMENT_MAX_WAIT)
1533            .await?;
1534        match value {
1535            None => Ok(None),
1536            Some(millis) => Ok(Some(Duration::from_millis(millis))),
1537        }
1538    }
1539
1540    #[mz_ore::instrument(level = "debug")]
1541    async fn get_0dt_deployment_ddl_check_interval(
1542        &mut self,
1543    ) -> Result<Option<Duration>, CatalogError> {
1544        let value = self
1545            .get_current_config(WITH_0DT_DEPLOYMENT_DDL_CHECK_INTERVAL)
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_enable_0dt_deployment_panic_after_timeout(
1555        &mut self,
1556    ) -> Result<Option<bool>, CatalogError> {
1557        let value = self
1558            .get_current_config(ENABLE_0DT_DEPLOYMENT_PANIC_AFTER_TIMEOUT)
1559            .await?;
1560        match value {
1561            None => Ok(None),
1562            Some(0) => Ok(Some(false)),
1563            Some(1) => Ok(Some(true)),
1564            Some(v) => Err(
1565                DurableCatalogError::from(TryFromProtoError::UnknownEnumVariant(format!(
1566                    "{v} is not a valid boolean value"
1567                )))
1568                .into(),
1569            ),
1570        }
1571    }
1572
1573    #[mz_ore::instrument]
1574    async fn has_system_config_synced_once(&mut self) -> Result<bool, DurableCatalogError> {
1575        self.get_current_config(SYSTEM_CONFIG_SYNCED_KEY)
1576            .await
1577            .map(|value| value.map(|value| value > 0).unwrap_or(false))
1578    }
1579
1580    #[mz_ore::instrument]
1581    async fn trace_unconsolidated(&mut self) -> Result<Trace, CatalogError> {
1582        self.sync_to_current_upper().await?;
1583        if self.is_initialized_inner() {
1584            let snapshot = self.snapshot_unconsolidated().await;
1585            Ok(Trace::from_snapshot(snapshot))
1586        } else {
1587            Err(CatalogError::Durable(DurableCatalogError::Uninitialized))
1588        }
1589    }
1590
1591    #[mz_ore::instrument]
1592    async fn trace_consolidated(&mut self) -> Result<Trace, CatalogError> {
1593        self.sync_to_current_upper().await?;
1594        if self.is_initialized_inner() {
1595            let snapshot = self.current_snapshot().await?;
1596            Ok(Trace::from_snapshot(snapshot))
1597        } else {
1598            Err(CatalogError::Durable(DurableCatalogError::Uninitialized))
1599        }
1600    }
1601
1602    #[mz_ore::instrument(level = "debug")]
1603    async fn expire(self: Box<Self>) {
1604        self.expire().await
1605    }
1606}
1607
1608/// Applies updates for an opened catalog.
1609#[derive(Debug)]
1610struct CatalogStateInner {
1611    /// A trace of all catalog updates that can be consumed by some higher layer.
1612    updates: VecDeque<memory::objects::StateUpdate>,
1613}
1614
1615impl CatalogStateInner {
1616    fn new() -> CatalogStateInner {
1617        CatalogStateInner {
1618            updates: VecDeque::new(),
1619        }
1620    }
1621}
1622
1623impl ApplyUpdate<StateUpdateKind> for CatalogStateInner {
1624    fn apply_update(
1625        &mut self,
1626        update: StateUpdate<StateUpdateKind>,
1627        current_fence_token: &mut FenceableToken,
1628        metrics: &Arc<Metrics>,
1629    ) -> Result<Option<StateUpdate<StateUpdateKind>>, FenceError> {
1630        if let Some(collection_type) = update.kind.collection_type() {
1631            metrics
1632                .collection_entries
1633                .with_label_values(&[&collection_type.to_string()])
1634                .add(update.diff.into_inner());
1635        }
1636
1637        {
1638            let update: Option<memory::objects::StateUpdate> = (&update)
1639                .try_into()
1640                .expect("invalid persisted update: {update:#?}");
1641            if let Some(update) = update {
1642                self.updates.push_back(update);
1643            }
1644        }
1645
1646        match (update.kind, update.diff) {
1647            (StateUpdateKind::AuditLog(_, ()), _) => Ok(None),
1648            // Nothing to due for fence token retractions but wait for the next insertion.
1649            (StateUpdateKind::FenceToken(_), Diff::MINUS_ONE) => Ok(None),
1650            (StateUpdateKind::FenceToken(token), Diff::ONE) => {
1651                current_fence_token.maybe_fence(token)?;
1652                Ok(None)
1653            }
1654            (kind, diff) => Ok(Some(StateUpdate {
1655                kind,
1656                ts: update.ts,
1657                diff,
1658            })),
1659        }
1660    }
1661}
1662
1663/// A durable store of the catalog state using Persist as an implementation. The durable store can
1664/// serve any catalog data and transactionally modify catalog data.
1665///
1666/// Production users should call [`Self::expire`] before dropping a [`PersistCatalogState`]
1667/// so that it can expire its leases. If/when rust gets AsyncDrop, this will be done automatically.
1668type PersistCatalogState = PersistHandle<StateUpdateKind, CatalogStateInner>;
1669
1670impl PersistHandle<StateUpdateKind, CatalogStateInner> {
1671    /// Creates a transaction without validating pending catalog updates.
1672    async fn transaction_unchecked(&mut self) -> Result<Transaction<'_>, CatalogError> {
1673        self.metrics.transactions_started.inc();
1674        let snapshot = self.snapshot().await?;
1675        let commit_ts = self.upper;
1676        Transaction::new(self, snapshot, commit_ts)
1677    }
1678}
1679
1680#[async_trait]
1681impl ReadOnlyDurableCatalogState for PersistCatalogState {
1682    fn epoch(&self) -> Epoch {
1683        self.fenceable_token
1684            .token()
1685            .expect("opened catalog state must have an epoch")
1686            .epoch
1687    }
1688
1689    fn metrics(&self) -> &Metrics {
1690        &self.metrics
1691    }
1692
1693    #[mz_ore::instrument(level = "debug")]
1694    async fn expire(self: Box<Self>) {
1695        self.expire().await
1696    }
1697
1698    fn is_bootstrap_complete(&self) -> bool {
1699        self.bootstrap_complete
1700    }
1701
1702    async fn get_audit_logs(&mut self) -> Result<Vec<VersionedEvent>, CatalogError> {
1703        self.sync_to_current_upper().await?;
1704        let audit_logs: Vec<_> = self
1705            .persist_snapshot()
1706            .await
1707            .filter_map(
1708                |StateUpdate {
1709                     kind,
1710                     ts: _,
1711                     diff: _,
1712                 }| match kind {
1713                    StateUpdateKind::AuditLog(key, ()) => Some(key),
1714                    _ => None,
1715                },
1716            )
1717            .collect();
1718        let mut audit_logs: Vec<_> = audit_logs
1719            .into_iter()
1720            .map(RustType::from_proto)
1721            .map_ok(|key: AuditLogKey| key.event)
1722            .collect::<Result<_, _>>()?;
1723        audit_logs.sort_by(|a, b| a.sortable_id().cmp(&b.sortable_id()));
1724        Ok(audit_logs)
1725    }
1726
1727    #[mz_ore::instrument(level = "debug")]
1728    async fn get_next_id(&mut self, id_type: &str) -> Result<u64, CatalogError> {
1729        self.with_trace(|trace| {
1730            Ok(trace
1731                .into_iter()
1732                .rev()
1733                .filter_map(|(kind, _, _)| match kind {
1734                    StateUpdateKind::IdAllocator(key, value) if key.name == id_type => {
1735                        Some(value.next_id)
1736                    }
1737                    _ => None,
1738                })
1739                .next()
1740                .expect("must exist"))
1741        })
1742        .await
1743    }
1744
1745    #[mz_ore::instrument(level = "debug")]
1746    async fn get_deployment_generation(&mut self) -> Result<u64, CatalogError> {
1747        self.sync_to_current_upper().await?;
1748        Ok(self
1749            .fenceable_token
1750            .token()
1751            .expect("opened catalogs must have a token")
1752            .deploy_generation)
1753    }
1754
1755    #[mz_ore::instrument(level = "debug")]
1756    async fn snapshot(&mut self) -> Result<Snapshot, CatalogError> {
1757        self.with_snapshot(Ok).await
1758    }
1759
1760    #[mz_ore::instrument(level = "debug")]
1761    async fn sync_to_current_updates(
1762        &mut self,
1763    ) -> Result<Vec<memory::objects::StateUpdate>, CatalogError> {
1764        let upper = self.current_upper().await;
1765        self.sync_updates(upper).await
1766    }
1767
1768    #[mz_ore::instrument(level = "debug")]
1769    async fn sync_updates(
1770        &mut self,
1771        target_upper: mz_repr::Timestamp,
1772    ) -> Result<Vec<memory::objects::StateUpdate>, CatalogError> {
1773        self.sync(target_upper).await?;
1774        let mut updates = Vec::new();
1775        while let Some(update) = self.update_applier.updates.front() {
1776            if update.ts >= target_upper {
1777                break;
1778            }
1779
1780            let update = self
1781                .update_applier
1782                .updates
1783                .pop_front()
1784                .expect("peeked above");
1785            updates.push(update);
1786        }
1787        Ok(updates)
1788    }
1789
1790    #[mz_ore::instrument(level = "debug")]
1791    async fn ensure_not_out_of_sync(
1792        &mut self,
1793        target_upper: Timestamp,
1794    ) -> Result<(), CatalogError> {
1795        self.sync(target_upper).await?;
1796        let update_count = self
1797            .update_applier
1798            .updates
1799            .iter()
1800            .take_while(|update| update.ts < target_upper)
1801            .count();
1802        if update_count == 0 {
1803            Ok(())
1804        } else {
1805            Err(DurableCatalogError::CatalogOutOfSync {
1806                update_count,
1807                upper: target_upper,
1808            }
1809            .into())
1810        }
1811    }
1812
1813    async fn current_upper(&mut self) -> Timestamp {
1814        self.current_upper().await
1815    }
1816}
1817
1818#[async_trait]
1819#[allow(mismatched_lifetime_syntaxes)]
1820impl DurableCatalogState for PersistCatalogState {
1821    fn is_read_only(&self) -> bool {
1822        matches!(self.mode, Mode::Readonly)
1823    }
1824
1825    fn is_savepoint(&self) -> bool {
1826        matches!(self.mode, Mode::Savepoint)
1827    }
1828
1829    async fn mark_bootstrap_complete(&mut self) {
1830        self.bootstrap_complete = true;
1831        if matches!(self.mode, Mode::Writable) {
1832            self.since_handle
1833                .upgrade_version()
1834                .await
1835                .expect("invalid usage")
1836        }
1837    }
1838
1839    #[mz_ore::instrument(level = "debug")]
1840    async fn transaction(&mut self) -> Result<Transaction, CatalogError> {
1841        let mut txn = self.transaction_unchecked().await?;
1842        txn.ensure_not_out_of_sync().await?;
1843        Ok(txn)
1844    }
1845
1846    fn transaction_from_snapshot(
1847        &mut self,
1848        snapshot: Snapshot,
1849    ) -> Result<DryRunTransaction, CatalogError> {
1850        let commit_ts = self.upper;
1851        Transaction::new(self, snapshot, commit_ts).map(DryRunTransaction::new)
1852    }
1853
1854    #[mz_ore::instrument(level = "debug")]
1855    async fn allocate_id(
1856        &mut self,
1857        id_type: &str,
1858        amount: u64,
1859        commit_ts: Timestamp,
1860    ) -> Result<Vec<u64>, CatalogError> {
1861        let start = Instant::now();
1862        if amount == 0 {
1863            return Ok(Vec::new());
1864        }
1865        let mut txn = self.transaction_unchecked().await?;
1866        let ids = txn.get_and_increment_id_by(id_type.to_string(), amount)?;
1867        txn.commit_internal(commit_ts).await?;
1868        self.metrics
1869            .allocate_id_seconds
1870            .observe(start.elapsed().as_secs_f64());
1871        Ok(ids)
1872    }
1873
1874    #[mz_ore::instrument(level = "debug")]
1875    async fn commit_transaction(
1876        &mut self,
1877        txn_batch: TransactionBatch,
1878        commit_ts: Timestamp,
1879    ) -> Result<Timestamp, CatalogError> {
1880        async fn commit_transaction_inner(
1881            catalog: &mut PersistCatalogState,
1882            txn_batch: TransactionBatch,
1883            commit_ts: Timestamp,
1884        ) -> Result<Timestamp, CatalogError> {
1885            // If the transaction is empty then we don't error, even in read-only mode.
1886            // This is mostly for legacy reasons (i.e. with enough elbow grease this
1887            // behavior can be changed without breaking any fundamental assumptions).
1888            if catalog.mode == Mode::Readonly {
1889                let updates: Vec<_> = StateUpdate::from_txn_batch(txn_batch).collect();
1890                if !updates.is_empty() {
1891                    let collection_types: Vec<_> = updates
1892                        .iter()
1893                        .filter_map(|u| u.0.collection_type())
1894                        .collect();
1895                    return Err(DurableCatalogError::NotWritable(format!(
1896                        "cannot commit a transaction in a read-only catalog: \
1897                         {} updates across collections: {collection_types:?}",
1898                        updates.len(),
1899                    ))
1900                    .into());
1901                }
1902                return Ok(catalog.upper);
1903            }
1904
1905            // The handle is mutex-protected from transaction creation through commit, so only a
1906            // local programming error can change its cached upper here.
1907            assert_eq!(
1908                catalog.upper, txn_batch.upper,
1909                "the handle was mutated mid-transaction"
1910            );
1911
1912            let updates: Vec<_> = StateUpdate::from_txn_batch(txn_batch).collect();
1913            debug!("committing updates: {updates:?}");
1914
1915            // Empty upper progress does not invalidate the transaction.
1916            let mut commit_ts = max(commit_ts, catalog.upper);
1917
1918            let next_upper = match catalog.mode {
1919                Mode::Writable => loop {
1920                    let updates_applied_before = catalog.updates_applied;
1921                    match catalog.compare_and_append(updates.clone(), commit_ts).await {
1922                        Ok(next_upper) => break next_upper,
1923                        Err(CompareAndAppendError::Fence(e)) => return Err(e.into()),
1924                        Err(CompareAndAppendError::UpperMismatch { actual_upper, .. }) => {
1925                            // The mismatch synchronized the handle. Retry only if it applied no
1926                            // content.
1927                            catalog
1928                                .classify_upper_mismatch(updates_applied_before, actual_upper)?;
1929                            commit_ts = max(commit_ts, catalog.upper);
1930                        }
1931                    }
1932                },
1933                Mode::Savepoint => {
1934                    let updates = updates.into_iter().map(|(kind, diff)| StateUpdate {
1935                        kind,
1936                        ts: commit_ts,
1937                        diff,
1938                    });
1939                    catalog.apply_updates_and_consolidate(updates)?;
1940                    catalog.upper = commit_ts.step_forward();
1941                    catalog.upper
1942                }
1943                Mode::Readonly => unreachable!("handled above"),
1944            };
1945
1946            Ok(next_upper)
1947        }
1948        self.metrics.transaction_commits.inc();
1949        let histogram = self.metrics.transaction_commit_latency_seconds.clone();
1950        commit_transaction_inner(self, txn_batch, commit_ts)
1951            .wall_time()
1952            .observe(histogram)
1953            .await
1954    }
1955
1956    #[mz_ore::instrument(level = "debug")]
1957    async fn advance_upper(&mut self, new_upper: Timestamp) -> Result<(), CatalogError> {
1958        loop {
1959            if self.upper >= new_upper {
1960                // This does not consult Persist. It only revalidates a fence already cached by
1961                // this handle, since a sync can advance `upper` while recording the fence.
1962                self.fenceable_token.validate()?;
1963                return Ok(());
1964            }
1965
1966            match self.mode {
1967                Mode::Writable => {}
1968                Mode::Savepoint => {
1969                    self.upper = new_upper;
1970                    return Ok(());
1971                }
1972                Mode::Readonly => {
1973                    return Err(DurableCatalogError::NotWritable(
1974                        "cannot advance upper of a read-only catalog".into(),
1975                    )
1976                    .into());
1977                }
1978            }
1979
1980            let updates_applied_before = self.updates_applied;
1981            match self.compare_and_append_inner([], new_upper).await {
1982                Ok(()) => {
1983                    self.upper = new_upper;
1984                    // No sync needed since no data was written.
1985                    return Ok(());
1986                }
1987                Err(CompareAndAppendError::Fence(e)) => return Err(e.into()),
1988                Err(CompareAndAppendError::UpperMismatch { actual_upper, .. }) => {
1989                    // The mismatch synchronized the handle. Retry only if it applied no content.
1990                    self.classify_upper_mismatch(updates_applied_before, actual_upper)?;
1991                }
1992            }
1993        }
1994    }
1995
1996    fn shard_id(&self) -> ShardId {
1997        self.shard_id
1998    }
1999}
2000
2001/// Deterministically generate a shard ID for the given `organization_id` and `seed`.
2002pub fn shard_id(organization_id: Uuid, seed: usize) -> ShardId {
2003    let hash = sha2::Sha256::digest(format!("{organization_id}{seed}")).to_vec();
2004    soft_assert_eq_or_log!(hash.len(), 32, "SHA256 returns 32 bytes (256 bits)");
2005    let uuid = Uuid::from_slice(&hash[0..16]).expect("from_slice accepts exactly 16 bytes");
2006    ShardId::from_str(&format!("s{uuid}")).expect("known to be valid")
2007}
2008
2009/// Generates a timestamp for reading from `read_handle` that is as fresh as possible, given
2010/// `upper`.
2011fn as_of(
2012    read_handle: &ReadHandle<SourceData, (), Timestamp, StorageDiff>,
2013    upper: Timestamp,
2014) -> Timestamp {
2015    let since = read_handle.since().clone();
2016    let mut as_of = upper.checked_sub(1).unwrap_or_else(|| {
2017        panic!("catalog persist shard should be initialize, found upper: {upper:?}")
2018    });
2019    // We only downgrade the since after writing, and we always set the since to one less than the
2020    // upper.
2021    soft_assert_or_log!(
2022        since.less_equal(&as_of),
2023        "since={since:?}, as_of={as_of:?}; since must be less than or equal to as_of"
2024    );
2025    // This should be a no-op if the assert above passes, however if it doesn't then we'd like to
2026    // continue with a correct timestamp instead of entering a panic loop.
2027    as_of.advance_by(since.borrow());
2028    as_of
2029}
2030
2031/// Fetch the persist version of the catalog shard, if one exists. A version will not
2032/// exist if we are creating a brand-new environment.
2033async fn fetch_catalog_shard_version(
2034    persist_client: &PersistClient,
2035    catalog_shard_id: ShardId,
2036) -> Option<semver::Version> {
2037    let shard_state = persist_client
2038        .inspect_shard::<Timestamp>(&catalog_shard_id)
2039        .await
2040        .ok()?;
2041    let json_state = serde_json::to_value(shard_state).expect("state serialization error");
2042    let json_version = json_state
2043        .get("applier_version")
2044        .cloned()
2045        .expect("missing applier_version");
2046    let version = serde_json::from_value(json_version).expect("version deserialization error");
2047    Some(version)
2048}
2049
2050/// Generates an iterator of [`StateUpdate`] that contain all updates to the catalog
2051/// state up to, and including, `as_of`.
2052///
2053/// The output is consolidated and sorted by timestamp in ascending order.
2054#[mz_ore::instrument(level = "debug")]
2055async fn snapshot_binary(
2056    read_handle: &mut ReadHandle<SourceData, (), Timestamp, StorageDiff>,
2057    as_of: Timestamp,
2058    metrics: &Arc<Metrics>,
2059) -> impl Iterator<Item = StateUpdate<StateUpdateKindJson>> + DoubleEndedIterator + use<> {
2060    metrics.snapshots_taken.inc();
2061    let histogram = metrics.snapshot_latency_seconds.clone();
2062    snapshot_binary_inner(read_handle, as_of)
2063        .wall_time()
2064        .observe(histogram)
2065        .await
2066}
2067
2068/// Generates an iterator of [`StateUpdate`] that contain all updates to the catalog
2069/// state up to, and including, `as_of`.
2070///
2071/// The output is consolidated and sorted by timestamp in ascending order.
2072#[mz_ore::instrument(level = "debug")]
2073async fn snapshot_binary_inner(
2074    read_handle: &mut ReadHandle<SourceData, (), Timestamp, StorageDiff>,
2075    as_of: Timestamp,
2076) -> impl Iterator<Item = StateUpdate<StateUpdateKindJson>> + DoubleEndedIterator + use<> {
2077    let snapshot = read_handle
2078        .snapshot_and_fetch(Antichain::from_elem(as_of))
2079        .await
2080        .expect("we have advanced the restart_as_of by the since");
2081    soft_assert_no_log!(
2082        snapshot.iter().all(|(_, _, diff)| *diff == 1),
2083        "snapshot_and_fetch guarantees a consolidated result: {snapshot:#?}"
2084    );
2085    snapshot
2086        .into_iter()
2087        .map(Into::<StateUpdate<StateUpdateKindJson>>::into)
2088        .sorted_by(|a, b| Ord::cmp(&b.ts, &a.ts))
2089}
2090
2091/// Convert an [`Antichain<Timestamp>`] to a [`Timestamp`].
2092///
2093/// The correctness of this function relies on [`Timestamp`] being totally ordered and never
2094/// finalizing the catalog shard.
2095pub(crate) fn antichain_to_timestamp(antichain: Antichain<Timestamp>) -> Timestamp {
2096    antichain
2097        .into_option()
2098        .expect("we use a totally ordered time and never finalize the shard")
2099}
2100
2101// Debug methods used by the catalog-debug tool.
2102
2103impl Trace {
2104    /// Generates a [`Trace`] from snapshot.
2105    fn from_snapshot(snapshot: impl IntoIterator<Item = StateUpdate>) -> Trace {
2106        let mut trace = Trace::new();
2107        for StateUpdate { kind, ts, diff } in snapshot {
2108            match kind {
2109                StateUpdateKind::AuditLog(k, v) => trace.audit_log.values.push(((k, v), ts, diff)),
2110                StateUpdateKind::Cluster(k, v) => trace.clusters.values.push(((k, v), ts, diff)),
2111                StateUpdateKind::ClusterReplica(k, v) => {
2112                    trace.cluster_replicas.values.push(((k, v), ts, diff))
2113                }
2114                StateUpdateKind::Comment(k, v) => trace.comments.values.push(((k, v), ts, diff)),
2115                StateUpdateKind::Config(k, v) => trace.configs.values.push(((k, v), ts, diff)),
2116                StateUpdateKind::Database(k, v) => trace.databases.values.push(((k, v), ts, diff)),
2117                StateUpdateKind::DefaultPrivilege(k, v) => {
2118                    trace.default_privileges.values.push(((k, v), ts, diff))
2119                }
2120                StateUpdateKind::FenceToken(_) => {
2121                    // Fence token not included in trace.
2122                }
2123                StateUpdateKind::IdAllocator(k, v) => {
2124                    trace.id_allocator.values.push(((k, v), ts, diff))
2125                }
2126                StateUpdateKind::IntrospectionSourceIndex(k, v) => {
2127                    trace.introspection_sources.values.push(((k, v), ts, diff))
2128                }
2129                StateUpdateKind::Item(k, v) => trace.items.values.push(((k, v), ts, diff)),
2130                StateUpdateKind::NetworkPolicy(k, v) => {
2131                    trace.network_policies.values.push(((k, v), ts, diff))
2132                }
2133                StateUpdateKind::Role(k, v) => trace.roles.values.push(((k, v), ts, diff)),
2134                StateUpdateKind::Schema(k, v) => trace.schemas.values.push(((k, v), ts, diff)),
2135                StateUpdateKind::Setting(k, v) => trace.settings.values.push(((k, v), ts, diff)),
2136                StateUpdateKind::SourceReferences(k, v) => {
2137                    trace.source_references.values.push(((k, v), ts, diff))
2138                }
2139                StateUpdateKind::SystemConfiguration(k, v) => {
2140                    trace.system_configurations.values.push(((k, v), ts, diff))
2141                }
2142                StateUpdateKind::ClusterSystemConfiguration(k, v) => trace
2143                    .cluster_system_configurations
2144                    .values
2145                    .push(((k, v), ts, diff)),
2146                StateUpdateKind::ReplicaSystemConfiguration(k, v) => trace
2147                    .replica_system_configurations
2148                    .values
2149                    .push(((k, v), ts, diff)),
2150                StateUpdateKind::SystemObjectMapping(k, v) => {
2151                    trace.system_object_mappings.values.push(((k, v), ts, diff))
2152                }
2153                StateUpdateKind::SystemPrivilege(k, v) => {
2154                    trace.system_privileges.values.push(((k, v), ts, diff))
2155                }
2156                StateUpdateKind::StorageCollectionMetadata(k, v) => trace
2157                    .storage_collection_metadata
2158                    .values
2159                    .push(((k, v), ts, diff)),
2160                StateUpdateKind::UnfinalizedShard(k, ()) => {
2161                    trace.unfinalized_shards.values.push(((k, ()), ts, diff))
2162                }
2163                StateUpdateKind::TxnWalShard((), v) => {
2164                    trace.txn_wal_shard.values.push((((), v), ts, diff))
2165                }
2166                StateUpdateKind::RoleAuth(k, v) => trace.role_auth.values.push(((k, v), ts, diff)),
2167            }
2168        }
2169        trace
2170    }
2171}
2172
2173impl UnopenedPersistCatalogState {
2174    /// Manually update value of `key` in collection `T` to `value`.
2175    #[mz_ore::instrument]
2176    pub(crate) async fn debug_edit<T: Collection>(
2177        &mut self,
2178        key: T::Key,
2179        value: T::Value,
2180    ) -> Result<Option<T::Value>, CatalogError>
2181    where
2182        T::Key: PartialEq + Eq + Debug + Clone,
2183        T::Value: Debug + Clone,
2184    {
2185        let prev_value = loop {
2186            let key = key.clone();
2187            let value = value.clone();
2188            let snapshot = self.current_snapshot().await?;
2189            let trace = Trace::from_snapshot(snapshot);
2190            let collection_trace = T::collection_trace(trace);
2191            let prev_values: Vec<_> = collection_trace
2192                .values
2193                .into_iter()
2194                .filter(|((k, _), _, diff)| {
2195                    soft_assert_eq_or_log!(*diff, Diff::ONE, "trace is consolidated");
2196                    &key == k
2197                })
2198                .collect();
2199
2200            let prev_value = match &prev_values[..] {
2201                [] => None,
2202                [((_, v), _, _)] => Some(v.clone()),
2203                prev_values => panic!("multiple values found for key {key:?}: {prev_values:?}"),
2204            };
2205
2206            let mut updates: Vec<_> = prev_values
2207                .into_iter()
2208                .map(|((k, v), _, _)| (T::update(k, v), Diff::MINUS_ONE))
2209                .collect();
2210            updates.push((T::update(key, value), Diff::ONE));
2211            // We must fence out all other catalogs, if we haven't already, since we are writing.
2212            match self.fenceable_token.generate_unfenced_token(self.mode)? {
2213                Some((fence_updates, current_fenceable_token)) => {
2214                    updates.extend(fence_updates.clone());
2215                    match self.compare_and_append(updates, self.upper).await {
2216                        Ok(_) => {
2217                            self.fenceable_token = current_fenceable_token;
2218                            break prev_value;
2219                        }
2220                        Err(CompareAndAppendError::Fence(e)) => return Err(e.into()),
2221                        Err(e @ CompareAndAppendError::UpperMismatch { .. }) => {
2222                            warn!("catalog write failed due to upper mismatch, retrying: {e:?}");
2223                            continue;
2224                        }
2225                    }
2226                }
2227                None => {
2228                    self.compare_and_append(updates, self.upper)
2229                        .await
2230                        .map_err(|e| e.unwrap_fence_error())?;
2231                    break prev_value;
2232                }
2233            }
2234        };
2235        Ok(prev_value)
2236    }
2237
2238    /// Manually delete `key` from collection `T`.
2239    #[mz_ore::instrument]
2240    pub(crate) async fn debug_delete<T: Collection>(
2241        &mut self,
2242        key: T::Key,
2243    ) -> Result<(), CatalogError>
2244    where
2245        T::Key: PartialEq + Eq + Debug + Clone,
2246        T::Value: Debug,
2247    {
2248        loop {
2249            let key = key.clone();
2250            let snapshot = self.current_snapshot().await?;
2251            let trace = Trace::from_snapshot(snapshot);
2252            let collection_trace = T::collection_trace(trace);
2253            let mut retractions: Vec<_> = collection_trace
2254                .values
2255                .into_iter()
2256                .filter(|((k, _), _, diff)| {
2257                    soft_assert_eq_or_log!(*diff, Diff::ONE, "trace is consolidated");
2258                    &key == k
2259                })
2260                .map(|((k, v), _, _)| (T::update(k, v), Diff::MINUS_ONE))
2261                .collect();
2262
2263            // We must fence out all other catalogs, if we haven't already, since we are writing.
2264            match self.fenceable_token.generate_unfenced_token(self.mode)? {
2265                Some((fence_updates, current_fenceable_token)) => {
2266                    retractions.extend(fence_updates.clone());
2267                    match self.compare_and_append(retractions, self.upper).await {
2268                        Ok(_) => {
2269                            self.fenceable_token = current_fenceable_token;
2270                            break;
2271                        }
2272                        Err(CompareAndAppendError::Fence(e)) => return Err(e.into()),
2273                        Err(e @ CompareAndAppendError::UpperMismatch { .. }) => {
2274                            warn!("catalog write failed due to upper mismatch, retrying: {e:?}");
2275                            continue;
2276                        }
2277                    }
2278                }
2279                None => {
2280                    self.compare_and_append(retractions, self.upper)
2281                        .await
2282                        .map_err(|e| e.unwrap_fence_error())?;
2283                    break;
2284                }
2285            }
2286        }
2287        Ok(())
2288    }
2289
2290    /// Generates a [`Vec<StateUpdate>`] that contain all updates to the catalog
2291    /// state.
2292    ///
2293    /// The output is consolidated and sorted by timestamp in ascending order and the current upper.
2294    async fn current_snapshot(
2295        &mut self,
2296    ) -> Result<impl IntoIterator<Item = StateUpdate> + '_, CatalogError> {
2297        self.sync_to_current_upper().await?;
2298        self.consolidate();
2299        Ok(self.snapshot.iter().cloned().map(|(kind, ts, diff)| {
2300            let kind = TryIntoStateUpdateKind::try_into(kind).expect("kind decoding error");
2301            StateUpdate { kind, ts, diff }
2302        }))
2303    }
2304}