Skip to main content

mz_adapter/coord/sequencer/inner/
cluster.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
10use std::collections::BTreeSet;
11use std::time::Duration;
12
13use itertools::Itertools;
14use mz_adapter_types::cluster_state::ReconfigurationAudit;
15use mz_catalog::builtin::BUILTINS;
16use mz_catalog::durable::managed_cluster_replica_name;
17use mz_catalog::memory::error::ErrorKind;
18use mz_catalog::memory::objects::{
19    Cluster, ClusterConfig, ClusterVariant, ClusterVariantManaged, DataSourceDesc,
20    ManagedReplicaConfigShape, ReconfigurationState, ReconfigurationStatus, ReconfigurationTarget,
21};
22use mz_compute_types::config::ComputeReplicaConfig;
23use mz_controller::clusters::{
24    ManagedReplicaLocation, ReplicaConfig, ReplicaLocation, ReplicaLogging,
25};
26use mz_controller_types::{ClusterId, DEFAULT_REPLICA_LOGGING_INTERVAL, ReplicaId};
27use mz_ore::cast::CastFrom;
28use mz_ore::collections::CollectionExt;
29use mz_ore::instrument;
30use mz_repr::Timestamp;
31use mz_repr::adt::numeric::Numeric;
32use mz_repr::role_id::RoleId;
33use mz_sql::catalog::{CatalogCluster, CatalogError, ObjectType};
34use mz_sql::names::FullItemName;
35use mz_sql::plan::{
36    self, AlterClusterPlanStrategy, AlterOptionParameter, AlterSetClusterPlan,
37    CreateClusterManagedPlan, CreateClusterPlan, CreateClusterReplicaPlan,
38    CreateClusterUnmanagedPlan, CreateClusterVariant, PlanClusterOption,
39};
40use mz_sql::plan::{AlterClusterPlan, OnTimeoutAction};
41use mz_sql::session::metadata::SessionMetadata;
42use mz_sql::session::vars::{
43    MAX_CREDIT_CONSUMPTION_RATE, MAX_REPLICAS_PER_CLUSTER, SystemVars, Var,
44};
45use mz_storage_types::sources::SourceConnection;
46use tracing::{Instrument, Span};
47
48use mz_adapter_types::dyncfgs::{
49    DEFAULT_CLUSTER_RECONFIGURATION_TIMEOUT, ENABLE_BACKGROUND_ALTER_CLUSTER,
50};
51
52use super::return_if_err;
53use crate::catalog::{self, Op, ReplicaCreateDropReason};
54use crate::coord::{
55    AlterCluster, AlterClusterAwaitReconfiguration, ClusterStage, Coordinator, Message,
56    PlanValidity, StageResult, Staged,
57};
58use crate::{AdapterError, AdapterNotice, ExecuteContext, ExecuteResponse, session::Session};
59
60impl Staged for ClusterStage {
61    type Ctx = ExecuteContext;
62
63    fn validity(&mut self) -> &mut PlanValidity {
64        match self {
65            Self::Alter(stage) => &mut stage.validity,
66            Self::AwaitReconfiguration(stage) => &mut stage.validity,
67        }
68    }
69
70    async fn stage(
71        self,
72        coord: &mut Coordinator,
73        ctx: &mut ExecuteContext,
74    ) -> Result<StageResult<Box<Self>>, crate::AdapterError> {
75        match self {
76            Self::Alter(stage) => {
77                coord
78                    .sequence_alter_cluster_stage(ctx.session(), stage.plan.clone(), stage.validity)
79                    .await
80            }
81            Self::AwaitReconfiguration(stage) => {
82                coord.await_reconfiguration_stage(stage.validity, stage.cluster_id, stage.target)
83            }
84        }
85    }
86
87    fn message(self, ctx: ExecuteContext, span: tracing::Span) -> Message {
88        Message::ClusterStageReady {
89            ctx,
90            span,
91            stage: self,
92        }
93    }
94
95    fn cancel_enabled(&self) -> bool {
96        true
97    }
98}
99
100impl Coordinator {
101    #[instrument]
102    pub(crate) async fn sequence_alter_cluster_staged(
103        &mut self,
104        ctx: ExecuteContext,
105        plan: plan::AlterClusterPlan,
106    ) {
107        let stage = return_if_err!(self.alter_cluster_validate(ctx.session(), plan).await, ctx);
108        self.sequence_staged(ctx, Span::current(), stage).await;
109    }
110
111    #[instrument]
112    async fn alter_cluster_validate(
113        &self,
114        session: &Session,
115        plan: plan::AlterClusterPlan,
116    ) -> Result<ClusterStage, AdapterError> {
117        let validity = PlanValidity::new(
118            self.catalog(),
119            BTreeSet::new(),
120            Some(plan.id.clone()),
121            None,
122            session.role_metadata().clone(),
123        );
124        Ok(ClusterStage::Alter(AlterCluster { validity, plan }))
125    }
126
127    async fn sequence_alter_cluster_stage(
128        &mut self,
129        session: &Session,
130        plan: plan::AlterClusterPlan,
131        validity: PlanValidity,
132    ) -> Result<StageResult<Box<ClusterStage>>, AdapterError> {
133        let AlterClusterPlan {
134            id: cluster_id,
135            name: _,
136            ref options,
137            ref strategy,
138        } = plan;
139
140        use mz_catalog::memory::objects::ClusterVariant::*;
141        use mz_sql::plan::AlterOptionParameter::*;
142        let cluster = self.catalog.get_cluster(cluster_id);
143        let config = cluster.config.clone();
144        let mut new_config = config.clone();
145
146        match options.query_policy {
147            Set(policy) => new_config.query_policy = policy,
148            Reset => new_config.query_policy = None,
149            Unchanged => {}
150        }
151
152        match (&new_config.variant, &options.managed) {
153            (Managed(_), Reset) | (Managed(_), Unchanged) | (Managed(_), Set(true)) => {}
154            (Managed(_), Set(false)) => new_config.variant = Unmanaged,
155            (Unmanaged, Unchanged) | (Unmanaged, Set(false)) => {}
156            (Unmanaged, Reset) | (Unmanaged, Set(true)) => {
157                // Generate a minimal correct configuration
158
159                // Size adjusted later when sequencing the actual configuration change.
160                let size = "".to_string();
161                let logging = ReplicaLogging {
162                    log_logging: false,
163                    interval: Some(DEFAULT_REPLICA_LOGGING_INTERVAL),
164                };
165                new_config.variant = Managed(ClusterVariantManaged {
166                    size,
167                    availability_zones: Default::default(),
168                    logging,
169                    arrangement_compression: false,
170                    replication_factor: 1,
171                    optimizer_feature_overrides: Default::default(),
172                    schedule: Default::default(),
173                    auto_scaling_strategy: None,
174                    reconfiguration: None,
175                    burst: None,
176                });
177            }
178        }
179
180        match &mut new_config.variant {
181            Managed(ClusterVariantManaged {
182                size,
183                availability_zones,
184                logging,
185                arrangement_compression,
186                replication_factor,
187                optimizer_feature_overrides: _,
188                schedule,
189                auto_scaling_strategy,
190                reconfiguration: _,
191                burst: _,
192            }) => {
193                match &options.size {
194                    Set(s) => size.clone_from(s),
195                    Reset => coord_bail!("SIZE has no default value"),
196                    Unchanged => {}
197                }
198                match &options.availability_zones {
199                    Set(az) => availability_zones.clone_from(az),
200                    Reset => *availability_zones = Default::default(),
201                    Unchanged => {}
202                }
203                match &options.introspection_debugging {
204                    Set(id) => logging.log_logging = *id,
205                    Reset => logging.log_logging = false,
206                    Unchanged => {}
207                }
208                match &options.introspection_interval {
209                    Set(ii) => logging.interval = ii.0,
210                    Reset => logging.interval = Some(DEFAULT_REPLICA_LOGGING_INTERVAL),
211                    Unchanged => {}
212                }
213                match &options.arrangement_compression {
214                    Set(ac) => *arrangement_compression = *ac,
215                    Reset => *arrangement_compression = false,
216                    Unchanged => {}
217                }
218                match &options.replication_factor {
219                    Set(rf) => *replication_factor = *rf,
220                    Reset => {
221                        *replication_factor = self
222                            .catalog
223                            .system_config()
224                            .default_cluster_replication_factor()
225                    }
226                    Unchanged => {}
227                }
228                match &options.schedule {
229                    Set(new_schedule) => {
230                        *schedule = new_schedule.clone();
231                    }
232                    Reset => *schedule = Default::default(),
233                    Unchanged => {}
234                }
235                match &options.auto_scaling_strategy {
236                    Set(new_strategy) => auto_scaling_strategy.clone_from(new_strategy),
237                    // The default is autoscaling disabled.
238                    Reset => *auto_scaling_strategy = None,
239                    Unchanged => {}
240                }
241                if !matches!(options.replicas, Unchanged) {
242                    coord_bail!("Cannot change REPLICAS of managed clusters");
243                }
244            }
245            Unmanaged => {
246                if !matches!(options.size, Unchanged) {
247                    coord_bail!("Cannot change SIZE of unmanaged clusters");
248                }
249                if !matches!(options.availability_zones, Unchanged) {
250                    coord_bail!("Cannot change AVAILABILITY ZONES of unmanaged clusters");
251                }
252                if !matches!(options.introspection_debugging, Unchanged) {
253                    coord_bail!("Cannot change INTROSPECTION DEGUBBING of unmanaged clusters");
254                }
255                if !matches!(options.introspection_interval, Unchanged) {
256                    coord_bail!("Cannot change INTROSPECTION INTERVAL of unmanaged clusters");
257                }
258                if !matches!(options.arrangement_compression, Unchanged) {
259                    coord_bail!(
260                        "Cannot change EXPERIMENTAL ARRANGEMENT COMPRESSION of unmanaged clusters"
261                    );
262                }
263                if !matches!(options.replication_factor, Unchanged) {
264                    coord_bail!("Cannot change REPLICATION FACTOR of unmanaged clusters");
265                }
266                if !matches!(options.auto_scaling_strategy, Unchanged) {
267                    coord_bail!("Cannot change AUTO SCALING STRATEGY of unmanaged clusters");
268                }
269            }
270        }
271
272        match &options.workload_class {
273            Set(wc) => new_config.workload_class.clone_from(wc),
274            Reset => new_config.workload_class = None,
275            Unchanged => {}
276        }
277
278        // Validate a HYDRATION SIZE that this ALTER introduces before
279        // dispatching, so that every ALTER path checks it. An unchanged
280        // HYDRATION SIZE is not re-validated.
281        if let Managed(new_managed) = &new_config.variant {
282            if let Some(on_hydration) = new_managed
283                .auto_scaling_strategy
284                .as_ref()
285                .and_then(|strategy| strategy.on_hydration.as_ref())
286            {
287                let old_hydration_size = match &config.variant {
288                    Managed(managed) => managed
289                        .auto_scaling_strategy
290                        .as_ref()
291                        .and_then(|strategy| strategy.on_hydration.as_ref())
292                        .map(|policy| &policy.hydration_size),
293                    Unmanaged => None,
294                };
295                if old_hydration_size != Some(&on_hydration.hydration_size) {
296                    let role_id = Some(session.role_metadata().current_role);
297                    self.catalog.ensure_valid_replica_size(
298                        &self.catalog().get_role_allowed_cluster_sizes(&role_id),
299                        &on_hydration.hydration_size,
300                        false,
301                    )?;
302                }
303            }
304        }
305
306        let reconfiguration_in_flight = matches!(
307            &config.variant,
308            Managed(managed) if managed
309                .reconfiguration
310                .as_ref()
311                .is_some_and(|record| record.is_in_progress())
312        );
313
314        // The schedule decides which strategy owns the cluster's replica set
315        // (the baseline for MANUAL, on-refresh otherwise), and the sequencer
316        // never writes a reconfiguration record for a scheduled cluster (see
317        // the routing below). Refuse flipping the schedule under an in-flight
318        // record rather than let the two ownership regimes overlap mid-flight.
319        if reconfiguration_in_flight && !matches!(options.schedule, Unchanged) {
320            return Err(AdapterError::AlterClusterScheduleWhileReconfiguring);
321        }
322
323        // A no-op `ALTER` short-circuits, except that an `ALTER` back to the
324        // realized configuration while a reconfiguration is in flight produces a
325        // byte-identical `new_config` and is still meaningful: it must reach
326        // the reshape path below to cancel the record.
327        let cancels_or_retargets =
328            reconfiguration_in_flight && alter_changes_reconfiguration_target(options);
329        if new_config == config && !cancels_or_retargets {
330            return Ok(StageResult::Response(ExecuteResponse::AlteredObject(
331                ObjectType::Cluster,
332            )));
333        }
334
335        // An `ALTER` that raises a managed cluster's replication factor above
336        // one deserves a notice when the cluster contains sources that run on
337        // only one replica, since the additional replicas do not benefit those
338        // sources. Computed here, emitted only after the alter succeeds. The
339        // unmanaged conversion paths never change the replica count, so only
340        // the managed-to-managed transition is of interest.
341        let single_replica_sources_notice = match (&config.variant, &new_config.variant) {
342            (Managed(old_managed), Managed(new_managed))
343                if new_managed.replication_factor > old_managed.replication_factor
344                    && new_managed.replication_factor > 1 =>
345            {
346                let sources = self.single_replica_source_names(cluster);
347                (!sources.is_empty()).then(|| {
348                    AdapterNotice::SingleReplicaSourcesOnMultiReplicaCluster {
349                        cluster: cluster.name.clone(),
350                        sources,
351                    }
352                })
353            }
354            _ => None,
355        };
356
357        // A shape-changing `ALTER` on a MANUAL cluster reshapes into a durable
358        // `reconfiguration` record that the controller converges on. A scheduled
359        // cluster without an in-flight record takes the direct path below because
360        // it has no baseline replica set to overlap. Everything else falls through
361        // to the realized-config update without touching the record.
362        //
363        // With a record in flight the statement decides: any target option,
364        // including replication factor, must reach the reshape path. Restoring
365        // the realized configuration cancels even when value-identical. With
366        // nothing in flight the values decide: a shape option set
367        // to its current value reconfigures nothing, and reshaping it anyway
368        // would write a spurious pre-cancelled record.
369        if let (Managed(old_managed), Managed(new_managed)) = (&config.variant, &new_config.variant)
370        {
371            let needs_record = if reconfiguration_in_flight {
372                alter_changes_reconfiguration_target(options)
373            } else {
374                new_managed.replica_config_shape() != old_managed.replica_config_shape()
375            };
376            // A scheduled (non-MANUAL) cluster holds its replication factor
377            // at 0 and the on-refresh strategy owns its replica set, so a
378            // graceful hydrate-overlap has nothing meaningful to wait for.
379            // A config-shape `ALTER` on such a cluster takes the direct
380            // path below instead of writing a record: that path only updates
381            // the realized config, and the controller reconciles any in-window
382            // replica to the new shape on its next tick. The schedule guard
383            // above keeps a schedule change from reaching here mid-record, so a
384            // record on a scheduled cluster can only pre-date the schedule
385            // (written on an older version). For that case the reshape
386            // path stays reachable, so the record can still be retargeted
387            // or cancelled until it settles.
388            let scheduled_direct =
389                !matches!(new_managed.schedule, mz_sql::plan::ClusterSchedule::Manual)
390                    && !reconfiguration_in_flight;
391            // A `WAIT` option would be silently vacuous on the direct
392            // path: there may be no replica at all (window closed), and
393            // an in-window replica is bounced to the new shape without a
394            // hydrate-overlap to wait on. Reject it rather than return an
395            // instant success that waited for nothing.
396            if scheduled_direct && !matches!(strategy, AlterClusterPlanStrategy::None) {
397                return Err(AdapterError::AlterClusterWaitOnScheduledCluster);
398            }
399            if needs_record && !scheduled_direct {
400                let result = self
401                    .reshape_alter_cluster_managed(
402                        session,
403                        cluster_id,
404                        new_config.clone(),
405                        options,
406                        strategy,
407                        validity,
408                    )
409                    .await;
410                if result.is_ok() {
411                    if let Some(notice) = single_replica_sources_notice {
412                        session.add_notice(notice);
413                    }
414                }
415                return result;
416            }
417        }
418
419        match (&config.variant, &new_config.variant) {
420            (Managed(_), Managed(_)) => {
421                // RF-only changes without an in-flight reconfiguration apply
422                // directly. Any WAIT clause has no effect on this path.
423                self.sequence_alter_cluster_managed_to_managed(
424                    session,
425                    cluster_id,
426                    new_config.clone(),
427                )
428                .await?;
429                if let Some(notice) = single_replica_sources_notice {
430                    session.add_notice(notice);
431                }
432            }
433            (Unmanaged, Managed(new_managed)) => {
434                // The conversion path creates no overlap replicas to wait on,
435                // and a scheduled target makes the `WAIT` permanently
436                // meaningless, mirroring the managed-to-managed rejection
437                // above.
438                if !matches!(new_managed.schedule, mz_sql::plan::ClusterSchedule::Manual)
439                    && !matches!(strategy, AlterClusterPlanStrategy::None)
440                {
441                    return Err(AdapterError::AlterClusterWaitOnScheduledCluster);
442                }
443                self.sequence_alter_cluster_unmanaged_to_managed(
444                    session,
445                    cluster_id,
446                    new_config,
447                    options.to_owned(),
448                )
449                .await?;
450            }
451            (Managed(_), Unmanaged) => {
452                self.sequence_alter_cluster_managed_to_unmanaged(session, cluster_id, new_config)
453                    .await?;
454            }
455            (Unmanaged, Unmanaged) => {
456                self.sequence_alter_cluster_unmanaged_to_unmanaged(
457                    session,
458                    cluster_id,
459                    new_config,
460                    options.replicas.clone(),
461                )
462                .await?;
463            }
464        }
465
466        Ok(StageResult::Response(ExecuteResponse::AlteredObject(
467            ObjectType::Cluster,
468        )))
469    }
470
471    /// Reshape a managed→managed `ALTER` into a durable `reconfiguration` record.
472    ///
473    /// Writes (or folds into) the `reconfiguration` record carrying the full target
474    /// config shape and a deadline, while leaving the realized *shape* in place.
475    /// Non-shape fields the `ALTER` changed (`workload_class`, `schedule`,
476    /// `auto_scaling_strategy`, ...) need no hydrate-overlap, so they are applied
477    /// to the realized config immediately. The controller converges the replica
478    /// set onto the target and cuts the realized shape over at hydration.
479    ///
480    /// **Fold semantics.** When a record is already in flight, the target is an
481    /// overlay on the *in-flight target*, not the realized config: a dimension the
482    /// `ALTER` set (`options.*` is `Set`/`Reset`) takes the new value, a dimension
483    /// left `Unchanged` keeps the in-flight target's value. `new_config` was built
484    /// against the realized config, which still holds the pre-reconfiguration shape
485    /// (the realized config is advanced only at cut-over), so seeding `Unchanged`
486    /// dimensions from it would silently revert the in-flight transition along any
487    /// dimension this `ALTER` did not mention. With no record in flight there is
488    /// nothing to fold and the target is exactly `new_config`'s shape.
489    ///
490    /// **Timeout action.** The record carries an `on_timeout` action resolved
491    /// from `WITH (WAIT ...)`, defaulting to `ROLLBACK`. At the deadline,
492    /// `ROLLBACK` marks the record timed out and drops the in-flight target set.
493    /// The realized config stays unchanged and the strategy disengages. For
494    /// `COMMIT`, the baseline yields while the complete target materializes in a
495    /// replacement transaction. A later reconciliation observes that target,
496    /// advances the realized config, and finalizes without requiring hydration.
497    /// Success always takes precedence. A target that hydrates before the
498    /// deadline cuts over regardless of the action.
499    ///
500    /// With `enable_background_alter_cluster` on, the statement returns
501    /// immediately. With it off, the session blocks on a wait-shim
502    /// ([`ClusterStage::AwaitReconfiguration`]) that polls until the controller
503    /// resolves the record, reporting success only if the realized config
504    /// reached the target, preserving today's foreground UX over the same
505    /// durable mechanism.
506    async fn reshape_alter_cluster_managed(
507        &mut self,
508        session: &Session,
509        cluster_id: ClusterId,
510        new_config: ClusterConfig,
511        options: &PlanClusterOption,
512        strategy: &AlterClusterPlanStrategy,
513        validity: PlanValidity,
514    ) -> Result<StageResult<Box<ClusterStage>>, AdapterError> {
515        use mz_sql::plan::AlterOptionParameter::Unchanged;
516
517        let ClusterVariant::Managed(new_managed) = &new_config.variant else {
518            return Err(AdapterError::Internal(
519                "reshape_alter_cluster_managed requires a managed target config".into(),
520            ));
521        };
522
523        // Fold onto the in-flight target when one exists: `new_config` carries the
524        // realized value for any dimension the `ALTER` left `Unchanged`, but the
525        // realized config is the pre-reconfiguration shape, so we instead carry the
526        // in-flight target's value for those dimensions. Only dimensions the `ALTER`
527        // explicitly set diverge from the in-flight target.
528        let cluster = self.catalog.get_cluster(cluster_id);
529        let in_flight = match &cluster.config.variant {
530            ClusterVariant::Managed(managed) => managed
531                .reconfiguration
532                .as_ref()
533                .filter(|record| record.is_in_progress())
534                .cloned(),
535            ClusterVariant::Unmanaged => None,
536        };
537        let new_target = ReconfigurationTarget {
538            size: new_managed.size.clone(),
539            replication_factor: new_managed.replication_factor,
540            availability_zones: new_managed.availability_zones.clone(),
541            logging: new_managed.logging.clone(),
542            arrangement_compression: new_managed.arrangement_compression,
543        };
544        let unchanged = ReconfigurationDimensionsUnchanged {
545            size: matches!(options.size, Unchanged),
546            replication_factor: matches!(options.replication_factor, Unchanged),
547            availability_zones: matches!(options.availability_zones, Unchanged),
548            // The two logging options fold independently, so a debugging-only
549            // `ALTER` cannot revert an in-flight interval change (or vice versa).
550            log_logging: matches!(options.introspection_debugging, Unchanged),
551            interval: matches!(options.introspection_interval, Unchanged),
552            arrangement_compression: matches!(options.arrangement_compression, Unchanged),
553        };
554        let target = fold_reconfiguration_target(
555            in_flight.as_ref().map(|r| &r.target),
556            new_target,
557            unchanged,
558        );
559
560        // Validate the target up front, so a bad reshape errors at `ALTER` time
561        // rather than silently parking an unconvergeable record.
562        // A size disabled after the cluster started using it stays valid for it.
563        let size_in_use = matches!(
564            &cluster.config.variant,
565            ClusterVariant::Managed(managed) if managed.size == target.size
566        ) || in_flight
567            .as_ref()
568            .is_some_and(|record| record.target.size == target.size);
569        let role_id = session.role_metadata().current_role;
570        self.catalog.ensure_valid_replica_size(
571            &self
572                .catalog()
573                .get_role_allowed_cluster_sizes(&Some(role_id)),
574            &target.size,
575            size_in_use,
576        )?;
577        self.ensure_valid_azs(target.availability_zones.iter())?;
578
579        let cancels = match &cluster.config.variant {
580            ClusterVariant::Managed(managed) => target.matches_realized_config(managed),
581            ClusterVariant::Unmanaged => false,
582        };
583        // Bound the target's steady baseline before the controller expands it
584        // into desired replica slots. This deliberately ignores overlap and
585        // other strategies. Concrete create transactions validate the complete
586        // strategy union. Cancellation remains available if the limit has
587        // fallen below the realized configuration's requirements.
588        if cluster_id.is_user() && !cancels {
589            self.validate_resource_limit(
590                0,
591                i64::from(target.replication_factor),
592                SystemVars::max_replicas_per_cluster,
593                "cluster replica",
594                MAX_REPLICAS_PER_CLUSTER.name(),
595            )?;
596
597            let credits_per_replica = self
598                .catalog()
599                .cluster_replica_sizes()
600                .0
601                .get(&target.size)
602                .expect("target replica size was validated")
603                .credits_per_hour;
604            let baseline_credits = credits_per_replica * Numeric::from(target.replication_factor);
605            self.validate_resource_limit_numeric(
606                self.current_credit_consumption_rate(Some(cluster_id)),
607                baseline_credits,
608                |system_vars| {
609                    self.license_key
610                        .max_credit_consumption_rate()
611                        .map_or_else(|| system_vars.max_credit_consumption_rate(), Numeric::from)
612                },
613                "cluster replica",
614                MAX_CREDIT_CONSUMPTION_RATE.name(),
615            )?;
616        }
617
618        // Resolve the deadline and the on-timeout action, both written relative
619        // to the current time so they survive session disconnect and restart.
620        // The target folds per-dimension onto the in-flight one. The deadline
621        // and `on_timeout`, in contrast, are the contract carried by a `WAIT`
622        // clause, so how a folding `ALTER` treats them depends on whether it
623        // carries one:
624        //   - no `WAIT`, reconfiguration in flight -> keep the in-flight
625        //                          record's deadline and `on_timeout`. The
626        //                          statement carries no contract of its own, so
627        //                          an unrelated config-shape `ALTER` must not
628        //                          silently reset the deadline and action the
629        //                          user set on the reconfiguration in progress.
630        //   - no `WAIT`, nothing in flight -> the system-default timeout and the
631        //                          implicit `on_timeout` default (`ROLLBACK`).
632        //   - `WAIT FOR`        -> sugar for `ON TIMEOUT ROLLBACK`.
633        //   - `WAIT UNTIL READY -> the explicit `TIMEOUT` / `ON TIMEOUT`, with
634        //                          `ON TIMEOUT` defaulting to `ROLLBACK` when
635        //                          omitted.
636        // An explicit `WAIT` clause is folded onto an in-flight record wholesale,
637        // which lets a later `ALTER` steer the deadline and timeout action of a
638        // reconfiguration in progress without discarding the hydration progress
639        // its target may already have. `ROLLBACK` (the default) reverts an
640        // un-hydrated reconfiguration to its pre-reconfiguration shape rather
641        // than cutting over to a not-yet-hydrated target, which could induce
642        // downtime.
643        let now = self.now();
644        let deadline_from = |timeout: Duration| -> Timestamp {
645            now.saturating_add(u64::try_from(timeout.as_millis()).unwrap_or(u64::MAX))
646                .into()
647        };
648        let (deadline, on_timeout) = match strategy {
649            AlterClusterPlanStrategy::None => match &in_flight {
650                Some(record) => (record.deadline, record.on_timeout),
651                None => (
652                    deadline_from(
653                        DEFAULT_CLUSTER_RECONFIGURATION_TIMEOUT
654                            .get(self.catalog().system_config().dyncfgs()),
655                    ),
656                    OnTimeoutAction::Rollback,
657                ),
658            },
659            AlterClusterPlanStrategy::For(timeout) => {
660                (deadline_from(*timeout), OnTimeoutAction::Rollback)
661            }
662            AlterClusterPlanStrategy::UntilReady {
663                timeout,
664                on_timeout,
665            } => (
666                deadline_from(*timeout),
667                on_timeout.unwrap_or(OnTimeoutAction::Rollback),
668            ),
669        };
670
671        // Build the durable write from `new_config`, which carries every field the
672        // `ALTER` changed, then reset the config *shape* (every
673        // `ReconfigurationTarget` dimension) back to the realized values: that
674        // transition is deferred to the `reconfiguration` record and applied at
675        // cut-over. This applies non-shape changes (`workload_class`, `schedule`,
676        // `auto_scaling_strategy`, ...) immediately, matching the legacy path,
677        // rather than silently dropping them. Any existing record is folded over by
678        // the `record` we just built.
679        let cluster = self.catalog.get_cluster(cluster_id);
680        let cluster_name = cluster.name().to_string();
681        let ClusterVariant::Managed(realized_now) = &cluster.config.variant else {
682            return Err(AdapterError::Internal(
683                "reshape_alter_cluster_managed requires a managed realized config".into(),
684            ));
685        };
686        let realized_target = realized_now.realized_reconfiguration_target();
687        // The status and the audit intent are two views of the same decision,
688        // made together here: an ALTER back to the realized shape is a cancel,
689        // anything else starts (or re-targets) a reconfiguration.
690        let (status, audit) = if cancels {
691            (
692                ReconfigurationStatus::Cancelled,
693                ReconfigurationAudit::Cancelled,
694            )
695        } else {
696            (
697                ReconfigurationStatus::InProgress,
698                ReconfigurationAudit::Started,
699            )
700        };
701        let record = ReconfigurationState {
702            target: target.clone(),
703            deadline,
704            on_timeout,
705            status,
706        };
707
708        let mut realized = new_config.clone();
709        let ClusterVariant::Managed(realized_managed) = &mut realized.variant else {
710            return Err(AdapterError::Internal(
711                "reshape_alter_cluster_managed requires a managed target config".into(),
712            ));
713        };
714        realized_managed.apply_reconfiguration_target(realized_target);
715        realized_managed.reconfiguration = Some(record);
716
717        self.catalog_transact(
718            Some(session),
719            vec![Op::UpdateClusterConfig {
720                id: cluster_id,
721                name: cluster_name,
722                config: realized,
723                reconfiguration_audit: Some(audit),
724                burst_audit: None,
725            }],
726        )
727        .await?;
728
729        let background =
730            ENABLE_BACKGROUND_ALTER_CLUSTER.get(self.catalog().system_config().dyncfgs());
731        if background {
732            return Ok(StageResult::Response(ExecuteResponse::AlteredObject(
733                ObjectType::Cluster,
734            )));
735        }
736
737        // Foreground wait-shim: poll the durable record until it resolves. The
738        // reconfiguration continues in the background regardless of the session. A
739        // disconnect during the wait only stops waiting.
740        Ok(StageResult::Immediate(Box::new(
741            ClusterStage::AwaitReconfiguration(AlterClusterAwaitReconfiguration {
742                validity,
743                cluster_id,
744                target,
745            }),
746        )))
747    }
748
749    /// Polls the durable `reconfiguration` record for the foreground wait-shim.
750    ///
751    /// The controller owns deadline handling. This stage reports success only once
752    /// the realized config reaches `target`, and otherwise keeps polling while
753    /// the record is in progress.
754    fn await_reconfiguration_stage(
755        &self,
756        validity: PlanValidity,
757        cluster_id: ClusterId,
758        target: ReconfigurationTarget,
759    ) -> Result<StageResult<Box<ClusterStage>>, AdapterError> {
760        let Some(cluster) = self.catalog().try_get_cluster(cluster_id) else {
761            // The cluster was dropped out from under the reconfiguration.
762            // There is nothing to wait on.
763            return Ok(StageResult::Response(ExecuteResponse::AlteredObject(
764                ObjectType::Cluster,
765            )));
766        };
767        let record = match &cluster.config.variant {
768            ClusterVariant::Managed(managed) => managed.reconfiguration.clone(),
769            ClusterVariant::Unmanaged => None,
770        };
771
772        let realized_matches_target = match &cluster.config.variant {
773            ClusterVariant::Managed(managed) => target.matches_realized_config(managed),
774            ClusterVariant::Unmanaged => false,
775        };
776
777        match reconfiguration_wait_result(record.as_ref(), &target, realized_matches_target) {
778            Some(result) => {
779                result?;
780                Ok(StageResult::Response(ExecuteResponse::AlteredObject(
781                    ObjectType::Cluster,
782                )))
783            }
784            None => {
785                // Still in progress. Re-poll after the configured interval and
786                // wait for the controller to resolve the record. We deliberately
787                // do not consult the deadline here: erroring while the record is
788                // in progress can race the controller and misreport an `ON
789                // TIMEOUT COMMIT` cut-over as a timeout.
790                //
791                // NOTE: If the controller stops resolving a record while it is
792                // in progress, the shim waits indefinitely. Cancelling the session
793                // only stops waiting. It does not abort the durable reconfiguration.
794                let poll_duration = self
795                    .catalog
796                    .system_config()
797                    .cluster_alter_check_ready_interval();
798                let span = Span::current();
799                Ok(StageResult::Handle(mz_ore::task::spawn(
800                    || "Await Cluster Reconfiguration",
801                    async move {
802                        tokio::time::sleep(poll_duration).await;
803                        Ok(Box::new(ClusterStage::AwaitReconfiguration(
804                            AlterClusterAwaitReconfiguration {
805                                validity,
806                                cluster_id,
807                                target,
808                            },
809                        )))
810                    }
811                    .instrument(span),
812                )))
813            }
814        }
815    }
816
817    pub(crate) async fn sequence_create_cluster(
818        &mut self,
819        session: &Session,
820        CreateClusterPlan {
821            name,
822            variant,
823            workload_class,
824            if_not_exists,
825            query_policy,
826        }: CreateClusterPlan,
827    ) -> Result<ExecuteResponse, AdapterError> {
828        tracing::debug!("sequence_create_cluster");
829
830        let id_ts = self.get_catalog_write_ts().await;
831        let id = self.catalog().allocate_user_cluster_id(id_ts).await?;
832        // The catalog items for the introspection sources are shared between all replicas
833        // of a compute instance, so we create them unconditionally during instance creation.
834        // Whether a replica actually maintains introspection arrangements is determined by the
835        // per-replica introspection configuration.
836        let introspection_sources = BUILTINS::logs().collect();
837        let cluster_variant = match &variant {
838            CreateClusterVariant::Managed(plan) => {
839                let logging = if let Some(config) = plan.compute.introspection {
840                    ReplicaLogging {
841                        log_logging: config.debugging,
842                        interval: Some(config.interval),
843                    }
844                } else {
845                    ReplicaLogging::default()
846                };
847                ClusterVariant::Managed(ClusterVariantManaged {
848                    size: plan.size.clone(),
849                    availability_zones: plan.availability_zones.clone(),
850                    logging,
851                    arrangement_compression: plan.compute.arrangement_compression,
852                    replication_factor: plan.replication_factor,
853                    optimizer_feature_overrides: plan.optimizer_feature_overrides.clone(),
854                    schedule: plan.schedule.clone(),
855                    auto_scaling_strategy: plan.auto_scaling_strategy.clone(),
856                    reconfiguration: None,
857                    burst: None,
858                })
859            }
860            CreateClusterVariant::Unmanaged(_) => ClusterVariant::Unmanaged,
861        };
862        let config = ClusterConfig {
863            variant: cluster_variant,
864            workload_class,
865            query_policy,
866        };
867        let ops = vec![catalog::Op::CreateCluster {
868            id,
869            name: name.clone(),
870            introspection_sources,
871            owner_id: *session.current_role_id(),
872            config,
873        }];
874
875        match variant {
876            CreateClusterVariant::Managed(plan) => {
877                self.sequence_create_managed_cluster(session, plan, id, ops)
878                    .await
879            }
880            CreateClusterVariant::Unmanaged(plan) => {
881                self.sequence_create_unmanaged_cluster(session, plan, id, ops)
882                    .await
883            }
884        }
885        .or_else(|err| match err {
886            AdapterError::Catalog(mz_catalog::memory::error::Error {
887                kind: ErrorKind::Sql(CatalogError::ClusterAlreadyExists(_)),
888            }) if if_not_exists => {
889                session.add_notice(AdapterNotice::ObjectAlreadyExists {
890                    name,
891                    ty: "cluster",
892                });
893                Ok(ExecuteResponse::CreatedCluster)
894            }
895            err => Err(err),
896        })
897    }
898
899    #[mz_ore::instrument(level = "debug")]
900    async fn sequence_create_managed_cluster(
901        &mut self,
902        session: &Session,
903        CreateClusterManagedPlan {
904            availability_zones,
905            compute,
906            replication_factor,
907            size,
908            optimizer_feature_overrides: _,
909            schedule: _,
910            auto_scaling_strategy,
911        }: CreateClusterManagedPlan,
912        cluster_id: ClusterId,
913        mut ops: Vec<catalog::Op>,
914    ) -> Result<ExecuteResponse, AdapterError> {
915        tracing::debug!("sequence_create_managed_cluster");
916
917        self.ensure_valid_azs(availability_zones.iter())?;
918
919        let role_id = session.role_metadata().current_role;
920        self.catalog.ensure_valid_replica_size(
921            &self
922                .catalog()
923                .get_role_allowed_cluster_sizes(&Some(role_id)),
924            &size,
925            false,
926        )?;
927        // A HYDRATION SIZE is validated like SIZE itself: it must name a real
928        // replica size the session role may use. Without this, a typo would
929        // fail invisibly at burst-arm time (the controller retrying every
930        // tick), and a size-restricted role could burst at a size it may not
931        // CREATE with.
932        if let Some(on_hydration) = auto_scaling_strategy
933            .as_ref()
934            .and_then(|strategy| strategy.on_hydration.as_ref())
935        {
936            self.catalog.ensure_valid_replica_size(
937                &self
938                    .catalog()
939                    .get_role_allowed_cluster_sizes(&Some(role_id)),
940                &on_hydration.hydration_size,
941                false,
942            )?;
943        }
944
945        // Eagerly validate the `max_replicas_per_cluster` limit.
946        // `catalog_transact` will do this validation too, but allocating
947        // replica IDs is expensive enough that we need to do this validation
948        // before allocating replica IDs. See database-issues#6046.
949        if cluster_id.is_user() {
950            self.validate_resource_limit(
951                0,
952                i64::from(replication_factor),
953                SystemVars::max_replicas_per_cluster,
954                "cluster replica",
955                MAX_REPLICAS_PER_CLUSTER.name(),
956            )?;
957        }
958
959        // Pre-allocate replica ids out-of-band via the durable allocator,
960        // picking the id type from the owning cluster. This mirrors how cluster
961        // and item ids are allocated, so nothing allocates a replica id in-apply.
962        let id_ts = self.get_catalog_write_ts().await;
963        let replica_ids = self
964            .catalog()
965            .allocate_replica_ids(cluster_id, u64::from(replication_factor), id_ts)
966            .await?;
967
968        for (replica_id, replica_name) in replica_ids
969            .into_iter()
970            .zip_eq((0..replication_factor).map(managed_cluster_replica_name))
971        {
972            self.create_managed_cluster_replica_op(
973                cluster_id,
974                replica_id,
975                replica_name.clone(),
976                &compute,
977                &size,
978                &mut ops,
979                if availability_zones.is_empty() {
980                    None
981                } else {
982                    Some(availability_zones.as_ref())
983                },
984                false,
985                *session.current_role_id(),
986                ReplicaCreateDropReason::Manual,
987            )?;
988        }
989
990        self.catalog_transact(Some(session), ops).await?;
991
992        Ok(ExecuteResponse::CreatedCluster)
993    }
994
995    fn create_managed_cluster_replica_op(
996        &self,
997        cluster_id: ClusterId,
998        replica_id: ReplicaId,
999        name: String,
1000        compute: &mz_sql::plan::ComputeReplicaConfig,
1001        size: &String,
1002        ops: &mut Vec<Op>,
1003        azs: Option<&[String]>,
1004        pending: bool,
1005        owner_id: RoleId,
1006        reason: ReplicaCreateDropReason,
1007    ) -> Result<(), AdapterError> {
1008        let location = mz_catalog::durable::ReplicaLocation::Managed {
1009            // Concretized below from the cluster config; this intermediate value
1010            // is discarded, so the list is left empty here.
1011            availability_zones: Vec::new(),
1012            billed_as: None,
1013            internal: false,
1014            size: size.clone(),
1015            pending,
1016        };
1017
1018        let logging = if let Some(config) = compute.introspection {
1019            ReplicaLogging {
1020                log_logging: config.debugging,
1021                interval: Some(config.interval),
1022            }
1023        } else {
1024            ReplicaLogging::default()
1025        };
1026
1027        let config = ReplicaConfig {
1028            location: self.catalog().concretize_replica_location(
1029                location,
1030                &self
1031                    .catalog()
1032                    .get_role_allowed_cluster_sizes(&Some(owner_id)),
1033                azs,
1034                false,
1035            )?,
1036            compute: ComputeReplicaConfig {
1037                logging,
1038                arrangement_compression: compute.arrangement_compression,
1039            },
1040        };
1041
1042        // The caller pre-allocates `replica_id` out-of-band via the durable
1043        // allocator, so nothing allocates a replica id in-apply.
1044        ops.push(catalog::Op::CreateClusterReplica {
1045            cluster_id,
1046            replica_id,
1047            name,
1048            config,
1049            owner_id,
1050            reason,
1051        });
1052        Ok(())
1053    }
1054
1055    fn ensure_valid_azs<'a, I: IntoIterator<Item = &'a String>>(
1056        &self,
1057        azs: I,
1058    ) -> Result<(), AdapterError> {
1059        let cat_azs = self.catalog().state().availability_zones();
1060        for az in azs.into_iter() {
1061            if !cat_azs.contains(az) {
1062                return Err(AdapterError::InvalidClusterReplicaAz {
1063                    az: az.to_string(),
1064                    expected: cat_azs.to_vec(),
1065                });
1066            }
1067        }
1068        Ok(())
1069    }
1070
1071    #[mz_ore::instrument(level = "debug")]
1072    async fn sequence_create_unmanaged_cluster(
1073        &mut self,
1074        session: &Session,
1075        CreateClusterUnmanagedPlan { replicas }: CreateClusterUnmanagedPlan,
1076        id: ClusterId,
1077        mut ops: Vec<catalog::Op>,
1078    ) -> Result<ExecuteResponse, AdapterError> {
1079        tracing::debug!("sequence_create_unmanaged_cluster");
1080
1081        self.ensure_valid_azs(replicas.iter().filter_map(|(_, r)| {
1082            if let mz_sql::plan::ReplicaConfig::Orchestrated {
1083                availability_zone: Some(az),
1084                ..
1085            } = &r
1086            {
1087                Some(az)
1088            } else {
1089                None
1090            }
1091        }))?;
1092
1093        // Eagerly validate the `max_replicas_per_cluster` limit.
1094        // `catalog_transact` will do this validation too, but allocating
1095        // replica IDs is expensive enough that we need to do this validation
1096        // before allocating replica IDs. See database-issues#6046.
1097        if id.is_user() {
1098            self.validate_resource_limit(
1099                0,
1100                i64::try_from(replicas.len()).unwrap_or(i64::MAX),
1101                SystemVars::max_replicas_per_cluster,
1102                "cluster replica",
1103                MAX_REPLICAS_PER_CLUSTER.name(),
1104            )?;
1105        }
1106
1107        // Pre-allocate replica ids out-of-band via the durable allocator,
1108        // picking the id type from the owning cluster. This mirrors how cluster
1109        // and item ids are allocated, so nothing allocates a replica id in-apply.
1110        let id_ts = self.get_catalog_write_ts().await;
1111        let replica_ids = self
1112            .catalog()
1113            .allocate_replica_ids(id, u64::cast_from(replicas.len()), id_ts)
1114            .await?;
1115
1116        for (replica_id, (replica_name, replica_config)) in replica_ids.into_iter().zip_eq(replicas)
1117        {
1118            // If the AZ was not specified, choose one, round-robin, from the ones with
1119            // the lowest number of configured replicas for this cluster.
1120            let (compute, location) = match replica_config {
1121                mz_sql::plan::ReplicaConfig::Unorchestrated {
1122                    storagectl_addrs,
1123                    computectl_addrs,
1124                    compute,
1125                } => {
1126                    let location = mz_catalog::durable::ReplicaLocation::Unmanaged {
1127                        storagectl_addrs,
1128                        computectl_addrs,
1129                    };
1130                    (compute, location)
1131                }
1132                mz_sql::plan::ReplicaConfig::Orchestrated {
1133                    availability_zone,
1134                    billed_as,
1135                    compute,
1136                    internal,
1137                    size,
1138                } => {
1139                    // Only internal users have access to INTERNAL and BILLED AS
1140                    if !session.user().is_internal() && (internal || billed_as.is_some()) {
1141                        coord_bail!("cannot specify INTERNAL or BILLED AS as non-internal user")
1142                    }
1143                    // BILLED AS implies the INTERNAL flag.
1144                    if billed_as.is_some() && !internal {
1145                        coord_bail!("must specify INTERNAL when specifying BILLED AS");
1146                    }
1147                    // Concretizing the location validates `SIZE` only, see
1148                    // `ensure_valid_billed_as_size`.
1149                    if let Some(billed_as) = &billed_as {
1150                        self.ensure_valid_billed_as_size(billed_as)?;
1151                    }
1152
1153                    let location = mz_catalog::durable::ReplicaLocation::Managed {
1154                        // The user-pinned `AVAILABILITY ZONE`, if any, as a zero-
1155                        // or one-element list.
1156                        availability_zones: availability_zone.into_iter().collect(),
1157                        billed_as,
1158                        internal,
1159                        size: size.clone(),
1160                        pending: false,
1161                    };
1162                    (compute, location)
1163                }
1164            };
1165
1166            let logging = if let Some(config) = compute.introspection {
1167                ReplicaLogging {
1168                    log_logging: config.debugging,
1169                    interval: Some(config.interval),
1170                }
1171            } else {
1172                ReplicaLogging::default()
1173            };
1174
1175            let role_id = session.role_metadata().current_role;
1176            let config = ReplicaConfig {
1177                location: self.catalog().concretize_replica_location(
1178                    location,
1179                    &self
1180                        .catalog()
1181                        .get_role_allowed_cluster_sizes(&Some(role_id)),
1182                    None,
1183                    false,
1184                )?,
1185                compute: ComputeReplicaConfig {
1186                    logging,
1187                    arrangement_compression: compute.arrangement_compression,
1188                },
1189            };
1190
1191            ops.push(catalog::Op::CreateClusterReplica {
1192                cluster_id: id,
1193                replica_id,
1194                name: replica_name.clone(),
1195                config,
1196                owner_id: *session.current_role_id(),
1197                reason: ReplicaCreateDropReason::Manual,
1198            });
1199        }
1200
1201        self.catalog_transact(Some(session), ops).await?;
1202
1203        Ok(ExecuteResponse::CreatedCluster)
1204    }
1205
1206    /// Returns the full names of all sources bound to `cluster` whose
1207    /// connections prefer to run on a single replica, so additional replicas
1208    /// do not make them more fault tolerant or increase their throughput.
1209    fn single_replica_source_names(&self, cluster: &Cluster) -> Vec<String> {
1210        cluster
1211            .bound_objects
1212            .iter()
1213            .filter_map(|id| {
1214                let entry = self.catalog().get_entry(id);
1215                let single_replica =
1216                    entry
1217                        .source()
1218                        .is_some_and(|source| match &source.data_source {
1219                            DataSourceDesc::Ingestion { desc, .. }
1220                            | DataSourceDesc::OldSyntaxIngestion { desc, .. } => {
1221                                desc.connection.prefers_single_replica()
1222                            }
1223                            _ => false,
1224                        });
1225                single_replica.then(|| {
1226                    self.catalog()
1227                        .resolve_full_name(entry.name(), None)
1228                        .to_string()
1229                })
1230            })
1231            .collect()
1232    }
1233
1234    /// The number of replicas `cluster` aims to run, for deciding whether to
1235    /// emit the single-replica-sources notice.
1236    ///
1237    /// For a managed cluster this is the replication factor, taking the target
1238    /// of an in-progress reconfiguration over the realized one, plus any
1239    /// INTERNAL or BILLED AS replicas, which are manually managed outside the
1240    /// replication-factor domain. Replicas belonging to a reconfiguration's
1241    /// hydrate-overlap are deliberately not counted: they replace the serving
1242    /// set at cut-over rather than adding to it. Counting the replication
1243    /// factor instead of replicas excludes the ordinary replicas the cluster
1244    /// controller creates for the target shape.
1245    fn notice_relevant_replica_count(&self, cluster: &Cluster) -> usize {
1246        match &cluster.config.variant {
1247            ClusterVariant::Managed(managed) => {
1248                let replication_factor = managed
1249                    .reconfiguration
1250                    .as_ref()
1251                    .filter(|record| record.is_in_progress())
1252                    .map_or(managed.replication_factor, |record| {
1253                        record.target.replication_factor
1254                    });
1255                let manual_replicas = cluster
1256                    .replicas()
1257                    .filter(|r| {
1258                        r.config.location.internal() || r.config.location.billed_as().is_some()
1259                    })
1260                    .count();
1261                usize::cast_from(replication_factor) + manual_replicas
1262            }
1263            ClusterVariant::Unmanaged => cluster.replicas().count(),
1264        }
1265    }
1266
1267    /// Emits a notice if `cluster` aims to run more than one replica while
1268    /// containing sources that run on only one replica. Call after a command
1269    /// that added a replica or such a source.
1270    ///
1271    /// `creating_source` names a source the current command is creating in
1272    /// `cluster`. It is included in the notice even when it is not yet visible
1273    /// in the catalog, which happens when the creation is staged in a DDL
1274    /// transaction that commits later.
1275    pub(crate) fn notify_single_replica_sources(
1276        &self,
1277        session: &Session,
1278        cluster: &Cluster,
1279        creating_source: Option<&FullItemName>,
1280    ) {
1281        if self.notice_relevant_replica_count(cluster) <= 1 {
1282            return;
1283        }
1284        let mut sources = self.single_replica_source_names(cluster);
1285        if let Some(name) = creating_source {
1286            let full_name = name.to_string();
1287            if !sources.contains(&full_name) {
1288                sources.push(full_name);
1289            }
1290        }
1291        if !sources.is_empty() {
1292            session.add_notice(AdapterNotice::SingleReplicaSourcesOnMultiReplicaCluster {
1293                cluster: cluster.name.clone(),
1294                sources,
1295            });
1296        }
1297    }
1298
1299    /// Rejects a `BILLED AS` size that is not in the replica size map.
1300    ///
1301    /// Billing only reads the size's credit rate, so unlike `SIZE` the value
1302    /// may be a disabled size and need not be in the role's allowed sizes.
1303    /// The check lives here rather than in `concretize_replica_location`,
1304    /// which catalog open also runs for every durable replica.
1305    fn ensure_valid_billed_as_size(&self, size: &str) -> Result<(), AdapterError> {
1306        if self.catalog().cluster_replica_sizes().0.contains_key(size) {
1307            Ok(())
1308        } else {
1309            coord_bail!("unknown cluster replica size {size} in BILLED AS")
1310        }
1311    }
1312
1313    #[mz_ore::instrument(level = "debug")]
1314    pub(crate) async fn sequence_create_cluster_replica(
1315        &mut self,
1316        session: &Session,
1317        CreateClusterReplicaPlan {
1318            name,
1319            cluster_id,
1320            config,
1321            if_not_exists,
1322        }: CreateClusterReplicaPlan,
1323    ) -> Result<ExecuteResponse, AdapterError> {
1324        // Choose default AZ if necessary
1325        let (compute, location) = match config {
1326            mz_sql::plan::ReplicaConfig::Unorchestrated {
1327                storagectl_addrs,
1328                computectl_addrs,
1329                compute,
1330            } => {
1331                let location = mz_catalog::durable::ReplicaLocation::Unmanaged {
1332                    storagectl_addrs,
1333                    computectl_addrs,
1334                };
1335                (compute, location)
1336            }
1337            mz_sql::plan::ReplicaConfig::Orchestrated {
1338                availability_zone,
1339                billed_as,
1340                compute,
1341                internal,
1342                size,
1343            } => {
1344                let availability_zone = match availability_zone {
1345                    Some(az) => {
1346                        self.ensure_valid_azs([&az])?;
1347                        Some(az)
1348                    }
1349                    None => None,
1350                };
1351                let location = mz_catalog::durable::ReplicaLocation::Managed {
1352                    // The user-pinned `AVAILABILITY ZONE`, if any, as a zero- or
1353                    // one-element list.
1354                    availability_zones: availability_zone.into_iter().collect(),
1355                    billed_as,
1356                    internal,
1357                    size,
1358                    pending: false,
1359                };
1360                (compute, location)
1361            }
1362        };
1363
1364        let logging = if let Some(config) = compute.introspection {
1365            ReplicaLogging {
1366                log_logging: config.debugging,
1367                interval: Some(config.interval),
1368            }
1369        } else {
1370            ReplicaLogging::default()
1371        };
1372
1373        let role_id = session.role_metadata().current_role;
1374        let config = ReplicaConfig {
1375            location: self.catalog().concretize_replica_location(
1376                location,
1377                &self
1378                    .catalog()
1379                    .get_role_allowed_cluster_sizes(&Some(role_id)),
1380                // Planning ensures all replicas in this codepath
1381                // are unmanaged.
1382                None,
1383                false,
1384            )?,
1385            compute: ComputeReplicaConfig {
1386                logging,
1387                arrangement_compression: compute.arrangement_compression,
1388            },
1389        };
1390
1391        let cluster = self.catalog().get_cluster(cluster_id);
1392
1393        if let ReplicaLocation::Managed(ManagedReplicaLocation {
1394            internal,
1395            billed_as,
1396            ..
1397        }) = &config.location
1398        {
1399            // Only internal users have access to INTERNAL and BILLED AS
1400            if !session.user().is_internal() && (*internal || billed_as.is_some()) {
1401                coord_bail!("cannot specify INTERNAL or BILLED AS as non-internal user")
1402            }
1403            // Managed clusters require the INTERNAL flag.
1404            if cluster.is_managed() && !*internal {
1405                coord_bail!("must specify INTERNAL when creating a replica in a managed cluster");
1406            }
1407            // BILLED AS implies the INTERNAL flag.
1408            if billed_as.is_some() && !*internal {
1409                coord_bail!("must specify INTERNAL when specifying BILLED AS");
1410            }
1411            // Concretizing the location validated `SIZE` only, see
1412            // `ensure_valid_billed_as_size`.
1413            if let Some(billed_as) = billed_as {
1414                self.ensure_valid_billed_as_size(billed_as)?;
1415            }
1416        }
1417
1418        // Replicas have the same owner as their cluster. Extract the owned
1419        // cluster info we need before the borrow is dropped for the awaits below.
1420        let owner_id = cluster.owner_id();
1421
1422        let cluster_name = cluster.name.clone();
1423        // A replica name is only unique within its cluster, so the notice on the
1424        // `IF NOT EXISTS` path below has to name both.
1425        let qualified_name = format!("{cluster_name}.{name}");
1426
1427        // Pre-allocate the replica id out-of-band via the durable allocator,
1428        // picking the id type from the target cluster, which may be a system
1429        // cluster. This mirrors how cluster and item ids are allocated, so
1430        // nothing allocates a replica id in-apply.
1431        let id_ts = self.get_catalog_write_ts().await;
1432        let replica_id = self
1433            .catalog()
1434            .allocate_replica_ids(cluster_id, 1, id_ts)
1435            .await?
1436            .into_element();
1437
1438        let ops = vec![catalog::Op::CreateClusterReplica {
1439            cluster_id,
1440            replica_id,
1441            name: name.clone(),
1442            config,
1443            owner_id,
1444            reason: ReplicaCreateDropReason::Manual,
1445        }];
1446
1447        match self.catalog_transact(Some(session), ops).await {
1448            Ok(()) => {
1449                // The commit made the new replica visible in the catalog, so
1450                // the check sees the updated replica count.
1451                self.notify_single_replica_sources(
1452                    session,
1453                    self.catalog().get_cluster(cluster_id),
1454                    None,
1455                );
1456                Ok(ExecuteResponse::CreatedClusterReplica)
1457            }
1458            Err(AdapterError::Catalog(mz_catalog::memory::error::Error {
1459                kind: ErrorKind::Sql(CatalogError::DuplicateReplica(_, _)),
1460            })) if if_not_exists => {
1461                session.add_notice(AdapterNotice::ObjectAlreadyExists {
1462                    name: qualified_name,
1463                    ty: "cluster replica",
1464                });
1465                Ok(ExecuteResponse::CreatedClusterReplica)
1466            }
1467            Err(err) => Err(err),
1468        }
1469    }
1470
1471    /// Applies a managed→managed `ALTER CLUSTER`.
1472    ///
1473    /// This is a config-only write: the cluster controller owns the replica set
1474    /// and reconciles it to the new realized config on its next tick. Emitting
1475    /// creates and drops here as well would fight it, since it derives replica
1476    /// names from the observed set, so an adapter create by canonical `rN` can
1477    /// collide with a controller-chosen name and an adapter drop by canonical
1478    /// `rN` can miss a churned one.
1479    ///
1480    /// # Panics
1481    ///
1482    /// Panics if the identified cluster is not a managed cluster.
1483    /// Panics if `new_config` is not a configuration for a managed cluster.
1484    pub(crate) async fn sequence_alter_cluster_managed_to_managed(
1485        &mut self,
1486        session: &Session,
1487        cluster_id: ClusterId,
1488        new_config: ClusterConfig,
1489    ) -> Result<(), AdapterError> {
1490        let cluster = self.catalog.get_cluster(cluster_id);
1491        let name = cluster.name().to_string();
1492
1493        let ClusterVariant::Managed(ClusterVariantManaged {
1494            size,
1495            availability_zones,
1496            logging,
1497            arrangement_compression,
1498            replication_factor,
1499            optimizer_feature_overrides: _,
1500            schedule: _,
1501            auto_scaling_strategy,
1502            reconfiguration,
1503            burst: _,
1504        }) = &cluster.config.variant
1505        else {
1506            panic!("expected existing managed cluster config");
1507        };
1508        let ClusterVariant::Managed(new_managed) = &new_config.variant else {
1509            panic!("expected new managed cluster config");
1510        };
1511        let ClusterVariantManaged {
1512            size: new_size,
1513            replication_factor: new_replication_factor,
1514            availability_zones: new_availability_zones,
1515            logging: _,
1516            arrangement_compression: _,
1517            optimizer_feature_overrides: _,
1518            schedule: _,
1519            auto_scaling_strategy: new_auto_scaling_strategy,
1520            reconfiguration: _,
1521            burst: _,
1522        } = new_managed;
1523
1524        let role_id = Some(session.role_metadata().current_role);
1525        // A size disabled after the cluster started using it stays valid for it.
1526        self.catalog.ensure_valid_replica_size(
1527            &self.catalog().get_role_allowed_cluster_sizes(&role_id),
1528            new_size,
1529            new_size == size,
1530        )?;
1531        if new_auto_scaling_strategy != auto_scaling_strategy {
1532            if let Some(on_hydration) = new_auto_scaling_strategy
1533                .as_ref()
1534                .and_then(|strategy| strategy.on_hydration.as_ref())
1535            {
1536                // The planner validated the hydration size against the
1537                // *realized* SIZE only. An in-flight reconfiguration will cut
1538                // the realized SIZE over to its target, so also reject equality
1539                // with that target. Letting it through would end the reshape
1540                // with a no-op burst shape and a stored statement that fails
1541                // its own re-plan.
1542                if reconfiguration.as_ref().is_some_and(|record| {
1543                    record.is_in_progress() && record.target.size == on_hydration.hydration_size
1544                }) {
1545                    coord_bail!(
1546                        "HYDRATION SIZE must differ from the target SIZE \
1547                         ('{}') of the in-progress cluster resize",
1548                        on_hydration.hydration_size
1549                    );
1550                }
1551            }
1552        }
1553
1554        // The committed baseline is an exact count, not a prediction of the
1555        // controller's transient strategy union, and no strategy can shed it.
1556        // Validate it here: `Op::UpdateClusterConfig` contributes nothing to
1557        // `catalog_transact`'s replica accounting, because the controller
1558        // materializes the replicas on a later tick rather than this transaction
1559        // emitting creates. Without the check the ALTER would succeed and the
1560        // controller would then fail its own create transaction on every tick.
1561        // See database-issues#6046.
1562        if new_replication_factor > replication_factor && cluster_id.is_user() {
1563            self.validate_resource_limit(
1564                usize::cast_from(*replication_factor),
1565                i64::from(*new_replication_factor) - i64::from(*replication_factor),
1566                SystemVars::max_replicas_per_cluster,
1567                "cluster replica",
1568                MAX_REPLICAS_PER_CLUSTER.name(),
1569            )?;
1570
1571            let credits_per_replica = self
1572                .catalog()
1573                .cluster_replica_sizes()
1574                .0
1575                .get(new_size)
1576                .expect("new replica size was validated")
1577                .credits_per_hour;
1578            let baseline_credits = credits_per_replica * Numeric::from(*new_replication_factor);
1579            self.validate_resource_limit_numeric(
1580                self.current_credit_consumption_rate(Some(cluster_id)),
1581                baseline_credits,
1582                |system_vars| {
1583                    self.license_key
1584                        .max_credit_consumption_rate()
1585                        .map_or_else(|| system_vars.max_credit_consumption_rate(), Numeric::from)
1586                },
1587                "cluster replica",
1588                MAX_CREDIT_CONSUMPTION_RATE.name(),
1589            )?;
1590        }
1591
1592        let config_changed = new_managed.replica_config_shape()
1593            != ManagedReplicaConfigShape::new(
1594                size,
1595                availability_zones,
1596                logging,
1597                *arrangement_compression,
1598            );
1599        // The controller creates replicas from the realized config without
1600        // re-validating availability zones, so an invalid pool written here
1601        // would produce an unplaceable replica.
1602        if config_changed {
1603            self.ensure_valid_azs(new_availability_zones.iter())?;
1604        }
1605
1606        // A record still in progress belongs to a live reconfiguration this
1607        // cluster-level write did not touch, so carry it through unchanged.
1608        let ops = vec![catalog::Op::UpdateClusterConfig {
1609            id: cluster_id,
1610            name,
1611            config: new_config,
1612            reconfiguration_audit: None,
1613            burst_audit: None,
1614        }];
1615
1616        self.catalog_transact(Some(session), ops).await?;
1617        Ok(())
1618    }
1619
1620    /// # Panics
1621    ///
1622    /// Panics if `new_config` is not a configuration for a managed cluster.
1623    async fn sequence_alter_cluster_unmanaged_to_managed(
1624        &mut self,
1625        session: &Session,
1626        cluster_id: ClusterId,
1627        mut new_config: ClusterConfig,
1628        options: PlanClusterOption,
1629    ) -> Result<(), AdapterError> {
1630        let cluster = self.catalog.get_cluster(cluster_id);
1631        let cluster_name = cluster.name().to_string();
1632
1633        let ClusterVariant::Managed(ClusterVariantManaged {
1634            size: new_size,
1635            replication_factor: new_replication_factor,
1636            availability_zones: new_availability_zones,
1637            logging: _,
1638            arrangement_compression: _,
1639            optimizer_feature_overrides: _,
1640            schedule: _,
1641            auto_scaling_strategy: _,
1642            reconfiguration: _,
1643            burst: _,
1644        }) = &mut new_config.variant
1645        else {
1646            panic!("expected new managed cluster config");
1647        };
1648
1649        // Validate replication factor parameter
1650        let user_replica_count = cluster
1651            .user_replicas()
1652            .count()
1653            .try_into()
1654            .expect("must_fit");
1655        match options.replication_factor {
1656            AlterOptionParameter::Set(_) => {
1657                // Validate that the replication factor matches the current length only if specified.
1658                if user_replica_count != *new_replication_factor {
1659                    coord_bail!(
1660                        "REPLICATION FACTOR {new_replication_factor} does not match number of replicas ({user_replica_count})"
1661                    );
1662                }
1663            }
1664            _ => {
1665                *new_replication_factor = user_replica_count;
1666            }
1667        }
1668
1669        let mut names = BTreeSet::new();
1670        let mut sizes = BTreeSet::new();
1671
1672        self.ensure_valid_azs(new_availability_zones.iter())?;
1673
1674        // Validate per-replica configuration
1675        for replica in cluster.user_replicas() {
1676            names.insert(replica.name.clone());
1677            match &replica.config.location {
1678                ReplicaLocation::Unmanaged(_) => coord_bail!(
1679                    "Cannot convert unmanaged cluster with unmanaged replicas to managed cluster"
1680                ),
1681                ReplicaLocation::Managed(location) => {
1682                    sizes.insert(location.size.clone());
1683
1684                    // An unmanaged cluster's replica carries its single
1685                    // user-pinned AZ (if any) as the sole entry; every pin must
1686                    // fall within the managed cluster's `AVAILABILITY ZONES`.
1687                    for az in &location.availability_zones {
1688                        if !new_availability_zones.contains(az) {
1689                            coord_bail!(
1690                                "unmanaged replica has availability zone {az} which is not \
1691                                in managed {new_availability_zones:?}"
1692                            )
1693                        }
1694                    }
1695                }
1696            }
1697        }
1698
1699        if sizes.is_empty() {
1700            assert!(
1701                cluster.user_replicas().next().is_none(),
1702                "Cluster should not have replicas"
1703            );
1704            // We didn't collect any size, so the user has to name it.
1705            match &options.size {
1706                AlterOptionParameter::Reset | AlterOptionParameter::Unchanged => {
1707                    coord_bail!("Missing SIZE for empty cluster")
1708                }
1709                AlterOptionParameter::Set(size) => {
1710                    let role_id = Some(session.role_metadata().current_role);
1711                    self.catalog.ensure_valid_replica_size(
1712                        &self.catalog().get_role_allowed_cluster_sizes(&role_id),
1713                        size,
1714                        false,
1715                    )?;
1716                }
1717            }
1718        } else if sizes.len() == 1 {
1719            let size = sizes.into_iter().next().expect("must exist");
1720            match &options.size {
1721                AlterOptionParameter::Set(sz) if *sz != size => {
1722                    coord_bail!("Cluster replicas of size {size} do not match expected SIZE {sz}");
1723                }
1724                _ => *new_size = size,
1725            }
1726        } else {
1727            let formatted = sizes
1728                .iter()
1729                .map(String::as_str)
1730                .collect::<Vec<_>>()
1731                .join(", ");
1732            coord_bail!(
1733                "Cannot convert unmanaged cluster to managed, non-unique replica sizes: {formatted}"
1734            );
1735        }
1736
1737        for i in 0..*new_replication_factor {
1738            let name = managed_cluster_replica_name(i);
1739            names.remove(&name);
1740        }
1741        if !names.is_empty() {
1742            let formatted = names
1743                .iter()
1744                .map(String::as_str)
1745                .collect::<Vec<_>>()
1746                .join(", ");
1747            coord_bail!(
1748                "Cannot convert unmanaged cluster to managed, invalid replica names: {formatted}"
1749            );
1750        }
1751
1752        let ops = vec![catalog::Op::UpdateClusterConfig {
1753            id: cluster_id,
1754            name: cluster_name,
1755            config: new_config,
1756            reconfiguration_audit: None,
1757            burst_audit: None,
1758        }];
1759
1760        self.catalog_transact(Some(session), ops).await?;
1761        Ok(())
1762    }
1763
1764    async fn sequence_alter_cluster_managed_to_unmanaged(
1765        &mut self,
1766        session: &Session,
1767        cluster_id: ClusterId,
1768        new_config: ClusterConfig,
1769    ) -> Result<(), AdapterError> {
1770        let cluster = self.catalog().get_cluster(cluster_id);
1771
1772        // The unmanaged variant has no reconfiguration field, so converting
1773        // would silently drop an in-progress record with no terminal status
1774        // and no audit event, and strand any overlap replicas the controller
1775        // already created. Refuse instead: the user can cancel (ALTER back to
1776        // the realized size) or wait for the record to settle first.
1777        if let ClusterVariant::Managed(managed) = &cluster.config.variant {
1778            if managed
1779                .reconfiguration
1780                .as_ref()
1781                .is_some_and(|record| record.is_in_progress())
1782            {
1783                return Err(AdapterError::AlterClusterUnmanagedWhileReconfiguring);
1784            }
1785            // Same hazard for an in-flight burst: the unmanaged variant has no
1786            // burst field either, so converting would drop the record with no
1787            // `Finished` audit event and strand the billed burst replica as an
1788            // ordinary unmanaged replica nothing ever tears down. Absence of a
1789            // record means the burst has settled, so no in-progress check is
1790            // needed.
1791            if managed.burst.is_some() {
1792                return Err(AdapterError::AlterClusterUnmanagedWhileBursting);
1793            }
1794        }
1795
1796        let ops = vec![catalog::Op::UpdateClusterConfig {
1797            id: cluster_id,
1798            name: cluster.name().to_string(),
1799            config: new_config,
1800            reconfiguration_audit: None,
1801            burst_audit: None,
1802        }];
1803
1804        self.catalog_transact(Some(session), ops).await?;
1805        Ok(())
1806    }
1807
1808    async fn sequence_alter_cluster_unmanaged_to_unmanaged(
1809        &mut self,
1810        session: &Session,
1811        cluster_id: ClusterId,
1812        new_config: ClusterConfig,
1813        replicas: AlterOptionParameter<Vec<(String, mz_sql::plan::ReplicaConfig)>>,
1814    ) -> Result<(), AdapterError> {
1815        if !matches!(replicas, AlterOptionParameter::Unchanged) {
1816            coord_bail!("Cannot alter replicas in unmanaged cluster");
1817        }
1818
1819        let cluster = self.catalog().get_cluster(cluster_id);
1820
1821        let ops = vec![catalog::Op::UpdateClusterConfig {
1822            id: cluster_id,
1823            name: cluster.name().to_string(),
1824            config: new_config,
1825            reconfiguration_audit: None,
1826            burst_audit: None,
1827        }];
1828
1829        self.catalog_transact(Some(session), ops).await?;
1830        Ok(())
1831    }
1832
1833    /// Convert a [`AlterSetClusterPlan`] to a sequence of catalog operators and adjust state.
1834    pub(crate) async fn sequence_alter_set_cluster(
1835        &self,
1836        _session: &Session,
1837        AlterSetClusterPlan { id, set_cluster: _ }: AlterSetClusterPlan,
1838    ) -> Result<ExecuteResponse, AdapterError> {
1839        // TODO: This function needs to be implemented.
1840
1841        // Satisfy Clippy that this is an async func.
1842        async {}.await;
1843        let entry = self.catalog().get_entry(&id);
1844        match entry.item().typ() {
1845            _ => {
1846                // Unexpected; planner permitted unsupported plan.
1847                Err(AdapterError::Unsupported("ALTER SET CLUSTER"))
1848            }
1849        }
1850    }
1851}
1852
1853/// Which reconfiguration-target dimensions an `ALTER` left unset (`Unchanged`).
1854/// Drives [`fold_reconfiguration_target`]. Logging is two sub-dimensions
1855/// because `INTROSPECTION DEBUGGING` and `INTROSPECTION INTERVAL` are
1856/// independently alterable.
1857struct ReconfigurationDimensionsUnchanged {
1858    size: bool,
1859    replication_factor: bool,
1860    availability_zones: bool,
1861    log_logging: bool,
1862    interval: bool,
1863    arrangement_compression: bool,
1864}
1865
1866/// Returns the foreground result, or `None` while the awaited target is pending.
1867///
1868/// Records are overwritten by later ALTERs, so success is defined by realized
1869/// state rather than record identity. A waiter follows a record only while that
1870/// record still carries its target.
1871fn reconfiguration_wait_result(
1872    record: Option<&ReconfigurationState>,
1873    awaited_target: &ReconfigurationTarget,
1874    realized_matches_target: bool,
1875) -> Option<Result<(), AdapterError>> {
1876    if realized_matches_target {
1877        return Some(Ok(()));
1878    }
1879    let Some(record) = record.filter(|record| record.target == *awaited_target) else {
1880        return Some(Err(AdapterError::AlterClusterSuperseded));
1881    };
1882    match record.status {
1883        ReconfigurationStatus::InProgress => None,
1884        ReconfigurationStatus::ResourceExhausted => {
1885            Some(Err(AdapterError::AlterClusterResourceExhausted))
1886        }
1887        ReconfigurationStatus::TimedOut => Some(Err(AdapterError::AlterClusterTimeout)),
1888        ReconfigurationStatus::Finalized | ReconfigurationStatus::Cancelled => {
1889            Some(Err(AdapterError::AlterClusterSuperseded))
1890        }
1891    }
1892}
1893
1894/// Whether an `ALTER` statement sets a reconfiguration target dimension.
1895///
1896/// A statement-level check, used while a reconfiguration is in flight: an
1897/// `ALTER` back to the realized configuration sets an option without changing its
1898/// value, yet must reach the reshape path to cancel the record. All target
1899/// dimensions, including replication factor, must update the in-flight target
1900/// rather than the realized config so cut-over does not overwrite them. With
1901/// nothing in flight the routing compares shapes instead (see
1902/// `sequence_alter_cluster_stage`).
1903fn alter_changes_reconfiguration_target(options: &PlanClusterOption) -> bool {
1904    use mz_sql::plan::AlterOptionParameter::Unchanged;
1905    let PlanClusterOption {
1906        availability_zones,
1907        introspection_debugging,
1908        introspection_interval,
1909        arrangement_compression,
1910        managed: _,
1911        replicas: _,
1912        replication_factor,
1913        size,
1914        schedule: _,
1915        workload_class: _,
1916        auto_scaling_strategy: _,
1917        query_policy: _,
1918    } = options;
1919    !matches!(size, Unchanged)
1920        || !matches!(replication_factor, Unchanged)
1921        || !matches!(availability_zones, Unchanged)
1922        || !matches!(introspection_debugging, Unchanged)
1923        || !matches!(introspection_interval, Unchanged)
1924        || !matches!(arrangement_compression, Unchanged)
1925}
1926
1927/// Fold a new `ALTER` onto an in-flight reconfiguration target.
1928///
1929/// `new_target` was built against the *realized* config, so any dimension the
1930/// `ALTER` left `Unchanged` carries the realized (pre-reconfiguration) value. When
1931/// a reconfiguration is in flight (`in_flight` is `Some`), the realized config is
1932/// the pre-reconfiguration shape, so for each `Unchanged` dimension we instead
1933/// keep the in-flight target's value. Only dimensions the `ALTER` explicitly set
1934/// re-target. With nothing in flight (`in_flight` is `None`) the target is exactly
1935/// `new_target`. This is what keeps an `ALTER` that touches one dimension (e.g.
1936/// AZ-only) from silently reverting the in-flight transition along every dimension
1937/// it did not mention.
1938fn fold_reconfiguration_target(
1939    in_flight: Option<&ReconfigurationTarget>,
1940    new_target: ReconfigurationTarget,
1941    unchanged: ReconfigurationDimensionsUnchanged,
1942) -> ReconfigurationTarget {
1943    let Some(prev) = in_flight else {
1944        return new_target;
1945    };
1946    ReconfigurationTarget {
1947        size: if unchanged.size {
1948            prev.size.clone()
1949        } else {
1950            new_target.size
1951        },
1952        replication_factor: if unchanged.replication_factor {
1953            prev.replication_factor
1954        } else {
1955            new_target.replication_factor
1956        },
1957        availability_zones: if unchanged.availability_zones {
1958            prev.availability_zones.clone()
1959        } else {
1960            new_target.availability_zones
1961        },
1962        logging: ReplicaLogging {
1963            log_logging: if unchanged.log_logging {
1964                prev.logging.log_logging
1965            } else {
1966                new_target.logging.log_logging
1967            },
1968            interval: if unchanged.interval {
1969                prev.logging.interval
1970            } else {
1971                new_target.logging.interval
1972            },
1973        },
1974        arrangement_compression: if unchanged.arrangement_compression {
1975            prev.arrangement_compression
1976        } else {
1977            new_target.arrangement_compression
1978        },
1979    }
1980}
1981
1982#[cfg(test)]
1983mod tests {
1984    use mz_controller::clusters::ReplicaLogging;
1985    use mz_controller_types::DEFAULT_REPLICA_LOGGING_INTERVAL;
1986
1987    use super::*;
1988
1989    fn target(size: &str, rf: u32, azs: &[&str], log_logging: bool) -> ReconfigurationTarget {
1990        ReconfigurationTarget {
1991            size: size.to_string(),
1992            replication_factor: rf,
1993            availability_zones: azs.iter().map(|s| s.to_string()).collect(),
1994            logging: ReplicaLogging {
1995                log_logging,
1996                interval: Some(DEFAULT_REPLICA_LOGGING_INTERVAL),
1997            },
1998            arrangement_compression: false,
1999        }
2000    }
2001
2002    fn all_changed() -> ReconfigurationDimensionsUnchanged {
2003        ReconfigurationDimensionsUnchanged {
2004            size: false,
2005            replication_factor: false,
2006            availability_zones: false,
2007            log_logging: false,
2008            interval: false,
2009            arrangement_compression: false,
2010        }
2011    }
2012
2013    fn all_unchanged() -> ReconfigurationDimensionsUnchanged {
2014        ReconfigurationDimensionsUnchanged {
2015            size: true,
2016            replication_factor: true,
2017            availability_zones: true,
2018            log_logging: true,
2019            interval: true,
2020            arrangement_compression: true,
2021        }
2022    }
2023
2024    #[mz_ore::test]
2025    fn foreground_wait_succeeds_when_target_is_realized() {
2026        let awaited = target("200cc", 1, &[], false);
2027        let record = ReconfigurationState {
2028            target: target("300cc", 1, &[], false),
2029            deadline: Timestamp::from(0),
2030            on_timeout: OnTimeoutAction::Rollback,
2031            status: ReconfigurationStatus::InProgress,
2032        };
2033
2034        assert!(matches!(
2035            reconfiguration_wait_result(Some(&record), &awaited, true),
2036            Some(Ok(()))
2037        ));
2038    }
2039
2040    #[mz_ore::test]
2041    fn foreground_wait_follows_matching_target() {
2042        let awaited = target("200cc", 1, &[], false);
2043        let mut record = ReconfigurationState {
2044            target: awaited.clone(),
2045            deadline: Timestamp::from(0),
2046            on_timeout: OnTimeoutAction::Rollback,
2047            status: ReconfigurationStatus::InProgress,
2048        };
2049
2050        assert!(reconfiguration_wait_result(Some(&record), &awaited, false).is_none());
2051
2052        record.status = ReconfigurationStatus::ResourceExhausted;
2053        assert!(matches!(
2054            reconfiguration_wait_result(Some(&record), &awaited, false),
2055            Some(Err(AdapterError::AlterClusterResourceExhausted))
2056        ));
2057
2058        record.status = ReconfigurationStatus::TimedOut;
2059        assert!(matches!(
2060            reconfiguration_wait_result(Some(&record), &awaited, false),
2061            Some(Err(AdapterError::AlterClusterTimeout))
2062        ));
2063    }
2064
2065    #[mz_ore::test]
2066    fn foreground_wait_reports_superseded_target() {
2067        let awaited = target("200cc", 1, &[], false);
2068        let record = ReconfigurationState {
2069            target: target("300cc", 1, &[], false),
2070            deadline: Timestamp::from(0),
2071            on_timeout: OnTimeoutAction::Rollback,
2072            status: ReconfigurationStatus::InProgress,
2073        };
2074
2075        assert!(matches!(
2076            reconfiguration_wait_result(Some(&record), &awaited, false),
2077            Some(Err(AdapterError::AlterClusterSuperseded))
2078        ));
2079        assert!(matches!(
2080            reconfiguration_wait_result(None, &awaited, false),
2081            Some(Err(AdapterError::AlterClusterSuperseded))
2082        ));
2083    }
2084
2085    #[mz_ore::test]
2086    fn fold_with_no_record_takes_new_target() {
2087        // No reconfiguration in flight: the target is exactly the new one.
2088        let new = target("200cc", 3, &["az1"], true);
2089        let folded = fold_reconfiguration_target(None, new.clone(), all_changed());
2090        assert_eq!(folded, new);
2091    }
2092
2093    #[mz_ore::test]
2094    fn fold_rf_only_keeps_in_flight_shape() {
2095        // A 200cc size change is in flight. A later rf-only ALTER must NOT revert
2096        // the in-flight size/AZ/logging back to the realized (100cc) values that
2097        // `new_target` carries for the dimensions the ALTER left unchanged.
2098        let in_flight = target("200cc", 1, &["az2"], true);
2099        // new_target reflects realized 100cc/az1 for every dimension but rf, which
2100        // the ALTER set to 5.
2101        let new = target("100cc", 5, &["az1"], false);
2102        let unchanged = ReconfigurationDimensionsUnchanged {
2103            size: true,
2104            replication_factor: false,
2105            availability_zones: true,
2106            log_logging: true,
2107            interval: true,
2108            arrangement_compression: true,
2109        };
2110        let folded = fold_reconfiguration_target(Some(&in_flight), new, unchanged);
2111        // The in-flight size/AZ/logging survive. Only rf is re-targeted.
2112        assert_eq!(folded, target("200cc", 5, &["az2"], true));
2113    }
2114
2115    #[mz_ore::test]
2116    fn fold_with_all_set_overwrites_every_dimension() {
2117        // Every dimension explicitly set: the fold takes all of new_target.
2118        let in_flight = target("200cc", 1, &["az2"], true);
2119        let new = target("400cc", 9, &["az9"], false);
2120        let folded = fold_reconfiguration_target(Some(&in_flight), new.clone(), all_changed());
2121        assert_eq!(folded, new);
2122    }
2123
2124    #[mz_ore::test]
2125    fn fold_all_unchanged_is_alter_back_to_in_flight() {
2126        // An all-unchanged fold keeps the in-flight target intact rather than
2127        // reverting it to the realized shape. Unreachable from the `ALTER`
2128        // path (non-shape statements no longer reach the fold), pinned as a
2129        // property of the pure function.
2130        let in_flight = target("200cc", 2, &["az2"], true);
2131        let realized_shaped = target("100cc", 1, &["az1"], false);
2132        let folded =
2133            fold_reconfiguration_target(Some(&in_flight), realized_shaped, all_unchanged());
2134        assert_eq!(folded, in_flight);
2135    }
2136
2137    #[mz_ore::test]
2138    fn fold_logging_subdimensions_fold_independently() {
2139        // An interval change is in flight. A later ALTER that sets only
2140        // INTROSPECTION DEBUGGING must not revert the in-flight interval to the
2141        // realized value that `new_target` carries for options the ALTER left
2142        // unset.
2143        let mut in_flight = target("100cc", 1, &["az1"], false);
2144        in_flight.logging.interval = Some(Duration::from_secs(5));
2145        let new = target("100cc", 1, &["az1"], true);
2146        let unchanged = ReconfigurationDimensionsUnchanged {
2147            size: true,
2148            replication_factor: true,
2149            availability_zones: true,
2150            log_logging: false,
2151            interval: true,
2152            arrangement_compression: true,
2153        };
2154        let folded = fold_reconfiguration_target(Some(&in_flight), new, unchanged);
2155        assert_eq!(
2156            folded.logging,
2157            ReplicaLogging {
2158                log_logging: true,
2159                interval: Some(Duration::from_secs(5)),
2160            }
2161        );
2162    }
2163}