mz_cluster_controller/lib.rs
1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! The cluster controller: the single decision-maker for the replica set of
11//! every managed cluster.
12//!
13//! It is a **reconciler**. Each tick it reads desired cluster state and live
14//! signals through the [`ClusterControllerCtx`] boundary, runs a set of pure
15//! [`Strategy`]s, unions their desired contributions, diffs that against the
16//! actual replica set, and emits the create/drop and durable-state-write
17//! [`Decision`]s that close the gap. It holds no in-memory state: the source of
18//! truth is always the catalog plus live signals, pulled fresh each tick.
19//!
20//! The crate is **pure**. It depends only on primitive id/shape types and the
21//! [`ClusterControllerCtx`] trait, never on the adapter or catalog. That
22//! boundary is what makes the controller testable against a fake
23//! implementation and extractable later without touching controller code.
24//!
25//! A tick runs two phases per cluster, `update_state` then `desired_replicas`
26//! (see [`ClusterController::reconcile`]). Every [`Decision`] carries the
27//! durable state it was derived from, and the apply path transacts it only if
28//! that state still holds (compare-and-append). So a create or drop derived
29//! from a pre-`ALTER` snapshot can never reshape the replica set against the
30//! config the `ALTER` has since established. Applies are per cluster, so one
31//! cluster's rejection does not block the others, and commands name explicit
32//! replicas, so re-emitting one across a lagging view or a restart is a no-op.
33//!
34//! [`ClusterControllerCtx`]: crate::ctx::ClusterControllerCtx
35
36pub mod ctx;
37pub mod strategy;
38
39use std::collections::{BTreeMap, BTreeSet};
40
41use mz_adapter_types::dyncfgs::{DEFAULT_HYDRATION_BURST_LINGER, ENABLE_HYDRATION_BURST};
42use mz_controller_types::ClusterId;
43use mz_dyncfg::ConfigSet;
44use mz_ore::soft_panic_or_log;
45
46use crate::ctx::{
47 ApplyOutcome, ClusterControllerCtx, ClusterState, CreateReason, Decision, ObservedReplica,
48 ReconfigurationAudit, ReconfigurationRecord, ReconfigurationStatus, ReconfigurationWrite,
49 RefreshWindowInputs, ReplicaShape, StateWrite,
50};
51use crate::strategy::{
52 BaselineStrategy, ConfigSignals, DesiredReplica, GracefulReconfigurationStrategy,
53 HydrationBurstStrategy, LiveSignals, OnRefreshStrategy, SignalRequest, Strategy,
54};
55
56/// The cluster controller. Holds the (stateless) set of strategies and drives a
57/// reconcile tick against a [`ClusterControllerCtx`].
58pub struct ClusterController {
59 strategies: Vec<Box<dyn Strategy>>,
60 /// The dyncfgs the config signals are latched from each tick. A shared
61 /// handle, so a flipped flag takes effect on the next tick.
62 dyncfgs: ConfigSet,
63}
64
65impl ClusterController {
66 /// A controller with the full set of strategies. Each strategy's rustdoc
67 /// describes when it engages.
68 pub fn new(dyncfgs: ConfigSet) -> Self {
69 Self {
70 strategies: vec![
71 Box::new(BaselineStrategy),
72 Box::new(GracefulReconfigurationStrategy),
73 Box::new(OnRefreshStrategy),
74 Box::new(HydrationBurstStrategy),
75 ],
76 dyncfgs,
77 }
78 }
79
80 /// The tick's config signals, latched from the dyncfgs so every strategy
81 /// decides against one consistent config per tick.
82 fn config_signals(&self) -> ConfigSignals {
83 ConfigSignals {
84 burst_enabled: ENABLE_HYDRATION_BURST.get(&self.dyncfgs),
85 default_burst_linger: DEFAULT_HYDRATION_BURST_LINGER.get(&self.dyncfgs),
86 }
87 }
88
89 /// Run one reconcile tick over every managed cluster the ctx reports.
90 ///
91 /// See the module docs for the two-phase structure. Both phases apply per
92 /// cluster, so a compare-and-append rejection on one cluster never blocks
93 /// progress on the others.
94 pub async fn reconcile(&self, ctx: &mut dyn ClusterControllerCtx) {
95 let cluster_ids = ctx.managed_cluster_ids().await;
96 if cluster_ids.is_empty() {
97 return;
98 }
99
100 // Phase 1: update_state. We merge every strategy's write for a cluster
101 // into one compare-and-append, applied per cluster and independently of
102 // other clusters. Two separate decisions live here.
103 //
104 // Per cluster, not one batch per tick: a write rejected because a
105 // concurrent `ALTER` moved the cluster off its `expected` rejects only
106 // that cluster and leaves the rest free to progress. One batched apply
107 // would let a single mid-`ALTER` cluster sink the whole tick, the failure
108 // mode at large cluster counts where some cluster is almost always
109 // mid-`ALTER`.
110 //
111 // Merged across strategies, not one apply per strategy: every strategy
112 // for a cluster shares the same start-of-tick `expected`, so applying
113 // them one at a time would let the first write move the cluster off that
114 // `expected` and reject all the rest, serializing a cluster's disjoint
115 // writes one-per-tick. Merging lands them together under one guard. We
116 // still rely on the compare-and-append, not the merge, for `ALTER`
117 // safety, which is why the merged write carries the cluster's `expected`.
118 // See `merge_state_writes` for the join and its conflict handling.
119 let states = ctx.cluster_states(&cluster_ids).await;
120 let config = self.config_signals();
121 let signals = self.fetch_signals(ctx, &states, &config).await;
122 let now = ctx.now();
123 // Set when we issue any phase-1 apply, applied or rejected. Either way
124 // the durable state may have moved (our write, or the concurrent `ALTER`
125 // that rejected it), so phase 2 re-reads.
126 let mut phase_1_wrote = false;
127 // Clusters whose phase-1 write was rejected. We skip their phase 2 this
128 // tick. Proceeding would be safe (we re-read below and every create/drop
129 // is guard-checked), but a cluster that just lost a race is likely still
130 // settling, so we let it recompute next tick instead of emitting work
131 // that is probably about to go stale.
132 let mut rejected = BTreeSet::new();
133 for state in &states {
134 let Some(signals) = signals.get(&state.cluster_id) else {
135 continue;
136 };
137 let write = self.merge_state_writes(state, signals, &config, now);
138 if write.is_empty() {
139 continue;
140 }
141 phase_1_wrote = true;
142 let decision = Decision::UpdateClusterState {
143 cluster_id: state.cluster_id,
144 expected: state.expected(),
145 write,
146 };
147 // A phase-1 batch carries no creates, so it cannot exhaust the
148 // resource budget. Treat any non-applied outcome as a rejection.
149 if ctx.apply(vec![decision]).await != ApplyOutcome::Applied {
150 rejected.insert(state.cluster_id);
151 }
152 }
153
154 // Phase 2: desired_replicas. The barrier exists so that a cut-over a
155 // phase-1 write performed is visible before we diff the replica set
156 // against the realized config. We re-read (and re-enrich) only if phase 1
157 // wrote. The first read is otherwise still current. A stale diff is
158 // harmless: every create/drop carries its `expected` and is guard-rejected
159 // if the durable state has since diverged.
160 let (states, signals) = if phase_1_wrote {
161 let states = ctx.cluster_states(&cluster_ids).await;
162 let signals = self.fetch_signals(ctx, &states, &config).await;
163 (states, signals)
164 } else {
165 (states, signals)
166 };
167 let now = ctx.now();
168 for state in &states {
169 if rejected.contains(&state.cluster_id) {
170 continue;
171 }
172 let Some(signals) = signals.get(&state.cluster_id) else {
173 continue;
174 };
175 let decisions = self.collect_replica_decisions(state, signals, &config, now);
176 if decisions.is_empty() {
177 continue;
178 }
179 // Per-cluster apply: a guard failure here is isolated to this cluster,
180 // and benign anyway since every command names an explicit replica and
181 // is reconciled away next tick. We do not retry within the tick.
182 match ctx.apply(decisions).await {
183 ApplyOutcome::Applied | ApplyOutcome::Rejected => {}
184 ApplyOutcome::ResourceExhausted => {
185 // The batch exceeded the resource budget. Retrying cannot make
186 // the transient peak smaller, so shed the cluster's most
187 // expendable transient strategy and recompute next tick.
188 //
189 // The failed apply rolled back without changing durable state,
190 // so this tick's `expected` witness is still current, unless a
191 // concurrent user `ALTER` re-targeted the record, in which case
192 // the guard rejects the shed and that new reconfiguration is
193 // left to converge instead of being clobbered.
194 if let Some(shed) = Self::shed_decision(state) {
195 let _ = ctx.apply(vec![shed]).await;
196 }
197 }
198 }
199 }
200 }
201
202 /// The decision that sheds this cluster's most expendable transient strategy
203 /// after a resource-exhausted apply, or `None` if nothing sheddable is
204 /// active.
205 ///
206 /// The strategy to shed is chosen by presence, ranked by expendability, not
207 /// by which create failed: validation is aggregate, and the strategy worth
208 /// giving up may be one whose replicas already materialized rather than one
209 /// in the failed batch. The graceful reconfiguration is the most expendable:
210 /// a discretionary user change that fails cleanly (audited, and the wait-shim
211 /// reports a timeout) and can be retried, while aborting it leaves the
212 /// cluster running at its realized shape. The baseline is never shed, it is
213 /// the committed floor.
214 ///
215 /// We shed one strategy per exhausted apply. If that was not enough, the
216 /// next tick recomputes and sheds the next one.
217 fn shed_decision(state: &ClusterState) -> Option<Decision> {
218 let record = state.reconfiguration.as_ref()?;
219 if !record.is_in_progress() {
220 return None;
221 }
222 Some(Decision::UpdateClusterState {
223 cluster_id: state.cluster_id,
224 expected: state.expected(),
225 write: StateWrite {
226 reconfiguration: Some(ReconfigurationWrite {
227 record: Some(ReconfigurationRecord {
228 status: ReconfigurationStatus::ResourceExhausted,
229 ..record.clone()
230 }),
231 audit: Some(ReconfigurationAudit::ResourceExhausted),
232 }),
233 ..Default::default()
234 },
235 })
236 }
237
238 /// Merge every strategy's [`Strategy::update_state`] for one cluster into the
239 /// single [`StateWrite`] the tick applies under one compare-and-append.
240 ///
241 /// The merge is a per-field join, independent of the order strategies run
242 /// in: a field set by exactly one strategy is taken as-is, a field no
243 /// strategy sets is left unchanged, and a field set to the same value by
244 /// several is that value.
245 ///
246 /// Two strategies setting one field to *different* values is a conflict.
247 /// The strategies keep every field single-writer at any given moment:
248 /// most fields are owned by exactly one strategy outright, and
249 /// `new_replication_factor`, which both the graceful cut-over and the
250 /// on-refresh normalization write, is time-shared (on-refresh skips its
251 /// normalization while a reconfiguration record is in progress). So by
252 /// design a conflict cannot happen and the merge is really a disjoint
253 /// union. We treat a conflict as an invariant violation rather than a
254 /// condition to resolve: there is no safety-meaningful winner to pick for
255 /// a contended `size` or record, so we trip [`soft_panic_or_log!`] (a
256 /// panic under test/CI soft assertions, a logged error in production) and
257 /// leave the field unchanged, the only outcome that cannot make things
258 /// worse. A persistent conflict then freezes that field and keeps tripping
259 /// the alarm, which is the point: surface the design bug loudly instead of
260 /// silently picking an arbitrary value.
261 fn merge_state_writes(
262 &self,
263 state: &ClusterState,
264 signals: &LiveSignals,
265 config: &ConfigSignals,
266 now: mz_repr::Timestamp,
267 ) -> StateWrite {
268 let writes: Vec<StateWrite> = self
269 .strategies
270 .iter()
271 .map(|strategy| strategy.update_state(state, signals, config, now))
272 .filter(|write| !write.is_empty())
273 .collect();
274
275 let mut conflicts: Vec<&'static str> = Vec::new();
276 // Exhaustive construction (every field named, no `..`): a field added to
277 // `StateWrite` is a compile error here until its join is spelled out.
278 let merged = StateWrite {
279 new_size: join(
280 "size",
281 writes.iter().map(|w| w.new_size.clone()),
282 &mut conflicts,
283 ),
284 new_replication_factor: join(
285 "replication_factor",
286 writes.iter().map(|w| w.new_replication_factor),
287 &mut conflicts,
288 ),
289 new_availability_zones: join(
290 "availability_zones",
291 writes.iter().map(|w| w.new_availability_zones.clone()),
292 &mut conflicts,
293 ),
294 new_logging: join(
295 "logging",
296 writes.iter().map(|w| w.new_logging.clone()),
297 &mut conflicts,
298 ),
299 new_arrangement_compression: join(
300 "arrangement_compression",
301 writes.iter().map(|w| w.new_arrangement_compression),
302 &mut conflicts,
303 ),
304 reconfiguration: join(
305 "reconfiguration",
306 writes.iter().map(|w| w.reconfiguration.clone()),
307 &mut conflicts,
308 ),
309 burst: join(
310 "burst",
311 writes.iter().map(|w| w.burst.clone()),
312 &mut conflicts,
313 ),
314 };
315
316 if !conflicts.is_empty() {
317 soft_panic_or_log!(
318 "cluster {:?}: strategies produced conflicting state writes for \
319 field(s) {}; leaving those fields unchanged. Strategies must own \
320 disjoint `StateWrite` fields.",
321 state.cluster_id,
322 conflicts.join(", "),
323 );
324 }
325
326 merged
327 }
328
329 /// Fetch the live signals the strategies declared they need for `states`.
330 ///
331 /// Each strategy names its needs as a pure function of the durable state
332 /// and the tick's config signals ([`Strategy::signal_request`]), so the
333 /// kernel stays ignorant of when a strategy engages. Signals are fetched
334 /// only where requested: a steady cluster is never probed, keeping the ctx
335 /// seam pay-for-what-you-use. Refresh-window inputs are fetched as one batch
336 /// so every scheduled cluster shares one oracle read per phase. The returned
337 /// map omits a state when one of its required inputs was unavailable, which
338 /// causes the reconciliation phase to skip that cluster.
339 async fn fetch_signals(
340 &self,
341 ctx: &mut dyn ClusterControllerCtx,
342 states: &[ClusterState],
343 config: &ConfigSignals,
344 ) -> BTreeMap<ClusterId, LiveSignals> {
345 let mut signals = BTreeMap::new();
346 let mut refresh_window_clusters = Vec::new();
347 for state in states {
348 let request = self
349 .strategies
350 .iter()
351 .fold(SignalRequest::default(), |acc, strategy| {
352 acc.union(strategy.signal_request(state, config))
353 });
354 let mut live = LiveSignals::default();
355 if request.hydratable_objects {
356 live.has_hydratable_objects = ctx.has_hydratable_objects(state.cluster_id).await;
357 }
358 if request.hydration {
359 let replica_ids: Vec<_> = state
360 .replicas
361 .iter()
362 .filter(|r| r.owned_shape().is_some())
363 .map(|r| r.replica_id)
364 .collect();
365 if !replica_ids.is_empty() {
366 live.hydrated_replicas =
367 ctx.hydrated_replicas(state.cluster_id, &replica_ids).await;
368 }
369 }
370 if request.refresh_window {
371 refresh_window_clusters.push(state.cluster_id);
372 }
373 signals.insert(state.cluster_id, live);
374 }
375 if !refresh_window_clusters.is_empty() {
376 match ctx.refresh_window_inputs(&refresh_window_clusters).await {
377 Some(batch) => {
378 let read_ts = batch.read_ts;
379 let mut cluster_inputs = batch.cluster_inputs;
380 for cluster_id in refresh_window_clusters {
381 let Some(inputs) = cluster_inputs.remove(&cluster_id) else {
382 signals.remove(&cluster_id);
383 continue;
384 };
385 let live = signals
386 .get_mut(&cluster_id)
387 .expect("signal entry inserted for requested cluster");
388 live.refresh_window = Some(RefreshWindowInputs {
389 read_ts,
390 compaction_estimate: inputs.compaction_estimate,
391 refresh_mvs: inputs.refresh_mvs,
392 });
393 }
394 }
395 None => {
396 for cluster_id in refresh_window_clusters {
397 signals.remove(&cluster_id);
398 }
399 }
400 }
401 }
402 signals
403 }
404
405 /// Diff the unioned desired set against the actual replicas of one cluster
406 /// and emit the create/drop decisions that close the gap.
407 fn collect_replica_decisions(
408 &self,
409 state: &ClusterState,
410 signals: &LiveSignals,
411 config: &ConfigSignals,
412 now: mz_repr::Timestamp,
413 ) -> Vec<Decision> {
414 let contributions: Vec<Vec<DesiredReplica>> = self
415 .strategies
416 .iter()
417 .map(|strategy| strategy.desired_replicas(state, signals, config, now))
418 .collect();
419
420 reconcile_replicas(state, &contributions)
421 }
422}
423
424/// Join one `StateWrite` field across the strategies that set it: `None` if
425/// none did, the common value if one or more set it to the same value, and
426/// `None` with `field` pushed onto `conflicts` if two set it to different
427/// values. The result and the conflict signal depend only on the set of values,
428/// not the order they arrive in.
429fn join<T: PartialEq>(
430 field: &'static str,
431 values: impl IntoIterator<Item = Option<T>>,
432 conflicts: &mut Vec<&'static str>,
433) -> Option<T> {
434 let mut merged: Option<T> = None;
435 for value in values.into_iter().flatten() {
436 match &merged {
437 None => merged = Some(value),
438 Some(existing) if *existing == value => {}
439 // Two strategies disagree on this field. Record it and leave the
440 // field unchanged; merge_state_writes raises the alarm.
441 Some(_) => {
442 conflicts.push(field);
443 return None;
444 }
445 }
446 }
447 merged
448}
449
450/// The pure multiset union/diff kernel for one cluster: given each strategy's
451/// desired replica slots and the actual replicas, match slots to replicas by
452/// shape and emit the creates and drops that close the gap.
453///
454/// Semantics:
455/// - The desired set is the multiset **union** of every strategy's slots: a
456/// given shape is desired `max` over strategies (not the sum), since a replica
457/// of that shape satisfies every strategy that wants one. This is what makes a
458/// replica survive iff *some* strategy desires its shape.
459/// - For each shape, if actual count < desired count we create the difference;
460/// if actual count > desired count we drop the difference, picking specific
461/// excess replicas. A replica of a shape no strategy desires is dropped.
462/// - Creates carry the winning [`CreateReason`] among the slots that
463/// desired the shape (see [`CreateReason::outranks`]). Drops carry no
464/// attribution. A drop happens exactly when no strategy desires the replica.
465fn reconcile_replicas(
466 state: &ClusterState,
467 contributions: &[Vec<DesiredReplica>],
468) -> Vec<Decision> {
469 // Desired count per shape = max over strategies of how many that strategy
470 // wants of the shape, carrying the highest-ranking reason among the
471 // slots.
472 let mut desired: Vec<DesiredShape> = Vec::new();
473 for slots in contributions {
474 // How many of each shape this strategy wants, and the winning reason
475 // among the shape's slots.
476 let mut per_shape: Vec<(ReplicaShape, usize, CreateReason)> = Vec::new();
477 for slot in slots {
478 match per_shape
479 .iter_mut()
480 .find(|(s, _, _)| s.matches(&slot.shape))
481 {
482 Some((_, count, reason)) => {
483 *count += 1;
484 if slot.reason.outranks(reason) {
485 *reason = slot.reason.clone();
486 }
487 }
488 None => per_shape.push((slot.shape.clone(), 1, slot.reason.clone())),
489 }
490 }
491 for (shape, count, reason) in per_shape {
492 match desired.iter_mut().find(|d| d.shape.matches(&shape)) {
493 Some(existing) => {
494 existing.count = existing.count.max(count);
495 if reason.outranks(&existing.reason) {
496 existing.reason = reason;
497 }
498 }
499 None => desired.push(DesiredShape {
500 shape,
501 count,
502 reason,
503 }),
504 }
505 }
506 }
507
508 // Bucket the controller-owned replicas by shape. Replicas the controller
509 // does not own (see `ObservedReplica::owned_shape`) are invisible to the
510 // desired/actual diff: neither counted toward a shape nor dropped.
511 let mut actual_by_shape: Vec<(ReplicaShape, Vec<&ObservedReplica>)> = Vec::new();
512 for replica in &state.replicas {
513 let Some(shape) = replica.owned_shape() else {
514 continue;
515 };
516 match actual_by_shape.iter_mut().find(|(s, _)| s.matches(shape)) {
517 Some((_, replicas)) => replicas.push(replica),
518 None => actual_by_shape.push((shape.clone(), vec![replica])),
519 }
520 }
521
522 let mut decisions = Vec::new();
523
524 // Every observed replica occupies a name, owned or not, so a generated
525 // name never collides with a replica already on the cluster.
526 let used_names: Vec<&str> = state.replicas.iter().map(|r| r.name.as_str()).collect();
527 let mut name_gen = ReplicaNameGen::new(&used_names);
528
529 // The compare-and-append witness for every create/drop this tick emits for
530 // the cluster: the apply path rejects the batch if the cluster's durable
531 // state has diverged from what we diffed against (e.g. a concurrent `ALTER`),
532 // so a stale create/drop can never reshape the replica set against the new
533 // config.
534 let expected = state.expected();
535
536 // Creates: for each desired shape, fill the gap below its desired count.
537 for d in &desired {
538 let actual_count = actual_by_shape
539 .iter()
540 .find(|(s, _)| s.matches(&d.shape))
541 .map(|(_, replicas)| replicas.len())
542 .unwrap_or(0);
543 for _ in actual_count..d.count {
544 decisions.push(Decision::CreateReplica {
545 cluster_id: state.cluster_id,
546 name: name_gen.next_name(),
547 shape: d.shape.clone(),
548 // Multiple creates of one shape in a tick share the merged
549 // reason.
550 reason: d.reason.clone(),
551 expected: expected.clone(),
552 });
553 }
554 }
555
556 // Drops: any actual replica beyond the desired count for its shape, plus
557 // every replica of a shape no strategy desires.
558 for (shape, replicas) in &actual_by_shape {
559 let desired_count = desired
560 .iter()
561 .find(|d| d.shape.matches(shape))
562 .map(|d| d.count)
563 .unwrap_or(0);
564 for replica in replicas.iter().skip(desired_count) {
565 decisions.push(Decision::DropReplica {
566 cluster_id: state.cluster_id,
567 replica_id: replica.replica_id,
568 expected: expected.clone(),
569 });
570 }
571 }
572
573 decisions
574}
575
576/// A shape the union desires, how many, and the highest-ranking reason of
577/// the strategies that wanted it.
578struct DesiredShape {
579 shape: ReplicaShape,
580 count: usize,
581 reason: CreateReason,
582}
583
584/// Generates deterministic fresh replica names that avoid a set of in-use names.
585///
586/// The controller derives names from the observed actual set rather than
587/// renaming existing replicas, which keeps re-emission harmless. The concrete
588/// naming convention (the `rNN` managed-replica scheme) is the environment's; the
589/// kernel only needs distinct, stable-per-tick names, so it uses a simple
590/// monotonic scheme starting past the highest observed `rNN` index, and never
591/// below `r1` since managed-replica names are 1-based.
592struct ReplicaNameGen {
593 next: u32,
594 used: BTreeSet<String>,
595}
596
597impl ReplicaNameGen {
598 fn new(used: &[&str]) -> Self {
599 let mut highest = 1;
600 for name in used {
601 if let Some(idx) = name.strip_prefix('r').and_then(|n| n.parse::<u32>().ok()) {
602 highest = highest.max(idx + 1);
603 }
604 }
605 Self {
606 next: highest,
607 used: used.iter().map(|n| n.to_string()).collect(),
608 }
609 }
610
611 fn next_name(&mut self) -> String {
612 loop {
613 let name = format!("r{}", self.next);
614 self.next += 1;
615 if !self.used.contains(&name) {
616 self.used.insert(name.clone());
617 return name;
618 }
619 }
620 }
621}
622
623#[cfg(test)]
624mod tests;