Skip to main content

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
47//! 8. Add a new file to `catalog/src/durable/upgrade` which is where we'll put the new migration
48//!    path.
49//! 9. Write upgrade functions using the two versions of the protos we now have, e.g.
50//!    `objects_v15.proto` and `objects_v16.proto`. In this migration code you __should not__
51//!    import any defaults or constants from elsewhere in the codebase, because then a future
52//!    change could then impact a previous migration.
53//! 10. Add an import for your new module to this file: mod v<CATALOG_VERSION-1>_to_v<CATALOG_VERSION>;
54//! 11. Call your upgrade function in [`run_upgrade()`].
55//! 12. Generate a test file for the new version:
56//!     ```ignore
57//!     cargo test --package mz-catalog --lib durable::upgrade::tests::generate_missing_encodings -- --ignored
58//!     ```
59//!
60//! When in doubt, reach out to the Surfaces team, and we'll be more than happy to help :)
61
62pub mod json_compatible;
63#[cfg(test)]
64mod tests;
65
66use mz_ore::{soft_assert_eq_or_log, soft_assert_ne_or_log};
67use mz_repr::Diff;
68use paste::paste;
69#[cfg(test)]
70use proptest::prelude::*;
71#[cfg(test)]
72use proptest::strategy::ValueTree;
73#[cfg(test)]
74use proptest_derive::Arbitrary;
75use timely::progress::Timestamp as TimelyTimestamp;
76
77use crate::durable::initialize::USER_VERSION_KEY;
78use crate::durable::objects::serialization::proto;
79use crate::durable::objects::state_update::{
80    IntoStateUpdateKindJson, StateUpdate, StateUpdateKind, StateUpdateKindJson,
81};
82use crate::durable::persist::{Mode, Timestamp, UnopenedPersistCatalogState};
83use crate::durable::{CatalogError, DurableCatalogError};
84
85#[cfg(test)]
86const ENCODED_TEST_CASES: usize = 100;
87
88/// Generate per-version support code.
89///
90/// Here we have to deal with the fact that the pre-v79 objects had a protobuf-generated format,
91/// which gives them additional levels of indirection that the post-v79 objects don't have and thus
92/// requires slightly different code to be generated.
93macro_rules! objects {
94    ( [$( $x_old:ident ),*], [$( $x:ident ),*] ) => {
95        paste! {
96            $(
97                pub(crate) mod [<objects_ $x_old>] {
98                    pub use mz_catalog_protos::[<objects_ $x_old>]::*;
99
100                    use crate::durable::objects::state_update::StateUpdateKindJson;
101
102                    impl From<StateUpdateKind> for StateUpdateKindJson {
103                        fn from(value: StateUpdateKind) -> Self {
104                            let kind = value.kind.expect("kind should be set");
105                            // TODO: This requires that the json->proto->json roundtrips
106                            // exactly, see database-issues#7179.
107                            StateUpdateKindJson::from_serde(&kind)
108                        }
109                    }
110
111                    impl From<StateUpdateKindJson> for StateUpdateKind {
112                        fn from(value: StateUpdateKindJson) -> Self {
113                            let kind: state_update_kind::Kind = value.to_serde();
114                            StateUpdateKind { kind: Some(kind) }
115                        }
116                    }
117                }
118            )*
119
120            $(
121                pub(crate) mod [<objects_ $x>] {
122                    pub use mz_catalog_protos::[<objects_ $x>]::*;
123
124                    use crate::durable::objects::state_update::StateUpdateKindJson;
125
126                    impl From<StateUpdateKind> for StateUpdateKindJson {
127                        fn from(value: StateUpdateKind) -> Self {
128                            // TODO: This requires that the json->proto->json roundtrips
129                            // exactly, see database-issues#7179.
130                            StateUpdateKindJson::from_serde(&value)
131                        }
132                    }
133
134                    impl From<StateUpdateKindJson> for StateUpdateKind {
135                        fn from(value: StateUpdateKindJson) -> Self {
136                            value.to_serde()
137                        }
138                    }
139                }
140            )*
141
142            // Generate test helpers for each version.
143
144            #[cfg(test)]
145            #[derive(Debug, Arbitrary)]
146            enum AllVersionsStateUpdateKind {
147                $(
148                    [<$x_old:upper>](crate::durable::upgrade::[<objects_ $x_old>]::StateUpdateKind),
149                )*
150                $(
151                    [<$x:upper>](crate::durable::upgrade::[<objects_ $x>]::StateUpdateKind),
152                )*
153            }
154
155            #[cfg(test)]
156            impl AllVersionsStateUpdateKind {
157                #[cfg(test)]
158                fn arbitrary_vec(version: &str) -> Result<Vec<Self>, String> {
159                    let mut runner = proptest::test_runner::TestRunner::deterministic();
160                    std::iter::repeat(())
161                        .filter_map(|_| {
162                            AllVersionsStateUpdateKind::arbitrary(version, &mut runner)
163                                .transpose()
164                        })
165                        .take(ENCODED_TEST_CASES)
166                        .collect::<Result<_, _>>()
167                }
168
169                #[cfg(test)]
170                fn arbitrary(
171                    version: &str,
172                    runner: &mut proptest::test_runner::TestRunner,
173                ) -> Result<Option<Self>, String> {
174                    match version {
175                        $(
176                            concat!("objects_", stringify!($x_old)) => {
177                                let arbitrary_data =
178                                    crate::durable::upgrade
179                                        ::[<objects_ $x_old>]::StateUpdateKind::arbitrary()
180                                        .new_tree(runner)
181                                        .expect("unable to create arbitrary data")
182                                        .current();
183                                // Skip over generated data where kind is None
184                                // because they are not interesting or possible in
185                                // production. Unfortunately any of the inner fields
186                                // can still be None, which is also not possible in
187                                // production.
188                                // TODO(jkosh44) See if there's an arbitrary config
189                                // that forces Some.
190                                let arbitrary_data = if arbitrary_data.kind.is_some() {
191                                    Some(Self::[<$x_old:upper>](arbitrary_data))
192                                } else {
193                                    None
194                                };
195                                Ok(arbitrary_data)
196                            }
197                        )*
198                        $(
199                            concat!("objects_", stringify!($x)) => {
200                                let arbitrary_data =
201                                    crate::durable::upgrade
202                                        ::[<objects_ $x>]::StateUpdateKind::arbitrary()
203                                        .new_tree(runner)
204                                        .expect("unable to create arbitrary data")
205                                        .current();
206                                Ok(Some(Self::[<$x:upper>](arbitrary_data)))
207                            }
208                        )*
209                        _ => Err(format!("unrecognized version {version} add enum variant")),
210                    }
211                }
212
213                #[cfg(test)]
214                fn try_from_raw(version: &str, raw: StateUpdateKindJson) -> Result<Self, String> {
215                    match version {
216                        $(
217                            concat!("objects_", stringify!($x_old)) => Ok(Self::[<$x_old:upper>](raw.into())),
218                        )*
219                        $(
220                            concat!("objects_", stringify!($x)) => Ok(Self::[<$x:upper>](raw.into())),
221
222                        )*
223                        _ => Err(format!("unrecognized version {version} add enum variant")),
224                    }
225                }
226
227                #[cfg(test)]
228                fn raw(self) -> StateUpdateKindJson {
229                    match self {
230                        $(
231                            Self::[<$x_old:upper>](kind) => kind.into(),
232                        )*
233                        $(
234                            Self::[<$x:upper>](kind) => kind.into(),
235                        )*
236                    }
237                }
238            }
239        }
240    }
241}
242
243objects!(
244    [v74, v75, v76, v77, v78],
245    [
246        v79, v80, v81, v82, v83, v84, v85, v86, v87, v88, v89, v90, v91, v92, v93
247    ]
248);
249
250/// The current version of the `Catalog`.
251pub use mz_catalog_protos::CATALOG_VERSION;
252/// The minimum `Catalog` version number that we support migrating from.
253pub use mz_catalog_protos::MIN_CATALOG_VERSION;
254
255// Note(parkmycar): Ideally we wouldn't have to define these extra constants,
256// but const expressions aren't yet supported in match statements.
257const TOO_OLD_VERSION: u64 = MIN_CATALOG_VERSION - 1;
258const FUTURE_VERSION: u64 = CATALOG_VERSION + 1;
259
260mod v74_to_v75;
261mod v75_to_v76;
262mod v76_to_v77;
263mod v77_to_v78;
264mod v78_to_v79;
265mod v79_to_v80;
266mod v80_to_v81;
267mod v81_to_v82;
268mod v82_to_v83;
269mod v83_to_v84;
270mod v84_to_v85;
271mod v85_to_v86;
272mod v86_to_v87;
273mod v87_to_v88;
274mod v88_to_v89;
275mod v89_to_v90;
276mod v90_to_v91;
277mod v91_to_v92;
278mod v92_to_v93;
279
280/// Describes a single action to take during a migration from `V1` to `V2`.
281#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
282enum MigrationAction<V1: IntoStateUpdateKindJson, V2: IntoStateUpdateKindJson> {
283    /// Deletes the provided key.
284    #[allow(unused)]
285    Delete(V1),
286    /// Inserts the provided key-value pair. The key must not currently exist!
287    #[allow(unused)]
288    Insert(V2),
289    /// Update the key-value pair for the provided key.
290    #[allow(unused)]
291    Update(V1, V2),
292}
293
294impl<V1: IntoStateUpdateKindJson, V2: IntoStateUpdateKindJson> MigrationAction<V1, V2> {
295    /// Converts `self` into a `Vec<StateUpdate<StateUpdateKindBinary>>` that can be appended
296    /// to persist.
297    fn into_updates(self) -> Vec<(StateUpdateKindJson, Diff)> {
298        match self {
299            MigrationAction::Delete(kind) => {
300                vec![(kind.into(), Diff::MINUS_ONE)]
301            }
302            MigrationAction::Insert(kind) => {
303                vec![(kind.into(), Diff::ONE)]
304            }
305            MigrationAction::Update(old_kind, new_kind) => {
306                vec![
307                    (old_kind.into(), Diff::MINUS_ONE),
308                    (new_kind.into(), Diff::ONE),
309                ]
310            }
311        }
312    }
313}
314
315/// Upgrades the data in the catalog to version [`CATALOG_VERSION`].
316///
317/// Returns the current upper after all migrations have executed.
318#[mz_ore::instrument(name = "persist::upgrade", level = "debug")]
319pub(crate) async fn upgrade(
320    persist_handle: &mut UnopenedPersistCatalogState,
321    mut commit_ts: Timestamp,
322) -> Result<Timestamp, CatalogError> {
323    soft_assert_ne_or_log!(
324        persist_handle.upper,
325        Timestamp::minimum(),
326        "cannot upgrade uninitialized catalog"
327    );
328
329    // Consolidate to avoid migrating old state.
330    persist_handle.consolidate();
331    let mut version = persist_handle
332        .get_user_version()
333        .await?
334        .expect("initialized catalog must have a version");
335    // Run migrations until we're up-to-date.
336    while version < CATALOG_VERSION {
337        (version, commit_ts) = run_upgrade(persist_handle, version, commit_ts).await?;
338    }
339
340    Ok(commit_ts)
341}
342
343/// Determines which upgrade to run for the `version` and executes it.
344///
345/// Returns the new version and upper.
346async fn run_upgrade(
347    unopened_catalog_state: &mut UnopenedPersistCatalogState,
348    version: u64,
349    commit_ts: Timestamp,
350) -> Result<(u64, Timestamp), CatalogError> {
351    let incompatible = DurableCatalogError::IncompatibleDataVersion {
352        found_version: version,
353        min_catalog_version: MIN_CATALOG_VERSION,
354        catalog_version: CATALOG_VERSION,
355    }
356    .into();
357
358    match version {
359        ..=TOO_OLD_VERSION => Err(incompatible),
360
361        74 => {
362            run_versioned_upgrade(
363                unopened_catalog_state,
364                version,
365                commit_ts,
366                v74_to_v75::upgrade,
367            )
368            .await
369        }
370        75 => {
371            run_versioned_upgrade(
372                unopened_catalog_state,
373                version,
374                commit_ts,
375                v75_to_v76::upgrade,
376            )
377            .await
378        }
379        76 => {
380            run_versioned_upgrade(
381                unopened_catalog_state,
382                version,
383                commit_ts,
384                v76_to_v77::upgrade,
385            )
386            .await
387        }
388        77 => {
389            run_versioned_upgrade(
390                unopened_catalog_state,
391                version,
392                commit_ts,
393                v77_to_v78::upgrade,
394            )
395            .await
396        }
397        78 => {
398            run_versioned_upgrade(
399                unopened_catalog_state,
400                version,
401                commit_ts,
402                v78_to_v79::upgrade,
403            )
404            .await
405        }
406        79 => {
407            run_versioned_upgrade(
408                unopened_catalog_state,
409                version,
410                commit_ts,
411                v79_to_v80::upgrade,
412            )
413            .await
414        }
415        80 => {
416            run_versioned_upgrade(
417                unopened_catalog_state,
418                version,
419                commit_ts,
420                v80_to_v81::upgrade,
421            )
422            .await
423        }
424        81 => {
425            run_versioned_upgrade(
426                unopened_catalog_state,
427                version,
428                commit_ts,
429                v81_to_v82::upgrade,
430            )
431            .await
432        }
433        // v82→v83 is a one-shot byte-level repair, not a proto evolution. It
434        // needs raw access to the snapshot's diffs (which `run_versioned_upgrade`
435        // strips) so it plugs into `run_upgrade` directly.
436        82 => v82_to_v83::upgrade(unopened_catalog_state, commit_ts).await,
437        83 => v83_to_v84::upgrade(unopened_catalog_state, commit_ts).await,
438        84 => {
439            run_versioned_upgrade(
440                unopened_catalog_state,
441                version,
442                commit_ts,
443                v84_to_v85::upgrade,
444            )
445            .await
446        }
447        85 => {
448            run_versioned_upgrade(
449                unopened_catalog_state,
450                version,
451                commit_ts,
452                v85_to_v86::upgrade,
453            )
454            .await
455        }
456        86 => {
457            run_versioned_upgrade(
458                unopened_catalog_state,
459                version,
460                commit_ts,
461                v86_to_v87::upgrade,
462            )
463            .await
464        }
465        87 => {
466            run_versioned_upgrade(
467                unopened_catalog_state,
468                version,
469                commit_ts,
470                v87_to_v88::upgrade,
471            )
472            .await
473        }
474        88 => {
475            run_versioned_upgrade(
476                unopened_catalog_state,
477                version,
478                commit_ts,
479                v88_to_v89::upgrade,
480            )
481            .await
482        }
483        89 => {
484            run_versioned_upgrade(
485                unopened_catalog_state,
486                version,
487                commit_ts,
488                v89_to_v90::upgrade,
489            )
490            .await
491        }
492        90 => {
493            run_versioned_upgrade(
494                unopened_catalog_state,
495                version,
496                commit_ts,
497                v90_to_v91::upgrade,
498            )
499            .await
500        }
501        91 => {
502            run_versioned_upgrade(
503                unopened_catalog_state,
504                version,
505                commit_ts,
506                v91_to_v92::upgrade,
507            )
508            .await
509        }
510        92 => {
511            run_versioned_upgrade(
512                unopened_catalog_state,
513                version,
514                commit_ts,
515                v92_to_v93::upgrade,
516            )
517            .await
518        }
519        // Up-to-date, no migration needed!
520        CATALOG_VERSION => Ok((CATALOG_VERSION, commit_ts)),
521        FUTURE_VERSION.. => Err(incompatible),
522    }
523}
524
525/// Runs `migration_logic` on the contents of the current catalog assuming a current version of
526/// `current_version`.
527///
528/// Returns the new version and upper.
529async fn run_versioned_upgrade<V1: IntoStateUpdateKindJson, V2: IntoStateUpdateKindJson>(
530    unopened_catalog_state: &mut UnopenedPersistCatalogState,
531    current_version: u64,
532    mut commit_ts: Timestamp,
533    migration_logic: impl FnOnce(Vec<V1>) -> Vec<MigrationAction<V1, V2>>,
534) -> Result<(u64, Timestamp), CatalogError> {
535    tracing::info!(current_version, "running versioned Catalog upgrade");
536
537    // 1. Use the V1 to deserialize the contents of the current snapshot.
538    let snapshot: Vec<_> = unopened_catalog_state
539        .snapshot
540        .iter()
541        .map(|(kind, ts, diff)| {
542            soft_assert_eq_or_log!(
543                *diff,
544                Diff::ONE,
545                "snapshot is consolidated, ({kind:?}, {ts:?}, {diff:?})"
546            );
547            V1::try_from(kind.clone()).expect("invalid catalog data persisted")
548        })
549        .collect();
550
551    // 2. Generate updates from version specific migration logic.
552    let migration_actions = migration_logic(snapshot);
553    let mut updates: Vec<_> = migration_actions
554        .into_iter()
555        .flat_map(|action| action.into_updates().into_iter())
556        .collect();
557    // Validate that we're not migrating an un-migratable collection.
558    for (update, _) in &updates {
559        if update.is_always_deserializable() {
560            panic!("migration to un-migratable collection: {update:?}\nall updates: {updates:?}");
561        }
562    }
563
564    // 3. Add a retraction for old version and insertion for new version into updates.
565    let next_version = current_version + 1;
566    let version_retraction = (version_update_kind(current_version), Diff::MINUS_ONE);
567    updates.push(version_retraction);
568    let version_insertion = (version_update_kind(next_version), Diff::ONE);
569    updates.push(version_insertion);
570
571    // 4. Apply migration to catalog.
572    if matches!(unopened_catalog_state.mode, Mode::Writable) {
573        commit_ts = unopened_catalog_state
574            .compare_and_append(updates, commit_ts)
575            .await
576            .map_err(|e| e.unwrap_fence_error())?;
577    } else {
578        let ts = commit_ts;
579        let updates = updates
580            .into_iter()
581            .map(|(kind, diff)| StateUpdate { kind, ts, diff });
582        commit_ts = commit_ts.step_forward();
583        unopened_catalog_state.apply_updates_and_consolidate(updates)?;
584    }
585
586    // 5. Consolidate snapshot to remove old versions.
587    unopened_catalog_state.consolidate();
588
589    Ok((next_version, commit_ts))
590}
591
592/// Generates a [`proto::StateUpdateKind`] to update the user version.
593fn version_update_kind(version: u64) -> StateUpdateKindJson {
594    // We can use the current version because Configs can never be migrated and are always wire
595    // compatible.
596    StateUpdateKind::Config(
597        proto::ConfigKey {
598            key: USER_VERSION_KEY.to_string(),
599        },
600        proto::ConfigValue { value: version },
601    )
602    .into()
603}