mz_compute_client/controller.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 that provides an interface to the compute layer, and the storage layer below it.
11//!
12//! The compute controller manages the creation, maintenance, and removal of compute instances.
13//! This involves ensuring the intended service state with the orchestrator, as well as maintaining
14//! a dedicated compute instance controller for each active compute instance.
15//!
16//! For each compute instance, the compute controller curates the creation of indexes and sinks
17//! installed on the instance, the progress of readers through these collections, and their
18//! eventual dropping and resource reclamation.
19//!
20//! The state maintained for a compute instance can be viewed as a partial map from `GlobalId` to
21//! collection. It is an error to use an identifier before it has been "created" with
22//! `create_dataflow()`. Once created, the controller holds a read capability for each output
23//! collection of a dataflow, which is manipulated with `set_read_policy()`. Eventually, a
24//! collection is dropped with `drop_collections()`.
25//!
26//! A dataflow can be in read-only or read-write mode. In read-only mode, the dataflow does not
27//! modify any persistent state. Sending a `allow_write` message to the compute instance will
28//! transition the dataflow to read-write mode, allowing it to write to persistent sinks.
29//!
30//! Created dataflows will prevent the compaction of their inputs, including other compute
31//! collections but also collections managed by the storage layer. Each dataflow input is prevented
32//! from compacting beyond the allowed compaction of each of its outputs, ensuring that we can
33//! recover each dataflow to its current state in case of failure or other reconfiguration.
34
35use std::collections::{BTreeMap, BTreeSet};
36use std::sync::{Arc, Mutex};
37use std::time::Duration;
38
39use mz_build_info::BuildInfo;
40use mz_cluster_client::client::ClusterReplicaLocation;
41use mz_cluster_client::metrics::ControllerMetrics;
42use mz_cluster_client::{ReplicaId, WallclockLagFn};
43use mz_compute_types::ComputeInstanceId;
44use mz_compute_types::config::ComputeReplicaConfig;
45use mz_compute_types::dyncfgs::{
46 COMPUTE_REPLICA_EXPIRATION_OFFSET, ENABLE_ARRANGEMENT_DICTIONARY_COMPRESSION_ALPHA,
47};
48use mz_dyncfg::{ConfigSet, ConfigUpdates};
49use mz_expr::RowSetFinishing;
50use mz_expr::row::RowCollection;
51use mz_ore::cast::CastFrom;
52use mz_ore::metrics::MetricsRegistry;
53use mz_ore::now::NowFn;
54use mz_ore::soft_assert_or_log;
55use mz_ore::soft_panic_or_log;
56use mz_ore::tracing::OpenTelemetryContext;
57use mz_persist_types::PersistLocation;
58use mz_repr::{GlobalId, RelationDesc, Row, Timestamp, frontier_within_lag};
59use mz_storage_client::controller::StorageController;
60use mz_storage_types::dyncfgs::ORE_OVERFLOWING_BEHAVIOR;
61use mz_storage_types::read_holds::ReadHold;
62use mz_storage_types::read_policy::ReadPolicy;
63use mz_storage_types::time_dependence::{TimeDependence, TimeDependenceError};
64use prometheus::proto::LabelPair;
65use serde::{Deserialize, Serialize};
66use timely::PartialOrder;
67use timely::progress::Antichain;
68use tokio::sync::{mpsc, oneshot};
69use tokio::time::{self, MissedTickBehavior};
70use uuid::Uuid;
71
72use crate::controller::error::{
73 CollectionLookupError, CollectionMissing, CollectionUpdateError, DataflowCreationError,
74 HydrationCheckBadTarget, InstanceExists, InstanceMissing, PeekError, ReadPolicyError,
75 ReplicaCreationError, ReplicaDropError,
76};
77use crate::controller::instance::{Instance, SharedCollectionState};
78use crate::controller::introspection::{IntrospectionUpdates, spawn_introspection_sink};
79use crate::controller::replica::ReplicaConfig;
80use crate::logging::{LogVariant, LoggingConfig};
81use crate::metrics::ComputeControllerMetrics;
82use crate::protocol::command::{ComputeParameters, PeekTarget};
83use crate::protocol::response::{PeekResponse, SubscribeBatch};
84
85mod instance;
86mod introspection;
87mod replica;
88mod sequential_hydration;
89
90pub mod error;
91pub mod instance_client;
92pub mod peek_lifecycle;
93pub use instance_client::InstanceClient;
94use peek_lifecycle::PeekLifecycle;
95
96pub(crate) type StorageCollections =
97 Arc<dyn mz_storage_client::storage_collections::StorageCollections + Send + Sync>;
98
99/// A collection's hydration and catch-up status.
100#[derive(Debug, Clone, Copy, PartialEq, Eq)]
101pub enum CollectionReadiness {
102 /// Hydrated and within the requested lag allowance.
103 Ready,
104 /// Hydrated, but behind the requested frontier.
105 Lagging {
106 /// The gap in timestamp ticks, or `None` when awaiting completion.
107 /// Ticks are milliseconds only on the epoch-milliseconds timeline.
108 lag: Option<u64>,
109 },
110 /// Not yet hydrated.
111 Unhydrated,
112}
113
114impl CollectionReadiness {
115 /// Classifies progress against an optional reference and lag allowance.
116 ///
117 /// The caller selects comparable frontiers: graceful replacement uses
118 /// per-replica output frontiers, whereas 0dt uses collection write frontiers.
119 /// No lag requirement means hydration alone. An empty reference requires
120 /// an empty frontier, since completion cannot be matched by finite progress.
121 pub fn classify(
122 hydrated: bool,
123 frontier: &Antichain<Timestamp>,
124 lag_requirement: Option<(&Antichain<Timestamp>, Timestamp)>,
125 ) -> Self {
126 if !hydrated {
127 Self::Unhydrated
128 } else if lag_requirement
129 .is_some_and(|(reference, lag)| !frontier_within_lag(frontier, reference, lag))
130 {
131 let reference = lag_requirement.expect("lag requirement was checked").0;
132 let lag =
133 frontier
134 .as_option()
135 .zip(reference.as_option())
136 .map(|(frontier, reference)| {
137 u64::from(*reference).saturating_sub(u64::from(*frontier))
138 });
139 Self::Lagging { lag }
140 } else {
141 Self::Ready
142 }
143 }
144}
145
146/// Responses from the compute controller.
147#[derive(Debug)]
148pub enum ComputeControllerResponse {
149 /// See [`PeekNotification`].
150 PeekNotification(Uuid, PeekNotification, OpenTelemetryContext),
151 /// See [`crate::protocol::response::ComputeResponse::SubscribeResponse`].
152 SubscribeResponse(GlobalId, SubscribeBatch),
153 /// The response from a dataflow containing an `CopyToS3Oneshot` sink.
154 ///
155 /// The `GlobalId` identifies the sink. The `Result` is the response from
156 /// the sink, where an `Ok(n)` indicates that `n` rows were successfully
157 /// copied to S3 and an `Err` indicates that an error was encountered
158 /// during the copy operation.
159 ///
160 /// For a given `CopyToS3Oneshot` sink, there will be at most one `CopyToResponse`
161 /// produced. (The sink may produce no responses if its dataflow is dropped
162 /// before completion.)
163 CopyToResponse(GlobalId, Result<u64, anyhow::Error>),
164 /// A response reporting advancement of a collection's upper frontier.
165 ///
166 /// Once a collection's upper (aka "write frontier") has advanced to beyond a given time, the
167 /// contents of the collection as of that time have been sealed and cannot change anymore.
168 FrontierUpper {
169 /// The ID of a compute collection.
170 id: GlobalId,
171 /// The new upper frontier of the identified compute collection.
172 upper: Antichain<Timestamp>,
173 },
174}
175
176/// Notification and summary of a received and forwarded [`crate::protocol::response::ComputeResponse::PeekResponse`].
177#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
178pub enum PeekNotification {
179 /// Returned rows of a successful peek.
180 Success {
181 /// Number of rows in the returned peek result.
182 rows: u64,
183 /// Size of the returned peek result in bytes.
184 result_size: u64,
185 },
186 /// Error of an unsuccessful peek, including the reason for the error.
187 Error(String),
188 /// The peek was canceled.
189 Canceled,
190}
191
192impl PeekNotification {
193 /// Construct a new [`PeekNotification`] from a [`PeekResponse`]. The `offset` and `limit`
194 /// parameters are used to calculate the number of rows in the peek result.
195 fn new(peek_response: &PeekResponse, offset: usize, limit: Option<usize>) -> Self {
196 match peek_response {
197 PeekResponse::Rows(rows) => {
198 let num_rows = u64::cast_from(RowCollection::offset_limit(
199 rows.iter().map(|r| r.count()).sum(),
200 offset,
201 limit,
202 ));
203 let result_size = u64::cast_from(rows.iter().map(|r| r.byte_len()).sum::<usize>());
204
205 tracing::trace!(?num_rows, ?result_size, "inline peek result");
206
207 Self::Success {
208 rows: num_rows,
209 result_size,
210 }
211 }
212 PeekResponse::Stashed(stashed_response) => {
213 let rows = stashed_response.num_rows(offset, limit);
214 let result_size = stashed_response.size_bytes();
215
216 tracing::trace!(?rows, ?result_size, "stashed peek result");
217
218 Self::Success {
219 rows: u64::cast_from(rows),
220 result_size: u64::cast_from(result_size),
221 }
222 }
223 PeekResponse::Error(err) => Self::Error(err.to_string()),
224 PeekResponse::Canceled => Self::Canceled,
225 }
226 }
227}
228
229/// A controller for the compute layer.
230pub struct ComputeController {
231 instances: BTreeMap<ComputeInstanceId, InstanceState>,
232 /// A map from an instance ID to an arbitrary string that describes the
233 /// class of the workload that compute instance is running (e.g.,
234 /// `production` or `staging`).
235 instance_workload_classes: Arc<Mutex<BTreeMap<ComputeInstanceId, Option<String>>>>,
236 build_info: &'static BuildInfo,
237 /// A handle providing access to storage collections.
238 storage_collections: StorageCollections,
239 /// Set to `true` once `initialization_complete` has been called.
240 initialized: bool,
241 /// Whether or not this controller is in read-only mode.
242 ///
243 /// When in read-only mode, neither this controller nor the instances
244 /// controlled by it are allowed to affect changes to external systems
245 /// (largely persist).
246 read_only: bool,
247 /// Compute configuration to apply to new instances.
248 config: ComputeParameters,
249 /// The persist location where we can stash large peek results.
250 peek_stash_persist_location: PersistLocation,
251 /// A controller response to be returned on the next call to [`ComputeController::process`].
252 stashed_response: Option<ComputeControllerResponse>,
253 /// The compute controller metrics.
254 metrics: ComputeControllerMetrics,
255 /// A function that produces the current wallclock time.
256 now: NowFn,
257 /// A function that computes the lag between the given time and wallclock time.
258 wallclock_lag: WallclockLagFn<Timestamp>,
259 /// Dynamic system configuration.
260 ///
261 /// Updated through `ComputeController::update_configuration` calls and shared with all
262 /// subcomponents of the compute controller.
263 dyncfg: Arc<ConfigSet>,
264 /// The replica-local scoped overrides of [`Self::dyncfg`], by replica.
265 ///
266 /// Sparse, and kept here in addition to on the `Instance`s because replica
267 /// configuration that the controller resolves once, at replica creation,
268 /// must be read through the new replica's overrides.
269 replica_dyncfg_overrides: BTreeMap<ReplicaId, ConfigUpdates>,
270
271 /// Receiver for responses produced by `Instance`s.
272 response_rx: mpsc::UnboundedReceiver<ComputeControllerResponse>,
273 /// Response sender that's passed to new `Instance`s.
274 response_tx: mpsc::UnboundedSender<ComputeControllerResponse>,
275 /// Receiver for introspection updates produced by `Instance`s.
276 ///
277 /// When [`ComputeController::start_introspection_sink`] is first called, this receiver is
278 /// passed to the introspection sink task.
279 introspection_rx: Option<mpsc::UnboundedReceiver<IntrospectionUpdates>>,
280 /// Introspection updates sender that's passed to new `Instance`s.
281 introspection_tx: mpsc::UnboundedSender<IntrospectionUpdates>,
282
283 /// Ticker for scheduling periodic maintenance work.
284 maintenance_ticker: tokio::time::Interval,
285 /// Whether maintenance work was scheduled.
286 maintenance_scheduled: bool,
287}
288
289impl ComputeController {
290 /// Construct a new [`ComputeController`].
291 pub fn new(
292 build_info: &'static BuildInfo,
293 storage_collections: StorageCollections,
294 read_only: bool,
295 metrics_registry: &MetricsRegistry,
296 peek_stash_persist_location: PersistLocation,
297 controller_metrics: ControllerMetrics,
298 now: NowFn,
299 wallclock_lag: WallclockLagFn<Timestamp>,
300 ) -> Self {
301 let (response_tx, response_rx) = mpsc::unbounded_channel();
302 let (introspection_tx, introspection_rx) = mpsc::unbounded_channel();
303
304 let mut maintenance_ticker = time::interval(Duration::from_secs(1));
305 maintenance_ticker.set_missed_tick_behavior(MissedTickBehavior::Skip);
306
307 let instance_workload_classes = Arc::new(Mutex::new(BTreeMap::<
308 ComputeInstanceId,
309 Option<String>,
310 >::new()));
311
312 // Apply a `workload_class` label to all metrics in the registry that
313 // have an `instance_id` label for an instance whose workload class is
314 // known.
315 metrics_registry.register_postprocessor({
316 let instance_workload_classes = Arc::clone(&instance_workload_classes);
317 move |metrics| {
318 let instance_workload_classes = instance_workload_classes
319 .lock()
320 .expect("lock poisoned")
321 .iter()
322 .map(|(id, workload_class)| (id.to_string(), workload_class.clone()))
323 .collect::<BTreeMap<String, Option<String>>>();
324 for metric in metrics {
325 'metric: for metric in metric.mut_metric() {
326 for label in metric.get_label() {
327 if label.name() == "instance_id" {
328 if let Some(workload_class) = instance_workload_classes
329 .get(label.value())
330 .cloned()
331 .flatten()
332 {
333 let mut label = LabelPair::default();
334 label.set_name("workload_class".into());
335 label.set_value(workload_class.clone());
336
337 let mut labels = metric.take_label();
338 labels.push(label);
339 metric.set_label(labels);
340 }
341 continue 'metric;
342 }
343 }
344 }
345 }
346 }
347 });
348
349 let metrics = ComputeControllerMetrics::new(metrics_registry, controller_metrics);
350
351 Self {
352 instances: BTreeMap::new(),
353 instance_workload_classes,
354 build_info,
355 storage_collections,
356 initialized: false,
357 read_only,
358 config: Default::default(),
359 peek_stash_persist_location,
360 stashed_response: None,
361 metrics,
362 now,
363 wallclock_lag,
364 dyncfg: Arc::new(mz_dyncfgs::all_dyncfgs()),
365 replica_dyncfg_overrides: BTreeMap::new(),
366 response_rx,
367 response_tx,
368 introspection_rx: Some(introspection_rx),
369 introspection_tx,
370 maintenance_ticker,
371 maintenance_scheduled: false,
372 }
373 }
374
375 /// Start sinking the compute controller's introspection data into storage.
376 ///
377 /// This method should be called once the introspection collections have been registered with
378 /// the storage controller. It will panic if invoked earlier than that.
379 pub fn start_introspection_sink(&mut self, storage_controller: &dyn StorageController) {
380 if let Some(rx) = self.introspection_rx.take() {
381 spawn_introspection_sink(rx, storage_controller);
382 }
383 }
384
385 /// TODO(database-issues#7533): Add documentation.
386 pub fn instance_exists(&self, id: ComputeInstanceId) -> bool {
387 self.instances.contains_key(&id)
388 }
389
390 /// Return a reference to the indicated compute instance.
391 fn instance(&self, id: ComputeInstanceId) -> Result<&InstanceState, InstanceMissing> {
392 self.instances.get(&id).ok_or(InstanceMissing(id))
393 }
394
395 /// Return an `InstanceClient` for the indicated compute instance.
396 pub fn instance_client(
397 &self,
398 id: ComputeInstanceId,
399 ) -> Result<InstanceClient, InstanceMissing> {
400 self.instance(id).map(|instance| instance.client.clone())
401 }
402
403 /// Return a mutable reference to the indicated compute instance.
404 fn instance_mut(
405 &mut self,
406 id: ComputeInstanceId,
407 ) -> Result<&mut InstanceState, InstanceMissing> {
408 self.instances.get_mut(&id).ok_or(InstanceMissing(id))
409 }
410
411 /// List the IDs of all collections in the identified compute instance.
412 pub fn collection_ids(
413 &self,
414 instance_id: ComputeInstanceId,
415 ) -> Result<impl Iterator<Item = GlobalId> + '_, InstanceMissing> {
416 let instance = self.instance(instance_id)?;
417 let ids = instance.collections.keys().copied();
418 Ok(ids)
419 }
420
421 /// Return the frontiers of the indicated collection.
422 ///
423 /// If an `instance_id` is provided, the collection is assumed to be installed on that
424 /// instance. Otherwise all available instances are searched.
425 pub fn collection_frontiers(
426 &self,
427 collection_id: GlobalId,
428 instance_id: Option<ComputeInstanceId>,
429 ) -> Result<CollectionFrontiers, CollectionLookupError> {
430 let collection = match instance_id {
431 Some(id) => self.instance(id)?.collection(collection_id)?,
432 None => self
433 .instances
434 .values()
435 .find_map(|i| i.collections.get(&collection_id))
436 .ok_or(CollectionMissing(collection_id))?,
437 };
438
439 Ok(collection.frontiers())
440 }
441
442 /// List compute collections that depend on the given collection.
443 pub fn collection_reverse_dependencies(
444 &self,
445 instance_id: ComputeInstanceId,
446 id: GlobalId,
447 ) -> Result<impl Iterator<Item = GlobalId> + '_, InstanceMissing> {
448 let instance = self.instance(instance_id)?;
449 let collections = instance.collections.iter();
450 let ids = collections
451 .filter_map(move |(cid, c)| c.compute_dependencies.contains(&id).then_some(*cid));
452 Ok(ids)
453 }
454
455 /// Requests whether each collection is hydrated on at least one hosting replica.
456 ///
457 /// Collections with no hosting replicas count as hydrated. Missing collections
458 /// have an error entry. A dropped response means the instance shut down
459 /// before answering. This method sends one request and does not wait for it.
460 pub fn collections_hydrated(
461 &self,
462 instance_id: ComputeInstanceId,
463 collection_ids: Vec<GlobalId>,
464 ) -> Result<
465 oneshot::Receiver<BTreeMap<GlobalId, Result<bool, CollectionMissing>>>,
466 InstanceMissing,
467 > {
468 let instance = self.instance(instance_id)?;
469 let (tx, rx) = oneshot::channel();
470 instance.call(move |i| {
471 let result = collection_ids
472 .into_iter()
473 .map(|id| (id, i.collection_hydrated(id)))
474 .collect();
475 let _ = tx.send(result);
476 });
477 Ok(rx)
478 }
479
480 /// Returns `true` if all non-transient, non-excluded collections are ready on any of the
481 /// provided replicas: hydrated, and, when `allowed_lag` is `Some`, no further than that
482 /// behind the furthest output frontier any of the `reference_replicas` reports for the
483 /// collection.
484 ///
485 /// See `Instance::collections_ready_on_replicas` for why hydration alone is not a
486 /// readiness signal for a cut-over.
487 ///
488 /// For this check, zero-replica clusters are always considered ready.
489 /// Their collections would never normally be considered hydrated but it's
490 /// clearly intentional that they have no replicas.
491 pub fn collections_ready_for_replicas(
492 &self,
493 instance_id: ComputeInstanceId,
494 replicas: Vec<ReplicaId>,
495 exclude_collections: BTreeSet<GlobalId>,
496 allowed_lag: Option<Timestamp>,
497 reference_replicas: BTreeSet<ReplicaId>,
498 ) -> Result<oneshot::Receiver<bool>, anyhow::Error> {
499 let instance = self.instance(instance_id)?;
500
501 // Validation
502 if !instance.replicas.is_empty()
503 && !replicas.iter().any(|id| instance.replicas.contains(id))
504 {
505 return Err(HydrationCheckBadTarget(replicas).into());
506 }
507
508 let (tx, rx) = oneshot::channel();
509 instance.call(move |i| {
510 let result = i
511 .collections_ready_on_replicas(
512 Some(replicas),
513 &exclude_collections,
514 allowed_lag,
515 &reference_replicas,
516 )
517 .expect("validated");
518 let _ = tx.send(result);
519 });
520
521 Ok(rx)
522 }
523
524 /// Returns the state of the [`ComputeController`] formatted as JSON.
525 ///
526 /// The returned value is not guaranteed to be stable and may change at any point in time.
527 pub async fn dump(&self) -> Result<serde_json::Value, anyhow::Error> {
528 // Note: We purposefully use the `Debug` formatting for the value of all fields in the
529 // returned object as a tradeoff between usability and stability. `serde_json` will fail
530 // to serialize an object if the keys aren't strings, so `Debug` formatting the values
531 // prevents a future unrelated change from silently breaking this method.
532
533 // Destructure `self` here so we don't forget to consider dumping newly added fields.
534 let Self {
535 instances,
536 instance_workload_classes,
537 build_info: _,
538 storage_collections: _,
539 initialized,
540 read_only,
541 config: _,
542 peek_stash_persist_location: _,
543 stashed_response,
544 metrics: _,
545 now: _,
546 wallclock_lag: _,
547 dyncfg: _,
548 replica_dyncfg_overrides: _,
549 response_rx: _,
550 response_tx: _,
551 introspection_rx: _,
552 introspection_tx: _,
553 maintenance_ticker: _,
554 maintenance_scheduled,
555 } = self;
556
557 let mut instances_dump = BTreeMap::new();
558 for (id, instance) in instances {
559 let dump = instance.dump().await?;
560 instances_dump.insert(id.to_string(), dump);
561 }
562
563 let instance_workload_classes: BTreeMap<_, _> = instance_workload_classes
564 .lock()
565 .expect("lock poisoned")
566 .iter()
567 .map(|(id, wc)| (id.to_string(), format!("{wc:?}")))
568 .collect();
569
570 Ok(serde_json::json!({
571 "instances": instances_dump,
572 "instance_workload_classes": instance_workload_classes,
573 "initialized": initialized,
574 "read_only": read_only,
575 "stashed_response": format!("{stashed_response:?}"),
576 "maintenance_scheduled": maintenance_scheduled,
577 }))
578 }
579}
580
581impl ComputeController {
582 /// Create a compute instance.
583 pub fn create_instance(
584 &mut self,
585 id: ComputeInstanceId,
586 arranged_logs: BTreeMap<LogVariant, GlobalId>,
587 workload_class: Option<String>,
588 ) -> Result<(), InstanceExists> {
589 if self.instances.contains_key(&id) {
590 return Err(InstanceExists(id));
591 }
592
593 let mut collections = BTreeMap::new();
594 let mut logs = Vec::with_capacity(arranged_logs.len());
595 for (&log, &id) in &arranged_logs {
596 let collection = Collection::new_log();
597 let shared = collection.shared.clone();
598 collections.insert(id, collection);
599 logs.push((log, id, shared));
600 }
601
602 let client = InstanceClient::spawn(
603 id,
604 self.build_info,
605 Arc::clone(&self.storage_collections),
606 self.peek_stash_persist_location.clone(),
607 logs,
608 self.metrics.for_instance(id),
609 self.now.clone(),
610 self.wallclock_lag.clone(),
611 Arc::clone(&self.dyncfg),
612 self.response_tx.clone(),
613 self.introspection_tx.clone(),
614 self.read_only,
615 );
616
617 let instance = InstanceState::new(client, collections);
618 self.instances.insert(id, instance);
619
620 self.instance_workload_classes
621 .lock()
622 .expect("lock poisoned")
623 .insert(id, workload_class.clone());
624
625 let instance = self.instances.get_mut(&id).expect("instance just added");
626 if self.initialized {
627 instance.call(Instance::initialization_complete);
628 }
629
630 // The replica also receives the current dyncfg create-time, folded into `CreateInstance`
631 // so create-time setup observes synced values. This `UpdateConfiguration` is still
632 // required: it carries the rest of `ComputeParameters` (workload class, max result size,
633 // tracing) and syncs the dyncfg into the persist config and metrics, none of which ride in
634 // `CreateInstance`. The overlapping dyncfg application is idempotent.
635 let mut config_params = self.config.clone();
636 config_params.workload_class = Some(workload_class);
637 instance.call(|i| i.update_configuration(config_params));
638
639 Ok(())
640 }
641
642 /// Updates a compute instance's workload class.
643 pub fn update_instance_workload_class(
644 &mut self,
645 id: ComputeInstanceId,
646 workload_class: Option<String>,
647 ) -> Result<(), InstanceMissing> {
648 // Ensure that the instance exists first.
649 let _ = self.instance(id)?;
650
651 self.instance_workload_classes
652 .lock()
653 .expect("lock poisoned")
654 .insert(id, workload_class);
655
656 // Cause a config update to notify the instance about its new workload class.
657 self.update_configuration(Default::default());
658
659 Ok(())
660 }
661
662 /// Remove a compute instance.
663 ///
664 /// # Panics
665 ///
666 /// Panics if the identified `instance` still has active replicas.
667 pub fn drop_instance(&mut self, id: ComputeInstanceId) {
668 if let Some(instance) = self.instances.remove(&id) {
669 instance.call(|i| i.shutdown());
670 }
671
672 self.instance_workload_classes
673 .lock()
674 .expect("lock poisoned")
675 .remove(&id);
676 }
677
678 /// Returns the compute controller's config set.
679 pub fn dyncfg(&self) -> &Arc<ConfigSet> {
680 &self.dyncfg
681 }
682
683 /// Update compute configuration.
684 pub fn update_configuration(&mut self, config_params: ComputeParameters) {
685 // Apply dyncfg updates.
686 config_params.dyncfg_updates.apply(&self.dyncfg);
687
688 let instance_workload_classes = self
689 .instance_workload_classes
690 .lock()
691 .expect("lock poisoned");
692
693 // Forward updates to existing clusters.
694 // Workload classes are cluster-specific, so we need to overwrite them here.
695 for (id, instance) in self.instances.iter_mut() {
696 let mut params = config_params.clone();
697 params.workload_class = Some(instance_workload_classes[id].clone());
698 instance.call(|i| i.update_configuration(params));
699 }
700
701 let overflowing_behavior = ORE_OVERFLOWING_BEHAVIOR.get(&self.dyncfg);
702 match overflowing_behavior.parse() {
703 Ok(behavior) => mz_ore::overflowing::set_behavior(behavior),
704 Err(err) => {
705 tracing::error!(
706 err,
707 overflowing_behavior,
708 "Invalid value for ore_overflowing_behavior"
709 );
710 }
711 }
712
713 // Remember updates for future clusters.
714 self.config.update(config_params);
715 }
716
717 /// Replaces the per-replica dyncfg overrides for the given instances.
718 ///
719 /// This only stores the overrides, here and on the instances; callers
720 /// should follow with a configuration push (e.g.
721 /// [`Self::update_configuration`]) so existing replicas observe the new
722 /// values. Instances absent from `overrides` have their overrides cleared,
723 /// so a replica that no longer has an override reverts to the
724 /// environment-wide configuration. Used by the scoped feature flags
725 /// (replica-local) layer.
726 pub fn update_replica_dyncfg_overrides(
727 &mut self,
728 mut overrides: BTreeMap<ComputeInstanceId, BTreeMap<ReplicaId, ConfigUpdates>>,
729 ) {
730 self.replica_dyncfg_overrides = overrides
731 .values()
732 .flat_map(|replicas| replicas.iter())
733 .map(|(replica_id, updates)| (*replica_id, updates.clone()))
734 .collect();
735 for (id, instance) in self.instances.iter_mut() {
736 let instance_overrides = overrides.remove(id).unwrap_or_default();
737 instance.call(move |i| i.update_replica_dyncfg_overrides(instance_overrides));
738 }
739 }
740
741 /// Mark the end of any initialization commands.
742 ///
743 /// The implementor may wait for this method to be called before implementing prior commands,
744 /// and so it is important for a user to invoke this method as soon as it is comfortable.
745 /// This method can be invoked immediately, at the potential expense of performance.
746 pub fn initialization_complete(&mut self) {
747 self.initialized = true;
748 for instance in self.instances.values_mut() {
749 instance.call(Instance::initialization_complete);
750 }
751 }
752
753 /// Wait until the controller is ready to do some processing.
754 ///
755 /// This method may block for an arbitrarily long time.
756 ///
757 /// When the method returns, the caller should call [`ComputeController::process`].
758 ///
759 /// This method is cancellation safe.
760 pub async fn ready(&mut self) {
761 if self.stashed_response.is_some() {
762 // We still have a response stashed, which we are immediately ready to process.
763 return;
764 }
765 if self.maintenance_scheduled {
766 // Maintenance work has been scheduled.
767 return;
768 }
769
770 tokio::select! {
771 resp = self.response_rx.recv() => {
772 let resp = resp.expect("`self.response_tx` not dropped");
773 self.stashed_response = Some(resp);
774 }
775 _ = self.maintenance_ticker.tick() => {
776 self.maintenance_scheduled = true;
777 },
778 }
779 }
780
781 /// Adds replicas of an instance.
782 pub fn add_replica_to_instance(
783 &mut self,
784 instance_id: ComputeInstanceId,
785 replica_id: ReplicaId,
786 location: ClusterReplicaLocation,
787 config: ComputeReplicaConfig,
788 ) -> Result<(), ReplicaCreationError> {
789 use ReplicaCreationError::*;
790
791 let instance = self.instance(instance_id)?;
792
793 // Validation
794 if instance.replicas.contains(&replica_id) {
795 return Err(ReplicaExists(replica_id));
796 }
797
798 let (enable_logging, interval) = match config.logging.interval {
799 Some(interval) => (true, interval),
800 None => (false, Duration::from_secs(1)),
801 };
802
803 // Both configs below are `ParameterScope::Replica` and are resolved
804 // here, once, for the replica being created. Reading them through the
805 // new replica's scoped overrides is what makes those declarations
806 // effective: the values are frozen into `ReplicaConfig` and never
807 // re-read from the environment-wide set. The overrides for a replica
808 // created by DDL are committed in the same transaction that creates it,
809 // so they are already installed by the time we get here.
810 let overrides = self.replica_dyncfg_overrides.get(&replica_id);
811
812 let expiration_offset =
813 COMPUTE_REPLICA_EXPIRATION_OFFSET.get_with_overrides(&self.dyncfg, overrides);
814
815 // Capture dictionary compression once, at replica creation, and hold it fixed for the
816 // replica's lifetime (see `InstanceConfig::arrangement_dictionary_compression`). This is
817 // why a later flip of the flag only affects replicas created afterwards. The feature flag
818 // only gates the feature: a replica honors its per-cluster/replica configured value only
819 // while the flag is enabled, so turning the flag off disables compression on new or
820 // restarted replicas regardless of their configuration.
821 let arrangement_dictionary_compression = ENABLE_ARRANGEMENT_DICTIONARY_COMPRESSION_ALPHA
822 .get_with_overrides(&self.dyncfg, overrides)
823 && config.arrangement_compression;
824
825 let replica_config = ReplicaConfig {
826 location,
827 logging: LoggingConfig {
828 interval,
829 enable_logging,
830 log_logging: config.logging.log_logging,
831 index_logs: Default::default(),
832 },
833 grpc_client: self.config.grpc_client.clone(),
834 expiration_offset: (!expiration_offset.is_zero()).then_some(expiration_offset),
835 arrangement_dictionary_compression,
836 };
837
838 let dyncfg_override = overrides.cloned().unwrap_or_default();
839
840 let instance = self.instance_mut(instance_id).expect("validated");
841 instance.replicas.insert(replica_id);
842
843 instance.call(move |i| {
844 i.add_replica(replica_id, replica_config, None, dyncfg_override)
845 .expect("validated")
846 });
847
848 Ok(())
849 }
850
851 /// Removes a replica from an instance, including its service in the orchestrator.
852 pub fn drop_replica(
853 &mut self,
854 instance_id: ComputeInstanceId,
855 replica_id: ReplicaId,
856 ) -> Result<(), ReplicaDropError> {
857 use ReplicaDropError::*;
858
859 let instance = self.instance_mut(instance_id)?;
860
861 // Validation
862 if !instance.replicas.contains(&replica_id) {
863 return Err(ReplicaMissing(replica_id));
864 }
865
866 instance.replicas.remove(&replica_id);
867
868 // The coordinator only re-pushes the override map when the scoped
869 // configuration itself changes, so a dropped replica's entry would
870 // otherwise be retained until the next such change.
871 self.replica_dyncfg_overrides.remove(&replica_id);
872
873 let instance = self.instance_mut(instance_id).expect("validated");
874 instance.call(move |i| i.remove_replica(replica_id).expect("validated"));
875
876 Ok(())
877 }
878
879 /// Creates the described dataflow and initializes state for its output.
880 ///
881 /// Only sink exports are allowed to have a `target_replica`: materialized views, subscribes,
882 /// and metric sinks. A user's `CREATE METRIC SINK` runs untargeted, so every replica renders it
883 /// into its own registry. The coordinator's curated metric sinks are installed per replica and
884 /// do target one, so each replica's series are attributable to it.
885 ///
886 /// Panics if called with a dataflow description that has index exports
887 /// when `target_replica` is set.
888 pub fn create_dataflow(
889 &mut self,
890 instance_id: ComputeInstanceId,
891 mut dataflow: mz_compute_types::dataflows::LirDataflowDescription,
892 target_replica: Option<ReplicaId>,
893 ) -> Result<(), DataflowCreationError> {
894 use DataflowCreationError::*;
895
896 let instance = self.instance(instance_id)?;
897
898 // Validation: target replica
899 if let Some(replica_id) = target_replica {
900 if !instance.replicas.contains(&replica_id) {
901 return Err(ReplicaMissing(replica_id));
902 }
903 assert!(
904 dataflow.exported_index_ids().next().is_none(),
905 "Replica-targeted indexes are not supported"
906 );
907 }
908
909 // Validation: as_of
910 let as_of = dataflow.as_of.as_ref().ok_or(MissingAsOf)?;
911 if as_of.is_empty() && dataflow.subscribe_ids().next().is_some() {
912 return Err(EmptyAsOfForSubscribe);
913 }
914 if as_of.is_empty() && dataflow.copy_to_ids().next().is_some() {
915 return Err(EmptyAsOfForCopyTo);
916 }
917
918 // Validation: the dataflow exports something
919 //
920 // An export-less description has nothing to render and no answer to "what do the exports
921 // read", which the checks below are phrased in terms of. `optimize_dataflow` leaves such a
922 // description's imports alone for that reason, so one arriving here would fail the import
923 // check for the wrong reason.
924 soft_assert_or_log!(
925 !dataflow.index_exports.is_empty() || !dataflow.sink_exports.is_empty(),
926 "dataflow {} has no exports",
927 dataflow.debug_name,
928 );
929
930 // The imports the exports actually read. `optimize_dataflow` prunes the import list to
931 // exactly this set, so the two agree unless a producer stopped pruning.
932 //
933 // Computed once and used twice: the check below reports a loose list, and
934 // `determine_time_dependence` counts through it rather than over the raw list. That
935 // consumer is the one whose wrong answer hangs an environment: an import no export reads
936 // would report wall-clock dependence for a dataflow whose exports are constant, earning it
937 // a dataflow expiration that pins the output frontier days short of the empty antichain,
938 // and nothing downstream would learn the collection is final. Deriving it from this set
939 // makes that correct by construction, leaving the prune to reclaim the read hold and the
940 // persist source.
941 let used_imports = dataflow.used_import_ids();
942
943 // Validation: every import is read
944 //
945 // The read holds and the persist sources the replicas build are still derived from the raw
946 // list below, so a loose one describes a dataflow other than the one that will run. A
947 // logging variant rather than `soft_assert_no_log!`: the walk is paid for above either way,
948 // so reporting it in production costs only the comparison.
949 soft_assert_or_log!(
950 dataflow.import_ids().all(|id| used_imports.contains(&id)),
951 "dataflow {} imports collections no export reads: imports {:?}, read {:?}",
952 dataflow.debug_name,
953 dataflow.import_ids().collect::<Vec<_>>(),
954 used_imports,
955 );
956
957 // Validation: input collections
958 let storage_ids = dataflow.imported_source_ids().collect();
959 let mut import_read_holds = self.storage_collections.acquire_read_holds(storage_ids)?;
960 for id in dataflow.imported_index_ids() {
961 let read_hold = instance.acquire_read_hold(id)?;
962 import_read_holds.push(read_hold);
963 }
964 for hold in &import_read_holds {
965 if PartialOrder::less_than(as_of, hold.since()) {
966 return Err(SinceViolation(hold.id()));
967 }
968 }
969
970 // Validation: storage sink collections
971 for id in dataflow.persist_sink_ids() {
972 if self.storage_collections.check_exists(id).is_err() {
973 return Err(CollectionMissing(id));
974 }
975 }
976 let time_dependence = self
977 .determine_time_dependence(instance_id, &dataflow, &used_imports)
978 .expect("must exist");
979
980 let instance = self.instance_mut(instance_id).expect("validated");
981
982 let mut shared_collection_state = BTreeMap::new();
983 for id in dataflow.export_ids() {
984 let shared = SharedCollectionState::new(as_of.clone());
985 let collection = Collection {
986 write_only: dataflow.sink_exports.contains_key(&id),
987 compute_dependencies: dataflow.imported_index_ids().collect(),
988 shared: shared.clone(),
989 time_dependence: time_dependence.clone(),
990 };
991 instance.collections.insert(id, collection);
992 shared_collection_state.insert(id, shared);
993 }
994
995 dataflow.time_dependence = time_dependence;
996
997 instance.call(move |i| {
998 i.create_dataflow(
999 dataflow,
1000 import_read_holds,
1001 shared_collection_state,
1002 target_replica,
1003 )
1004 .expect("validated")
1005 });
1006
1007 Ok(())
1008 }
1009
1010 /// Drop the read capability for the given collections and allow their resources to be
1011 /// reclaimed.
1012 pub fn drop_collections(
1013 &mut self,
1014 instance_id: ComputeInstanceId,
1015 collection_ids: Vec<GlobalId>,
1016 ) -> Result<(), CollectionUpdateError> {
1017 let instance = self.instance_mut(instance_id)?;
1018
1019 // Validation
1020 for id in &collection_ids {
1021 instance.collection(*id)?;
1022 }
1023
1024 for id in &collection_ids {
1025 instance.collections.remove(id);
1026 }
1027
1028 instance.call(|i| i.drop_collections(collection_ids).expect("validated"));
1029
1030 Ok(())
1031 }
1032
1033 /// Initiate a peek request for the contents of the given collection at `timestamp`.
1034 ///
1035 /// The caller supplies a `read_hold` for the peek target — via
1036 /// [`ComputeController::acquire_read_hold`] for `PeekTarget::Index`, or via the storage
1037 /// collections for `PeekTarget::Persist`. The hold keeps the collection's `since` at
1038 /// `<= timestamp` until the peek completes.
1039 ///
1040 /// `lifecycle` has the contract documented on [`InstanceClient::peek`]. The
1041 /// caller must also retire it if this returns `Err`.
1042 pub fn peek(
1043 &self,
1044 instance_id: ComputeInstanceId,
1045 peek_target: PeekTarget,
1046 literal_constraints: Option<Vec<Row>>,
1047 uuid: Uuid,
1048 timestamp: Timestamp,
1049 result_desc: RelationDesc,
1050 finishing: RowSetFinishing,
1051 map_filter_project: mz_expr::SafeMfpPlan,
1052 read_hold: ReadHold,
1053 target_replica: Option<ReplicaId>,
1054 peek_response_tx: oneshot::Sender<PeekResponse>,
1055 lifecycle: Option<Arc<PeekLifecycle>>,
1056 ) -> Result<(), PeekError> {
1057 use PeekError::*;
1058
1059 let instance = self.instance(instance_id)?;
1060
1061 // Validation: target replica
1062 if let Some(replica_id) = target_replica {
1063 if !instance.replicas.contains(&replica_id) {
1064 return Err(ReplicaMissing(replica_id));
1065 }
1066 }
1067
1068 // Validation: the read hold must target this collection and must hold its `since`
1069 // at `<= timestamp`.
1070 if read_hold.id() != peek_target.id() {
1071 return Err(ReadHoldIdMismatch(read_hold.id()));
1072 }
1073 if !read_hold.since().less_equal(×tamp) {
1074 return Err(SinceViolation(peek_target.id()));
1075 }
1076
1077 let issue = instance.client.peek_command(
1078 peek_target,
1079 literal_constraints,
1080 uuid,
1081 timestamp,
1082 result_desc,
1083 finishing,
1084 map_filter_project,
1085 read_hold,
1086 target_replica,
1087 peek_response_tx,
1088 lifecycle,
1089 );
1090 instance.call(move |i| issue(i).expect("validated"));
1091
1092 Ok(())
1093 }
1094
1095 /// Cancel an existing peek request.
1096 ///
1097 /// Canceling a peek is best effort. The caller may see any of the following
1098 /// after canceling a peek request:
1099 ///
1100 /// * A `PeekResponse::Rows` indicating that the cancellation request did
1101 /// not take effect in time and the query succeeded.
1102 /// * A `PeekResponse::Canceled` affirming that the peek was canceled.
1103 /// * No `PeekResponse` at all.
1104 pub fn cancel_peek(
1105 &self,
1106 instance_id: ComputeInstanceId,
1107 uuid: Uuid,
1108 reason: PeekResponse,
1109 ) -> Result<(), InstanceMissing> {
1110 self.instance(instance_id)?
1111 .call(move |i| i.cancel_peek(uuid, reason));
1112 Ok(())
1113 }
1114
1115 /// Assign a read policy to specific identifiers.
1116 ///
1117 /// The policies are assigned in the order presented, and repeated identifiers should
1118 /// conclude with the last policy. Changing a policy will immediately downgrade the read
1119 /// capability if appropriate, but it will not "recover" the read capability if the prior
1120 /// capability is already ahead of it.
1121 ///
1122 /// Identifiers not present in `policies` retain their existing read policies.
1123 ///
1124 /// It is an error to attempt to set a read policy for a collection that is not readable in the
1125 /// context of compute. At this time, only indexes are readable compute collections.
1126 pub fn set_read_policy(
1127 &self,
1128 instance_id: ComputeInstanceId,
1129 policies: Vec<(GlobalId, ReadPolicy)>,
1130 ) -> Result<(), ReadPolicyError> {
1131 use ReadPolicyError::*;
1132
1133 let instance = self.instance(instance_id)?;
1134
1135 // Validation
1136 for (id, _) in &policies {
1137 let collection = instance.collection(*id)?;
1138 if collection.write_only {
1139 return Err(WriteOnlyCollection(*id));
1140 }
1141 }
1142
1143 self.instance(instance_id)?
1144 .call(|i| i.set_read_policy(policies).expect("validated"));
1145
1146 Ok(())
1147 }
1148
1149 /// Acquires a [`ReadHold`] for the identified compute collection.
1150 pub fn acquire_read_hold(
1151 &self,
1152 instance_id: ComputeInstanceId,
1153 collection_id: GlobalId,
1154 ) -> Result<ReadHold, CollectionUpdateError> {
1155 let read_hold = self
1156 .instance(instance_id)?
1157 .acquire_read_hold(collection_id)?;
1158 Ok(read_hold)
1159 }
1160
1161 /// Determine the time dependence for a dataflow.
1162 ///
1163 /// `used_imports` are the imports the exports read, as
1164 /// [`DataflowDescription::used_import_ids`] reports them. Only those count: an import no export
1165 /// reads would report wall-clock dependence for a dataflow whose exports are constant, and that
1166 /// earns it a dataflow expiration, which pins its output frontier at the expiration time. A
1167 /// constant export's frontier is the empty antichain, so the pin would hold it days short of
1168 /// the truth and whoever reads that frontier would never learn the collection can no longer
1169 /// change.
1170 ///
1171 /// `optimize_dataflow` prunes the import list to this set, so the two agree and the filtering
1172 /// is a no-op. It is here because this is the consumer whose wrong answer hangs an environment,
1173 /// and deriving the answer from the read set makes it independent of the list staying tight.
1174 ///
1175 /// [`DataflowDescription::used_import_ids`]: mz_compute_types::dataflows::DataflowDescription::used_import_ids
1176 fn determine_time_dependence(
1177 &self,
1178 instance_id: ComputeInstanceId,
1179 dataflow: &mz_compute_types::dataflows::LirDataflowDescription,
1180 used_imports: &BTreeSet<GlobalId>,
1181 ) -> Result<Option<TimeDependence>, TimeDependenceError> {
1182 let instance = self
1183 .instance(instance_id)
1184 .map_err(|err| TimeDependenceError::InstanceMissing(err.0))?;
1185 let mut time_dependencies = Vec::new();
1186
1187 for id in dataflow
1188 .imported_index_ids()
1189 .filter(|id| used_imports.contains(id))
1190 {
1191 let dependence = instance
1192 .get_time_dependence(id)
1193 .map_err(|err| TimeDependenceError::CollectionMissing(err.0))?;
1194 time_dependencies.push(dependence);
1195 }
1196
1197 'source: for id in dataflow
1198 .imported_source_ids()
1199 .filter(|id| used_imports.contains(id))
1200 {
1201 // We first check whether the id is backed by a compute object, in which case we use
1202 // the time dependence we know. This is true for storage sinks.
1203 for instance in self.instances.values() {
1204 if let Ok(dependence) = instance.get_time_dependence(id) {
1205 time_dependencies.push(dependence);
1206 continue 'source;
1207 }
1208 }
1209
1210 // Not a compute object: Consult the storage collections controller.
1211 time_dependencies.push(self.storage_collections.determine_time_dependence(id)?);
1212 }
1213
1214 Ok(TimeDependence::merge(
1215 time_dependencies,
1216 dataflow.refresh_schedule.as_ref(),
1217 ))
1218 }
1219
1220 /// Processes the work queued by [`ComputeController::ready`].
1221 #[mz_ore::instrument(level = "debug")]
1222 pub fn process(&mut self) -> Option<ComputeControllerResponse> {
1223 // Perform periodic maintenance work.
1224 if self.maintenance_scheduled {
1225 self.maintain();
1226 self.maintenance_scheduled = false;
1227 }
1228
1229 // Return a ready response, if any.
1230 self.stashed_response.take()
1231 }
1232
1233 #[mz_ore::instrument(level = "debug")]
1234 fn maintain(&mut self) {
1235 // Perform instance maintenance work.
1236 for instance in self.instances.values_mut() {
1237 instance.call(Instance::maintain);
1238 }
1239 }
1240
1241 /// Allow writes for the specified collections on `instance_id`.
1242 ///
1243 /// If this controller is in read-only mode, this is a no-op.
1244 pub fn allow_writes(
1245 &mut self,
1246 instance_id: ComputeInstanceId,
1247 collection_id: GlobalId,
1248 ) -> Result<(), CollectionUpdateError> {
1249 if self.read_only {
1250 tracing::debug!("Skipping allow_writes in read-only mode");
1251 return Ok(());
1252 }
1253
1254 self.allow_writes_inner(instance_id, collection_id)
1255 }
1256
1257 /// Like [`Self::allow_writes`], but takes effect even in read-only mode.
1258 ///
1259 /// The caller must guarantee that no leader environment writes the collection's output shard.
1260 /// In a 0dt deployment that means a shard this environment created for itself, such as the
1261 /// replacement shard of a `Replacement`-migrated builtin collection, never one the leader is
1262 /// still serving from. `Evolution` migrates in place and reuses the leader's shard, so it must
1263 /// not reach this path. Violating the guarantee races two writers on one shard.
1264 ///
1265 /// NOTE: ownership is exclusive per (build version, deploy generation), not per process: the
1266 /// migration shard entry naming the shard is keyed by that pair and a read-only catalog open is
1267 /// a savepoint, so two read-only processes of one generation both write it. Same shape as a
1268 /// multi-replica materialized view, which the self-correcting persist sink tolerates (see the
1269 /// `mz_compute::sink::materialized_view` module docs).
1270 ///
1271 /// This is the compute-side counterpart to the storage controller's `force_writable` handling
1272 /// of migrated storage collections. Migrated builtin tables are storage collections that
1273 /// storage force-writes read-only; migrated builtin MVs are compute collections that only this
1274 /// path can force-write. Both rest on the same guarantee (this environment exclusively owns the
1275 /// shard) but run on separate write paths, so each needs its own bypass.
1276 ///
1277 /// NOTE: the replica-side handler enables persist compaction process-wide on the clusterd
1278 /// (`ComputeState::handle_allow_writes`), which this path is the first to trigger inside a
1279 /// read-only deployment.
1280 pub fn allow_writes_in_read_only(
1281 &mut self,
1282 instance_id: ComputeInstanceId,
1283 collection_id: GlobalId,
1284 ) -> Result<(), CollectionUpdateError> {
1285 // Every builtin eligible for this bypass has a system id, so a non-system id means the
1286 // caller's invariant (only shards from the builtin migration shard) broke. No-op rather
1287 // than risk writing a shard the leader still serves. The collection then sits in the
1288 // caught-up gate on an unwritten shard and blocks promotion, which is the loud, safe
1289 // direction to fail.
1290 //
1291 // Storage asserts the same invariant hard, in
1292 // `StorageController::register_introspection_collection`. The asymmetry is deliberate: a
1293 // soft panic keeps a caller bug visible in CI and Sentry without downing production.
1294 if self.read_only && !collection_id.is_system() {
1295 soft_panic_or_log!(
1296 "allow_writes_in_read_only called for non-system collection {collection_id}; \
1297 falling back to read-only no-op"
1298 );
1299 return Ok(());
1300 }
1301
1302 self.allow_writes_inner(instance_id, collection_id)
1303 }
1304
1305 fn allow_writes_inner(
1306 &mut self,
1307 instance_id: ComputeInstanceId,
1308 collection_id: GlobalId,
1309 ) -> Result<(), CollectionUpdateError> {
1310 let instance = self.instance_mut(instance_id)?;
1311
1312 // Validation
1313 instance.collection(collection_id)?;
1314
1315 instance.call(move |i| i.allow_writes(collection_id).expect("validated"));
1316
1317 Ok(())
1318 }
1319}
1320
1321#[derive(Debug)]
1322struct InstanceState {
1323 client: InstanceClient,
1324 replicas: BTreeSet<ReplicaId>,
1325 collections: BTreeMap<GlobalId, Collection>,
1326}
1327
1328impl InstanceState {
1329 fn new(client: InstanceClient, collections: BTreeMap<GlobalId, Collection>) -> Self {
1330 Self {
1331 client,
1332 replicas: Default::default(),
1333 collections,
1334 }
1335 }
1336
1337 fn collection(&self, id: GlobalId) -> Result<&Collection, CollectionMissing> {
1338 self.collections.get(&id).ok_or(CollectionMissing(id))
1339 }
1340
1341 /// Calls the given function on the instance task. Does not await the result.
1342 ///
1343 /// # Panics
1344 ///
1345 /// Panics if the instance corresponding to `self` does not exist.
1346 fn call<F>(&self, f: F)
1347 where
1348 F: FnOnce(&mut Instance) + Send + 'static,
1349 {
1350 self.client.call(f).expect("instance not dropped")
1351 }
1352
1353 /// Calls the given function on the instance task, and awaits the result.
1354 ///
1355 /// # Panics
1356 ///
1357 /// Panics if the instance corresponding to `self` does not exist.
1358 async fn call_sync<F, R>(&self, f: F) -> R
1359 where
1360 F: FnOnce(&mut Instance) -> R + Send + 'static,
1361 R: Send + 'static,
1362 {
1363 self.client
1364 .call_sync(f)
1365 .await
1366 .expect("instance not dropped")
1367 }
1368
1369 /// Acquires a [`ReadHold`] for the identified compute collection.
1370 pub fn acquire_read_hold(&self, id: GlobalId) -> Result<ReadHold, CollectionMissing> {
1371 // We acquire read holds at the earliest possible time rather than returning a copy
1372 // of the implied read hold. This is so that in `create_dataflow` we can acquire read holds
1373 // on compute dependencies at frontiers that are held back by other read holds the caller
1374 // has previously taken.
1375 //
1376 // If/when we change the compute API to expect callers to pass in the `ReadHold`s rather
1377 // than acquiring them ourselves, we might tighten this up and instead acquire read holds
1378 // at the implied capability.
1379
1380 let collection = self.collection(id)?;
1381 let since = collection.shared.lock_read_capabilities(|caps| {
1382 let since = caps.frontier().to_owned();
1383 caps.update_iter(since.iter().map(|t| (t.clone(), 1)));
1384 since
1385 });
1386
1387 let hold = ReadHold::new(id, since, self.client.read_hold_tx());
1388 Ok(hold)
1389 }
1390
1391 /// Return the stored time dependence for a collection.
1392 fn get_time_dependence(
1393 &self,
1394 id: GlobalId,
1395 ) -> Result<Option<TimeDependence>, CollectionMissing> {
1396 Ok(self.collection(id)?.time_dependence.clone())
1397 }
1398
1399 /// Returns the [`InstanceState`] formatted as JSON.
1400 pub async fn dump(&self) -> Result<serde_json::Value, anyhow::Error> {
1401 // Destructure `self` here so we don't forget to consider dumping newly added fields.
1402 let Self {
1403 client: _,
1404 replicas,
1405 collections,
1406 } = self;
1407
1408 let instance = self.call_sync(|i| i.dump()).await?;
1409 let replicas: Vec<_> = replicas.iter().map(|id| id.to_string()).collect();
1410 let collections: BTreeMap<_, _> = collections
1411 .iter()
1412 .map(|(id, c)| (id.to_string(), format!("{c:?}")))
1413 .collect();
1414
1415 Ok(serde_json::json!({
1416 "instance": instance,
1417 "replicas": replicas,
1418 "collections": collections,
1419 }))
1420 }
1421}
1422
1423#[derive(Debug)]
1424struct Collection {
1425 /// Whether a collection is write-only, i.e., we cannot read it directly like an index.
1426 write_only: bool,
1427 compute_dependencies: BTreeSet<GlobalId>,
1428 shared: SharedCollectionState,
1429 /// The computed time dependence for this collection. None indicates no specific information,
1430 /// a value describes how the collection relates to wall-clock time.
1431 time_dependence: Option<TimeDependence>,
1432}
1433
1434impl Collection {
1435 fn new_log() -> Self {
1436 let as_of = Antichain::from_elem(Timestamp::MIN);
1437 Self {
1438 write_only: false,
1439 compute_dependencies: Default::default(),
1440 shared: SharedCollectionState::new(as_of),
1441 time_dependence: Some(TimeDependence::default()),
1442 }
1443 }
1444
1445 fn frontiers(&self) -> CollectionFrontiers {
1446 let read_frontier = self
1447 .shared
1448 .lock_read_capabilities(|c| c.frontier().to_owned());
1449 let write_frontier = self.shared.lock_write_frontier(|f| f.clone());
1450 CollectionFrontiers {
1451 read_frontier,
1452 write_frontier,
1453 }
1454 }
1455}
1456
1457/// The frontiers of a compute collection.
1458#[derive(Clone, Debug)]
1459pub struct CollectionFrontiers {
1460 /// The read frontier.
1461 pub read_frontier: Antichain<Timestamp>,
1462 /// The write frontier.
1463 pub write_frontier: Antichain<Timestamp>,
1464}
1465
1466impl Default for CollectionFrontiers {
1467 fn default() -> Self {
1468 Self {
1469 read_frontier: Antichain::from_elem(Timestamp::MIN),
1470 write_frontier: Antichain::from_elem(Timestamp::MIN),
1471 }
1472 }
1473}