1pub 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
88macro_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 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 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 #[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 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, v94, v95, v96
247 ]
248);
249
250pub use mz_catalog_protos::CATALOG_VERSION;
252pub use mz_catalog_protos::MIN_CATALOG_VERSION;
254
255const 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;
279mod v93_to_v94;
280mod v94_to_v95;
281mod v95_to_v96;
282
283#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
285enum MigrationAction<V1: IntoStateUpdateKindJson, V2: IntoStateUpdateKindJson> {
286 #[allow(unused)]
288 Delete(V1),
289 #[allow(unused)]
291 Insert(V2),
292 #[allow(unused)]
294 Update(V1, V2),
295}
296
297impl<V1: IntoStateUpdateKindJson, V2: IntoStateUpdateKindJson> MigrationAction<V1, V2> {
298 fn into_updates(self) -> Vec<(StateUpdateKindJson, Diff)> {
301 match self {
302 MigrationAction::Delete(kind) => {
303 vec![(kind.into(), Diff::MINUS_ONE)]
304 }
305 MigrationAction::Insert(kind) => {
306 vec![(kind.into(), Diff::ONE)]
307 }
308 MigrationAction::Update(old_kind, new_kind) => {
309 vec![
310 (old_kind.into(), Diff::MINUS_ONE),
311 (new_kind.into(), Diff::ONE),
312 ]
313 }
314 }
315 }
316}
317
318#[mz_ore::instrument(name = "persist::upgrade", level = "debug")]
322pub(crate) async fn upgrade(
323 persist_handle: &mut UnopenedPersistCatalogState,
324 mut commit_ts: Timestamp,
325 force_migration: bool,
326) -> Result<Timestamp, CatalogError> {
327 soft_assert_ne_or_log!(
328 persist_handle.upper,
329 Timestamp::minimum(),
330 "cannot upgrade uninitialized catalog"
331 );
332
333 persist_handle.consolidate();
335 let mut version = persist_handle
336 .get_user_version()
337 .await?
338 .expect("initialized catalog must have a version");
339 while version < CATALOG_VERSION {
341 (version, commit_ts) = run_upgrade(persist_handle, version, commit_ts).await?;
342 }
343 if force_migration {
344 tracing::info!(version, "running forced Catalog upgrade");
345 commit_ts = apply_migration(persist_handle, Vec::new(), commit_ts).await?;
346 }
347
348 Ok(commit_ts)
349}
350
351async fn run_upgrade(
355 unopened_catalog_state: &mut UnopenedPersistCatalogState,
356 version: u64,
357 commit_ts: Timestamp,
358) -> Result<(u64, Timestamp), CatalogError> {
359 let incompatible = DurableCatalogError::IncompatibleDataVersion {
360 found_version: version,
361 min_catalog_version: MIN_CATALOG_VERSION,
362 catalog_version: CATALOG_VERSION,
363 }
364 .into();
365
366 match version {
367 ..=TOO_OLD_VERSION => Err(incompatible),
368
369 74 => {
370 run_versioned_upgrade(
371 unopened_catalog_state,
372 version,
373 commit_ts,
374 v74_to_v75::upgrade,
375 )
376 .await
377 }
378 75 => {
379 run_versioned_upgrade(
380 unopened_catalog_state,
381 version,
382 commit_ts,
383 v75_to_v76::upgrade,
384 )
385 .await
386 }
387 76 => {
388 run_versioned_upgrade(
389 unopened_catalog_state,
390 version,
391 commit_ts,
392 v76_to_v77::upgrade,
393 )
394 .await
395 }
396 77 => {
397 run_versioned_upgrade(
398 unopened_catalog_state,
399 version,
400 commit_ts,
401 v77_to_v78::upgrade,
402 )
403 .await
404 }
405 78 => {
406 run_versioned_upgrade(
407 unopened_catalog_state,
408 version,
409 commit_ts,
410 v78_to_v79::upgrade,
411 )
412 .await
413 }
414 79 => {
415 run_versioned_upgrade(
416 unopened_catalog_state,
417 version,
418 commit_ts,
419 v79_to_v80::upgrade,
420 )
421 .await
422 }
423 80 => {
424 run_versioned_upgrade(
425 unopened_catalog_state,
426 version,
427 commit_ts,
428 v80_to_v81::upgrade,
429 )
430 .await
431 }
432 81 => {
433 run_versioned_upgrade(
434 unopened_catalog_state,
435 version,
436 commit_ts,
437 v81_to_v82::upgrade,
438 )
439 .await
440 }
441 82 => v82_to_v83::upgrade(unopened_catalog_state, commit_ts).await,
445 83 => v83_to_v84::upgrade(unopened_catalog_state, commit_ts).await,
446 84 => {
447 run_versioned_upgrade(
448 unopened_catalog_state,
449 version,
450 commit_ts,
451 v84_to_v85::upgrade,
452 )
453 .await
454 }
455 85 => {
456 run_versioned_upgrade(
457 unopened_catalog_state,
458 version,
459 commit_ts,
460 v85_to_v86::upgrade,
461 )
462 .await
463 }
464 86 => {
465 run_versioned_upgrade(
466 unopened_catalog_state,
467 version,
468 commit_ts,
469 v86_to_v87::upgrade,
470 )
471 .await
472 }
473 87 => {
474 run_versioned_upgrade(
475 unopened_catalog_state,
476 version,
477 commit_ts,
478 v87_to_v88::upgrade,
479 )
480 .await
481 }
482 88 => {
483 run_versioned_upgrade(
484 unopened_catalog_state,
485 version,
486 commit_ts,
487 v88_to_v89::upgrade,
488 )
489 .await
490 }
491 89 => {
492 run_versioned_upgrade(
493 unopened_catalog_state,
494 version,
495 commit_ts,
496 v89_to_v90::upgrade,
497 )
498 .await
499 }
500 90 => {
501 run_versioned_upgrade(
502 unopened_catalog_state,
503 version,
504 commit_ts,
505 v90_to_v91::upgrade,
506 )
507 .await
508 }
509 91 => {
510 run_versioned_upgrade(
511 unopened_catalog_state,
512 version,
513 commit_ts,
514 v91_to_v92::upgrade,
515 )
516 .await
517 }
518 92 => {
519 run_versioned_upgrade(
520 unopened_catalog_state,
521 version,
522 commit_ts,
523 v92_to_v93::upgrade,
524 )
525 .await
526 }
527 93 => {
528 run_versioned_upgrade(
529 unopened_catalog_state,
530 version,
531 commit_ts,
532 v93_to_v94::upgrade,
533 )
534 .await
535 }
536 94 => {
537 run_versioned_upgrade(
538 unopened_catalog_state,
539 version,
540 commit_ts,
541 v94_to_v95::upgrade,
542 )
543 .await
544 }
545 95 => {
546 run_versioned_upgrade(
547 unopened_catalog_state,
548 version,
549 commit_ts,
550 v95_to_v96::upgrade,
551 )
552 .await
553 }
554 CATALOG_VERSION => Ok((CATALOG_VERSION, commit_ts)),
556 FUTURE_VERSION.. => Err(incompatible),
557 }
558}
559
560async fn run_versioned_upgrade<V1: IntoStateUpdateKindJson, V2: IntoStateUpdateKindJson>(
565 unopened_catalog_state: &mut UnopenedPersistCatalogState,
566 current_version: u64,
567 commit_ts: Timestamp,
568 migration_logic: impl FnOnce(Vec<V1>) -> Vec<MigrationAction<V1, V2>>,
569) -> Result<(u64, Timestamp), CatalogError> {
570 tracing::info!(current_version, "running versioned Catalog upgrade");
571
572 let snapshot: Vec<_> = unopened_catalog_state
574 .snapshot
575 .iter()
576 .map(|(kind, ts, diff)| {
577 soft_assert_eq_or_log!(
578 *diff,
579 Diff::ONE,
580 "snapshot is consolidated, ({kind:?}, {ts:?}, {diff:?})"
581 );
582 V1::try_from(kind.clone()).expect("invalid catalog data persisted")
583 })
584 .collect();
585
586 let migration_actions = migration_logic(snapshot);
588 let mut updates: Vec<_> = migration_actions
589 .into_iter()
590 .flat_map(|action| action.into_updates().into_iter())
591 .collect();
592 for (update, _) in &updates {
594 if update.is_always_deserializable() {
595 panic!("migration to un-migratable collection: {update:?}\nall updates: {updates:?}");
596 }
597 }
598
599 let next_version = current_version + 1;
601 let version_retraction = (version_update_kind(current_version), Diff::MINUS_ONE);
602 updates.push(version_retraction);
603 let version_insertion = (version_update_kind(next_version), Diff::ONE);
604 updates.push(version_insertion);
605
606 let commit_ts = apply_migration(unopened_catalog_state, updates, commit_ts).await?;
608
609 unopened_catalog_state.consolidate();
611
612 Ok((next_version, commit_ts))
613}
614
615async fn apply_migration(
617 unopened_catalog_state: &mut UnopenedPersistCatalogState,
618 updates: Vec<(StateUpdateKindJson, Diff)>,
619 commit_ts: Timestamp,
620) -> Result<Timestamp, CatalogError> {
621 if matches!(unopened_catalog_state.mode, Mode::Writable) {
622 Ok(unopened_catalog_state
623 .compare_and_append(updates, commit_ts)
624 .await
625 .map_err(|e| e.unwrap_fence_error())?)
626 } else {
627 let ts = commit_ts;
628 let updates = updates
629 .into_iter()
630 .map(|(kind, diff)| StateUpdate { kind, ts, diff });
631 unopened_catalog_state.apply_updates_and_consolidate(updates)?;
632 Ok(commit_ts.step_forward())
633 }
634}
635
636fn version_update_kind(version: u64) -> StateUpdateKindJson {
638 StateUpdateKind::Config(
641 proto::ConfigKey {
642 key: USER_VERSION_KEY.to_string(),
643 },
644 proto::ConfigValue { value: version },
645 )
646 .into()
647}