mz_catalog/durable/
upgrade.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 module contains all the helpers and code paths for upgrading/migrating the `Catalog`.
11//!
12//! We facilitate migrations by keeping snapshots of the objects we previously stored, and relying
13//! entirely on these snapshots. These snapshots exist in the [`mz_catalog_protos`] crate in the
14//! form of `catalog-protos/protos/objects_vXX.proto`. By maintaining and relying on snapshots we
15//! don't have to worry about changes elsewhere in the codebase effecting our migrations because
16//! our application and serialization logic is decoupled, and the objects of the Catalog for a
17//! given version are "frozen in time".
18//!
19//! > **Note**: The protobuf snapshot files themselves live in a separate crate because it takes a
20//!             relatively significant amount of time to codegen and build them. By placing them in
21//!             a separate crate we don't have to pay this compile time cost when building the
22//!             catalog, allowing for faster iteration.
23//!
24//! You cannot make any changes to the following message or anything that they depend on:
25//!
26//!   - Config
27//!   - Setting
28//!   - FenceToken
29//!   - AuditLog
30//!
31//! When you want to make a change to the `Catalog` you need to follow these steps:
32//!
33//! 1. Check the current [`CATALOG_VERSION`], make sure an `objects_v<CATALOG_VERSION>.proto` file
34//!    exists. If one doesn't, copy and paste the current `objects.proto` file, renaming it to
35//!    `objects_v<CATALOG_VERSION>.proto`.
36//! 2. Bump [`CATALOG_VERSION`] by one.
37//! 3. Make your changes to `objects.proto`.
38//! 4. Copy and paste `objects.proto`, naming the copy `objects_v<CATALOG_VERSION>.proto`. Update
39//!    the package name of the `.proto` to `package objects_v<CATALOG_VERSION>;`
40//! 5. We should now have a copy of the protobuf objects as they currently exist, and a copy of
41//!    how we want them to exist. For example, if the version of the Catalog before we made our
42//!    changes was 15, we should now have `objects_v15.proto` and `objects_v16.proto`.
43//! 6. Rebuild Materialize which will error because the hashes stored in
44//!    `src/catalog-protos/protos/hashes.json` have now changed. Update these to match the new
45//!    hashes for objects.proto and `objects_v<CATALOG_VERSION>.proto`.
46//! 7. Add `v<CATALOG_VERSION>` to the call to the `objects!` macro in this file, and to the
47//!    `proto_objects!` macro in the [`mz_catalog_protos`] crate.
48//! 8. Add a new file to `catalog/src/durable/upgrade` which is where we'll put the new migration
49//!    path.
50//! 9. Write upgrade functions using the two versions of the protos we now have, e.g.
51//!    `objects_v15.proto` and `objects_v16.proto`. In this migration code you __should not__
52//!    import any defaults or constants from elsewhere in the codebase, because then a future
53//!    change could then impact a previous migration.
54//! 10. Add an import for your new module to this file: mod v<CATALOG_VERSION-1>_to_v<CATALOG_VERSION>;
55//! 11. Call your upgrade function in [`run_upgrade()`].
56//! 12. Generate a test file for the new version:
57//!     ```ignore
58//!     cargo test --package mz-catalog --lib durable::upgrade::tests::generate_missing_encodings -- --ignored
59//!     ```
60//!
61//! When in doubt, reach out to the Surfaces team, and we'll be more than happy to help :)
62
63pub mod json_compatible;
64#[cfg(test)]
65mod tests;
66
67use mz_ore::{soft_assert_eq_or_log, soft_assert_ne_or_log};
68use mz_repr::Diff;
69use paste::paste;
70#[cfg(test)]
71use proptest::prelude::*;
72#[cfg(test)]
73use proptest::strategy::ValueTree;
74#[cfg(test)]
75use proptest_derive::Arbitrary;
76use timely::progress::Timestamp as TimelyTimestamp;
77
78use crate::durable::initialize::USER_VERSION_KEY;
79use crate::durable::objects::serialization::proto;
80use crate::durable::objects::state_update::{
81    IntoStateUpdateKindJson, StateUpdate, StateUpdateKind, StateUpdateKindJson,
82};
83use crate::durable::persist::{Mode, Timestamp, UnopenedPersistCatalogState};
84use crate::durable::{CatalogError, DurableCatalogError};
85
86#[cfg(test)]
87const ENCODED_TEST_CASES: usize = 100;
88
89macro_rules! objects {
90    ( $( $x:ident ),* ) => {
91        paste! {
92            $(
93                pub(crate) mod [<objects_ $x>] {
94                    pub use mz_catalog_protos::[<objects_ $x>]::*;
95
96                    use crate::durable::objects::state_update::StateUpdateKindJson;
97
98                    impl From<StateUpdateKind> for StateUpdateKindJson {
99                        fn from(value: StateUpdateKind) -> Self {
100                            let kind = value.kind.expect("kind should be set");
101                            // TODO: This requires that the json->proto->json roundtrips
102                            // exactly, see database-issues#7179.
103                            StateUpdateKindJson::from_serde(&kind)
104                        }
105                    }
106
107                    impl TryFrom<StateUpdateKindJson> for StateUpdateKind {
108                        type Error = String;
109
110                        fn try_from(value: StateUpdateKindJson) -> Result<Self, Self::Error> {
111                            let kind: state_update_kind::Kind = value.to_serde();
112                            Ok(StateUpdateKind { kind: Some(kind) })
113                        }
114                    }
115                }
116            )*
117
118            // Generate test helpers for each version.
119
120            #[cfg(test)]
121            #[derive(Debug, Arbitrary)]
122            enum AllVersionsStateUpdateKind {
123                $(
124                    [<$x:upper>](crate::durable::upgrade::[<objects_ $x>]::StateUpdateKind),
125                )*
126            }
127
128            #[cfg(test)]
129            impl AllVersionsStateUpdateKind {
130                #[cfg(test)]
131                fn arbitrary_vec(version: &str) -> Result<Vec<Self>, String> {
132                    let mut runner = proptest::test_runner::TestRunner::deterministic();
133                    std::iter::repeat(())
134                        .filter_map(|_| AllVersionsStateUpdateKind::arbitrary(version, &mut runner).transpose())
135                        .take(ENCODED_TEST_CASES)
136                        .collect::<Result<_, _>>()
137                }
138
139                #[cfg(test)]
140                fn arbitrary(
141                    version: &str,
142                    runner: &mut proptest::test_runner::TestRunner,
143                ) -> Result<Option<Self>, String> {
144                    match version {
145                        $(
146                            concat!("objects_", stringify!($x)) => {
147                                let arbitrary_data =
148                                    crate::durable::upgrade::[<objects_ $x>]::StateUpdateKind::arbitrary()
149                                        .new_tree(runner)
150                                        .expect("unable to create arbitrary data")
151                                        .current();
152                                // Skip over generated data where kind is None because they are not interesting or
153                                // possible in production. Unfortunately any of the inner fields can still be None,
154                                // which is also not possible in production.
155                                // TODO(jkosh44) See if there's an arbitrary config that forces Some.
156                                let arbitrary_data = if arbitrary_data.kind.is_some() {
157                                    Some(Self::[<$x:upper>](arbitrary_data))
158                                } else {
159                                    None
160                                };
161                                Ok(arbitrary_data)
162                            }
163                        )*
164                        _ => Err(format!("unrecognized version {version} add enum variant")),
165                    }
166                }
167
168                #[cfg(test)]
169                fn try_from_raw(version: &str, raw: StateUpdateKindJson) -> Result<Self, String> {
170                    match version {
171                        $(
172                            concat!("objects_", stringify!($x)) => Ok(Self::[<$x:upper>](raw.try_into()?)),
173                        )*
174                        _ => Err(format!("unrecognized version {version} add enum variant")),
175                    }
176                }
177
178                #[cfg(test)]
179                fn raw(self) -> StateUpdateKindJson {
180                    match self {
181                        $(
182                            Self::[<$x:upper>](kind) => kind.into(),
183                        )*
184                    }
185                }
186            }
187        }
188    }
189}
190
191objects!(v74, v75, v76, v77, v78);
192
193/// The current version of the `Catalog`.
194pub use mz_catalog_protos::CATALOG_VERSION;
195/// The minimum `Catalog` version number that we support migrating from.
196pub use mz_catalog_protos::MIN_CATALOG_VERSION;
197
198// Note(parkmycar): Ideally we wouldn't have to define these extra constants,
199// but const expressions aren't yet supported in match statements.
200const TOO_OLD_VERSION: u64 = MIN_CATALOG_VERSION - 1;
201const FUTURE_VERSION: u64 = CATALOG_VERSION + 1;
202
203mod v74_to_v75;
204mod v75_to_v76;
205mod v76_to_v77;
206mod v77_to_v78;
207
208/// Describes a single action to take during a migration from `V1` to `V2`.
209#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
210enum MigrationAction<V1: IntoStateUpdateKindJson, V2: IntoStateUpdateKindJson> {
211    /// Deletes the provided key.
212    #[allow(unused)]
213    Delete(V1),
214    /// Inserts the provided key-value pair. The key must not currently exist!
215    #[allow(unused)]
216    Insert(V2),
217    /// Update the key-value pair for the provided key.
218    #[allow(unused)]
219    Update(V1, V2),
220}
221
222impl<V1: IntoStateUpdateKindJson, V2: IntoStateUpdateKindJson> MigrationAction<V1, V2> {
223    /// Converts `self` into a `Vec<StateUpdate<StateUpdateKindBinary>>` that can be appended
224    /// to persist.
225    fn into_updates(self) -> Vec<(StateUpdateKindJson, Diff)> {
226        match self {
227            MigrationAction::Delete(kind) => {
228                vec![(kind.into(), Diff::MINUS_ONE)]
229            }
230            MigrationAction::Insert(kind) => {
231                vec![(kind.into(), Diff::ONE)]
232            }
233            MigrationAction::Update(old_kind, new_kind) => {
234                vec![
235                    (old_kind.into(), Diff::MINUS_ONE),
236                    (new_kind.into(), Diff::ONE),
237                ]
238            }
239        }
240    }
241}
242
243/// Upgrades the data in the catalog to version [`CATALOG_VERSION`].
244///
245/// Returns the current upper after all migrations have executed.
246#[mz_ore::instrument(name = "persist::upgrade", level = "debug")]
247pub(crate) async fn upgrade(
248    persist_handle: &mut UnopenedPersistCatalogState,
249    mut commit_ts: Timestamp,
250) -> Result<Timestamp, CatalogError> {
251    soft_assert_ne_or_log!(
252        persist_handle.upper,
253        Timestamp::minimum(),
254        "cannot upgrade uninitialized catalog"
255    );
256
257    // Consolidate to avoid migrating old state.
258    persist_handle.consolidate();
259    let mut version = persist_handle
260        .get_user_version()
261        .await?
262        .expect("initialized catalog must have a version");
263    // Run migrations until we're up-to-date.
264    while version < CATALOG_VERSION {
265        (version, commit_ts) = run_upgrade(persist_handle, version, commit_ts).await?;
266    }
267
268    Ok(commit_ts)
269}
270
271/// Determines which upgrade to run for the `version` and executes it.
272///
273/// Returns the new version and upper.
274async fn run_upgrade(
275    unopened_catalog_state: &mut UnopenedPersistCatalogState,
276    version: u64,
277    commit_ts: Timestamp,
278) -> Result<(u64, Timestamp), CatalogError> {
279    let incompatible = DurableCatalogError::IncompatibleDataVersion {
280        found_version: version,
281        min_catalog_version: MIN_CATALOG_VERSION,
282        catalog_version: CATALOG_VERSION,
283    }
284    .into();
285
286    match version {
287        ..=TOO_OLD_VERSION => Err(incompatible),
288
289        74 => {
290            run_versioned_upgrade(
291                unopened_catalog_state,
292                version,
293                commit_ts,
294                v74_to_v75::upgrade,
295            )
296            .await
297        }
298        75 => {
299            run_versioned_upgrade(
300                unopened_catalog_state,
301                version,
302                commit_ts,
303                v75_to_v76::upgrade,
304            )
305            .await
306        }
307        76 => {
308            run_versioned_upgrade(
309                unopened_catalog_state,
310                version,
311                commit_ts,
312                v76_to_v77::upgrade,
313            )
314            .await
315        }
316        77 => {
317            run_versioned_upgrade(
318                unopened_catalog_state,
319                version,
320                commit_ts,
321                v77_to_v78::upgrade,
322            )
323            .await
324        }
325
326        // Up-to-date, no migration needed!
327        CATALOG_VERSION => Ok((CATALOG_VERSION, commit_ts)),
328        FUTURE_VERSION.. => Err(incompatible),
329    }
330}
331
332/// Runs `migration_logic` on the contents of the current catalog assuming a current version of
333/// `current_version`.
334///
335/// Returns the new version and upper.
336async fn run_versioned_upgrade<V1: IntoStateUpdateKindJson, V2: IntoStateUpdateKindJson>(
337    unopened_catalog_state: &mut UnopenedPersistCatalogState,
338    current_version: u64,
339    mut commit_ts: Timestamp,
340    migration_logic: impl FnOnce(Vec<V1>) -> Vec<MigrationAction<V1, V2>>,
341) -> Result<(u64, Timestamp), CatalogError> {
342    tracing::info!(current_version, "running versioned Catalog upgrade");
343
344    // 1. Use the V1 to deserialize the contents of the current snapshot.
345    let snapshot: Vec<_> = unopened_catalog_state
346        .snapshot
347        .iter()
348        .map(|(kind, ts, diff)| {
349            soft_assert_eq_or_log!(
350                *diff,
351                Diff::ONE,
352                "snapshot is consolidated, ({kind:?}, {ts:?}, {diff:?})"
353            );
354            V1::try_from(kind.clone()).expect("invalid catalog data persisted")
355        })
356        .collect();
357
358    // 2. Generate updates from version specific migration logic.
359    let migration_actions = migration_logic(snapshot);
360    let mut updates: Vec<_> = migration_actions
361        .into_iter()
362        .flat_map(|action| action.into_updates().into_iter())
363        .collect();
364    // Validate that we're not migrating an un-migratable collection.
365    for (update, _) in &updates {
366        if update.is_always_deserializable() {
367            panic!("migration to un-migratable collection: {update:?}\nall updates: {updates:?}");
368        }
369    }
370
371    // 3. Add a retraction for old version and insertion for new version into updates.
372    let next_version = current_version + 1;
373    let version_retraction = (version_update_kind(current_version), Diff::MINUS_ONE);
374    updates.push(version_retraction);
375    let version_insertion = (version_update_kind(next_version), Diff::ONE);
376    updates.push(version_insertion);
377
378    // 4. Apply migration to catalog.
379    if matches!(unopened_catalog_state.mode, Mode::Writable) {
380        commit_ts = unopened_catalog_state
381            .compare_and_append(updates, commit_ts)
382            .await
383            .map_err(|e| e.unwrap_fence_error())?;
384    } else {
385        let ts = commit_ts;
386        let updates = updates
387            .into_iter()
388            .map(|(kind, diff)| StateUpdate { kind, ts, diff });
389        commit_ts = commit_ts.step_forward();
390        unopened_catalog_state.apply_updates(updates)?;
391    }
392
393    // 5. Consolidate snapshot to remove old versions.
394    unopened_catalog_state.consolidate();
395
396    Ok((next_version, commit_ts))
397}
398
399/// Generates a [`proto::StateUpdateKind`] to update the user version.
400fn version_update_kind(version: u64) -> StateUpdateKindJson {
401    // We can use the current version because Configs can never be migrated and are always wire
402    // compatible.
403    StateUpdateKind::Config(
404        proto::ConfigKey {
405            key: USER_VERSION_KEY.to_string(),
406        },
407        proto::ConfigValue { value: version },
408    )
409    .into()
410}