Skip to main content

mz_adapter/catalog/open/
builtin_schema_migration.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//! Support for migrating the schemas of builtin storage collections.
11//!
12//! If a version upgrade changes the schema of a builtin collection that's made durable in persist,
13//! that persist shard's schema must be migrated accordingly. The migration must happen in a way
14//! that's compatible with 0dt upgrades: Read-only environments need to be able to read the
15//! collections with the new schema, without interfering with the leader environment's continued
16//! use of the old schema.
17//!
18//! Two migration mechanisms are provided:
19//!
20//!  * [`Mechanism::Evolution`] uses persist's schema evolution support to evolve the persist
21//!    shard's schema in-place. Only works for backward-compatible changes.
22//!  * [`Mechanism::Replacement`] creates a new shard to serve the builtin collection in the new
23//!    version. Works for all schema changes but discards existing data.
24//!
25//! Which mechanism to use is selected through entries in the `MIGRATIONS` list. In general, the
26//! `Evolution` mechanism should be used when possible, as it avoids data loss.
27//!
28//! Builtin storage collections that have no shard yet, in practice new ones, get their shards from
29//! the migration shard that `Replacement` uses, so that a read-only environment can write them
30//! (see `Migration::plan_allocation`).
31//!
32//! For more context and details on the implementation, see
33//! `doc/developer/design/20251015_builtin_schema_migration.md`.
34
35use std::collections::{BTreeMap, BTreeSet};
36use std::sync::{Arc, LazyLock};
37
38use anyhow::bail;
39use futures::FutureExt;
40use futures::future::BoxFuture;
41use mz_build_info::{BuildInfo, DUMMY_BUILD_INFO};
42use mz_catalog::builtin::{
43    BUILTIN_LOOKUP, Builtin, Fingerprint, MZ_CATALOG_RAW, MZ_CATALOG_RAW_DESCRIPTION,
44    MZ_CLUSTER_REPLICA_FRONTIERS_DESCRIPTION, MZ_COMPUTE_HYDRATION_TIMES_DESCRIPTION,
45    MZ_OBJECT_ARRANGEMENT_SIZE_HISTORY_DESCRIPTION, MZ_OBJECT_HYDRATION_HISTORY,
46    MZ_OBJECT_HYDRATION_HISTORY_DESCRIPTION, MZ_REPLICA_HYDRATION_HISTORY,
47    MZ_REPLICA_HYDRATION_HISTORY_DESCRIPTION, MZ_STORAGE_USAGE_BY_SHARD,
48    MZ_STORAGE_USAGE_BY_SHARD_DESCRIPTION, RUNTIME_ALTERABLE_FINGERPRINT_SENTINEL,
49};
50use mz_catalog::config::BuiltinItemMigrationConfig;
51use mz_catalog::durable::objects::SystemObjectUniqueIdentifier;
52use mz_catalog::durable::{SystemObjectDescription, SystemObjectMapping, Transaction};
53use mz_catalog::memory::error::{Error, ErrorKind};
54use mz_ore::soft_assert_or_log;
55use mz_persist_client::cfg::USE_CRITICAL_SINCE_CATALOG;
56use mz_persist_client::critical::{Opaque, SinceHandle};
57use mz_persist_client::read::ReadHandle;
58use mz_persist_client::schema::CaESchema;
59use mz_persist_client::write::WriteHandle;
60use mz_persist_client::{Diagnostics, PersistClient};
61use mz_persist_types::ShardId;
62use mz_persist_types::codec_impls::{ShardIdSchema, UnitSchema};
63use mz_persist_types::schema::backward_compatible;
64use mz_repr::namespaces::{MZ_CATALOG_SCHEMA, MZ_INTERNAL_SCHEMA};
65use mz_repr::{CatalogItemId, GlobalId, Timestamp};
66use mz_sql::catalog::{CatalogItemType, NameReference};
67use mz_storage_client::controller::StorageTxn;
68use mz_storage_types::StorageDiff;
69use mz_storage_types::sources::SourceData;
70use semver::Version;
71use timely::progress::Antichain;
72use tracing::{debug, info};
73
74use crate::catalog::migrate::get_migration_version;
75
76/// Builtin schema migrations required to upgrade to the current build version.
77///
78/// Migration steps for old versions must be retained around according to the upgrade policy. For
79/// example, if we support upgrading one major version at a time, the release of version `N.0.0`
80/// can delete all migration steps with versions before `(N-1).0.0`.
81///
82/// Exception: when a builtin's `SystemObjectDescription` changes — e.g. a builtin table is
83/// converted to a materialized view (see `migrate_builtin_tables_to_mvs`), or a builtin is
84/// renamed or removed — existing steps naming the old description must be removed regardless
85/// of version, because `validate_migration_steps` panics on steps that don't resolve to a
86/// current builtin. This is safe only if a `Replacement` step for the new description is added
87/// at the conversion version: every environment that needed the removed steps upgrades from an
88/// even older version, so the new replacement subsumes them.
89///
90/// Smallest supported version: 0.147.0
91static MIGRATIONS: LazyLock<Vec<MigrationStep>> = LazyLock::new(|| {
92    vec![
93        MigrationStep::replacement(
94            "0.149.0",
95            CatalogItemType::Source,
96            MZ_INTERNAL_SCHEMA,
97            "mz_sink_statistics_raw",
98        ),
99        MigrationStep::replacement(
100            "0.149.0",
101            CatalogItemType::Source,
102            MZ_INTERNAL_SCHEMA,
103            "mz_source_statistics_raw",
104        ),
105        MigrationStep::evolution(
106            "0.159.0",
107            CatalogItemType::Source,
108            MZ_INTERNAL_SCHEMA,
109            "mz_cluster_replica_metrics_history",
110        ),
111        MigrationStep::replacement(
112            "26.18.0-dev.0",
113            CatalogItemType::MaterializedView,
114            MZ_CATALOG_SCHEMA,
115            "mz_databases",
116        ),
117        MigrationStep::replacement(
118            "26.19.0-dev.0",
119            CatalogItemType::MaterializedView,
120            MZ_CATALOG_SCHEMA,
121            "mz_schemas",
122        ),
123        MigrationStep::replacement(
124            "26.19.0-dev.0",
125            CatalogItemType::MaterializedView,
126            MZ_CATALOG_SCHEMA,
127            "mz_role_members",
128        ),
129        MigrationStep::replacement(
130            "26.19.0-dev.0",
131            CatalogItemType::MaterializedView,
132            MZ_INTERNAL_SCHEMA,
133            "mz_network_policies",
134        ),
135        MigrationStep::replacement(
136            "26.19.0-dev.0",
137            CatalogItemType::MaterializedView,
138            MZ_INTERNAL_SCHEMA,
139            "mz_network_policy_rules",
140        ),
141        MigrationStep::replacement(
142            "26.19.0-dev.0",
143            CatalogItemType::MaterializedView,
144            MZ_INTERNAL_SCHEMA,
145            "mz_cluster_workload_classes",
146        ),
147        MigrationStep::replacement(
148            "26.19.0-dev.0",
149            CatalogItemType::MaterializedView,
150            MZ_INTERNAL_SCHEMA,
151            "mz_internal_cluster_replicas",
152        ),
153        MigrationStep::replacement(
154            "26.19.0-dev.0",
155            CatalogItemType::MaterializedView,
156            MZ_INTERNAL_SCHEMA,
157            "mz_pending_cluster_replicas",
158        ),
159        MigrationStep::replacement(
160            "26.20.0-dev.0",
161            CatalogItemType::MaterializedView,
162            MZ_CATALOG_SCHEMA,
163            "mz_materialized_views",
164        ),
165        MigrationStep::replacement(
166            "26.22.0-dev.0",
167            CatalogItemType::MaterializedView,
168            MZ_CATALOG_SCHEMA,
169            "mz_connections",
170        ),
171        MigrationStep::replacement(
172            "26.22.0-dev.0",
173            CatalogItemType::MaterializedView,
174            MZ_CATALOG_SCHEMA,
175            "mz_secrets",
176        ),
177        MigrationStep::replacement(
178            "26.27.0-dev.0",
179            CatalogItemType::MaterializedView,
180            MZ_CATALOG_SCHEMA,
181            "mz_sources",
182        ),
183        MigrationStep::replacement(
184            "26.29.0-dev.0",
185            CatalogItemType::MaterializedView,
186            MZ_CATALOG_SCHEMA,
187            "mz_indexes",
188        ),
189        MigrationStep::replacement(
190            "26.29.0-dev.0",
191            CatalogItemType::MaterializedView,
192            MZ_CATALOG_SCHEMA,
193            "mz_roles",
194        ),
195        MigrationStep::replacement(
196            "26.29.0-dev.0",
197            CatalogItemType::MaterializedView,
198            MZ_CATALOG_SCHEMA,
199            "mz_role_parameters",
200        ),
201        // Required because we added `mz_cluster_replica_size_internal_ind` builtin
202        // index without bumping mz_indexes. make_mz_indexes inlines the builtin-index
203        // set as VALUES, so any add/remove changes its SQL fingerprint and requires
204        // an explicit replacement step.
205        MigrationStep::replacement(
206            "26.30.0-dev.0",
207            CatalogItemType::MaterializedView,
208            MZ_CATALOG_SCHEMA,
209            "mz_indexes",
210        ),
211        MigrationStep::replacement(
212            "26.30.0-dev.0",
213            CatalogItemType::MaterializedView,
214            MZ_CATALOG_SCHEMA,
215            "mz_clusters",
216        ),
217        MigrationStep::replacement(
218            "26.30.0-dev.0",
219            CatalogItemType::MaterializedView,
220            MZ_CATALOG_SCHEMA,
221            "mz_cluster_replicas",
222        ),
223        MigrationStep::replacement(
224            "26.30.0-dev.0",
225            CatalogItemType::MaterializedView,
226            MZ_INTERNAL_SCHEMA,
227            "mz_cluster_schedules",
228        ),
229        MigrationStep::replacement(
230            "26.30.0-dev.0",
231            CatalogItemType::MaterializedView,
232            MZ_CATALOG_SCHEMA,
233            "mz_default_privileges",
234        ),
235        MigrationStep::replacement(
236            "26.30.0-dev.0",
237            CatalogItemType::MaterializedView,
238            MZ_CATALOG_SCHEMA,
239            "mz_system_privileges",
240        ),
241        // The mz_cluster_replicas MV definition changed in 26.31.0-dev (the
242        // `availability_zone` column now aggregates the durable
243        // `availability_zones` list).
244        MigrationStep::replacement(
245            "26.31.0-dev.0",
246            CatalogItemType::MaterializedView,
247            MZ_CATALOG_SCHEMA,
248            "mz_cluster_replicas",
249        ),
250        MigrationStep::replacement(
251            "26.32.0-dev.0",
252            CatalogItemType::MaterializedView,
253            MZ_INTERNAL_SCHEMA,
254            "mz_comments",
255        ),
256        // Required because we added the console cluster-utilization overview builtin
257        // indexes (overview/_3h/_24h). make_mz_indexes inlines the builtin-index set
258        // as VALUES, so any add/remove changes its SQL fingerprint and requires an
259        // explicit replacement step.
260        MigrationStep::replacement(
261            "26.32.0-dev.0",
262            CatalogItemType::MaterializedView,
263            MZ_CATALOG_SCHEMA,
264            "mz_indexes",
265        ),
266        MigrationStep::replacement(
267            "26.33.0-dev.0",
268            CatalogItemType::MaterializedView,
269            MZ_CATALOG_SCHEMA,
270            "mz_audit_events",
271        ),
272        // Required because we added the `mz_cluster_reconfigurations_ind` and
273        // `mz_cluster_auto_scaling_strategies_ind` builtin indexes without
274        // bumping mz_indexes. make_mz_indexes inlines the builtin-index set as
275        // VALUES, so any add/remove changes its SQL fingerprint and requires an
276        // explicit replacement step.
277        //
278        // NOTE: this version must stay at the workspace's current dev version
279        // until this change ships in a release. A dev version orders below its
280        // release, so a step pinned to an older dev version is skipped when
281        // upgrading from that release onward, and the fingerprint check then
282        // panics at catalog open.
283        MigrationStep::replacement(
284            "26.34.0-dev.0",
285            CatalogItemType::MaterializedView,
286            MZ_CATALOG_SCHEMA,
287            "mz_indexes",
288        ),
289        // Converting mz_postgres_sources / mz_kafka_sources from builtin tables
290        // to materialized views changes their catalog fingerprint, so both need
291        // an explicit replacement step. See the NOTE above: this version must
292        // stay at the workspace's current dev version until the change ships.
293        MigrationStep::replacement(
294            "26.34.0-dev.0",
295            CatalogItemType::MaterializedView,
296            MZ_INTERNAL_SCHEMA,
297            "mz_postgres_sources",
298        ),
299        MigrationStep::replacement(
300            "26.34.0-dev.0",
301            CatalogItemType::MaterializedView,
302            MZ_CATALOG_SCHEMA,
303            "mz_kafka_sources",
304        ),
305        // Converting the four mz_*_source_tables from builtin tables to
306        // materialized views changes their catalog fingerprint, so each needs an
307        // explicit replacement step.
308        MigrationStep::replacement(
309            "26.37.0-dev.0",
310            CatalogItemType::MaterializedView,
311            MZ_INTERNAL_SCHEMA,
312            "mz_postgres_source_tables",
313        ),
314        MigrationStep::replacement(
315            "26.37.0-dev.0",
316            CatalogItemType::MaterializedView,
317            MZ_INTERNAL_SCHEMA,
318            "mz_mysql_source_tables",
319        ),
320        MigrationStep::replacement(
321            "26.37.0-dev.0",
322            CatalogItemType::MaterializedView,
323            MZ_INTERNAL_SCHEMA,
324            "mz_sql_server_source_tables",
325        ),
326        MigrationStep::replacement(
327            "26.37.0-dev.0",
328            CatalogItemType::MaterializedView,
329            MZ_INTERNAL_SCHEMA,
330            "mz_kafka_source_tables",
331        ),
332        // `mz_type_pg_metadata` gained a trailing `typsend` column. See the NOTE
333        // above: this version must stay at the workspace's current dev version
334        // until the change ships.
335        MigrationStep::replacement(
336            "26.40.0-dev.0",
337            CatalogItemType::Table,
338            MZ_INTERNAL_SCHEMA,
339            "mz_type_pg_metadata",
340        ),
341        // `mz_type_pg_metadata` gained a trailing `typlen` column. See the NOTE
342        // above: this version must stay at the workspace's current dev version
343        // until the change ships.
344        MigrationStep::replacement(
345            "26.47.0-dev.0",
346            CatalogItemType::Table,
347            MZ_INTERNAL_SCHEMA,
348            "mz_type_pg_metadata",
349        ),
350        // Converting the connection-detail builtin tables to materialized views
351        // changes their catalog fingerprint, so each needs an explicit
352        // replacement step.
353        MigrationStep::replacement(
354            "26.37.0-dev.0",
355            CatalogItemType::MaterializedView,
356            MZ_CATALOG_SCHEMA,
357            "mz_kafka_connections",
358        ),
359        MigrationStep::replacement(
360            "26.37.0-dev.0",
361            CatalogItemType::MaterializedView,
362            MZ_CATALOG_SCHEMA,
363            "mz_ssh_tunnel_connections",
364        ),
365        MigrationStep::replacement(
366            "26.37.0-dev.0",
367            CatalogItemType::MaterializedView,
368            MZ_INTERNAL_SCHEMA,
369            "mz_aws_connections",
370        ),
371        MigrationStep::replacement(
372            "26.37.0-dev.0",
373            CatalogItemType::MaterializedView,
374            MZ_CATALOG_SCHEMA,
375            "mz_aws_privatelink_connections",
376        ),
377        // The three sink tables became materialized views, which moves their
378        // fingerprints. The old `0.160.0` `mz_sinks` step had to go at the same
379        // time, because it names the `Table` description and that no longer
380        // resolves. Nothing is lost: anything that needed the old step upgrades
381        // from further back than this one, so this one covers it too.
382        MigrationStep::replacement(
383            "26.38.0-dev.0",
384            CatalogItemType::MaterializedView,
385            MZ_CATALOG_SCHEMA,
386            "mz_sinks",
387        ),
388        MigrationStep::replacement(
389            "26.38.0-dev.0",
390            CatalogItemType::MaterializedView,
391            MZ_CATALOG_SCHEMA,
392            "mz_kafka_sinks",
393        ),
394        MigrationStep::replacement(
395            "26.38.0-dev.0",
396            CatalogItemType::MaterializedView,
397            MZ_CATALOG_SCHEMA,
398            "mz_iceberg_sinks",
399        ),
400        // The mz_cluster_reconfigurations MV definition changed (the `changes`
401        // diff now includes the `arrangement_compression` dimension).
402        MigrationStep::replacement(
403            "26.38.0-rc.2",
404            CatalogItemType::MaterializedView,
405            MZ_INTERNAL_SCHEMA,
406            "mz_cluster_reconfigurations",
407        ),
408        // The mz_audit_events MV gained a `metric-sink` arm in its object_type
409        // CASE, changing its SQL fingerprint, so it needs an explicit
410        // replacement step. See the NOTE above: this version must stay at the
411        // workspace's current dev version until the change ships.
412        MigrationStep::replacement(
413            "26.39.0-dev.0",
414            CatalogItemType::MaterializedView,
415            MZ_CATALOG_SCHEMA,
416            "mz_audit_events",
417        ),
418        // Required because we added the `mz_metric_sinks_ind` builtin index.
419        // make_mz_indexes inlines the builtin-index set as VALUES, so any add or
420        // remove changes its SQL fingerprint and requires an explicit
421        // replacement. See the NOTE above: this version must stay at the
422        // workspace's current dev version until the change ships. The addition
423        // is unshipped, so this step supersedes the earlier `26.39.0-dev.0`
424        // `mz_indexes` step (which covered `mz_object_graph_edges_ind`): a
425        // replacement recreates `mz_indexes` from its current definition, so a
426        // single step at the current dev version covers every earlier change too.
427        MigrationStep::replacement(
428            "26.40.0-dev.0",
429            CatalogItemType::MaterializedView,
430            MZ_CATALOG_SCHEMA,
431            "mz_indexes",
432        ),
433        // Converting mz_tables and mz_views from builtin tables to
434        // materialized views over mz_catalog_raw changes their catalog
435        // fingerprints, so each needs an explicit replacement step. See the
436        // NOTE above: this version must stay at the workspace's current dev
437        // version until the change ships.
438        MigrationStep::replacement(
439            "26.39.0-dev.0",
440            CatalogItemType::MaterializedView,
441            MZ_CATALOG_SCHEMA,
442            "mz_tables",
443        ),
444        MigrationStep::replacement(
445            "26.39.0-dev.0",
446            CatalogItemType::MaterializedView,
447            MZ_CATALOG_SCHEMA,
448            "mz_views",
449        ),
450        // Required because we added the `mz_cluster_replica_resource_usage` builtin log.
451        // make_mz_indexes and make_mz_sources inline the builtin-log set as
452        // VALUES, so adding one changes both MVs' SQL fingerprints. See the NOTE
453        // above: this version must stay at the workspace's current dev version
454        // until the change ships.
455        MigrationStep::replacement(
456            "26.40.0-dev.0",
457            CatalogItemType::MaterializedView,
458            MZ_CATALOG_SCHEMA,
459            "mz_indexes",
460        ),
461        MigrationStep::replacement(
462            "26.40.0-dev.0",
463            CatalogItemType::MaterializedView,
464            MZ_CATALOG_SCHEMA,
465            "mz_sources",
466        ),
467        // Converting mz_object_dependencies from a builtin table to a
468        // materialized view over mz_catalog_raw changes its catalog
469        // fingerprint, so it needs an explicit replacement step. See the
470        // NOTE above: this version must stay at the workspace's current dev
471        // version until the change ships.
472        MigrationStep::replacement(
473            "26.41.0-dev.0",
474            CatalogItemType::MaterializedView,
475            MZ_INTERNAL_SCHEMA,
476            "mz_object_dependencies",
477        ),
478        // Adding the `swap_bytes` column to `mz_cluster_replica_metrics_history`
479        // is a backward-compatible append, so the shard schema can evolve in
480        // place. See the NOTE above: this version must stay at the workspace's
481        // current dev version until the change ships.
482        MigrationStep::evolution(
483            "26.43.0-dev.0",
484            CatalogItemType::Source,
485            MZ_INTERNAL_SCHEMA,
486            "mz_cluster_replica_metrics_history",
487        ),
488        MigrationStep::evolution(
489            "26.43.0-dev.0",
490            CatalogItemType::Table,
491            MZ_INTERNAL_SCHEMA,
492            "mz_replica_hydration_history",
493        ),
494        // Converting mz_object_global_ids from a builtin table to a
495        // materialized view over mz_catalog_raw changes its catalog
496        // fingerprint.
497        MigrationStep::replacement(
498            "26.44.0-dev.0",
499            CatalogItemType::MaterializedView,
500            MZ_INTERNAL_SCHEMA,
501            "mz_object_global_ids",
502        ),
503        // Converting mz_source_references from a builtin table to a
504        // materialized view over mz_catalog_raw changes its catalog
505        // fingerprint.
506        MigrationStep::replacement(
507            "26.45.0-dev.0",
508            CatalogItemType::MaterializedView,
509            MZ_INTERNAL_SCHEMA,
510            "mz_source_references",
511        ),
512        // Converting mz_replacements from a builtin table to a
513        // materialized view over mz_catalog_raw changes its catalog
514        // fingerprint.
515        MigrationStep::replacement(
516            "26.46.0-dev.0",
517            CatalogItemType::MaterializedView,
518            MZ_INTERNAL_SCHEMA,
519            "mz_replacements",
520        ),
521        // mz_indexes reads builtin indexes from mz_builtin_indexes
522        // and builtin logs from mz_builtin_log_indexes instead of
523        // inlining them, which changes its SQL fingerprint.
524        MigrationStep::replacement(
525            "26.47.0-dev.0",
526            CatalogItemType::MaterializedView,
527            MZ_CATALOG_SCHEMA,
528            "mz_indexes",
529        ),
530        // mz_sources reads builtin sources from mz_builtin_sources
531        // and builtin logs from mz_builtin_log_indexes
532        // instead of inlining them, which changes its SQL fingerprint.
533        MigrationStep::replacement(
534            "26.47.0-dev.0",
535            CatalogItemType::MaterializedView,
536            MZ_CATALOG_SCHEMA,
537            "mz_sources",
538        ),
539        // Converting mz_history_retention_strategies from a builtin table to a
540        // materialized view over mz_catalog_raw changes its catalog
541        // fingerprint.
542        MigrationStep::replacement(
543            "26.47.0-dev.0",
544            CatalogItemType::MaterializedView,
545            MZ_INTERNAL_SCHEMA,
546            "mz_history_retention_strategies",
547        ),
548        // Converting mz_materialized_view_refresh_strategies from a builtin table to a
549        // materialized view over mz_catalog_raw changes its catalog
550        // fingerprint. We also change columns:
551        // - aligned_at (timestamptz) -> aligned_to_expression (text)
552        // - at (timestamptz)-> at_expression (text)
553        MigrationStep::replacement(
554            "26.47.0-dev.0",
555            CatalogItemType::MaterializedView,
556            MZ_INTERNAL_SCHEMA,
557            "mz_materialized_view_refresh_strategies",
558        ),
559        // Converting mz_columns from a builtin table to a
560        // materialized view over mz_catalog_raw changes its catalog
561        // fingerprint.
562        MigrationStep::replacement(
563            "26.49.0-dev.0",
564            CatalogItemType::MaterializedView,
565            MZ_CATALOG_SCHEMA,
566            "mz_columns",
567        ),
568        // Converting mz_index_columns from a builtin table to a
569        // materialized view over mz_catalog_raw changes its catalog
570        // fingerprint.
571        MigrationStep::replacement(
572            "26.49.0-dev.0",
573            CatalogItemType::MaterializedView,
574            MZ_CATALOG_SCHEMA,
575            "mz_index_columns",
576        ),
577        // Adding the `disabled` column to mz_cluster_replica_sizes. The table
578        // is rewritten at every startup, so replacing the shard loses nothing.
579        MigrationStep::replacement(
580            "26.51.0-dev.0",
581            CatalogItemType::Table,
582            MZ_CATALOG_SCHEMA,
583            "mz_cluster_replica_sizes",
584        ),
585        // These three MVs recognize query policies in their SQL definitions. Their
586        // row schemas are unchanged, but their SQL fingerprints change, requiring
587        // explicit migrations for `update_fingerprints` to accept the upgrade.
588        MigrationStep::replacement(
589            "26.52.0-dev.0",
590            CatalogItemType::MaterializedView,
591            MZ_CATALOG_SCHEMA,
592            "mz_audit_events",
593        ),
594        MigrationStep::replacement(
595            "26.52.0-dev.0",
596            CatalogItemType::MaterializedView,
597            MZ_CATALOG_SCHEMA,
598            "mz_default_privileges",
599        ),
600        MigrationStep::replacement(
601            "26.52.0-dev.0",
602            CatalogItemType::MaterializedView,
603            MZ_INTERNAL_SCHEMA,
604            "mz_comments",
605        ),
606    ]
607});
608
609/// A migration required to upgrade past a specific version.
610#[derive(Clone, Debug)]
611struct MigrationStep {
612    /// The build version that requires this migration.
613    version: Version,
614    /// The object that requires migration.
615    object: SystemObjectDescription,
616    /// The migration mechanism to be used.
617    mechanism: Mechanism,
618}
619
620impl MigrationStep {
621    /// Helper to construct an `Evolution` migration step.
622    fn evolution(version: &str, type_: CatalogItemType, schema: &str, name: &str) -> Self {
623        Self {
624            version: Version::parse(version).expect("valid"),
625            object: SystemObjectDescription {
626                schema_name: schema.into(),
627                object_type: type_,
628                object_name: name.into(),
629            },
630            mechanism: Mechanism::Evolution,
631        }
632    }
633
634    /// Helper to construct a `Replacement` migration step.
635    fn replacement(version: &str, type_: CatalogItemType, schema: &str, name: &str) -> Self {
636        Self {
637            version: Version::parse(version).expect("valid"),
638            object: SystemObjectDescription {
639                schema_name: schema.into(),
640                object_type: type_,
641                object_name: name.into(),
642            },
643            mechanism: Mechanism::Replacement,
644        }
645    }
646}
647
648/// The mechanism to use to migrate the schema of a builtin collection.
649#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
650#[allow(dead_code)]
651enum Mechanism {
652    /// Persist schema evolution.
653    ///
654    /// Keeps existing contents but only works for schema changes that are backward compatible
655    /// according to [`backward_compatible`].
656    Evolution,
657    /// Shard replacement.
658    ///
659    /// Works for arbitrary schema changes but loses existing contents.
660    Replacement,
661}
662
663/// The result of a builtin schema migration.
664pub(super) struct MigrationResult {
665    /// IDs of items that got a new shard from the migration shard: `Replacement`-migrated items
666    /// and builtin storage collections that had none.
667    pub replaced_items: BTreeSet<CatalogItemId>,
668    /// A cleanup action to take once the migration has been made durable.
669    pub cleanup_action: BoxFuture<'static, ()>,
670}
671
672impl Default for MigrationResult {
673    fn default() -> Self {
674        Self {
675            replaced_items: Default::default(),
676            cleanup_action: async {}.boxed(),
677        }
678    }
679}
680
681/// Run builtin schema migrations.
682///
683/// This is the entry point used by adapter when opening the catalog. It uses the hardcoded
684/// `BUILTINS` and `MIGRATIONS` lists to initialize the lists of available builtins and required
685/// migrations, respectively.
686pub(super) async fn run(
687    build_info: &BuildInfo,
688    deploy_generation: u64,
689    txn: &mut Transaction<'_>,
690    config: BuiltinItemMigrationConfig,
691) -> Result<MigrationResult, Error> {
692    // Sanity check to ensure we're not touching durable state in read-only mode.
693    assert_eq!(config.read_only, txn.is_savepoint());
694
695    // Tests may provide a dummy build info that confuses the migration step selection logic. Skip
696    // migrations if we observe this build info.
697    if *build_info == DUMMY_BUILD_INFO {
698        return Ok(MigrationResult::default());
699    }
700
701    let Some(durable_version) = get_migration_version(txn) else {
702        // New catalog; nothing to do.
703        return Ok(MigrationResult::default());
704    };
705    let build_version = build_info.semver_version();
706
707    let collection_metadata = txn.get_collection_metadata();
708    let system_objects = txn
709        .get_system_object_mappings()
710        .map(|m| {
711            let object = m.description;
712            let global_id = m.unique_identifier.global_id;
713            let shard_id = collection_metadata.get(&global_id).copied();
714            let Some((_, builtin)) = BUILTIN_LOOKUP.get(&object) else {
715                panic!("missing builtin {object:?}");
716            };
717            let info = ObjectInfo {
718                global_id,
719                shard_id,
720                builtin,
721                fingerprint: m.unique_identifier.fingerprint,
722            };
723            (object, info)
724        })
725        .collect();
726
727    let migration_shard = txn.get_builtin_migration_shard().expect("must exist");
728
729    let migration = Migration {
730        source_version: durable_version.clone(),
731        target_version: build_version.clone(),
732        deploy_generation,
733        system_objects,
734        migration_shard,
735        config,
736    };
737
738    let result = migration.run(&MIGRATIONS).await.map_err(|e| {
739        Error::new(ErrorKind::FailedBuiltinSchemaMigration {
740            last_seen_version: durable_version.to_string(),
741            this_version: build_version.to_string(),
742            cause: e.to_string(),
743        })
744    })?;
745
746    result.apply(txn);
747
748    let replaced_items = txn
749        .get_system_object_mappings()
750        .map(|m| m.unique_identifier)
751        .filter(|ids| result.new_shards.contains_key(&ids.global_id))
752        .map(|ids| ids.catalog_id)
753        .collect();
754
755    Ok(MigrationResult {
756        replaced_items,
757        cleanup_action: result.cleanup_action,
758    })
759}
760
761/// Result produced by `Migration::run`.
762struct MigrationRunResult {
763    new_shards: BTreeMap<GlobalId, ShardId>,
764    new_fingerprints: BTreeMap<SystemObjectDescription, String>,
765    shards_to_finalize: BTreeSet<ShardId>,
766    cleanup_action: BoxFuture<'static, ()>,
767}
768
769impl Default for MigrationRunResult {
770    fn default() -> Self {
771        Self {
772            new_shards: BTreeMap::new(),
773            new_fingerprints: BTreeMap::new(),
774            shards_to_finalize: BTreeSet::new(),
775            cleanup_action: async {}.boxed(),
776        }
777    }
778}
779
780impl MigrationRunResult {
781    /// Apply this migration result to the given transaction.
782    fn apply(&self, txn: &mut Transaction<'_>) {
783        // Update collection metadata.
784        let replaced_ids = self.new_shards.keys().copied().collect();
785        let old_metadata = txn.delete_collection_metadata(replaced_ids);
786        txn.insert_collection_metadata(self.new_shards.clone())
787            .expect("inserting unique shards IDs after deleting existing entries");
788
789        // Register shards for finalization.
790        let mut unfinalized_shards: BTreeSet<_> =
791            old_metadata.into_iter().map(|(_, sid)| sid).collect();
792        unfinalized_shards.extend(self.shards_to_finalize.iter().copied());
793        txn.insert_unfinalized_shards(unfinalized_shards)
794            .expect("cannot fail");
795
796        // Update fingerprints.
797        let mappings = txn
798            .get_system_object_mappings()
799            .filter_map(|m| {
800                let fingerprint = self.new_fingerprints.get(&m.description)?;
801                Some(SystemObjectMapping {
802                    description: m.description,
803                    unique_identifier: SystemObjectUniqueIdentifier {
804                        catalog_id: m.unique_identifier.catalog_id,
805                        global_id: m.unique_identifier.global_id,
806                        fingerprint: fingerprint.clone(),
807                    },
808                })
809            })
810            .collect();
811        txn.set_system_object_mappings(mappings)
812            .expect("filtered existing mappings remain unique");
813    }
814}
815
816/// Information about a system object required to run a `Migration`.
817#[derive(Clone, Debug)]
818struct ObjectInfo {
819    global_id: GlobalId,
820    shard_id: Option<ShardId>,
821    builtin: &'static Builtin<NameReference>,
822    fingerprint: String,
823}
824
825/// Context of a builtin schema migration.
826struct Migration {
827    /// The version we are migrating from.
828    ///
829    /// Same as the build version of the most recent leader process that successfully performed
830    /// migrations.
831    source_version: Version,
832    /// The version we are migration to.
833    ///
834    /// Same as the build version of this process.
835    target_version: Version,
836    /// The deploy generation of this process.
837    deploy_generation: u64,
838    /// Information about all objects in the system.
839    system_objects: BTreeMap<SystemObjectDescription, ObjectInfo>,
840    /// The ID of the migration shard.
841    migration_shard: ShardId,
842    /// Additional configuration.
843    config: BuiltinItemMigrationConfig,
844}
845
846/// Whether `builtin` is a storage collection with a shard of its own.
847fn has_own_shard(builtin: &Builtin<NameReference>) -> bool {
848    use Builtin::*;
849    match builtin {
850        Table(..) | MaterializedView(..) => true,
851        // `mz_catalog_raw`'s shard is the catalog shard, which
852        // `Catalog::initialize_storage_state` registers.
853        Source(source) => **source != *MZ_CATALOG_RAW,
854        Log(..) | View(..) | Type(..) | Func(..) | Index(..) | Connection(..) => false,
855    }
856}
857
858/// Whether `builtin` participates in a forced migration using `mechanism`.
859fn participates_in_forced_migration(
860    builtin: &Builtin<NameReference>,
861    mechanism: Mechanism,
862) -> bool {
863    use Builtin::*;
864    match builtin {
865        // A forced replacement allocates a fresh shard, which discards the
866        // table's contents. Exclude the tables whose contents are the point:
867        // storage usage is retained for billing, and hydration histories cannot
868        // be rebuilt from any other source.
869        //
870        // Hydration history tables take part in a forced `Evolution`, which
871        // keeps the rows. They have to: dev upgrades force one for every object,
872        // and a table left out of the plan never gets its new schema registered.
873        // `update_fingerprints` then panics at open as soon as the desc changes.
874        // See the tripwire in `validate_migration_steps` for how to give up the
875        // replacement exemption deliberately.
876        Table(table) => {
877            **table != *MZ_STORAGE_USAGE_BY_SHARD
878                && (mechanism != Mechanism::Replacement
879                    || (**table != *MZ_OBJECT_HYDRATION_HISTORY
880                        && **table != *MZ_REPLICA_HYDRATION_HISTORY))
881        }
882        _ => has_own_shard(builtin),
883    }
884}
885
886impl Migration {
887    async fn run(self, steps: &[MigrationStep]) -> anyhow::Result<MigrationRunResult> {
888        info!(
889            deploy_generation = %self.deploy_generation,
890            "running builtin schema migration: {} -> {}",
891            self.source_version, self.target_version
892        );
893
894        self.validate_migration_steps(steps);
895
896        // Version-based migration filter fails for dev versions, see for example
897        // https://github.com/MaterializeInc/database-issues/issues/11335
898        let force_migration = if self.source_version != self.target_version
899            && self.source_version.pre.as_str().starts_with("dev")
900            && self.config.force_migration.is_none()
901        {
902            Some("evolution".to_string())
903        } else {
904            self.config.force_migration.clone()
905        };
906
907        let (force, plan) = match force_migration.as_deref() {
908            None => (false, self.plan_migration(steps)),
909            Some("evolution") => (true, self.plan_forced_migration(Mechanism::Evolution)),
910            Some("replacement") => (true, self.plan_forced_migration(Mechanism::Replacement)),
911            Some(other) => panic!("unknown force migration mechanism: {other}"),
912        };
913        let plan = self.drop_shardless(plan);
914
915        if self.source_version == self.target_version && !force {
916            info!("skipping migration: already at target version");
917            return Ok(MigrationRunResult::default());
918        } else if self.source_version > self.target_version {
919            bail!("downgrade not supported");
920        }
921
922        // In leader mode, upgrade the version of the migration shard to the target version.
923        // This fences out any readers at lower versions.
924        if !self.config.read_only {
925            self.upgrade_migration_shard_version().await;
926        }
927
928        let allocate = self.plan_allocation();
929
930        info!(?allocate, "executing migration plan: {plan:?}");
931
932        self.migrate_evolve(&plan.evolve).await?;
933        let new_shards = self
934            .get_or_insert_shards(&[plan.replace.as_slice(), &allocate].concat())
935            .await?;
936
937        let mut migrated_objects = BTreeSet::new();
938        migrated_objects.extend(plan.evolve);
939        migrated_objects.extend(plan.replace);
940
941        let new_fingerprints = self.update_fingerprints(&migrated_objects)?;
942
943        let (shards_to_finalize, cleanup_action) = self.cleanup().await?;
944
945        Ok(MigrationRunResult {
946            new_shards,
947            new_fingerprints,
948            shards_to_finalize,
949            cleanup_action,
950        })
951    }
952
953    /// Sanity check the given migration steps.
954    ///
955    /// If any of these checks fail, that's a bug in Materialize, and we panic immediately.
956    fn validate_migration_steps(&self, steps: &[MigrationStep]) {
957        for step in steps {
958            assert!(
959                step.version <= self.target_version,
960                "migration step version greater than target version: {} > {}",
961                step.version,
962                self.target_version,
963            );
964
965            let object = &step.object;
966
967            // `mz_storage_usage_by_shard` cannot be migrated for multiple reasons. Firstly, it would
968            // cause the table to be truncated because the contents are not also stored in the durable
969            // catalog. Secondly, we prune `mz_storage_usage_by_shard` of old events in the background
970            // on startup. The correctness of that pruning relies on there being no other retractions
971            // to `mz_storage_usage_by_shard`.
972            //
973            // TODO: Confirm the above reasoning, it might be outdated?
974            assert_ne!(
975                &*MZ_STORAGE_USAGE_BY_SHARD_DESCRIPTION, object,
976                "mz_storage_usage_by_shard cannot be migrated or else the table will be truncated"
977            );
978
979            // Same hazard as `mz_storage_usage_by_shard`: the startup pruner
980            // (`Coordinator::prune_arrangement_sizes_history_on_startup`) assumes it is
981            // the only source of retractions, so migration-driven truncation would break it.
982            assert_ne!(
983                &*MZ_OBJECT_ARRANGEMENT_SIZE_HISTORY_DESCRIPTION, object,
984                "mz_object_arrangement_size_history cannot be migrated or else the table will be truncated"
985            );
986
987            // Unlike the two tables above, there is no correctness hazard here, a
988            // truncation would only lose history. This is a tripwire so that the
989            // loss is chosen rather than stumbled into: if a schema change to
990            // this table is worth clearing it for, remove this assert along with
991            // the exemption in `plan_forced_migration`, and say in the release
992            // notes that the history restarts.
993            //
994            // Only `Replacement` loses the rows. An `Evolution` keeps the shard
995            // and its contents, so it is the path a schema change to this table
996            // should take and we let it through.
997            if step.mechanism == Mechanism::Replacement {
998                assert_ne!(
999                    &*MZ_OBJECT_HYDRATION_HISTORY_DESCRIPTION, object,
1000                    "replacing mz_object_hydration_history clears it, see the comment above"
1001                );
1002                assert_ne!(
1003                    &*MZ_REPLICA_HYDRATION_HISTORY_DESCRIPTION, object,
1004                    "replacing mz_replica_hydration_history clears it, see the comment above"
1005                );
1006            }
1007
1008            // `mz_catalog_raw` cannot be migrated because it contains the durable catalog and it
1009            // wouldn't be very durable if we allowed it to be truncated.
1010            assert_ne!(
1011                &*MZ_CATALOG_RAW_DESCRIPTION, object,
1012                "mz_catalog_raw cannot be migrated"
1013            );
1014
1015            // The 0dt caught-up gate reads the leader's `mz_cluster_replica_frontiers` shard for
1016            // the live frontiers it checks every collection against. Migrating it via `Replacement`
1017            // hands us a fresh shard we write ourselves, so the gate would compare us against
1018            // ourselves instead of against the leader.
1019            assert_ne!(
1020                &*MZ_CLUSTER_REPLICA_FRONTIERS_DESCRIPTION, object,
1021                "mz_cluster_replica_frontiers cannot be migrated or else the 0dt caught-up gate loses its live-frontier reference"
1022            );
1023            assert_ne!(
1024                &*MZ_COMPUTE_HYDRATION_TIMES_DESCRIPTION, object,
1025                "mz_compute_hydration_times cannot be migrated or else the 0dt caught-up gate loses its leader-hydration reference"
1026            );
1027
1028            let Some(object_info) = self.system_objects.get(object) else {
1029                panic!("migration step for non-existent builtin: {object:?}");
1030            };
1031
1032            let builtin = object_info.builtin;
1033            assert!(
1034                has_own_shard(builtin),
1035                "schema migration not supported for builtin: {builtin:?}",
1036            );
1037        }
1038    }
1039
1040    /// Select for each object to migrate the appropriate migration mechanism.
1041    fn plan_migration(&self, steps: &[MigrationStep]) -> Plan {
1042        // Ignore any steps at versions before `source_version`.
1043        let steps = steps.iter().filter(|s| s.version > self.source_version);
1044
1045        // Select a mechanism for each object, according to the requested migrations:
1046        //  * If any `Replacement` was requested, use `Replacement`.
1047        //  * Otherwise, (i.e. only `Evolution` was requested), use `Evolution`.
1048        let mut by_object = BTreeMap::new();
1049        for step in steps {
1050            if let Some(entry) = by_object.get_mut(&step.object) {
1051                *entry = match (step.mechanism, *entry) {
1052                    (Mechanism::Evolution, Mechanism::Evolution) => Mechanism::Evolution,
1053                    (Mechanism::Replacement, _) | (_, Mechanism::Replacement) => {
1054                        Mechanism::Replacement
1055                    }
1056                };
1057            } else {
1058                by_object.insert(step.object.clone(), step.mechanism);
1059            }
1060        }
1061
1062        let mut plan = Plan::default();
1063        for (object, mechanism) in by_object {
1064            match mechanism {
1065                Mechanism::Evolution => plan.evolve.push(object),
1066                Mechanism::Replacement => plan.replace.push(object),
1067            }
1068        }
1069
1070        plan
1071    }
1072
1073    /// Plan a forced migration of all objects using the given mechanism.
1074    fn plan_forced_migration(&self, mechanism: Mechanism) -> Plan {
1075        let objects = self
1076            .system_objects
1077            .iter()
1078            .filter(|(_, info)| participates_in_forced_migration(info.builtin, mechanism))
1079            .map(|(object, _)| object.clone())
1080            .collect();
1081
1082        let mut plan = Plan::default();
1083        match mechanism {
1084            Mechanism::Evolution => plan.evolve = objects,
1085            Mechanism::Replacement => plan.replace = objects,
1086        }
1087
1088        plan
1089    }
1090
1091    /// Drop objects that have no shard registered from the plan.
1092    ///
1093    /// A builtin without a shard does not exist in persist yet: either it was added in the target
1094    /// version, or the source version predates it entirely (an upgrade from before the builtin
1095    /// was introduced can reach an `Evolution` step registered for a later version). In both
1096    /// cases the shard gets allocated at the target schema, from the migration shard (see
1097    /// `plan_allocation`), and there is nothing to evolve or replace. Applied to every plan,
1098    /// forced or versioned, so that both paths agree; a read-only process that reached
1099    /// `migrate_evolve_one` with such an object would otherwise bail out and crash-loop.
1100    fn drop_shardless(&self, mut plan: Plan) -> Plan {
1101        let has_shard = |object: &SystemObjectDescription| {
1102            self.system_objects
1103                .get(object)
1104                .is_none_or(|info| info.shard_id.is_some())
1105        };
1106        plan.evolve.retain(has_shard);
1107        plan.replace.retain(has_shard);
1108        plan
1109    }
1110
1111    /// Select the builtin storage collections that get a shard allocated from the migration shard:
1112    /// those without a registered shard, in practice those added since the source version.
1113    ///
1114    /// A read-only process never commits the shard the storage controller would allocate for
1115    /// them, so the promoted leader would allocate another. From the migration shard, every
1116    /// process of this version and deploy generation gets the same shards for them, given the same
1117    /// global ids (see `get_or_insert_shards`). The current leader does not know these shards, so the
1118    /// read-only process can write them, and what it writes survives promotion.
1119    fn plan_allocation(&self) -> Vec<SystemObjectDescription> {
1120        self.system_objects
1121            .iter()
1122            .filter(|(_, info)| info.shard_id.is_none() && has_own_shard(info.builtin))
1123            .map(|(object, _)| object.clone())
1124            .collect()
1125    }
1126
1127    /// Upgrade the migration shard to the target version.
1128    async fn upgrade_migration_shard_version(&self) {
1129        let persist = &self.config.persist_client;
1130        let diagnostics = Diagnostics {
1131            shard_name: "builtin_migration".to_string(),
1132            handle_purpose: format!("migration shard upgrade @ {}", self.target_version),
1133        };
1134
1135        persist
1136            .upgrade_version::<migration_shard::Key, ShardId, Timestamp, StorageDiff>(
1137                self.migration_shard,
1138                diagnostics,
1139            )
1140            .await
1141            .expect("valid usage");
1142    }
1143
1144    /// Migrate the given objects using the `Evolution` mechanism.
1145    async fn migrate_evolve(&self, objects: &[SystemObjectDescription]) -> anyhow::Result<()> {
1146        for object in objects {
1147            self.migrate_evolve_one(object).await?;
1148        }
1149        Ok(())
1150    }
1151
1152    async fn migrate_evolve_one(&self, object: &SystemObjectDescription) -> anyhow::Result<()> {
1153        let persist = &self.config.persist_client;
1154
1155        let Some(object_info) = self.system_objects.get(object) else {
1156            bail!("missing builtin {object:?}");
1157        };
1158        let id = object_info.global_id;
1159
1160        let Some(shard_id) = object_info.shard_id else {
1161            // No shard is registered for this builtin. In leader mode, this is fine, the shard
1162            // comes from the migration shard (see `plan_allocation`). In read-only mode, we might
1163            // be racing with the leader to register the shard and it's unclear what sort of
1164            // confusion can arise from that -- better to bail out in this case.
1165            //
1166            // TODO: Consider removing this branch. `drop_shardless` keeps objects without a shard
1167            // out of every plan, so it is unreachable.
1168            if self.config.read_only {
1169                bail!("missing shard ID for builtin {object:?} ({id})");
1170            } else {
1171                return Ok(());
1172            }
1173        };
1174
1175        let target_desc = match object_info.builtin {
1176            Builtin::Table(table) => &table.desc,
1177            Builtin::Source(source) => &source.desc,
1178            Builtin::MaterializedView(mv) => &mv.desc,
1179            _ => bail!("not a storage collection: {object:?}"),
1180        };
1181
1182        let diagnostics = Diagnostics {
1183            shard_name: id.to_string(),
1184            handle_purpose: format!("builtin schema migration @ {}", self.target_version),
1185        };
1186        let source_schema = persist
1187            .latest_schema::<SourceData, (), Timestamp, StorageDiff>(shard_id, diagnostics.clone())
1188            .await
1189            .expect("valid usage");
1190
1191        info!(?object, %id, %shard_id, ?source_schema, ?target_desc, "migrating by evolution");
1192
1193        if self.config.read_only {
1194            // In read-only mode, only check that the new schema is backward compatible.
1195            // We'll register it when/if we restart in leader mode.
1196            if let Some((_, source_desc, _)) = &source_schema {
1197                let old = mz_persist_types::columnar::data_type::<SourceData>(source_desc)?;
1198                let new = mz_persist_types::columnar::data_type::<SourceData>(target_desc)?;
1199                if backward_compatible(&old, &new).is_none() {
1200                    bail!(
1201                        "incompatible schema evolution for {object:?}: \
1202                         {source_desc:?} -> {target_desc:?}"
1203                    );
1204                }
1205            }
1206
1207            return Ok(());
1208        }
1209
1210        let (mut schema_id, mut source_desc) = match source_schema {
1211            Some((schema_id, source_desc, _)) => (schema_id, source_desc),
1212            None => {
1213                // If no schema was previously registered, simply try to register the new one. This
1214                // might fail due to a concurrent registration, in which case we'll fall back to
1215                // `compare_and_evolve_schema`.
1216
1217                debug!(%id, %shard_id, "no previous schema found; registering initial one");
1218                let schema_id = persist
1219                    .register_schema::<SourceData, (), Timestamp, StorageDiff>(
1220                        shard_id,
1221                        target_desc,
1222                        &UnitSchema,
1223                        diagnostics.clone(),
1224                    )
1225                    .await
1226                    .expect("valid usage");
1227                if schema_id.is_some() {
1228                    return Ok(());
1229                }
1230
1231                debug!(%id, %shard_id, "schema registration failed; falling back to CaES");
1232                let (schema_id, source_desc, _) = persist
1233                    .latest_schema::<SourceData, (), Timestamp, StorageDiff>(
1234                        shard_id,
1235                        diagnostics.clone(),
1236                    )
1237                    .await
1238                    .expect("valid usage")
1239                    .expect("known to exist");
1240
1241                (schema_id, source_desc)
1242            }
1243        };
1244
1245        loop {
1246            // Evolving the schema might fail if another process evolved the schema concurrently,
1247            // in which case we need to retry. Most likely the other process evolved the schema to
1248            // our own target schema and the second try is a no-op.
1249
1250            debug!(%id, %shard_id, %schema_id, ?source_desc, ?target_desc, "attempting CaES");
1251            let result = persist
1252                .compare_and_evolve_schema::<SourceData, (), Timestamp, StorageDiff>(
1253                    shard_id,
1254                    schema_id,
1255                    target_desc,
1256                    &UnitSchema,
1257                    diagnostics.clone(),
1258                )
1259                .await
1260                .expect("valid usage");
1261
1262            match result {
1263                CaESchema::Ok(schema_id) => {
1264                    debug!(%id, %shard_id, %schema_id, "schema evolved successfully");
1265                    break;
1266                }
1267                CaESchema::Incompatible => bail!(
1268                    "incompatible schema evolution for {object:?}: \
1269                     {source_desc:?} -> {target_desc:?}"
1270                ),
1271                CaESchema::ExpectedMismatch {
1272                    schema_id: new_id,
1273                    key,
1274                    val: UnitSchema,
1275                } => {
1276                    schema_id = new_id;
1277                    source_desc = key;
1278                }
1279            }
1280        }
1281
1282        Ok(())
1283    }
1284
1285    /// Get shards for `objects` from the migration shard, inserting new ones where it has none at
1286    /// this version and deploy generation.
1287    async fn get_or_insert_shards(
1288        &self,
1289        objects: &[SystemObjectDescription],
1290    ) -> anyhow::Result<BTreeMap<GlobalId, ShardId>> {
1291        if objects.is_empty() {
1292            return Ok(Default::default());
1293        }
1294
1295        let mut wanted = BTreeSet::new();
1296        for object in objects {
1297            let Some(info) = self.system_objects.get(object) else {
1298                bail!("missing id for builtin {object:?}");
1299            };
1300            // An object without a shard may have its global id only in this process's catalog
1301            // transaction. A read-only process never commits that transaction, so a later boot can
1302            // give the id to another builtin. So the entry also names the object, and a later boot
1303            // only reuses it for the same global id and object.
1304            let entry_object = info.shard_id.is_none().then(|| object.into());
1305            wanted.insert((info.global_id, entry_object));
1306        }
1307
1308        let diagnostics = Diagnostics {
1309            shard_name: "builtin_migration".to_string(),
1310            handle_purpose: format!("builtin schema migration @ {}", self.target_version),
1311        };
1312        let (mut persist_write, mut persist_read) =
1313            self.open_migration_shard(diagnostics.clone()).await;
1314
1315        info!(
1316            ?objects,
1317            ?wanted,
1318            "allocating shards from the migration shard"
1319        );
1320
1321        // Fetch replacement shard IDs from the migration shard, or insert new ones if none exist.
1322        // This can fail due to writes by concurrent processes, so we need to retry.
1323        let replaced_shards = loop {
1324            if let Some(shards) = self
1325                .try_get_or_insert_shards(&wanted, &mut persist_write, &mut persist_read)
1326                .await?
1327            {
1328                break shards;
1329            }
1330        };
1331
1332        Ok(replaced_shards)
1333    }
1334
1335    /// Try to get or insert shards for the `wanted` entries into the migration shard, at
1336    /// `target_version` and `deploy_generation`. `wanted` holds the global id and
1337    /// `migration_shard::Key::object` of each entry.
1338    ///
1339    /// This method looks for existing entries in the migration shards and returns those if they
1340    /// are present. Otherwise it generates new shard IDs and tries to insert them.
1341    ///
1342    /// The result of this call is `None` if no existing entries were found and inserting new ones
1343    /// failed because of a concurrent write to the migration shard. In this case, the caller is
1344    /// expected to retry.
1345    async fn try_get_or_insert_shards(
1346        &self,
1347        wanted: &BTreeSet<(GlobalId, Option<migration_shard::ObjectKey>)>,
1348        persist_write: &mut WriteHandle<migration_shard::Key, ShardId, Timestamp, StorageDiff>,
1349        persist_read: &mut ReadHandle<migration_shard::Key, ShardId, Timestamp, StorageDiff>,
1350    ) -> anyhow::Result<Option<BTreeMap<GlobalId, ShardId>>> {
1351        let upper = persist_write.fetch_recent_upper().await;
1352        let write_ts = *upper.as_option().expect("migration shard not sealed");
1353
1354        let mut todo = wanted.clone();
1355        let mut replaced_shards = BTreeMap::new();
1356
1357        // Another process might already have done a shard replacement at our version and
1358        // generation, in which case we can directly reuse the replacement shards.
1359        //
1360        // Note that we can't assume that the previous process had the same `wanted` entries as we
1361        // do. The set of migrations to run depends on both the source and the target version, and
1362        // the migration shard is not keyed by source version. The previous writer might have seen
1363        // a different source version, if there was a concurrent migration by a leader process.
1364        if let Some(read_ts) = write_ts.step_back() {
1365            let pred = |key: &migration_shard::Key| {
1366                key.build_version == self.target_version
1367                    && key.deploy_generation == Some(self.deploy_generation)
1368            };
1369            if let Some(entries) = read_migration_shard(persist_read, read_ts, pred).await {
1370                for (key, shard_id) in entries {
1371                    let id = GlobalId::System(key.global_id);
1372                    if todo.remove(&(id, key.object)) {
1373                        replaced_shards.insert(id, shard_id);
1374                    }
1375                }
1376
1377                debug!(
1378                    %read_ts, ?replaced_shards, ?todo,
1379                    "found existing entries in migration shard",
1380                );
1381            }
1382
1383            if todo.is_empty() {
1384                return Ok(Some(replaced_shards));
1385            }
1386        }
1387
1388        // Generate new shard IDs and attempt to insert them into the migration shard. If we get a
1389        // CaA failure at `write_ts` that means a concurrent process has inserted in the meantime
1390        // and we need to re-check the migration shard contents.
1391        let mut updates = Vec::new();
1392        for (id, object) in todo {
1393            let shard_id = ShardId::new();
1394            replaced_shards.insert(id, shard_id);
1395
1396            let GlobalId::System(global_id) = id else {
1397                bail!("attempt to migrate a non-system collection: {id}");
1398            };
1399            let key = migration_shard::Key {
1400                global_id,
1401                build_version: self.target_version.clone(),
1402                deploy_generation: Some(self.deploy_generation),
1403                object,
1404            };
1405            updates.push(((key, shard_id), write_ts, 1));
1406        }
1407
1408        let upper = Antichain::from_elem(write_ts);
1409        let new_upper = Antichain::from_elem(write_ts.step_forward());
1410        debug!(%write_ts, "attempting insert into migration shard");
1411        let result = persist_write
1412            .compare_and_append(updates, upper, new_upper)
1413            .await
1414            .expect("valid usage");
1415
1416        match result {
1417            Ok(()) => {
1418                debug!(
1419                    %write_ts, ?replaced_shards,
1420                    "successfully inserted into migration shard"
1421                );
1422                Ok(Some(replaced_shards))
1423            }
1424            Err(_mismatch) => Ok(None),
1425        }
1426    }
1427
1428    /// Open writer and reader for the migration shard.
1429    async fn open_migration_shard(
1430        &self,
1431        diagnostics: Diagnostics,
1432    ) -> (
1433        WriteHandle<migration_shard::Key, ShardId, Timestamp, StorageDiff>,
1434        ReadHandle<migration_shard::Key, ShardId, Timestamp, StorageDiff>,
1435    ) {
1436        let persist = &self.config.persist_client;
1437
1438        persist
1439            .open(
1440                self.migration_shard,
1441                Arc::new(migration_shard::KeySchema),
1442                Arc::new(ShardIdSchema),
1443                diagnostics,
1444                USE_CRITICAL_SINCE_CATALOG.get(persist.dyncfgs()),
1445            )
1446            .await
1447            .expect("valid usage")
1448    }
1449
1450    /// Open a [`SinceHandle`] for the migration shard.
1451    async fn open_migration_shard_since(
1452        &self,
1453        diagnostics: Diagnostics,
1454    ) -> SinceHandle<migration_shard::Key, ShardId, Timestamp, StorageDiff> {
1455        self.config
1456            .persist_client
1457            .open_critical_since(
1458                self.migration_shard,
1459                // TODO: We may need to use a different critical reader
1460                // id for this if we want to be able to introspect it via SQL.
1461                PersistClient::CONTROLLER_CRITICAL_SINCE,
1462                Opaque::encode(&i64::MIN),
1463                diagnostics.clone(),
1464            )
1465            .await
1466            .expect("valid usage")
1467    }
1468
1469    /// Update the fingerprints for `migrated_items`.
1470    ///
1471    /// Returns the new fingerprints. Also asserts that the current fingerprints of all other
1472    /// system items match their builtin definitions.
1473    fn update_fingerprints(
1474        &self,
1475        migrated_items: &BTreeSet<SystemObjectDescription>,
1476    ) -> anyhow::Result<BTreeMap<SystemObjectDescription, String>> {
1477        let mut new_fingerprints = BTreeMap::new();
1478        for (object, object_info) in &self.system_objects {
1479            let id = object_info.global_id;
1480            let builtin = object_info.builtin;
1481
1482            let fingerprint = builtin.fingerprint();
1483            if fingerprint == object_info.fingerprint {
1484                continue; // fingerprint unchanged, nothing to do
1485            }
1486
1487            // Fingerprint mismatch is expected for a migrated item.
1488            let migrated = migrated_items.contains(object);
1489            // Some builtin types have schemas but no durable state. No migration needed for those.
1490            let ephemeral = matches!(
1491                builtin,
1492                Builtin::Log(_) | Builtin::View(_) | Builtin::Index(_),
1493            );
1494
1495            if migrated || ephemeral {
1496                new_fingerprints.insert(object.clone(), fingerprint);
1497            } else if builtin.runtime_alterable() {
1498                // Runtime alterable builtins have no meaningful builtin fingerprint, and a
1499                // sentinel value stored in the catalog.
1500                assert_eq!(
1501                    object_info.fingerprint, RUNTIME_ALTERABLE_FINGERPRINT_SENTINEL,
1502                    "fingerprint mismatch for runtime-alterable builtin {object:?} ({id})",
1503                );
1504            } else {
1505                panic!(
1506                    "fingerprint mismatch for builtin {builtin:?} ({id}): {} != {}",
1507                    fingerprint, object_info.fingerprint,
1508                );
1509            }
1510        }
1511
1512        Ok(new_fingerprints)
1513    }
1514
1515    /// Perform cleanup of migration state, i.e. the migration shard.
1516    ///
1517    /// Returns a list of shards to finalize, and a `Future` that must be run after the shard
1518    /// finalization has been durably enqueued. The `Future` is used to remove entries from the
1519    /// migration shard only after we know the respective shards will be finalized. Removing
1520    /// entries immediately would risk leaking the shards.
1521    ///
1522    /// We only perform cleanup in leader mode, to keep the durable state changes made by read-only
1523    /// processes a minimal as possible. Given that Materialize doesn't support version downgrades,
1524    /// it is safe to assume that any state for versions below the `target_version` is not needed
1525    /// anymore and can be cleaned up.
1526    ///
1527    /// Note that it is fine for cleanup to sometimes fail or be skipped. The size of the migration
1528    /// shard should always be pretty small, so keeping migration state around for longer isn't a
1529    /// concern. As a result, we can keep the logic simple here and skip doing cleanup in response
1530    /// to transient failures, instead of retrying.
1531    async fn cleanup(&self) -> anyhow::Result<(BTreeSet<ShardId>, BoxFuture<'static, ()>)> {
1532        let noop_action = async {}.boxed();
1533        let noop_result = (BTreeSet::new(), noop_action);
1534
1535        if self.config.read_only {
1536            return Ok(noop_result);
1537        }
1538
1539        let diagnostics = Diagnostics {
1540            shard_name: "builtin_migration".to_string(),
1541            handle_purpose: "builtin schema migration cleanup".into(),
1542        };
1543        let (mut persist_write, mut persist_read) =
1544            self.open_migration_shard(diagnostics.clone()).await;
1545        let mut persist_since = self.open_migration_shard_since(diagnostics.clone()).await;
1546
1547        let upper = persist_write.fetch_recent_upper().await.clone();
1548        let write_ts = *upper.as_option().expect("migration shard not sealed");
1549        let Some(read_ts) = write_ts.step_back() else {
1550            return Ok(noop_result);
1551        };
1552
1553        // Collect old entries to remove.
1554        let pred = |key: &migration_shard::Key| key.build_version < self.target_version;
1555        let Some(stale_entries) = read_migration_shard(&mut persist_read, read_ts, pred).await
1556        else {
1557            return Ok(noop_result);
1558        };
1559
1560        debug!(
1561            ?stale_entries,
1562            "cleaning migration shard up to version {}", self.target_version,
1563        );
1564
1565        let current_shards: BTreeMap<_, _> = self
1566            .system_objects
1567            .values()
1568            .filter_map(|o| o.shard_id.map(|shard_id| (o.global_id, shard_id)))
1569            .collect();
1570
1571        let mut shards_to_finalize = BTreeSet::new();
1572        let mut retractions = Vec::new();
1573        for (key, shard_id) in stale_entries {
1574            // The migration shard contains both shards created during aborted upgrades and shards
1575            // created during successful upgrades. The latter may still be in use, so we have to
1576            // check and only finalize those that aren't anymore.
1577            let gid = GlobalId::System(key.global_id);
1578            if current_shards.get(&gid) != Some(&shard_id) {
1579                shards_to_finalize.insert(shard_id);
1580            }
1581
1582            retractions.push(((key, shard_id), write_ts, -1));
1583        }
1584
1585        let cleanup_action = async move {
1586            if !retractions.is_empty() {
1587                let new_upper = Antichain::from_elem(write_ts.step_forward());
1588                let result = persist_write
1589                    .compare_and_append(retractions, upper, new_upper)
1590                    .await
1591                    .expect("valid usage");
1592                match result {
1593                    Ok(()) => debug!("cleaned up migration shard"),
1594                    Err(mismatch) => debug!(?mismatch, "migration shard cleanup failed"),
1595                }
1596            }
1597        }
1598        .boxed();
1599
1600        // Downgrade the since, to enable some compaction.
1601        let o = persist_since.opaque().clone();
1602        let new_since = Antichain::from_elem(read_ts);
1603        let result = persist_since
1604            .maybe_compare_and_downgrade_since(&o, (&o, &new_since))
1605            .await;
1606        soft_assert_or_log!(result.is_none_or(|r| r.is_ok()), "opaque mismatch");
1607
1608        Ok((shards_to_finalize, cleanup_action))
1609    }
1610}
1611
1612/// Read the migration shard at the given timestamp, returning all entries that match the given
1613/// predicate.
1614///
1615/// Returns `None` if the migration shard contains no matching entries, or if it isn't readable at
1616/// `read_ts`.
1617async fn read_migration_shard<P>(
1618    persist_read: &mut ReadHandle<migration_shard::Key, ShardId, Timestamp, StorageDiff>,
1619    read_ts: Timestamp,
1620    predicate: P,
1621) -> Option<Vec<(migration_shard::Key, ShardId)>>
1622where
1623    P: Fn(&migration_shard::Key) -> bool,
1624{
1625    let as_of = Antichain::from_elem(read_ts);
1626    let updates = persist_read.snapshot_and_fetch(as_of).await.ok()?;
1627
1628    assert!(
1629        updates.iter().all(|(_, _, diff)| *diff == 1),
1630        "migration shard contains invalid diffs: {updates:?}",
1631    );
1632
1633    let entries: Vec<_> = updates
1634        .into_iter()
1635        .map(|(data, _, _)| data)
1636        .filter(move |(key, _)| predicate(key))
1637        .collect();
1638
1639    (!entries.is_empty()).then_some(entries)
1640}
1641
1642/// A plan to migrate between two versions.
1643#[derive(Debug, Default)]
1644struct Plan {
1645    /// Objects to migrate using the `Evolution` mechanism.
1646    evolve: Vec<SystemObjectDescription>,
1647    /// Objects to migrate using the `Replacement` mechanism.
1648    replace: Vec<SystemObjectDescription>,
1649}
1650
1651/// Types and persist codec impls for the migration shard used by the `Replacement` mechanism and
1652/// for builtin storage collections without a shard.
1653mod migration_shard {
1654    use std::fmt;
1655    use std::str::FromStr;
1656
1657    use arrow::array::{StringArray, StringBuilder};
1658    use bytes::{BufMut, Bytes};
1659    use mz_catalog::durable::SystemObjectDescription;
1660    use mz_persist_types::Codec;
1661    use mz_persist_types::codec_impls::{
1662        SimpleColumnarData, SimpleColumnarDecoder, SimpleColumnarEncoder,
1663    };
1664    use mz_persist_types::columnar::Schema;
1665    use mz_persist_types::stats::NoneStats;
1666    use semver::Version;
1667    use serde::{Deserialize, Serialize};
1668
1669    #[derive(Debug, Clone, Eq, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
1670    pub(super) struct Key {
1671        pub(super) global_id: u64,
1672        pub(super) build_version: Version,
1673        // Versions < 26.0 didn't include the deploy generation. As long as we still might
1674        // encounter migration shard entries that don't have it, we need to keep this an `Option`
1675        // and keep supporting both key formats.
1676        pub(super) deploy_generation: Option<u64>,
1677        /// The builtin this entry is for, set in entries for builtins that had no shard (see
1678        /// `Migration::get_or_insert_shards`).
1679        ///
1680        /// NOTE: once a release writes this field, it must not be reverted or left out of a
1681        /// backport. A version that doesn't know the field decodes these entries without it. If
1682        /// such a version ran at a higher build version than the entries, its cleanup would
1683        /// retract them under keys without the field. That doesn't cancel them, and the next
1684        /// version that knows the field would panic on the leftover diffs in
1685        /// `read_migration_shard`.
1686        #[serde(skip_serializing_if = "Option::is_none")]
1687        pub(super) object: Option<ObjectKey>,
1688    }
1689
1690    /// A builtin as identified in the migration shard.
1691    #[derive(Debug, Clone, Eq, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
1692    pub(super) struct ObjectKey {
1693        schema_name: String,
1694        object_name: String,
1695        object_type: String,
1696    }
1697
1698    impl From<&SystemObjectDescription> for ObjectKey {
1699        fn from(object: &SystemObjectDescription) -> Self {
1700            Self {
1701                schema_name: object.schema_name.clone(),
1702                object_name: object.object_name.clone(),
1703                object_type: object.object_type.to_string(),
1704            }
1705        }
1706    }
1707
1708    impl fmt::Display for Key {
1709        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1710            if self.deploy_generation.is_some() {
1711                // current format
1712                let s = serde_json::to_string(self).expect("JSON serializable");
1713                f.write_str(&s)
1714            } else {
1715                // pre-26.0 format
1716                write!(f, "{}-{}", self.global_id, self.build_version)
1717            }
1718        }
1719    }
1720
1721    impl FromStr for Key {
1722        type Err = String;
1723
1724        fn from_str(s: &str) -> Result<Self, String> {
1725            // current format
1726            if let Ok(key) = serde_json::from_str(s) {
1727                return Ok(key);
1728            };
1729
1730            // pre-26.0 format
1731            let parts: Vec<_> = s.splitn(2, '-').collect();
1732            let &[global_id, build_version] = parts.as_slice() else {
1733                return Err(format!("invalid Key '{s}'"));
1734            };
1735            let global_id = global_id.parse::<u64>().map_err(|e| e.to_string())?;
1736            let build_version = build_version
1737                .parse::<Version>()
1738                .map_err(|e| e.to_string())?;
1739            Ok(Key {
1740                global_id,
1741                build_version,
1742                deploy_generation: None,
1743                object: None,
1744            })
1745        }
1746    }
1747
1748    impl Default for Key {
1749        fn default() -> Self {
1750            Self {
1751                global_id: Default::default(),
1752                build_version: Version::new(0, 0, 0),
1753                deploy_generation: Some(0),
1754                object: None,
1755            }
1756        }
1757    }
1758
1759    impl Codec for Key {
1760        type Schema = KeySchema;
1761        type Storage = ();
1762
1763        fn codec_name() -> String {
1764            "TableKey".into()
1765        }
1766
1767        fn encode<B: BufMut>(&self, buf: &mut B) {
1768            buf.put(self.to_string().as_bytes())
1769        }
1770
1771        fn decode<'a>(buf: &'a [u8], _schema: &KeySchema) -> Result<Self, String> {
1772            let s = str::from_utf8(buf).map_err(|e| e.to_string())?;
1773            s.parse()
1774        }
1775
1776        fn encode_schema(_schema: &KeySchema) -> Bytes {
1777            Bytes::new()
1778        }
1779
1780        fn decode_schema(buf: &Bytes) -> Self::Schema {
1781            assert_eq!(*buf, Bytes::new());
1782            KeySchema
1783        }
1784    }
1785
1786    impl SimpleColumnarData for Key {
1787        type ArrowBuilder = StringBuilder;
1788        type ArrowColumn = StringArray;
1789
1790        fn goodbytes(builder: &Self::ArrowBuilder) -> usize {
1791            builder.values_slice().len()
1792        }
1793
1794        fn push(&self, builder: &mut Self::ArrowBuilder) {
1795            builder.append_value(&self.to_string());
1796        }
1797
1798        fn push_null(builder: &mut Self::ArrowBuilder) {
1799            builder.append_null();
1800        }
1801
1802        fn read(&mut self, idx: usize, column: &Self::ArrowColumn) {
1803            *self = column.value(idx).parse().expect("valid Key");
1804        }
1805    }
1806
1807    #[derive(Debug, PartialEq)]
1808    pub(super) struct KeySchema;
1809
1810    impl Schema<Key> for KeySchema {
1811        type ArrowColumn = StringArray;
1812        type Statistics = NoneStats;
1813        type Decoder = SimpleColumnarDecoder<Key>;
1814        type Encoder = SimpleColumnarEncoder<Key>;
1815
1816        fn encoder(&self) -> anyhow::Result<SimpleColumnarEncoder<Key>> {
1817            Ok(SimpleColumnarEncoder::default())
1818        }
1819
1820        fn decoder(&self, col: StringArray) -> anyhow::Result<SimpleColumnarDecoder<Key>> {
1821            Ok(SimpleColumnarDecoder::new(col))
1822        }
1823    }
1824}
1825
1826#[cfg(test)]
1827#[path = "builtin_schema_migration_tests.rs"]
1828mod tests;