1use std::collections::{BTreeMap, BTreeSet};
13use std::fmt::Debug;
14use std::sync::{Arc, Mutex};
15use std::time::{Duration, Instant};
16
17use chrono::{DateTime, DurationRound, TimeDelta, Utc};
18use differential_dataflow::lattice::Lattice;
19use mz_build_info::BuildInfo;
20use mz_cluster_client::WallclockLagFn;
21use mz_compute_types::dataflows::{BuildDesc, DataflowDescription, LirDataflowDescription};
22use mz_compute_types::plan::render_plan::RenderPlan;
23use mz_compute_types::sinks::{
24 ComputeSinkConnection, ComputeSinkDesc, MaterializedViewSinkConnection,
25};
26use mz_compute_types::sources::SourceInstanceDesc;
27use mz_controller_types::dyncfgs::{
28 ENABLE_PAUSED_CLUSTER_READHOLD_DOWNGRADE, WALLCLOCK_LAG_RECORDING_INTERVAL,
29};
30use mz_dyncfg::{ConfigSet, ConfigUpdates};
31use mz_expr::RowSetFinishing;
32use mz_ore::cast::CastFrom;
33use mz_ore::channel::instrumented_unbounded_channel;
34use mz_ore::now::NowFn;
35use mz_ore::tracing::OpenTelemetryContext;
36use mz_ore::{soft_assert_or_log, soft_panic_or_log};
37use mz_persist_types::PersistLocation;
38use mz_repr::adt::timestamp::CheckedTimestamp;
39use mz_repr::refresh_schedule::RefreshSchedule;
40use mz_repr::{Datum, Diff, GlobalId, RelationDesc, Row, Timestamp};
41use mz_storage_client::controller::{IntrospectionType, WallclockLag, WallclockLagHistogramPeriod};
42use mz_storage_types::read_holds::{self, ReadHold};
43use mz_storage_types::read_policy::ReadPolicy;
44use thiserror::Error;
45use timely::PartialOrder;
46use timely::progress::frontier::MutableAntichain;
47use timely::progress::{Antichain, ChangeBatch};
48use tokio::sync::{mpsc, oneshot};
49use uuid::Uuid;
50
51use crate::controller::error::{
52 CollectionMissing, ERROR_TARGET_REPLICA_FAILED, HydrationCheckBadTarget,
53};
54use crate::controller::instance_client::PeekError;
55use crate::controller::peek_lifecycle::PeekLifecycle;
56use crate::controller::replica::{ReplicaClient, ReplicaConfig};
57use crate::controller::{
58 CollectionReadiness, ComputeControllerResponse, IntrospectionUpdates, PeekNotification,
59 ReplicaId, StorageCollections,
60};
61use crate::logging::LogVariant;
62use crate::metrics::IntCounter;
63use crate::metrics::{InstanceMetrics, ReplicaCollectionMetrics, ReplicaMetrics, UIntGauge};
64use crate::protocol::command::{
65 ComputeCommand, ComputeParameters, InstanceConfig, Peek, PeekTarget,
66};
67use crate::protocol::history::ComputeCommandHistory;
68use crate::protocol::response::{
69 ComputeResponse, CopyToResponse, FrontiersResponse, PeekError as ProtocolPeekError,
70 PeekResponse, StatusResponse, SubscribeBatch, SubscribeResponse,
71};
72
73#[derive(Error, Debug)]
74#[error("replica exists already: {0}")]
75pub(super) struct ReplicaExists(pub ReplicaId);
76
77#[derive(Error, Debug)]
78#[error("replica does not exist: {0}")]
79pub(super) struct ReplicaMissing(pub ReplicaId);
80
81#[derive(Error, Debug)]
82pub(super) enum DataflowCreationError {
83 #[error("collection does not exist: {0}")]
84 CollectionMissing(GlobalId),
85 #[error("replica does not exist: {0}")]
86 ReplicaMissing(ReplicaId),
87 #[error("dataflow definition lacks an as_of value")]
88 MissingAsOf,
89 #[error("subscribe dataflow has an empty as_of")]
90 EmptyAsOfForSubscribe,
91 #[error("copy to dataflow has an empty as_of")]
92 EmptyAsOfForCopyTo,
93 #[error("no read hold provided for dataflow import: {0}")]
94 ReadHoldMissing(GlobalId),
95 #[error("insufficient read hold provided for dataflow import: {0}")]
96 ReadHoldInsufficient(GlobalId),
97}
98
99impl From<CollectionMissing> for DataflowCreationError {
100 fn from(error: CollectionMissing) -> Self {
101 Self::CollectionMissing(error.0)
102 }
103}
104
105#[derive(Error, Debug)]
106pub(super) enum ReadPolicyError {
107 #[error("collection does not exist: {0}")]
108 CollectionMissing(GlobalId),
109 #[error("collection is write-only: {0}")]
110 WriteOnlyCollection(GlobalId),
111}
112
113impl From<CollectionMissing> for ReadPolicyError {
114 fn from(error: CollectionMissing) -> Self {
115 Self::CollectionMissing(error.0)
116 }
117}
118
119pub(super) type Command = Box<dyn FnOnce(&mut Instance) + Send>;
121
122pub(super) type ReplicaResponse = (ReplicaId, u64, ComputeResponse);
125
126pub(super) struct Instance {
128 build_info: &'static BuildInfo,
130 storage_collections: StorageCollections,
132 initialized: bool,
134 read_only: bool,
139 workload_class: Option<String>,
143 replicas: BTreeMap<ReplicaId, ReplicaState>,
145 collections: BTreeMap<GlobalId, CollectionState>,
153 log_sources: BTreeMap<LogVariant, GlobalId>,
155 peeks: BTreeMap<Uuid, PendingPeek>,
164 subscribes: BTreeMap<GlobalId, ActiveSubscribe>,
178 copy_tos: BTreeSet<GlobalId>,
186 history: ComputeCommandHistory<UIntGauge>,
188 command_rx: mpsc::UnboundedReceiver<Command>,
190 response_tx: mpsc::UnboundedSender<ComputeControllerResponse>,
192 introspection_tx: mpsc::UnboundedSender<IntrospectionUpdates>,
194 metrics: InstanceMetrics,
196 dyncfg: Arc<ConfigSet>,
198
199 peek_stash_persist_location: PersistLocation,
201
202 now: NowFn,
204 wallclock_lag: WallclockLagFn<Timestamp>,
206 wallclock_lag_last_recorded: DateTime<Utc>,
208
209 read_hold_tx: read_holds::ChangeTx,
214 replica_tx: mz_ore::channel::InstrumentedUnboundedSender<ReplicaResponse, IntCounter>,
216 replica_rx: mz_ore::channel::InstrumentedUnboundedReceiver<ReplicaResponse, IntCounter>,
218}
219
220impl Instance {
221 fn collection(&self, id: GlobalId) -> Result<&CollectionState, CollectionMissing> {
223 self.collections.get(&id).ok_or(CollectionMissing(id))
224 }
225
226 fn collection_mut(&mut self, id: GlobalId) -> Result<&mut CollectionState, CollectionMissing> {
228 self.collections.get_mut(&id).ok_or(CollectionMissing(id))
229 }
230
231 fn expect_collection(&self, id: GlobalId) -> &CollectionState {
237 self.collections.get(&id).expect("collection must exist")
238 }
239
240 fn expect_collection_mut(&mut self, id: GlobalId) -> &mut CollectionState {
246 self.collections
247 .get_mut(&id)
248 .expect("collection must exist")
249 }
250
251 fn collections_iter(&self) -> impl Iterator<Item = (GlobalId, &CollectionState)> {
252 self.collections.iter().map(|(id, coll)| (*id, coll))
253 }
254
255 fn replicas_hosting(
262 &self,
263 id: GlobalId,
264 ) -> Result<impl Iterator<Item = &ReplicaState> + Clone, CollectionMissing> {
265 let target = self.collection(id)?.target_replica;
266 Ok(self
267 .replicas
268 .values()
269 .filter(move |r| target.map_or(true, |t| t == r.id)))
270 }
271
272 fn add_collection(
278 &mut self,
279 id: GlobalId,
280 as_of: Antichain<Timestamp>,
281 shared: SharedCollectionState,
282 storage_dependencies: BTreeMap<GlobalId, ReadHold>,
283 compute_dependencies: BTreeMap<GlobalId, ReadHold>,
284 replica_input_read_holds: Vec<ReadHold>,
285 write_only: bool,
286 storage_sink: bool,
287 initial_as_of: Option<Antichain<Timestamp>>,
288 refresh_schedule: Option<RefreshSchedule>,
289 target_replica: Option<ReplicaId>,
290 ) {
291 let dependency_ids: Vec<GlobalId> = compute_dependencies
293 .keys()
294 .chain(storage_dependencies.keys())
295 .copied()
296 .collect();
297 let introspection = CollectionIntrospection::new(
298 id,
299 self.introspection_tx.clone(),
300 as_of.clone(),
301 storage_sink,
302 initial_as_of,
303 refresh_schedule,
304 dependency_ids,
305 );
306 let mut state = CollectionState::new(
307 id,
308 as_of.clone(),
309 shared,
310 storage_dependencies,
311 compute_dependencies,
312 Arc::clone(&self.read_hold_tx),
313 introspection,
314 );
315 state.target_replica = target_replica;
316 if write_only {
318 state.read_policy = None;
319 }
320
321 if let Some(previous) = self.collections.insert(id, state) {
322 panic!("attempt to add a collection with existing ID {id} (previous={previous:?}");
323 }
324
325 for replica in self.replicas.values_mut() {
327 if target_replica.is_some_and(|id| id != replica.id) {
328 continue;
329 }
330 replica.add_collection(id, as_of.clone(), replica_input_read_holds.clone());
331 }
332 }
333
334 fn remove_collection(&mut self, id: GlobalId) {
335 for replica in self.replicas.values_mut() {
337 replica.remove_collection(id);
338 }
339
340 self.collections.remove(&id);
342 }
343
344 fn add_replica_state(
345 &mut self,
346 id: ReplicaId,
347 client: ReplicaClient,
348 config: ReplicaConfig,
349 epoch: u64,
350 dyncfg_override: ConfigUpdates,
351 ) -> Result<(), read_holds::ReadHoldIssuerHungUp> {
352 let log_ids: BTreeSet<_> = config.logging.index_logs.values().copied().collect();
353
354 let metrics = self.metrics.for_replica(id);
355 let mut replica = ReplicaState::new(
356 id,
357 client,
358 config,
359 metrics,
360 self.introspection_tx.clone(),
361 epoch,
362 dyncfg_override,
363 );
364
365 let mut shutdown_input = None;
367 for (collection_id, collection) in &self.collections {
368 if (collection.log_collection && !log_ids.contains(collection_id))
371 || collection.target_replica.is_some_and(|rid| rid != id)
372 {
373 continue;
374 }
375
376 let as_of = if collection.log_collection {
377 Antichain::from_elem(Timestamp::MIN)
382 } else {
383 collection.read_frontier().to_owned()
384 };
385
386 let mut input_read_holds = Vec::with_capacity(collection.storage_dependencies.len());
394 let mut hung_up = Vec::new();
395 for hold in collection.storage_dependencies.values() {
396 match hold.try_clone() {
397 Ok(hold) => input_read_holds.push(hold),
398 Err(read_holds::ReadHoldIssuerHungUp(input_id)) => hung_up.push(input_id),
399 }
400 }
401 if !hung_up.is_empty() {
402 tracing::error!(
403 replica_id = %id,
404 %collection_id,
405 ?hung_up,
406 "giving up on adding replica collections: storage read hold issuers hung \
407 up, the process is shutting down",
408 );
409 shutdown_input = hung_up.into_iter().next();
410 break;
411 }
412
413 replica.add_collection(*collection_id, as_of, input_read_holds);
414 }
415
416 self.replicas.insert(id, replica);
417
418 match shutdown_input {
419 Some(input_id) => Err(read_holds::ReadHoldIssuerHungUp(input_id)),
420 None => Ok(()),
421 }
422 }
423
424 fn deliver_response(&self, response: ComputeControllerResponse) {
426 let _ = self.response_tx.send(response);
429 }
430
431 fn deliver_introspection_updates(&self, type_: IntrospectionType, updates: Vec<(Row, Diff)>) {
433 let _ = self.introspection_tx.send((type_, updates));
436 }
437
438 fn replica_exists(&self, id: ReplicaId) -> bool {
440 self.replicas.contains_key(&id)
441 }
442
443 fn peeks_targeting(&self, replica_id: ReplicaId) -> impl Iterator<Item = (Uuid, &PendingPeek)> {
445 self.peeks.iter().filter_map(move |(uuid, peek)| {
446 if peek.target_replica == Some(replica_id) {
447 Some((*uuid, peek))
448 } else {
449 None
450 }
451 })
452 }
453
454 fn subscribes_targeting(&self, replica_id: ReplicaId) -> impl Iterator<Item = GlobalId> + '_ {
456 self.subscribes.keys().copied().filter(move |id| {
457 let collection = self.expect_collection(*id);
458 collection.target_replica == Some(replica_id)
459 })
460 }
461
462 fn update_frontier_introspection(&mut self) {
471 for collection in self.collections.values_mut() {
472 collection
473 .introspection
474 .observe_frontiers(&collection.read_frontier(), &collection.write_frontier());
475 }
476
477 for replica in self.replicas.values_mut() {
478 for collection in replica.collections.values_mut() {
479 collection
480 .introspection
481 .observe_frontier(&collection.write_frontier);
482 }
483 }
484 }
485
486 fn refresh_state_metrics(&self) {
495 let unscheduled_collections_count =
496 self.collections.values().filter(|c| !c.scheduled).count();
497 let connected_replica_count = self
498 .replicas
499 .values()
500 .filter(|r| r.client.is_connected())
501 .count();
502
503 self.metrics
504 .replica_count
505 .set(u64::cast_from(self.replicas.len()));
506 self.metrics
507 .collection_count
508 .set(u64::cast_from(self.collections.len()));
509 self.metrics
510 .collection_unscheduled_count
511 .set(u64::cast_from(unscheduled_collections_count));
512 self.metrics
513 .peek_count
514 .set(u64::cast_from(self.peeks.len()));
515 self.metrics
516 .subscribe_count
517 .set(u64::cast_from(self.subscribes.len()));
518 self.metrics
519 .copy_to_count
520 .set(u64::cast_from(self.copy_tos.len()));
521 self.metrics
522 .connected_replica_count
523 .set(u64::cast_from(connected_replica_count));
524 }
525
526 fn refresh_wallclock_lag(&mut self) {
545 let frontier_lag = |frontier: &Antichain<Timestamp>| match frontier.as_option() {
546 Some(ts) => (self.wallclock_lag)(ts.clone()),
547 None => Duration::ZERO,
548 };
549
550 let now_ms = (self.now)();
551 let histogram_period = WallclockLagHistogramPeriod::from_epoch_millis(now_ms, &self.dyncfg);
552 let histogram_labels = match &self.workload_class {
553 Some(wc) => [("workload_class", wc.clone())].into(),
554 None => BTreeMap::new(),
555 };
556
557 let readable_storage_collections: BTreeSet<_> = self
560 .collections
561 .keys()
562 .filter_map(|id| {
563 let frontiers = self.storage_collections.collection_frontiers(*id).ok()?;
564 PartialOrder::less_than(&frontiers.read_capabilities, &frontiers.write_frontier)
565 .then_some(*id)
566 })
567 .collect();
568
569 for (id, collection) in &mut self.collections {
571 let write_frontier = collection.write_frontier();
572 let readable = if self.storage_collections.check_exists(*id).is_ok() {
573 readable_storage_collections.contains(id)
574 } else {
575 PartialOrder::less_than(&collection.read_frontier(), &write_frontier)
576 };
577
578 if let Some(stash) = &mut collection.wallclock_lag_histogram_stash {
579 let bucket = if readable {
580 let lag = frontier_lag(&write_frontier);
581 let lag = lag.as_secs().next_power_of_two();
582 WallclockLag::Seconds(lag)
583 } else {
584 WallclockLag::Undefined
585 };
586
587 let key = (histogram_period, bucket, histogram_labels.clone());
588 *stash.entry(key).or_default() += Diff::ONE;
589 }
590 }
591
592 for replica in self.replicas.values_mut() {
594 for (id, collection) in &mut replica.collections {
595 let readable = readable_storage_collections.contains(id) || collection.hydrated();
600
601 let lag = if readable {
602 let lag = frontier_lag(&collection.write_frontier);
603 WallclockLag::Seconds(lag.as_secs())
604 } else {
605 WallclockLag::Undefined
606 };
607
608 if let Some(wallclock_lag_max) = &mut collection.wallclock_lag_max {
609 *wallclock_lag_max = (*wallclock_lag_max).max(lag);
610 }
611
612 if let Some(metrics) = &mut collection.metrics {
613 let secs = lag.unwrap_seconds_or(u64::MAX);
616 metrics.wallclock_lag.observe(secs);
617 };
618 }
619 }
620
621 self.maybe_record_wallclock_lag();
623 }
624
625 fn maybe_record_wallclock_lag(&mut self) {
633 if self.read_only {
634 return;
635 }
636
637 let duration_trunc = |datetime: DateTime<_>, interval| {
638 let td = TimeDelta::from_std(interval).ok()?;
639 datetime.duration_trunc(td).ok()
640 };
641
642 let interval = WALLCLOCK_LAG_RECORDING_INTERVAL.get(&self.dyncfg);
643 let now_dt = mz_ore::now::to_datetime((self.now)());
644 let now_trunc = duration_trunc(now_dt, interval).unwrap_or_else(|| {
645 soft_panic_or_log!("excessive wallclock lag recording interval: {interval:?}");
646 let default = WALLCLOCK_LAG_RECORDING_INTERVAL.default();
647 duration_trunc(now_dt, *default).unwrap()
648 });
649 if now_trunc <= self.wallclock_lag_last_recorded {
650 return;
651 }
652
653 let now_ts: CheckedTimestamp<_> = now_trunc.try_into().expect("must fit");
654
655 let mut history_updates = Vec::new();
656 for (replica_id, replica) in &mut self.replicas {
657 for (collection_id, collection) in &mut replica.collections {
658 let Some(wallclock_lag_max) = &mut collection.wallclock_lag_max else {
659 continue;
660 };
661
662 let max_lag = std::mem::replace(wallclock_lag_max, WallclockLag::MIN);
663 let row = Row::pack_slice(&[
664 Datum::String(&collection_id.to_string()),
665 Datum::String(&replica_id.to_string()),
666 max_lag.into_interval_datum(),
667 Datum::TimestampTz(now_ts),
668 ]);
669 history_updates.push((row, Diff::ONE));
670 }
671 }
672 if !history_updates.is_empty() {
673 self.deliver_introspection_updates(
674 IntrospectionType::WallclockLagHistory,
675 history_updates,
676 );
677 }
678
679 let mut histogram_updates = Vec::new();
680 let mut row_buf = Row::default();
681 for (collection_id, collection) in &mut self.collections {
682 let Some(stash) = &mut collection.wallclock_lag_histogram_stash else {
683 continue;
684 };
685
686 for ((period, lag, labels), count) in std::mem::take(stash) {
687 let mut packer = row_buf.packer();
688 packer.extend([
689 Datum::TimestampTz(period.start),
690 Datum::TimestampTz(period.end),
691 Datum::String(&collection_id.to_string()),
692 lag.into_uint64_datum(),
693 ]);
694 let labels = labels.iter().map(|(k, v)| (*k, Datum::String(v)));
695 packer.push_dict(labels);
696
697 histogram_updates.push((row_buf.clone(), count));
698 }
699 }
700 if !histogram_updates.is_empty() {
701 self.deliver_introspection_updates(
702 IntrospectionType::WallclockLagHistogram,
703 histogram_updates,
704 );
705 }
706
707 self.wallclock_lag_last_recorded = now_trunc;
708 }
709
710 #[mz_ore::instrument(level = "debug")]
716 pub fn collection_hydrated(&self, collection_id: GlobalId) -> Result<bool, CollectionMissing> {
717 let mut hosting_replicas = self.replicas_hosting(collection_id)?.peekable();
718 if hosting_replicas.peek().is_none() {
719 return Ok(true);
720 }
721 for replica_state in hosting_replicas {
722 if replica_state.expect_collection(collection_id).hydrated() {
723 return Ok(true);
724 }
725 }
726
727 Ok(false)
728 }
729
730 #[mz_ore::instrument(level = "debug")]
746 pub fn collections_ready_on_replicas(
747 &self,
748 target_replica_ids: Option<Vec<ReplicaId>>,
749 exclude_collections: &BTreeSet<GlobalId>,
750 allowed_lag: Option<Timestamp>,
751 reference_replica_ids: &BTreeSet<ReplicaId>,
752 ) -> Result<bool, HydrationCheckBadTarget> {
753 if self.replicas.is_empty() {
754 return Ok(true);
755 }
756 let target_replicas: BTreeSet<ReplicaId> = self
757 .replicas
758 .keys()
759 .filter_map(|id| match target_replica_ids {
760 None => Some(id.clone()),
761 Some(ref ids) if ids.contains(id) => Some(id.clone()),
762 Some(_) => None,
763 })
764 .collect();
765 if let Some(targets) = target_replica_ids {
766 if target_replicas.is_empty() {
767 return Err(HydrationCheckBadTarget(targets));
768 }
769 }
770
771 let mut unhydrated = BTreeSet::new();
772 let mut lagging_ticks = BTreeMap::new();
773 let mut awaiting_completion = BTreeSet::new();
774 for (id, _collection) in self.collections_iter() {
775 if id.is_transient() || exclude_collections.contains(&id) {
776 continue;
777 }
778
779 let replicas = self
782 .replicas_hosting(id)
783 .expect("collection must exist")
784 .map(|replica| (replica.id, replica.expect_collection(id)));
785
786 match classify_collection_readiness(
787 replicas,
788 &target_replicas,
789 reference_replica_ids,
790 allowed_lag,
791 ) {
792 CollectionReadiness::Ready => {}
793 CollectionReadiness::Lagging { lag: Some(lag) } => {
797 lagging_ticks.insert(id, lag);
798 }
799 CollectionReadiness::Lagging { lag: None } => {
800 awaiting_completion.insert(id);
801 }
802 CollectionReadiness::Unhydrated => {
803 unhydrated.insert(id);
804 }
805 }
806 }
807
808 let ready =
809 unhydrated.is_empty() && lagging_ticks.is_empty() && awaiting_completion.is_empty();
810 if !ready {
811 tracing::info!(
815 replicas = ?target_replicas,
816 reference = ?reference_replica_ids,
817 unhydrated = ?unhydrated,
818 ?lagging_ticks,
819 ?awaiting_completion,
820 ?allowed_lag,
821 "collections are not ready on any target replica",
822 );
823 }
824
825 Ok(ready)
826 }
827
828 fn cleanup_collections(&mut self) {
844 let to_remove: Vec<_> = self
845 .collections_iter()
846 .filter(|(id, collection)| {
847 collection.dropped
848 && collection.shared.lock_read_capabilities(|c| c.is_empty())
849 && self
850 .replicas
851 .values()
852 .all(|r| r.collection_frontiers_empty(*id))
853 })
854 .map(|(id, _collection)| id)
855 .collect();
856
857 for id in to_remove {
858 self.remove_collection(id);
859 }
860 }
861
862 #[mz_ore::instrument(level = "debug")]
866 pub fn dump(&self) -> Result<serde_json::Value, anyhow::Error> {
867 let Self {
874 build_info: _,
875 storage_collections: _,
876 peek_stash_persist_location: _,
877 initialized,
878 read_only,
879 workload_class,
880 replicas,
881 collections,
882 log_sources: _,
883 peeks,
884 subscribes,
885 copy_tos,
886 history: _,
887 command_rx: _,
888 response_tx: _,
889 introspection_tx: _,
890 metrics: _,
891 dyncfg: _,
892 now: _,
893 wallclock_lag: _,
894 wallclock_lag_last_recorded,
895 read_hold_tx: _,
896 replica_tx: _,
897 replica_rx: _,
898 } = self;
899
900 let replicas: BTreeMap<_, _> = replicas
901 .iter()
902 .map(|(id, replica)| Ok((id.to_string(), replica.dump()?)))
903 .collect::<Result<_, anyhow::Error>>()?;
904 let collections: BTreeMap<_, _> = collections
905 .iter()
906 .map(|(id, collection)| (id.to_string(), format!("{collection:?}")))
907 .collect();
908 let peeks: BTreeMap<_, _> = peeks
909 .iter()
910 .map(|(uuid, peek)| (uuid.to_string(), format!("{peek:?}")))
911 .collect();
912 let subscribes: BTreeMap<_, _> = subscribes
913 .iter()
914 .map(|(id, subscribe)| (id.to_string(), format!("{subscribe:?}")))
915 .collect();
916 let copy_tos: Vec<_> = copy_tos.iter().map(|id| id.to_string()).collect();
917 let wallclock_lag_last_recorded = format!("{wallclock_lag_last_recorded:?}");
918
919 Ok(serde_json::json!({
920 "initialized": initialized,
921 "read_only": read_only,
922 "workload_class": workload_class,
923 "replicas": replicas,
924 "collections": collections,
925 "peeks": peeks,
926 "subscribes": subscribes,
927 "copy_tos": copy_tos,
928 "wallclock_lag_last_recorded": wallclock_lag_last_recorded,
929 }))
930 }
931
932 pub(super) fn collection_write_frontier(
934 &self,
935 id: GlobalId,
936 ) -> Result<Antichain<Timestamp>, CollectionMissing> {
937 Ok(self.collection(id)?.write_frontier())
938 }
939}
940
941impl Instance {
942 pub(super) fn new(
943 build_info: &'static BuildInfo,
944 storage: StorageCollections,
945 peek_stash_persist_location: PersistLocation,
946 arranged_logs: Vec<(LogVariant, GlobalId, SharedCollectionState)>,
947 metrics: InstanceMetrics,
948 now: NowFn,
949 wallclock_lag: WallclockLagFn<Timestamp>,
950 dyncfg: Arc<ConfigSet>,
951 command_rx: mpsc::UnboundedReceiver<Command>,
952 response_tx: mpsc::UnboundedSender<ComputeControllerResponse>,
953 read_hold_tx: read_holds::ChangeTx,
954 introspection_tx: mpsc::UnboundedSender<IntrospectionUpdates>,
955 read_only: bool,
956 ) -> Self {
957 let mut collections = BTreeMap::new();
958 let mut log_sources = BTreeMap::new();
959 for (log, id, shared) in arranged_logs {
960 let collection = CollectionState::new_log_collection(
961 id,
962 shared,
963 Arc::clone(&read_hold_tx),
964 introspection_tx.clone(),
965 );
966 collections.insert(id, collection);
967 log_sources.insert(log, id);
968 }
969
970 let history = ComputeCommandHistory::new(metrics.for_history());
971
972 let send_count = metrics.response_send_count.clone();
973 let recv_count = metrics.response_recv_count.clone();
974 let (replica_tx, replica_rx) = instrumented_unbounded_channel(send_count, recv_count);
975
976 let now_dt = mz_ore::now::to_datetime(now());
977
978 Self {
979 build_info,
980 storage_collections: storage,
981 peek_stash_persist_location,
982 initialized: false,
983 read_only,
984 workload_class: None,
985 replicas: Default::default(),
986 collections,
987 log_sources,
988 peeks: Default::default(),
989 subscribes: Default::default(),
990 copy_tos: Default::default(),
991 history,
992 command_rx,
993 response_tx,
994 introspection_tx,
995 metrics,
996 dyncfg,
997 now,
998 wallclock_lag,
999 wallclock_lag_last_recorded: now_dt,
1000 read_hold_tx,
1001 replica_tx,
1002 replica_rx,
1003 }
1004 }
1005
1006 pub(super) async fn run(mut self) {
1007 self.send(ComputeCommand::Hello {
1008 nonce: Uuid::default(),
1011 });
1012
1013 let instance_config = InstanceConfig {
1014 peek_stash_persist_location: self.peek_stash_persist_location.clone(),
1015 logging: Default::default(),
1019 expiration_offset: Default::default(),
1020 arrangement_dictionary_compression: Default::default(),
1021 initial_config: Default::default(),
1022 };
1023
1024 self.send(ComputeCommand::CreateInstance(Box::new(instance_config)));
1025
1026 loop {
1027 tokio::select! {
1028 command = self.command_rx.recv() => match command {
1029 Some(cmd) => cmd(&mut self),
1030 None => break,
1031 },
1032 response = self.replica_rx.recv() => match response {
1033 Some(response) => self.handle_response(response),
1034 None => unreachable!("self owns a sender side of the channel"),
1035 }
1036 }
1037 }
1038 }
1039
1040 #[mz_ore::instrument(level = "debug")]
1042 pub fn update_configuration(&mut self, config_params: ComputeParameters) {
1043 if let Some(workload_class) = &config_params.workload_class {
1044 self.workload_class = workload_class.clone();
1045 }
1046
1047 let command = ComputeCommand::UpdateConfiguration(Box::new(config_params));
1048 self.send(command);
1049 }
1050
1051 #[mz_ore::instrument(level = "debug")]
1056 pub fn initialization_complete(&mut self) {
1057 if !self.initialized {
1059 self.send(ComputeCommand::InitializationComplete);
1060 self.initialized = true;
1061 }
1062 }
1063
1064 #[mz_ore::instrument(level = "debug")]
1068 pub fn allow_writes(&mut self, collection_id: GlobalId) -> Result<(), CollectionMissing> {
1069 let collection = self.collection_mut(collection_id)?;
1070
1071 if !collection.read_only {
1073 return Ok(());
1074 }
1075
1076 let as_of = collection.read_frontier();
1078
1079 if as_of.is_empty() {
1082 return Ok(());
1083 }
1084
1085 collection.read_only = false;
1086 self.send(ComputeCommand::AllowWrites(collection_id));
1087
1088 Ok(())
1089 }
1090
1091 #[mz_ore::instrument(level = "debug")]
1101 pub fn shutdown(&mut self) {
1102 let (_tx, rx) = mpsc::unbounded_channel();
1104 self.command_rx = rx;
1105
1106 let stray_replicas: Vec<_> = self.replicas.keys().collect();
1107 soft_assert_or_log!(
1108 stray_replicas.is_empty(),
1109 "dropped instance still has provisioned replicas: {stray_replicas:?}",
1110 );
1111 }
1112
1113 fn initiate_shutdown(&mut self) {
1119 let (_tx, rx) = mpsc::unbounded_channel();
1122 self.command_rx = rx;
1123 }
1124
1125 #[mz_ore::instrument(level = "debug")]
1127 fn send(&mut self, cmd: ComputeCommand) {
1128 self.history.push(cmd.clone());
1133
1134 let target_replica = self.target_replica(&cmd);
1135
1136 let dyncfg = &self.dyncfg;
1137 if let Some(rid) = target_replica {
1138 if let Some(replica) = self.replicas.get_mut(&rid) {
1139 let cmd =
1140 Self::specialize_command_for_replica(cmd, &replica.dyncfg_override, dyncfg);
1141 let _ = replica.client.send(cmd);
1142 }
1143 } else {
1144 for replica in self.replicas.values_mut() {
1145 let cmd = Self::specialize_command_for_replica(
1146 cmd.clone(),
1147 &replica.dyncfg_override,
1148 dyncfg,
1149 );
1150 let _ = replica.client.send(cmd);
1151 }
1152 }
1153 }
1154
1155 fn specialize_command_for_replica(
1163 mut cmd: ComputeCommand,
1164 dyncfg_override: &ConfigUpdates,
1165 dyncfg: &ConfigSet,
1166 ) -> ComputeCommand {
1167 match &mut cmd {
1168 ComputeCommand::UpdateConfiguration(params) => {
1169 if !dyncfg_override.updates.is_empty() {
1170 params.dyncfg_updates.extend(dyncfg_override.clone());
1171 }
1172 }
1173 ComputeCommand::CreateInstance(config) => {
1174 let mut initial = ConfigUpdates::from(dyncfg);
1175 initial.extend(dyncfg_override.clone());
1176 config.initial_config = initial;
1177 }
1178 _ => {}
1179 }
1180 cmd
1181 }
1182
1183 pub(super) fn update_replica_dyncfg_overrides(
1187 &mut self,
1188 mut overrides: BTreeMap<ReplicaId, ConfigUpdates>,
1189 ) {
1190 for (id, replica) in self.replicas.iter_mut() {
1191 replica.dyncfg_override = overrides.remove(id).unwrap_or_default();
1192 }
1193 }
1194
1195 fn target_replica(&self, cmd: &ComputeCommand) -> Option<ReplicaId> {
1203 match &cmd {
1204 ComputeCommand::Schedule(id)
1205 | ComputeCommand::AllowWrites(id)
1206 | ComputeCommand::AllowCompaction { id, .. } => {
1207 self.expect_collection(*id).target_replica
1208 }
1209 ComputeCommand::CreateDataflow(desc) => {
1210 let mut target_replica = None;
1211 for id in desc.export_ids() {
1212 if let Some(replica) = self.expect_collection(id).target_replica {
1213 if target_replica.is_some() {
1214 assert_eq!(target_replica, Some(replica));
1215 }
1216 target_replica = Some(replica);
1217 }
1218 }
1219 target_replica
1220 }
1221 ComputeCommand::Peek(_)
1223 | ComputeCommand::Hello { .. }
1224 | ComputeCommand::CreateInstance(_)
1225 | ComputeCommand::InitializationComplete
1226 | ComputeCommand::UpdateConfiguration(_)
1227 | ComputeCommand::CancelPeek { .. } => None,
1228 }
1229 }
1230
1231 #[mz_ore::instrument(level = "debug")]
1236 pub fn add_replica(
1237 &mut self,
1238 id: ReplicaId,
1239 mut config: ReplicaConfig,
1240 epoch: Option<u64>,
1241 dyncfg_override: ConfigUpdates,
1242 ) -> Result<(), ReplicaExists> {
1243 if self.replica_exists(id) {
1244 return Err(ReplicaExists(id));
1245 }
1246
1247 config.logging.index_logs = self.log_sources.clone();
1248
1249 let epoch = epoch.unwrap_or(1);
1250 let metrics = self.metrics.for_replica(id);
1251 let client = ReplicaClient::spawn(
1252 id,
1253 self.build_info,
1254 config.clone(),
1255 epoch,
1256 metrics.clone(),
1257 Arc::clone(&self.dyncfg),
1258 self.replica_tx.clone(),
1259 );
1260
1261 self.history.reduce();
1263
1264 self.history.update_source_uppers(&self.storage_collections);
1266
1267 for command in self.history.iter() {
1269 if let Some(target_replica) = self.target_replica(command)
1271 && target_replica != id
1272 {
1273 continue;
1274 }
1275
1276 let command = Self::specialize_command_for_replica(
1279 command.clone(),
1280 &dyncfg_override,
1281 &self.dyncfg,
1282 );
1283 if client.send(command).is_err() {
1284 tracing::warn!("Replica {:?} connection terminated during hydration", id);
1287 break;
1288 }
1289 }
1290
1291 if self
1293 .add_replica_state(id, client, config, epoch, dyncfg_override)
1294 .is_err()
1295 {
1296 self.initiate_shutdown();
1302 }
1303
1304 Ok(())
1305 }
1306
1307 #[mz_ore::instrument(level = "debug")]
1309 pub fn remove_replica(&mut self, id: ReplicaId) -> Result<(), ReplicaMissing> {
1310 let replica = self.replicas.remove(&id).ok_or(ReplicaMissing(id))?;
1311
1312 for (collection_id, replica_collection) in &replica.collections {
1320 let collection = self.collections.get(collection_id);
1321 for replica_hold in &replica_collection.input_read_holds {
1322 let input_id = replica_hold.id();
1323 let global_hold = collection.and_then(|c| c.storage_dependencies.get(&input_id));
1324 let unprotected = global_hold
1325 .is_none_or(|h| PartialOrder::less_than(replica_hold.since(), h.since()));
1326 if unprotected {
1327 tracing::warn!(
1328 replica_id = %id,
1329 %collection_id,
1330 %input_id,
1331 replica_hold_since = ?replica_hold.since(),
1332 global_hold_since = ?global_hold.map(|h| h.since()),
1333 "dropping per-replica read hold without equivalent global read hold",
1334 );
1335 }
1336 }
1337 }
1338 drop(replica);
1339
1340 let to_drop: Vec<_> = self.subscribes_targeting(id).collect();
1344 for subscribe_id in to_drop {
1345 let subscribe = self.subscribes.remove(&subscribe_id).unwrap();
1346 let response = ComputeControllerResponse::SubscribeResponse(
1347 subscribe_id,
1348 SubscribeBatch {
1349 lower: subscribe.frontier.clone(),
1350 upper: subscribe.frontier,
1351 updates: Err(ERROR_TARGET_REPLICA_FAILED.into()),
1352 },
1353 );
1354 self.deliver_response(response);
1355 }
1356
1357 let mut peek_responses = Vec::new();
1362 let mut to_drop = Vec::new();
1363 for (uuid, peek) in self.peeks_targeting(id) {
1364 peek_responses.push((
1365 uuid,
1366 PeekNotification::Error(ERROR_TARGET_REPLICA_FAILED.into()),
1367 peek.otel_ctx.clone(),
1368 ));
1369 to_drop.push(uuid);
1370 }
1371 for (uuid, notification, otel_ctx) in peek_responses {
1372 self.deliver_peek_notification(uuid, notification, otel_ctx);
1373 }
1374 for uuid in to_drop {
1375 let response =
1376 PeekResponse::Error(ProtocolPeekError::unstructured(ERROR_TARGET_REPLICA_FAILED));
1377 self.finish_peek(uuid, response);
1378 }
1379
1380 Ok(())
1381 }
1382
1383 fn rehydrate_replica(&mut self, id: ReplicaId) {
1389 let replica = &self.replicas[&id];
1390 let config = replica.config.clone();
1391 let epoch = replica.epoch + 1;
1392 let dyncfg_override = replica.dyncfg_override.clone();
1393
1394 self.remove_replica(id).expect("replica must exist");
1401 let result = self.add_replica(id, config, Some(epoch), dyncfg_override);
1402
1403 match result {
1404 Ok(()) => (),
1405 Err(ReplicaExists(_)) => unreachable!("replica was removed"),
1406 }
1407 }
1408
1409 fn rehydrate_failed_replicas(&mut self) {
1411 let replicas = self.replicas.iter();
1412 let failed_replicas: Vec<_> = replicas
1413 .filter_map(|(id, replica)| replica.client.is_failed().then_some(*id))
1414 .collect();
1415
1416 for replica_id in failed_replicas {
1417 self.rehydrate_replica(replica_id);
1418 }
1419 }
1420
1421 #[mz_ore::instrument(level = "debug")]
1426 pub fn create_dataflow(
1427 &mut self,
1428 dataflow: LirDataflowDescription,
1429 import_read_holds: Vec<ReadHold>,
1430 mut shared_collection_state: BTreeMap<GlobalId, SharedCollectionState>,
1431 target_replica: Option<ReplicaId>,
1432 ) -> Result<(), DataflowCreationError> {
1433 use DataflowCreationError::*;
1434
1435 if let Some(replica_id) = target_replica {
1439 if !self.replica_exists(replica_id) {
1440 return Err(ReplicaMissing(replica_id));
1441 }
1442 }
1443
1444 let as_of = dataflow.as_of.as_ref().ok_or(MissingAsOf)?;
1446 if as_of.is_empty() && dataflow.subscribe_ids().next().is_some() {
1447 return Err(EmptyAsOfForSubscribe);
1448 }
1449 if as_of.is_empty() && dataflow.copy_to_ids().next().is_some() {
1450 return Err(EmptyAsOfForCopyTo);
1451 }
1452
1453 let mut storage_dependencies = BTreeMap::new();
1455 let mut compute_dependencies = BTreeMap::new();
1456
1457 let mut replica_input_read_holds = Vec::new();
1462
1463 let mut import_read_holds: BTreeMap<_, _> =
1464 import_read_holds.into_iter().map(|r| (r.id(), r)).collect();
1465
1466 for &id in dataflow.source_imports.keys() {
1467 let mut read_hold = import_read_holds.remove(&id).ok_or(ReadHoldMissing(id))?;
1468 replica_input_read_holds.push(read_hold.clone());
1469
1470 read_hold
1471 .try_downgrade(as_of.clone())
1472 .map_err(|_| ReadHoldInsufficient(id))?;
1473 storage_dependencies.insert(id, read_hold);
1474 }
1475
1476 for &id in dataflow.index_imports.keys() {
1477 let mut read_hold = import_read_holds.remove(&id).ok_or(ReadHoldMissing(id))?;
1478 read_hold
1479 .try_downgrade(as_of.clone())
1480 .map_err(|_| ReadHoldInsufficient(id))?;
1481 compute_dependencies.insert(id, read_hold);
1482 }
1483
1484 if as_of.is_empty() {
1487 replica_input_read_holds = Default::default();
1488 }
1489
1490 for export_id in dataflow.export_ids() {
1492 let shared = shared_collection_state
1493 .remove(&export_id)
1494 .unwrap_or_else(|| SharedCollectionState::new(as_of.clone()));
1495 let write_only = dataflow.sink_exports.contains_key(&export_id);
1496 let storage_sink = dataflow.persist_sink_ids().any(|id| id == export_id);
1497
1498 self.add_collection(
1499 export_id,
1500 as_of.clone(),
1501 shared,
1502 storage_dependencies.clone(),
1503 compute_dependencies.clone(),
1504 replica_input_read_holds.clone(),
1505 write_only,
1506 storage_sink,
1507 dataflow.initial_storage_as_of.clone(),
1508 dataflow.refresh_schedule.clone(),
1509 target_replica,
1510 );
1511
1512 if let Ok(frontiers) = self.storage_collections.collection_frontiers(export_id) {
1515 self.maybe_update_global_write_frontier(export_id, frontiers.write_frontier);
1516 }
1517 }
1518
1519 for subscribe_id in dataflow.subscribe_ids() {
1521 self.subscribes
1522 .insert(subscribe_id, ActiveSubscribe::default());
1523 }
1524
1525 for copy_to_id in dataflow.copy_to_ids() {
1527 self.copy_tos.insert(copy_to_id);
1528 }
1529
1530 let mut source_imports = BTreeMap::new();
1533 for (id, import) in dataflow.source_imports {
1534 let frontiers = self
1535 .storage_collections
1536 .collection_frontiers(id)
1537 .expect("collection exists");
1538
1539 let collection_metadata = self
1540 .storage_collections
1541 .collection_metadata(id)
1542 .expect("we have a read hold on this collection");
1543
1544 let desc = SourceInstanceDesc {
1545 storage_metadata: collection_metadata.clone(),
1546 arguments: import.desc.arguments,
1547 typ: import.desc.typ.clone(),
1548 };
1549 source_imports.insert(
1550 id,
1551 mz_compute_types::dataflows::SourceImport {
1552 desc,
1553 monotonic: import.monotonic,
1554 with_snapshot: import.with_snapshot,
1555 upper: frontiers.write_frontier,
1556 },
1557 );
1558 }
1559
1560 let mut sink_exports = BTreeMap::new();
1561 for (id, se) in dataflow.sink_exports {
1562 let connection = match se.connection {
1563 ComputeSinkConnection::MaterializedView(conn) => {
1564 let metadata = self
1565 .storage_collections
1566 .collection_metadata(id)
1567 .map_err(|_| CollectionMissing(id))?
1568 .clone();
1569 let conn = MaterializedViewSinkConnection {
1570 value_desc: conn.value_desc,
1571 storage_metadata: metadata,
1572 };
1573 ComputeSinkConnection::MaterializedView(conn)
1574 }
1575 ComputeSinkConnection::Subscribe(conn) => ComputeSinkConnection::Subscribe(conn),
1576 ComputeSinkConnection::CopyToS3Oneshot(conn) => {
1577 ComputeSinkConnection::CopyToS3Oneshot(conn)
1578 }
1579 ComputeSinkConnection::MetricSink(conn) => ComputeSinkConnection::MetricSink(conn),
1580 };
1581 let desc = ComputeSinkDesc {
1582 from: se.from,
1583 from_desc: se.from_desc,
1584 connection,
1585 with_snapshot: se.with_snapshot,
1586 up_to: se.up_to,
1587 non_null_assertions: se.non_null_assertions,
1588 refresh_schedule: se.refresh_schedule,
1589 from_arrangement: se.from_arrangement,
1590 };
1591 sink_exports.insert(id, desc);
1592 }
1593
1594 let objects_to_build = dataflow
1596 .objects_to_build
1597 .into_iter()
1598 .map(|object| BuildDesc {
1599 id: object.id,
1600 plan: RenderPlan::try_from(object.plan).expect("valid plan"),
1601 })
1602 .collect();
1603
1604 let augmented_dataflow = DataflowDescription {
1605 source_imports,
1606 sink_exports,
1607 objects_to_build,
1608 index_imports: dataflow.index_imports,
1610 index_exports: dataflow.index_exports,
1611 as_of: dataflow.as_of.clone(),
1612 until: dataflow.until,
1613 initial_storage_as_of: dataflow.initial_storage_as_of,
1614 refresh_schedule: dataflow.refresh_schedule,
1615 debug_name: dataflow.debug_name,
1616 time_dependence: dataflow.time_dependence,
1617 };
1618
1619 if augmented_dataflow.is_transient() {
1620 tracing::debug!(
1621 name = %augmented_dataflow.debug_name,
1622 import_ids = %augmented_dataflow.display_import_ids(),
1623 export_ids = %augmented_dataflow.display_export_ids(),
1624 as_of = ?augmented_dataflow.as_of.as_ref().unwrap().elements(),
1625 until = ?augmented_dataflow.until.elements(),
1626 "creating dataflow",
1627 );
1628 } else {
1629 tracing::info!(
1630 name = %augmented_dataflow.debug_name,
1631 import_ids = %augmented_dataflow.display_import_ids(),
1632 export_ids = %augmented_dataflow.display_export_ids(),
1633 as_of = ?augmented_dataflow.as_of.as_ref().unwrap().elements(),
1634 until = ?augmented_dataflow.until.elements(),
1635 "creating dataflow",
1636 );
1637 }
1638
1639 if as_of.is_empty() {
1642 tracing::info!(
1643 name = %augmented_dataflow.debug_name,
1644 "not sending `CreateDataflow`, because of empty `as_of`",
1645 );
1646 } else {
1647 let collections: Vec<_> = augmented_dataflow.export_ids().collect();
1648 self.send(ComputeCommand::CreateDataflow(Box::new(augmented_dataflow)));
1649
1650 for id in collections {
1651 self.maybe_schedule_collection(id);
1652 }
1653 }
1654
1655 Ok(())
1656 }
1657
1658 fn maybe_schedule_collection(&mut self, id: GlobalId) {
1664 let collection = self.expect_collection(id);
1665
1666 if collection.scheduled {
1668 return;
1669 }
1670
1671 let as_of = collection.read_frontier();
1672
1673 if as_of.is_empty() {
1676 return;
1677 }
1678
1679 let ready = if id.is_transient() {
1680 true
1686 } else {
1687 let not_self_dep = |x: &GlobalId| *x != id;
1693
1694 let mut deps_scheduled = true;
1697
1698 let compute_deps = collection.compute_dependency_ids().filter(not_self_dep);
1703 let mut compute_frontiers = Vec::new();
1704 for id in compute_deps {
1705 let dep = &self.expect_collection(id);
1706 deps_scheduled &= dep.scheduled;
1707 compute_frontiers.push(dep.write_frontier());
1708 }
1709
1710 let storage_deps = collection.storage_dependency_ids().filter(not_self_dep);
1711 let storage_frontiers = self
1712 .storage_collections
1713 .collections_frontiers(storage_deps.collect())
1714 .expect("must exist");
1715 let storage_frontiers = storage_frontiers.into_iter().map(|f| f.write_frontier);
1716
1717 let mut frontiers = compute_frontiers.into_iter().chain(storage_frontiers);
1718 let frontiers_ready =
1719 frontiers.all(|frontier| PartialOrder::less_than(&as_of, &frontier));
1720
1721 deps_scheduled && frontiers_ready
1722 };
1723
1724 if ready {
1725 self.send(ComputeCommand::Schedule(id));
1726 let collection = self.expect_collection_mut(id);
1727 collection.scheduled = true;
1728 }
1729 }
1730
1731 fn schedule_collections(&mut self) {
1733 let ids: Vec<_> = self.collections.keys().copied().collect();
1734 for id in ids {
1735 self.maybe_schedule_collection(id);
1736 }
1737 }
1738
1739 #[mz_ore::instrument(level = "debug")]
1742 pub fn drop_collections(&mut self, ids: Vec<GlobalId>) -> Result<(), CollectionMissing> {
1743 for id in &ids {
1744 let collection = self.collection_mut(*id)?;
1745
1746 collection.dropped = true;
1748
1749 collection.implied_read_hold.release();
1752 collection.warmup_read_hold.release();
1753
1754 self.subscribes.remove(id);
1757 self.copy_tos.remove(id);
1760 }
1761
1762 Ok(())
1763 }
1764
1765 #[mz_ore::instrument(level = "debug")]
1769 pub fn peek(
1770 &mut self,
1771 peek_target: PeekTarget,
1772 literal_constraints: Option<Vec<Row>>,
1773 uuid: Uuid,
1774 timestamp: Timestamp,
1775 result_desc: RelationDesc,
1776 finishing: RowSetFinishing,
1777 map_filter_project: mz_expr::SafeMfpPlan,
1778 mut read_hold: ReadHold,
1779 target_replica: Option<ReplicaId>,
1780 peek_response_tx: oneshot::Sender<PeekResponse>,
1781 lifecycle: Option<Arc<PeekLifecycle>>,
1782 ) -> Result<(), PeekError> {
1783 use PeekError::*;
1784
1785 let target_id = peek_target.id();
1786
1787 if read_hold.id() != target_id {
1789 return Err(ReadHoldIdMismatch(read_hold.id()));
1790 }
1791 read_hold
1792 .try_downgrade(Antichain::from_elem(timestamp.clone()))
1793 .map_err(|_| ReadHoldInsufficient(target_id))?;
1794
1795 if let Some(target) = target_replica {
1796 if !self.replica_exists(target) {
1797 return Err(ReplicaMissing(target));
1798 }
1799 }
1800
1801 let otel_ctx = OpenTelemetryContext::obtain();
1802
1803 self.peeks.insert(
1804 uuid,
1805 PendingPeek {
1806 target_replica,
1807 otel_ctx: otel_ctx.clone(),
1809 requested_at: Instant::now(),
1810 read_hold,
1811 peek_response_tx,
1812 lifecycle,
1813 limit: finishing.limit.map(usize::cast_from),
1814 offset: finishing.offset,
1815 },
1816 );
1817
1818 let peek = Peek {
1819 literal_constraints,
1820 uuid,
1821 timestamp,
1822 finishing,
1823 map_filter_project,
1824 otel_ctx,
1827 target: peek_target,
1828 result_desc,
1829 };
1830 self.send(ComputeCommand::Peek(Box::new(peek)));
1831
1832 Ok(())
1833 }
1834
1835 #[mz_ore::instrument(level = "debug")]
1837 pub fn cancel_peek(&mut self, uuid: Uuid, reason: PeekResponse) {
1838 let Some(peek) = self.peeks.get_mut(&uuid) else {
1839 tracing::warn!("did not find pending peek for {uuid}");
1840 return;
1841 };
1842
1843 let duration = peek.requested_at.elapsed();
1844 self.metrics
1845 .observe_peek_response(&PeekResponse::Canceled, duration);
1846
1847 let otel_ctx = peek.otel_ctx.clone();
1849 otel_ctx.attach_as_parent();
1850
1851 self.deliver_peek_notification(uuid, PeekNotification::Canceled, otel_ctx);
1852
1853 self.finish_peek(uuid, reason);
1856 }
1857
1858 #[mz_ore::instrument(level = "debug")]
1870 pub fn set_read_policy(
1871 &mut self,
1872 policies: Vec<(GlobalId, ReadPolicy)>,
1873 ) -> Result<(), ReadPolicyError> {
1874 for (id, _policy) in &policies {
1877 let collection = self.collection(*id)?;
1878 if collection.read_policy.is_none() {
1879 return Err(ReadPolicyError::WriteOnlyCollection(*id));
1880 }
1881 }
1882
1883 for (id, new_policy) in policies {
1884 let collection = self.expect_collection_mut(id);
1885 let new_since = new_policy.frontier(collection.write_frontier().borrow());
1886 let _ = collection.implied_read_hold.try_downgrade(new_since);
1887 collection.read_policy = Some(new_policy);
1888 }
1889
1890 Ok(())
1891 }
1892
1893 #[mz_ore::instrument(level = "debug")]
1901 fn maybe_update_global_write_frontier(
1902 &mut self,
1903 id: GlobalId,
1904 new_frontier: Antichain<Timestamp>,
1905 ) {
1906 let collection = self.expect_collection_mut(id);
1907
1908 let advanced = collection.shared.lock_write_frontier(|f| {
1909 let advanced = PartialOrder::less_than(f, &new_frontier);
1910 if advanced {
1911 f.clone_from(&new_frontier);
1912 }
1913 advanced
1914 });
1915
1916 if !advanced {
1917 return;
1918 }
1919
1920 let new_since = match &collection.read_policy {
1922 Some(read_policy) => {
1923 read_policy.frontier(new_frontier.borrow())
1926 }
1927 None => {
1928 Antichain::from_iter(
1937 new_frontier
1938 .iter()
1939 .map(|t| t.step_back().unwrap_or(Timestamp::MIN)),
1940 )
1941 }
1942 };
1943 let _ = collection.implied_read_hold.try_downgrade(new_since);
1944
1945 self.deliver_response(ComputeControllerResponse::FrontierUpper {
1947 id,
1948 upper: new_frontier,
1949 });
1950 }
1951
1952 pub(super) fn apply_read_hold_change(
1954 &mut self,
1955 id: GlobalId,
1956 mut update: ChangeBatch<Timestamp>,
1957 ) {
1958 let Some(collection) = self.collections.get_mut(&id) else {
1959 soft_panic_or_log!(
1960 "read hold change for absent collection (id={id}, changes={update:?})"
1961 );
1962 return;
1963 };
1964
1965 let new_since = collection.shared.lock_read_capabilities(|caps| {
1966 let read_frontier = caps.frontier();
1969 for (time, diff) in update.iter() {
1970 let count = caps.count_for(time) + diff;
1971 assert!(
1972 count >= 0,
1973 "invalid read capabilities update: negative capability \
1974 (id={id:?}, read_capabilities={caps:?}, update={update:?})",
1975 );
1976 assert!(
1977 count == 0 || read_frontier.less_equal(time),
1978 "invalid read capabilities update: frontier regression \
1979 (id={id:?}, read_capabilities={caps:?}, update={update:?})",
1980 );
1981 }
1982
1983 let changes = caps.update_iter(update.drain());
1986
1987 let changed = changes.count() > 0;
1988 changed.then(|| caps.frontier().to_owned())
1989 });
1990
1991 let Some(new_since) = new_since else {
1992 return; };
1994
1995 for read_hold in collection.compute_dependencies.values_mut() {
1997 read_hold
1998 .try_downgrade(new_since.clone())
1999 .expect("frontiers don't regress");
2000 }
2001 for read_hold in collection.storage_dependencies.values_mut() {
2002 read_hold
2003 .try_downgrade(new_since.clone())
2004 .expect("frontiers don't regress");
2005 }
2006
2007 self.send(ComputeCommand::AllowCompaction {
2009 id,
2010 frontier: new_since,
2011 });
2012 }
2013
2014 fn finish_peek(&mut self, uuid: Uuid, response: PeekResponse) {
2023 let Some(peek) = self.peeks.remove(&uuid) else {
2024 return;
2025 };
2026
2027 let _ = peek.peek_response_tx.send(response);
2029
2030 self.send(ComputeCommand::CancelPeek { uuid });
2033
2034 drop(peek.read_hold);
2035 }
2036
2037 fn deliver_peek_notification(
2040 &self,
2041 uuid: Uuid,
2042 notification: PeekNotification,
2043 otel_ctx: OpenTelemetryContext,
2044 ) {
2045 if let Some(lifecycle) = self
2046 .peeks
2047 .get(&uuid)
2048 .and_then(|peek| peek.lifecycle.as_ref())
2049 {
2050 otel_ctx.attach_as_parent();
2051 lifecycle.complete(notification);
2052 } else {
2053 self.deliver_response(ComputeControllerResponse::PeekNotification(
2054 uuid,
2055 notification,
2056 otel_ctx,
2057 ));
2058 }
2059 }
2060
2061 fn handle_response(&mut self, (replica_id, epoch, response): ReplicaResponse) {
2064 if self
2066 .replicas
2067 .get(&replica_id)
2068 .filter(|replica| replica.epoch == epoch)
2069 .is_none()
2070 {
2071 return;
2072 }
2073
2074 match response {
2077 ComputeResponse::Frontiers(id, frontiers) => {
2078 self.handle_frontiers_response(id, frontiers, replica_id);
2079 }
2080 ComputeResponse::PeekResponse(uuid, peek_response, otel_ctx) => {
2081 self.handle_peek_response(uuid, peek_response, otel_ctx, replica_id);
2082 }
2083 ComputeResponse::CopyToResponse(id, response) => {
2084 self.handle_copy_to_response(id, response, replica_id);
2085 }
2086 ComputeResponse::SubscribeResponse(id, response) => {
2087 self.handle_subscribe_response(id, response, replica_id);
2088 }
2089 ComputeResponse::Status(response) => {
2090 self.handle_status_response(response, replica_id);
2091 }
2092 }
2093 }
2094
2095 fn handle_frontiers_response(
2098 &mut self,
2099 id: GlobalId,
2100 frontiers: FrontiersResponse,
2101 replica_id: ReplicaId,
2102 ) {
2103 if !self.collections.contains_key(&id) {
2104 soft_panic_or_log!(
2105 "frontiers update for an unknown collection \
2106 (id={id}, replica_id={replica_id}, frontiers={frontiers:?})"
2107 );
2108 return;
2109 }
2110 let Some(replica) = self.replicas.get_mut(&replica_id) else {
2111 soft_panic_or_log!(
2112 "frontiers update for an unknown replica \
2113 (replica_id={replica_id}, frontiers={frontiers:?})"
2114 );
2115 return;
2116 };
2117 let Some(replica_collection) = replica.collections.get_mut(&id) else {
2118 soft_panic_or_log!(
2119 "frontiers update for an unknown replica collection \
2120 (id={id}, replica_id={replica_id}, frontiers={frontiers:?})"
2121 );
2122 return;
2123 };
2124
2125 if let Some(new_frontier) = frontiers.input_frontier {
2126 replica_collection.update_input_frontier(new_frontier.clone());
2127 }
2128 if let Some(new_frontier) = frontiers.output_frontier {
2129 replica_collection.update_output_frontier(new_frontier.clone());
2130 }
2131 if let Some(new_frontier) = frontiers.write_frontier {
2132 replica_collection.update_write_frontier(new_frontier.clone());
2133 self.maybe_update_global_write_frontier(id, new_frontier);
2134 }
2135 }
2136
2137 #[mz_ore::instrument(level = "debug")]
2138 fn handle_peek_response(
2139 &mut self,
2140 uuid: Uuid,
2141 response: PeekResponse,
2142 otel_ctx: OpenTelemetryContext,
2143 replica_id: ReplicaId,
2144 ) {
2145 otel_ctx.attach_as_parent();
2146
2147 let Some(peek) = self.peeks.get(&uuid) else {
2150 return;
2151 };
2152
2153 let target_replica = peek.target_replica.unwrap_or(replica_id);
2155 if target_replica != replica_id {
2156 return;
2157 }
2158
2159 let duration = peek.requested_at.elapsed();
2160 self.metrics.observe_peek_response(&response, duration);
2161
2162 let notification = PeekNotification::new(&response, peek.offset, peek.limit);
2163 self.deliver_peek_notification(uuid, notification, otel_ctx);
2166
2167 self.finish_peek(uuid, response)
2168 }
2169
2170 fn handle_copy_to_response(
2171 &mut self,
2172 sink_id: GlobalId,
2173 response: CopyToResponse,
2174 replica_id: ReplicaId,
2175 ) {
2176 if !self.collections.contains_key(&sink_id) {
2177 soft_panic_or_log!(
2178 "received response for an unknown copy-to \
2179 (sink_id={sink_id}, replica_id={replica_id})",
2180 );
2181 return;
2182 }
2183 let Some(replica) = self.replicas.get_mut(&replica_id) else {
2184 soft_panic_or_log!("copy-to response for an unknown replica (replica_id={replica_id})");
2185 return;
2186 };
2187 let Some(replica_collection) = replica.collections.get_mut(&sink_id) else {
2188 soft_panic_or_log!(
2189 "copy-to response for an unknown replica collection \
2190 (sink_id={sink_id}, replica_id={replica_id})"
2191 );
2192 return;
2193 };
2194
2195 replica_collection.update_write_frontier(Antichain::new());
2199 replica_collection.update_input_frontier(Antichain::new());
2200 replica_collection.update_output_frontier(Antichain::new());
2201
2202 if !self.copy_tos.remove(&sink_id) {
2205 return;
2206 }
2207
2208 let result = match response {
2209 CopyToResponse::RowCount(count) => Ok(count),
2210 CopyToResponse::Error(error) => Err(anyhow::anyhow!(error)),
2211 CopyToResponse::Dropped => {
2216 tracing::error!(
2217 %sink_id, %replica_id,
2218 "received `Dropped` response for a tracked copy to",
2219 );
2220 return;
2221 }
2222 };
2223
2224 self.deliver_response(ComputeControllerResponse::CopyToResponse(sink_id, result));
2225 }
2226
2227 fn handle_subscribe_response(
2228 &mut self,
2229 subscribe_id: GlobalId,
2230 response: SubscribeResponse,
2231 replica_id: ReplicaId,
2232 ) {
2233 if !self.collections.contains_key(&subscribe_id) {
2234 soft_panic_or_log!(
2235 "received response for an unknown subscribe \
2236 (subscribe_id={subscribe_id}, replica_id={replica_id})",
2237 );
2238 return;
2239 }
2240 let Some(replica) = self.replicas.get_mut(&replica_id) else {
2241 soft_panic_or_log!(
2242 "subscribe response for an unknown replica (replica_id={replica_id})"
2243 );
2244 return;
2245 };
2246 let Some(replica_collection) = replica.collections.get_mut(&subscribe_id) else {
2247 soft_panic_or_log!(
2248 "subscribe response for an unknown replica collection \
2249 (subscribe_id={subscribe_id}, replica_id={replica_id})"
2250 );
2251 return;
2252 };
2253
2254 let write_frontier = match &response {
2258 SubscribeResponse::Batch(batch) => batch.upper.clone(),
2259 SubscribeResponse::DroppedAt(_) => Antichain::new(),
2260 };
2261
2262 replica_collection.update_write_frontier(write_frontier.clone());
2266 replica_collection.update_input_frontier(write_frontier.clone());
2267 replica_collection.update_output_frontier(write_frontier.clone());
2268
2269 let Some(mut subscribe) = self.subscribes.get(&subscribe_id).cloned() else {
2271 return;
2272 };
2273
2274 self.maybe_update_global_write_frontier(subscribe_id, write_frontier);
2280
2281 match response {
2282 SubscribeResponse::Batch(batch) => {
2283 let upper = batch.upper;
2284 let mut updates = batch.updates;
2285
2286 if PartialOrder::less_than(&subscribe.frontier, &upper) {
2289 let lower = std::mem::replace(&mut subscribe.frontier, upper.clone());
2290
2291 if upper.is_empty() {
2292 self.subscribes.remove(&subscribe_id);
2294 } else {
2295 self.subscribes.insert(subscribe_id, subscribe);
2297 }
2298
2299 if let Ok(updates) = updates.as_mut() {
2300 updates.retain_mut(|updates| {
2301 let offset = updates.times().partition_point(|t| {
2302 !lower.less_equal(t)
2305 });
2306 let (_, past_lower) = std::mem::take(updates).split_at(offset);
2307 *updates = past_lower;
2308 updates.len() > 0
2309 });
2310 }
2311 self.deliver_response(ComputeControllerResponse::SubscribeResponse(
2312 subscribe_id,
2313 SubscribeBatch {
2314 lower,
2315 upper,
2316 updates,
2317 },
2318 ));
2319 }
2320 }
2321 SubscribeResponse::DroppedAt(frontier) => {
2322 tracing::error!(
2327 %subscribe_id,
2328 %replica_id,
2329 frontier = ?frontier.elements(),
2330 "received `DroppedAt` response for a tracked subscribe",
2331 );
2332 self.subscribes.remove(&subscribe_id);
2333 }
2334 }
2335 }
2336
2337 fn handle_status_response(&self, response: StatusResponse, _replica_id: ReplicaId) {
2338 match response {
2339 StatusResponse::Placeholder => {}
2340 }
2341 }
2342
2343 fn dependency_write_frontiers<'b>(
2345 &'b self,
2346 collection: &'b CollectionState,
2347 ) -> impl Iterator<Item = Antichain<Timestamp>> + 'b {
2348 let compute_frontiers = collection.compute_dependency_ids().filter_map(|dep_id| {
2349 let collection = self.collections.get(&dep_id);
2350 collection.map(|c| c.write_frontier())
2351 });
2352 let storage_frontiers = collection.storage_dependency_ids().filter_map(|dep_id| {
2353 let frontiers = self.storage_collections.collection_frontiers(dep_id).ok();
2354 frontiers.map(|f| f.write_frontier)
2355 });
2356
2357 compute_frontiers.chain(storage_frontiers)
2358 }
2359
2360 fn transitive_storage_dependency_write_frontiers<'b>(
2362 &'b self,
2363 collection: &'b CollectionState,
2364 ) -> impl Iterator<Item = Antichain<Timestamp>> + 'b {
2365 let mut storage_ids: BTreeSet<_> = collection.storage_dependency_ids().collect();
2366 let mut todo: Vec<_> = collection.compute_dependency_ids().collect();
2367 let mut done = BTreeSet::new();
2368
2369 while let Some(id) = todo.pop() {
2370 if done.contains(&id) {
2371 continue;
2372 }
2373 if let Some(dep) = self.collections.get(&id) {
2374 storage_ids.extend(dep.storage_dependency_ids());
2375 todo.extend(dep.compute_dependency_ids())
2376 }
2377 done.insert(id);
2378 }
2379
2380 let storage_frontiers = storage_ids.into_iter().filter_map(|id| {
2381 let frontiers = self.storage_collections.collection_frontiers(id).ok();
2382 frontiers.map(|f| f.write_frontier)
2383 });
2384
2385 storage_frontiers
2386 }
2387
2388 fn downgrade_warmup_capabilities(&mut self) {
2401 let mut new_capabilities = BTreeMap::new();
2402 for (id, collection) in &self.collections {
2403 if collection.read_policy.is_none()
2407 && collection.shared.lock_write_frontier(|f| f.is_empty())
2408 {
2409 new_capabilities.insert(*id, Antichain::new());
2410 continue;
2411 }
2412
2413 let mut new_capability = Antichain::new();
2414 for frontier in self.dependency_write_frontiers(collection) {
2415 for time in frontier {
2416 new_capability.insert(time.step_back().unwrap_or(time));
2417 }
2418 }
2419
2420 new_capabilities.insert(*id, new_capability);
2421 }
2422
2423 for (id, new_capability) in new_capabilities {
2424 let collection = self.expect_collection_mut(id);
2425 let _ = collection.warmup_read_hold.try_downgrade(new_capability);
2426 }
2427 }
2428
2429 fn forward_implied_capabilities(&mut self) {
2457 if !ENABLE_PAUSED_CLUSTER_READHOLD_DOWNGRADE.get(&self.dyncfg) {
2458 return;
2459 }
2460 if !self.replicas.is_empty() {
2461 return;
2462 }
2463
2464 let mut new_capabilities = BTreeMap::new();
2465 for (id, collection) in &self.collections {
2466 let Some(read_policy) = &collection.read_policy else {
2467 continue;
2469 };
2470
2471 let mut dep_frontier = Antichain::new();
2475 for frontier in self.transitive_storage_dependency_write_frontiers(collection) {
2476 dep_frontier.extend(frontier);
2477 }
2478
2479 let new_capability = read_policy.frontier(dep_frontier.borrow());
2480 if PartialOrder::less_than(collection.implied_read_hold.since(), &new_capability) {
2481 new_capabilities.insert(*id, new_capability);
2482 }
2483 }
2484
2485 for (id, new_capability) in new_capabilities {
2486 let collection = self.expect_collection_mut(id);
2487 let _ = collection.implied_read_hold.try_downgrade(new_capability);
2488 }
2489 }
2490
2491 pub(super) fn acquire_read_hold(&self, id: GlobalId) -> Result<ReadHold, CollectionMissing> {
2496 let collection = self.collection(id)?;
2502 let since = collection.shared.lock_read_capabilities(|caps| {
2503 let since = caps.frontier().to_owned();
2504 caps.update_iter(since.iter().map(|t| (t.clone(), 1)));
2505 since
2506 });
2507 let hold = ReadHold::new(id, since, Arc::clone(&self.read_hold_tx));
2508 Ok(hold)
2509 }
2510
2511 #[mz_ore::instrument(level = "debug")]
2517 pub fn maintain(&mut self) {
2518 self.rehydrate_failed_replicas();
2519 self.downgrade_warmup_capabilities();
2520 self.forward_implied_capabilities();
2521 self.schedule_collections();
2522 self.cleanup_collections();
2523 self.update_frontier_introspection();
2524 self.refresh_state_metrics();
2525 self.refresh_wallclock_lag();
2526 }
2527}
2528
2529#[derive(Debug)]
2534struct CollectionState {
2535 target_replica: Option<ReplicaId>,
2537 log_collection: bool,
2541 dropped: bool,
2547 scheduled: bool,
2550
2551 read_only: bool,
2555
2556 shared: SharedCollectionState,
2558
2559 implied_read_hold: ReadHold,
2566 warmup_read_hold: ReadHold,
2574 read_policy: Option<ReadPolicy>,
2580
2581 storage_dependencies: BTreeMap<GlobalId, ReadHold>,
2584 compute_dependencies: BTreeMap<GlobalId, ReadHold>,
2587
2588 introspection: CollectionIntrospection,
2590
2591 wallclock_lag_histogram_stash: Option<
2598 BTreeMap<
2599 (
2600 WallclockLagHistogramPeriod,
2601 WallclockLag,
2602 BTreeMap<&'static str, String>,
2603 ),
2604 Diff,
2605 >,
2606 >,
2607}
2608
2609impl CollectionState {
2610 fn new(
2612 collection_id: GlobalId,
2613 as_of: Antichain<Timestamp>,
2614 shared: SharedCollectionState,
2615 storage_dependencies: BTreeMap<GlobalId, ReadHold>,
2616 compute_dependencies: BTreeMap<GlobalId, ReadHold>,
2617 read_hold_tx: read_holds::ChangeTx,
2618 introspection: CollectionIntrospection,
2619 ) -> Self {
2620 let since = as_of.clone();
2622 let upper = as_of;
2624
2625 assert!(shared.lock_read_capabilities(|c| c.frontier() == since.borrow()));
2627 assert!(shared.lock_write_frontier(|f| f == &upper));
2628
2629 let implied_read_hold =
2633 ReadHold::new(collection_id, since.clone(), Arc::clone(&read_hold_tx));
2634 let warmup_read_hold = ReadHold::new(collection_id, since.clone(), read_hold_tx);
2635
2636 let updates = warmup_read_hold.since().iter().map(|t| (t.clone(), 1));
2637 shared.lock_read_capabilities(|c| {
2638 c.update_iter(updates);
2639 });
2640
2641 let wallclock_lag_histogram_stash = match collection_id.is_transient() {
2645 true => None,
2646 false => Some(Default::default()),
2647 };
2648
2649 Self {
2650 target_replica: None,
2651 log_collection: false,
2652 dropped: false,
2653 scheduled: false,
2654 read_only: true,
2655 shared,
2656 implied_read_hold,
2657 warmup_read_hold,
2658 read_policy: Some(ReadPolicy::ValidFrom(since)),
2659 storage_dependencies,
2660 compute_dependencies,
2661 introspection,
2662 wallclock_lag_histogram_stash,
2663 }
2664 }
2665
2666 fn new_log_collection(
2668 id: GlobalId,
2669 shared: SharedCollectionState,
2670 read_hold_tx: read_holds::ChangeTx,
2671 introspection_tx: mpsc::UnboundedSender<IntrospectionUpdates>,
2672 ) -> Self {
2673 let since = Antichain::from_elem(Timestamp::MIN);
2674 let introspection = CollectionIntrospection::new(
2675 id,
2676 introspection_tx,
2677 since.clone(),
2678 false,
2679 None,
2680 None,
2681 Vec::new(),
2682 );
2683 let mut state = Self::new(
2684 id,
2685 since,
2686 shared,
2687 Default::default(),
2688 Default::default(),
2689 read_hold_tx,
2690 introspection,
2691 );
2692 state.log_collection = true;
2693 state.scheduled = true;
2695 state
2696 }
2697
2698 fn read_frontier(&self) -> Antichain<Timestamp> {
2700 self.shared
2701 .lock_read_capabilities(|c| c.frontier().to_owned())
2702 }
2703
2704 fn write_frontier(&self) -> Antichain<Timestamp> {
2706 self.shared.lock_write_frontier(|f| f.clone())
2707 }
2708
2709 fn storage_dependency_ids(&self) -> impl Iterator<Item = GlobalId> + '_ {
2710 self.storage_dependencies.keys().copied()
2711 }
2712
2713 fn compute_dependency_ids(&self) -> impl Iterator<Item = GlobalId> + '_ {
2714 self.compute_dependencies.keys().copied()
2715 }
2716}
2717
2718#[derive(Clone, Debug)]
2729pub(super) struct SharedCollectionState {
2730 read_capabilities: Arc<Mutex<MutableAntichain<Timestamp>>>,
2743 write_frontier: Arc<Mutex<Antichain<Timestamp>>>,
2745}
2746
2747impl SharedCollectionState {
2748 pub fn new(as_of: Antichain<Timestamp>) -> Self {
2749 let since = as_of.clone();
2751 let upper = as_of;
2753
2754 let mut read_capabilities = MutableAntichain::new();
2758 read_capabilities.update_iter(since.iter().map(|time| (time.clone(), 1)));
2759
2760 Self {
2761 read_capabilities: Arc::new(Mutex::new(read_capabilities)),
2762 write_frontier: Arc::new(Mutex::new(upper)),
2763 }
2764 }
2765
2766 pub fn lock_read_capabilities<F, R>(&self, f: F) -> R
2767 where
2768 F: FnOnce(&mut MutableAntichain<Timestamp>) -> R,
2769 {
2770 let mut caps = self.read_capabilities.lock().expect("poisoned");
2771 f(&mut *caps)
2772 }
2773
2774 pub fn lock_write_frontier<F, R>(&self, f: F) -> R
2775 where
2776 F: FnOnce(&mut Antichain<Timestamp>) -> R,
2777 {
2778 let mut frontier = self.write_frontier.lock().expect("poisoned");
2779 f(&mut *frontier)
2780 }
2781}
2782
2783#[derive(Debug)]
2786struct CollectionIntrospection {
2787 collection_id: GlobalId,
2789 introspection_tx: mpsc::UnboundedSender<IntrospectionUpdates>,
2791 frontiers: Option<FrontiersIntrospectionState>,
2796 refresh: Option<RefreshIntrospectionState>,
2800 dependency_ids: Vec<GlobalId>,
2802}
2803
2804impl CollectionIntrospection {
2805 fn new(
2806 collection_id: GlobalId,
2807 introspection_tx: mpsc::UnboundedSender<IntrospectionUpdates>,
2808 as_of: Antichain<Timestamp>,
2809 storage_sink: bool,
2810 initial_as_of: Option<Antichain<Timestamp>>,
2811 refresh_schedule: Option<RefreshSchedule>,
2812 dependency_ids: Vec<GlobalId>,
2813 ) -> Self {
2814 let refresh =
2815 match (refresh_schedule, initial_as_of) {
2816 (Some(refresh_schedule), Some(initial_as_of)) => Some(
2817 RefreshIntrospectionState::new(refresh_schedule, initial_as_of, &as_of),
2818 ),
2819 (refresh_schedule, _) => {
2820 soft_assert_or_log!(
2823 refresh_schedule.is_none(),
2824 "`refresh_schedule` without an `initial_as_of`: {collection_id}"
2825 );
2826 None
2827 }
2828 };
2829 let frontiers = (!storage_sink).then(|| FrontiersIntrospectionState::new(as_of));
2830
2831 let self_ = Self {
2832 collection_id,
2833 introspection_tx,
2834 frontiers,
2835 refresh,
2836 dependency_ids,
2837 };
2838
2839 self_.report_initial_state();
2840 self_
2841 }
2842
2843 fn report_initial_state(&self) {
2845 if let Some(frontiers) = &self.frontiers {
2846 let row = frontiers.row_for_collection(self.collection_id);
2847 let updates = vec![(row, Diff::ONE)];
2848 self.send(IntrospectionType::Frontiers, updates);
2849 }
2850
2851 if let Some(refresh) = &self.refresh {
2852 let row = refresh.row_for_collection(self.collection_id);
2853 let updates = vec![(row, Diff::ONE)];
2854 self.send(IntrospectionType::ComputeMaterializedViewRefreshes, updates);
2855 }
2856
2857 if !self.dependency_ids.is_empty() {
2858 let updates = self.dependency_rows(Diff::ONE);
2859 self.send(IntrospectionType::ComputeDependencies, updates);
2860 }
2861 }
2862
2863 fn dependency_rows(&self, diff: Diff) -> Vec<(Row, Diff)> {
2865 self.dependency_ids
2866 .iter()
2867 .map(|dependency_id| {
2868 let row = Row::pack_slice(&[
2869 Datum::String(&self.collection_id.to_string()),
2870 Datum::String(&dependency_id.to_string()),
2871 ]);
2872 (row, diff)
2873 })
2874 .collect()
2875 }
2876
2877 fn observe_frontiers(
2880 &mut self,
2881 read_frontier: &Antichain<Timestamp>,
2882 write_frontier: &Antichain<Timestamp>,
2883 ) {
2884 self.update_frontier_introspection(read_frontier, write_frontier);
2885 self.update_refresh_introspection(write_frontier);
2886 }
2887
2888 fn update_frontier_introspection(
2889 &mut self,
2890 read_frontier: &Antichain<Timestamp>,
2891 write_frontier: &Antichain<Timestamp>,
2892 ) {
2893 let Some(frontiers) = &mut self.frontiers else {
2894 return;
2895 };
2896
2897 if &frontiers.read_frontier == read_frontier && &frontiers.write_frontier == write_frontier
2898 {
2899 return; };
2901
2902 let retraction = frontiers.row_for_collection(self.collection_id);
2903 frontiers.update(read_frontier, write_frontier);
2904 let insertion = frontiers.row_for_collection(self.collection_id);
2905 let updates = vec![(retraction, Diff::MINUS_ONE), (insertion, Diff::ONE)];
2906 self.send(IntrospectionType::Frontiers, updates);
2907 }
2908
2909 fn update_refresh_introspection(&mut self, write_frontier: &Antichain<Timestamp>) {
2910 let Some(refresh) = &mut self.refresh else {
2911 return;
2912 };
2913
2914 let retraction = refresh.row_for_collection(self.collection_id);
2915 refresh.frontier_update(write_frontier);
2916 let insertion = refresh.row_for_collection(self.collection_id);
2917
2918 if retraction == insertion {
2919 return; }
2921
2922 let updates = vec![(retraction, Diff::MINUS_ONE), (insertion, Diff::ONE)];
2923 self.send(IntrospectionType::ComputeMaterializedViewRefreshes, updates);
2924 }
2925
2926 fn send(&self, introspection_type: IntrospectionType, updates: Vec<(Row, Diff)>) {
2927 let _ = self.introspection_tx.send((introspection_type, updates));
2930 }
2931}
2932
2933impl Drop for CollectionIntrospection {
2934 fn drop(&mut self) {
2935 if let Some(frontiers) = &self.frontiers {
2937 let row = frontiers.row_for_collection(self.collection_id);
2938 let updates = vec![(row, Diff::MINUS_ONE)];
2939 self.send(IntrospectionType::Frontiers, updates);
2940 }
2941
2942 if let Some(refresh) = &self.refresh {
2944 let retraction = refresh.row_for_collection(self.collection_id);
2945 let updates = vec![(retraction, Diff::MINUS_ONE)];
2946 self.send(IntrospectionType::ComputeMaterializedViewRefreshes, updates);
2947 }
2948
2949 if !self.dependency_ids.is_empty() {
2951 let updates = self.dependency_rows(Diff::MINUS_ONE);
2952 self.send(IntrospectionType::ComputeDependencies, updates);
2953 }
2954 }
2955}
2956
2957#[derive(Debug)]
2958struct FrontiersIntrospectionState {
2959 read_frontier: Antichain<Timestamp>,
2960 write_frontier: Antichain<Timestamp>,
2961}
2962
2963impl FrontiersIntrospectionState {
2964 fn new(as_of: Antichain<Timestamp>) -> Self {
2965 Self {
2966 read_frontier: as_of.clone(),
2967 write_frontier: as_of,
2968 }
2969 }
2970
2971 fn row_for_collection(&self, collection_id: GlobalId) -> Row {
2973 let read_frontier = self
2974 .read_frontier
2975 .as_option()
2976 .map_or(Datum::Null, |ts| ts.clone().into());
2977 let write_frontier = self
2978 .write_frontier
2979 .as_option()
2980 .map_or(Datum::Null, |ts| ts.clone().into());
2981 Row::pack_slice(&[
2982 Datum::String(&collection_id.to_string()),
2983 read_frontier,
2984 write_frontier,
2985 ])
2986 }
2987
2988 fn update(
2990 &mut self,
2991 read_frontier: &Antichain<Timestamp>,
2992 write_frontier: &Antichain<Timestamp>,
2993 ) {
2994 if read_frontier != &self.read_frontier {
2995 self.read_frontier.clone_from(read_frontier);
2996 }
2997 if write_frontier != &self.write_frontier {
2998 self.write_frontier.clone_from(write_frontier);
2999 }
3000 }
3001}
3002
3003#[derive(Debug)]
3006struct RefreshIntrospectionState {
3007 refresh_schedule: RefreshSchedule,
3009 initial_as_of: Antichain<Timestamp>,
3010 next_refresh: Datum<'static>, last_completed_refresh: Datum<'static>, }
3014
3015impl RefreshIntrospectionState {
3016 fn row_for_collection(&self, collection_id: GlobalId) -> Row {
3018 Row::pack_slice(&[
3019 Datum::String(&collection_id.to_string()),
3020 self.last_completed_refresh,
3021 self.next_refresh,
3022 ])
3023 }
3024}
3025
3026impl RefreshIntrospectionState {
3027 fn new(
3030 refresh_schedule: RefreshSchedule,
3031 initial_as_of: Antichain<Timestamp>,
3032 upper: &Antichain<Timestamp>,
3033 ) -> Self {
3034 let mut self_ = Self {
3035 refresh_schedule: refresh_schedule.clone(),
3036 initial_as_of: initial_as_of.clone(),
3037 next_refresh: Datum::Null,
3038 last_completed_refresh: Datum::Null,
3039 };
3040 self_.frontier_update(upper);
3041 self_
3042 }
3043
3044 fn frontier_update(&mut self, write_frontier: &Antichain<Timestamp>) {
3047 if write_frontier.is_empty() {
3048 self.last_completed_refresh =
3049 if let Some(last_refresh) = self.refresh_schedule.last_refresh() {
3050 last_refresh.into()
3051 } else {
3052 Timestamp::MAX.into()
3055 };
3056 self.next_refresh = Datum::Null;
3057 } else {
3058 if PartialOrder::less_equal(write_frontier, &self.initial_as_of) {
3059 self.last_completed_refresh = Datum::Null;
3061 let initial_as_of = self.initial_as_of.as_option().expect(
3062 "initial_as_of can't be [], because then there would be no refreshes at all",
3063 );
3064 let first_refresh = self
3065 .refresh_schedule
3066 .round_up_timestamp(*initial_as_of)
3067 .expect("sequencing makes sure that REFRESH MVs always have a first refresh");
3068 soft_assert_or_log!(
3069 first_refresh == *initial_as_of,
3070 "initial_as_of should be set to the first refresh"
3071 );
3072 self.next_refresh = first_refresh.into();
3073 } else {
3074 let write_frontier = write_frontier.as_option().expect("checked above");
3076 self.last_completed_refresh = self
3077 .refresh_schedule
3078 .round_down_timestamp_m1(*write_frontier)
3079 .map_or_else(
3080 || {
3081 soft_panic_or_log!(
3082 "rounding down should have returned the first refresh or later"
3083 );
3084 Datum::Null
3085 },
3086 |last_completed_refresh| last_completed_refresh.into(),
3087 );
3088 self.next_refresh = write_frontier.clone().into();
3089 }
3090 }
3091 }
3092}
3093
3094#[derive(Debug)]
3096struct PendingPeek {
3097 lifecycle: Option<Arc<PeekLifecycle>>,
3099 target_replica: Option<ReplicaId>,
3103 otel_ctx: OpenTelemetryContext,
3105 requested_at: Instant,
3109 read_hold: ReadHold,
3111 peek_response_tx: oneshot::Sender<PeekResponse>,
3113 limit: Option<usize>,
3115 offset: usize,
3117}
3118
3119#[derive(Debug, Clone)]
3120struct ActiveSubscribe {
3121 frontier: Antichain<Timestamp>,
3123}
3124
3125impl Default for ActiveSubscribe {
3126 fn default() -> Self {
3127 Self {
3128 frontier: Antichain::from_elem(Timestamp::MIN),
3129 }
3130 }
3131}
3132
3133#[derive(Debug)]
3135struct ReplicaState {
3136 id: ReplicaId,
3138 client: ReplicaClient,
3140 config: ReplicaConfig,
3142 metrics: ReplicaMetrics,
3144 introspection_tx: mpsc::UnboundedSender<IntrospectionUpdates>,
3146 collections: BTreeMap<GlobalId, ReplicaCollectionState>,
3148 epoch: u64,
3150 dyncfg_override: ConfigUpdates,
3154}
3155
3156impl ReplicaState {
3157 fn new(
3158 id: ReplicaId,
3159 client: ReplicaClient,
3160 config: ReplicaConfig,
3161 metrics: ReplicaMetrics,
3162 introspection_tx: mpsc::UnboundedSender<IntrospectionUpdates>,
3163 epoch: u64,
3164 dyncfg_override: ConfigUpdates,
3165 ) -> Self {
3166 Self {
3167 id,
3168 client,
3169 config,
3170 metrics,
3171 introspection_tx,
3172 epoch,
3173 dyncfg_override,
3174 collections: Default::default(),
3175 }
3176 }
3177
3178 fn add_collection(
3184 &mut self,
3185 id: GlobalId,
3186 as_of: Antichain<Timestamp>,
3187 input_read_holds: Vec<ReadHold>,
3188 ) {
3189 let metrics = self.metrics.for_collection(id);
3190 let introspection = ReplicaCollectionIntrospection::new(
3191 self.id,
3192 id,
3193 self.introspection_tx.clone(),
3194 as_of.clone(),
3195 );
3196 let mut state =
3197 ReplicaCollectionState::new(metrics, as_of, introspection, input_read_holds);
3198
3199 if id.is_transient() {
3203 state.wallclock_lag_max = None;
3204 }
3205
3206 if let Some(previous) = self.collections.insert(id, state) {
3207 panic!("attempt to add a collection with existing ID {id} (previous={previous:?}");
3208 }
3209 }
3210
3211 fn remove_collection(&mut self, id: GlobalId) -> Option<ReplicaCollectionState> {
3213 self.collections.remove(&id)
3214 }
3215
3216 fn expect_collection(&self, id: GlobalId) -> &ReplicaCollectionState {
3223 self.collections
3224 .get(&id)
3225 .expect("hosting replica must have per-replica collection state")
3226 }
3227
3228 fn collection_frontiers_empty(&self, id: GlobalId) -> bool {
3230 self.collections.get(&id).map_or(true, |c| {
3231 c.write_frontier.is_empty()
3232 && c.input_frontier.is_empty()
3233 && c.output_frontier.is_empty()
3234 })
3235 }
3236
3237 #[mz_ore::instrument(level = "debug")]
3241 pub fn dump(&self) -> Result<serde_json::Value, anyhow::Error> {
3242 let Self {
3249 id,
3250 client: _,
3251 config: _,
3252 metrics: _,
3253 introspection_tx: _,
3254 epoch,
3255 dyncfg_override,
3256 collections,
3257 } = self;
3258
3259 let collections: BTreeMap<_, _> = collections
3260 .iter()
3261 .map(|(id, collection)| (id.to_string(), format!("{collection:?}")))
3262 .collect();
3263
3264 Ok(serde_json::json!({
3265 "id": id.to_string(),
3266 "collections": collections,
3267 "epoch": epoch,
3268 "dyncfg_override": format!("{dyncfg_override:?}"),
3269 }))
3270 }
3271}
3272
3273#[derive(Debug)]
3274struct ReplicaCollectionState {
3275 write_frontier: Antichain<Timestamp>,
3279 input_frontier: Antichain<Timestamp>,
3283 output_frontier: Antichain<Timestamp>,
3287
3288 metrics: Option<ReplicaCollectionMetrics>,
3292 as_of: Antichain<Timestamp>,
3294 introspection: ReplicaCollectionIntrospection,
3296 input_read_holds: Vec<ReadHold>,
3302
3303 wallclock_lag_max: Option<WallclockLag>,
3307}
3308
3309impl ReplicaCollectionState {
3310 fn new(
3311 metrics: Option<ReplicaCollectionMetrics>,
3312 as_of: Antichain<Timestamp>,
3313 introspection: ReplicaCollectionIntrospection,
3314 input_read_holds: Vec<ReadHold>,
3315 ) -> Self {
3316 Self {
3317 write_frontier: as_of.clone(),
3318 input_frontier: as_of.clone(),
3319 output_frontier: as_of.clone(),
3320 metrics,
3321 as_of,
3322 introspection,
3323 input_read_holds,
3324 wallclock_lag_max: Some(WallclockLag::MIN),
3325 }
3326 }
3327
3328 fn hydrated(&self) -> bool {
3330 self.as_of.is_empty() || PartialOrder::less_than(&self.as_of, &self.output_frontier)
3346 }
3347
3348 fn update_write_frontier(&mut self, new_frontier: Antichain<Timestamp>) {
3350 if PartialOrder::less_than(&new_frontier, &self.write_frontier) {
3351 soft_panic_or_log!(
3352 "replica collection write frontier regression (old={:?}, new={new_frontier:?})",
3353 self.write_frontier,
3354 );
3355 return;
3356 } else if new_frontier == self.write_frontier {
3357 return;
3358 }
3359
3360 self.write_frontier = new_frontier;
3361 }
3362
3363 fn update_input_frontier(&mut self, new_frontier: Antichain<Timestamp>) {
3365 if PartialOrder::less_than(&new_frontier, &self.input_frontier) {
3366 soft_panic_or_log!(
3367 "replica collection input frontier regression (old={:?}, new={new_frontier:?})",
3368 self.input_frontier,
3369 );
3370 return;
3371 } else if new_frontier == self.input_frontier {
3372 return;
3373 }
3374
3375 self.input_frontier = new_frontier;
3376
3377 for read_hold in &mut self.input_read_holds {
3379 let result = read_hold.try_downgrade(self.input_frontier.clone());
3380 soft_assert_or_log!(
3381 result.is_ok(),
3382 "read hold downgrade failed (read_hold={read_hold:?}, new_since={:?})",
3383 self.input_frontier,
3384 );
3385 }
3386 }
3387
3388 fn update_output_frontier(&mut self, new_frontier: Antichain<Timestamp>) {
3390 if PartialOrder::less_than(&new_frontier, &self.output_frontier) {
3391 soft_panic_or_log!(
3392 "replica collection output frontier regression (old={:?}, new={new_frontier:?})",
3393 self.output_frontier,
3394 );
3395 return;
3396 } else if new_frontier == self.output_frontier {
3397 return;
3398 }
3399
3400 self.output_frontier = new_frontier;
3401 }
3402}
3403
3404#[derive(Debug)]
3407struct ReplicaCollectionIntrospection {
3408 replica_id: ReplicaId,
3410 collection_id: GlobalId,
3412 write_frontier: Antichain<Timestamp>,
3414 introspection_tx: mpsc::UnboundedSender<IntrospectionUpdates>,
3416}
3417
3418impl ReplicaCollectionIntrospection {
3419 fn new(
3421 replica_id: ReplicaId,
3422 collection_id: GlobalId,
3423 introspection_tx: mpsc::UnboundedSender<IntrospectionUpdates>,
3424 as_of: Antichain<Timestamp>,
3425 ) -> Self {
3426 let self_ = Self {
3427 replica_id,
3428 collection_id,
3429 write_frontier: as_of,
3430 introspection_tx,
3431 };
3432
3433 self_.report_initial_state();
3434 self_
3435 }
3436
3437 fn report_initial_state(&self) {
3439 let row = self.write_frontier_row();
3440 let updates = vec![(row, Diff::ONE)];
3441 self.send(IntrospectionType::ReplicaFrontiers, updates);
3442 }
3443
3444 fn observe_frontier(&mut self, write_frontier: &Antichain<Timestamp>) {
3446 if self.write_frontier == *write_frontier {
3447 return; }
3449
3450 let retraction = self.write_frontier_row();
3451 self.write_frontier.clone_from(write_frontier);
3452 let insertion = self.write_frontier_row();
3453
3454 let updates = vec![(retraction, Diff::MINUS_ONE), (insertion, Diff::ONE)];
3455 self.send(IntrospectionType::ReplicaFrontiers, updates);
3456 }
3457
3458 fn write_frontier_row(&self) -> Row {
3460 let write_frontier = self
3461 .write_frontier
3462 .as_option()
3463 .map_or(Datum::Null, |ts| ts.clone().into());
3464 Row::pack_slice(&[
3465 Datum::String(&self.collection_id.to_string()),
3466 Datum::String(&self.replica_id.to_string()),
3467 write_frontier,
3468 ])
3469 }
3470
3471 fn send(&self, introspection_type: IntrospectionType, updates: Vec<(Row, Diff)>) {
3472 let _ = self.introspection_tx.send((introspection_type, updates));
3475 }
3476}
3477
3478impl Drop for ReplicaCollectionIntrospection {
3479 fn drop(&mut self) {
3480 let row = self.write_frontier_row();
3482 let updates = vec![(row, Diff::MINUS_ONE)];
3483 self.send(IntrospectionType::ReplicaFrontiers, updates);
3484 }
3485}
3486
3487fn classify_collection_readiness<'a, I>(
3493 replicas: I,
3494 target_replica_ids: &BTreeSet<ReplicaId>,
3495 reference_replica_ids: &BTreeSet<ReplicaId>,
3496 allowed_lag: Option<Timestamp>,
3497) -> CollectionReadiness
3498where
3499 I: Iterator<Item = (ReplicaId, &'a ReplicaCollectionState)> + Clone,
3500{
3501 let lag = allowed_lag.map(|allowed_lag| {
3502 let mut reference = Antichain::from_elem(Timestamp::MIN);
3503 for (_, state) in replicas
3504 .clone()
3505 .filter(|(id, _)| reference_replica_ids.contains(id))
3506 {
3507 reference.join_assign(&state.output_frontier);
3508 }
3509 (reference, allowed_lag)
3510 });
3511
3512 let mut result = CollectionReadiness::Unhydrated;
3513 for (_, state) in replicas.filter(|(id, _)| target_replica_ids.contains(id)) {
3514 match CollectionReadiness::classify(
3515 state.hydrated(),
3516 &state.output_frontier,
3517 lag.as_ref().map(|(reference, lag)| (reference, *lag)),
3518 ) {
3519 CollectionReadiness::Ready => return CollectionReadiness::Ready,
3520 CollectionReadiness::Lagging { lag } => {
3521 let lag = match result {
3524 CollectionReadiness::Lagging {
3525 lag: Some(previous),
3526 } => Some(previous.min(lag.unwrap_or(u64::MAX))),
3527 _ => lag,
3528 };
3529 result = CollectionReadiness::Lagging { lag };
3530 }
3531 CollectionReadiness::Unhydrated => {}
3532 }
3533 }
3534 result
3535}
3536
3537#[cfg(test)]
3538pub(super) mod tests {
3539 use std::collections::{BTreeMap, BTreeSet};
3540 use std::sync::Arc;
3541
3542 use async_trait::async_trait;
3543 use futures::future::BoxFuture;
3544 use futures::stream::BoxStream;
3545 use mz_compute_types::dyncfgs::{ENABLE_COLUMN_PAGED_BATCHER, ENABLE_MZ_JOIN_CORE};
3546 use mz_dyncfg::{ConfigSet, ConfigUpdates, ConfigVal};
3547 use mz_ore::tracing::OpenTelemetryContext;
3548 use mz_persist_client::stats::{SnapshotPartsStats, SnapshotStats};
3549 use mz_persist_types::{PersistLocation, ShardId};
3550 use mz_repr::{GlobalId, RelationDesc, RelationVersion, Row, Timestamp};
3551 use mz_storage_client::client::TimestamplessUpdateBuilder;
3552 use mz_storage_client::controller::{CollectionDescription, StorageMetadata, StorageTxn};
3553 use mz_storage_client::storage_collections::{CollectionFrontiers, SnapshotCursor};
3554 use mz_storage_types::StorageDiff;
3555 use mz_storage_types::controller::{CollectionMetadata, StorageError};
3556 use mz_storage_types::errors::CollectionMissing;
3557 use mz_storage_types::parameters::StorageParameters;
3558 use mz_storage_types::read_holds::ReadHold;
3559 use mz_storage_types::read_policy::ReadPolicy;
3560 use mz_storage_types::sources::SourceData;
3561 use mz_storage_types::time_dependence::{TimeDependence, TimeDependenceError};
3562 use timely::progress::Antichain;
3563 use tokio::sync::{mpsc, oneshot};
3564 use uuid::Uuid;
3565
3566 use crate::controller::peek_lifecycle::PeekLifecycle;
3567 use crate::controller::{ComputeControllerResponse, PeekNotification};
3568 use crate::protocol::command::{ComputeCommand, InstanceConfig, PeekTarget};
3569 use crate::protocol::response::{PeekError as ProtocolPeekError, PeekResponse};
3570
3571 use super::{
3572 CollectionReadiness, Instance, ReplicaCollectionIntrospection, ReplicaCollectionState,
3573 ReplicaId, classify_collection_readiness,
3574 };
3575
3576 fn ac(ts: u64) -> Antichain<Timestamp> {
3577 Antichain::from_elem(Timestamp::new(ts))
3578 }
3579
3580 fn state(id: ReplicaId, as_of: u64, write: u64, output: u64) -> ReplicaCollectionState {
3581 let (tx, _rx) = mpsc::unbounded_channel();
3582 let introspection =
3583 ReplicaCollectionIntrospection::new(id, GlobalId::User(1), tx, ac(as_of));
3584 let mut state = ReplicaCollectionState::new(None, ac(as_of), introspection, Vec::new());
3585 state.update_write_frontier(ac(write));
3586 state.update_output_frontier(ac(output));
3587 state
3588 }
3589
3590 fn classify(
3591 replicas: &[(ReplicaId, ReplicaCollectionState)],
3592 targets: &[ReplicaId],
3593 references: &[ReplicaId],
3594 lag: Option<Timestamp>,
3595 ) -> CollectionReadiness {
3596 classify_collection_readiness(
3597 replicas.iter().map(|(id, state)| (*id, state)),
3598 &targets.iter().copied().collect::<BTreeSet<_>>(),
3599 &references.iter().copied().collect::<BTreeSet<_>>(),
3600 lag,
3601 )
3602 }
3603
3604 const LAG: Option<Timestamp> = Some(Timestamp::new(60));
3605
3606 #[mz_ore::test]
3610 fn shared_write_does_not_hide_output_lag() {
3611 let reference = ReplicaId::User(1);
3612 let target = ReplicaId::User(2);
3613 let mut replicas = vec![
3614 (reference, state(reference, 100, 10_000, 10_000)),
3615 (target, state(target, 100, 10_000, 101)),
3618 ];
3619 assert_eq!(
3620 classify(&replicas, &[target], &[reference], LAG),
3621 CollectionReadiness::Lagging { lag: Some(9_899) },
3622 );
3623 replicas[1].1.update_output_frontier(ac(9_940));
3624 assert_eq!(
3625 classify(&replicas, &[target], &[reference], LAG),
3626 CollectionReadiness::Ready,
3627 );
3628 }
3629
3630 #[mz_ore::test]
3631 fn refresh_writes_ahead_of_outputs_is_ready() {
3632 let reference = ReplicaId::User(1);
3633 let target = ReplicaId::User(2);
3634 let replicas = vec![
3635 (reference, state(reference, 100, 20_000, 10_000)),
3636 (target, state(target, 100, 20_000, 10_000)),
3637 ];
3638 assert_eq!(
3639 classify(&replicas, &[target], &[reference], LAG),
3640 CollectionReadiness::Ready,
3641 );
3642 }
3643
3644 #[mz_ore::test]
3645 fn furthest_reference_and_bystander_exclusion() {
3646 let trailing = ReplicaId::User(1);
3647 let ahead = ReplicaId::User(2);
3648 let target = ReplicaId::User(3);
3649 let bystander = ReplicaId::User(4);
3650 let replicas = vec![
3651 (trailing, state(trailing, 100, 9_000, 9_000)),
3652 (ahead, state(ahead, 100, 10_000, 10_000)),
3653 (target, state(target, 100, 8_990, 8_990)),
3654 (bystander, state(bystander, 100, 1_000_000, 1_000_000)),
3655 ];
3656 assert_eq!(
3657 classify(&replicas, &[target], &[trailing], LAG),
3658 CollectionReadiness::Ready,
3659 );
3660 assert_eq!(
3661 classify(&replicas, &[target], &[trailing, ahead], LAG),
3662 CollectionReadiness::Lagging { lag: Some(1_010) },
3663 );
3664 }
3665
3666 #[mz_ore::test]
3667 fn one_ready_target_suffices() {
3668 let reference = ReplicaId::User(1);
3669 let unhydrated = ReplicaId::User(2);
3670 let lagging = ReplicaId::User(3);
3671 let ready = ReplicaId::User(4);
3672 let replicas = vec![
3673 (reference, state(reference, 100, 10_000, 10_000)),
3674 (unhydrated, state(unhydrated, 10_000, 10_000, 10_000)),
3678 (lagging, state(lagging, 100, 1_000, 1_000)),
3679 (ready, state(ready, 100, 9_990, 9_990)),
3680 ];
3681 assert_eq!(
3682 classify(&replicas, &[unhydrated, lagging, ready], &[reference], LAG),
3683 CollectionReadiness::Ready,
3684 );
3685 assert_eq!(
3686 classify(&replicas, &[unhydrated, lagging], &[reference], LAG),
3687 CollectionReadiness::Lagging { lag: Some(9_000) },
3688 );
3689 }
3690
3691 #[mz_ore::test]
3692 fn no_lag_gate_is_hydration_only() {
3693 let reference = ReplicaId::User(1);
3694 let target = ReplicaId::User(2);
3695 let replicas = vec![
3696 (reference, state(reference, 100, 10_000, 10_000)),
3697 (target, state(target, 100, 101, 101)),
3698 ];
3699 assert_eq!(
3700 classify(&replicas, &[target], &[reference], None),
3701 CollectionReadiness::Ready,
3702 );
3703 let unhydrated = vec![(target, state(target, 100, 100, 100))];
3704 assert_eq!(
3705 classify(&unhydrated, &[target], &[], None),
3706 CollectionReadiness::Unhydrated,
3707 );
3708 }
3709
3710 #[mz_ore::test]
3711 fn lag_reports_the_closest_hydrated_target() {
3712 let reference = ReplicaId::User(1);
3713 let far = ReplicaId::User(2);
3714 let close = ReplicaId::User(3);
3715 let mut replicas = vec![
3716 (reference, state(reference, 100, 10_000, 10_000)),
3717 (far, state(far, 100, 1_000, 1_000)),
3718 (close, state(close, 100, 9_000, 9_000)),
3719 ];
3720 for _ in 0..2 {
3721 assert_eq!(
3722 classify(&replicas, &[far, close], &[reference], LAG),
3723 CollectionReadiness::Lagging { lag: Some(1_000) },
3724 );
3725 replicas.reverse();
3726 }
3727 }
3728
3729 #[mz_ore::test]
3730 fn completed_reference_requires_completed_target() {
3731 let reference = ReplicaId::User(1);
3732 let target = ReplicaId::User(2);
3733 let mut replicas = vec![
3734 (reference, state(reference, 100, 1_000, 1_000)),
3735 (target, state(target, 100, 1_000, 1_000)),
3736 ];
3737 replicas[0].1.update_output_frontier(Antichain::new());
3738 assert_eq!(
3739 classify(&replicas, &[target], &[reference], Some(Timestamp::new(0))),
3740 CollectionReadiness::Lagging { lag: None },
3741 );
3742 replicas[1].1.update_output_frontier(Antichain::new());
3743 assert_eq!(
3744 classify(&replicas, &[target], &[reference], Some(Timestamp::new(0))),
3745 CollectionReadiness::Ready,
3746 );
3747 }
3748
3749 #[mz_ore::test]
3750 fn no_reference_means_nothing_to_regress() {
3751 let target = ReplicaId::User(1);
3752 let replicas = vec![(target, state(target, 100, 5_000, 5_000))];
3753 assert_eq!(
3754 classify(&replicas, &[target], &[], Some(Timestamp::new(0))),
3755 CollectionReadiness::Ready,
3756 );
3757 assert_eq!(
3758 classify(&replicas, &[target], &[target], Some(Timestamp::new(0))),
3759 CollectionReadiness::Ready,
3760 );
3761 }
3762
3763 #[mz_ore::test]
3764 fn no_targets_is_unhydrated() {
3765 let reference = ReplicaId::User(1);
3766 let replicas = vec![(reference, state(reference, 100, 10_000, 10_000))];
3767 assert_eq!(
3768 classify(&replicas, &[], &[reference], LAG),
3769 CollectionReadiness::Unhydrated,
3770 );
3771 }
3772
3773 fn create_instance_command() -> ComputeCommand {
3774 ComputeCommand::CreateInstance(Box::new(InstanceConfig {
3775 logging: Default::default(),
3776 expiration_offset: None,
3777 peek_stash_persist_location: PersistLocation::new_in_mem(),
3778 arrangement_dictionary_compression: false,
3779 initial_config: Default::default(),
3780 }))
3781 }
3782
3783 fn initial_config(cmd: &ComputeCommand) -> &ConfigUpdates {
3784 match cmd {
3785 ComputeCommand::CreateInstance(config) => &config.initial_config,
3786 other => panic!("expected CreateInstance, got {other:?}"),
3787 }
3788 }
3789
3790 #[mz_ore::test]
3795 fn create_instance_snapshots_instance_wide_dyncfg() {
3796 let dyncfg = ConfigSet::default()
3797 .add(&ENABLE_COLUMN_PAGED_BATCHER)
3798 .add(&ENABLE_MZ_JOIN_CORE);
3799 let mut updates = ConfigUpdates::default();
3800 updates.add(&ENABLE_COLUMN_PAGED_BATCHER, true);
3801 updates.add(&ENABLE_MZ_JOIN_CORE, false);
3802 updates.apply(&dyncfg);
3803
3804 let cmd = Instance::specialize_command_for_replica(
3806 create_instance_command(),
3807 &ConfigUpdates::default(),
3808 &dyncfg,
3809 );
3810 let snapshot = initial_config(&cmd);
3811 assert_eq!(
3812 snapshot.updates.get(ENABLE_COLUMN_PAGED_BATCHER.name()),
3813 Some(&ConfigVal::Bool(true)),
3814 );
3815 assert_eq!(
3816 snapshot.updates.get(ENABLE_MZ_JOIN_CORE.name()),
3817 Some(&ConfigVal::Bool(false)),
3818 );
3819 }
3820
3821 #[mz_ore::test]
3824 fn create_instance_snapshot_applies_replica_override() {
3825 let dyncfg = ConfigSet::default().add(&ENABLE_COLUMN_PAGED_BATCHER);
3826 let mut updates = ConfigUpdates::default();
3827 updates.add(&ENABLE_COLUMN_PAGED_BATCHER, true);
3828 updates.apply(&dyncfg);
3829
3830 let mut override_updates = ConfigUpdates::default();
3831 override_updates.add(&ENABLE_COLUMN_PAGED_BATCHER, false);
3832
3833 let cmd = Instance::specialize_command_for_replica(
3834 create_instance_command(),
3835 &override_updates,
3836 &dyncfg,
3837 );
3838 assert_eq!(
3839 initial_config(&cmd)
3840 .updates
3841 .get(ENABLE_COLUMN_PAGED_BATCHER.name()),
3842 Some(&ConfigVal::Bool(false)),
3843 "replica override should win over the instance-wide value",
3844 );
3845 }
3846
3847 #[mz_ore::test]
3849 fn update_configuration_merges_replica_override() {
3850 let dyncfg = ConfigSet::default().add(&ENABLE_COLUMN_PAGED_BATCHER);
3851
3852 let mut override_updates = ConfigUpdates::default();
3853 override_updates.add(&ENABLE_COLUMN_PAGED_BATCHER, true);
3854
3855 let cmd = Instance::specialize_command_for_replica(
3856 ComputeCommand::UpdateConfiguration(Box::new(Default::default())),
3857 &override_updates,
3858 &dyncfg,
3859 );
3860 match cmd {
3861 ComputeCommand::UpdateConfiguration(params) => assert_eq!(
3862 params
3863 .dyncfg_updates
3864 .updates
3865 .get(ENABLE_COLUMN_PAGED_BATCHER.name()),
3866 Some(&ConfigVal::Bool(true)),
3867 ),
3868 other => panic!("expected UpdateConfiguration, got {other:?}"),
3869 }
3870 }
3871
3872 #[derive(Debug)]
3873 struct UnusedStorage;
3874
3875 #[async_trait]
3876 impl mz_storage_client::storage_collections::StorageCollections for UnusedStorage {
3877 async fn initialize_state(
3878 &self,
3879 _txn: &mut (dyn StorageTxn + Send),
3880 _init_ids: BTreeSet<GlobalId>,
3881 ) -> Result<(), StorageError> {
3882 unimplemented!()
3883 }
3884
3885 fn update_parameters(&self, _config_params: StorageParameters) {
3886 unimplemented!()
3887 }
3888
3889 fn collection_metadata(
3890 &self,
3891 _id: GlobalId,
3892 ) -> Result<CollectionMetadata, CollectionMissing> {
3893 unimplemented!()
3894 }
3895
3896 fn active_collection_metadatas(&self) -> Vec<(GlobalId, CollectionMetadata)> {
3897 unimplemented!()
3898 }
3899
3900 fn collections_frontiers(
3901 &self,
3902 _ids: Vec<GlobalId>,
3903 ) -> Result<Vec<CollectionFrontiers>, CollectionMissing> {
3904 unimplemented!("peek routing must not access storage")
3905 }
3906
3907 fn active_collection_frontiers(&self) -> Vec<CollectionFrontiers> {
3908 unimplemented!()
3909 }
3910
3911 fn check_exists(&self, _id: GlobalId) -> Result<(), StorageError> {
3912 unimplemented!()
3913 }
3914
3915 async fn snapshot_stats(
3916 &self,
3917 _id: GlobalId,
3918 _as_of: Antichain<Timestamp>,
3919 ) -> Result<SnapshotStats, StorageError> {
3920 unimplemented!()
3921 }
3922
3923 async fn snapshot_parts_stats(
3924 &self,
3925 _id: GlobalId,
3926 _as_of: Antichain<Timestamp>,
3927 ) -> BoxFuture<'static, Result<SnapshotPartsStats, StorageError>> {
3928 unimplemented!()
3929 }
3930
3931 fn snapshot(
3932 &self,
3933 _id: GlobalId,
3934 _as_of: Timestamp,
3935 ) -> BoxFuture<'static, Result<Vec<(Row, StorageDiff)>, StorageError>> {
3936 unimplemented!()
3937 }
3938
3939 async fn snapshot_latest(&self, _id: GlobalId) -> Result<Vec<Row>, StorageError> {
3940 unimplemented!()
3941 }
3942
3943 fn snapshot_cursor(
3944 &self,
3945 _id: GlobalId,
3946 _as_of: Timestamp,
3947 ) -> BoxFuture<'static, Result<SnapshotCursor, StorageError>> {
3948 unimplemented!()
3949 }
3950
3951 fn snapshot_and_stream(
3952 &self,
3953 _id: GlobalId,
3954 _as_of: Timestamp,
3955 ) -> BoxFuture<
3956 'static,
3957 Result<BoxStream<'static, (SourceData, Timestamp, StorageDiff)>, StorageError>,
3958 > {
3959 unimplemented!()
3960 }
3961
3962 fn create_update_builder(
3963 &self,
3964 _id: GlobalId,
3965 ) -> BoxFuture<
3966 'static,
3967 Result<TimestamplessUpdateBuilder<SourceData, (), StorageDiff>, StorageError>,
3968 > {
3969 unimplemented!()
3970 }
3971
3972 async fn prepare_state(
3973 &self,
3974 _txn: &mut (dyn StorageTxn + Send),
3975 _ids_to_add: BTreeSet<GlobalId>,
3976 _ids_to_drop: BTreeSet<GlobalId>,
3977 _ids_to_register: BTreeMap<GlobalId, ShardId>,
3978 ) -> Result<(), StorageError> {
3979 unimplemented!()
3980 }
3981
3982 async fn create_collections_for_bootstrap(
3983 &self,
3984 _storage_metadata: &StorageMetadata,
3985 _register_ts: Option<Timestamp>,
3986 _collections: Vec<(GlobalId, CollectionDescription)>,
3987 _migrated_storage_collections: &BTreeSet<GlobalId>,
3988 ) -> Result<(), StorageError> {
3989 unimplemented!()
3990 }
3991
3992 async fn alter_table_desc(
3993 &self,
3994 _existing_collection: GlobalId,
3995 _new_collection: GlobalId,
3996 _new_desc: RelationDesc,
3997 _expected_version: RelationVersion,
3998 ) -> Result<(), StorageError> {
3999 unimplemented!()
4000 }
4001
4002 fn drop_collections_unvalidated(
4003 &self,
4004 _storage_metadata: &StorageMetadata,
4005 _identifiers: Vec<GlobalId>,
4006 ) {
4007 unimplemented!()
4008 }
4009
4010 fn set_read_policies(&self, _policies: Vec<(GlobalId, ReadPolicy)>) {
4011 unimplemented!()
4012 }
4013
4014 fn acquire_read_holds(
4015 &self,
4016 _desired_holds: Vec<GlobalId>,
4017 ) -> Result<Vec<ReadHold>, CollectionMissing> {
4018 unimplemented!("peek routing must not access storage")
4019 }
4020
4021 fn determine_time_dependence(
4022 &self,
4023 _id: GlobalId,
4024 ) -> Result<Option<TimeDependence>, TimeDependenceError> {
4025 unimplemented!()
4026 }
4027
4028 fn dump(&self) -> Result<serde_json::Value, anyhow::Error> {
4029 unimplemented!()
4030 }
4031 }
4032
4033 pub(in crate::controller) fn peek_test_instance()
4034 -> (Instance, mpsc::UnboundedReceiver<ComputeControllerResponse>) {
4035 let registry = mz_ore::metrics::MetricsRegistry::new();
4036 let metrics = crate::metrics::ComputeControllerMetrics::new(
4037 ®istry,
4038 mz_cluster_client::metrics::ControllerMetrics::new(®istry),
4039 )
4040 .for_instance(mz_compute_types::ComputeInstanceId::User(1));
4041 let (_, command_rx) = mpsc::unbounded_channel();
4042 let (response_tx, response_rx) = mpsc::unbounded_channel();
4043 let (introspection_tx, _) = mpsc::unbounded_channel();
4044 let now = mz_ore::now::SYSTEM_TIME.clone();
4045 let instance = Instance::new(
4046 &mz_build_info::DUMMY_BUILD_INFO,
4047 Arc::new(UnusedStorage),
4048 PersistLocation::new_in_mem(),
4049 Vec::new(),
4050 metrics,
4051 now.clone(),
4052 mz_cluster_client::WallclockLagFn::new(now),
4053 Arc::new(mz_dyncfgs::all_dyncfgs()),
4054 command_rx,
4055 response_tx,
4056 Arc::new(|_, _| Ok(())),
4057 introspection_tx,
4058 false,
4059 );
4060 (instance, response_rx)
4061 }
4062
4063 fn issue_peek(
4064 instance: &mut Instance,
4065 target: Option<ReplicaId>,
4066 lifecycle_owned: bool,
4067 ) -> (
4068 Uuid,
4069 oneshot::Receiver<PeekResponse>,
4070 mpsc::UnboundedReceiver<PeekNotification>,
4071 ) {
4072 let uuid = Uuid::new_v4();
4073 let id = GlobalId::User(1);
4074 let (result_tx, result_rx) = oneshot::channel();
4075 let (retire_tx, retire_rx) = mpsc::unbounded_channel();
4076 let lifecycle = lifecycle_owned.then(|| {
4077 Arc::new(PeekLifecycle::new(move |outcome| {
4078 retire_tx.send(outcome).unwrap();
4079 }))
4080 });
4081 let issue = || {
4082 instance.peek(
4083 PeekTarget::Index { id },
4084 None,
4085 uuid,
4086 Timestamp::MIN,
4087 RelationDesc::empty(),
4088 mz_expr::RowSetFinishing::trivial(0),
4089 mz_expr::SafeMfpPlan::from_mfp(mz_expr::MapFilterProject::new(0)),
4090 ReadHold::new(id, ac(0), Arc::new(|_, _| Ok(()))),
4091 target,
4092 result_tx,
4093 lifecycle.clone(),
4094 )
4095 };
4096 if let Some(lifecycle) = &lifecycle {
4097 assert_eq!(
4098 lifecycle
4099 .issue(issue, |_| panic!("completion must not cancel lifecycle"))
4100 .unwrap(),
4101 None
4102 );
4103 } else {
4104 issue().unwrap();
4105 }
4106 (uuid, result_rx, retire_rx)
4107 }
4108
4109 fn assert_peek_routing(
4110 lifecycle_owned: bool,
4111 uuid: Uuid,
4112 expected: PeekNotification,
4113 retired: &mut mpsc::UnboundedReceiver<PeekNotification>,
4114 coordinator: &mut mpsc::UnboundedReceiver<ComputeControllerResponse>,
4115 ) {
4116 if lifecycle_owned {
4117 assert_eq!(retired.try_recv().unwrap(), expected);
4118 } else {
4119 match coordinator.try_recv().unwrap() {
4120 ComputeControllerResponse::PeekNotification(id, notification, _) => {
4121 assert_eq!(id, uuid);
4122 assert_eq!(notification, expected);
4123 }
4124 other => panic!("expected peek notification, got {other:?}"),
4125 }
4126 }
4127 assert!(retired.try_recv().is_err());
4128 assert!(coordinator.try_recv().is_err());
4129 }
4130
4131 #[mz_ore::test]
4132 fn peek_response_routes_retirement_and_result() {
4133 for lifecycle_owned in [false, true] {
4134 let (mut instance, mut coordinator) = peek_test_instance();
4135 let (uuid, mut result, mut retired) = issue_peek(&mut instance, None, lifecycle_owned);
4136 let response = PeekResponse::Rows(Vec::new());
4137 instance.handle_peek_response(
4138 uuid,
4139 response.clone(),
4140 OpenTelemetryContext::empty(),
4141 ReplicaId::User(1),
4142 );
4143 assert_eq!(result.try_recv().unwrap(), response);
4144 assert!(!instance.peeks.contains_key(&uuid));
4145 instance.handle_peek_response(
4147 uuid,
4148 PeekResponse::Canceled,
4149 OpenTelemetryContext::empty(),
4150 ReplicaId::User(2),
4151 );
4152 assert_peek_routing(
4153 lifecycle_owned,
4154 uuid,
4155 PeekNotification::Success {
4156 rows: 0,
4157 result_size: 0,
4158 },
4159 &mut retired,
4160 &mut coordinator,
4161 );
4162 }
4163 }
4164
4165 #[mz_ore::test]
4166 fn cancel_peek_routes_retirement_and_preserves_result_reason() {
4167 for lifecycle_owned in [false, true] {
4168 for reason in [
4169 PeekResponse::Canceled,
4170 PeekResponse::Error(ProtocolPeekError::unstructured("dependency dropped")),
4171 ] {
4172 let (mut instance, mut coordinator) = peek_test_instance();
4173 let (uuid, mut result, mut retired) =
4174 issue_peek(&mut instance, None, lifecycle_owned);
4175 instance.cancel_peek(uuid, reason.clone());
4176 assert_eq!(result.try_recv().unwrap(), reason);
4177 assert!(!instance.peeks.contains_key(&uuid));
4178 instance.cancel_peek(uuid, PeekResponse::Canceled);
4179 instance.handle_peek_response(
4180 uuid,
4181 PeekResponse::Rows(Vec::new()),
4182 OpenTelemetryContext::empty(),
4183 ReplicaId::User(1),
4184 );
4185 assert_peek_routing(
4186 lifecycle_owned,
4187 uuid,
4188 PeekNotification::Canceled,
4189 &mut retired,
4190 &mut coordinator,
4191 );
4192 }
4193 }
4194 }
4195
4196 #[mz_ore::test(tokio::test)]
4197 async fn targeted_replica_removal_routes_failure_only_to_targeted_peeks() {
4198 for lifecycle_owned in [false, true] {
4199 let (mut instance, mut coordinator) = peek_test_instance();
4200 let target = ReplicaId::User(1);
4201 let other = ReplicaId::User(2);
4202 for replica in [target, other] {
4203 instance
4204 .add_replica(
4205 replica,
4206 super::ReplicaConfig {
4207 location: mz_cluster_client::client::ClusterReplicaLocation {
4208 ctl_addrs: Vec::new(),
4209 },
4210 logging: Default::default(),
4211 grpc_client: Default::default(),
4212 expiration_offset: None,
4213 arrangement_dictionary_compression: false,
4214 },
4215 None,
4216 Default::default(),
4217 )
4218 .unwrap();
4219 }
4220 let (uuid, mut result, mut retired) =
4221 issue_peek(&mut instance, Some(target), lifecycle_owned);
4222 let (other_uuid, mut other_result, mut other_retired) =
4223 issue_peek(&mut instance, Some(other), lifecycle_owned);
4224 let (untargeted_uuid, mut untargeted_result, mut untargeted_retired) =
4225 issue_peek(&mut instance, None, lifecycle_owned);
4226 instance.handle_peek_response(
4227 uuid,
4228 PeekResponse::Rows(Vec::new()),
4229 OpenTelemetryContext::empty(),
4230 other,
4231 );
4232 assert!(matches!(
4233 result.try_recv(),
4234 Err(oneshot::error::TryRecvError::Empty)
4235 ));
4236 assert!(retired.try_recv().is_err());
4237 assert!(coordinator.try_recv().is_err());
4238
4239 instance.remove_replica(target).unwrap();
4240 assert_eq!(
4241 result.try_recv().unwrap(),
4242 PeekResponse::Error(ProtocolPeekError::unstructured(
4243 super::ERROR_TARGET_REPLICA_FAILED
4244 ))
4245 );
4246 assert!(!instance.peeks.contains_key(&uuid));
4247 assert!(instance.peeks.contains_key(&other_uuid));
4248 assert!(instance.peeks.contains_key(&untargeted_uuid));
4249 assert!(matches!(
4250 other_result.try_recv(),
4251 Err(oneshot::error::TryRecvError::Empty)
4252 ));
4253 assert!(matches!(
4254 untargeted_result.try_recv(),
4255 Err(oneshot::error::TryRecvError::Empty)
4256 ));
4257 assert!(other_retired.try_recv().is_err());
4258 assert!(untargeted_retired.try_recv().is_err());
4259 instance.handle_peek_response(
4260 uuid,
4261 PeekResponse::Rows(Vec::new()),
4262 OpenTelemetryContext::empty(),
4263 target,
4264 );
4265 assert_peek_routing(
4266 lifecycle_owned,
4267 uuid,
4268 PeekNotification::Error(super::ERROR_TARGET_REPLICA_FAILED.into()),
4269 &mut retired,
4270 &mut coordinator,
4271 );
4272 }
4273 }
4274}