Skip to main content

mz_compute_client/controller/
instance.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! A controller for a compute instance.
11
12use 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
119/// A command sent to an [`Instance`] task.
120pub(super) type Command = Box<dyn FnOnce(&mut Instance) + Send>;
121
122/// A response from a replica, composed of a replica ID, the replica's current epoch, and the
123/// compute response itself.
124pub(super) type ReplicaResponse = (ReplicaId, u64, ComputeResponse);
125
126/// The state we keep for a compute instance.
127pub(super) struct Instance {
128    /// Build info for spawning replicas
129    build_info: &'static BuildInfo,
130    /// A handle providing access to storage collections.
131    storage_collections: StorageCollections,
132    /// Whether instance initialization has been completed.
133    initialized: bool,
134    /// Whether this instance is in read-only mode.
135    ///
136    /// When in read-only mode, this instance will not update persistent state, such as
137    /// wallclock lag introspection.
138    read_only: bool,
139    /// The workload class of this instance.
140    ///
141    /// This is currently only used to annotate metrics.
142    workload_class: Option<String>,
143    /// The replicas of this compute instance.
144    replicas: BTreeMap<ReplicaId, ReplicaState>,
145    /// Currently installed compute collections.
146    ///
147    /// New entries are added for all collections exported from dataflows created through
148    /// [`Instance::create_dataflow`].
149    ///
150    /// Entries are removed by [`Instance::cleanup_collections`]. See that method's documentation
151    /// about the conditions for removing collection state.
152    collections: BTreeMap<GlobalId, CollectionState>,
153    /// IDs of log sources maintained by this compute instance.
154    log_sources: BTreeMap<LogVariant, GlobalId>,
155    /// Currently outstanding peeks.
156    ///
157    /// New entries are added for all peeks initiated through [`Instance::peek`].
158    ///
159    /// The entry for a peek is only removed once all replicas have responded to the peek. This is
160    /// currently required to ensure all replicas have stopped reading from the peeked collection's
161    /// inputs before we allow them to compact. database-issues#4822 tracks changing this so we only have to wait
162    /// for the first peek response.
163    peeks: BTreeMap<Uuid, PendingPeek>,
164    /// Currently in-progress subscribes.
165    ///
166    /// New entries are added for all subscribes exported from dataflows created through
167    /// [`Instance::create_dataflow`].
168    ///
169    /// The entry for a subscribe is removed once at least one replica has reported the subscribe
170    /// to have advanced to the empty frontier or to have been dropped, implying that no further
171    /// updates will be emitted for this subscribe.
172    ///
173    /// Note that subscribes are tracked both in `collections` and `subscribes`. `collections`
174    /// keeps track of the subscribe's upper and since frontiers and ensures appropriate read holds
175    /// on the subscribe's input. `subscribes` is only used to track which updates have been
176    /// emitted, to decide if new ones should be emitted or suppressed.
177    subscribes: BTreeMap<GlobalId, ActiveSubscribe>,
178    /// Tracks all in-progress COPY TOs.
179    ///
180    /// New entries are added for all s3 oneshot sinks (corresponding to a COPY TO) exported from
181    /// dataflows created through [`Instance::create_dataflow`].
182    ///
183    /// The entry for a copy to is removed once at least one replica has finished
184    /// or the exporting collection is dropped.
185    copy_tos: BTreeSet<GlobalId>,
186    /// The command history, used when introducing new replicas or restarting existing replicas.
187    history: ComputeCommandHistory<UIntGauge>,
188    /// Receiver for commands to be executed.
189    command_rx: mpsc::UnboundedReceiver<Command>,
190    /// Sender for responses to be delivered.
191    response_tx: mpsc::UnboundedSender<ComputeControllerResponse>,
192    /// Sender for introspection updates to be recorded.
193    introspection_tx: mpsc::UnboundedSender<IntrospectionUpdates>,
194    /// The registry the controller uses to report metrics.
195    metrics: InstanceMetrics,
196    /// Dynamic system configuration.
197    dyncfg: Arc<ConfigSet>,
198
199    /// The persist location where we can stash large peek results.
200    peek_stash_persist_location: PersistLocation,
201
202    /// A function that produces the current wallclock time.
203    now: NowFn,
204    /// A function that computes the lag between the given time and wallclock time.
205    wallclock_lag: WallclockLagFn<Timestamp>,
206    /// The last time wallclock lag introspection was recorded.
207    wallclock_lag_last_recorded: DateTime<Utc>,
208
209    /// Sender for updates to collection read holds.
210    ///
211    /// Copies of this sender are given to [`ReadHold`]s that are created in
212    /// [`CollectionState::new`].
213    read_hold_tx: read_holds::ChangeTx,
214    /// A sender for responses from replicas.
215    replica_tx: mz_ore::channel::InstrumentedUnboundedSender<ReplicaResponse, IntCounter>,
216    /// A receiver for responses from replicas.
217    replica_rx: mz_ore::channel::InstrumentedUnboundedReceiver<ReplicaResponse, IntCounter>,
218}
219
220impl Instance {
221    /// Acquire a handle to the collection state associated with `id`.
222    fn collection(&self, id: GlobalId) -> Result<&CollectionState, CollectionMissing> {
223        self.collections.get(&id).ok_or(CollectionMissing(id))
224    }
225
226    /// Acquire a mutable handle to the collection state associated with `id`.
227    fn collection_mut(&mut self, id: GlobalId) -> Result<&mut CollectionState, CollectionMissing> {
228        self.collections.get_mut(&id).ok_or(CollectionMissing(id))
229    }
230
231    /// Acquire a handle to the collection state associated with `id`.
232    ///
233    /// # Panics
234    ///
235    /// Panics if the identified collection does not exist.
236    fn expect_collection(&self, id: GlobalId) -> &CollectionState {
237        self.collections.get(&id).expect("collection must exist")
238    }
239
240    /// Acquire a mutable handle to the collection state associated with `id`.
241    ///
242    /// # Panics
243    ///
244    /// Panics if the identified collection does not exist.
245    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    /// Returns an iterator over replicas that host the given collection.
256    ///
257    /// For replica-targeted collections, this returns only the target replica.
258    /// For non-targeted collections, this returns all replicas.
259    ///
260    /// Returns `Err` if the collection does not exist.
261    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    /// Add a collection to the instance state.
273    ///
274    /// # Panics
275    ///
276    /// Panics if a collection with the same ID exists already.
277    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        // Add global collection state.
292        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 the collection is write-only, clear its read policy to reflect that.
317        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        // Add per-replica collection state.
326        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        // Remove per-replica collection state.
336        for replica in self.replicas.values_mut() {
337            replica.remove_collection(id);
338        }
339
340        // Remove global collection state.
341        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        // Add per-replica collection state.
366        let mut shutdown_input = None;
367        for (collection_id, collection) in &self.collections {
368            // Skip log collections not maintained by this replica,
369            // and collections targeted at a different replica.
370            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                // For log collections, we don't send a `CreateDataflow` command to the replica, so
378                // it doesn't know which as-of the controler chose and defaults to the minimum
379                // frontier instead. We need to initialize the controller-side tracking with the
380                // same frontier, to avoid observing regressions in the reported frontiers.
381                Antichain::from_elem(Timestamp::MIN)
382            } else {
383                collection.read_frontier().to_owned()
384            };
385
386            // Cloning a `ReadHold` fails when its issuer has hung up. For these holds the issuer
387            // is the `StorageCollections`, which doesn't hang up as long as the `Instance` exists,
388            // except during process shutdown, when the tokio runtime drops tasks in arbitrary
389            // order. In that case there is no way of correctly initializing the per-replica
390            // collection state, so we give up. We still add the replica itself, to keep the
391            // bookkeeping consistent with the controller's, and then signal the unrecoverable
392            // error to the caller, which shuts the instance down.
393            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    /// Enqueue the given response for delivery to the controller clients.
425    fn deliver_response(&self, response: ComputeControllerResponse) {
426        // Failure to send means the `ComputeController` has been dropped and doesn't care about
427        // responses anymore.
428        let _ = self.response_tx.send(response);
429    }
430
431    /// Enqueue the given introspection updates for recording.
432    fn deliver_introspection_updates(&self, type_: IntrospectionType, updates: Vec<(Row, Diff)>) {
433        // Failure to send means the `ComputeController` has been dropped and doesn't care about
434        // introspection updates anymore.
435        let _ = self.introspection_tx.send((type_, updates));
436    }
437
438    /// Returns whether the identified replica exists.
439    fn replica_exists(&self, id: ReplicaId) -> bool {
440        self.replicas.contains_key(&id)
441    }
442
443    /// Return the IDs of pending peeks targeting the specified replica.
444    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    /// Return the IDs of in-progress subscribes targeting the specified replica.
455    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    /// Update introspection with the current collection frontiers.
463    ///
464    /// We could also do this directly in response to frontier changes, but doing it periodically
465    /// lets us avoid emitting some introspection updates that can be consolidated (e.g. a write
466    /// frontier updated immediately followed by a read frontier update).
467    ///
468    /// This method is invoked by `ComputeController::maintain`, which we expect to be called once
469    /// per second during normal operation.
470    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    /// Refresh the controller state metrics for this instance.
487    ///
488    /// We could also do state metric updates directly in response to state changes, but that would
489    /// mean littering the code with metric update calls. Encapsulating state metric maintenance in
490    /// a single method is less noisy.
491    ///
492    /// This method is invoked by `ComputeController::maintain`, which we expect to be called once
493    /// per second during normal operation.
494    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    /// Refresh the wallclock lag introspection and metrics with the current lag values.
527    ///
528    /// This method produces wallclock lag metrics of two different shapes:
529    ///
530    /// * Histories: For each replica and each collection, we measure the lag of the write frontier
531    ///   behind the wallclock time every second. Every minute we emit the maximum lag observed
532    ///   over the last minute, together with the current time.
533    /// * Histograms: For each collection, we measure the lag of the write frontier behind
534    ///   wallclock time every second. Every minute we emit all lags observed over the last minute,
535    ///   together with the current histogram period.
536    ///
537    /// Histories are emitted to both Mz introspection and Prometheus, histograms only to
538    /// introspection. We treat lags of unreadable collections (i.e. collections that contain no
539    /// readable times) as undefined and set them to NULL in introspection and `u64::MAX` in
540    /// Prometheus.
541    ///
542    /// This method is invoked by `ComputeController::maintain`, which we expect to be called once
543    /// per second during normal operation.
544    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        // For collections that sink into storage, we need to ask the storage controller to know
558        // whether they're currently readable.
559        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        // First, iterate over all collections and collect histogram measurements.
570        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        // Second, iterate over all per-replica collections and collect history measurements.
593        for replica in self.replicas.values_mut() {
594            for (id, collection) in &mut replica.collections {
595                // A per-replica collection is considered readable in the context of lag
596                // measurement if either:
597                //  (a) it sinks into a storage collection that is readable
598                //  (b) it is hydrated
599                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                    // No way to specify values as undefined in Prometheus metrics, so we use the
614                    // maximum value instead.
615                    let secs = lag.unwrap_seconds_or(u64::MAX);
616                    metrics.wallclock_lag.observe(secs);
617                };
618            }
619        }
620
621        // Record lags to persist, if it's time.
622        self.maybe_record_wallclock_lag();
623    }
624
625    /// Produce new wallclock lag introspection updates, provided enough time has passed since the
626    /// last recording.
627    //
628    /// We emit new introspection updates if the system time has passed into a new multiple of the
629    /// recording interval (typically 1 minute) since the last refresh. The storage controller uses
630    /// the same approach, ensuring that both controllers commit their lags at roughly the same
631    /// time, avoiding confusion caused by inconsistencies.
632    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    /// Returns `true` if the given collection is hydrated on at least one
711    /// replica.
712    ///
713    /// This also returns `true` in case this cluster does not have any
714    /// replicas that host the given collection.
715    #[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    /// Returns `true` if each non-transient, non-excluded collection is *ready* on at
731    /// least one of the target replicas.
732    ///
733    /// A target must be hydrated and, when `allowed_lag` is `Some`, its output
734    /// frontier must be within that allowance of the furthest output frontier
735    /// among the collection's hosting `reference_replica_ids`. No reference
736    /// replicas means hydration suffices. An empty reference frontier requires
737    /// the target to complete too. `None` checks only hydration.
738    ///
739    /// Hydration alone only guarantees output past the installation as-of, not
740    /// that the replica has replayed subsequent updates. Output frontiers measure
741    /// that replay. MV write frontiers can instead reflect another replica's
742    /// writes to the shared shard, or jump ahead to the next `REFRESH` time.
743    ///
744    /// Zero-replica clusters return `true`.
745    #[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            // `replicas_hosting` cannot fail here because `collections_iter`
780            // only yields collections that exist.
781            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                // We collect all not-ready collections instead of breaking out
794                // early, so that the log below names every collection the caller
795                // is waiting on, and why.
796                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            // Callers poll this on the cluster controller's reconcile tick,
812            // which tests turn down to milliseconds, so this is deliberately
813            // one line per call rather than one per collection.
814            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    /// Clean up collection state that is not needed anymore.
829    ///
830    /// Three conditions need to be true before we can remove state for a collection:
831    ///
832    ///  1. A client must have explicitly dropped the collection. If that is not the case, clients
833    ///     can still reasonably assume that the controller knows about the collection and can
834    ///     answer queries about it.
835    ///  2. There must be no outstanding read capabilities on the collection. As long as someone
836    ///     still holds read capabilities on a collection, we need to keep it around to be able
837    ///     to properly handle downgrading of said capabilities.
838    ///  3. All replica frontiers for the collection must have advanced to the empty frontier.
839    ///     Advancement to the empty frontiers signals that replicas are done computing the
840    ///     collection and that they won't send more `ComputeResponse`s for it. As long as we might
841    ///     receive responses for a collection we want to keep it around to be able to validate and
842    ///     handle these responses.
843    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    /// Returns the state of the [`Instance`] formatted as JSON.
863    ///
864    /// The returned value is not guaranteed to be stable and may change at any point in time.
865    #[mz_ore::instrument(level = "debug")]
866    pub fn dump(&self) -> Result<serde_json::Value, anyhow::Error> {
867        // Note: We purposefully use the `Debug` formatting for the value of all fields in the
868        // returned object as a tradeoff between usability and stability. `serde_json` will fail
869        // to serialize an object if the keys aren't strings, so `Debug` formatting the values
870        // prevents a future unrelated change from silently breaking this method.
871
872        // Destructure `self` here so we don't forget to consider dumping newly added fields.
873        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    /// Reports the current write frontier for the identified compute collection.
933    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            // The nonce is protocol iteration-specific and will be set in
1009            // `ReplicaTask::specialize_command`.
1010            nonce: Uuid::default(),
1011        });
1012
1013        let instance_config = InstanceConfig {
1014            peek_stash_persist_location: self.peek_stash_persist_location.clone(),
1015            // The remaining fields are replica-specific and will be set in
1016            // `ReplicaTask::specialize_command` (logging, expiration, dictionary compression) and
1017            // `Instance::specialize_command_for_replica` (the initial config snapshot).
1018            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    /// Update instance configuration.
1041    #[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    /// Marks the end of any initialization commands.
1052    ///
1053    /// Intended to be called by `Controller`, rather than by other code.
1054    /// Calling this method repeatedly has no effect.
1055    #[mz_ore::instrument(level = "debug")]
1056    pub fn initialization_complete(&mut self) {
1057        // The compute protocol requires that `InitializationComplete` is sent only once.
1058        if !self.initialized {
1059            self.send(ComputeCommand::InitializationComplete);
1060            self.initialized = true;
1061        }
1062    }
1063
1064    /// Allows collections to affect writes to external systems (persist).
1065    ///
1066    /// Calling this method repeatedly has no effect.
1067    #[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        // Do not send redundant allow-writes commands.
1072        if !collection.read_only {
1073            return Ok(());
1074        }
1075
1076        // Don't send allow-writes for collections that are not installed.
1077        let as_of = collection.read_frontier();
1078
1079        // If the collection has an empty `as_of`, it was either never installed on the replica or
1080        // has since been dropped. In either case the replica does not expect any commands for it.
1081        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    /// Shut down this instance.
1092    ///
1093    /// This method asserts that the instance has no replicas left. It exists to help
1094    /// us find bugs where the client drops a compute instance that still has replicas
1095    /// installed, and later assumes that said replicas still exist.
1096    ///
1097    /// # Panics
1098    ///
1099    /// Soft-panics if the compute instance still has active replicas.
1100    #[mz_ore::instrument(level = "debug")]
1101    pub fn shutdown(&mut self) {
1102        // Taking the `command_rx` ensures that the [`Instance::run`] loop terminates.
1103        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    /// Terminate the [`Instance::run`] loop, causing the instance task to shut down.
1114    ///
1115    /// Unlike [`Instance::shutdown`], this does not assert that the instance has no replicas
1116    /// left. We use it to react to unrecoverable errors that can only occur during process
1117    /// shutdown, such as a storage read hold issuer hanging up while we rehydrate a replica.
1118    fn initiate_shutdown(&mut self) {
1119        // Replacing `command_rx` with a fresh, sender-less channel makes the next `recv` in
1120        // [`Instance::run`] return `None`, terminating the loop.
1121        let (_tx, rx) = mpsc::unbounded_channel();
1122        self.command_rx = rx;
1123    }
1124
1125    /// Sends a command to replicas of this instance.
1126    #[mz_ore::instrument(level = "debug")]
1127    fn send(&mut self, cmd: ComputeCommand) {
1128        // Record the command so that new replicas can be brought up to speed.
1129        // We record the *base* (un-specialized) command, so that the per-replica
1130        // dyncfg overrides are re-applied at replay time in `add_replica` rather
1131        // than baked into the shared history.
1132        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    /// Specializes a command for a specific replica by merging that replica's dyncfg override into
1156    /// its configuration. For `UpdateConfiguration` the override is merged into the update. For
1157    /// `CreateInstance` the current dyncfg, with the override applied on top, is captured as the
1158    /// initial config snapshot. All other commands are returned unchanged.
1159    ///
1160    /// The snapshot is built here, rather than baked into the history, so it reflects the dyncfg
1161    /// and override values current at the time the command is sent or replayed to the replica.
1162    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    /// Replaces the dyncfg overrides of this instance's replicas. A replica absent from
1184    /// `overrides` has its override cleared. Callers should follow this with a configuration push
1185    /// (e.g. `update_configuration`) so that existing replicas observe the new overrides.
1186    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    /// Determine the target replica for a compute command. Retrieves the
1196    /// collection named by the command, and returns the target replica if
1197    /// it is set, and None if not set, or the command doesn't name a collection.
1198    ///
1199    /// Panics if a create-dataflow command names collections that have different
1200    /// target replicas. It is an error to construct such an object and would
1201    /// indicate a bug in [`Self::create_dataflow`].
1202    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            // Skip Peek as we don't allow replica-targeted indexes.
1222            ComputeCommand::Peek(_)
1223            | ComputeCommand::Hello { .. }
1224            | ComputeCommand::CreateInstance(_)
1225            | ComputeCommand::InitializationComplete
1226            | ComputeCommand::UpdateConfiguration(_)
1227            | ComputeCommand::CancelPeek { .. } => None,
1228        }
1229    }
1230
1231    /// Add a new instance replica, by ID.
1232    ///
1233    /// `dyncfg_override` holds the replica's scoped parameters, which every configuration
1234    /// command sent or replayed to the replica carries.
1235    #[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        // Take this opportunity to clean up the history we should present.
1262        self.history.reduce();
1263
1264        // Advance the uppers of source imports
1265        self.history.update_source_uppers(&self.storage_collections);
1266
1267        // Replay the commands at the client, creating new dataflow identifiers.
1268        for command in self.history.iter() {
1269            // Skip `CreateDataflow` commands targeted at different replicas.
1270            if let Some(target_replica) = self.target_replica(command)
1271                && target_replica != id
1272            {
1273                continue;
1274            }
1275
1276            // Re-apply this replica's dyncfg override to replayed config commands, and rebuild the
1277            // create-instance snapshot from the current dyncfg.
1278            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                // We swallow the error here. On the next send, we will fail again, and
1285                // restart the connection as well as this rehydration.
1286                tracing::warn!("Replica {:?} connection terminated during hydration", id);
1287                break;
1288            }
1289        }
1290
1291        // Add replica to tracked state.
1292        if self
1293            .add_replica_state(id, client, config, epoch, dyncfg_override)
1294            .is_err()
1295        {
1296            // A storage read hold issuer hung up, which only happens during process shutdown.
1297            // There is no way to correctly bring up the replica anymore, so we shut the instance
1298            // down instead of running on with half-initialized replica state. `add_replica_state`
1299            // has already logged the details and inserted the replica to keep our bookkeeping
1300            // consistent with the controller's.
1301            self.initiate_shutdown();
1302        }
1303
1304        Ok(())
1305    }
1306
1307    /// Remove an existing instance replica, by ID.
1308    #[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        // Before dropping the replica state (and the contained input read holds), log read holds
1313        // that are the last line of defense against compaction of a dataflow's storage inputs. If
1314        // the corresponding global read hold has already been released, dropping the per-replica
1315        // read hold will allow compaction, which can cause the replica to panic trying to install
1316        // the dataflow.
1317        //
1318        // This exists primarily to help diagnose incidents-and-escalations#39.
1319        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        // Subscribes targeting this replica either won't be served anymore (if the replica is
1341        // dropped) or might produce inconsistent output (if the target collection is an
1342        // introspection index). We produce an error to inform upstream.
1343        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        // Peeks targeting this replica might not be served anymore (if the replica is dropped).
1358        // If the replica has failed it might come back and respond to the peek later, but it still
1359        // seems like a good idea to cancel the peek to inform the caller about the failure. This
1360        // is consistent with how we handle targeted subscribes above.
1361        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    /// Rehydrate the given instance replica.
1384    ///
1385    /// # Panics
1386    ///
1387    /// Panics if the specified replica does not exist.
1388    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        // NOTE: Between `remove_replica` and `add_replica` the replica map can be empty while the
1395        // replica process is still running its dataflows. Nothing on this path may treat that as
1396        // a cluster without replicas, in particular `forward_implied_capabilities`. Forwarding
1397        // advances the input read holds of a dataflow that has not hydrated past its as-of, and
1398        // the replica keeps that dataflow at the old as-of when it reconciles. If its persist
1399        // reader has not registered yet, the import halts with "cannot serve requested as_of".
1400        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    /// Rehydrate any failed replicas of this instance.
1410    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    /// Creates the described dataflow and initializes state for its output.
1422    ///
1423    /// This method expects a `DataflowDescription` with an `as_of` frontier specified, as well as
1424    /// for each imported collection a read hold in `import_read_holds` at at least the `as_of`.
1425    #[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        // Validate that the target replica, if specified, exists.
1436        // A targeted dataflow is only installed on a single replica; if that
1437        // replica doesn't exist, we can't create the dataflow.
1438        if let Some(replica_id) = target_replica {
1439            if !self.replica_exists(replica_id) {
1440                return Err(ReplicaMissing(replica_id));
1441            }
1442        }
1443
1444        // Simple sanity checks around `as_of`
1445        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        // Collect all dependencies of the dataflow, and read holds on them at the `as_of`.
1454        let mut storage_dependencies = BTreeMap::new();
1455        let mut compute_dependencies = BTreeMap::new();
1456
1457        // When we install per-replica input read holds, we cannot use the `as_of` because of
1458        // reconciliation: Existing slow replicas might be reading from the inputs at times before
1459        // the `as_of` and we would rather not crash them by allowing their inputs to compact too
1460        // far. So instead we take read holds at the least time available.
1461        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 the `as_of` is empty, we are not going to create a dataflow, so replicas won't read
1485        // from the inputs.
1486        if as_of.is_empty() {
1487            replica_input_read_holds = Default::default();
1488        }
1489
1490        // Install collection state for each of the exports.
1491        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 the export is a storage sink, we can advance its write frontier to the write
1513            // frontier of the target storage collection.
1514            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        // Initialize tracking of subscribes.
1520        for subscribe_id in dataflow.subscribe_ids() {
1521            self.subscribes
1522                .insert(subscribe_id, ActiveSubscribe::default());
1523        }
1524
1525        // Initialize tracking of copy tos.
1526        for copy_to_id in dataflow.copy_to_ids() {
1527            self.copy_tos.insert(copy_to_id);
1528        }
1529
1530        // Here we augment all imported sources and all exported sinks with the appropriate
1531        // storage metadata needed by the compute instance.
1532        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        // Flatten the dataflow plans into the representation expected by replicas.
1595        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            // The rest of the fields are identical
1609            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        // Skip the actual dataflow creation for an empty `as_of`. (Happens e.g. for the
1640        // bootstrapping of a REFRESH AT mat view that is past its last refresh.)
1641        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    /// Schedule the identified collection if all its inputs are available.
1659    ///
1660    /// # Panics
1661    ///
1662    /// Panics if the identified collection does not exist.
1663    fn maybe_schedule_collection(&mut self, id: GlobalId) {
1664        let collection = self.expect_collection(id);
1665
1666        // Don't schedule collections twice.
1667        if collection.scheduled {
1668            return;
1669        }
1670
1671        let as_of = collection.read_frontier();
1672
1673        // If the collection has an empty `as_of`, it was either never installed on the replica or
1674        // has since been dropped. In either case the replica does not expect any commands for it.
1675        if as_of.is_empty() {
1676            return;
1677        }
1678
1679        let ready = if id.is_transient() {
1680            // Always schedule transient collections immediately. The assumption is that those are
1681            // created by interactive user commands and we want to schedule them as quickly as
1682            // possible. Inputs might not yet be available, but when they become available, we
1683            // don't need to wait for the controller to become aware and for the scheduling check
1684            // to run again.
1685            true
1686        } else {
1687            // Ignore self-dependencies. Any self-dependencies do not need to be
1688            // available at the as_of for the dataflow to make progress, so we
1689            // can ignore them here. At the moment, only continual tasks have
1690            // self-dependencies, but this logic is correct for any dataflow, so
1691            // we don't special case it to CTs.
1692            let not_self_dep = |x: &GlobalId| *x != id;
1693
1694            // Make sure we never schedule a collection before its input compute collections have
1695            // been scheduled. Scheduling in the wrong order can lead to deadlocks.
1696            let mut deps_scheduled = true;
1697
1698            // Check dependency frontiers to determine if all inputs are
1699            // available. An input is available when its frontier is greater
1700            // than the `as_of`, i.e., all input data up to and including the
1701            // `as_of` has been sealed.
1702            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    /// Schedule any unscheduled collections that are ready.
1732    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    /// Drops the read capability for the given collections and allows their resources to be
1740    /// reclaimed.
1741    #[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            // Mark the collection as dropped to allow it to be removed from the controller state.
1747            collection.dropped = true;
1748
1749            // Drop the implied and warmup read holds to announce that clients are not
1750            // interested in the collection anymore.
1751            collection.implied_read_hold.release();
1752            collection.warmup_read_hold.release();
1753
1754            // If the collection is a subscribe, stop tracking it. This ensures that the controller
1755            // ceases to produce `SubscribeResponse`s for this subscribe.
1756            self.subscribes.remove(id);
1757            // If the collection is a copy to, stop tracking it. This ensures that the controller
1758            // ceases to produce `CopyToResponse`s` for this copy to.
1759            self.copy_tos.remove(id);
1760        }
1761
1762        Ok(())
1763    }
1764
1765    /// Initiate a peek request for the contents of `id` at `timestamp`.
1766    ///
1767    /// If this returns an error, then it didn't modify any `Instance` state.
1768    #[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        // Downgrade the provided read hold to the peek time.
1788        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                // TODO(guswynn): can we just hold the `tracing::Span` here instead?
1808                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            // Obtain an `OpenTelemetryContext` from the thread-local tracing
1825            // tree to forward it on to the compute worker.
1826            otel_ctx,
1827            target: peek_target,
1828            result_desc,
1829        };
1830        self.send(ComputeCommand::Peek(Box::new(peek)));
1831
1832        Ok(())
1833    }
1834
1835    /// Cancels an existing peek request.
1836    #[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        // Enqueue a notification for the cancellation.
1848        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        // Finish the peek.
1854        // This will also propagate the cancellation to the replicas.
1855        self.finish_peek(uuid, reason);
1856    }
1857
1858    /// Assigns a read policy to specific identifiers.
1859    ///
1860    /// The policies are assigned in the order presented, and repeated identifiers should
1861    /// conclude with the last policy. Changing a policy will immediately downgrade the read
1862    /// capability if appropriate, but it will not "recover" the read capability if the prior
1863    /// capability is already ahead of it.
1864    ///
1865    /// Identifiers not present in `policies` retain their existing read policies.
1866    ///
1867    /// It is an error to attempt to set a read policy for a collection that is not readable in the
1868    /// context of compute. At this time, only indexes are readable compute collections.
1869    #[mz_ore::instrument(level = "debug")]
1870    pub fn set_read_policy(
1871        &mut self,
1872        policies: Vec<(GlobalId, ReadPolicy)>,
1873    ) -> Result<(), ReadPolicyError> {
1874        // Do error checking upfront, to avoid introducing inconsistencies between a collection's
1875        // `implied_capability` and `read_capabilities`.
1876        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    /// Advance the global write frontier of the given collection.
1894    ///
1895    /// Frontier regressions are gracefully ignored.
1896    ///
1897    /// # Panics
1898    ///
1899    /// Panics if the identified collection does not exist.
1900    #[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        // Relax the implied read hold according to the read policy.
1921        let new_since = match &collection.read_policy {
1922            Some(read_policy) => {
1923                // For readable collections the read frontier is determined by applying the
1924                // client-provided read policy to the write frontier.
1925                read_policy.frontier(new_frontier.borrow())
1926            }
1927            None => {
1928                // Write-only collections cannot be read within the context of the compute
1929                // controller, so their read frontier only controls the read holds taken on their
1930                // inputs. We can safely downgrade the input read holds to any time less than the
1931                // write frontier.
1932                //
1933                // Note that some write-only collections (continual tasks) need to observe changes
1934                // at their current write frontier during hydration. Thus, we cannot downgrade the
1935                // read frontier to the write frontier and instead step it back by one.
1936                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        // Report the frontier advancement.
1946        self.deliver_response(ComputeControllerResponse::FrontierUpper {
1947            id,
1948            upper: new_frontier,
1949        });
1950    }
1951
1952    /// Apply a collection read hold change.
1953    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            // Sanity check to prevent corrupted `read_capabilities`, which can cause hard-to-debug
1967            // issues (usually stuck read frontiers).
1968            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            // Apply read capability updates and learn about resulting changes to the read
1984            // frontier.
1985            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; // read frontier did not change
1993        };
1994
1995        // Propagate read frontier update to dependencies.
1996        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        // Produce `AllowCompaction` command.
2008        self.send(ComputeCommand::AllowCompaction {
2009            id,
2010            frontier: new_since,
2011        });
2012    }
2013
2014    /// Fulfills a registered peek and cleans up associated state.
2015    ///
2016    /// As part of this we:
2017    ///  * Send a `PeekResponse` through the peek's response channel.
2018    ///  * Emit a `CancelPeek` command to instruct replicas to stop spending resources on this
2019    ///    peek, and to allow the `ComputeCommandHistory` to reduce away the corresponding `Peek`
2020    ///    command.
2021    ///  * Remove the read hold for this peek, unblocking compaction that might have waited on it.
2022    fn finish_peek(&mut self, uuid: Uuid, response: PeekResponse) {
2023        let Some(peek) = self.peeks.remove(&uuid) else {
2024            return;
2025        };
2026
2027        // The recipient might not be interested in the peek response anymore, which is fine.
2028        let _ = peek.peek_response_tx.send(response);
2029
2030        // NOTE: We need to send the `CancelPeek` command _before_ we release the peek's read hold
2031        // (by dropping it), to avoid the edge case that caused database-issues#4812.
2032        self.send(ComputeCommand::CancelPeek { uuid });
2033
2034        drop(peek.read_hold);
2035    }
2036
2037    /// Routes a peek's terminal notification to its lifecycle, or to the
2038    /// coordinator if it has none. Must run before `finish_peek` removes the peek.
2039    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    /// Handles a response from a replica. Replica IDs are re-used across replica restarts, so we
2062    /// use the replica epoch to drop stale responses.
2063    fn handle_response(&mut self, (replica_id, epoch, response): ReplicaResponse) {
2064        // Filter responses from non-existing or stale replicas.
2065        if self
2066            .replicas
2067            .get(&replica_id)
2068            .filter(|replica| replica.epoch == epoch)
2069            .is_none()
2070        {
2071            return;
2072        }
2073
2074        // Invariant: the replica exists and has the expected epoch.
2075
2076        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    /// Handle new frontiers, returning any compute response that needs to
2096    /// be sent to the client.
2097    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        // We might not be tracking this peek anymore, because we have served a response already or
2148        // because it was canceled. If this is the case, we ignore the response.
2149        let Some(peek) = self.peeks.get(&uuid) else {
2150            return;
2151        };
2152
2153        // If the peek is targeting a replica, ignore responses from other replicas.
2154        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        // NOTE: We use the `otel_ctx` from the response, not the pending peek, because we
2164        // currently want the parent to be whatever the compute worker did with this peek.
2165        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        // Downgrade the replica frontiers, to enable dropping of input read holds and clean up of
2196        // collection state.
2197        // TODO(database-issues#4701): report copy-to frontiers through `Frontiers` responses
2198        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        // We might not be tracking this COPY TO because we have already returned a response
2203        // from one of the replicas. In that case, we ignore the response.
2204        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            // We should never get here: Replicas only drop copy to collections in response
2212            // to the controller allowing them to do so, and when the controller drops a
2213            // copy to it also removes it from the list of tracked copy_tos (see
2214            // [`Instance::drop_collections`]).
2215            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        // Always apply replica write frontier updates. Even if the subscribe is not tracked
2255        // anymore, there might still be replicas reading from its inputs, so we need to track the
2256        // frontiers until all replicas have advanced to the empty one.
2257        let write_frontier = match &response {
2258            SubscribeResponse::Batch(batch) => batch.upper.clone(),
2259            SubscribeResponse::DroppedAt(_) => Antichain::new(),
2260        };
2261
2262        // For subscribes we downgrade all replica frontiers based on write frontiers. This should
2263        // be fine because the input and output frontier of a subscribe track its write frontier.
2264        // TODO(database-issues#4701): report subscribe frontiers through `Frontiers` responses
2265        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        // If the subscribe is not tracked, or targets a different replica, there is nothing to do.
2270        let Some(mut subscribe) = self.subscribes.get(&subscribe_id).cloned() else {
2271            return;
2272        };
2273
2274        // Apply a global frontier update.
2275        // If this is a replica-targeted subscribe, it is important that we advance the global
2276        // frontier only based on responses from the targeted replica. Otherwise, another replica
2277        // could advance to the empty frontier, making us drop the subscribe on the targeted
2278        // replica prematurely.
2279        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 this batch advances the subscribe's frontier, we emit all updates at times
2287                // greater or equal to the last frontier (to avoid emitting duplicate updates).
2288                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                        // This subscribe cannot produce more data. Stop tracking it.
2293                        self.subscribes.remove(&subscribe_id);
2294                    } else {
2295                        // This subscribe can produce more data. Update our tracking of it.
2296                        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                                // True for times that are strictly less than lower (and should be skipped)
2303                                // and false otherwise.
2304                                !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                // We should never get here: Replicas only drop subscribe collections in response
2323                // to the controller allowing them to do so, and when the controller drops a
2324                // subscribe it also removes it from the list of tracked subscribes (see
2325                // [`Instance::drop_collections`]).
2326                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    /// Return the write frontiers of the dependencies of the given collection.
2344    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    /// Return the write frontiers of transitive storage dependencies of the given collection.
2361    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    /// Downgrade the warmup capabilities of collections as much as possible.
2389    ///
2390    /// The only requirement we have for a collection's warmup capability is that it is for a time
2391    /// that is available in all of the collection's inputs. For each input the latest time that is
2392    /// the case for is `write_frontier - 1`. So the farthest we can downgrade a collection's
2393    /// warmup capability is the minimum of `write_frontier - 1` of all its inputs.
2394    ///
2395    /// This method expects to be periodically called as part of instance maintenance work.
2396    /// We would like to instead update the warmup capabilities synchronously in response to
2397    /// frontier updates of dependency collections, but that is not generally possible because we
2398    /// don't learn about frontier updates of storage collections synchronously. We could do
2399    /// synchronous updates for compute dependencies, but we refrain from doing for simplicity.
2400    fn downgrade_warmup_capabilities(&mut self) {
2401        let mut new_capabilities = BTreeMap::new();
2402        for (id, collection) in &self.collections {
2403            // For write-only collections that have advanced to the empty frontier, we can drop the
2404            // warmup capability entirely. There is no reason why we would need to hydrate those
2405            // collections again, so being able to warm them up is not useful.
2406            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    /// Forward the implied capabilities of collections, if possible.
2430    ///
2431    /// The implied capability of a collection controls (a) which times are still readable (for
2432    /// indexes) and (b) with which as-of the collection gets installed on a new replica. We are
2433    /// usually not allowed to advance an implied capability beyond the frontier that follows from
2434    /// the collection's read policy applied to its write frontier:
2435    ///
2436    ///  * For sink collections, some external consumer might rely on seeing all distinct times in
2437    ///    the input reflected in the output. If we'd forward the implied capability of a sink,
2438    ///    we'd risk skipping times in the output across replica restarts.
2439    ///  * For index collections, we might make the index unreadable by advancing its read frontier
2440    ///    beyond its write frontier.
2441    ///
2442    /// There is one case where forwarding an implied capability is fine though: an index installed
2443    /// on a cluster that has no replicas. Such indexes are not readable anyway until a new replica
2444    /// is added, so advancing its read frontier can't make it unreadable. We can thus advance the
2445    /// implied capability as long as we make sure that when a new replica is added, the expected
2446    /// relationship between write frontier, read policy, and implied capability can be restored
2447    /// immediately (modulo computation time).
2448    ///
2449    /// Forwarding implied capabilities is not necessary for the correct functioning of the
2450    /// controller but an optimization that is beneficial in two ways:
2451    ///
2452    ///  * It relaxes read holds on inputs to forwarded collections, allowing their compaction.
2453    ///  * It reduces the amount of historical detail new replicas need to process when computing
2454    ///    forwarded collections, as forwarding the implied capability also forwards the corresponding
2455    ///    dataflow as-of.
2456    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                // Collection is write-only, i.e. a sink.
2468                continue;
2469            };
2470
2471            // When a new replica is started, it will immediately be able to compute all collection
2472            // output up to the write frontier of its transitive storage inputs. So the new implied
2473            // read capability should be the read policy applied to that frontier.
2474            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    /// Acquires a `ReadHold` for the identified compute collection.
2492    ///
2493    /// This mirrors the logic used by the controller-side `InstanceState::acquire_read_hold`,
2494    /// but executes on the instance task itself.
2495    pub(super) fn acquire_read_hold(&self, id: GlobalId) -> Result<ReadHold, CollectionMissing> {
2496        // Similarly to InstanceState::acquire_read_hold and StorageCollections::acquire_read_holds,
2497        // we acquire read holds at the earliest possible time rather than returning a copy
2498        // of the implied read hold. This is so that dependents can acquire read holds on
2499        // compute dependencies at frontiers that are held back by other read holds the caller
2500        // has previously taken.
2501        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    /// Process pending maintenance work.
2512    ///
2513    /// This method is invoked periodically by the global controller.
2514    /// It is a good place to perform maintenance work that arises from various controller state
2515    /// changes and that cannot conveniently be handled synchronously with those state changes.
2516    #[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/// State maintained about individual compute collections.
2530///
2531/// A compute collection is either an index, or a storage sink, or a subscribe, exported by a
2532/// compute dataflow.
2533#[derive(Debug)]
2534struct CollectionState {
2535    /// If set, this collection is only maintained by the specified replica.
2536    target_replica: Option<ReplicaId>,
2537    /// Whether this collection is a log collection.
2538    ///
2539    /// Log collections are special in that they are only maintained by a subset of all replicas.
2540    log_collection: bool,
2541    /// Whether this collection has been dropped by a controller client.
2542    ///
2543    /// The controller is allowed to remove the `CollectionState` for a collection only when
2544    /// `dropped == true`. Otherwise, clients might still expect to be able to query information
2545    /// about this collection.
2546    dropped: bool,
2547    /// Whether this collection has been scheduled, i.e., the controller has sent a `Schedule`
2548    /// command for it.
2549    scheduled: bool,
2550
2551    /// Whether this collection is in read-only mode.
2552    ///
2553    /// When in read-only mode, the dataflow is not allowed to affect external state (largely persist).
2554    read_only: bool,
2555
2556    /// State shared with the `ComputeController`.
2557    shared: SharedCollectionState,
2558
2559    /// A read hold maintaining the implicit capability of the collection.
2560    ///
2561    /// This capability is kept to ensure that the collection remains readable according to its
2562    /// `read_policy`. It also ensures that read holds on the collection's dependencies are kept at
2563    /// some time not greater than the collection's `write_frontier`, guaranteeing that the
2564    /// collection's next outputs can always be computed without skipping times.
2565    implied_read_hold: ReadHold,
2566    /// A read hold held to enable dataflow warmup.
2567    ///
2568    /// Dataflow warmup is an optimization that allows dataflows to immediately start hydrating
2569    /// even when their next output time (as implied by the `write_frontier`) is in the future.
2570    /// By installing a read capability derived from the write frontiers of the collection's
2571    /// inputs, we ensure that the as-of of new dataflows installed for the collection is at a time
2572    /// that is immediately available, so hydration can begin immediately too.
2573    warmup_read_hold: ReadHold,
2574    /// The policy to use to downgrade `self.implied_read_hold`.
2575    ///
2576    /// If `None`, the collection is a write-only collection (i.e. a sink). For write-only
2577    /// collections, the `implied_read_hold` is only required for maintaining read holds on the
2578    /// inputs, so we can immediately downgrade it to the `write_frontier`.
2579    read_policy: Option<ReadPolicy>,
2580
2581    /// Storage identifiers on which this collection depends, and read holds this collection
2582    /// requires on them.
2583    storage_dependencies: BTreeMap<GlobalId, ReadHold>,
2584    /// Compute identifiers on which this collection depends, and read holds this collection
2585    /// requires on them.
2586    compute_dependencies: BTreeMap<GlobalId, ReadHold>,
2587
2588    /// Introspection state associated with this collection.
2589    introspection: CollectionIntrospection,
2590
2591    /// Frontier wallclock lag measurements stashed until the next `WallclockLagHistogram`
2592    /// introspection update.
2593    ///
2594    /// Keys are `(period, lag, labels)` triples, values are counts.
2595    ///
2596    /// If this is `None`, wallclock lag is not tracked for this collection.
2597    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    /// Creates a new collection state, with an initial read policy valid from `since`.
2611    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        // A collection is not readable before the `as_of`.
2621        let since = as_of.clone();
2622        // A collection won't produce updates for times before the `as_of`.
2623        let upper = as_of;
2624
2625        // Ensure that the provided `shared` is valid for the given `as_of`.
2626        assert!(shared.lock_read_capabilities(|c| c.frontier() == since.borrow()));
2627        assert!(shared.lock_write_frontier(|f| f == &upper));
2628
2629        // Initialize collection read holds.
2630        // Note that the implied read hold was already added to the `read_capabilities` when
2631        // `shared` was created, so we only need to add the warmup read hold here.
2632        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        // In an effort to keep the produced wallclock lag introspection data small and
2642        // predictable, we disable wallclock lag tracking for transient collections, i.e. slow-path
2643        // select indexes and subscribes.
2644        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    /// Creates a new collection state for a log collection.
2667    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        // Log collections are created and scheduled implicitly as part of replica initialization.
2694        state.scheduled = true;
2695        state
2696    }
2697
2698    /// Reports the current read frontier.
2699    fn read_frontier(&self) -> Antichain<Timestamp> {
2700        self.shared
2701            .lock_read_capabilities(|c| c.frontier().to_owned())
2702    }
2703
2704    /// Reports the current write frontier.
2705    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/// Collection state shared with the `ComputeController`.
2719///
2720/// Having this allows certain controller APIs, such as `ComputeController::collection_frontiers`
2721/// and `ComputeController::acquire_read_hold` to be non-`async`. This comes at the cost of
2722/// complexity (by introducing shared mutable state) and performance (by introducing locking). We
2723/// should aim to reduce the amount of shared state over time, rather than expand it.
2724///
2725/// Note that [`SharedCollectionState`]s are initialized by the `ComputeController` prior to the
2726/// collection's creation in the [`Instance`]. This is to allow compute clients to query frontiers
2727/// and take new read holds immediately, without having to wait for the [`Instance`] to update.
2728#[derive(Clone, Debug)]
2729pub(super) struct SharedCollectionState {
2730    /// Accumulation of read capabilities for the collection.
2731    ///
2732    /// This accumulation contains the capabilities held by all [`ReadHold`]s given out for the
2733    /// collection, including `implied_read_hold` and `warmup_read_hold`.
2734    ///
2735    /// NOTE: This field may only be modified by [`Instance::apply_read_hold_change`],
2736    /// [`Instance::acquire_read_hold`], and `ComputeController::acquire_read_hold`.
2737    /// Nobody else should modify read capabilities directly. Instead, collection users should
2738    /// manage read holds through [`ReadHold`] objects acquired through
2739    /// `ComputeController::acquire_read_hold`.
2740    ///
2741    /// TODO(teskje): Restructure the code to enforce the above in the type system.
2742    read_capabilities: Arc<Mutex<MutableAntichain<Timestamp>>>,
2743    /// The write frontier of this collection.
2744    write_frontier: Arc<Mutex<Antichain<Timestamp>>>,
2745}
2746
2747impl SharedCollectionState {
2748    pub fn new(as_of: Antichain<Timestamp>) -> Self {
2749        // A collection is not readable before the `as_of`.
2750        let since = as_of.clone();
2751        // A collection won't produce updates for times before the `as_of`.
2752        let upper = as_of;
2753
2754        // Initialize read capabilities to the `since`.
2755        // The is the implied read capability. The corresponding [`ReadHold`] is created in
2756        // [`CollectionState::new`].
2757        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/// Manages certain introspection relations associated with a collection. Upon creation, it adds
2784/// rows to introspection relations. When dropped, it retracts its managed rows.
2785#[derive(Debug)]
2786struct CollectionIntrospection {
2787    /// The ID of the compute collection.
2788    collection_id: GlobalId,
2789    /// A channel through which introspection updates are delivered.
2790    introspection_tx: mpsc::UnboundedSender<IntrospectionUpdates>,
2791    /// Introspection state for `IntrospectionType::Frontiers`.
2792    ///
2793    /// `Some` if the collection does _not_ sink into a storage collection (i.e. is not an MV). If
2794    /// the collection sinks into storage, the storage controller reports its frontiers instead.
2795    frontiers: Option<FrontiersIntrospectionState>,
2796    /// Introspection state for `IntrospectionType::ComputeMaterializedViewRefreshes`.
2797    ///
2798    /// `Some` if the collection is a REFRESH MV.
2799    refresh: Option<RefreshIntrospectionState>,
2800    /// The IDs of the collection's dependencies, for `IntrospectionType::ComputeDependencies`.
2801    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                    // If we have a `refresh_schedule`, then the collection is a MV, so we should also have
2821                    // an `initial_as_of`.
2822                    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    /// Reports the initial introspection state.
2844    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    /// Produces rows for the `ComputeDependencies` introspection relation.
2864    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    /// Observe the given current collection frontiers and update the introspection state as
2878    /// necessary.
2879    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; // no change
2900        };
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; // no change
2920        }
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        // Failure to send means the `ComputeController` has been dropped and doesn't care about
2928        // introspection updates anymore.
2929        let _ = self.introspection_tx.send((introspection_type, updates));
2930    }
2931}
2932
2933impl Drop for CollectionIntrospection {
2934    fn drop(&mut self) {
2935        // Retract collection frontiers.
2936        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        // Retract MV refresh state.
2943        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        // Retract collection dependencies.
2950        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    /// Return a `Row` reflecting the current collection frontiers.
2972    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    /// Update the introspection state with the given new frontiers.
2989    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/// Information needed to compute introspection updates for a REFRESH materialized view when the
3004/// write frontier advances.
3005#[derive(Debug)]
3006struct RefreshIntrospectionState {
3007    // Immutable properties of the MV
3008    refresh_schedule: RefreshSchedule,
3009    initial_as_of: Antichain<Timestamp>,
3010    // Refresh state
3011    next_refresh: Datum<'static>,           // Null or an MzTimestamp
3012    last_completed_refresh: Datum<'static>, // Null or an MzTimestamp
3013}
3014
3015impl RefreshIntrospectionState {
3016    /// Return a `Row` reflecting the current refresh introspection state.
3017    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    /// Construct a new [`RefreshIntrospectionState`], and apply an initial `frontier_update()` at
3028    /// the `upper`.
3029    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    /// Should be called whenever the write frontier of the collection advances. It updates the
3045    /// state that should be recorded in introspection relations, but doesn't send the updates yet.
3046    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                    // If there is no last refresh, then we have a `REFRESH EVERY`, in which case
3053                    // the saturating roundup puts a refresh at the maximum possible timestamp.
3054                    Timestamp::MAX.into()
3055                };
3056            self.next_refresh = Datum::Null;
3057        } else {
3058            if PartialOrder::less_equal(write_frontier, &self.initial_as_of) {
3059                // We are before the first refresh.
3060                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                // The first refresh has already happened.
3075                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/// A note of an outstanding peek response.
3095#[derive(Debug)]
3096struct PendingPeek {
3097    /// Receives the peek's terminal notification. If `None`, the coordinator does.
3098    lifecycle: Option<Arc<PeekLifecycle>>,
3099    /// For replica-targeted peeks, this specifies the replica whose response we should pass on.
3100    ///
3101    /// If this value is `None`, we pass on the first response.
3102    target_replica: Option<ReplicaId>,
3103    /// The OpenTelemetry context for this peek.
3104    otel_ctx: OpenTelemetryContext,
3105    /// The time at which the peek was requested.
3106    ///
3107    /// Used to track peek durations.
3108    requested_at: Instant,
3109    /// The read hold installed to serve this peek.
3110    read_hold: ReadHold,
3111    /// The channel to send peek results.
3112    peek_response_tx: oneshot::Sender<PeekResponse>,
3113    /// An optional limit of the peek's result size.
3114    limit: Option<usize>,
3115    /// The offset into the peek's result.
3116    offset: usize,
3117}
3118
3119#[derive(Debug, Clone)]
3120struct ActiveSubscribe {
3121    /// Current upper frontier of this subscribe.
3122    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/// State maintained about individual replicas.
3134#[derive(Debug)]
3135struct ReplicaState {
3136    /// The ID of the replica.
3137    id: ReplicaId,
3138    /// Client for the running replica task.
3139    client: ReplicaClient,
3140    /// The replica configuration.
3141    config: ReplicaConfig,
3142    /// Replica metrics.
3143    metrics: ReplicaMetrics,
3144    /// A channel through which introspection updates are delivered.
3145    introspection_tx: mpsc::UnboundedSender<IntrospectionUpdates>,
3146    /// Per-replica collection state.
3147    collections: BTreeMap<GlobalId, ReplicaCollectionState>,
3148    /// The epoch of the replica.
3149    epoch: u64,
3150    /// The replica's dyncfg override, merged into every configuration command sent or replayed
3151    /// to it. Holds only the scoped values that differ from the environment-wide configuration,
3152    /// and is empty for a replica without scoped parameters.
3153    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    /// Add a collection to the replica state.
3179    ///
3180    /// # Panics
3181    ///
3182    /// Panics if a collection with the same ID exists already.
3183    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        // In an effort to keep the produced wallclock lag introspection data small and
3200        // predictable, we disable wallclock lag tracking for transient collections, i.e. slow-path
3201        // select indexes and subscribes.
3202        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    /// Remove state for a collection.
3212    fn remove_collection(&mut self, id: GlobalId) -> Option<ReplicaCollectionState> {
3213        self.collections.remove(&id)
3214    }
3215
3216    /// Returns the per-replica state of a collection this replica hosts.
3217    ///
3218    /// # Panics
3219    ///
3220    /// Panics if the replica does not host the collection. Callers obtain the
3221    /// replica from [`Instance::replicas_hosting`], which guarantees it does.
3222    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    /// Returns whether all replica frontiers of the given collection are empty.
3229    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    /// Returns the state of the [`ReplicaState`] formatted as JSON.
3238    ///
3239    /// The returned value is not guaranteed to be stable and may change at any point in time.
3240    #[mz_ore::instrument(level = "debug")]
3241    pub fn dump(&self) -> Result<serde_json::Value, anyhow::Error> {
3242        // Note: We purposefully use the `Debug` formatting for the value of all fields in the
3243        // returned object as a tradeoff between usability and stability. `serde_json` will fail
3244        // to serialize an object if the keys aren't strings, so `Debug` formatting the values
3245        // prevents a future unrelated change from silently breaking this method.
3246
3247        // Destructure `self` here so we don't forget to consider dumping newly added fields.
3248        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    /// The replica write frontier of this collection.
3276    ///
3277    /// See [`FrontiersResponse::write_frontier`].
3278    write_frontier: Antichain<Timestamp>,
3279    /// The replica input frontier of this collection.
3280    ///
3281    /// See [`FrontiersResponse::input_frontier`].
3282    input_frontier: Antichain<Timestamp>,
3283    /// The replica output frontier of this collection.
3284    ///
3285    /// See [`FrontiersResponse::output_frontier`].
3286    output_frontier: Antichain<Timestamp>,
3287
3288    /// Metrics tracked for this collection.
3289    ///
3290    /// If this is `None`, no metrics are collected.
3291    metrics: Option<ReplicaCollectionMetrics>,
3292    /// As-of frontier with which this collection was installed on the replica.
3293    as_of: Antichain<Timestamp>,
3294    /// Tracks introspection state for this collection.
3295    introspection: ReplicaCollectionIntrospection,
3296    /// Read holds on storage inputs to this collection.
3297    ///
3298    /// These read holds are kept to ensure that the replica is able to read from storage inputs at
3299    /// all times it hasn't read yet. We only need to install read holds for storage inputs since
3300    /// compaction of compute inputs is implicitly held back by Timely/DD.
3301    input_read_holds: Vec<ReadHold>,
3302
3303    /// Maximum frontier wallclock lag since the last `WallclockLagHistory` introspection update.
3304    ///
3305    /// If this is `None`, wallclock lag is not tracked for this collection.
3306    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    /// Returns whether this collection is hydrated.
3329    fn hydrated(&self) -> bool {
3330        // If the observed frontier is greater than the collection's as-of, the collection has
3331        // produced some output and is therefore hydrated.
3332        //
3333        // We need to consider the edge case where the as-of is the empty frontier. Such an as-of
3334        // is not useful for indexes, because they wouldn't be readable. For write-only
3335        // collections, an empty as-of means that the collection has been fully written and no new
3336        // dataflow needs to be created for it. Consequently, no hydration will happen either.
3337        //
3338        // Based on this, we could respond in two ways:
3339        //  * `false`, as in "the dataflow was never created"
3340        //  * `true`, as in "the dataflow completed immediately"
3341        //
3342        // Since hydration is often used as a measure of dataflow progress and we don't want to
3343        // give the impression that certain dataflows are somehow stuck when they are not, we go
3344        // with the second interpretation here.
3345        self.as_of.is_empty() || PartialOrder::less_than(&self.as_of, &self.output_frontier)
3346    }
3347
3348    /// Updates the replica write frontier of this collection.
3349    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    /// Updates the replica input frontier of this collection.
3364    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        // Relax our read holds on collection inputs.
3378        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    /// Updates the replica output frontier of this collection.
3389    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/// Maintains the introspection state for a given replica and collection, and ensures that reported
3405/// introspection data is retracted when the collection is dropped.
3406#[derive(Debug)]
3407struct ReplicaCollectionIntrospection {
3408    /// The ID of the replica.
3409    replica_id: ReplicaId,
3410    /// The ID of the compute collection.
3411    collection_id: GlobalId,
3412    /// The collection's reported replica write frontier.
3413    write_frontier: Antichain<Timestamp>,
3414    /// A channel through which introspection updates are delivered.
3415    introspection_tx: mpsc::UnboundedSender<IntrospectionUpdates>,
3416}
3417
3418impl ReplicaCollectionIntrospection {
3419    /// Create a new `HydrationState` and initialize introspection.
3420    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    /// Reports the initial introspection state.
3438    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    /// Observe the given current write frontier and update the introspection state as necessary.
3445    fn observe_frontier(&mut self, write_frontier: &Antichain<Timestamp>) {
3446        if self.write_frontier == *write_frontier {
3447            return; // no change
3448        }
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    /// Return a `Row` reflecting the current replica write frontier.
3459    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        // Failure to send means the `ComputeController` has been dropped and doesn't care about
3473        // introspection updates anymore.
3474        let _ = self.introspection_tx.send((introspection_type, updates));
3475    }
3476}
3477
3478impl Drop for ReplicaCollectionIntrospection {
3479    fn drop(&mut self) {
3480        // Retract the write frontier.
3481        let row = self.write_frontier_row();
3482        let updates = vec![(row, Diff::MINUS_ONE)];
3483        self.send(IntrospectionType::ReplicaFrontiers, updates);
3484    }
3485}
3486
3487/// Classifies one collection's readiness over every replica hosting it.
3488///
3489/// Hydration and sufficient progress must belong to the same target replica.
3490/// No reference replicas yields `MIN`, while a completed reference yields the
3491/// empty frontier. Those cases must remain distinct.
3492fn 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                // Report the closest hydrated target, since any ready target
3522                // suffices. A finite gap is closer than awaiting completion.
3523                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    /// The regression the lag gate exists for: a pending replica whose dataflow
3607    /// has produced its first output past the as-of, and so reports hydrated,
3608    /// while its output frontier is still far behind the outgoing replica.
3609    #[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            // The shared MV write frontier is caught up, but this replica has
3616            // only just produced its first output past the as-of.
3617            (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            // This replica is within the lag allowance but has not advanced
3675            // past its own as-of. It cannot supply progress for the hydrated,
3676            // lagging replica below.
3677            (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    /// `CreateInstance` is specialized with a full snapshot of the instance-wide dyncfg, so the
3791    /// replica seeds its worker config at create time rather than waiting for the first
3792    /// `UpdateConfiguration`. This is the regression guard for create-time setup observing dyncfg
3793    /// defaults.
3794    #[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        // A replica without an override sees exactly the instance-wide values.
3805        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    /// A replica-scoped override beats the instance-wide value in the create-time snapshot, so a
3822    /// create-time-frozen scoped flag reaches the replica with its override applied.
3823    #[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    /// `UpdateConfiguration` continues to merge the replica's override into the update.
3848    #[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            &registry,
4038            mz_cluster_client::metrics::ControllerMetrics::new(&registry),
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            // Late replica responses must not retire or notify a second time.
4146            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}