mz_cluster_controller/ctx.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 boundary between the controller and its environment.
11//!
12//! [`ClusterControllerCtx`] is the single, strategy-agnostic boundary through which
13//! the controller pulls the signals a tick examines and applies the catalog
14//! mutations it derives. The signals in are primitive and carry no per-strategy
15//! state; the decisions out are primitive catalog mutations plus per-tick audit
16//! attribution. A create carries the [`CreateReason`] of the winning strategy
17//! behind it, which the environment turns into the audit event. The controller
18//! crate knows nothing about the Coordinator. The Coordinator implements this
19//! trait, which is what makes the controller testable against a fake
20//! implementation and extractable later without touching controller code.
21//!
22//! The interface is **pull-based**: a tick fetches only the signals it actually
23//! examines (no eager all-clusters-all-replicas snapshot is pushed in), and the
24//! controller drives what is fetched. Read methods are batched so a separate-task
25//! deployment can bound its round-trips to the Coordinator.
26
27use std::collections::BTreeSet;
28use std::time::Duration;
29
30use async_trait::async_trait;
31use mz_compute_types::config::ComputeReplicaLogging;
32use mz_controller_types::{ClusterId, ReplicaId};
33use mz_repr::refresh_schedule::RefreshSchedule;
34use mz_repr::{GlobalId, Timestamp};
35use timely::progress::Antichain;
36
37// The compare-and-append witness types, and the replica shape they pair with,
38// live in `mz-adapter-types` so the catalog transaction that applies a
39// decision can share them without depending on this crate. They are part of the
40// ctx vocabulary, so re-export them here.
41pub use mz_adapter_types::cluster_state::{
42 AutoScalingPolicy, AvailabilityZones, BurstAudit, BurstFinishCause, BurstRecord,
43 ClusterSchedule, ExpectedClusterState, OnHydrationPolicy, OnTimeout, ReconfigurationAudit,
44 ReconfigurationRecord, ReconfigurationStatus, ReconfigurationTarget, ReplicaShape,
45};
46
47/// A replica that actually exists on a cluster, as observed through the ctx.
48/// Every replica physically on the cluster appears here, whether or not the
49/// controller owns it; [`Self::owned_shape`] is the ownership test.
50#[derive(Clone, Debug)]
51pub struct ObservedReplica {
52 pub replica_id: ReplicaId,
53 pub name: String,
54 /// `None` for a replica with an unmanaged location, which has no managed
55 /// shape to reconcile against.
56 pub shape: Option<ReplicaShape>,
57 /// Created with `INTERNAL`.
58 pub internal: bool,
59 /// Carries a `BILLED AS` override.
60 pub billed_as: bool,
61 /// The `-pending` target of an in-flight graceful reconfiguration.
62 pub pending: bool,
63}
64
65impl ObservedReplica {
66 /// The replica's shape if the controller owns it, `None` otherwise.
67 ///
68 /// INTERNAL / BILLED AS replicas are manually managed: a user can attach
69 /// one to any managed cluster, outside the replication-factor domain. A
70 /// pending replica is owned by the reconfiguration sequencer path until
71 /// finalize (retiring it would defeat the zero-downtime resize creating
72 /// it). The controller must neither count such a replica toward a desired
73 /// shape nor drop it as excess, but their names still block the name
74 /// generator, since every replica observed here occupies a name.
75 pub fn owned_shape(&self) -> Option<&ReplicaShape> {
76 if self.internal || self.billed_as || self.pending {
77 return None;
78 }
79 self.shape.as_ref()
80 }
81}
82
83/// One REFRESH materialized view bound to a scheduled cluster, as the on-refresh
84/// strategy needs to see it.
85///
86/// `write_frontier` is the MV's storage write frontier, carried with full
87/// fidelity as the `Antichain` the storage controller reports. The strategy
88/// compares it against the read timestamp (`less_than`) to decide whether the MV
89/// still needs a refresh. For the compaction window it reads the frontier's lone
90/// element via `as_option` to find the previous refresh time, falling back to the
91/// schedule's last refresh on the empty/sealed frontier `[]`, mirroring the
92/// legacy refresh policy. The frontier of a single-input total-order MV holds at
93/// most one element.
94#[derive(Clone, Debug, PartialEq, Eq)]
95pub struct RefreshMvInfo {
96 /// The MV's writes-`GlobalId`: the identity the window decision records in
97 /// [`RefreshWindowDecision`] so the audit log can say which MVs kept the
98 /// cluster on.
99 pub id: GlobalId,
100 pub write_frontier: Antichain<Timestamp>,
101 pub refresh_schedule: RefreshSchedule,
102}
103
104/// Why a strategy desires a replica slot: the audit attribution a create
105/// decision carries. When several strategies desire the same shape the
106/// winning reason is decided by [`CreateReason::outranks`], since the audit
107/// event carries exactly one reason.
108#[derive(Clone, Debug, PartialEq, Eq)]
109pub enum CreateReason {
110 /// The implicit baseline: the user's own cluster config calls for the
111 /// replica. The environment audits it as a manual create.
112 Baseline,
113 /// The graceful-reconfiguration strategy converging an in-flight
114 /// background `ALTER CLUSTER`.
115 GracefulReconfiguration,
116 /// The hydration-burst strategy accelerating hydration.
117 HydrationBurst,
118 /// The on-refresh strategy holding a scheduled cluster on inside a
119 /// refresh window. Embeds the window decision behind the create, which
120 /// the environment renders into the audit event's detail. Embedding it
121 /// makes "the decision detail appears iff the create audits the schedule
122 /// reason" structural: when another reason wins the precedence, the
123 /// decision is discarded with it.
124 OnRefresh(RefreshWindowDecision),
125}
126
127impl CreateReason {
128 /// Whether this reason wins over `other` when several strategies desire
129 /// the same shape, so the create audits this reason.
130 ///
131 /// A pairwise check rather than `Ord`: an `Ord` ranking by variant would
132 /// have to call two `OnRefresh` reasons with different window decisions
133 /// equal while `Eq` says they differ, violating the `Ord` contract.
134 pub fn outranks(&self, other: &CreateReason) -> bool {
135 self.rank() > other.rank()
136 }
137
138 fn rank(&self) -> u8 {
139 match self {
140 // Graceful wins over burst when both desire a shape (their shapes
141 // differ in practice, so this is a stable tie-break), both win
142 // over on-refresh, and the baseline loses to everything: any
143 // strategy's reason beats the implicit "the config calls for it".
144 CreateReason::Baseline => 0,
145 CreateReason::OnRefresh(_) => 1,
146 CreateReason::HydrationBurst => 2,
147 CreateReason::GracefulReconfiguration => 3,
148 }
149 }
150}
151
152/// The on-refresh strategy's per-tick window decision: which bound REFRESH MVs
153/// keep a scheduled cluster on, and why. The window is open iff either list is
154/// non-empty, so an open window always has an explanation.
155///
156/// Carried inside [`CreateReason::OnRefresh`] on the create decisions the open
157/// window produces. The environment converts it to the audit log's
158/// `scheduling_policies` detail. Plain ids and durations so the controller crate
159/// stays free of audit-log vocabulary.
160#[derive(Clone, Debug, PartialEq, Eq)]
161pub struct RefreshWindowDecision {
162 /// MVs whose write frontier has not yet passed the (hydration-adjusted) read
163 /// timestamp: a refresh is due or imminent.
164 pub objects_needing_refresh: Vec<GlobalId>,
165 /// MVs estimated to still need Persist compaction after their last refresh.
166 pub objects_needing_compaction: Vec<GlobalId>,
167 /// The cluster's `HYDRATION TIME ESTIMATE` the refresh window was widened by.
168 pub hydration_time_estimate: Duration,
169}
170
171impl RefreshWindowDecision {
172 /// Whether the refresh window is open: some MV still needs a refresh or
173 /// compaction time.
174 pub fn window_open(&self) -> bool {
175 !self.objects_needing_refresh.is_empty() || !self.objects_needing_compaction.is_empty()
176 }
177}
178
179/// The live signals the on-refresh strategy reads to decide whether a scheduled
180/// cluster is inside a refresh window: the current read timestamp, the
181/// Persist-compaction time estimate, and the bound REFRESH MVs' frontiers and
182/// schedules.
183///
184/// Pulled on demand only for scheduled clusters. A MANUAL cluster carries `None`
185/// and is never probed.
186#[derive(Clone, Debug, PartialEq, Eq)]
187pub struct RefreshWindowInputs {
188 /// The local oracle read timestamp the window decision is taken against.
189 pub read_ts: Timestamp,
190 /// How long after a refresh an MV is estimated to still need Persist
191 /// compaction, which also keeps the cluster on.
192 pub compaction_estimate: Duration,
193 /// The REFRESH MVs bound to the cluster.
194 pub refresh_mvs: Vec<RefreshMvInfo>,
195}
196
197/// The durable state of a single managed cluster plus its observed replicas, as
198/// pulled through the ctx for one reconcile tick.
199///
200/// This is the input every strategy reads. Unmanaged clusters are not
201/// controller-owned and are not represented here.
202///
203/// The `size`, `replication_factor`, `availability_zones`, and `logging` fields
204/// together are the realized config the cluster is currently serving. The
205/// implicit baseline desires `replication_factor` replicas at that shape.
206#[derive(Clone, Debug)]
207pub struct ClusterState {
208 pub cluster_id: ClusterId,
209 pub size: String,
210 pub replication_factor: u32,
211 pub availability_zones: Vec<String>,
212 pub logging: ComputeReplicaLogging,
213 pub arrangement_compression: bool,
214 /// The cluster's scheduling policy. Drives whether the implicit baseline owns
215 /// the replica set (MANUAL) or the on-refresh strategy does (REFRESH).
216 pub schedule: ClusterSchedule,
217 pub auto_scaling_policy: Option<AutoScalingPolicy>,
218 /// Latest graceful reconfiguration record, if one has been written.
219 pub reconfiguration: Option<ReconfigurationRecord>,
220 /// In-flight hydration burst, if any.
221 pub burst: Option<BurstRecord>,
222 /// The replicas that actually exist on the cluster, owned or not.
223 pub replicas: Vec<ObservedReplica>,
224}
225
226impl ClusterState {
227 /// The shape the implicit baseline desires: the realized config.
228 pub fn realized_shape(&self) -> ReplicaShape {
229 ReplicaShape {
230 size: self.size.clone(),
231 availability_zones: AvailabilityZones(self.availability_zones.clone()),
232 logging: self.logging.clone(),
233 arrangement_compression: self.arrangement_compression,
234 }
235 }
236
237 /// The compare-and-append witness for decisions derived from this state: the
238 /// durable fields a concurrent `ALTER` could change out from under a tick.
239 pub fn expected(&self) -> ExpectedClusterState {
240 ExpectedClusterState {
241 size: self.size.clone(),
242 replication_factor: self.replication_factor,
243 availability_zones: AvailabilityZones(self.availability_zones.clone()),
244 logging: self.logging.clone(),
245 arrangement_compression: self.arrangement_compression,
246 schedule: self.schedule,
247 auto_scaling_policy: self.auto_scaling_policy.clone(),
248 reconfiguration: self.reconfiguration.clone(),
249 burst: self.burst.clone(),
250 }
251 }
252}
253
254/// A durable state mutation a strategy's `update_state` asks for: cut over the
255/// realized config to a target and/or write or clear the reconfiguration/burst
256/// records. The reconcile kernel pairs it with the [`ExpectedClusterState`] it
257/// was derived from for the compare-and-append guard.
258#[derive(Clone, Debug, Default, PartialEq, Eq)]
259pub struct StateWrite {
260 /// New realized config to cut over to. `None` leaves it unchanged.
261 pub new_size: Option<String>,
262 pub new_replication_factor: Option<u32>,
263 pub new_availability_zones: Option<Vec<String>>,
264 pub new_logging: Option<ComputeReplicaLogging>,
265 pub new_arrangement_compression: Option<bool>,
266 /// Write or clear the reconfiguration record, together with its audit
267 /// intent. `None` leaves the record unchanged.
268 pub reconfiguration: Option<ReconfigurationWrite>,
269 /// Write or clear the burst record, together with its audit intent.
270 /// `None` leaves the record unchanged.
271 pub burst: Option<BurstWrite>,
272}
273
274/// A write to the `reconfiguration` record, bundled with the audit intent
275/// declaring which lifecycle transition the write represents.
276///
277/// Bundling means a writer cannot move the record without deciding, at the same
278/// decision point, what the papertrail should say. The two travel together
279/// through the apply path and are transacted atomically with the state.
280#[derive(Clone, Debug, PartialEq, Eq)]
281pub struct ReconfigurationWrite {
282 /// The record to write, or `None` to clear it.
283 pub record: Option<ReconfigurationRecord>,
284 /// The lifecycle transition to audit. `None` declares that this write is
285 /// not a lifecycle transition and must not emit an event.
286 pub audit: Option<ReconfigurationAudit>,
287}
288
289/// A write to the `burst` record, bundled with its audit intent. See
290/// [`ReconfigurationWrite`]. A bookkeeping rewrite of an existing record (the
291/// linger stamp and its reset) declares `audit: None`.
292#[derive(Clone, Debug, PartialEq, Eq)]
293pub struct BurstWrite {
294 /// The record to write, or `None` to clear it.
295 pub record: Option<BurstRecord>,
296 /// The lifecycle transition to audit, or `None` for a bookkeeping rewrite.
297 pub audit: Option<BurstAudit>,
298}
299
300impl StateWrite {
301 /// Whether this write would actually mutate any durable field.
302 pub fn is_empty(&self) -> bool {
303 // Exhaustive destructure (no `..`): a field added to `StateWrite` is a
304 // compile error here until it's accounted for.
305 let StateWrite {
306 new_size,
307 new_replication_factor,
308 new_availability_zones,
309 new_logging,
310 new_arrangement_compression,
311 reconfiguration,
312 burst,
313 } = self;
314 new_size.is_none()
315 && new_replication_factor.is_none()
316 && new_availability_zones.is_none()
317 && new_logging.is_none()
318 && new_arrangement_compression.is_none()
319 && reconfiguration.is_none()
320 && burst.is_none()
321 }
322}
323
324/// A single command the controller emits for the environment to transact. The
325/// apply path interprets these and turns them into catalog operations.
326///
327/// Every variant carries the [`ExpectedClusterState`] the decision was derived
328/// from. The apply path re-reads each target cluster and rejects the whole batch
329/// if any state has since diverged (compare-and-append), so a user `ALTER` that
330/// lands mid-tick cannot let a stale create or drop reshape the replica set
331/// against the new config; the controller recomputes from the new state next
332/// tick.
333#[derive(Clone, Debug)]
334pub enum Decision {
335 /// Create a replica of the given shape under a deterministic fresh name.
336 /// `reason` is the audit attribution: the winning [`CreateReason`] among
337 /// the strategies that desired the shape (see [`CreateReason::outranks`]).
338 CreateReplica {
339 cluster_id: ClusterId,
340 name: String,
341 shape: ReplicaShape,
342 reason: CreateReason,
343 expected: ExpectedClusterState,
344 },
345 /// Drop a specific existing replica. A drop happens exactly when no
346 /// strategy desires the replica, so it carries no strategy attribution;
347 /// the apply path audits every controller drop with the uniform `retired`
348 /// reason.
349 DropReplica {
350 cluster_id: ClusterId,
351 replica_id: ReplicaId,
352 expected: ExpectedClusterState,
353 },
354 /// Apply a durable state write under a compare-and-append guard against
355 /// `expected`.
356 UpdateClusterState {
357 cluster_id: ClusterId,
358 expected: ExpectedClusterState,
359 write: StateWrite,
360 },
361}
362
363/// The outcome of applying one tick's batch of [`Decision`]s.
364#[derive(Clone, Copy, Debug, PartialEq, Eq)]
365pub enum ApplyOutcome {
366 /// Every decision in the batch was transacted.
367 Applied,
368 /// At least one decision failed its compare-and-append guard. The whole
369 /// batch is rejected; the controller recomputes next tick.
370 Rejected,
371 /// The batch was rejected because it exceeded the environment's resource
372 /// budget. Nothing was transacted. Unlike a guard rejection, retrying the
373 /// same batch cannot succeed on its own: the controller decides what to
374 /// shed to make room.
375 ResourceExhausted,
376}
377
378/// The strategy-agnostic pull/apply interface between the controller and its
379/// environment.
380///
381/// The controller depends on exactly this trait. Reads are batched and pulled
382/// on demand; the single write applies a tick's batch under a compare-and-append
383/// guard. Implementations marshal these to wherever the live signals live (for
384/// v1, the Coordinator's catalog and compute/storage controllers, reached over a
385/// channel from the controller's own task, hence the `Send` bound).
386#[async_trait]
387pub trait ClusterControllerCtx: Send {
388 /// Current wall-clock time, as the controller's strategies should see it.
389 fn now(&self) -> Timestamp;
390
391 /// A consistent durable view of the given managed clusters and their
392 /// replicas. Clusters that do not exist or are unmanaged are omitted from
393 /// the result.
394 async fn cluster_states(&mut self, clusters: &[ClusterId]) -> Vec<ClusterState>;
395
396 /// The ids of all managed clusters the controller owns this tick.
397 async fn managed_cluster_ids(&mut self) -> Vec<ClusterId>;
398
399 /// Of `replicas` on `cluster`, which are online and have *all* current
400 /// (non-transient) collections on the cluster hydrated. The returned set
401 /// is a subset of `replicas`.
402 ///
403 /// Callers should request only replicas their strategy currently needs. This
404 /// keeps live-signal dependencies local to the strategies that consume them.
405 async fn hydrated_replicas(
406 &mut self,
407 cluster_id: ClusterId,
408 replicas: &[ReplicaId],
409 ) -> BTreeSet<ReplicaId>;
410
411 /// Whether `cluster_id` has at least one hydratable (dataflow-backed) object
412 /// bound to it: an index, materialized view, ingestion source, or sink.
413 ///
414 /// A catalog-level approximation of "the hydration check has something to
415 /// count". Where the two disagree at the margin, the mismatch is
416 /// self-healing: a replica with nothing to hydrate reads hydrated, and the
417 /// burst winds down via its linger.
418 async fn has_hydratable_objects(&mut self, cluster_id: ClusterId) -> bool;
419
420 /// The refresh-window live signals for one scheduled cluster: the read
421 /// timestamp, the compaction estimate, and the bound REFRESH MVs' write
422 /// frontiers and schedules. Returns `None` when the cluster is missing,
423 /// unmanaged, or no longer scheduled `ON REFRESH` at pull time. The
424 /// controller only asks about clusters it observed as scheduled, so `None`
425 /// means a concurrent DDL moved the cluster mid-tick, and the schedule's
426 /// membership in the compare-and-append witness rejects any decision
427 /// derived from the stale observation.
428 ///
429 /// Pulled on demand the same way as [`Self::hydrated_replicas`]: the
430 /// controller probes a cluster only when the on-refresh strategy needs the
431 /// signal (i.e. the cluster is scheduled), so a steady MANUAL cluster never
432 /// pays for it.
433 async fn refresh_window_inputs(&mut self, cluster_id: ClusterId)
434 -> Option<RefreshWindowInputs>;
435
436 /// Apply a tick's batch of decisions under their compare-and-append guards.
437 /// Each decision carries the [`ExpectedClusterState`] it was derived from;
438 /// the implementation re-reads every target cluster and, if any has since
439 /// diverged, returns [`ApplyOutcome::Rejected`] without transacting anything.
440 /// Otherwise the batch's catalog operations are transacted together.
441 async fn apply(&mut self, decisions: Vec<Decision>) -> ApplyOutcome;
442}