Skip to main content

mz_catalog/
durable.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//! This crate is responsible for durably storing and modifying the catalog contents.
11
12use std::fmt::Debug;
13use std::num::NonZeroI64;
14use std::sync::Arc;
15use std::time::Duration;
16
17use async_trait::async_trait;
18use mz_audit_log::VersionedEvent;
19use mz_controller_types::{ClusterId, ReplicaId};
20use mz_ore::collections::CollectionExt;
21use mz_ore::metrics::MetricsRegistry;
22use mz_persist_client::PersistClient;
23use mz_persist_types::ShardId;
24use mz_repr::{CatalogItemId, GlobalId, RelationDesc, SqlScalarType};
25use mz_sql::catalog::CatalogError as SqlCatalogError;
26use uuid::Uuid;
27
28use crate::config::ClusterReplicaSizeMap;
29use crate::durable::debug::{DebugCatalogState, Trace};
30pub use crate::durable::error::{CatalogError, DurableCatalogError, FenceError};
31pub use crate::durable::metrics::Metrics;
32pub use crate::durable::objects::Snapshot;
33pub use crate::durable::objects::state_update::StateUpdate;
34pub use crate::durable::objects::{
35    BurstState, Cluster, ClusterConfig, ClusterReplica, ClusterReplicaSize,
36    ClusterSystemConfiguration, ClusterVariant, ClusterVariantManaged, Comment, Database,
37    DefaultPrivilege, IndexColumn, IndexColumns, IntrospectionSourceIndex, Item, ItemColumn,
38    ItemColumns, ItemMetadata, NetworkPolicy, QueryPolicy, ReconfigurationState,
39    ReconfigurationStatus, ReconfigurationTarget, ReplicaConfig, ReplicaLocation,
40    ReplicaSystemConfiguration, Role, RoleAuth, Schema, SourceReference, SourceReferences,
41    StorageCollectionMetadata, SystemConfiguration, SystemObjectDescription, SystemObjectMapping,
42    UnfinalizedShard, managed_cluster_replica_name,
43};
44pub use crate::durable::persist::shard_id;
45use crate::durable::persist::{Timestamp, UnopenedPersistCatalogState};
46use crate::durable::transaction::TransactionBatch;
47pub use crate::durable::transaction::{DryRunTransaction, Transaction};
48pub use crate::durable::upgrade::CATALOG_VERSION;
49use crate::memory;
50
51pub mod debug;
52mod error;
53pub mod initialize;
54mod metrics;
55pub mod objects;
56mod persist;
57mod traits;
58mod transaction;
59mod upgrade;
60
61pub const DATABASE_ID_ALLOC_KEY: &str = "database";
62pub const SCHEMA_ID_ALLOC_KEY: &str = "schema";
63pub const USER_ITEM_ALLOC_KEY: &str = "user";
64pub const SYSTEM_ITEM_ALLOC_KEY: &str = "system";
65pub const USER_ROLE_ID_ALLOC_KEY: &str = "user_role";
66pub const USER_CLUSTER_ID_ALLOC_KEY: &str = "user_compute";
67pub const SYSTEM_CLUSTER_ID_ALLOC_KEY: &str = "system_compute";
68pub const USER_REPLICA_ID_ALLOC_KEY: &str = "replica";
69pub const SYSTEM_REPLICA_ID_ALLOC_KEY: &str = "system_replica";
70pub const AUDIT_LOG_ID_ALLOC_KEY: &str = "auditlog";
71pub const STORAGE_USAGE_ID_ALLOC_KEY: &str = "storage_usage";
72pub const USER_NETWORK_POLICY_ID_ALLOC_KEY: &str = "user_network_policy";
73pub const USER_CLUSTER_REPLICA_SIZE_ID_ALLOC_KEY: &str = "user_cluster_replica_size";
74pub const SYSTEM_CLUSTER_REPLICA_SIZE_ID_ALLOC_KEY: &str = "system_cluster_replica_size";
75pub const USER_QUERY_POLICY_ID_ALLOC_KEY: &str = "user_query_policy";
76pub const OID_ALLOC_KEY: &str = "oid";
77pub(crate) const CATALOG_CONTENT_VERSION_KEY: &str = "catalog_content_version";
78pub const BUILTIN_MIGRATION_SHARD_KEY: &str = "builtin_migration_shard";
79pub const EXPRESSION_CACHE_SHARD_KEY: &str = "expression_cache_shard";
80pub const MOCK_AUTHENTICATION_NONCE_KEY: &str = "mock_authentication_nonce";
81
82#[derive(Clone, Debug)]
83pub struct BootstrapArgs {
84    pub cluster_replica_size_map: ClusterReplicaSizeMap,
85    pub default_cluster_replica_size: String,
86    pub default_cluster_replication_factor: u32,
87    pub bootstrap_role: Option<String>,
88    /// Testing only: every open that runs migrations also applies an empty migration.
89    pub force_catalog_migration: bool,
90}
91
92pub type Epoch = NonZeroI64;
93
94/// An API for opening a durable catalog state.
95///
96/// If a catalog is not opened, then resources should be release via [`Self::expire`].
97#[async_trait]
98pub trait OpenableDurableCatalogState: Debug + Send {
99    // TODO(jkosh44) Teaching savepoint mode how to listen to additional
100    // durable updates will be necessary for zero down time upgrades.
101    /// Opens the catalog in a mode that accepts and buffers all writes,
102    /// but never durably commits them. This is used to check and see if
103    /// opening the catalog would be successful, without making any durable
104    /// changes.
105    ///
106    /// Once a savepoint catalog reads an initial snapshot from durable
107    /// storage, it will never read another update from durable storage. As a
108    /// consequence, savepoint catalogs can never be fenced.
109    ///
110    /// Will return an error in the following scenarios:
111    ///   - Catalog initialization fails.
112    ///   - Catalog migrations fail.
113    ///
114    /// `initial_ts` is used as the initial timestamp for new environments.
115    async fn open_savepoint(
116        mut self: Box<Self>,
117        initial_ts: Timestamp,
118        bootstrap_args: &BootstrapArgs,
119    ) -> Result<Box<dyn DurableCatalogState>, CatalogError>;
120
121    /// Opens the catalog in read only mode. All mutating methods
122    /// will return an error.
123    ///
124    /// If the catalog is uninitialized or requires a migrations, then
125    /// it will fail to open in read only mode.
126    async fn open_read_only(
127        mut self: Box<Self>,
128        bootstrap_args: &BootstrapArgs,
129    ) -> Result<Box<dyn DurableCatalogState>, CatalogError>;
130
131    /// Opens the catalog in a writeable mode. Optionally initializes the
132    /// catalog, if it has not been initialized, and perform any migrations
133    /// needed.
134    ///
135    /// `initial_ts` is used as the initial timestamp for new environments.
136    async fn open(
137        mut self: Box<Self>,
138        initial_ts: Timestamp,
139        bootstrap_args: &BootstrapArgs,
140    ) -> Result<Box<dyn DurableCatalogState>, CatalogError>;
141
142    /// Opens the catalog for manual editing of the underlying data. This is helpful for
143    /// fixing a corrupt catalog.
144    async fn open_debug(mut self: Box<Self>) -> Result<DebugCatalogState, CatalogError>;
145
146    /// Reports if the catalog state has been initialized.
147    async fn is_initialized(&mut self) -> Result<bool, CatalogError>;
148
149    /// Returns the epoch of the current durable catalog state. The epoch acts as
150    /// a fencing token to prevent split brain issues across two
151    /// [`DurableCatalogState`]s. When a new [`DurableCatalogState`] opens the
152    /// catalog, it will increment the epoch by one (or initialize it to some
153    /// value if there's no existing epoch) and store the value in memory. It's
154    /// guaranteed that no two [`DurableCatalogState`]s will return the same value
155    /// for their epoch.
156    ///
157    /// NB: We may remove this in later iterations of Pv2.
158    async fn epoch(&mut self) -> Result<Epoch, CatalogError>;
159
160    /// Get the most recent deployment generation written to the catalog. Not necessarily the
161    /// deploy generation of this instance.
162    async fn get_deployment_generation(&mut self) -> Result<u64, CatalogError>;
163
164    /// Get the `with_0dt_deployment_max_wait` config value of this instance.
165    ///
166    /// This mirrors the `with_0dt_deployment_max_wait` "system var" so that we can
167    /// toggle the flag with LaunchDarkly, but use it in boot before
168    /// LaunchDarkly is available.
169    async fn get_0dt_deployment_max_wait(&mut self) -> Result<Option<Duration>, CatalogError>;
170
171    /// Get the `with_0dt_deployment_ddl_check_interval` config value of this instance.
172    ///
173    /// This mirrors the `with_0dt_deployment_ddl_check_interval` "system var" so that we can
174    /// toggle the flag with LaunchDarkly, but use it in boot before
175    /// LaunchDarkly is available.
176    async fn get_0dt_deployment_ddl_check_interval(
177        &mut self,
178    ) -> Result<Option<Duration>, CatalogError>;
179
180    /// Get the `enable_0dt_deployment_panic_after_timeout` config value of this
181    /// instance.
182    ///
183    /// This mirrors the `enable_0dt_deployment_panic_after_timeout` "system var"
184    /// so that we can toggle the flag with LaunchDarkly, but use it in boot
185    /// before LaunchDarkly is available.
186    async fn get_enable_0dt_deployment_panic_after_timeout(
187        &mut self,
188    ) -> Result<Option<bool>, CatalogError>;
189
190    /// Reports if the remote configuration was synchronized at least once.
191    async fn has_system_config_synced_once(&mut self) -> Result<bool, DurableCatalogError>;
192
193    /// Generate an unconsolidated [`Trace`] of catalog contents.
194    async fn trace_unconsolidated(&mut self) -> Result<Trace, CatalogError>;
195
196    /// Generate a consolidated [`Trace`] of catalog contents.
197    async fn trace_consolidated(&mut self) -> Result<Trace, CatalogError>;
198
199    /// Politely releases all external resources that can only be released in an async context.
200    async fn expire(self: Box<Self>);
201}
202
203/// A read only API for the durable catalog state.
204#[async_trait]
205pub trait ReadOnlyDurableCatalogState: Debug + Send + Sync {
206    /// Returns the epoch of the current durable catalog state. The epoch acts as
207    /// a fencing token to prevent split brain issues across two
208    /// [`DurableCatalogState`]s. When a new [`DurableCatalogState`] opens the
209    /// catalog, it will increment the epoch by one (or initialize it to some
210    /// value if there's no existing epoch) and store the value in memory. It's
211    /// guaranteed that no two [`DurableCatalogState`]s will return the same value
212    /// for their epoch.
213    ///
214    /// NB: We may remove this in later iterations of Pv2.
215    fn epoch(&self) -> Epoch;
216
217    /// Returns the metrics for this catalog state.
218    fn metrics(&self) -> &Metrics;
219
220    /// Politely releases all external resources that can only be released in an async context.
221    async fn expire(self: Box<Self>);
222
223    /// Returns true if the system bootstrapping process is complete, false otherwise.
224    fn is_bootstrap_complete(&self) -> bool;
225
226    /// Get all audit log events.
227    ///
228    /// Results are guaranteed to be sorted by ID.
229    ///
230    /// WARNING: This is meant for use in integration tests and has bad performance.
231    async fn get_audit_logs(&mut self) -> Result<Vec<VersionedEvent>, CatalogError>;
232
233    /// Get the next ID of `id_type`, without allocating it.
234    async fn get_next_id(&mut self, id_type: &str) -> Result<u64, CatalogError>;
235
236    /// Get the next user ID without allocating it.
237    async fn get_next_user_item_id(&mut self) -> Result<u64, CatalogError> {
238        self.get_next_id(USER_ITEM_ALLOC_KEY).await
239    }
240
241    /// Get the next system ID without allocating it.
242    async fn get_next_system_item_id(&mut self) -> Result<u64, CatalogError> {
243        self.get_next_id(SYSTEM_ITEM_ALLOC_KEY).await
244    }
245
246    /// Get the next system replica id without allocating it.
247    async fn get_next_system_replica_id(&mut self) -> Result<u64, CatalogError> {
248        self.get_next_id(SYSTEM_REPLICA_ID_ALLOC_KEY).await
249    }
250
251    /// Get the next user replica id without allocating it.
252    async fn get_next_user_replica_id(&mut self) -> Result<u64, CatalogError> {
253        self.get_next_id(USER_REPLICA_ID_ALLOC_KEY).await
254    }
255
256    /// Get the deployment generation of this instance.
257    async fn get_deployment_generation(&mut self) -> Result<u64, CatalogError>;
258
259    /// Get a snapshot of the catalog.
260    async fn snapshot(&mut self) -> Result<Snapshot, CatalogError>;
261
262    /// Listen and return all updates that are currently in the catalog.
263    ///
264    /// IMPORTANT: This excludes updates to storage usage.
265    ///
266    /// Returns an error if this instance has been fenced out.
267    async fn sync_to_current_updates(
268        &mut self,
269    ) -> Result<Vec<memory::objects::StateUpdate>, CatalogError>;
270
271    // TODO(jkosh44) The fact that the timestamp argument is an exclusive upper bound makes
272    // it difficult to use for readers. For now it's correct and easy to implement, but we should
273    // consider a better API.
274    /// Listen and return all updates in the catalog up to `target_upper`.
275    ///
276    /// IMPORTANT: This excludes updates to storage usage.
277    ///
278    /// Returns an error if this instance has been fenced out.
279    async fn sync_updates(
280        &mut self,
281        target_upper: Timestamp,
282    ) -> Result<Vec<memory::objects::StateUpdate>, CatalogError>;
283
284    /// Checks for unapplied catalog content before `target_upper` without consuming it.
285    ///
286    /// Returns an error if this instance has been fenced out.
287    async fn ensure_not_out_of_sync(&mut self, target_upper: Timestamp)
288    -> Result<(), CatalogError>;
289
290    /// Fetch the current upper of the catalog state.
291    async fn current_upper(&mut self) -> Timestamp;
292}
293
294/// A read-write API for the durable catalog state.
295#[async_trait]
296#[allow(mismatched_lifetime_syntaxes)]
297pub trait DurableCatalogState: ReadOnlyDurableCatalogState {
298    /// Returns true if the catalog is opened in read only mode, false otherwise.
299    fn is_read_only(&self) -> bool;
300
301    /// Returns true if the catalog is opened is savepoint mode, false otherwise.
302    fn is_savepoint(&self) -> bool;
303
304    /// Marks the bootstrap process as complete.
305    async fn mark_bootstrap_complete(&mut self);
306
307    /// Creates a transaction only if no durable catalog content is pending.
308    ///
309    /// Empty upper progress is accepted.
310    async fn transaction(&mut self) -> Result<Transaction, CatalogError>;
311
312    /// Creates a non-committable dry-run transaction from the given [`Snapshot`].
313    ///
314    /// The snapshot may include changes accumulated by earlier incremental dry runs.
315    fn transaction_from_snapshot(
316        &mut self,
317        snapshot: Snapshot,
318    ) -> Result<DryRunTransaction, CatalogError>;
319
320    /// Commits a durable catalog state transaction. The transaction will be committed at
321    /// `commit_ts`.
322    ///
323    /// Returns what the upper was directly after the transaction committed.
324    ///
325    /// Panics if `commit_ts` is not greater than or equal to the most recent upper seen by this
326    /// process.
327    async fn commit_transaction(
328        &mut self,
329        txn_batch: TransactionBatch,
330        commit_ts: Timestamp,
331    ) -> Result<Timestamp, CatalogError>;
332
333    /// Advances the catalog upper to at least `new_upper`.
334    ///
335    /// A durable attempt observes fencing and reports concurrent non-fencing content as
336    /// [`DurableCatalogError::CatalogOutOfSync`]. A no-op only validates a fence already observed
337    /// by this handle.
338    async fn advance_upper(&mut self, new_upper: Timestamp) -> Result<(), CatalogError>;
339
340    /// Allocates and returns `amount` IDs of `id_type`.
341    ///
342    /// Allocation rebases over empty upper progress. Fresh IDs do not require a catalog
343    /// staleness check.
344    async fn allocate_id(
345        &mut self,
346        id_type: &str,
347        amount: u64,
348        commit_ts: Timestamp,
349    ) -> Result<Vec<u64>, CatalogError>;
350
351    /// Allocates and returns `amount` many user [`CatalogItemId`] and [`GlobalId`].
352    ///
353    /// See [`Self::commit_transaction`] for details on `commit_ts`.
354    async fn allocate_user_ids(
355        &mut self,
356        amount: u64,
357        commit_ts: Timestamp,
358    ) -> Result<Vec<(CatalogItemId, GlobalId)>, CatalogError> {
359        let ids = self
360            .allocate_id(USER_ITEM_ALLOC_KEY, amount, commit_ts)
361            .await?;
362        let ids = ids
363            .iter()
364            .map(|id| (CatalogItemId::User(*id), GlobalId::User(*id)))
365            .collect();
366        Ok(ids)
367    }
368
369    /// Allocates and returns both a user [`CatalogItemId`] and [`GlobalId`].
370    ///
371    /// See [`Self::commit_transaction`] for details on `commit_ts`.
372    async fn allocate_user_id(
373        &mut self,
374        commit_ts: Timestamp,
375    ) -> Result<(CatalogItemId, GlobalId), CatalogError> {
376        let id = self.allocate_id(USER_ITEM_ALLOC_KEY, 1, commit_ts).await?;
377        let id = id.into_element();
378        Ok((CatalogItemId::User(id), GlobalId::User(id)))
379    }
380
381    /// Allocates and returns a user [`ClusterId`].
382    ///
383    /// See [`Self::commit_transaction`] for details on `commit_ts`.
384    async fn allocate_user_cluster_id(
385        &mut self,
386        commit_ts: Timestamp,
387    ) -> Result<ClusterId, CatalogError> {
388        let id = self
389            .allocate_id(USER_CLUSTER_ID_ALLOC_KEY, 1, commit_ts)
390            .await?
391            .into_element();
392        Ok(ClusterId::user(id).ok_or(SqlCatalogError::IdExhaustion)?)
393    }
394
395    /// Allocates and returns `amount` many user [`ReplicaId`]s.
396    ///
397    /// See [`Self::commit_transaction`] for details on `commit_ts`.
398    async fn allocate_user_replica_ids(
399        &mut self,
400        amount: u64,
401        commit_ts: Timestamp,
402    ) -> Result<Vec<ReplicaId>, CatalogError> {
403        let ids = self
404            .allocate_id(USER_REPLICA_ID_ALLOC_KEY, amount, commit_ts)
405            .await?;
406        let ids = ids.into_iter().map(ReplicaId::User).collect();
407        Ok(ids)
408    }
409
410    /// Allocates and returns `amount` many system [`ReplicaId`]s.
411    ///
412    /// See [`Self::commit_transaction`] for details on `commit_ts`.
413    async fn allocate_system_replica_ids(
414        &mut self,
415        amount: u64,
416        commit_ts: Timestamp,
417    ) -> Result<Vec<ReplicaId>, CatalogError> {
418        let ids = self
419            .allocate_id(SYSTEM_REPLICA_ID_ALLOC_KEY, amount, commit_ts)
420            .await?;
421        let ids = ids.into_iter().map(ReplicaId::System).collect();
422        Ok(ids)
423    }
424
425    fn shard_id(&self) -> ShardId;
426}
427
428/// Returns the schema of the `Row`s/`SourceData`s stored in the persist
429/// shard backing the catalog.
430pub fn persist_desc() -> RelationDesc {
431    RelationDesc::builder()
432        .with_column("data", SqlScalarType::Jsonb.nullable(false))
433        .finish()
434}
435
436/// A builder to help create an [`OpenableDurableCatalogState`] for tests.
437#[derive(Debug, Clone)]
438pub struct TestCatalogStateBuilder {
439    persist_client: PersistClient,
440    organization_id: Uuid,
441    version: semver::Version,
442    deploy_generation: Option<u64>,
443    metrics: Arc<Metrics>,
444}
445
446impl TestCatalogStateBuilder {
447    pub fn new(persist_client: PersistClient) -> Self {
448        Self {
449            persist_client,
450            organization_id: Uuid::new_v4(),
451            version: semver::Version::new(0, 0, 0),
452            deploy_generation: None,
453            metrics: Arc::new(Metrics::new(&MetricsRegistry::new())),
454        }
455    }
456
457    pub fn with_organization_id(mut self, organization_id: Uuid) -> Self {
458        self.organization_id = organization_id;
459        self
460    }
461
462    pub fn with_version(mut self, version: semver::Version) -> Self {
463        self.version = version;
464        self
465    }
466
467    pub fn with_deploy_generation(mut self, deploy_generation: u64) -> Self {
468        self.deploy_generation = Some(deploy_generation);
469        self
470    }
471
472    pub fn with_default_deploy_generation(self) -> Self {
473        self.with_deploy_generation(0)
474    }
475
476    pub fn with_metrics(mut self, metrics: Arc<Metrics>) -> Self {
477        self.metrics = metrics;
478        self
479    }
480
481    pub async fn build(self) -> Result<Box<dyn OpenableDurableCatalogState>, DurableCatalogError> {
482        persist_backed_catalog_state(
483            self.persist_client,
484            self.organization_id,
485            self.version,
486            self.deploy_generation,
487            self.metrics,
488        )
489        .await
490    }
491
492    pub async fn unwrap_build(self) -> Box<dyn OpenableDurableCatalogState> {
493        self.expect_build("failed to build").await
494    }
495
496    pub async fn expect_build(self, msg: &str) -> Box<dyn OpenableDurableCatalogState> {
497        self.build().await.expect(msg)
498    }
499}
500
501/// Creates an openable durable catalog state implemented using persist.
502///
503/// `deploy_generation` MUST be `Some` to initialize a new catalog.
504pub async fn persist_backed_catalog_state(
505    persist_client: PersistClient,
506    organization_id: Uuid,
507    version: semver::Version,
508    deploy_generation: Option<u64>,
509    metrics: Arc<Metrics>,
510) -> Result<Box<dyn OpenableDurableCatalogState>, DurableCatalogError> {
511    let state = UnopenedPersistCatalogState::new(
512        persist_client,
513        organization_id,
514        version,
515        deploy_generation,
516        metrics,
517    )
518    .await?;
519    Ok(Box::new(state))
520}
521
522pub fn test_bootstrap_args() -> BootstrapArgs {
523    BootstrapArgs {
524        default_cluster_replica_size: "scale=1,workers=1".into(),
525        default_cluster_replication_factor: 1,
526        bootstrap_role: None,
527        cluster_replica_size_map: ClusterReplicaSizeMap::for_tests(),
528        force_catalog_migration: false,
529    }
530}