1use 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
88const STABILITY_QUERY_TIMEOUT: Duration = Duration::from_secs(5);
93
94fn 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#[derive(Debug)]
122pub struct CaughtUpCheckContext {
123 pub trigger: Trigger,
126 pub exclude_collections: BTreeSet<GlobalId>,
129}
130
131#[derive(Debug)]
133pub struct CaughtUpCheckRequest {
134 exclude_collections: Arc<BTreeSet<GlobalId>>,
135 tx: oneshot::Sender<CaughtUpCheck>,
136}
137
138#[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 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#[derive(Debug)]
179struct CaughtUpSnapshot {
180 now: EpochMillis,
181 all_caught_up: bool,
183 stability_check_enabled: bool,
184 stability_period_ms: u64,
185 caught_up_clusters: BTreeMap<ClusterId, CaughtUpCluster>,
187}
188
189#[derive(Debug)]
191struct CaughtUpCluster {
192 ignored_compute_collections: BTreeSet<GlobalId>,
195 replicas: BTreeMap<ReplicaId, ReplicaTarget>,
196}
197
198#[derive(Debug, Clone, Copy, PartialEq, Eq)]
201enum ReplicaTarget {
202 NotOnline,
204 Exempt,
206 Ask,
208}
209
210#[derive(Debug, Clone, PartialEq, Eq)]
212enum ClusterCaughtUpStatus {
213 CaughtUp {
216 ignored_compute_collections: BTreeSet<GlobalId>,
219 },
220 Ignored,
225 NotCaughtUp,
227}
228
229#[derive(Debug, Clone, Copy, PartialEq, Eq)]
231enum ReplicaHealth {
232 NotOnline,
234 NotHydrated,
237 HealthySince(EpochMillis),
239 Exempt,
241}
242
243#[derive(Debug, Clone, Copy, PartialEq, Eq)]
246enum StabilityBlocker {
247 NotOnline,
249 NotHydrated,
251 WithinPeriod,
253}
254
255#[derive(Debug, Clone, Copy)]
257struct StabilityObservation {
258 stable_for_ms: Option<u64>,
261 blocked_by: Option<StabilityBlocker>,
263}
264
265fn 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 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
315struct StabilityGate {
318 client: PeekClient,
319 replica_created_at: BTreeMap<ReplicaId, EpochMillis>,
320}
321
322impl StabilityGate {
323 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 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 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 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
477fn replica_health(rows: &[Row]) -> ReplicaHealth {
479 let Some(row) = rows.first() else {
480 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 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 u64::try_from(millis).map_or(ReplicaHealth::NotHydrated, ReplicaHealth::HealthySince)
498}
499
500impl Coordinator {
501 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 if let Some(delay) = delay {
531 tokio::time::sleep(delay).await;
532 }
533 delay = Some(period);
534 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 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 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 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 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 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 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 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 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 tracing::info!("cluster {} is not caught up", cluster_id);
952 }
953
954 result.insert(cluster_id, status);
955 }
956
957 result
958 }
959
960 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 let cluster_has_only_problematic_replicas = cluster
981 .replicas
982 .keys()
983 .all(|id| problematic_replicas.contains(id));
984 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 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 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 if live_write_frontier.is_empty() || readiness == CollectionReadiness::Ready {
1098 if (readiness != CollectionReadiness::Ready || !collection_hydrated)
1100 && matches!(collection_type, CollectionType::Compute)
1101 {
1102 ignored_compute_collections.insert(id);
1103 }
1104 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 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 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 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 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 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 if diff <= 0 {
1197 continue;
1198 }
1199
1200 let row = match source_data.0 {
1202 Ok(row) => row,
1203 Err(err) => {
1204 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 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 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 drop(read_hold);
1268
1269 Ok(result)
1270 }
1271
1272 fn is_problematic_status(_status: &str, reason: Option<&str>) -> bool {
1275 if let Some(reason) = reason {
1278 return reason == OfflineReason::OomKilled.to_string();
1279 }
1280
1281 false
1282 }
1283}
1284
1285#[derive(Debug, Default)]
1287struct LeaderHydration {
1288 hydrated_on_any_replica: BTreeSet<GlobalId>,
1289 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 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 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 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), row("u4", "u10", Datum::Null),
1543 row("u4", "u12", Datum::UInt64(9)),
1544 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 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 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}