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 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 write = self.merge_state_writes(state, &signals[&state.cluster_id], &config, now);
135 if write.is_empty() {
136 continue;
137 }
138 phase_1_wrote = true;
139 let decision = Decision::UpdateClusterState {
140 cluster_id: state.cluster_id,
141 expected: state.expected(),
142 write,
143 };
144 // A phase-1 batch carries no creates, so it cannot exhaust the
145 // resource budget. Treat any non-applied outcome as a rejection.
146 if ctx.apply(vec![decision]).await != ApplyOutcome::Applied {
147 rejected.insert(state.cluster_id);
148 }
149 }
150
151 // Phase 2: desired_replicas. The barrier exists so that a cut-over a
152 // phase-1 write performed is visible before we diff the replica set
153 // against the realized config. We re-read (and re-enrich) only if phase 1
154 // wrote. The first read is otherwise still current. A stale diff is
155 // harmless: every create/drop carries its `expected` and is guard-rejected
156 // if the durable state has since diverged.
157 let (states, signals) = if phase_1_wrote {
158 let states = ctx.cluster_states(&cluster_ids).await;
159 let signals = self.fetch_signals(ctx, &states, &config).await;
160 (states, signals)
161 } else {
162 (states, signals)
163 };
164 let now = ctx.now();
165 for state in &states {
166 if rejected.contains(&state.cluster_id) {
167 continue;
168 }
169 let decisions =
170 self.collect_replica_decisions(state, &signals[&state.cluster_id], &config, now);
171 if decisions.is_empty() {
172 continue;
173 }
174 // Per-cluster apply: a guard failure here is isolated to this cluster,
175 // and benign anyway since every command names an explicit replica and
176 // is reconciled away next tick. We do not retry within the tick.
177 match ctx.apply(decisions).await {
178 ApplyOutcome::Applied | ApplyOutcome::Rejected => {}
179 ApplyOutcome::ResourceExhausted => {
180 // The batch exceeded the resource budget. Retrying cannot make
181 // the transient peak smaller, so shed the cluster's most
182 // expendable transient strategy and recompute next tick.
183 //
184 // The failed apply rolled back without changing durable state,
185 // so this tick's `expected` witness is still current, unless a
186 // concurrent user `ALTER` re-targeted the record, in which case
187 // the guard rejects the shed and that new reconfiguration is
188 // left to converge instead of being clobbered.
189 if let Some(shed) = Self::shed_decision(state) {
190 let _ = ctx.apply(vec![shed]).await;
191 }
192 }
193 }
194 }
195 }
196
197 /// The decision that sheds this cluster's most expendable transient strategy
198 /// after a resource-exhausted apply, or `None` if nothing sheddable is
199 /// active.
200 ///
201 /// The strategy to shed is chosen by presence, ranked by expendability, not
202 /// by which create failed: validation is aggregate, and the strategy worth
203 /// giving up may be one whose replicas already materialized rather than one
204 /// in the failed batch. The graceful reconfiguration is the most expendable:
205 /// a discretionary user change that fails cleanly (audited, and the wait-shim
206 /// reports a timeout) and can be retried, while aborting it leaves the
207 /// cluster running at its realized shape. The baseline is never shed, it is
208 /// the committed floor.
209 ///
210 /// We shed one strategy per exhausted apply. If that was not enough, the
211 /// next tick recomputes and sheds the next one.
212 fn shed_decision(state: &ClusterState) -> Option<Decision> {
213 let record = state.reconfiguration.as_ref()?;
214 if !record.is_in_progress() {
215 return None;
216 }
217 Some(Decision::UpdateClusterState {
218 cluster_id: state.cluster_id,
219 expected: state.expected(),
220 write: StateWrite {
221 reconfiguration: Some(ReconfigurationWrite {
222 record: Some(ReconfigurationRecord {
223 status: ReconfigurationStatus::ResourceExhausted,
224 ..record.clone()
225 }),
226 audit: Some(ReconfigurationAudit::ResourceExhausted),
227 }),
228 ..Default::default()
229 },
230 })
231 }
232
233 /// Merge every strategy's [`Strategy::update_state`] for one cluster into the
234 /// single [`StateWrite`] the tick applies under one compare-and-append.
235 ///
236 /// The merge is a per-field join, independent of the order strategies run
237 /// in: a field set by exactly one strategy is taken as-is, a field no
238 /// strategy sets is left unchanged, and a field set to the same value by
239 /// several is that value.
240 ///
241 /// Two strategies setting one field to *different* values is a conflict.
242 /// The strategies keep every field single-writer at any given moment:
243 /// most fields are owned by exactly one strategy outright, and
244 /// `new_replication_factor`, which both the graceful cut-over and the
245 /// on-refresh normalization write, is time-shared (on-refresh skips its
246 /// normalization while a reconfiguration record is in progress). So by
247 /// design a conflict cannot happen and the merge is really a disjoint
248 /// union. We treat a conflict as an invariant violation rather than a
249 /// condition to resolve: there is no safety-meaningful winner to pick for
250 /// a contended `size` or record, so we trip [`soft_panic_or_log!`] (a
251 /// panic under test/CI soft assertions, a logged error in production) and
252 /// leave the field unchanged, the only outcome that cannot make things
253 /// worse. A persistent conflict then freezes that field and keeps tripping
254 /// the alarm, which is the point: surface the design bug loudly instead of
255 /// silently picking an arbitrary value.
256 fn merge_state_writes(
257 &self,
258 state: &ClusterState,
259 signals: &LiveSignals,
260 config: &ConfigSignals,
261 now: mz_repr::Timestamp,
262 ) -> StateWrite {
263 let writes: Vec<StateWrite> = self
264 .strategies
265 .iter()
266 .map(|strategy| strategy.update_state(state, signals, config, now))
267 .filter(|write| !write.is_empty())
268 .collect();
269
270 let mut conflicts: Vec<&'static str> = Vec::new();
271 // Exhaustive construction (every field named, no `..`): a field added to
272 // `StateWrite` is a compile error here until its join is spelled out.
273 let merged = StateWrite {
274 new_size: join(
275 "size",
276 writes.iter().map(|w| w.new_size.clone()),
277 &mut conflicts,
278 ),
279 new_replication_factor: join(
280 "replication_factor",
281 writes.iter().map(|w| w.new_replication_factor),
282 &mut conflicts,
283 ),
284 new_availability_zones: join(
285 "availability_zones",
286 writes.iter().map(|w| w.new_availability_zones.clone()),
287 &mut conflicts,
288 ),
289 new_logging: join(
290 "logging",
291 writes.iter().map(|w| w.new_logging.clone()),
292 &mut conflicts,
293 ),
294 new_arrangement_compression: join(
295 "arrangement_compression",
296 writes.iter().map(|w| w.new_arrangement_compression),
297 &mut conflicts,
298 ),
299 reconfiguration: join(
300 "reconfiguration",
301 writes.iter().map(|w| w.reconfiguration.clone()),
302 &mut conflicts,
303 ),
304 burst: join(
305 "burst",
306 writes.iter().map(|w| w.burst.clone()),
307 &mut conflicts,
308 ),
309 };
310
311 if !conflicts.is_empty() {
312 soft_panic_or_log!(
313 "cluster {:?}: strategies produced conflicting state writes for \
314 field(s) {}; leaving those fields unchanged. Strategies must own \
315 disjoint `StateWrite` fields.",
316 state.cluster_id,
317 conflicts.join(", "),
318 );
319 }
320
321 merged
322 }
323
324 /// Fetch the live signals the strategies declared they need for `states`.
325 ///
326 /// Each strategy names its needs as a pure function of the durable state
327 /// and the tick's config signals ([`Strategy::signal_request`]), so the
328 /// kernel stays ignorant of when a strategy engages. Signals are fetched per
329 /// cluster and only where requested: a steady cluster is never probed,
330 /// keeping the ctx seam pay-for-what-you-use. The returned map has an entry
331 /// for every state.
332 async fn fetch_signals(
333 &self,
334 ctx: &mut dyn ClusterControllerCtx,
335 states: &[ClusterState],
336 config: &ConfigSignals,
337 ) -> BTreeMap<ClusterId, LiveSignals> {
338 let mut signals = BTreeMap::new();
339 for state in states {
340 let request = self
341 .strategies
342 .iter()
343 .fold(SignalRequest::default(), |acc, strategy| {
344 acc.union(strategy.signal_request(state, config))
345 });
346 let mut live = LiveSignals::default();
347 if request.hydratable_objects {
348 live.has_hydratable_objects = ctx.has_hydratable_objects(state.cluster_id).await;
349 }
350 if request.hydration {
351 let replica_ids: Vec<_> = state
352 .replicas
353 .iter()
354 .filter(|r| r.owned_shape().is_some())
355 .map(|r| r.replica_id)
356 .collect();
357 if !replica_ids.is_empty() {
358 live.hydrated_replicas =
359 ctx.hydrated_replicas(state.cluster_id, &replica_ids).await;
360 }
361 }
362 if request.refresh_window {
363 live.refresh_window = ctx.refresh_window_inputs(state.cluster_id).await;
364 }
365 signals.insert(state.cluster_id, live);
366 }
367 signals
368 }
369
370 /// Diff the unioned desired set against the actual replicas of one cluster
371 /// and emit the create/drop decisions that close the gap.
372 fn collect_replica_decisions(
373 &self,
374 state: &ClusterState,
375 signals: &LiveSignals,
376 config: &ConfigSignals,
377 now: mz_repr::Timestamp,
378 ) -> Vec<Decision> {
379 let contributions: Vec<Vec<DesiredReplica>> = self
380 .strategies
381 .iter()
382 .map(|strategy| strategy.desired_replicas(state, signals, config, now))
383 .collect();
384
385 reconcile_replicas(state, &contributions)
386 }
387}
388
389/// Join one `StateWrite` field across the strategies that set it: `None` if
390/// none did, the common value if one or more set it to the same value, and
391/// `None` with `field` pushed onto `conflicts` if two set it to different
392/// values. The result and the conflict signal depend only on the set of values,
393/// not the order they arrive in.
394fn join<T: PartialEq>(
395 field: &'static str,
396 values: impl IntoIterator<Item = Option<T>>,
397 conflicts: &mut Vec<&'static str>,
398) -> Option<T> {
399 let mut merged: Option<T> = None;
400 for value in values.into_iter().flatten() {
401 match &merged {
402 None => merged = Some(value),
403 Some(existing) if *existing == value => {}
404 // Two strategies disagree on this field. Record it and leave the
405 // field unchanged; merge_state_writes raises the alarm.
406 Some(_) => {
407 conflicts.push(field);
408 return None;
409 }
410 }
411 }
412 merged
413}
414
415/// The pure multiset union/diff kernel for one cluster: given each strategy's
416/// desired replica slots and the actual replicas, match slots to replicas by
417/// shape and emit the creates and drops that close the gap.
418///
419/// Semantics:
420/// - The desired set is the multiset **union** of every strategy's slots: a
421/// given shape is desired `max` over strategies (not the sum), since a replica
422/// of that shape satisfies every strategy that wants one. This is what makes a
423/// replica survive iff *some* strategy desires its shape.
424/// - For each shape, if actual count < desired count we create the difference;
425/// if actual count > desired count we drop the difference, picking specific
426/// excess replicas. A replica of a shape no strategy desires is dropped.
427/// - Creates carry the winning [`CreateReason`] among the slots that
428/// desired the shape (see [`CreateReason::outranks`]). Drops carry no
429/// attribution. A drop happens exactly when no strategy desires the replica.
430fn reconcile_replicas(
431 state: &ClusterState,
432 contributions: &[Vec<DesiredReplica>],
433) -> Vec<Decision> {
434 // Desired count per shape = max over strategies of how many that strategy
435 // wants of the shape, carrying the highest-ranking reason among the
436 // slots.
437 let mut desired: Vec<DesiredShape> = Vec::new();
438 for slots in contributions {
439 // How many of each shape this strategy wants, and the winning reason
440 // among the shape's slots.
441 let mut per_shape: Vec<(ReplicaShape, usize, CreateReason)> = Vec::new();
442 for slot in slots {
443 match per_shape
444 .iter_mut()
445 .find(|(s, _, _)| s.matches(&slot.shape))
446 {
447 Some((_, count, reason)) => {
448 *count += 1;
449 if slot.reason.outranks(reason) {
450 *reason = slot.reason.clone();
451 }
452 }
453 None => per_shape.push((slot.shape.clone(), 1, slot.reason.clone())),
454 }
455 }
456 for (shape, count, reason) in per_shape {
457 match desired.iter_mut().find(|d| d.shape.matches(&shape)) {
458 Some(existing) => {
459 existing.count = existing.count.max(count);
460 if reason.outranks(&existing.reason) {
461 existing.reason = reason;
462 }
463 }
464 None => desired.push(DesiredShape {
465 shape,
466 count,
467 reason,
468 }),
469 }
470 }
471 }
472
473 // Bucket the controller-owned replicas by shape. Replicas the controller
474 // does not own (see `ObservedReplica::owned_shape`) are invisible to the
475 // desired/actual diff: neither counted toward a shape nor dropped.
476 let mut actual_by_shape: Vec<(ReplicaShape, Vec<&ObservedReplica>)> = Vec::new();
477 for replica in &state.replicas {
478 let Some(shape) = replica.owned_shape() else {
479 continue;
480 };
481 match actual_by_shape.iter_mut().find(|(s, _)| s.matches(shape)) {
482 Some((_, replicas)) => replicas.push(replica),
483 None => actual_by_shape.push((shape.clone(), vec![replica])),
484 }
485 }
486
487 let mut decisions = Vec::new();
488
489 // Every observed replica occupies a name, owned or not, so a generated
490 // name never collides with a replica already on the cluster.
491 let used_names: Vec<&str> = state.replicas.iter().map(|r| r.name.as_str()).collect();
492 let mut name_gen = ReplicaNameGen::new(&used_names);
493
494 // The compare-and-append witness for every create/drop this tick emits for
495 // the cluster: the apply path rejects the batch if the cluster's durable
496 // state has diverged from what we diffed against (e.g. a concurrent `ALTER`),
497 // so a stale create/drop can never reshape the replica set against the new
498 // config.
499 let expected = state.expected();
500
501 // Creates: for each desired shape, fill the gap below its desired count.
502 for d in &desired {
503 let actual_count = actual_by_shape
504 .iter()
505 .find(|(s, _)| s.matches(&d.shape))
506 .map(|(_, replicas)| replicas.len())
507 .unwrap_or(0);
508 for _ in actual_count..d.count {
509 decisions.push(Decision::CreateReplica {
510 cluster_id: state.cluster_id,
511 name: name_gen.next_name(),
512 shape: d.shape.clone(),
513 // Multiple creates of one shape in a tick share the merged
514 // reason.
515 reason: d.reason.clone(),
516 expected: expected.clone(),
517 });
518 }
519 }
520
521 // Drops: any actual replica beyond the desired count for its shape, plus
522 // every replica of a shape no strategy desires.
523 for (shape, replicas) in &actual_by_shape {
524 let desired_count = desired
525 .iter()
526 .find(|d| d.shape.matches(shape))
527 .map(|d| d.count)
528 .unwrap_or(0);
529 for replica in replicas.iter().skip(desired_count) {
530 decisions.push(Decision::DropReplica {
531 cluster_id: state.cluster_id,
532 replica_id: replica.replica_id,
533 expected: expected.clone(),
534 });
535 }
536 }
537
538 decisions
539}
540
541/// A shape the union desires, how many, and the highest-ranking reason of
542/// the strategies that wanted it.
543struct DesiredShape {
544 shape: ReplicaShape,
545 count: usize,
546 reason: CreateReason,
547}
548
549/// Generates deterministic fresh replica names that avoid a set of in-use names.
550///
551/// The controller derives names from the observed actual set rather than
552/// renaming existing replicas, which keeps re-emission harmless. The concrete
553/// naming convention (the `rNN` managed-replica scheme) is the environment's; the
554/// kernel only needs distinct, stable-per-tick names, so it uses a simple
555/// monotonic scheme starting past the highest observed `rNN` index, and never
556/// below `r1` since managed-replica names are 1-based.
557struct ReplicaNameGen {
558 next: u32,
559 used: BTreeSet<String>,
560}
561
562impl ReplicaNameGen {
563 fn new(used: &[&str]) -> Self {
564 let mut highest = 1;
565 for name in used {
566 if let Some(idx) = name.strip_prefix('r').and_then(|n| n.parse::<u32>().ok()) {
567 highest = highest.max(idx + 1);
568 }
569 }
570 Self {
571 next: highest,
572 used: used.iter().map(|n| n.to_string()).collect(),
573 }
574 }
575
576 fn next_name(&mut self) -> String {
577 loop {
578 let name = format!("r{}", self.next);
579 self.next += 1;
580 if !self.used.contains(&name) {
581 self.used.insert(name.clone());
582 return name;
583 }
584 }
585 }
586}
587
588#[cfg(test)]
589mod tests;