Skip to main content

mz_adapter/coord/
caught_up.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! Support for checking whether clusters/collections are caught up during a 0dt
11//! deployment.
12//!
13//! During a zero-downtime upgrade the new `environmentd` boots read-only and
14//! reports "ready to promote" once its clusters have caught up with the leader
15//! generation. A task spawned by [`Coordinator::spawn_caught_up_check_task`]
16//! runs that check on an interval (see
17//! [`WITH_0DT_DEPLOYMENT_CAUGHT_UP_CHECK_INTERVAL`]). We call one such run a
18//! "tick", and the term is used throughout this module.
19//!
20//! Each tick the task reads the leader's Persist collections, then asks the
21//! coordinator to capture local state and issue hydration requests. The task
22//! awaits the replies, classifies the clusters and applies the stability gate.
23//! None of those waits run on the coordinator loop.
24//!
25//! A point-in-time caught-up check is not enough on its own: a crash- or
26//! OOM-looping replica can momentarily look hydrated and caught-up, and cutting
27//! over right then drops us straight into a crashing replica. On top of the
28//! per-tick caught-up classification we therefore run a stability gate. A
29//! caught-up cluster is ready only once every replica is `Online` and every
30//! non-exempt replica has had its non-ignored collections hydrated for a
31//! configurable period, capped for young replicas by [`observe_stability`].
32//!
33//! Each replica reports its hydration times in its
34//! `mz_compute_hydration_times_per_worker` introspection log. The log lives in
35//! the replica process. It survives environmentd restarts, because a restarted
36//! environmentd reconciles with the same replica processes and they keep
37//! compatible dataflows, so a DDL-triggered restart does not restart the
38//! period. A dataflow that changed rehydrates and restarts it. The log dies
39//! with the process, so a restarted replica must hydrate again and establish
40//! a new observation period, subject to the young-replica cap.
41//!
42//! Hydration times come from the replica's clock, while the period is measured
43//! against environmentd's. A replica clock that runs ahead only lengthens the
44//! wait, but one that runs behind shortens the period by the skew. We rely on
45//! hosts keeping their clocks in sync.
46//!
47//! A replica without introspection logging cannot report hydration times. It
48//! only has to be `Online`. Leader-relative exemptions are defined by
49//! [`LeaderHydration::replica_has_unhydrated_collection`].
50
51use std::collections::{BTreeMap, BTreeSet};
52use std::sync::Arc;
53use std::time::Duration;
54
55use anyhow::Context;
56use differential_dataflow::lattice::Lattice as _;
57use futures::{StreamExt, future};
58use itertools::Itertools;
59use mz_adapter_types::dyncfgs::{
60    ENABLE_0DT_CAUGHT_UP_REPLICA_STATUS_CHECK, ENABLE_0DT_CAUGHT_UP_STABILITY_CHECK,
61    WITH_0DT_CAUGHT_UP_CHECK_ALLOWED_LAG, WITH_0DT_CAUGHT_UP_CHECK_CUTOFF,
62    WITH_0DT_CAUGHT_UP_CHECK_STABILITY_PERIOD, WITH_0DT_DEPLOYMENT_CAUGHT_UP_CHECK_INTERVAL,
63};
64use mz_catalog::builtin::{
65    MZ_CATALOG_SERVER_CLUSTER, MZ_CLUSTER_REPLICA_FRONTIERS, MZ_CLUSTER_REPLICA_STATUS_HISTORY,
66    MZ_COMPUTE_HYDRATION_TIMES,
67};
68use mz_catalog::memory::objects::Cluster;
69use mz_compute_client::controller::CollectionReadiness;
70use mz_compute_client::controller::error::CollectionMissing;
71use mz_compute_client::logging::{ComputeLog, LogVariant};
72use mz_controller::clusters::ClusterStatus;
73use mz_controller_types::{ClusterId, ReplicaId};
74use mz_orchestrator::OfflineReason;
75use mz_ore::channel::trigger::Trigger;
76use mz_ore::now::EpochMillis;
77use mz_ore::task;
78use mz_repr::{GlobalId, Row, Timestamp};
79use mz_storage_client::storage_collections::StorageCollections;
80use timely::progress::{Antichain, Timestamp as _};
81use tokio::sync::oneshot;
82
83use crate::PeekClient;
84use crate::catalog::Catalog;
85use crate::command::{CatalogSnapshot, Command};
86use crate::coord::{ClusterReplicaStatuses, Coordinator, Message};
87
88/// How long the stability gate waits for an internal query.
89///
90/// Timeout drops the query without canceling its peek. See
91/// [`PeekClient::background_peek`] for the lifetime of retained resources.
92const STABILITY_QUERY_TIMEOUT: Duration = Duration::from_secs(5);
93
94/// Returns a query for when a replica last finished hydrating an export.
95///
96/// It returns no row if the replica has reported no non-transient export.
97/// Otherwise its one row says whether the export is in `ignored`, which holds
98/// only when every reported export is, and its hydration time: NULL if some
99/// export not in `ignored` is not hydrated on some worker, else the latest
100/// time one of them hydrated.
101///
102/// NOTE: This must stay a fast-path peek, an index scan plus a finishing, so
103/// that it does not install a dataflow on every replica on every tick.
104/// Aggregates would make it a slow-path peek.
105fn hydration_query(ignored: &BTreeSet<GlobalId>) -> String {
106    let is_ignored = if ignored.is_empty() {
107        "false".to_string()
108    } else {
109        let ids = ignored.iter().map(|id| format!("'{id}'")).join(", ");
110        format!("export_id IN ({ids})")
111    };
112    format!(
113        "SELECT {is_ignored} AS ignored, hydrated_at \
114        FROM mz_introspection.mz_compute_hydration_times_per_worker \
115        WHERE export_id NOT LIKE 't%' \
116        ORDER BY ignored, hydrated_at DESC NULLS FIRST LIMIT 1"
117    )
118}
119
120/// Context needed to check whether clusters/collections are caught up.
121#[derive(Debug)]
122pub struct CaughtUpCheckContext {
123    /// A trigger that signals that all clusters/collections have been caught
124    /// up.
125    pub trigger: Trigger,
126    /// Collections to exclude from the caught up check, such as collections that can't advance
127    /// their write frontier in read-only mode during a 0dt upgrade.
128    pub exclude_collections: BTreeSet<GlobalId>,
129}
130
131/// Requests local controller state without waiting for external reads.
132#[derive(Debug)]
133pub struct CaughtUpCheckRequest {
134    exclude_collections: Arc<BTreeSet<GlobalId>>,
135    tx: oneshot::Sender<CaughtUpCheck>,
136}
137
138/// Inputs owned by one background check.
139#[derive(Debug)]
140struct CaughtUpCheck {
141    catalog: Arc<Catalog>,
142    now: EpochMillis,
143    clusters: BTreeMap<ClusterId, Result<ClusterSnapshot, anyhow::Error>>,
144}
145
146struct LeaderSnapshot {
147    frontiers: BTreeMap<GlobalId, Antichain<Timestamp>>,
148    /// The leader's clock: the upper of `mz_cluster_replica_frontiers`, the collection that
149    /// `frontiers` is read from.
150    ///
151    /// The leader advances that upper to its wall clock every second, even when it has nothing to
152    /// write. A read-only process never advances it (see the storage controller's
153    /// `collection_mgmt`). So while the leader is down, this stays at the leader's last second.
154    ///
155    /// NOTE: the newest of `frontiers` is no substitute: a collection such as a `REFRESH` MV holds
156    /// its frontier at its next refresh, which can be far ahead of the leader's clock.
157    clock: Timestamp,
158    hydration: LeaderHydration,
159    unhydrated_collections: BTreeSet<GlobalId>,
160    problematic_replicas: BTreeSet<ReplicaId>,
161}
162
163#[derive(Debug)]
164struct ClusterSnapshot {
165    replicas: BTreeMap<ReplicaId, ReplicaTarget>,
166    ignored_compute_collections: BTreeSet<GlobalId>,
167    collections: Vec<(GlobalId, Antichain<Timestamp>, CollectionType)>,
168    compute_hydration: oneshot::Receiver<BTreeMap<GlobalId, Result<bool, CollectionMissing>>>,
169}
170
171#[derive(Debug)]
172enum CollectionType {
173    Storage { hydrated: bool },
174    Compute,
175}
176
177/// The cluster classification and stability inputs for one tick.
178#[derive(Debug)]
179struct CaughtUpSnapshot {
180    now: EpochMillis,
181    /// Whether every cluster is caught up or ignored.
182    all_caught_up: bool,
183    stability_check_enabled: bool,
184    stability_period_ms: u64,
185    /// Every caught-up cluster. Empty when the stability check is disabled.
186    caught_up_clusters: BTreeMap<ClusterId, CaughtUpCluster>,
187}
188
189/// A caught-up cluster, as the stability gate needs to know it.
190#[derive(Debug)]
191struct CaughtUpCluster {
192    /// Compute collections the classification ignored, which therefore need not
193    /// hydrate.
194    ignored_compute_collections: BTreeSet<GlobalId>,
195    replicas: BTreeMap<ReplicaId, ReplicaTarget>,
196}
197
198/// What the coordinator knows about a replica of a caught-up cluster, and so
199/// whether the stability gate has to ask it.
200#[derive(Debug, Clone, Copy, PartialEq, Eq)]
201enum ReplicaTarget {
202    /// See [`ReplicaHealth::NotOnline`].
203    NotOnline,
204    /// See [`ReplicaHealth::Exempt`].
205    Exempt,
206    /// The replica is `Online` and has to report its hydration times.
207    Ask,
208}
209
210/// How a cluster relates to the 0dt caught-up check on a given tick.
211#[derive(Debug, Clone, PartialEq, Eq)]
212enum ClusterCaughtUpStatus {
213    /// Hydrated and within lag, apart from `ignored_compute_collections`.
214    /// Subject to the stability gate.
215    CaughtUp {
216        /// Compute collections the classification ignored, see
217        /// [`CaughtUpCluster::ignored_compute_collections`].
218        ignored_compute_collections: BTreeSet<GlobalId>,
219    },
220    /// Excluded by the existing checks (no replicas, or hopelessly behind with
221    /// only crash/OOM-looping replicas). Does not block readiness and is not
222    /// health-gated, so we keep ignoring clusters that are already unhealthy in
223    /// the leader environment.
224    Ignored,
225    /// Not yet caught up. Blocks readiness.
226    NotCaughtUp,
227}
228
229/// What the stability gate knows about one replica on a given tick.
230#[derive(Debug, Clone, Copy, PartialEq, Eq)]
231enum ReplicaHealth {
232    /// The replica is not currently `Online`.
233    NotOnline,
234    /// The replica is `Online`, but has not hydrated everything it hosts, or
235    /// did not answer the hydration query.
236    NotHydrated,
237    /// The replica has been healthy since this wall-clock time.
238    HealthySince(EpochMillis),
239    /// The replica is `Online` and exempt from the hydration stability check.
240    Exempt,
241}
242
243/// Why a caught-up cluster is being held back by the stability gate on a given
244/// tick. Recorded so we can log the cause.
245#[derive(Debug, Clone, Copy, PartialEq, Eq)]
246enum StabilityBlocker {
247    /// Not all replicas are currently `Online`.
248    NotOnline,
249    /// Some replica has not hydrated everything it hosts.
250    NotHydrated,
251    /// Every replica is healthy, but not yet for the required period.
252    WithinPeriod,
253}
254
255/// Outcome of folding a cluster's replica health.
256#[derive(Debug, Clone, Copy)]
257struct StabilityObservation {
258    /// How long the cluster has been stable, in milliseconds. `None` when some
259    /// replica has no evidence of health.
260    stable_for_ms: Option<u64>,
261    /// Why the cluster is held back. `None` once it is ready.
262    blocked_by: Option<StabilityBlocker>,
263}
264
265/// Folds the health of a cluster's replicas into the gate's verdict.
266///
267/// Each replica waits for the configured period, capped at its creation age
268/// when it hydrated. Missing or invalid creation evidence retains the full
269/// period. Replica clocks running behind shorten the wait by their skew.
270fn observe_stability(
271    replicas: &[(ReplicaHealth, Option<EpochMillis>)],
272    now: EpochMillis,
273    period_ms: u64,
274) -> StabilityObservation {
275    let blocked = |blocker| StabilityObservation {
276        stable_for_ms: None,
277        blocked_by: Some(blocker),
278    };
279    if replicas.is_empty()
280        || replicas
281            .iter()
282            .any(|(health, _)| *health == ReplicaHealth::NotOnline)
283    {
284        return blocked(StabilityBlocker::NotOnline);
285    }
286    let mut stable_since = EpochMillis::MIN;
287    let mut within_period = false;
288    for (health, created_at) in replicas {
289        match health {
290            ReplicaHealth::HealthySince(since) => {
291                stable_since = stable_since.max(*since);
292                // Freeze the age at hydration. Using its current age makes
293                // the required period grow as quickly as the observed period.
294                let required = match created_at {
295                    Some(created) if created <= since && *since <= now => {
296                        period_ms.min(since - created)
297                    }
298                    _ => period_ms,
299                };
300                within_period |= now.saturating_sub(*since) < required;
301            }
302            ReplicaHealth::Exempt => {}
303            ReplicaHealth::NotOnline | ReplicaHealth::NotHydrated => {
304                return blocked(StabilityBlocker::NotHydrated);
305            }
306        }
307    }
308    let stable_for_ms = now.saturating_sub(stable_since.min(now));
309    StabilityObservation {
310        stable_for_ms: Some(stable_for_ms),
311        blocked_by: within_period.then_some(StabilityBlocker::WithinPeriod),
312    }
313}
314
315/// The part of the caught-up check that runs in its own task: it asks replicas
316/// for their hydration times and applies the stability gate.
317struct StabilityGate {
318    client: PeekClient,
319    replica_created_at: BTreeMap<ReplicaId, EpochMillis>,
320}
321
322impl StabilityGate {
323    /// Returns whether `snapshot` shows every cluster ready for promotion.
324    async fn ready(&mut self, snapshot: CaughtUpSnapshot) -> bool {
325        fail::fail_point!("0dt_caught_up_check", |_| false);
326        let CaughtUpSnapshot {
327            now,
328            all_caught_up,
329            stability_check_enabled,
330            stability_period_ms,
331            caught_up_clusters,
332        } = snapshot;
333        // Disabling the stability check is a fleet-wide break-glass that makes
334        // caught-up clusters ready without waiting on replica health. While
335        // some cluster is not caught up, readiness is blocked anyway, so no
336        // replica needs to be asked.
337        if !all_caught_up || !stability_check_enabled {
338            tracing::info!(all_ready = %all_caught_up, "checked caught-up status of clusters");
339            return all_caught_up;
340        }
341
342        // Missing evidence keeps the full period. Retry until every queried
343        // user replica has a creation time, since catalog views may hydrate late.
344        if caught_up_clusters.values().any(|cluster| {
345            cluster.replicas.iter().any(|(id, target)| {
346                id.is_user()
347                    && *target == ReplicaTarget::Ask
348                    && !self.replica_created_at.contains_key(id)
349            })
350        }) {
351            self.load_replica_creation_times().await;
352        }
353        let answers = self.ask_replicas(&caught_up_clusters).await;
354
355        let mut all_ready = true;
356        for (cluster_id, cluster) in caught_up_clusters {
357            let health: BTreeMap<_, _> = cluster
358                .replicas
359                .iter()
360                .map(|(replica_id, target)| {
361                    let replica_health = match target {
362                        ReplicaTarget::NotOnline => ReplicaHealth::NotOnline,
363                        ReplicaTarget::Exempt => ReplicaHealth::Exempt,
364                        ReplicaTarget::Ask => answers
365                            .get(replica_id)
366                            .copied()
367                            .unwrap_or(ReplicaHealth::NotHydrated),
368                    };
369                    (*replica_id, replica_health)
370                })
371                .collect();
372
373            let replica_health = health
374                .iter()
375                .map(|(id, health)| (*health, self.replica_created_at.get(id).copied()))
376                .collect_vec();
377            let observation = observe_stability(&replica_health, now, stability_period_ms);
378            if let Some(reason) = observation.blocked_by {
379                all_ready = false;
380                tracing::debug!(
381                    %cluster_id,
382                    ?reason,
383                    replicas = ?health,
384                    stable_for_ms = ?observation.stable_for_ms,
385                    required_period_ms = stability_period_ms,
386                    "cluster is caught up but not yet stable for the required period"
387                );
388            }
389        }
390
391        tracing::info!(%all_ready, "checked caught-up status of clusters");
392        all_ready
393    }
394
395    async fn load_replica_creation_times(&mut self) {
396        let query = async {
397            let CatalogSnapshot { catalog } = self
398                .client
399                .call_coordinator(|tx| Command::CatalogSnapshot { tx })
400                .await?;
401            let cluster = catalog.resolve_builtin_cluster(&MZ_CATALOG_SERVER_CLUSTER);
402            let replica = cluster.replicas().next().ok_or_else(|| {
403                crate::AdapterError::Internal("catalog server has no replicas".into())
404            })?;
405            let (cluster_id, replica_id) = (cluster.id, replica.replica_id);
406            drop(catalog);
407            self.client.background_peek(
408                "SELECT replica_id, created_at FROM mz_internal.mz_cluster_replica_history WHERE dropped_at IS NULL",
409                cluster_id, replica_id,
410            ).await
411        };
412        match tokio::time::timeout(STABILITY_QUERY_TIMEOUT, query).await {
413            Ok(Ok(rows)) => {
414                for row in rows {
415                    let mut values = row.iter();
416                    let id = values.next().expect("replica_id");
417                    let created = values.next().expect("created_at");
418                    if id.is_null() || created.is_null() {
419                        continue;
420                    }
421                    if let (Ok(id), Ok(created)) = (
422                        id.unwrap_str().parse::<ReplicaId>(),
423                        u64::try_from(created.unwrap_timestamptz().timestamp_millis()),
424                    ) {
425                        self.replica_created_at.insert(id, created);
426                    }
427                }
428            }
429            Ok(Err(error)) => {
430                tracing::warn!(%error, "replica creation query failed; retaining full stability period")
431            }
432            Err(_) => {
433                tracing::warn!("replica creation query timed out; retaining full stability period")
434            }
435        }
436    }
437
438    /// Asks every [`ReplicaTarget::Ask`] replica, concurrently, when it last
439    /// finished hydrating an export.
440    async fn ask_replicas(
441        &self,
442        clusters: &BTreeMap<ClusterId, CaughtUpCluster>,
443    ) -> BTreeMap<ReplicaId, ReplicaHealth> {
444        let queries = clusters.iter().flat_map(|(&cluster_id, cluster)| {
445            let sql = hydration_query(&cluster.ignored_compute_collections);
446            cluster
447                .replicas
448                .iter()
449                .filter(|(_, target)| **target == ReplicaTarget::Ask)
450                .map(move |(&replica_id, _)| {
451                    let mut client = self.client.clone();
452                    let sql = sql.clone();
453                    async move {
454                        let query = client.background_peek(&sql, cluster_id, replica_id);
455                        let answer = tokio::time::timeout(STABILITY_QUERY_TIMEOUT, query).await;
456                        let health = match answer {
457                            Ok(Ok(rows)) => replica_health(&rows),
458                            Ok(Err(error)) => {
459                                tracing::warn!(
460                                    %cluster_id, %replica_id, %error, "hydration query failed"
461                                );
462                                ReplicaHealth::NotHydrated
463                            }
464                            Err(_elapsed) => {
465                                tracing::warn!(%cluster_id, %replica_id, "hydration query timed out");
466                                ReplicaHealth::NotHydrated
467                            }
468                        };
469                        (replica_id, health)
470                    }
471                })
472        });
473        future::join_all(queries).await.into_iter().collect()
474    }
475}
476
477/// Interprets the rows of a [`hydration_query`].
478fn replica_health(rows: &[Row]) -> ReplicaHealth {
479    let Some(row) = rows.first() else {
480        // The replica has not reported its exports yet.
481        return ReplicaHealth::NotHydrated;
482    };
483    let mut datums = row.iter();
484    let ignored = datums.next().expect("ignored column");
485    let hydrated_at = datums.next().expect("hydrated_at column");
486    if ignored.unwrap_bool() {
487        // The classification ignored every export the replica hosts, so no
488        // hydration is left to wait for.
489        return ReplicaHealth::Exempt;
490    }
491    if hydrated_at.is_null() {
492        return ReplicaHealth::NotHydrated;
493    }
494    let millis = hydrated_at.unwrap_timestamptz().timestamp_millis();
495    // A time before the epoch is nonsense, and must not read as stable for
496    // decades.
497    u64::try_from(millis).map_or(ReplicaHealth::NotHydrated, ReplicaHealth::HealthySince)
498}
499
500impl Coordinator {
501    /// Spawns the task that checks, on an interval, whether all
502    /// clusters/collections are caught up, and fires the trigger of
503    /// `self.caught_up_check` once they are.
504    ///
505    /// A no-op when there is no caught-up check, i.e. outside read-only mode.
506    pub(crate) fn spawn_caught_up_check_task(&mut self) {
507        let Some(CaughtUpCheckContext {
508            trigger,
509            exclude_collections,
510        }) = self.caught_up_check.take()
511        else {
512            return;
513        };
514        let exclude_collections = Arc::new(exclude_collections);
515        let period = WITH_0DT_DEPLOYMENT_CAUGHT_UP_CHECK_INTERVAL
516            .get(self.catalog().system_config().dyncfgs());
517        let internal_cmd_tx = self.internal_cmd_tx.clone();
518        let mut catalog = self.owned_catalog();
519        let storage_collections = Arc::clone(&self.controller.storage_collections);
520        let mut gate = StabilityGate {
521            client: self.background_peek_client(&self.owned_catalog()),
522            replica_created_at: BTreeMap::new(),
523        };
524
525        task::spawn(|| "caught_up_check", async move {
526            let mut delay = None;
527            loop {
528                // Leave a full idle period between attempts, including retries.
529                // An interval would immediately retry a check that outlasted its period.
530                if let Some(delay) = delay {
531                    tokio::time::sleep(delay).await;
532                }
533                delay = Some(period);
534                // Sample the leader before local frontiers and hydration. Slow
535                // Persist reads must not age local evidence or create artificial lag.
536                let leader = match LeaderSnapshot::read(&catalog, &*storage_collections).await {
537                    Ok(leader) => leader,
538                    Err(error) => {
539                        tracing::warn!(%error, "cannot read leader caught-up state");
540                        continue;
541                    }
542                };
543                let leader_revision = catalog.transient_revision();
544                let (tx, rx) = oneshot::channel();
545                let request = CaughtUpCheckRequest {
546                    exclude_collections: Arc::clone(&exclude_collections),
547                    tx,
548                };
549                // A failed send or a dropped reply means the coordinator is
550                // gone.
551                //
552                // NOTE: Returning drops `trigger`, which fires it, so a
553                // coordinator shutdown reads as caught up.
554                if internal_cmd_tx
555                    .send(Message::CaughtUpCheck(request))
556                    .is_err()
557                {
558                    return;
559                }
560                let Ok(check) = rx.await else {
561                    return;
562                };
563                catalog = Arc::clone(&check.catalog);
564                // Read-only mode rejects catalog transactions and handles leader DDL
565                // by restarting via `check_ddl_changes`. Both revision checks guard
566                // against stale evidence if catalog changes are ever applied in place.
567                if catalog.transient_revision() != leader_revision {
568                    continue;
569                }
570                let snapshot = check.run(leader).await;
571                if gate.ready(snapshot).await && catalog.transient_revision_is_current() {
572                    trigger.fire();
573                    return;
574                }
575            }
576        });
577    }
578
579    /// Captures local state and issues hydration requests without awaiting them.
580    pub(crate) fn handle_caught_up_check_request(&self, request: CaughtUpCheckRequest) {
581        let CaughtUpCheckRequest {
582            exclude_collections,
583            tx,
584        } = request;
585        let clusters = self
586            .catalog()
587            .clusters()
588            .filter(|cluster| cluster.replicas().next().is_some())
589            .map(|cluster| {
590                (
591                    cluster.id,
592                    self.caught_up_cluster_snapshot(cluster, &exclude_collections),
593                )
594            })
595            .collect();
596        let _ = tx.send(CaughtUpCheck {
597            catalog: self.owned_catalog(),
598            now: self.now(),
599            clusters,
600        });
601    }
602
603    fn caught_up_cluster_snapshot(
604        &self,
605        cluster: &Cluster,
606        exclude_collections: &BTreeSet<GlobalId>,
607    ) -> Result<ClusterSnapshot, anyhow::Error> {
608        let has_hydration_log = cluster
609            .log_indexes
610            .contains_key(&LogVariant::Compute(ComputeLog::HydrationTime));
611        let replicas = cluster
612            .replicas()
613            .map(|replica| {
614                let online = self
615                    .cluster_replica_statuses
616                    .try_get_cluster_replica_statuses(cluster.id, replica.replica_id)
617                    .is_some_and(|processes| {
618                        !processes.is_empty()
619                            && ClusterReplicaStatuses::cluster_replica_status(processes)
620                                == ClusterStatus::Online
621                    });
622                let target = if !online {
623                    ReplicaTarget::NotOnline
624                } else if !has_hydration_log || !replica.config.compute.logging.enabled() {
625                    ReplicaTarget::Exempt
626                } else {
627                    ReplicaTarget::Ask
628                };
629                (replica.replica_id, target)
630            })
631            .collect();
632        let mut collections = Vec::new();
633        for id in self
634            .controller
635            .storage
636            .active_ingestion_exports(cluster.id)
637            .copied()
638            .filter(|id| !id.is_transient() && !exclude_collections.contains(id))
639        {
640            let (_, frontier) = self.controller.storage.collection_frontiers(id)?;
641            let hydrated = self.controller.storage.collection_hydrated(id)?;
642            collections.push((id, frontier, CollectionType::Storage { hydrated }));
643        }
644        let mut ignored_compute_collections = BTreeSet::new();
645        let mut compute_ids = Vec::new();
646        for id in self.controller.compute.collection_ids(cluster.id)? {
647            if exclude_collections.contains(&id) {
648                ignored_compute_collections.insert(id);
649            } else if !id.is_transient() {
650                let frontier = self
651                    .controller
652                    .compute
653                    .collection_frontiers(id, Some(cluster.id))?
654                    .write_frontier
655                    .to_owned();
656                collections.push((id, frontier, CollectionType::Compute));
657                compute_ids.push(id);
658            }
659        }
660        let compute_hydration = self
661            .controller
662            .compute
663            .collections_hydrated(cluster.id, compute_ids)?;
664        Ok(ClusterSnapshot {
665            replicas,
666            ignored_compute_collections,
667            collections,
668            compute_hydration,
669        })
670    }
671}
672
673impl LeaderSnapshot {
674    async fn read(
675        catalog: &Catalog,
676        storage_collections: &(dyn StorageCollections + Send + Sync),
677    ) -> Result<Self, anyhow::Error> {
678        fail::fail_point!("0dt_caught_up_read");
679        let replica_frontier_item_id =
680            catalog.resolve_builtin_storage_collection(&MZ_CLUSTER_REPLICA_FRONTIERS);
681        let replica_frontier_gid = catalog
682            .get_entry(&replica_frontier_item_id)
683            .latest_global_id();
684
685        // `snapshot_latest` requires that the collection consolidates to a
686        // set. `mz_cluster_replica_frontiers` is a controller-managed builtin
687        // written with ±1 diffs, so it satisfies that invariant.
688        //
689        // NOTE: these are the leader's frontiers only because we read the leader's shard.
690        // `validate_migration_steps` forbids migrating `mz_cluster_replica_frontiers` for this
691        // reason, so a declared migration can't reach here. A test forcing replacement across all
692        // builtins bypasses that guard, hands us a shard we write ourselves, and the lag check
693        // below then compares this deployment against itself.
694        let live_frontiers = storage_collections
695            .snapshot_latest(replica_frontier_gid)
696            .await
697            .context("cannot read mz_cluster_replica_frontiers")?;
698        let clock = storage_collections
699            .collection_frontiers(replica_frontier_gid)
700            .context("cannot read the upper of mz_cluster_replica_frontiers")?
701            .write_frontier
702            .into_option()
703            .context("mz_cluster_replica_frontiers has an empty upper")?;
704
705        let live_frontiers = live_frontiers
706            .into_iter()
707            .map(|row| {
708                let mut iter = row.into_iter();
709
710                let id: GlobalId = iter
711                    .next()
712                    .expect("missing object id")
713                    .unwrap_str()
714                    .parse()
715                    .expect("cannot parse id");
716                let replica_id = iter
717                    .next()
718                    .expect("missing replica id")
719                    .unwrap_str()
720                    .to_string();
721                let maybe_upper_ts = iter.next().expect("missing upper_ts");
722                // The timestamp has a total order, so there can be at
723                // most one entry in the upper frontier, which is this
724                // timestamp here. And NULL encodes the empty upper
725                // frontier.
726                let upper_frontier = if maybe_upper_ts.is_null() {
727                    Antichain::new()
728                } else {
729                    let upper_ts = maybe_upper_ts.unwrap_mz_timestamp();
730                    Antichain::from_elem(upper_ts)
731                };
732
733                (id, replica_id, upper_frontier)
734            })
735            .collect_vec();
736
737        let leader_hydration = {
738            let item_id = catalog.resolve_builtin_storage_collection(&MZ_COMPUTE_HYDRATION_TIMES);
739            let id = catalog.get_entry(&item_id).latest_global_id();
740            match storage_collections.snapshot_latest(id).await {
741                Ok(rows) => LeaderHydration::from_rows(rows),
742                Err(error) => {
743                    tracing::warn!(%error, "cannot read leader hydration; requiring local hydration");
744                    LeaderHydration::default()
745                }
746            }
747        };
748        let leader_unhydrated_collections =
749            leader_hydration.collections_unhydrated_on_all_hosting_replicas(&live_frontiers);
750
751        let live_collection_frontiers: BTreeMap<_, _> = live_frontiers
752            .into_iter()
753            .map(|(oid, _replica_id, upper_ts)| (oid, upper_ts))
754            .into_grouping_map()
755            .fold(
756                Antichain::from_elem(Timestamp::minimum()),
757                |mut acc, _key, upper| {
758                    acc.join_assign(&upper);
759                    acc
760                },
761            )
762            .into_iter()
763            .collect();
764
765        let problematic_replicas = if ENABLE_0DT_CAUGHT_UP_REPLICA_STATUS_CHECK
766            .get(catalog.system_config().dyncfgs())
767        {
768            Self::analyze_replica_looping(catalog, storage_collections, (catalog.config().now)())
769                .await?
770        } else {
771            BTreeSet::new()
772        };
773        Ok(Self {
774            frontiers: live_collection_frontiers,
775            clock,
776            hydration: leader_hydration,
777            unhydrated_collections: leader_unhydrated_collections,
778            problematic_replicas,
779        })
780    }
781}
782
783impl CaughtUpCheck {
784    async fn run(mut self, leader: LeaderSnapshot) -> CaughtUpSnapshot {
785        let LeaderSnapshot {
786            frontiers,
787            clock,
788            hydration,
789            unhydrated_collections,
790            problematic_replicas,
791        } = leader;
792        tracing::debug!(?frontiers, "checking re-hydration status");
793        let allowed_lag =
794            WITH_0DT_CAUGHT_UP_CHECK_ALLOWED_LAG.get(self.catalog.system_config().dyncfgs());
795        let allowed_lag: u64 = allowed_lag
796            .as_millis()
797            .try_into()
798            .expect("must fit into u64");
799
800        let cutoff = WITH_0DT_CAUGHT_UP_CHECK_CUTOFF.get(self.catalog.system_config().dyncfgs());
801        let cutoff: u64 = cutoff.as_millis().try_into().expect("must fit into u64");
802
803        let now = self.now;
804
805        let stability_check_enabled =
806            ENABLE_0DT_CAUGHT_UP_STABILITY_CHECK.get(self.catalog.system_config().dyncfgs());
807        let stability_period =
808            WITH_0DT_CAUGHT_UP_CHECK_STABILITY_PERIOD.get(self.catalog.system_config().dyncfgs());
809        // Cap rather than panic on an absurdly large configured duration. A
810        // period of u64::MAX milliseconds means "effectively never auto-ready",
811        // which is the safe, conservative outcome: we won't cut over on our own,
812        // and an operator can still force it via skip-catchup.
813        let stability_period_ms = u64::try_from(stability_period.as_millis()).unwrap_or(u64::MAX);
814
815        let classification = self
816            .classify_clusters(
817                allowed_lag.into(),
818                cutoff.into(),
819                now.into(),
820                clock,
821                &frontiers,
822                &unhydrated_collections,
823                &problematic_replicas,
824            )
825            .await;
826
827        let all_caught_up = classification
828            .values()
829            .all(|status| *status != ClusterCaughtUpStatus::NotCaughtUp);
830        let caught_up_clusters = if stability_check_enabled {
831            classification
832                .into_iter()
833                .filter_map(|(cluster_id, status)| match status {
834                    ClusterCaughtUpStatus::CaughtUp {
835                        ignored_compute_collections,
836                    } => Some((
837                        cluster_id,
838                        CaughtUpCluster {
839                            replicas: self.replica_targets(
840                                cluster_id,
841                                &hydration,
842                                &ignored_compute_collections,
843                            ),
844                            ignored_compute_collections,
845                        },
846                    )),
847                    _ => None,
848                })
849                .collect()
850        } else {
851            BTreeMap::new()
852        };
853
854        CaughtUpSnapshot {
855            now,
856            all_caught_up,
857            stability_check_enabled,
858            stability_period_ms,
859            caught_up_clusters,
860        }
861    }
862
863    /// Classifies the replicas of a cluster for the stability gate.
864    fn replica_targets(
865        &self,
866        cluster_id: ClusterId,
867        leader: &LeaderHydration,
868        ignored: &BTreeSet<GlobalId>,
869    ) -> BTreeMap<ReplicaId, ReplicaTarget> {
870        let cluster = self.clusters[&cluster_id]
871            .as_ref()
872            .expect("classified cluster");
873        cluster
874            .replicas
875            .iter()
876            .map(|(&id, &target)| {
877                let target = if target == ReplicaTarget::Ask
878                    && leader.replica_has_unhydrated_collection(id, ignored)
879                {
880                    ReplicaTarget::Exempt
881                } else {
882                    target
883                };
884                (id, target)
885            })
886            .collect()
887    }
888
889    /// Classifies every cluster for the caught-up check.
890    ///
891    /// Informally, a cluster is considered caught-up if it is at least as healthy as its
892    /// counterpart in the leader environment. To determine that, we use the following rules:
893    ///
894    ///  (1) A cluster is caught-up if all non-transient, non-excluded collections installed on it
895    ///      are either caught-up or ignored.
896    ///  (2) A collection is caught-up when it is (a) hydrated (waived for compute collections
897    ///      returned by [`LeaderHydration::collections_unhydrated_on_all_hosting_replicas`]),
898    ///      and (b) its write frontier is within
899    ///      `allowed_lag` of the "live" frontier, the collection's frontier reported by the leader
900    ///      environment. For a collection without one, `leader_clock` stands in (see
901    ///      `LeaderSnapshot::clock`).
902    ///  (3) A collection is ignored if its "live" frontier is behind `now` by more than `cutoff`.
903    ///      Such a collection is unhealthy in the leader environment, so we don't care about its
904    ///      health in the read-only environment either.
905    ///  (4) On a cluster that is crash-looping, all collections are ignored.
906    ///
907    /// A cluster that is caught-up only because it has no replicas, or because it is hopelessly
908    /// behind with only crash/OOM-looping replicas (rule 4), is reported as
909    /// [`ClusterCaughtUpStatus::Ignored`] rather than [`ClusterCaughtUpStatus::CaughtUp`]. The
910    /// caller does not health-gate ignored clusters, so we keep ignoring clusters that are already
911    /// unhealthy in the leader environment.
912    async fn classify_clusters(
913        &mut self,
914        allowed_lag: Timestamp,
915        cutoff: Timestamp,
916        now: Timestamp,
917        leader_clock: Timestamp,
918        live_frontiers: &BTreeMap<GlobalId, Antichain<Timestamp>>,
919        leader_unhydrated_collections: &BTreeSet<GlobalId>,
920        problematic_replicas: &BTreeSet<ReplicaId>,
921    ) -> BTreeMap<ClusterId, ClusterCaughtUpStatus> {
922        let mut result = BTreeMap::new();
923        for (&cluster_id, cluster) in &mut self.clusters {
924            let status = match cluster {
925                Ok(cluster) => {
926                    Self::collections_caught_up(
927                        cluster_id,
928                        cluster,
929                        allowed_lag.clone(),
930                        cutoff.clone(),
931                        now.clone(),
932                        leader_clock,
933                        live_frontiers,
934                        leader_unhydrated_collections,
935                        problematic_replicas,
936                    )
937                    .await
938                }
939                Err(error) => Err(anyhow::anyhow!("{error:#}")),
940            }
941            .unwrap_or_else(|e| {
942                tracing::error!(
943                    "unexpected error while checking if cluster {} caught up: {e:#}",
944                    cluster_id
945                );
946                ClusterCaughtUpStatus::NotCaughtUp
947            });
948
949            if status == ClusterCaughtUpStatus::NotCaughtUp {
950                // We log all non-caught-up clusters instead of breaking out early.
951                tracing::info!("cluster {} is not caught up", cluster_id);
952            }
953
954            result.insert(cluster_id, status);
955        }
956
957        result
958    }
959
960    /// Classifies the given cluster for the caught-up check.
961    ///
962    /// See [`Self::classify_clusters`] for details.
963    async fn collections_caught_up(
964        cluster_id: ClusterId,
965        cluster: &mut ClusterSnapshot,
966        allowed_lag: Timestamp,
967        cutoff: Timestamp,
968        now: Timestamp,
969        leader_clock: Timestamp,
970        live_frontiers: &BTreeMap<GlobalId, Antichain<Timestamp>>,
971        leader_unhydrated_collections: &BTreeSet<GlobalId>,
972        problematic_replicas: &BTreeSet<ReplicaId>,
973    ) -> Result<ClusterCaughtUpStatus, anyhow::Error> {
974        if cluster.replicas.is_empty() {
975            return Ok(ClusterCaughtUpStatus::Ignored);
976        }
977
978        // Check if all replicas in this cluster are crash/OOM-looping. As long
979        // as there is at least one healthy replica, the cluster is okay-ish.
980        let cluster_has_only_problematic_replicas = cluster
981            .replicas
982            .keys()
983            .all(|id| problematic_replicas.contains(id));
984        // A cluster whose collections all exceed the cutoff must not wait on
985        // its compute controller.
986        let mut hydration = None;
987        let mut all_caught_up = true;
988        let mut ignored_compute_collections = cluster.ignored_compute_collections.clone();
989
990        for (id, write_frontier, collection_type) in &cluster.collections {
991            let id = *id;
992            if let Some(live_write_frontier) = live_frontiers.get(&id) {
993                // We can't do comparisons and subtractions, so we bump up the live
994                // write frontier by the cutoff, and then compare that against
995                // `now`.
996                let live_write_frontier_plus_cutoff = live_write_frontier
997                    .iter()
998                    .map(|t| t.step_forward_by(&cutoff));
999                let live_write_frontier_plus_cutoff =
1000                    Antichain::from_iter(live_write_frontier_plus_cutoff);
1001
1002                let beyond_all_hope = live_write_frontier_plus_cutoff.less_equal(&now);
1003
1004                if beyond_all_hope && cluster_has_only_problematic_replicas {
1005                    tracing::info!(
1006                        ?live_write_frontier,
1007                        ?cutoff,
1008                        ?now,
1009                        "live write frontier of collection {id} is too far behind 'now'"
1010                    );
1011                    tracing::info!(
1012                        "ALL replicas of cluster {} are crash/OOM-looping and it has at least one \
1013                     collection that is too far behind 'now'; ignoring cluster for caught-up \
1014                     checks",
1015                        cluster_id
1016                    );
1017                    return Ok(ClusterCaughtUpStatus::Ignored);
1018                } else if beyond_all_hope {
1019                    tracing::info!(
1020                        ?live_write_frontier,
1021                        ?cutoff,
1022                        ?now,
1023                        "live write frontier of collection {id} is too far behind 'now'; \
1024                     ignoring for caught-up checks"
1025                    );
1026                    if matches!(collection_type, CollectionType::Compute) {
1027                        ignored_compute_collections.insert(id);
1028                    }
1029                    continue;
1030                }
1031            }
1032            let collection_hydrated = match collection_type {
1033                CollectionType::Compute => {
1034                    if hydration.is_none() {
1035                        hydration = Some((&mut cluster.compute_hydration).await?);
1036                    }
1037                    *hydration.as_ref().expect("hydration received")[&id]
1038                        .as_ref()
1039                        .map_err(|_| CollectionMissing(id))?
1040                }
1041                CollectionType::Storage { hydrated } => *hydrated,
1042            };
1043            let live_write_frontier = match live_frontiers.get(&id) {
1044                Some(frontier) => frontier,
1045                None => {
1046                    // No live frontier to compare against, either because the collection didn't
1047                    // exist on the leader or because the leader hosts it as something
1048                    // `mz_cluster_replica_frontiers` doesn't track. A table→MV conversion is the
1049                    // latter: it keeps the table's `GlobalId`, still a table on the leader, so the
1050                    // new MV lands here instead of the strong path below.
1051                    //
1052                    // Require hydration, not just a write frontier past the minimum. A fresh MV's
1053                    // sink reaches frontier 1 after one batch, which would otherwise look caught
1054                    // up mid-hydration and bring back the cut-over spike this gate prevents.
1055                    // Also require the frontier to be within the allowed lag, the bound the
1056                    // live-frontier path applies, with `leader_clock` standing in for the missing
1057                    // live frontier. Hydration is one-shot: a collection that hydrated and then
1058                    // stalled would otherwise satisfy this branch forever. We don't compare
1059                    // against `now`: a collection fed by inputs that only the leader advances,
1060                    // such as the catalog shard, would then lag forever while the leader is down.
1061                    //
1062                    // NOTE: there is deliberately no `cutoff` escape hatch here. A frontier frozen
1063                    // at the minimum is exactly what this gate must catch, so a collection stuck
1064                    // here blocks promotion until `with_0dt_deployment_max_wait` elapses.
1065                    let readiness = CollectionReadiness::classify(
1066                        collection_hydrated,
1067                        write_frontier,
1068                        Some((&Antichain::from_elem(leader_clock), allowed_lag)),
1069                    );
1070
1071                    tracing::info!(
1072                        ?write_frontier,
1073                        ?readiness,
1074                        ?allowed_lag,
1075                        ?leader_clock,
1076                        "collection {id} not in live frontiers"
1077                    );
1078                    if write_frontier.less_equal(&Timestamp::minimum())
1079                        || readiness != CollectionReadiness::Ready
1080                    {
1081                        all_caught_up = false;
1082                    }
1083                    continue;
1084                }
1085            };
1086
1087            let unhydrated_on_leader = matches!(collection_type, CollectionType::Compute)
1088                && leader_unhydrated_collections.contains(&id);
1089            let readiness = CollectionReadiness::classify(
1090                collection_hydrated || unhydrated_on_leader,
1091                write_frontier,
1092                Some((live_write_frontier, allowed_lag)),
1093            );
1094
1095            // We don't expect collections to get hydrated, ingestions to be
1096            // started, etc. when they are already at the empty write frontier.
1097            if live_write_frontier.is_empty() || readiness == CollectionReadiness::Ready {
1098                // Carry hydration waivers into the per-replica stability check.
1099                if (readiness != CollectionReadiness::Ready || !collection_hydrated)
1100                    && matches!(collection_type, CollectionType::Compute)
1101                {
1102                    ignored_compute_collections.insert(id);
1103                }
1104                // This is a bit spammy, but log caught-up collections while we
1105                // investigate why environments are cutting over but then a lot
1106                // of compute collections are _not_ in fact hydrated on
1107                // clusters.
1108                tracing::debug!(
1109                    %id,
1110                    ?readiness,
1111                    ?write_frontier,
1112                    ?live_write_frontier,
1113                    ?allowed_lag,
1114                    %cluster_id,
1115                    "collection is caught up");
1116            } else {
1117                // We are not within the allowed lag, or not hydrated!
1118                //
1119                // We continue with our loop instead of breaking out early, so
1120                // that we log all non-caught-up replicas.
1121                tracing::info!(
1122                    %id,
1123                    ?readiness,
1124                    ?write_frontier,
1125                    ?live_write_frontier,
1126                    ?allowed_lag,
1127                    %cluster_id,
1128                    "collection is not caught up"
1129                );
1130                all_caught_up = false;
1131            }
1132        }
1133
1134        Ok(if all_caught_up {
1135            ClusterCaughtUpStatus::CaughtUp {
1136                ignored_compute_collections,
1137            }
1138        } else {
1139            ClusterCaughtUpStatus::NotCaughtUp
1140        })
1141    }
1142}
1143
1144impl LeaderSnapshot {
1145    /// Analyzes replica status history to detect replicas that are
1146    /// crash-looping or OOM-looping.
1147    ///
1148    /// A replica is considered problematic if it has multiple OOM kills in a
1149    /// short-ish window.
1150    async fn analyze_replica_looping(
1151        catalog: &Catalog,
1152        storage_collections: &(dyn StorageCollections + Send + Sync),
1153        now: EpochMillis,
1154    ) -> Result<BTreeSet<ReplicaId>, anyhow::Error> {
1155        // Look back 1 day for patterns.
1156        let lookback_window: u64 = Duration::from_secs(24 * 60 * 60)
1157            .as_millis()
1158            .try_into()
1159            .expect("fits into u64");
1160        let min_timestamp = now.saturating_sub(lookback_window);
1161        let min_timestamp_dt = mz_ore::now::to_datetime(min_timestamp);
1162
1163        // Get the replica status collection GlobalId
1164        let replica_status_item_id =
1165            catalog.resolve_builtin_storage_collection(&MZ_CLUSTER_REPLICA_STATUS_HISTORY);
1166        let replica_status_gid = catalog
1167            .get_entry(&replica_status_item_id)
1168            .latest_global_id();
1169
1170        // Acquire a read hold to determine the as_of timestamp for snapshot_and_stream
1171        let read_holds = storage_collections
1172            .acquire_read_holds(vec![replica_status_gid])
1173            .context("cannot acquire read hold for mz_cluster_replica_status_history")?;
1174        let read_hold = if let Some(read_hold) = read_holds.into_iter().next() {
1175            read_hold
1176        } else {
1177            anyhow::bail!("mz_cluster_replica_status_history is not readable");
1178        };
1179
1180        let as_of = read_hold
1181            .since()
1182            .iter()
1183            .next()
1184            .cloned()
1185            .context("mz_cluster_replica_status_history is closed")?;
1186
1187        let mut replica_statuses_stream = storage_collections
1188            .snapshot_and_stream(replica_status_gid, as_of)
1189            .await
1190            .context("cannot read mz_cluster_replica_status_history")?;
1191
1192        let mut replica_problem_counts: BTreeMap<ReplicaId, u32> = BTreeMap::new();
1193
1194        while let Some((source_data, _ts, diff)) = replica_statuses_stream.next().await {
1195            // Only process inserts (positive diffs)
1196            if diff <= 0 {
1197                continue;
1198            }
1199
1200            // Extract the Row from SourceData
1201            let row = match source_data.0 {
1202                Ok(row) => row,
1203                Err(err) => {
1204                    // This builtin collection shouldn't have errors, so we at
1205                    // least log an error so that tests or sentry will notice.
1206                    tracing::error!(
1207                        collection = MZ_CLUSTER_REPLICA_STATUS_HISTORY.name,
1208                        ?err,
1209                        "unexpected error in builtin collection"
1210                    );
1211                    continue;
1212                }
1213            };
1214
1215            let mut iter = row.into_iter();
1216
1217            let replica_id: ReplicaId = iter
1218                .next()
1219                .expect("missing replica_id")
1220                .unwrap_str()
1221                .parse()
1222                .expect("must parse as replica ID");
1223            let _process_id = iter.next().expect("missing process_id").unwrap_uint64();
1224            let status = iter
1225                .next()
1226                .expect("missing status")
1227                .unwrap_str()
1228                .to_string();
1229            let reason_datum = iter.next().expect("missing reason");
1230            let reason = if reason_datum.is_null() {
1231                None
1232            } else {
1233                Some(reason_datum.unwrap_str().to_string())
1234            };
1235            let occurred_at = iter
1236                .next()
1237                .expect("missing occurred_at")
1238                .unwrap_timestamptz();
1239
1240            // Only consider events within the time window and that are problematic
1241            if occurred_at.naive_utc() >= min_timestamp_dt.naive_utc() {
1242                if Self::is_problematic_status(&status, reason.as_deref()) {
1243                    *replica_problem_counts.entry(replica_id).or_insert(0) += 1;
1244                }
1245            }
1246        }
1247
1248        // Filter to replicas with 3 or more problematic events.
1249        let result = replica_problem_counts
1250            .into_iter()
1251            .filter_map(|(replica_id, count)| {
1252                if count >= 3 {
1253                    tracing::info!(
1254                        "Detected problematic cluster replica {}: {} problematic events in last {:?}",
1255                        replica_id,
1256                        count,
1257                        Duration::from_millis(lookback_window)
1258                    );
1259                    Some(replica_id)
1260                } else {
1261                    None
1262                }
1263            })
1264            .collect();
1265
1266        // Explicitly keep the read hold alive until this point.
1267        drop(read_hold);
1268
1269        Ok(result)
1270    }
1271
1272    /// Determines if a replica status indicates a problematic state that could
1273    /// indicate looping.
1274    fn is_problematic_status(_status: &str, reason: Option<&str>) -> bool {
1275        // For now, we only look at the reason, but we could change/expand this
1276        // if/when needed.
1277        if let Some(reason) = reason {
1278            return reason == OfflineReason::OomKilled.to_string();
1279        }
1280
1281        false
1282    }
1283}
1284
1285/// The leader's hydration reports, read from its `mz_compute_hydration_times`.
1286#[derive(Debug, Default)]
1287struct LeaderHydration {
1288    hydrated_on_any_replica: BTreeSet<GlobalId>,
1289    /// (Collection ID, replica ID) pairs explicitly reported as unhydrated.
1290    unhydrated_replica_collections: BTreeSet<(GlobalId, String)>,
1291}
1292
1293impl LeaderHydration {
1294    fn from_rows(rows: Vec<Row>) -> Self {
1295        let mut leader = Self::default();
1296        for row in rows {
1297            let mut values = row.iter();
1298            let replica = values
1299                .next()
1300                .expect("missing replica_id")
1301                .unwrap_str()
1302                .to_owned();
1303            let id: GlobalId = values
1304                .next()
1305                .expect("missing object_id")
1306                .unwrap_str()
1307                .parse()
1308                .expect("valid object ID");
1309            if values.next().expect("missing time_ns").is_null() {
1310                leader.unhydrated_replica_collections.insert((id, replica));
1311            } else {
1312                leader.hydrated_on_any_replica.insert(id);
1313            }
1314        }
1315        leader
1316    }
1317
1318    /// Returns the collections that every frontier-hosting leader replica
1319    /// explicitly reports unhydrated.
1320    ///
1321    /// Missing reports or frontiers grant no waiver. A hydrated report from any
1322    /// replica vetoes the waiver, even if that replica has no frontier report.
1323    fn collections_unhydrated_on_all_hosting_replicas(
1324        &self,
1325        frontiers: &[(GlobalId, String, Antichain<Timestamp>)],
1326    ) -> BTreeSet<GlobalId> {
1327        let mut collections = BTreeMap::new();
1328        for (id, replica, _) in frontiers {
1329            let all_unhydrated = collections.entry(*id).or_insert(true);
1330            *all_unhydrated &= !self.hydrated_on_any_replica.contains(id)
1331                && self
1332                    .unhydrated_replica_collections
1333                    .contains(&(*id, replica.clone()));
1334        }
1335        collections
1336            .into_iter()
1337            .filter_map(|(id, unhydrated)| unhydrated.then_some(id))
1338            .collect()
1339    }
1340
1341    /// Returns whether leader replica `replica_id` explicitly reports at least
1342    /// one collection outside `ignored` as unhydrated.
1343    ///
1344    /// The leader snapshot has per-collection reports, not a separate replica
1345    /// hydration signal. The gate uses these as a proxy: a replica is fully
1346    /// hydrated only when all its non-ignored collections are hydrated. One
1347    /// unhydrated collection therefore waives the incoming replica's stability
1348    /// wait, since the leader lacks a fully hydrated counterpart. Missing
1349    /// reports grant no exemption.
1350    fn replica_has_unhydrated_collection(
1351        &self,
1352        replica_id: ReplicaId,
1353        ignored: &BTreeSet<GlobalId>,
1354    ) -> bool {
1355        let replica_id = replica_id.to_string();
1356        self.unhydrated_replica_collections
1357            .iter()
1358            .any(|(id, replica)| *replica == replica_id && !ignored.contains(id))
1359    }
1360}
1361
1362#[cfg(test)]
1363mod tests {
1364    use mz_repr::Datum;
1365    use mz_repr::adt::timestamp::CheckedTimestamp;
1366
1367    use super::*;
1368
1369    use ReplicaHealth::{Exempt, HealthySince, NotHydrated, NotOnline};
1370
1371    #[mz_ore::test(tokio::test)]
1372    async fn classification_waits_for_hydration_and_rejects_lost_responses() {
1373        use futures::poll;
1374        use std::task::Poll;
1375
1376        for response in [
1377            Some(Ok(true)),
1378            Some(Err(CollectionMissing(GlobalId::User(1)))),
1379            None,
1380        ] {
1381            let id = GlobalId::User(1);
1382            let (tx, rx) = oneshot::channel();
1383            let mut cluster = ClusterSnapshot {
1384                replicas: BTreeMap::from([(ReplicaId::User(1), ReplicaTarget::Ask)]),
1385                ignored_compute_collections: BTreeSet::new(),
1386                collections: vec![(
1387                    id,
1388                    Antichain::from_elem(100.into()),
1389                    CollectionType::Compute,
1390                )],
1391                compute_hydration: rx,
1392            };
1393            let frontiers = BTreeMap::from([(id, Antichain::from_elem(100.into()))]);
1394            let empty = BTreeSet::new();
1395            let problematic = BTreeSet::new();
1396            let check = CaughtUpCheck::collections_caught_up(
1397                ClusterId::User(1),
1398                &mut cluster,
1399                0.into(),
1400                1000.into(),
1401                100.into(),
1402                100.into(),
1403                &frontiers,
1404                &empty,
1405                &problematic,
1406            );
1407            tokio::pin!(check);
1408            assert!(matches!(poll!(&mut check), Poll::Pending));
1409            let success = matches!(response, Some(Ok(true)));
1410            match response {
1411                Some(response) => tx
1412                    .send(BTreeMap::from([(id, response)]))
1413                    .expect("classification still holds the receiver"),
1414                None => drop(tx),
1415            }
1416            let result = check.await;
1417            if success {
1418                assert_eq!(
1419                    result.expect("hydration reply succeeds"),
1420                    ClusterCaughtUpStatus::CaughtUp {
1421                        ignored_compute_collections: BTreeSet::new(),
1422                    }
1423                );
1424            } else {
1425                assert!(
1426                    result.is_err(),
1427                    "missing hydration evidence must not authorize promotion"
1428                );
1429            }
1430        }
1431    }
1432
1433    #[mz_ore::test(tokio::test)]
1434    async fn cutoff_exemptions_do_not_wait_for_hydration() {
1435        use futures::FutureExt;
1436
1437        let id = GlobalId::User(1);
1438        let replica = ReplicaId::User(1);
1439        for problematic in [BTreeSet::new(), BTreeSet::from([replica])] {
1440            let (_tx, rx) = oneshot::channel();
1441            let mut cluster = ClusterSnapshot {
1442                replicas: BTreeMap::from([(replica, ReplicaTarget::Ask)]),
1443                ignored_compute_collections: BTreeSet::new(),
1444                collections: vec![(id, Antichain::from_elem(0.into()), CollectionType::Compute)],
1445                compute_hydration: rx,
1446            };
1447            let status = CaughtUpCheck::collections_caught_up(
1448                ClusterId::User(1),
1449                &mut cluster,
1450                0.into(),
1451                100.into(),
1452                100.into(),
1453                100.into(),
1454                &BTreeMap::from([(id, Antichain::from_elem(0.into()))]),
1455                &BTreeSet::new(),
1456                &problematic,
1457            )
1458            .now_or_never()
1459            .expect("ignored collections must not wait for hydration")
1460            .expect("ignored collections need no hydration evidence");
1461            let expected = if problematic.is_empty() {
1462                ClusterCaughtUpStatus::CaughtUp {
1463                    ignored_compute_collections: BTreeSet::from([id]),
1464                }
1465            } else {
1466                ClusterCaughtUpStatus::Ignored
1467            };
1468            assert_eq!(status, expected);
1469        }
1470    }
1471
1472    #[mz_ore::test(tokio::test)]
1473    async fn collection_without_live_frontier_is_compared_against_the_leader() {
1474        use futures::FutureExt;
1475
1476        // The leader's clock stopped at 1_000, long before `now`, as when it is down.
1477        let leader_clock = Timestamp::from(1_000);
1478        let now = Timestamp::from(1_000_000);
1479
1480        for (write_frontier, caught_up) in [(950, true), (500, false)] {
1481            let (_tx, rx) = oneshot::channel();
1482            let mut cluster = ClusterSnapshot {
1483                replicas: BTreeMap::from([(ReplicaId::System(1), ReplicaTarget::Ask)]),
1484                ignored_compute_collections: BTreeSet::new(),
1485                collections: vec![(
1486                    GlobalId::System(1),
1487                    Antichain::from_elem(write_frontier.into()),
1488                    CollectionType::Storage { hydrated: true },
1489                )],
1490                compute_hydration: rx,
1491            };
1492            let status = CaughtUpCheck::collections_caught_up(
1493                ClusterId::System(1),
1494                &mut cluster,
1495                100.into(),
1496                now,
1497                now,
1498                leader_clock,
1499                &BTreeMap::new(),
1500                &BTreeSet::new(),
1501                &BTreeSet::new(),
1502            )
1503            .now_or_never()
1504            .expect("storage collections need no hydration reply")
1505            .expect("classification succeeds");
1506            assert_eq!(
1507                matches!(status, ClusterCaughtUpStatus::CaughtUp { .. }),
1508                caught_up,
1509                "write frontier {write_frontier} against the leader's 1_000 with lag 100"
1510            );
1511        }
1512    }
1513
1514    #[mz_ore::test]
1515    fn collection_hydration_waiver_requires_complete_leader_reports() {
1516        let frontier = |id, replica: &str| {
1517            (
1518                GlobalId::User(id),
1519                replica.to_owned(),
1520                Antichain::from_elem(Timestamp::from(100)),
1521            )
1522        };
1523        let row = |id: &str, replica: &str, time| {
1524            Row::pack_slice(&[Datum::String(replica), Datum::String(id), time])
1525        };
1526        let frontiers = vec![
1527            frontier(1, "u10"),
1528            frontier(1, "u11"),
1529            frontier(2, "u10"),
1530            frontier(2, "u11"),
1531            frontier(3, "u10"),
1532            frontier(3, "u11"),
1533            frontier(4, "u10"),
1534            frontier(5, "u10"),
1535        ];
1536        let rows = vec![
1537            row("u1", "u10", Datum::Null),
1538            row("u1", "u11", Datum::Null),
1539            row("u2", "u10", Datum::Null),
1540            row("u2", "u11", Datum::UInt64(7)),
1541            row("u3", "u10", Datum::Null), // u11 has not reported.
1542            row("u4", "u10", Datum::Null),
1543            row("u4", "u12", Datum::UInt64(9)),
1544            // u5 has no hydration reports. u6 has no frontier.
1545            row("u6", "u10", Datum::Null),
1546        ];
1547        assert_eq!(
1548            LeaderHydration::from_rows(rows)
1549                .collections_unhydrated_on_all_hosting_replicas(&frontiers),
1550            BTreeSet::from([GlobalId::User(1)])
1551        );
1552        assert!(
1553            LeaderHydration::default()
1554                .collections_unhydrated_on_all_hosting_replicas(&frontiers)
1555                .is_empty()
1556        );
1557    }
1558
1559    #[mz_ore::test]
1560    fn replica_hydration_exemption_requires_an_unhydrated_collection_report() {
1561        let row = |id: &str, replica: &str, time| {
1562            Row::pack_slice(&[Datum::String(replica), Datum::String(id), time])
1563        };
1564        let leader = LeaderHydration::from_rows(vec![
1565            row("u1", "u10", Datum::UInt64(7)),
1566            row("u2", "u10", Datum::UInt64(7)),
1567            row("u1", "u11", Datum::UInt64(7)),
1568            row("u2", "u11", Datum::Null),
1569            row("u3", "u12", Datum::Null),
1570        ]);
1571        let none = BTreeSet::new();
1572        let replica = ReplicaId::User;
1573        assert!(
1574            !leader.replica_has_unhydrated_collection(replica(10), &none),
1575            "fully hydrated"
1576        );
1577        assert!(leader.replica_has_unhydrated_collection(replica(11), &none));
1578        assert!(
1579            !leader.replica_has_unhydrated_collection(
1580                replica(12),
1581                &BTreeSet::from([GlobalId::User(3)])
1582            ),
1583            "unhydrated only for an ignored collection"
1584        );
1585        assert!(
1586            !leader.replica_has_unhydrated_collection(replica(13), &none),
1587            "no reports"
1588        );
1589    }
1590
1591    #[mz_ore::test]
1592    fn stable_since_latest_replica() {
1593        let period_ms = 1000;
1594        let replicas = [
1595            (HealthySince(100), None),
1596            (HealthySince(500), None),
1597            (Exempt, None),
1598        ];
1599        let observation = observe_stability(&replicas, 1499, period_ms);
1600        assert_eq!(observation.stable_for_ms, Some(999));
1601        assert_eq!(observation.blocked_by, Some(StabilityBlocker::WithinPeriod));
1602        assert_eq!(
1603            observe_stability(&replicas, 1500, period_ms).blocked_by,
1604            None
1605        );
1606    }
1607
1608    #[mz_ore::test]
1609    fn every_replica_needs_evidence() {
1610        // `NotOnline` wins, because it is the more fundamental problem.
1611        for (replicas, blocker) in [
1612            (vec![], StabilityBlocker::NotOnline),
1613            (
1614                vec![HealthySince(0), NotOnline],
1615                StabilityBlocker::NotOnline,
1616            ),
1617            (vec![NotHydrated, NotOnline], StabilityBlocker::NotOnline),
1618            (
1619                vec![HealthySince(0), NotHydrated],
1620                StabilityBlocker::NotHydrated,
1621            ),
1622            (vec![Exempt, NotHydrated], StabilityBlocker::NotHydrated),
1623        ] {
1624            // Even a zero period requires evidence from every replica.
1625            let evidence = replicas.iter().map(|health| (*health, None)).collect_vec();
1626            let observation = observe_stability(&evidence, 10_000, 0);
1627            assert_eq!(observation.blocked_by, Some(blocker), "{replicas:?}");
1628            assert_eq!(observation.stable_for_ms, None, "{replicas:?}");
1629        }
1630    }
1631
1632    #[mz_ore::test]
1633    fn replica_clock_ahead_is_clamped() {
1634        let observation = observe_stability(&[(HealthySince(2000), None)], 1000, 0);
1635        assert_eq!(observation.stable_for_ms, Some(0));
1636        assert_eq!(observation.blocked_by, None);
1637    }
1638
1639    #[mz_ore::test]
1640    fn young_replica_has_a_fixed_deadline_until_it_rehydrates() {
1641        let evidence = [(HealthySince(1010), Some(1000))];
1642        assert_eq!(
1643            observe_stability(&evidence, 1019, 1000).blocked_by,
1644            Some(StabilityBlocker::WithinPeriod)
1645        );
1646        assert_eq!(observe_stability(&evidence, 1020, 1000).blocked_by, None);
1647
1648        let restarted = [(HealthySince(1030), Some(1000))];
1649        assert_eq!(
1650            observe_stability(&restarted, 1059, 1000).blocked_by,
1651            Some(StabilityBlocker::WithinPeriod)
1652        );
1653        assert_eq!(observe_stability(&restarted, 1060, 1000).blocked_by, None);
1654    }
1655
1656    #[mz_ore::test]
1657    fn age_cap_does_not_waive_other_replicas_or_missing_health() {
1658        let young = (HealthySince(1010), Some(1000));
1659        for other in [
1660            (HealthySince(1000), Some(0)),
1661            (HealthySince(1000), None),
1662            (HealthySince(1000), Some(1001)),
1663        ] {
1664            let replicas = [young, other];
1665            assert_eq!(
1666                observe_stability(&replicas, 1999, 1000).blocked_by,
1667                Some(StabilityBlocker::WithinPeriod)
1668            );
1669            assert_eq!(observe_stability(&replicas, 2000, 1000).blocked_by, None);
1670        }
1671        assert_eq!(
1672            observe_stability(&[young, (NotOnline, Some(1000))], 2000, 1000).blocked_by,
1673            Some(StabilityBlocker::NotOnline)
1674        );
1675        assert_eq!(
1676            observe_stability(&[young, (NotHydrated, Some(1000))], 2000, 1000).blocked_by,
1677            Some(StabilityBlocker::NotHydrated)
1678        );
1679        assert_eq!(
1680            observe_stability(&[(HealthySince(3000), Some(3001))], 2000, 1000).blocked_by,
1681            Some(StabilityBlocker::WithinPeriod)
1682        );
1683    }
1684
1685    #[mz_ore::test]
1686    fn hydration_answer_fails_closed() {
1687        assert_eq!(
1688            replica_health(&answer(false, Some(1000))),
1689            HealthySince(1000)
1690        );
1691        assert_eq!(
1692            replica_health(&answer(false, Some(-1))),
1693            NotHydrated,
1694            "pre-epoch time"
1695        );
1696        assert_eq!(
1697            replica_health(&answer(false, None)),
1698            NotHydrated,
1699            "an export is not hydrated on some worker"
1700        );
1701        assert_eq!(replica_health(&[]), NotHydrated, "nothing reported yet");
1702    }
1703
1704    #[mz_ore::test]
1705    fn replica_with_only_ignored_exports_is_exempt() {
1706        assert_eq!(replica_health(&answer(true, Some(1000))), Exempt);
1707        assert_eq!(replica_health(&answer(true, None)), Exempt);
1708    }
1709
1710    fn answer(ignored: bool, hydrated_at: Option<i64>) -> Vec<Row> {
1711        let hydrated_at = hydrated_at.map_or(Datum::Null, |millis| {
1712            let time = chrono::DateTime::from_timestamp_millis(millis).expect("valid time");
1713            Datum::TimestampTz(CheckedTimestamp::from_timestamplike(time).expect("in range"))
1714        });
1715        vec![Row::pack_slice(&[Datum::from(ignored), hydrated_at])]
1716    }
1717}