1use std::any::Any;
13use std::collections::btree_map;
14use std::collections::{BTreeMap, BTreeSet};
15use std::fmt::Debug;
16use std::str::FromStr;
17use std::sync::{Arc, Mutex};
18use std::time::Duration;
19
20use crate::collection_mgmt::{
21 AppendOnlyIntrospectionConfig, CollectionManagerKind, DifferentialIntrospectionConfig,
22};
23use crate::instance::{Instance, ReplicaConfig};
24use async_trait::async_trait;
25use chrono::{DateTime, DurationRound, TimeDelta, Utc};
26use derivative::Derivative;
27use differential_dataflow::lattice::Lattice;
28use futures::FutureExt;
29use futures::StreamExt;
30use itertools::Itertools;
31use mz_build_info::BuildInfo;
32use mz_cluster_client::client::ClusterReplicaLocation;
33use mz_cluster_client::metrics::{ControllerMetrics, WallclockLagMetrics};
34use mz_cluster_client::{ReplicaId, WallclockLagFn};
35use mz_controller_types::dyncfgs::{
36 ENABLE_0DT_DEPLOYMENT_SOURCES, WALLCLOCK_LAG_RECORDING_INTERVAL,
37};
38use mz_dyncfg::ConfigUpdates;
39use mz_ore::collections::CollectionExt;
40use mz_ore::metrics::MetricsRegistry;
41use mz_ore::now::NowFn;
42use mz_ore::task::AbortOnDropHandle;
43use mz_ore::{assert_none, halt, instrument, restart_in_place, soft_panic_or_log};
44use mz_persist_client::batch::ProtoBatch;
45use mz_persist_client::cache::PersistClientCache;
46use mz_persist_client::cfg::USE_CRITICAL_SINCE_SNAPSHOT;
47use mz_persist_client::critical::Opaque;
48use mz_persist_client::read::ReadHandle;
49use mz_persist_client::schema::CaESchema;
50use mz_persist_client::write::WriteHandle;
51use mz_persist_client::{Diagnostics, PersistClient, PersistLocation, ShardId};
52use mz_persist_types::codec_impls::UnitSchema;
53use mz_repr::adt::timestamp::CheckedTimestamp;
54use mz_repr::{Datum, Diff, GlobalId, RelationDesc, RelationVersion, Row, Timestamp};
55use mz_storage_client::client::{
56 AppendOnlyUpdate, RunIngestionCommand, RunOneshotIngestion, RunSinkCommand, Status,
57 StatusUpdate, StorageCommand, StorageResponse, TableData,
58};
59use mz_storage_client::controller::{
60 BoxFuture, CollectionDescription, DataSource, ExportDescription, ExportState,
61 IntrospectionType, MonotonicAppender, PersistEpoch, Response, StorageController,
62 StorageMetadata, StorageTxn, StorageWriteOp, TableRegistration, WallclockLag,
63 WallclockLagHistogramPeriod,
64};
65use mz_storage_client::healthcheck::{
66 MZ_AWS_PRIVATELINK_CONNECTION_STATUS_HISTORY_DESC, MZ_SINK_STATUS_HISTORY_DESC,
67 MZ_SOURCE_STATUS_HISTORY_DESC, REPLICA_STATUS_HISTORY_DESC,
68};
69use mz_storage_client::metrics::StorageControllerMetrics;
70use mz_storage_client::statistics::{
71 ControllerSinkStatistics, ControllerSourceStatistics, WebhookStatistics,
72};
73use mz_storage_client::storage_collections::{StorageCollections, shard_has_no_updates};
74use mz_storage_types::configuration::StorageConfiguration;
75use mz_storage_types::connections::ConnectionContext;
76use mz_storage_types::connections::inline::InlinedConnection;
77use mz_storage_types::controller::{AlterError, CollectionMetadata, StorageError, TxnsCodecRow};
78use mz_storage_types::errors::CollectionMissing;
79use mz_storage_types::instances::StorageInstanceId;
80use mz_storage_types::oneshot_sources::{OneshotIngestionRequest, OneshotResultCallback};
81use mz_storage_types::parameters::StorageParameters;
82use mz_storage_types::read_holds::ReadHold;
83use mz_storage_types::read_policy::ReadPolicy;
84use mz_storage_types::sinks::{StorageSinkConnection, StorageSinkDesc};
85use mz_storage_types::sources::{
86 GenericSourceConnection, IngestionDescription, SourceConnection, SourceData, SourceDesc,
87 SourceExport, SourceExportDataConfig,
88};
89use mz_storage_types::{AlterCompatible, StorageDiff, dyncfgs};
90use mz_txn_wal::metrics::Metrics as TxnMetrics;
91use mz_txn_wal::txn_read::TxnsRead;
92use mz_txn_wal::txns::TxnsHandle;
93use timely::order::PartialOrder;
94use timely::progress::frontier::MutableAntichain;
95use timely::progress::{Antichain, ChangeBatch};
96use tokio::sync::watch::{Sender, channel};
97use tokio::sync::{mpsc, oneshot};
98use tokio::time::MissedTickBehavior;
99use tokio::time::error::Elapsed;
100use tracing::{debug, info, warn};
101
102mod collection_mgmt;
103mod history;
104mod instance;
105mod persist_handles;
106mod rtr;
107mod statistics;
108
109#[derive(Derivative)]
110#[derivative(Debug)]
111struct PendingOneshotIngestion {
112 #[derivative(Debug = "ignore")]
114 result_tx: OneshotResultCallback<ProtoBatch>,
115 cluster_id: StorageInstanceId,
117}
118
119impl PendingOneshotIngestion {
120 pub(crate) fn cancel(self) {
124 (self.result_tx)(vec![Err("canceled".to_string())])
125 }
126}
127
128#[derive(Derivative)]
130#[derivative(Debug)]
131pub struct Controller {
132 build_info: &'static BuildInfo,
134 now: NowFn,
136
137 read_only: bool,
143
144 pub(crate) collections: BTreeMap<GlobalId, CollectionState>,
149
150 dropped_objects: BTreeMap<GlobalId, BTreeSet<ReplicaId>>,
159
160 pub(crate) persist_table_worker: persist_handles::PersistTableWriteWorker,
162 txns_read: TxnsRead<Timestamp>,
164 txns_metrics: Arc<TxnMetrics>,
165 stashed_responses: Vec<(Option<ReplicaId>, StorageResponse)>,
166 #[derivative(Debug = "ignore")]
168 pending_table_handle_drops_tx: mpsc::UnboundedSender<GlobalId>,
169 #[derivative(Debug = "ignore")]
171 pending_table_handle_drops_rx: mpsc::UnboundedReceiver<GlobalId>,
172 #[derivative(Debug = "ignore")]
174 pending_oneshot_ingestions: BTreeMap<uuid::Uuid, PendingOneshotIngestion>,
175
176 pub(crate) collection_manager: collection_mgmt::CollectionManager,
178
179 pub(crate) introspection_ids: BTreeMap<IntrospectionType, GlobalId>,
181 introspection_tokens: Arc<Mutex<BTreeMap<GlobalId, Box<dyn Any + Send + Sync>>>>,
186
187 source_statistics: Arc<Mutex<statistics::SourceStatistics>>,
192 sink_statistics: Arc<Mutex<BTreeMap<(GlobalId, Option<ReplicaId>), ControllerSinkStatistics>>>,
195 statistics_interval_sender: Sender<Duration>,
197
198 instances: BTreeMap<StorageInstanceId, Instance>,
200 replica_dyncfg_overrides: BTreeMap<ReplicaId, ConfigUpdates>,
205 initialized: bool,
207 config: StorageConfiguration,
209 persist_location: PersistLocation,
211 persist: Arc<PersistClientCache>,
213 metrics: StorageControllerMetrics,
215 recorded_frontiers: BTreeMap<GlobalId, (Antichain<Timestamp>, Antichain<Timestamp>)>,
218 recorded_replica_frontiers: BTreeMap<(GlobalId, ReplicaId), Antichain<Timestamp>>,
221
222 #[derivative(Debug = "ignore")]
224 wallclock_lag: WallclockLagFn<Timestamp>,
225 wallclock_lag_last_recorded: DateTime<Utc>,
227
228 storage_collections: Arc<dyn StorageCollections + Send + Sync>,
230 migrated_storage_collections: BTreeSet<GlobalId>,
232
233 maintenance_ticker: tokio::time::Interval,
235 maintenance_scheduled: bool,
237
238 instance_response_tx: mpsc::UnboundedSender<(Option<ReplicaId>, StorageResponse)>,
240 instance_response_rx: mpsc::UnboundedReceiver<(Option<ReplicaId>, StorageResponse)>,
242
243 persist_warm_task: Option<AbortOnDropHandle<Box<dyn Debug + Send>>>,
245}
246
247enum WriteHandleOrUpper {
256 Handle(WriteHandle<SourceData, (), Timestamp, StorageDiff>),
257 Upper(Antichain<Timestamp>),
258}
259
260impl WriteHandleOrUpper {
261 fn upper(&self) -> Antichain<Timestamp> {
262 match self {
263 Self::Handle(handle) => handle.upper().clone(),
264 Self::Upper(upper) => upper.clone(),
265 }
266 }
267
268 fn expect_handle(self, context: &str) -> WriteHandle<SourceData, (), Timestamp, StorageDiff> {
271 match self {
272 Self::Handle(handle) => handle,
273 Self::Upper(_) => panic!("write handle required: {context}"),
274 }
275 }
276}
277
278fn warm_persist_state_in_background(
279 client: PersistClient,
280 shard_ids: impl Iterator<Item = ShardId> + Send + 'static,
281) -> mz_ore::task::JoinHandle<Box<dyn Debug + Send>> {
282 const MAX_CONCURRENT_WARMS: usize = 16;
284 let logic = async move {
285 let fetchers: Vec<_> = tokio_stream::iter(shard_ids)
286 .map(|shard_id| {
287 let client = client.clone();
288 async move {
289 client
290 .create_batch_fetcher::<SourceData, (), mz_repr::Timestamp, StorageDiff>(
291 shard_id,
292 Arc::new(RelationDesc::empty()),
293 Arc::new(UnitSchema),
294 true,
295 Diagnostics::from_purpose("warm persist load state"),
296 )
297 .await
298 }
299 })
300 .buffer_unordered(MAX_CONCURRENT_WARMS)
301 .collect()
302 .await;
303 let fetchers: Box<dyn Debug + Send> = Box::new(fetchers);
304 fetchers
305 };
306 mz_ore::task::spawn(|| "warm_persist_load_state", logic)
307}
308
309#[async_trait(?Send)]
310impl StorageController for Controller {
311 fn initialization_complete(&mut self) {
312 self.reconcile_dangling_statistics();
313 self.initialized = true;
314
315 for instance in self.instances.values_mut() {
316 instance.send(StorageCommand::InitializationComplete);
317 }
318 }
319
320 fn update_parameters(&mut self, config_params: StorageParameters) {
321 self.storage_collections
322 .update_parameters(config_params.clone());
323
324 self.persist.cfg().apply_from(&config_params.dyncfg_updates);
327
328 for instance in self.instances.values_mut() {
329 let params = Box::new(config_params.clone());
330 instance.send(StorageCommand::UpdateConfiguration(params));
331 }
332 self.config.update(config_params);
333 self.statistics_interval_sender
334 .send_replace(self.config.parameters.statistics_interval);
335 self.collection_manager.update_user_batch_duration(
336 self.config
337 .parameters
338 .user_storage_managed_collections_batch_duration,
339 );
340 }
341
342 fn update_replica_dyncfg_overrides(
343 &mut self,
344 mut overrides: BTreeMap<StorageInstanceId, BTreeMap<ReplicaId, ConfigUpdates>>,
345 ) {
346 self.replica_dyncfg_overrides = overrides
347 .values()
348 .flat_map(|replicas| replicas.iter())
349 .map(|(replica_id, updates)| (*replica_id, updates.clone()))
350 .collect();
351 for (id, instance) in self.instances.iter_mut() {
352 let instance_overrides = overrides.remove(id).unwrap_or_default();
353 instance.update_replica_dyncfg_overrides(instance_overrides);
354 }
355 }
356
357 fn config(&self) -> &StorageConfiguration {
359 &self.config
360 }
361
362 fn collection_metadata(&self, id: GlobalId) -> Result<CollectionMetadata, CollectionMissing> {
363 self.storage_collections.collection_metadata(id)
364 }
365
366 fn collection_hydrated(&self, collection_id: GlobalId) -> Result<bool, StorageError> {
367 let collection = self.collection(collection_id)?;
368
369 let instance_id = match &collection.data_source {
370 DataSource::Ingestion(ingestion_description) => ingestion_description.instance_id,
371 DataSource::IngestionExport { ingestion_id, .. } => {
372 let ingestion_state = self.collections.get(ingestion_id).expect("known to exist");
373
374 let instance_id = match &ingestion_state.data_source {
375 DataSource::Ingestion(ingestion_desc) => ingestion_desc.instance_id,
376 _ => unreachable!("SourceExport must only refer to primary source"),
377 };
378
379 instance_id
380 }
381 _ => return Ok(true),
382 };
383
384 let instance = self.instances.get(&instance_id).ok_or_else(|| {
385 StorageError::IngestionInstanceMissing {
386 storage_instance_id: instance_id,
387 ingestion_id: collection_id,
388 }
389 })?;
390
391 if instance.replica_ids().next().is_none() {
392 return Ok(true);
395 }
396
397 match &collection.extra_state {
398 CollectionStateExtra::Ingestion(ingestion_state) => {
399 Ok(ingestion_state.hydrated_on.len() >= 1)
401 }
402 CollectionStateExtra::Export(_) => {
403 Ok(true)
408 }
409 CollectionStateExtra::None => {
410 Ok(true)
414 }
415 }
416 }
417
418 #[mz_ore::instrument(level = "debug")]
419 fn collections_hydrated_on_replicas(
420 &self,
421 target_replica_ids: Option<Vec<ReplicaId>>,
422 target_cluster_id: &StorageInstanceId,
423 exclude_collections: &BTreeSet<GlobalId>,
424 ) -> Result<bool, StorageError> {
425 if target_replica_ids.as_ref().is_some_and(|v| v.is_empty()) {
428 return Ok(true);
429 }
430
431 let target_replicas: Option<BTreeSet<ReplicaId>> =
434 target_replica_ids.map(|ids| ids.into_iter().collect());
435
436 let instance = self.instances.get(target_cluster_id);
437
438 let mut all_hydrated = true;
439 for (collection_id, collection_state) in self.collections.iter() {
440 if collection_id.is_transient() || exclude_collections.contains(collection_id) {
441 continue;
442 }
443 let hydrated = match &collection_state.extra_state {
444 CollectionStateExtra::Ingestion(state) => {
445 if &state.instance_id != target_cluster_id {
446 continue;
447 }
448 match &target_replicas {
449 Some(target_replicas) => {
450 let scheduled_on = instance
458 .map(|i| i.get_active_replicas_for_object(collection_id))
459 .unwrap_or_default();
460 if scheduled_on.is_disjoint(target_replicas) {
461 true
462 } else {
463 !state.hydrated_on.is_disjoint(target_replicas)
464 }
465 }
466 None => {
467 state.hydrated_on.len() >= 1
470 }
471 }
472 }
473 CollectionStateExtra::Export(_) => {
474 true
479 }
480 CollectionStateExtra::None => {
481 true
485 }
486 };
487 if !hydrated {
488 tracing::info!(%collection_id, "collection is not hydrated on any replica");
489 all_hydrated = false;
490 }
493 }
494 Ok(all_hydrated)
495 }
496
497 fn collection_frontiers(
498 &self,
499 id: GlobalId,
500 ) -> Result<(Antichain<Timestamp>, Antichain<Timestamp>), CollectionMissing> {
501 let frontiers = self.storage_collections.collection_frontiers(id)?;
502 Ok((frontiers.implied_capability, frontiers.write_frontier))
503 }
504
505 fn collections_frontiers(
506 &self,
507 mut ids: Vec<GlobalId>,
508 ) -> Result<Vec<(GlobalId, Antichain<Timestamp>, Antichain<Timestamp>)>, CollectionMissing>
509 {
510 let mut result = vec![];
511 ids.retain(|&id| match self.export(id) {
516 Ok(export) => {
517 result.push((
518 id,
519 export.input_hold().since().clone(),
520 export.write_frontier.clone(),
521 ));
522 false
523 }
524 Err(_) => true,
525 });
526 result.extend(
527 self.storage_collections
528 .collections_frontiers(ids)?
529 .into_iter()
530 .map(|frontiers| {
531 (
532 frontiers.id,
533 frontiers.implied_capability,
534 frontiers.write_frontier,
535 )
536 }),
537 );
538
539 Ok(result)
540 }
541
542 fn active_collection_metadatas(&self) -> Vec<(GlobalId, CollectionMetadata)> {
543 self.storage_collections.active_collection_metadatas()
544 }
545
546 fn active_ingestion_exports(
547 &self,
548 instance_id: StorageInstanceId,
549 ) -> Box<dyn Iterator<Item = &GlobalId> + '_> {
550 let active_storage_collections: BTreeMap<_, _> = self
551 .storage_collections
552 .active_collection_frontiers()
553 .into_iter()
554 .map(|c| (c.id, c))
555 .collect();
556
557 let active_exports = self.instances[&instance_id]
558 .active_ingestion_exports()
559 .filter(move |id| {
560 let frontiers = active_storage_collections.get(id);
561 match frontiers {
562 Some(frontiers) => !frontiers.write_frontier.is_empty(),
563 None => {
564 false
566 }
567 }
568 });
569
570 Box::new(active_exports)
571 }
572
573 fn check_exists(&self, id: GlobalId) -> Result<(), StorageError> {
574 self.storage_collections.check_exists(id)
575 }
576
577 fn create_instance(&mut self, id: StorageInstanceId, workload_class: Option<String>) {
578 let metrics = self.metrics.for_instance(id);
579 let mut instance = Instance::new(
580 workload_class,
581 metrics,
582 self.now.clone(),
583 self.instance_response_tx.clone(),
584 );
585 if self.initialized {
586 instance.send(StorageCommand::InitializationComplete);
587 }
588 if !self.read_only {
589 instance.send(StorageCommand::AllowWrites);
590 }
591
592 let params = Box::new(self.config.parameters.clone());
593 instance.send(StorageCommand::UpdateConfiguration(params));
594
595 let old_instance = self.instances.insert(id, instance);
596 assert_none!(old_instance, "storage instance {id} already exists");
597 }
598
599 fn drop_instance(&mut self, id: StorageInstanceId) {
600 let instance = self.instances.remove(&id);
601 assert!(instance.is_some(), "storage instance {id} does not exist");
602 }
603
604 fn update_instance_workload_class(
605 &mut self,
606 id: StorageInstanceId,
607 workload_class: Option<String>,
608 ) {
609 let instance = self
610 .instances
611 .get_mut(&id)
612 .unwrap_or_else(|| panic!("instance {id} does not exist"));
613
614 instance.workload_class = workload_class;
615 }
616
617 fn connect_replica(
618 &mut self,
619 instance_id: StorageInstanceId,
620 replica_id: ReplicaId,
621 location: ClusterReplicaLocation,
622 ) {
623 let instance = self
624 .instances
625 .get_mut(&instance_id)
626 .unwrap_or_else(|| panic!("instance {instance_id} does not exist"));
627
628 let config = ReplicaConfig {
629 build_info: self.build_info,
630 location,
631 grpc_client: self.config.parameters.grpc_client.clone(),
632 };
633 let dyncfg_override = self
634 .replica_dyncfg_overrides
635 .get(&replica_id)
636 .cloned()
637 .unwrap_or_default();
638 instance.add_replica(replica_id, config, dyncfg_override);
639 }
640
641 fn drop_replica(&mut self, instance_id: StorageInstanceId, replica_id: ReplicaId) {
642 self.replica_dyncfg_overrides.remove(&replica_id);
646
647 let instance = self
648 .instances
649 .get_mut(&instance_id)
650 .unwrap_or_else(|| panic!("instance {instance_id} does not exist"));
651
652 let status_now = mz_ore::now::to_datetime((self.now)());
653 let mut source_status_updates = vec![];
654 let mut sink_status_updates = vec![];
655
656 let make_update = |id, object_type| StatusUpdate {
659 id,
660 status: Status::Paused,
661 timestamp: status_now,
662 error: None,
663 hints: BTreeSet::from([format!(
664 "The replica running this {object_type} has been dropped"
665 )]),
666 namespaced_errors: Default::default(),
667 replica_id: Some(replica_id),
668 };
669
670 for ingestion_id in instance.active_ingestions() {
671 if let Some(active_replicas) = self.dropped_objects.get_mut(ingestion_id) {
672 active_replicas.remove(&replica_id);
673 if active_replicas.is_empty() {
674 self.dropped_objects.remove(ingestion_id);
675 }
676 }
677
678 let ingestion = self
679 .collections
680 .get_mut(ingestion_id)
681 .expect("instance contains unknown ingestion");
682
683 let ingestion_description = match &ingestion.data_source {
684 DataSource::Ingestion(ingestion_description) => ingestion_description.clone(),
685 _ => panic!(
686 "unexpected data source for ingestion: {:?}",
687 ingestion.data_source
688 ),
689 };
690
691 let old_style_ingestion = *ingestion_id != ingestion_description.remap_collection_id;
692 let subsource_ids = ingestion_description.collection_ids().filter(|id| {
693 let should_discard =
698 old_style_ingestion && id == &ingestion_description.remap_collection_id;
699 !should_discard
700 });
701 for id in subsource_ids {
702 source_status_updates.push(make_update(id, "source"));
703 }
704 }
705
706 for id in instance.active_exports() {
707 if let Some(active_replicas) = self.dropped_objects.get_mut(id) {
708 active_replicas.remove(&replica_id);
709 if active_replicas.is_empty() {
710 self.dropped_objects.remove(id);
711 }
712 }
713
714 sink_status_updates.push(make_update(*id, "sink"));
715 }
716
717 instance.drop_replica(replica_id);
718
719 if !self.read_only {
720 if !source_status_updates.is_empty() {
721 self.append_status_introspection_updates(
722 IntrospectionType::SourceStatusHistory,
723 source_status_updates,
724 );
725 }
726 if !sink_status_updates.is_empty() {
727 self.append_status_introspection_updates(
728 IntrospectionType::SinkStatusHistory,
729 sink_status_updates,
730 );
731 }
732 }
733 }
734
735 async fn evolve_nullability_for_bootstrap(
736 &mut self,
737 storage_metadata: &StorageMetadata,
738 collections: Vec<(GlobalId, RelationDesc)>,
739 ) -> Result<(), StorageError> {
740 use futures::TryStreamExt;
741
742 let persist_client = self
743 .persist
744 .open(self.persist_location.clone())
745 .await
746 .unwrap();
747 let persist_client = &persist_client;
748
749 let evolve = |shard_id, global_id: GlobalId, relation_desc: RelationDesc| async move {
750 let diagnostics = Diagnostics {
751 shard_name: global_id.to_string(),
752 handle_purpose: "evolve nullability for bootstrap".to_string(),
753 };
754 let latest_schema = persist_client
755 .latest_schema::<SourceData, (), Timestamp, StorageDiff>(shard_id, diagnostics)
756 .await
757 .expect("invalid persist usage");
758 let Some((schema_id, current_schema, _)) = latest_schema else {
759 tracing::debug!(?global_id, "no schema registered");
760 return Ok(());
761 };
762 tracing::debug!(?global_id, ?current_schema, new_schema = ?relation_desc, "migrating schema");
763
764 let diagnostics = Diagnostics {
765 shard_name: global_id.to_string(),
766 handle_purpose: "evolve nullability for bootstrap".to_string(),
767 };
768 let evolve_result = persist_client
769 .compare_and_evolve_schema::<SourceData, (), Timestamp, StorageDiff>(
770 shard_id,
771 schema_id,
772 &relation_desc,
773 &UnitSchema,
774 diagnostics,
775 )
776 .await
777 .expect("invalid persist usage");
778 match evolve_result {
779 CaESchema::Ok(_) => (),
780 CaESchema::ExpectedMismatch {
781 schema_id,
782 key,
783 val: _,
784 } => {
785 return Err(StorageError::PersistSchemaEvolveRace {
786 global_id,
787 shard_id,
788 schema_id,
789 relation_desc: key,
790 });
791 }
792 CaESchema::Incompatible => {
793 return Err(StorageError::PersistInvalidSchemaEvolve {
794 global_id,
795 shard_id,
796 });
797 }
798 };
799 Ok(())
800 };
801
802 let mut by_shard: BTreeMap<_, Vec<_>> = BTreeMap::new();
805 for (global_id, relation_desc) in collections {
806 let shard_id = storage_metadata.get_collection_shard(global_id)?;
807 by_shard
808 .entry(shard_id)
809 .or_default()
810 .push((global_id, relation_desc));
811 }
812
813 futures::stream::iter(by_shard)
817 .map(|(shard_id, collections)| async move {
818 for (global_id, relation_desc) in collections {
819 evolve(shard_id, global_id, relation_desc).await?;
820 }
821 Ok(())
822 })
823 .buffer_unordered(50)
824 .try_collect()
825 .await
826 }
827
828 #[instrument(name = "storage::create_collections")]
847 async fn create_collections_for_bootstrap(
848 &mut self,
849 storage_metadata: &StorageMetadata,
850 register_ts: Option<Timestamp>,
851 mut collections: Vec<(GlobalId, CollectionDescription)>,
852 migrated_storage_collections: &BTreeSet<GlobalId>,
853 ) -> Result<(), StorageError> {
854 self.migrated_storage_collections
855 .extend(migrated_storage_collections.iter().cloned());
856
857 self.storage_collections
858 .create_collections_for_bootstrap(
859 storage_metadata,
860 register_ts,
861 collections.clone(),
862 migrated_storage_collections,
863 )
864 .await?;
865
866 drop(self.persist_warm_task.take());
869
870 collections.sort_by_key(|(id, _)| *id);
875 collections.dedup();
876 for pos in 1..collections.len() {
877 if collections[pos - 1].0 == collections[pos].0 {
878 return Err(StorageError::CollectionIdReused(collections[pos].0));
879 }
880 }
881
882 let enriched_with_metadata = collections
884 .into_iter()
885 .map(|(id, description)| {
886 let data_shard = storage_metadata.get_collection_shard(id)?;
887
888 let txns_shard = description
891 .data_source
892 .in_txns()
893 .then(|| *self.txns_read.txns_id());
894
895 let metadata = CollectionMetadata {
896 persist_location: self.persist_location.clone(),
897 data_shard,
898 relation_desc: description.desc.clone(),
899 txns_shard,
900 };
901
902 Ok((id, description, metadata))
903 })
904 .collect_vec();
905
906 let persist_client = self
908 .persist
909 .open(self.persist_location.clone())
910 .await
911 .unwrap();
912 let persist_client = &persist_client;
913
914 use futures::stream::{StreamExt, TryStreamExt};
917 let this = &*self;
918 let mut to_register: Vec<_> = futures::stream::iter(enriched_with_metadata)
919 .map(|data: Result<_, StorageError>| {
920 async move {
921 let (id, description, metadata) = data?;
922
923 debug!("mapping GlobalId={} to shard ({})", id, metadata.data_shard);
926
927 let write = if matches!(description.data_source, DataSource::Table) {
932 let diagnostics = Diagnostics {
933 shard_name: id.to_string(),
934 handle_purpose: format!("controller data for {}", id),
935 };
936 let upper = persist_client
937 .recent_upper::<SourceData, (), Timestamp, StorageDiff>(
938 metadata.data_shard,
939 diagnostics,
940 )
941 .await
942 .expect("invalid persist usage");
943 WriteHandleOrUpper::Upper(upper)
944 } else {
945 let write = this
946 .open_data_handles(
947 &id,
948 metadata.data_shard,
949 metadata.relation_desc.clone(),
950 persist_client,
951 )
952 .await;
953 WriteHandleOrUpper::Handle(write)
954 };
955
956 Ok::<_, StorageError>((id, description, write, metadata))
957 }
958 })
959 .buffer_unordered(50)
961 .try_collect()
974 .await?;
975
976 let mut to_execute = BTreeSet::new();
979 let mut new_collections = BTreeSet::new();
984
985 to_register.sort_by_key(|(id, ..)| *id);
987
988 let (tables_to_register, collections_to_register): (Vec<_>, Vec<_>) = to_register
994 .into_iter()
995 .partition(|(_id, desc, ..)| desc.data_source == DataSource::Table);
996 let to_register = tables_to_register
997 .into_iter()
998 .rev()
999 .chain(collections_to_register.into_iter());
1000
1001 let mut new_webhook_statistic_entries = BTreeSet::new();
1005
1006 for (id, description, write, metadata) in to_register {
1007 let is_in_txns = |id, metadata: &CollectionMetadata| {
1008 metadata.txns_shard.is_some()
1009 && !(self.read_only && migrated_storage_collections.contains(&id))
1010 };
1011
1012 to_execute.insert(id);
1013 new_collections.insert(id);
1014
1015 let write_frontier = write.upper();
1016
1017 let storage_dependencies = self.determine_collection_dependencies(id, &description)?;
1019
1020 let dependency_read_holds = self
1021 .storage_collections
1022 .acquire_read_holds(storage_dependencies)
1023 .expect("can acquire read holds");
1024
1025 let mut dependency_since = Antichain::from_elem(Timestamp::MIN);
1026 for read_hold in dependency_read_holds.iter() {
1027 dependency_since.join_assign(read_hold.since());
1028 }
1029
1030 let data_source = description.data_source;
1031
1032 if !dependency_read_holds.is_empty()
1041 && !is_in_txns(id, &metadata)
1042 && !matches!(&data_source, DataSource::Sink { .. })
1043 {
1044 if dependency_since.is_empty() && !write_frontier.is_empty() {
1057 let reason = format!(
1058 "dependency since frontier is empty while dependent upper \
1059 is not empty (dependent id={id}, write_frontier={:?}, dependency_read_holds={:?}), \
1060 this indicates concurrent deletion of a collection",
1061 write_frontier, dependency_read_holds,
1062 );
1063 if self.read_only {
1069 restart_in_place!("{}", reason);
1070 } else {
1071 halt!("{}", reason);
1072 }
1073 }
1074
1075 if description.primary.is_none()
1096 && write_frontier.elements() != &[Timestamp::MIN]
1097 && !write_frontier.is_empty()
1098 && !PartialOrder::less_than(&dependency_since, &write_frontier)
1099 && !(matches!(data_source, DataSource::IngestionExport { .. })
1100 && shard_has_no_updates(persist_client, id, &metadata).await)
1101 {
1102 mz_ore::soft_panic_or_log!(
1103 "dependency since has advanced past dependent ({id}) upper \n
1104 dependent ({id}): upper {:?} \n
1105 dependency since {:?} \n
1106 dependency read holds: {:?}",
1107 write_frontier,
1108 dependency_since,
1109 dependency_read_holds,
1110 );
1111 }
1112 }
1113
1114 let mut extra_state = CollectionStateExtra::None;
1116 let mut maybe_instance_id = None;
1117 match &data_source {
1118 DataSource::Introspection(typ) => {
1119 debug!(
1120 ?data_source, meta = ?metadata,
1121 "registering {id} with persist monotonic worker",
1122 );
1123 self.register_introspection_collection(
1129 id,
1130 *typ,
1131 write.expect_handle("introspection collections are not tables"),
1132 persist_client.clone(),
1133 )?;
1134 }
1135 DataSource::Webhook => {
1136 debug!(
1137 ?data_source, meta = ?metadata,
1138 "registering {id} with persist monotonic worker",
1139 );
1140 new_webhook_statistic_entries.insert(id);
1143 self.collection_manager.register_append_only_collection(
1149 id,
1150 write.expect_handle("webhook collections are not tables"),
1151 false,
1152 None,
1153 );
1154 }
1155 DataSource::IngestionExport {
1156 ingestion_id,
1157 details,
1158 data_config,
1159 } => {
1160 debug!(
1161 ?data_source, meta = ?metadata,
1162 "not registering {id} with a controller persist worker",
1163 );
1164 let ingestion_state = self
1166 .collections
1167 .get_mut(ingestion_id)
1168 .expect("known to exist");
1169
1170 let instance_id = match &mut ingestion_state.data_source {
1171 DataSource::Ingestion(ingestion_desc) => {
1172 ingestion_desc.source_exports.insert(
1173 id,
1174 SourceExport {
1175 storage_metadata: (),
1176 details: details.clone(),
1177 data_config: data_config.clone(),
1178 },
1179 );
1180
1181 ingestion_desc.instance_id
1186 }
1187 _ => unreachable!(
1188 "SourceExport must only refer to primary sources that already exist"
1189 ),
1190 };
1191
1192 to_execute.remove(&id);
1194 to_execute.insert(*ingestion_id);
1195
1196 let ingestion_state = IngestionState {
1197 read_capabilities: MutableAntichain::from(dependency_since.clone()),
1198 dependency_read_holds,
1199 derived_since: dependency_since,
1200 write_frontier: Antichain::from_elem(Timestamp::MIN),
1201 hold_policy: ReadPolicy::step_back(),
1202 instance_id,
1203 hydrated_on: BTreeSet::new(),
1204 };
1205
1206 extra_state = CollectionStateExtra::Ingestion(ingestion_state);
1207 maybe_instance_id = Some(instance_id);
1208 }
1209 DataSource::Table => {
1210 debug!(
1211 ?data_source, meta = ?metadata,
1212 "not registering {id} with the txns shard here; the caller does that \
1213 through the group committer",
1214 );
1215 }
1216 DataSource::Progress | DataSource::Other => {
1217 debug!(
1218 ?data_source, meta = ?metadata,
1219 "not registering {id} with a controller persist worker",
1220 );
1221 }
1222 DataSource::Ingestion(ingestion_desc) => {
1223 debug!(
1224 ?data_source, meta = ?metadata,
1225 "not registering {id} with a controller persist worker",
1226 );
1227
1228 let mut dependency_since = Antichain::from_elem(Timestamp::MIN);
1229 for read_hold in dependency_read_holds.iter() {
1230 dependency_since.join_assign(read_hold.since());
1231 }
1232
1233 let ingestion_state = IngestionState {
1234 read_capabilities: MutableAntichain::from(dependency_since.clone()),
1235 dependency_read_holds,
1236 derived_since: dependency_since,
1237 write_frontier: Antichain::from_elem(Timestamp::MIN),
1238 hold_policy: ReadPolicy::step_back(),
1239 instance_id: ingestion_desc.instance_id,
1240 hydrated_on: BTreeSet::new(),
1241 };
1242
1243 extra_state = CollectionStateExtra::Ingestion(ingestion_state);
1244 maybe_instance_id = Some(ingestion_desc.instance_id);
1245 }
1246 DataSource::Sink { desc } => {
1247 let mut dependency_since = Antichain::from_elem(Timestamp::MIN);
1248 for read_hold in dependency_read_holds.iter() {
1249 dependency_since.join_assign(read_hold.since());
1250 }
1251
1252 let [self_hold, read_hold] =
1253 dependency_read_holds.try_into().expect("two holds");
1254
1255 let state = ExportState::new(
1256 desc.instance_id,
1257 read_hold,
1258 self_hold,
1259 write_frontier.clone(),
1260 ReadPolicy::step_back(),
1261 );
1262 maybe_instance_id = Some(state.cluster_id);
1263 extra_state = CollectionStateExtra::Export(state);
1264 }
1265 }
1266
1267 let wallclock_lag_metrics = self.metrics.wallclock_lag_metrics(id, maybe_instance_id);
1268 let collection_state =
1269 CollectionState::new(data_source, metadata, extra_state, wallclock_lag_metrics);
1270
1271 self.collections.insert(id, collection_state);
1272 }
1273
1274 {
1275 let mut source_statistics = self.source_statistics.lock().expect("poisoned");
1276
1277 for id in new_webhook_statistic_entries {
1280 source_statistics.webhook_statistics.entry(id).or_default();
1281 }
1282
1283 }
1287
1288 self.append_shard_mappings(new_collections.into_iter(), Diff::ONE);
1289
1290 for id in to_execute {
1292 match &self.collection(id)?.data_source {
1293 DataSource::Ingestion(ingestion) => {
1294 if !self.read_only
1295 || (ENABLE_0DT_DEPLOYMENT_SOURCES.get(self.config.config_set())
1296 && ingestion.desc.connection.supports_read_only())
1297 {
1298 self.run_ingestion(id)?;
1299 }
1300 }
1301 DataSource::IngestionExport { .. } => unreachable!(
1302 "ingestion exports do not execute directly, but instead schedule their source to be re-executed"
1303 ),
1304 DataSource::Introspection(_)
1305 | DataSource::Webhook
1306 | DataSource::Table
1307 | DataSource::Progress
1308 | DataSource::Other => {}
1309 DataSource::Sink { .. } => {
1310 if !self.read_only {
1311 self.run_export(id)?;
1312 }
1313 }
1314 };
1315 }
1316
1317 Ok(())
1318 }
1319
1320 fn check_alter_ingestion_source_desc(
1321 &mut self,
1322 ingestion_id: GlobalId,
1323 source_desc: &SourceDesc,
1324 ) -> Result<(), StorageError> {
1325 let source_collection = self.collection(ingestion_id)?;
1326 let data_source = &source_collection.data_source;
1327 match &data_source {
1328 DataSource::Ingestion(cur_ingestion) => {
1329 cur_ingestion
1330 .desc
1331 .alter_compatible(ingestion_id, source_desc)?;
1332 }
1333 o => {
1334 tracing::info!(
1335 "{ingestion_id} inalterable because its data source is {:?} and not an ingestion",
1336 o
1337 );
1338 Err(AlterError { id: ingestion_id })?
1339 }
1340 }
1341
1342 Ok(())
1343 }
1344
1345 async fn alter_ingestion_source_desc(
1346 &mut self,
1347 ingestion_ids: BTreeMap<GlobalId, SourceDesc>,
1348 ) -> Result<(), StorageError> {
1349 let mut ingestions_to_run = BTreeSet::new();
1350
1351 for (id, new_desc) in ingestion_ids {
1352 let collection = self
1353 .collections
1354 .get_mut(&id)
1355 .ok_or_else(|| StorageError::IdentifierMissing(id))?;
1356
1357 match &mut collection.data_source {
1358 DataSource::Ingestion(ingestion) => {
1359 if ingestion.desc != new_desc {
1360 tracing::info!(
1361 from = ?ingestion.desc,
1362 to = ?new_desc,
1363 "alter_ingestion_source_desc, updating"
1364 );
1365 ingestion.desc = new_desc;
1366 ingestions_to_run.insert(id);
1367 }
1368 }
1369 o => {
1370 tracing::warn!("alter_ingestion_source_desc called on {:?}", o);
1371 Err(StorageError::IdentifierInvalid(id))?;
1372 }
1373 }
1374 }
1375
1376 for id in ingestions_to_run {
1377 self.run_ingestion(id)?;
1378 }
1379 Ok(())
1380 }
1381
1382 async fn alter_ingestion_connections(
1383 &mut self,
1384 source_connections: BTreeMap<GlobalId, GenericSourceConnection<InlinedConnection>>,
1385 ) -> Result<(), StorageError> {
1386 let mut ingestions_to_run = BTreeSet::new();
1387
1388 for (id, conn) in source_connections {
1389 let collection = self
1390 .collections
1391 .get_mut(&id)
1392 .ok_or_else(|| StorageError::IdentifierMissing(id))?;
1393
1394 match &mut collection.data_source {
1395 DataSource::Ingestion(ingestion) => {
1396 if ingestion.desc.connection != conn {
1399 tracing::info!(from = ?ingestion.desc.connection, to = ?conn, "alter_ingestion_connections, updating");
1400 ingestion.desc.connection = conn;
1401 ingestions_to_run.insert(id);
1402 } else {
1403 tracing::warn!(
1404 "update_source_connection called on {id} but the \
1405 connection was the same"
1406 );
1407 }
1408 }
1409 o => {
1410 tracing::warn!("update_source_connection called on {:?}", o);
1411 Err(StorageError::IdentifierInvalid(id))?;
1412 }
1413 }
1414 }
1415
1416 for id in ingestions_to_run {
1417 self.run_ingestion(id)?;
1418 }
1419 Ok(())
1420 }
1421
1422 async fn alter_ingestion_export_data_configs(
1423 &mut self,
1424 source_exports: BTreeMap<GlobalId, SourceExportDataConfig>,
1425 ) -> Result<(), StorageError> {
1426 let mut ingestions_to_run = BTreeSet::new();
1427
1428 for (source_export_id, new_data_config) in source_exports {
1429 let source_export_collection = self
1432 .collections
1433 .get_mut(&source_export_id)
1434 .ok_or_else(|| StorageError::IdentifierMissing(source_export_id))?;
1435 let ingestion_id = match &mut source_export_collection.data_source {
1436 DataSource::IngestionExport {
1437 ingestion_id,
1438 details: _,
1439 data_config,
1440 } => {
1441 *data_config = new_data_config.clone();
1442 *ingestion_id
1443 }
1444 o => {
1445 tracing::warn!("alter_ingestion_export_data_configs called on {:?}", o);
1446 Err(StorageError::IdentifierInvalid(source_export_id))?
1447 }
1448 };
1449 let ingestion_collection = self
1452 .collections
1453 .get_mut(&ingestion_id)
1454 .ok_or_else(|| StorageError::IdentifierMissing(ingestion_id))?;
1455
1456 match &mut ingestion_collection.data_source {
1457 DataSource::Ingestion(ingestion_desc) => {
1458 let source_export = ingestion_desc
1459 .source_exports
1460 .get_mut(&source_export_id)
1461 .ok_or_else(|| StorageError::IdentifierMissing(source_export_id))?;
1462
1463 if source_export.data_config != new_data_config {
1466 tracing::info!(?source_export_id, from = ?source_export.data_config, to = ?new_data_config, "alter_ingestion_export_data_configs, updating");
1467 source_export.data_config = new_data_config;
1468
1469 ingestions_to_run.insert(ingestion_id);
1470 } else {
1471 tracing::warn!(
1472 "alter_ingestion_export_data_configs called on \
1473 export {source_export_id} of {ingestion_id} but \
1474 the data config was the same"
1475 );
1476 }
1477 }
1478 o => {
1479 tracing::warn!("alter_ingestion_export_data_configs called on {:?}", o);
1480 Err(StorageError::IdentifierInvalid(ingestion_id))?
1481 }
1482 }
1483 }
1484
1485 for id in ingestions_to_run {
1486 self.run_ingestion(id)?;
1487 }
1488 Ok(())
1489 }
1490
1491 async fn alter_table_desc(
1492 &mut self,
1493 existing_collection: GlobalId,
1494 new_collection: GlobalId,
1495 new_desc: RelationDesc,
1496 expected_version: RelationVersion,
1497 ) -> Result<(), StorageError> {
1498 let data_shard = {
1499 let Controller {
1500 collections,
1501 storage_collections,
1502 ..
1503 } = self;
1504
1505 let existing = collections
1506 .get(&existing_collection)
1507 .ok_or(StorageError::IdentifierMissing(existing_collection))?;
1508 if existing.data_source != DataSource::Table {
1509 return Err(StorageError::IdentifierInvalid(existing_collection));
1510 }
1511
1512 storage_collections
1514 .alter_table_desc(
1515 existing_collection,
1516 new_collection,
1517 new_desc.clone(),
1518 expected_version,
1519 )
1520 .await?;
1521
1522 existing.collection_metadata.data_shard.clone()
1523 };
1524
1525 let collection_meta = CollectionMetadata {
1526 persist_location: self.persist_location.clone(),
1527 data_shard,
1528 relation_desc: new_desc.clone(),
1529 txns_shard: Some(self.txns_read.txns_id().clone()),
1531 };
1532 let wallclock_lag_metrics = self.metrics.wallclock_lag_metrics(new_collection, None);
1534 let collection_state = CollectionState::new(
1535 DataSource::Table,
1536 collection_meta,
1537 CollectionStateExtra::None,
1538 wallclock_lag_metrics,
1539 );
1540
1541 self.collections.insert(new_collection, collection_state);
1544
1545 self.append_shard_mappings([new_collection].into_iter(), Diff::ONE);
1546
1547 Ok(())
1548 }
1549
1550 async fn register_table_collections(
1551 &mut self,
1552 register_ts: Timestamp,
1553 ids: Vec<GlobalId>,
1554 ) -> Result<(), StorageError> {
1555 let mut tables = self.table_registrations(ids)?;
1556
1557 if self.read_only {
1559 tables.retain(|table| self.migrated_storage_collections.contains(&table.id));
1560 }
1561 if tables.is_empty() {
1562 return Ok(());
1563 }
1564
1565 match self
1566 .persist_table_worker
1567 .register(register_ts, tables)
1568 .await
1569 {
1570 Ok(res) => res,
1571 Err(_recv) => Err(StorageError::ShuttingDown("persist_table_worker")),
1572 }
1573 }
1574
1575 fn table_registrations(
1576 &self,
1577 ids: Vec<GlobalId>,
1578 ) -> Result<Vec<TableRegistration>, StorageError> {
1579 let mut tables = Vec::with_capacity(ids.len());
1581 for id in ids {
1582 let collection = self.collection(id)?;
1583 if matches!(collection.data_source, DataSource::Table) {
1584 let metadata = &collection.collection_metadata;
1585 tables.push(TableRegistration {
1586 id,
1587 data_shard: metadata.data_shard,
1588 relation_desc: metadata.relation_desc.clone(),
1589 });
1590 }
1591 }
1592 Ok(tables)
1593 }
1594
1595 fn txns_table_ids(&self, ids: Vec<GlobalId>) -> Result<Vec<GlobalId>, StorageError> {
1596 let mut tables = Vec::with_capacity(ids.len());
1597 for id in ids {
1598 let collection = self.collection(id)?;
1599 if matches!(collection.data_source, DataSource::Table) {
1600 tables.push(id);
1601 }
1602 }
1603 Ok(tables)
1604 }
1605
1606 fn export(&self, id: GlobalId) -> Result<&ExportState, StorageError> {
1607 self.collections
1608 .get(&id)
1609 .and_then(|c| match &c.extra_state {
1610 CollectionStateExtra::Export(state) => Some(state),
1611 _ => None,
1612 })
1613 .ok_or(StorageError::IdentifierMissing(id))
1614 }
1615
1616 fn export_mut(&mut self, id: GlobalId) -> Result<&mut ExportState, StorageError> {
1617 self.collections
1618 .get_mut(&id)
1619 .and_then(|c| match &mut c.extra_state {
1620 CollectionStateExtra::Export(state) => Some(state),
1621 _ => None,
1622 })
1623 .ok_or(StorageError::IdentifierMissing(id))
1624 }
1625
1626 async fn create_oneshot_ingestion(
1628 &mut self,
1629 ingestion_id: uuid::Uuid,
1630 collection_id: GlobalId,
1631 instance_id: StorageInstanceId,
1632 request: OneshotIngestionRequest,
1633 result_tx: OneshotResultCallback<ProtoBatch>,
1634 ) -> Result<(), StorageError> {
1635 let collection_meta = self
1636 .collections
1637 .get(&collection_id)
1638 .ok_or_else(|| StorageError::IdentifierMissing(collection_id))?
1639 .collection_metadata
1640 .clone();
1641 let instance = self.instances.get_mut(&instance_id).ok_or_else(|| {
1642 StorageError::Generic(anyhow::anyhow!("missing cluster {instance_id}"))
1644 })?;
1645 let oneshot_cmd = RunOneshotIngestion {
1646 ingestion_id,
1647 collection_id,
1648 collection_meta,
1649 request,
1650 };
1651
1652 if !self.read_only {
1653 instance.send(StorageCommand::RunOneshotIngestion(Box::new(oneshot_cmd)));
1654 let pending = PendingOneshotIngestion {
1655 result_tx,
1656 cluster_id: instance_id,
1657 };
1658 let novel = self
1659 .pending_oneshot_ingestions
1660 .insert(ingestion_id, pending);
1661 assert_none!(novel);
1662 Ok(())
1663 } else {
1664 Err(StorageError::ReadOnly)
1665 }
1666 }
1667
1668 fn cancel_oneshot_ingestion(&mut self, ingestion_id: uuid::Uuid) -> Result<(), StorageError> {
1669 if self.read_only {
1670 return Err(StorageError::ReadOnly);
1671 }
1672
1673 let pending = self
1674 .pending_oneshot_ingestions
1675 .remove(&ingestion_id)
1676 .ok_or_else(|| {
1677 StorageError::Generic(anyhow::anyhow!("missing oneshot ingestion {ingestion_id}"))
1679 })?;
1680
1681 match self.instances.get_mut(&pending.cluster_id) {
1682 Some(instance) => {
1683 instance.send(StorageCommand::CancelOneshotIngestion(ingestion_id));
1684 }
1685 None => {
1686 mz_ore::soft_panic_or_log!(
1687 "canceling oneshot ingestion on non-existent cluster, ingestion {:?}, instance {}",
1688 ingestion_id,
1689 pending.cluster_id,
1690 );
1691 }
1692 }
1693 pending.cancel();
1695
1696 Ok(())
1697 }
1698
1699 async fn alter_export(
1700 &mut self,
1701 id: GlobalId,
1702 new_description: ExportDescription,
1703 ) -> Result<(), StorageError> {
1704 let from_id = new_description.sink.from;
1705
1706 let desired_read_holds = vec![from_id.clone(), id.clone()];
1709 let [input_hold, self_hold] = self
1710 .storage_collections
1711 .acquire_read_holds(desired_read_holds)
1712 .expect("missing dependency")
1713 .try_into()
1714 .expect("expected number of holds");
1715 let from_storage_metadata = self.storage_collections.collection_metadata(from_id)?;
1716 let to_storage_metadata = self.storage_collections.collection_metadata(id)?;
1717
1718 let cur_export = self.export_mut(id)?;
1720 let input_readable = cur_export
1721 .write_frontier
1722 .iter()
1723 .all(|t| input_hold.since().less_than(t));
1724 if !input_readable {
1725 return Err(StorageError::ReadBeforeSince(from_id));
1726 }
1727
1728 let new_export = ExportState {
1729 read_capabilities: cur_export.read_capabilities.clone(),
1730 cluster_id: new_description.instance_id,
1731 derived_since: cur_export.derived_since.clone(),
1732 read_holds: [input_hold, self_hold],
1733 read_policy: cur_export.read_policy.clone(),
1734 write_frontier: cur_export.write_frontier.clone(),
1735 };
1736 *cur_export = new_export;
1737
1738 let with_snapshot = new_description.sink.with_snapshot
1745 && !PartialOrder::less_than(&new_description.sink.as_of, &cur_export.write_frontier);
1746
1747 let cmd = RunSinkCommand {
1748 id,
1749 description: StorageSinkDesc {
1750 from: from_id,
1751 from_desc: new_description.sink.from_desc.clone(),
1752 connection: new_description.sink.connection.clone(),
1753 envelope: new_description.sink.envelope,
1754 as_of: new_description.sink.as_of.clone(),
1755 version: new_description.sink.version,
1756 from_storage_metadata,
1757 with_snapshot,
1758 to_storage_metadata,
1759 commit_interval: new_description.sink.commit_interval,
1760 },
1761 };
1762
1763 let instance = self
1765 .instances
1766 .get_mut(&new_description.instance_id)
1767 .ok_or_else(|| StorageError::ExportInstanceMissing {
1768 storage_instance_id: new_description.instance_id,
1769 export_id: id,
1770 })?;
1771
1772 instance.send(StorageCommand::RunSink(Box::new(cmd)));
1773
1774 let state = self
1778 .collections
1779 .get_mut(&id)
1780 .expect("export known to exist");
1781 let DataSource::Sink { desc } = &mut state.data_source else {
1782 panic!("export known to exist")
1783 };
1784 *desc = new_description;
1785
1786 Ok(())
1787 }
1788
1789 async fn alter_export_connections(
1791 &mut self,
1792 exports: BTreeMap<GlobalId, StorageSinkConnection>,
1793 ) -> Result<(), StorageError> {
1794 let mut updates_by_instance =
1795 BTreeMap::<StorageInstanceId, Vec<(RunSinkCommand, ExportDescription)>>::new();
1796
1797 for (id, connection) in exports {
1798 let (current_export_description, as_of): (ExportDescription, _) = {
1806 let export = &self.collections[&id];
1807 let DataSource::Sink { desc } = &export.data_source else {
1808 panic!("export exists")
1809 };
1810 let CollectionStateExtra::Export(state) = &export.extra_state else {
1811 panic!("export exists")
1812 };
1813 let export_description = desc.clone();
1814 let as_of = state.input_hold().since().clone();
1815
1816 (export_description, as_of)
1817 };
1818
1819 let mut new_export_description = current_export_description.clone();
1820
1821 new_export_description.sink.connection = connection;
1822
1823 current_export_description
1825 .sink
1826 .alter_compatible(id, &new_export_description.sink)?;
1827
1828 let from_storage_metadata = self
1829 .storage_collections
1830 .collection_metadata(new_export_description.sink.from)?;
1831 let to_storage_metadata = self.storage_collections.collection_metadata(id)?;
1832
1833 let cmd = RunSinkCommand {
1834 id,
1835 description: StorageSinkDesc {
1836 from: new_export_description.sink.from,
1837 from_desc: new_export_description.sink.from_desc.clone(),
1838 connection: new_export_description.sink.connection.clone(),
1839 envelope: new_export_description.sink.envelope,
1840 with_snapshot: new_export_description.sink.with_snapshot,
1841 version: new_export_description.sink.version,
1842 as_of: as_of.to_owned(),
1853 from_storage_metadata,
1854 to_storage_metadata,
1855 commit_interval: new_export_description.sink.commit_interval,
1856 },
1857 };
1858
1859 let update = updates_by_instance
1860 .entry(new_export_description.instance_id)
1861 .or_default();
1862 update.push((cmd, new_export_description));
1863 }
1864
1865 for (instance_id, updates) in updates_by_instance {
1866 let mut export_updates = BTreeMap::new();
1867 let mut cmds = Vec::with_capacity(updates.len());
1868
1869 for (cmd, export_state) in updates {
1870 export_updates.insert(cmd.id, export_state);
1871 cmds.push(cmd);
1872 }
1873
1874 let instance = self.instances.get_mut(&instance_id).ok_or_else(|| {
1876 StorageError::ExportInstanceMissing {
1877 storage_instance_id: instance_id,
1878 export_id: *export_updates
1879 .keys()
1880 .next()
1881 .expect("set of exports not empty"),
1882 }
1883 })?;
1884
1885 for cmd in cmds {
1886 instance.send(StorageCommand::RunSink(Box::new(cmd)));
1887 }
1888
1889 for (id, new_export_description) in export_updates {
1891 let Some(state) = self.collections.get_mut(&id) else {
1892 panic!("export known to exist")
1893 };
1894 let DataSource::Sink { desc } = &mut state.data_source else {
1895 panic!("export known to exist")
1896 };
1897 *desc = new_export_description;
1898 }
1899 }
1900
1901 Ok(())
1902 }
1903
1904 fn drop_tables(
1905 &mut self,
1906 storage_metadata: &StorageMetadata,
1907 identifiers: Vec<GlobalId>,
1908 ) -> Result<(), StorageError> {
1909 let (table_write_ids, data_source_ids): (Vec<_>, Vec<_>) = identifiers
1910 .into_iter()
1911 .partition(|id| match self.collections[id].data_source {
1912 DataSource::Table => true,
1913 DataSource::IngestionExport { .. } | DataSource::Webhook => false,
1914 _ => panic!("identifier is not a table: {}", id),
1915 });
1916
1917 if table_write_ids.len() > 0 {
1918 let tx = self.pending_table_handle_drops_tx.clone();
1919 for identifier in table_write_ids {
1920 let _ = tx.send(identifier);
1921 }
1922 }
1923
1924 if data_source_ids.len() > 0 {
1925 self.validate_collection_ids(data_source_ids.iter().cloned())?;
1926 self.drop_sources_unvalidated(storage_metadata, data_source_ids)?;
1927 }
1928
1929 Ok(())
1930 }
1931
1932 fn drop_sources(
1933 &mut self,
1934 storage_metadata: &StorageMetadata,
1935 identifiers: Vec<GlobalId>,
1936 ) -> Result<(), StorageError> {
1937 self.validate_collection_ids(identifiers.iter().cloned())?;
1938 self.drop_sources_unvalidated(storage_metadata, identifiers)
1939 }
1940
1941 fn drop_sources_unvalidated(
1942 &mut self,
1943 storage_metadata: &StorageMetadata,
1944 ids: Vec<GlobalId>,
1945 ) -> Result<(), StorageError> {
1946 let mut ingestions_to_execute = BTreeSet::new();
1949 let mut ingestions_to_drop = BTreeSet::new();
1950 let mut source_statistics_to_drop = Vec::new();
1951
1952 let mut collections_to_drop = Vec::new();
1956
1957 for id in ids.iter() {
1958 let collection_state = self.collections.get(id);
1959
1960 if let Some(collection_state) = collection_state {
1961 match collection_state.data_source {
1962 DataSource::Webhook => {
1963 let fut = self.collection_manager.unregister_collection(*id);
1966 mz_ore::task::spawn(|| format!("storage-webhook-cleanup-{id}"), fut);
1967
1968 collections_to_drop.push(*id);
1969 source_statistics_to_drop.push(*id);
1970 }
1971 DataSource::Ingestion(_) => {
1972 ingestions_to_drop.insert(*id);
1973 source_statistics_to_drop.push(*id);
1974 }
1975 DataSource::IngestionExport { ingestion_id, .. } => {
1976 ingestions_to_execute.insert(ingestion_id);
1983
1984 let ingestion_state = match self.collections.get_mut(&ingestion_id) {
1986 Some(ingestion_collection) => ingestion_collection,
1987 None => {
1989 tracing::error!(
1990 "primary source {ingestion_id} seemingly dropped before subsource {id}"
1991 );
1992 continue;
1993 }
1994 };
1995
1996 match &mut ingestion_state.data_source {
1997 DataSource::Ingestion(ingestion_desc) => {
1998 let removed = ingestion_desc.source_exports.remove(id);
1999 mz_ore::soft_assert_or_log!(
2000 removed.is_some(),
2001 "dropped subsource {id} already removed from source exports"
2002 );
2003 }
2004 _ => unreachable!(
2005 "SourceExport must only refer to primary sources that already exist"
2006 ),
2007 };
2008
2009 ingestions_to_drop.insert(*id);
2013 source_statistics_to_drop.push(*id);
2014 }
2015 DataSource::Progress | DataSource::Table | DataSource::Other => {
2016 collections_to_drop.push(*id);
2017 }
2018 DataSource::Introspection(_) | DataSource::Sink { .. } => {
2019 soft_panic_or_log!(
2022 "drop_sources called on a {:?} (id={id}))",
2023 collection_state.data_source,
2024 );
2025 }
2026 }
2027 }
2028 }
2029
2030 ingestions_to_execute.retain(|id| !ingestions_to_drop.contains(id));
2032 for ingestion_id in ingestions_to_execute {
2033 self.run_ingestion(ingestion_id)?;
2034 }
2035
2036 let ingestion_policies = ingestions_to_drop
2043 .iter()
2044 .map(|id| (*id, ReadPolicy::ValidFrom(Antichain::new())))
2045 .collect();
2046
2047 tracing::debug!(
2048 ?ingestion_policies,
2049 "dropping sources by setting read hold policies"
2050 );
2051 self.set_hold_policies(ingestion_policies);
2052
2053 let shards_to_update: BTreeSet<_> = ingestions_to_drop
2055 .iter()
2056 .chain(collections_to_drop.iter())
2057 .cloned()
2058 .collect();
2059 self.append_shard_mappings(shards_to_update.into_iter(), Diff::MINUS_ONE);
2060
2061 let status_now = mz_ore::now::to_datetime((self.now)());
2062 let mut status_updates = vec![];
2063 for id in ingestions_to_drop.iter() {
2064 status_updates.push(StatusUpdate::new(*id, status_now, Status::Dropped));
2065 }
2066
2067 if !self.read_only {
2068 self.append_status_introspection_updates(
2069 IntrospectionType::SourceStatusHistory,
2070 status_updates,
2071 );
2072 }
2073
2074 {
2075 let mut source_statistics = self.source_statistics.lock().expect("poisoned");
2076 for id in source_statistics_to_drop {
2077 source_statistics
2078 .source_statistics
2079 .retain(|(stats_id, _), _| stats_id != &id);
2080 source_statistics
2081 .webhook_statistics
2082 .retain(|stats_id, _| stats_id != &id);
2083 }
2084 }
2085
2086 for id in ingestions_to_drop.iter().chain(collections_to_drop.iter()) {
2088 tracing::info!(%id, "dropping collection state");
2089 let collection = self
2090 .collections
2091 .remove(id)
2092 .expect("list populated after checking that self.collections contains it");
2093
2094 let instance = match &collection.extra_state {
2095 CollectionStateExtra::Ingestion(ingestion) => Some(ingestion.instance_id),
2096 CollectionStateExtra::Export(export) => Some(export.cluster_id()),
2097 CollectionStateExtra::None => None,
2098 }
2099 .and_then(|i| self.instances.get(&i));
2100
2101 if let Some(instance) = instance {
2105 let active_replicas = instance.get_active_replicas_for_object(id);
2106 if !active_replicas.is_empty() {
2107 match &collection.data_source {
2114 DataSource::Ingestion(ingestion_desc) => {
2115 if *id != ingestion_desc.remap_collection_id {
2116 self.dropped_objects.insert(
2117 ingestion_desc.remap_collection_id,
2118 active_replicas.clone(),
2119 );
2120 }
2121 }
2122 _ => {}
2123 }
2124
2125 self.dropped_objects.insert(*id, active_replicas);
2126 }
2127 }
2128 }
2129
2130 self.storage_collections
2132 .drop_collections_unvalidated(storage_metadata, ids);
2133
2134 Ok(())
2135 }
2136
2137 fn drop_sinks(
2139 &mut self,
2140 storage_metadata: &StorageMetadata,
2141 identifiers: Vec<GlobalId>,
2142 ) -> Result<(), StorageError> {
2143 self.validate_export_ids(identifiers.iter().cloned())?;
2144 self.drop_sinks_unvalidated(storage_metadata, identifiers);
2145 Ok(())
2146 }
2147
2148 fn drop_sinks_unvalidated(
2149 &mut self,
2150 storage_metadata: &StorageMetadata,
2151 mut sinks_to_drop: Vec<GlobalId>,
2152 ) {
2153 sinks_to_drop.retain(|id| self.export(*id).is_ok());
2155
2156 let drop_policy = sinks_to_drop
2163 .iter()
2164 .map(|id| (*id, ReadPolicy::ValidFrom(Antichain::new())))
2165 .collect();
2166
2167 tracing::debug!(
2168 ?drop_policy,
2169 "dropping sources by setting read hold policies"
2170 );
2171 self.set_hold_policies(drop_policy);
2172
2173 let status_now = mz_ore::now::to_datetime((self.now)());
2180
2181 let mut status_updates = vec![];
2183 {
2184 let mut sink_statistics = self.sink_statistics.lock().expect("poisoned");
2185 for id in sinks_to_drop.iter() {
2186 status_updates.push(StatusUpdate::new(*id, status_now, Status::Dropped));
2187 sink_statistics.retain(|(stats_id, _), _| stats_id != id);
2188 }
2189 }
2190
2191 if !self.read_only {
2192 self.append_status_introspection_updates(
2193 IntrospectionType::SinkStatusHistory,
2194 status_updates,
2195 );
2196 }
2197
2198 for id in sinks_to_drop.iter() {
2200 tracing::info!(%id, "dropping export state");
2201 let collection = self
2202 .collections
2203 .remove(id)
2204 .expect("list populated after checking that self.collections contains it");
2205
2206 let instance = match &collection.extra_state {
2207 CollectionStateExtra::Ingestion(ingestion) => Some(ingestion.instance_id),
2208 CollectionStateExtra::Export(export) => Some(export.cluster_id()),
2209 CollectionStateExtra::None => None,
2210 }
2211 .and_then(|i| self.instances.get(&i));
2212
2213 if let Some(instance) = instance {
2217 let active_replicas = instance.get_active_replicas_for_object(id);
2218 if !active_replicas.is_empty() {
2219 self.dropped_objects.insert(*id, active_replicas);
2220 }
2221 }
2222 }
2223
2224 self.storage_collections
2226 .drop_collections_unvalidated(storage_metadata, sinks_to_drop);
2227 }
2228
2229 #[instrument(level = "debug")]
2230 fn append_table(
2231 &mut self,
2232 write_ts: Timestamp,
2233 advance_to: Timestamp,
2234 commands: Vec<(GlobalId, Vec<TableData>)>,
2235 ) -> Result<tokio::sync::oneshot::Receiver<Result<(), StorageError>>, StorageError> {
2236 if self.read_only {
2237 if !commands
2240 .iter()
2241 .all(|(id, _)| id.is_system() && self.migrated_storage_collections.contains(id))
2242 {
2243 return Err(StorageError::ReadOnly);
2244 }
2245 }
2246
2247 for (id, updates) in commands.iter() {
2249 if !updates.is_empty() {
2250 if !write_ts.less_than(&advance_to) {
2251 return Err(StorageError::UpdateBeyondUpper(*id));
2252 }
2253 }
2254 }
2255
2256 Ok(self
2257 .persist_table_worker
2258 .append(write_ts, advance_to, commands))
2259 }
2260
2261 fn table_write_handle(&self) -> Arc<dyn mz_storage_client::controller::TableWriteHandle> {
2262 Arc::new(persist_handles::TableWriteWorkerHandle(
2263 self.persist_table_worker.clone(),
2264 ))
2265 }
2266
2267 fn monotonic_appender(&self, id: GlobalId) -> Result<MonotonicAppender, StorageError> {
2268 self.collection_manager.monotonic_appender(id)
2269 }
2270
2271 fn webhook_statistics(&self, id: GlobalId) -> Result<Arc<WebhookStatistics>, StorageError> {
2272 let source_statistics = self.source_statistics.lock().expect("poisoned");
2274 source_statistics
2275 .webhook_statistics
2276 .get(&id)
2277 .cloned()
2278 .ok_or(StorageError::IdentifierMissing(id))
2279 }
2280
2281 async fn ready(&mut self) {
2282 if self.maintenance_scheduled {
2283 return;
2284 }
2285
2286 if !self.pending_table_handle_drops_rx.is_empty() {
2287 return;
2288 }
2289
2290 tokio::select! {
2291 Some(m) = self.instance_response_rx.recv() => {
2292 self.stashed_responses.push(m);
2293 while let Ok(m) = self.instance_response_rx.try_recv() {
2294 self.stashed_responses.push(m);
2295 }
2296 }
2297 _ = self.maintenance_ticker.tick() => {
2298 self.maintenance_scheduled = true;
2299 },
2300 };
2301 }
2302
2303 #[instrument(level = "debug")]
2304 fn process(
2305 &mut self,
2306 storage_metadata: &StorageMetadata,
2307 ) -> Result<Option<Response>, anyhow::Error> {
2308 if self.maintenance_scheduled {
2310 self.maintain();
2311 self.maintenance_scheduled = false;
2312 }
2313
2314 for instance in self.instances.values_mut() {
2315 instance.rehydrate_failed_replicas();
2316 }
2317
2318 let mut status_updates = vec![];
2319 let mut updated_frontiers = BTreeMap::new();
2320
2321 let stashed_responses = std::mem::take(&mut self.stashed_responses);
2323 for resp in stashed_responses {
2324 match resp {
2325 (_replica_id, StorageResponse::FrontierUpper(id, upper)) => {
2326 self.update_write_frontier(id, &upper);
2327 updated_frontiers.insert(id, upper);
2328 }
2329 (replica_id, StorageResponse::DroppedId(id)) => {
2330 let replica_id = replica_id.expect("DroppedId from unknown replica");
2331 if let Some(remaining_replicas) = self.dropped_objects.get_mut(&id) {
2332 remaining_replicas.remove(&replica_id);
2333 if remaining_replicas.is_empty() {
2334 self.dropped_objects.remove(&id);
2335 }
2336 } else {
2337 soft_panic_or_log!("unexpected DroppedId for {id}");
2338 }
2339 }
2340 (replica_id, StorageResponse::StatisticsUpdates(source_stats, sink_stats)) => {
2341 {
2343 let replica_id = if let Some(replica_id) = replica_id {
2350 replica_id
2351 } else {
2352 tracing::error!(
2353 ?source_stats,
2354 "missing replica_id for source statistics update"
2355 );
2356 continue;
2357 };
2358
2359 let mut shared_stats = self.source_statistics.lock().expect("poisoned");
2360
2361 for stat in source_stats {
2362 let collection_id = stat.id.clone();
2363
2364 if self.collection(collection_id).is_err() {
2365 continue;
2368 }
2369
2370 let entry = shared_stats
2371 .source_statistics
2372 .entry((stat.id, Some(replica_id)));
2373
2374 match entry {
2375 btree_map::Entry::Vacant(vacant_entry) => {
2376 let mut stats = ControllerSourceStatistics::new(
2377 collection_id,
2378 Some(replica_id),
2379 );
2380 stats.incorporate(stat);
2381 vacant_entry.insert(stats);
2382 }
2383 btree_map::Entry::Occupied(mut occupied_entry) => {
2384 occupied_entry.get_mut().incorporate(stat);
2385 }
2386 }
2387 }
2388 }
2389
2390 {
2391 let replica_id = if let Some(replica_id) = replica_id {
2402 replica_id
2403 } else {
2404 tracing::error!(
2405 ?sink_stats,
2406 "missing replica_id for sink statistics update"
2407 );
2408 continue;
2409 };
2410
2411 let mut shared_stats = self.sink_statistics.lock().expect("poisoned");
2412
2413 for stat in sink_stats {
2414 let collection_id = stat.id.clone();
2415
2416 if self.collection(collection_id).is_err() {
2417 continue;
2420 }
2421
2422 let entry = shared_stats.entry((stat.id, Some(replica_id)));
2423
2424 match entry {
2425 btree_map::Entry::Vacant(vacant_entry) => {
2426 let mut stats =
2427 ControllerSinkStatistics::new(collection_id, replica_id);
2428 stats.incorporate(stat);
2429 vacant_entry.insert(stats);
2430 }
2431 btree_map::Entry::Occupied(mut occupied_entry) => {
2432 occupied_entry.get_mut().incorporate(stat);
2433 }
2434 }
2435 }
2436 }
2437 }
2438 (replica_id, StorageResponse::StatusUpdate(mut status_update)) => {
2439 match status_update.status {
2455 Status::Running => {
2456 let collection = self.collections.get_mut(&status_update.id);
2457 match collection {
2458 Some(collection) => {
2459 match collection.extra_state {
2460 CollectionStateExtra::Ingestion(
2461 ref mut ingestion_state,
2462 ) => {
2463 if ingestion_state.hydrated_on.is_empty() {
2464 tracing::debug!(ingestion_id = %status_update.id, "ingestion is hydrated");
2465 }
2466 ingestion_state.hydrated_on.insert(replica_id.expect(
2467 "replica id should be present for status running",
2468 ));
2469 }
2470 CollectionStateExtra::Export(_) => {
2471 }
2473 CollectionStateExtra::None => {
2474 }
2476 }
2477 }
2478 None => (), }
2481 }
2482 Status::Paused => {
2483 let collection = self.collections.get_mut(&status_update.id);
2484 match collection {
2485 Some(collection) => {
2486 match collection.extra_state {
2487 CollectionStateExtra::Ingestion(
2488 ref mut ingestion_state,
2489 ) => {
2490 tracing::debug!(ingestion_id = %status_update.id, "ingestion is now paused");
2497 ingestion_state.hydrated_on.clear();
2498 }
2499 CollectionStateExtra::Export(_) => {
2500 }
2502 CollectionStateExtra::None => {
2503 }
2505 }
2506 }
2507 None => (), }
2510 }
2511 _ => (),
2512 }
2513
2514 if let Some(id) = replica_id {
2516 status_update.replica_id = Some(id);
2517 }
2518 status_updates.push(status_update);
2519 }
2520 (_replica_id, StorageResponse::StagedBatches(batches)) => {
2521 for (ingestion_id, batches) in batches {
2522 match self.pending_oneshot_ingestions.remove(&ingestion_id) {
2523 Some(pending) => {
2524 if let Some(instance) = self.instances.get_mut(&pending.cluster_id)
2527 {
2528 instance
2529 .send(StorageCommand::CancelOneshotIngestion(ingestion_id));
2530 }
2531 (pending.result_tx)(batches)
2533 }
2534 None => {
2535 }
2538 }
2539 }
2540 }
2541 }
2542 }
2543
2544 self.record_status_updates(status_updates);
2545
2546 let mut dropped_table_ids = Vec::new();
2548 while let Ok(dropped_id) = self.pending_table_handle_drops_rx.try_recv() {
2549 dropped_table_ids.push(dropped_id);
2550 }
2551 if !dropped_table_ids.is_empty() {
2552 self.drop_sources(storage_metadata, dropped_table_ids)?;
2553 }
2554
2555 if updated_frontiers.is_empty() {
2556 Ok(None)
2557 } else {
2558 Ok(Some(Response::FrontierUpdates(
2559 updated_frontiers.into_iter().collect(),
2560 )))
2561 }
2562 }
2563
2564 async fn inspect_persist_state(
2565 &self,
2566 id: GlobalId,
2567 ) -> Result<serde_json::Value, anyhow::Error> {
2568 let collection = &self.storage_collections.collection_metadata(id)?;
2569 let client = self
2570 .persist
2571 .open(collection.persist_location.clone())
2572 .await?;
2573 let shard_state = client
2574 .inspect_shard::<Timestamp>(&collection.data_shard)
2575 .await?;
2576 let json_state = serde_json::to_value(shard_state)?;
2577 Ok(json_state)
2578 }
2579
2580 fn append_introspection_updates(
2581 &mut self,
2582 type_: IntrospectionType,
2583 updates: Vec<(Row, Diff)>,
2584 ) {
2585 let id = self.introspection_ids[&type_];
2586 let updates = updates.into_iter().map(|update| update.into()).collect();
2587 self.collection_manager.blind_write(id, updates);
2588 }
2589
2590 fn append_status_introspection_updates(
2591 &mut self,
2592 type_: IntrospectionType,
2593 updates: Vec<StatusUpdate>,
2594 ) {
2595 let id = self.introspection_ids[&type_];
2596 let updates: Vec<_> = updates.into_iter().map(|update| update.into()).collect();
2597 if !updates.is_empty() {
2598 self.collection_manager.blind_write(id, updates);
2599 }
2600 }
2601
2602 fn update_introspection_collection(&mut self, type_: IntrospectionType, op: StorageWriteOp) {
2603 let id = self.introspection_ids[&type_];
2604 self.collection_manager.differential_write(id, op);
2605 }
2606
2607 fn append_only_introspection_tx(
2608 &self,
2609 type_: IntrospectionType,
2610 ) -> mpsc::UnboundedSender<(
2611 Vec<AppendOnlyUpdate>,
2612 oneshot::Sender<Result<(), StorageError>>,
2613 )> {
2614 let id = self.introspection_ids[&type_];
2615 self.collection_manager.append_only_write_sender(id)
2616 }
2617
2618 fn differential_introspection_tx(
2619 &self,
2620 type_: IntrospectionType,
2621 ) -> mpsc::UnboundedSender<(StorageWriteOp, oneshot::Sender<Result<(), StorageError>>)> {
2622 let id = self.introspection_ids[&type_];
2623 self.collection_manager.differential_write_sender(id)
2624 }
2625
2626 async fn real_time_recent_timestamp(
2627 &self,
2628 timestamp_objects: BTreeSet<GlobalId>,
2629 timeout: Duration,
2630 ) -> Result<BoxFuture<Result<Timestamp, StorageError>>, StorageError> {
2631 use mz_storage_types::sources::GenericSourceConnection;
2632
2633 let mut rtr_futures = BTreeMap::new();
2634
2635 for id in timestamp_objects.into_iter().filter(GlobalId::is_user) {
2637 let collection = match self.collection(id) {
2638 Ok(c) => c,
2639 Err(_) => continue,
2641 };
2642
2643 let (source_conn, remap_id) = match &collection.data_source {
2644 DataSource::Ingestion(IngestionDescription {
2645 desc: SourceDesc { connection, .. },
2646 remap_collection_id,
2647 ..
2648 }) => match connection {
2649 GenericSourceConnection::Kafka(_)
2650 | GenericSourceConnection::Postgres(_)
2651 | GenericSourceConnection::MySql(_)
2652 | GenericSourceConnection::SqlServer(_) => {
2653 (connection.clone(), *remap_collection_id)
2654 }
2655
2656 GenericSourceConnection::LoadGenerator(_) => continue,
2661 },
2662 _ => {
2664 continue;
2665 }
2666 };
2667
2668 let config = self.config().clone();
2670
2671 let read_handle = self.read_handle_for_snapshot(remap_id).await?;
2679
2680 let remap_read_hold = self
2683 .storage_collections
2684 .acquire_read_holds(vec![remap_id])
2685 .map_err(|_e| StorageError::ReadBeforeSince(remap_id))?
2686 .expect_element(|| "known to be exactly one");
2687
2688 let remap_as_of = remap_read_hold
2689 .since()
2690 .to_owned()
2691 .into_option()
2692 .ok_or(StorageError::ReadBeforeSince(remap_id))?;
2693
2694 rtr_futures.insert(
2695 id,
2696 tokio::time::timeout(timeout, async move {
2697 use mz_storage_types::sources::SourceConnection as _;
2698
2699 let as_of = Antichain::from_elem(remap_as_of);
2702 let remap_subscribe = read_handle
2703 .subscribe(as_of.clone())
2704 .await
2705 .map_err(|_| StorageError::ReadBeforeSince(remap_id))?;
2706
2707 tracing::debug!(?id, type_ = source_conn.name(), upstream = ?source_conn.external_reference(), "fetching real time recency");
2708
2709 let result = rtr::real_time_recency_ts(
2710 source_conn,
2711 id,
2712 config,
2713 as_of,
2714 remap_subscribe,
2715 )
2716 .await
2717 .map_err(|e| {
2718 tracing::debug!(?id, "real time recency error: {:?}", e);
2719 e
2720 });
2721
2722 drop(remap_read_hold);
2724
2725 result
2726 }),
2727 );
2728 }
2729
2730 Ok(Box::pin(async move {
2731 let (ids, futs): (Vec<_>, Vec<_>) = rtr_futures.into_iter().unzip();
2732 ids.into_iter()
2733 .zip_eq(futures::future::join_all(futs).await)
2734 .try_fold(Timestamp::MIN, |curr, (id, per_source_res)| {
2735 let new =
2736 per_source_res.map_err(|_e: Elapsed| StorageError::RtrTimeout(id))??;
2737 Ok::<_, StorageError>(std::cmp::max(curr, new))
2738 })
2739 }))
2740 }
2741
2742 fn dump(&self) -> Result<serde_json::Value, anyhow::Error> {
2743 let Self {
2745 build_info: _,
2746 now: _,
2747 read_only,
2748 collections,
2749 dropped_objects,
2750 persist_table_worker: _,
2751 txns_read: _,
2752 txns_metrics: _,
2753 stashed_responses,
2754 pending_table_handle_drops_tx: _,
2755 pending_table_handle_drops_rx: _,
2756 pending_oneshot_ingestions,
2757 collection_manager: _,
2758 introspection_ids,
2759 introspection_tokens: _,
2760 source_statistics: _,
2761 sink_statistics: _,
2762 statistics_interval_sender: _,
2763 instances,
2764 replica_dyncfg_overrides: _,
2765 initialized,
2766 config,
2767 persist_location,
2768 persist: _,
2769 metrics: _,
2770 recorded_frontiers,
2771 recorded_replica_frontiers,
2772 wallclock_lag: _,
2773 wallclock_lag_last_recorded,
2774 storage_collections: _,
2775 migrated_storage_collections,
2776 maintenance_ticker: _,
2777 maintenance_scheduled,
2778 instance_response_tx: _,
2779 instance_response_rx: _,
2780 persist_warm_task: _,
2781 } = self;
2782
2783 let collections: BTreeMap<_, _> = collections
2784 .iter()
2785 .map(|(id, c)| (id.to_string(), format!("{c:?}")))
2786 .collect();
2787 let dropped_objects: BTreeMap<_, _> = dropped_objects
2788 .iter()
2789 .map(|(id, rs)| (id.to_string(), format!("{rs:?}")))
2790 .collect();
2791 let stashed_responses: Vec<_> =
2792 stashed_responses.iter().map(|r| format!("{r:?}")).collect();
2793 let pending_oneshot_ingestions: BTreeMap<_, _> = pending_oneshot_ingestions
2794 .iter()
2795 .map(|(uuid, i)| (uuid.to_string(), format!("{i:?}")))
2796 .collect();
2797 let introspection_ids: BTreeMap<_, _> = introspection_ids
2798 .iter()
2799 .map(|(typ, id)| (format!("{typ:?}"), id.to_string()))
2800 .collect();
2801 let instances: BTreeMap<_, _> = instances
2802 .iter()
2803 .map(|(id, i)| (id.to_string(), format!("{i:?}")))
2804 .collect();
2805 let recorded_frontiers: BTreeMap<_, _> = recorded_frontiers
2806 .iter()
2807 .map(|(id, fs)| (id.to_string(), format!("{fs:?}")))
2808 .collect();
2809 let recorded_replica_frontiers: Vec<_> = recorded_replica_frontiers
2810 .iter()
2811 .map(|((gid, rid), f)| (gid.to_string(), rid.to_string(), format!("{f:?}")))
2812 .collect();
2813 let migrated_storage_collections: Vec<_> = migrated_storage_collections
2814 .iter()
2815 .map(|id| id.to_string())
2816 .collect();
2817
2818 Ok(serde_json::json!({
2819 "read_only": read_only,
2820 "collections": collections,
2821 "dropped_objects": dropped_objects,
2822 "stashed_responses": stashed_responses,
2823 "pending_oneshot_ingestions": pending_oneshot_ingestions,
2824 "introspection_ids": introspection_ids,
2825 "instances": instances,
2826 "initialized": initialized,
2827 "config": format!("{config:?}"),
2828 "persist_location": format!("{persist_location:?}"),
2829 "recorded_frontiers": recorded_frontiers,
2830 "recorded_replica_frontiers": recorded_replica_frontiers,
2831 "wallclock_lag_last_recorded": format!("{wallclock_lag_last_recorded:?}"),
2832 "migrated_storage_collections": migrated_storage_collections,
2833 "maintenance_scheduled": maintenance_scheduled,
2834 }))
2835 }
2836}
2837
2838pub fn prepare_initialization(txn: &mut dyn StorageTxn) -> Result<(), StorageError> {
2845 if txn.get_txn_wal_shard().is_none() {
2846 let txns_id = ShardId::new();
2847 txn.write_txn_wal_shard(txns_id)?;
2848 }
2849
2850 Ok(())
2851}
2852
2853impl Controller
2854where
2855 Self: StorageController,
2856{
2857 pub async fn new(
2865 build_info: &'static BuildInfo,
2866 persist_location: PersistLocation,
2867 persist_clients: Arc<PersistClientCache>,
2868 now: NowFn,
2869 wallclock_lag: WallclockLagFn<Timestamp>,
2870 txns_metrics: Arc<TxnMetrics>,
2871 read_only: bool,
2872 metrics_registry: &MetricsRegistry,
2873 controller_metrics: ControllerMetrics,
2874 connection_context: ConnectionContext,
2875 txn: &dyn StorageTxn,
2876 storage_collections: Arc<dyn StorageCollections + Send + Sync>,
2877 ) -> Self {
2878 let txns_client = persist_clients
2879 .open(persist_location.clone())
2880 .await
2881 .expect("location should be valid");
2882
2883 let persist_warm_task = warm_persist_state_in_background(
2884 txns_client.clone(),
2885 txn.get_collection_metadata().into_values(),
2886 );
2887 let persist_warm_task = Some(persist_warm_task.abort_on_drop());
2888
2889 let txns_id = txn
2893 .get_txn_wal_shard()
2894 .expect("must call prepare initialization before creating storage controller");
2895
2896 let persist_table_worker = if read_only {
2897 let txns_write = txns_client
2898 .open_writer(
2899 txns_id,
2900 Arc::new(TxnsCodecRow::desc()),
2901 Arc::new(UnitSchema),
2902 Diagnostics {
2903 shard_name: "txns".to_owned(),
2904 handle_purpose: "follow txns upper".to_owned(),
2905 },
2906 )
2907 .await
2908 .expect("txns schema shouldn't change");
2909 persist_handles::PersistTableWriteWorker::new_read_only_mode(
2910 txns_write,
2911 txns_client.clone(),
2912 )
2913 } else {
2914 let mut txns = TxnsHandle::open(
2915 Timestamp::MIN,
2916 txns_client.clone(),
2917 txns_client.dyncfgs().clone(),
2918 Arc::clone(&txns_metrics),
2919 txns_id,
2920 Opaque::encode(&PersistEpoch::default()),
2921 )
2922 .await;
2923 txns.upgrade_version().await;
2924 persist_handles::PersistTableWriteWorker::new_txns(txns, txns_client.clone())
2925 };
2926 let txns_read = TxnsRead::start::<TxnsCodecRow>(txns_client.clone(), txns_id).await;
2927
2928 let collection_manager = collection_mgmt::CollectionManager::new(read_only, now.clone());
2929
2930 let introspection_ids = BTreeMap::new();
2931 let introspection_tokens = Arc::new(Mutex::new(BTreeMap::new()));
2932
2933 let (statistics_interval_sender, _) =
2934 channel(mz_storage_types::parameters::STATISTICS_INTERVAL_DEFAULT);
2935
2936 let (pending_table_handle_drops_tx, pending_table_handle_drops_rx) =
2937 tokio::sync::mpsc::unbounded_channel();
2938
2939 let mut maintenance_ticker = tokio::time::interval(Duration::from_secs(1));
2940 maintenance_ticker.set_missed_tick_behavior(MissedTickBehavior::Skip);
2941
2942 let (instance_response_tx, instance_response_rx) = mpsc::unbounded_channel();
2943
2944 let metrics = StorageControllerMetrics::new(metrics_registry, controller_metrics);
2945
2946 let now_dt = mz_ore::now::to_datetime(now());
2947
2948 Self {
2949 build_info,
2950 collections: BTreeMap::default(),
2951 dropped_objects: Default::default(),
2952 persist_table_worker,
2953 txns_read,
2954 txns_metrics,
2955 stashed_responses: vec![],
2956 pending_table_handle_drops_tx,
2957 pending_table_handle_drops_rx,
2958 pending_oneshot_ingestions: BTreeMap::default(),
2959 collection_manager,
2960 introspection_ids,
2961 introspection_tokens,
2962 now,
2963 read_only,
2964 source_statistics: Arc::new(Mutex::new(statistics::SourceStatistics {
2965 source_statistics: BTreeMap::new(),
2966 webhook_statistics: BTreeMap::new(),
2967 })),
2968 sink_statistics: Arc::new(Mutex::new(BTreeMap::new())),
2969 statistics_interval_sender,
2970 instances: BTreeMap::new(),
2971 replica_dyncfg_overrides: BTreeMap::new(),
2972 initialized: false,
2973 config: StorageConfiguration::new(connection_context, mz_dyncfgs::all_dyncfgs()),
2974 persist_location,
2975 persist: persist_clients,
2976 metrics,
2977 recorded_frontiers: BTreeMap::new(),
2978 recorded_replica_frontiers: BTreeMap::new(),
2979 wallclock_lag,
2980 wallclock_lag_last_recorded: now_dt,
2981 storage_collections,
2982 migrated_storage_collections: BTreeSet::new(),
2983 maintenance_ticker,
2984 maintenance_scheduled: false,
2985 instance_response_rx,
2986 instance_response_tx,
2987 persist_warm_task,
2988 }
2989 }
2990
2991 #[instrument(level = "debug")]
2999 fn set_hold_policies(&mut self, policies: Vec<(GlobalId, ReadPolicy)>) {
3000 let mut read_capability_changes = BTreeMap::default();
3001
3002 for (id, policy) in policies.into_iter() {
3003 if let Some(collection) = self.collections.get_mut(&id) {
3004 let (write_frontier, derived_since, hold_policy) = match &mut collection.extra_state
3005 {
3006 CollectionStateExtra::Ingestion(ingestion) => (
3007 ingestion.write_frontier.borrow(),
3008 &mut ingestion.derived_since,
3009 &mut ingestion.hold_policy,
3010 ),
3011 CollectionStateExtra::None => {
3012 unreachable!("set_hold_policies is only called for ingestions");
3013 }
3014 CollectionStateExtra::Export(export) => (
3015 export.write_frontier.borrow(),
3016 &mut export.derived_since,
3017 &mut export.read_policy,
3018 ),
3019 };
3020
3021 let new_derived_since = policy.frontier(write_frontier);
3022 let mut update = swap_updates(derived_since, new_derived_since);
3023 if !update.is_empty() {
3024 read_capability_changes.insert(id, update);
3025 }
3026
3027 *hold_policy = policy;
3028 }
3029 }
3030
3031 if !read_capability_changes.is_empty() {
3032 self.update_hold_capabilities(&mut read_capability_changes);
3033 }
3034 }
3035
3036 #[instrument(level = "debug", fields(updates))]
3037 fn update_write_frontier(&mut self, id: GlobalId, new_upper: &Antichain<Timestamp>) {
3038 let mut read_capability_changes = BTreeMap::default();
3039
3040 if let Some(collection) = self.collections.get_mut(&id) {
3041 let (write_frontier, derived_since, hold_policy) = match &mut collection.extra_state {
3042 CollectionStateExtra::Ingestion(ingestion) => (
3043 &mut ingestion.write_frontier,
3044 &mut ingestion.derived_since,
3045 &ingestion.hold_policy,
3046 ),
3047 CollectionStateExtra::None => {
3048 if matches!(collection.data_source, DataSource::Progress) {
3049 } else {
3051 tracing::error!(
3052 ?collection,
3053 ?new_upper,
3054 "updated write frontier for collection which is not an ingestion"
3055 );
3056 }
3057 return;
3058 }
3059 CollectionStateExtra::Export(export) => (
3060 &mut export.write_frontier,
3061 &mut export.derived_since,
3062 &export.read_policy,
3063 ),
3064 };
3065
3066 if PartialOrder::less_than(write_frontier, new_upper) {
3067 write_frontier.clone_from(new_upper);
3068 }
3069
3070 let new_derived_since = hold_policy.frontier(write_frontier.borrow());
3071 let mut update = swap_updates(derived_since, new_derived_since);
3072 if !update.is_empty() {
3073 read_capability_changes.insert(id, update);
3074 }
3075 } else if self.dropped_objects.contains_key(&id) {
3076 } else {
3079 soft_panic_or_log!("spurious upper update for {id}: {new_upper:?}");
3080 }
3081
3082 if !read_capability_changes.is_empty() {
3083 self.update_hold_capabilities(&mut read_capability_changes);
3084 }
3085 }
3086
3087 #[instrument(level = "debug", fields(updates))]
3091 fn update_hold_capabilities(
3092 &mut self,
3093 updates: &mut BTreeMap<GlobalId, ChangeBatch<Timestamp>>,
3094 ) {
3095 let mut collections_net = BTreeMap::new();
3097
3098 while let Some(key) = updates.keys().rev().next().cloned() {
3103 let mut update = updates.remove(&key).unwrap();
3104
3105 if key.is_user() {
3106 debug!(id = %key, ?update, "update_hold_capability");
3107 }
3108
3109 if let Some(collection) = self.collections.get_mut(&key) {
3110 match &mut collection.extra_state {
3111 CollectionStateExtra::Ingestion(ingestion) => {
3112 let changes = ingestion.read_capabilities.update_iter(update.drain());
3113 update.extend(changes);
3114
3115 let (changes, frontier, _cluster_id) =
3116 collections_net.entry(key).or_insert_with(|| {
3117 (
3118 <ChangeBatch<_>>::new(),
3119 Antichain::new(),
3120 ingestion.instance_id,
3121 )
3122 });
3123
3124 changes.extend(update.drain());
3125 *frontier = ingestion.read_capabilities.frontier().to_owned();
3126 }
3127 CollectionStateExtra::None => {
3128 soft_panic_or_log!(
3130 "trying to update holds for collection {collection:?} which is not \
3131 an ingestion: {update:?}"
3132 );
3133 continue;
3134 }
3135 CollectionStateExtra::Export(export) => {
3136 let changes = export.read_capabilities.update_iter(update.drain());
3137 update.extend(changes);
3138
3139 let (changes, frontier, _cluster_id) =
3140 collections_net.entry(key).or_insert_with(|| {
3141 (<ChangeBatch<_>>::new(), Antichain::new(), export.cluster_id)
3142 });
3143
3144 changes.extend(update.drain());
3145 *frontier = export.read_capabilities.frontier().to_owned();
3146 }
3147 }
3148 } else {
3149 tracing::warn!(id = ?key, ?update, "update_hold_capabilities for unknown object");
3151 }
3152 }
3153
3154 for (key, (mut changes, frontier, cluster_id)) in collections_net {
3157 if !changes.is_empty() {
3158 if key.is_user() {
3159 debug!(id = %key, ?frontier, "downgrading ingestion read holds!");
3160 }
3161
3162 let collection = self
3163 .collections
3164 .get_mut(&key)
3165 .expect("missing collection state");
3166
3167 let read_holds = match &mut collection.extra_state {
3168 CollectionStateExtra::Ingestion(ingestion) => {
3169 ingestion.dependency_read_holds.as_mut_slice()
3170 }
3171 CollectionStateExtra::Export(export) => export.read_holds.as_mut_slice(),
3172 CollectionStateExtra::None => {
3173 soft_panic_or_log!(
3174 "trying to downgrade read holds for collection which is not an \
3175 ingestion: {collection:?}"
3176 );
3177 continue;
3178 }
3179 };
3180
3181 for read_hold in read_holds.iter_mut() {
3182 read_hold
3183 .try_downgrade(frontier.clone())
3184 .expect("we only advance the frontier");
3185 }
3186
3187 if let Some(instance) = self.instances.get_mut(&cluster_id) {
3189 instance.send(StorageCommand::AllowCompaction(key, frontier.clone()));
3190 } else {
3191 soft_panic_or_log!(
3192 "missing instance client for cluster {cluster_id} while we still have outstanding AllowCompaction command {frontier:?} for {key}"
3193 );
3194 }
3195 }
3196 }
3197 }
3198
3199 fn validate_collection_ids(
3201 &self,
3202 ids: impl Iterator<Item = GlobalId>,
3203 ) -> Result<(), StorageError> {
3204 for id in ids {
3205 self.storage_collections.check_exists(id)?;
3206 }
3207 Ok(())
3208 }
3209
3210 fn validate_export_ids(&self, ids: impl Iterator<Item = GlobalId>) -> Result<(), StorageError> {
3212 for id in ids {
3213 self.export(id)?;
3214 }
3215 Ok(())
3216 }
3217
3218 async fn open_data_handles(
3220 &self,
3221 id: &GlobalId,
3222 shard: ShardId,
3223 relation_desc: RelationDesc,
3224 persist_client: &PersistClient,
3225 ) -> WriteHandle<SourceData, (), Timestamp, StorageDiff> {
3226 let diagnostics = Diagnostics {
3227 shard_name: id.to_string(),
3228 handle_purpose: format!("controller data for {}", id),
3229 };
3230
3231 let mut write = persist_client
3232 .open_writer(
3233 shard,
3234 Arc::new(relation_desc),
3235 Arc::new(UnitSchema),
3236 diagnostics.clone(),
3237 )
3238 .await
3239 .expect("invalid persist usage");
3240
3241 write.fetch_recent_upper().await;
3243
3244 write
3245 }
3246
3247 fn register_introspection_collection(
3252 &mut self,
3253 id: GlobalId,
3254 introspection_type: IntrospectionType,
3255 write_handle: WriteHandle<SourceData, (), Timestamp, StorageDiff>,
3256 persist_client: PersistClient,
3257 ) -> Result<(), StorageError> {
3258 tracing::info!(%id, ?introspection_type, "registering introspection collection");
3259
3260 let force_writable = self.read_only && self.migrated_storage_collections.contains(&id);
3268 if force_writable {
3269 assert!(id.is_system(), "unexpected non-system global id: {id:?}");
3270 info!("writing to migrated storage collection {id} in read-only mode");
3271 }
3272
3273 let prev = self.introspection_ids.insert(introspection_type, id);
3274 assert!(
3275 prev.is_none(),
3276 "cannot have multiple IDs for introspection type"
3277 );
3278
3279 let metadata = self.storage_collections.collection_metadata(id)?.clone();
3280
3281 let read_handle_fn = move || {
3282 let persist_client = persist_client.clone();
3283 let metadata = metadata.clone();
3284
3285 let fut = async move {
3286 let read_handle = persist_client
3287 .open_leased_reader::<SourceData, (), Timestamp, StorageDiff>(
3288 metadata.data_shard,
3289 Arc::new(metadata.relation_desc.clone()),
3290 Arc::new(UnitSchema),
3291 Diagnostics {
3292 shard_name: id.to_string(),
3293 handle_purpose: format!("snapshot {}", id),
3294 },
3295 USE_CRITICAL_SINCE_SNAPSHOT.get(persist_client.dyncfgs()),
3296 )
3297 .await
3298 .expect("invalid persist usage");
3299 read_handle
3300 };
3301
3302 fut.boxed()
3303 };
3304
3305 let recent_upper = write_handle.shared_upper();
3306
3307 match CollectionManagerKind::from(&introspection_type) {
3308 CollectionManagerKind::Differential => {
3313 let statistics_retention_duration =
3314 dyncfgs::STATISTICS_RETENTION_DURATION.get(self.config().config_set());
3315
3316 let introspection_config = DifferentialIntrospectionConfig {
3318 recent_upper,
3319 introspection_type,
3320 storage_collections: Arc::clone(&self.storage_collections),
3321 collection_manager: self.collection_manager.clone(),
3322 source_statistics: Arc::clone(&self.source_statistics),
3323 sink_statistics: Arc::clone(&self.sink_statistics),
3324 statistics_interval: self.config.parameters.statistics_interval.clone(),
3325 statistics_interval_receiver: self.statistics_interval_sender.subscribe(),
3326 statistics_retention_duration,
3327 metrics: self.metrics.clone(),
3328 introspection_tokens: Arc::clone(&self.introspection_tokens),
3329 };
3330 self.collection_manager.register_differential_collection(
3331 id,
3332 write_handle,
3333 read_handle_fn,
3334 force_writable,
3335 introspection_config,
3336 );
3337 }
3338 CollectionManagerKind::AppendOnly => {
3346 let introspection_config = AppendOnlyIntrospectionConfig {
3347 introspection_type,
3348 config_set: Arc::clone(self.config.config_set()),
3349 parameters: self.config.parameters.clone(),
3350 storage_collections: Arc::clone(&self.storage_collections),
3351 };
3352 self.collection_manager.register_append_only_collection(
3353 id,
3354 write_handle,
3355 force_writable,
3356 Some(introspection_config),
3357 );
3358 }
3359 }
3360
3361 Ok(())
3362 }
3363
3364 fn reconcile_dangling_statistics(&self) {
3367 self.source_statistics
3368 .lock()
3369 .expect("poisoned")
3370 .source_statistics
3371 .retain(|(k, _replica_id), _| self.storage_collections.check_exists(*k).is_ok());
3373 self.sink_statistics
3374 .lock()
3375 .expect("poisoned")
3376 .retain(|(k, _replica_id), _| self.export(*k).is_ok());
3377 }
3378
3379 #[instrument(level = "debug")]
3389 fn append_shard_mappings<I>(&self, global_ids: I, diff: Diff)
3390 where
3391 I: Iterator<Item = GlobalId>,
3392 {
3393 mz_ore::soft_assert_or_log!(
3394 diff == Diff::MINUS_ONE || diff == Diff::ONE,
3395 "use 1 for insert or -1 for delete"
3396 );
3397
3398 let id = *self
3399 .introspection_ids
3400 .get(&IntrospectionType::ShardMapping)
3401 .expect("should be registered before this call");
3402
3403 let mut updates = vec![];
3404 let mut row_buf = Row::default();
3406
3407 for global_id in global_ids {
3408 let shard_id = if let Some(collection) = self.collections.get(&global_id) {
3409 collection.collection_metadata.data_shard.clone()
3410 } else {
3411 panic!("unknown global id: {}", global_id);
3412 };
3413
3414 let mut packer = row_buf.packer();
3415 packer.push(Datum::from(global_id.to_string().as_str()));
3416 packer.push(Datum::from(shard_id.to_string().as_str()));
3417 updates.push((row_buf.clone(), diff));
3418 }
3419
3420 self.collection_manager.differential_append(id, updates);
3421 }
3422
3423 fn determine_collection_dependencies(
3425 &self,
3426 self_id: GlobalId,
3427 collection_desc: &CollectionDescription,
3428 ) -> Result<Vec<GlobalId>, StorageError> {
3429 let mut dependencies = Vec::new();
3430
3431 if let Some(id) = collection_desc.primary {
3432 dependencies.push(id);
3433 }
3434
3435 match &collection_desc.data_source {
3436 DataSource::Introspection(_)
3437 | DataSource::Webhook
3438 | DataSource::Table
3439 | DataSource::Progress
3440 | DataSource::Other => (),
3441 DataSource::IngestionExport { ingestion_id, .. } => {
3442 let source_collection = self.collection(*ingestion_id)?;
3445 let ingestion_remap_collection_id = match &source_collection.data_source {
3446 DataSource::Ingestion(ingestion) => ingestion.remap_collection_id,
3447 _ => unreachable!(
3448 "SourceExport must only refer to primary sources that already exist"
3449 ),
3450 };
3451
3452 dependencies.extend([self_id, ingestion_remap_collection_id]);
3458 }
3459 DataSource::Ingestion(ingestion) => {
3461 dependencies.push(self_id);
3466 if self_id != ingestion.remap_collection_id {
3467 dependencies.push(ingestion.remap_collection_id);
3468 }
3469 }
3470 DataSource::Sink { desc } => {
3471 dependencies.extend([self_id, desc.sink.from]);
3473 }
3474 };
3475
3476 Ok(dependencies)
3477 }
3478
3479 async fn read_handle_for_snapshot(
3480 &self,
3481 id: GlobalId,
3482 ) -> Result<ReadHandle<SourceData, (), Timestamp, StorageDiff>, StorageError> {
3483 let metadata = self.storage_collections.collection_metadata(id)?;
3484 read_handle_for_snapshot(&self.persist, id, &metadata).await
3485 }
3486
3487 fn record_status_updates(&mut self, updates: Vec<StatusUpdate>) {
3490 if self.read_only {
3491 return;
3492 }
3493
3494 let mut sink_status_updates = vec![];
3495 let mut source_status_updates = vec![];
3496
3497 for update in updates {
3498 let id = update.id;
3499 if self.export(id).is_ok() {
3500 sink_status_updates.push(update);
3501 } else if self.storage_collections.check_exists(id).is_ok() {
3502 source_status_updates.push(update);
3503 }
3504 }
3505
3506 self.append_status_introspection_updates(
3507 IntrospectionType::SourceStatusHistory,
3508 source_status_updates,
3509 );
3510 self.append_status_introspection_updates(
3511 IntrospectionType::SinkStatusHistory,
3512 sink_status_updates,
3513 );
3514 }
3515
3516 fn collection(&self, id: GlobalId) -> Result<&CollectionState, StorageError> {
3517 self.collections
3518 .get(&id)
3519 .ok_or(StorageError::IdentifierMissing(id))
3520 }
3521
3522 fn run_ingestion(&mut self, id: GlobalId) -> Result<(), StorageError> {
3525 tracing::info!(%id, "starting ingestion");
3526
3527 let collection = self.collection(id)?;
3528 let ingestion_description = match &collection.data_source {
3529 DataSource::Ingestion(i) => i.clone(),
3530 _ => {
3531 tracing::warn!("run_ingestion called on non-ingestion ID {}", id);
3532 Err(StorageError::IdentifierInvalid(id))?
3533 }
3534 };
3535
3536 let mut source_exports = BTreeMap::new();
3538 for (export_id, export) in ingestion_description.source_exports.clone() {
3539 let export_storage_metadata = self.collection(export_id)?.collection_metadata.clone();
3540 source_exports.insert(
3541 export_id,
3542 SourceExport {
3543 storage_metadata: export_storage_metadata,
3544 details: export.details,
3545 data_config: export.data_config,
3546 },
3547 );
3548 }
3549
3550 let remap_collection = self.collection(ingestion_description.remap_collection_id)?;
3551
3552 let description = IngestionDescription::<CollectionMetadata> {
3553 source_exports,
3554 remap_metadata: remap_collection.collection_metadata.clone(),
3555 desc: ingestion_description.desc.clone(),
3557 instance_id: ingestion_description.instance_id,
3558 remap_collection_id: ingestion_description.remap_collection_id,
3559 };
3560
3561 let storage_instance_id = description.instance_id;
3562 let instance = self
3564 .instances
3565 .get_mut(&storage_instance_id)
3566 .ok_or_else(|| StorageError::IngestionInstanceMissing {
3567 storage_instance_id,
3568 ingestion_id: id,
3569 })?;
3570
3571 let augmented_ingestion = Box::new(RunIngestionCommand { id, description });
3572 instance.send(StorageCommand::RunIngestion(augmented_ingestion));
3573
3574 Ok(())
3575 }
3576
3577 fn run_export(&mut self, id: GlobalId) -> Result<(), StorageError> {
3580 let DataSource::Sink { desc: description } = &self.collections[&id].data_source else {
3581 return Err(StorageError::IdentifierMissing(id));
3582 };
3583
3584 let from_storage_metadata = self
3585 .storage_collections
3586 .collection_metadata(description.sink.from)?;
3587 let to_storage_metadata = self.storage_collections.collection_metadata(id)?;
3588
3589 let export_state = self.storage_collections.collection_frontiers(id)?;
3593 let mut as_of = description.sink.as_of.clone();
3594 as_of.join_assign(&export_state.implied_capability);
3595 let with_snapshot = description.sink.with_snapshot
3596 && !PartialOrder::less_than(&as_of, &export_state.write_frontier);
3597
3598 info!(
3599 sink_id = %id,
3600 from_id = %description.sink.from,
3601 write_frontier = ?export_state.write_frontier,
3602 ?as_of,
3603 ?with_snapshot,
3604 "run_export"
3605 );
3606
3607 let cmd = RunSinkCommand {
3608 id,
3609 description: StorageSinkDesc {
3610 from: description.sink.from,
3611 from_desc: description.sink.from_desc.clone(),
3612 connection: description.sink.connection.clone(),
3613 envelope: description.sink.envelope,
3614 as_of,
3615 version: description.sink.version,
3616 from_storage_metadata,
3617 with_snapshot,
3618 to_storage_metadata,
3619 commit_interval: description.sink.commit_interval,
3620 },
3621 };
3622
3623 let storage_instance_id = description.instance_id.clone();
3624
3625 let instance = self
3626 .instances
3627 .get_mut(&storage_instance_id)
3628 .ok_or_else(|| StorageError::ExportInstanceMissing {
3629 storage_instance_id,
3630 export_id: id,
3631 })?;
3632
3633 instance.send(StorageCommand::RunSink(Box::new(cmd)));
3634
3635 Ok(())
3636 }
3637
3638 fn update_frontier_introspection(&mut self) {
3643 let mut global_frontiers = BTreeMap::new();
3644 let mut replica_frontiers = BTreeMap::new();
3645
3646 for collection_frontiers in self.storage_collections.active_collection_frontiers() {
3647 let id = collection_frontiers.id;
3648 let since = collection_frontiers.read_capabilities;
3649 let upper = collection_frontiers.write_frontier;
3650
3651 let instance = self
3652 .collections
3653 .get(&id)
3654 .and_then(|collection_state| match &collection_state.extra_state {
3655 CollectionStateExtra::Ingestion(ingestion) => Some(ingestion.instance_id),
3656 CollectionStateExtra::Export(export) => Some(export.cluster_id()),
3657 CollectionStateExtra::None => None,
3658 })
3659 .and_then(|i| self.instances.get(&i));
3660
3661 if let Some(instance) = instance {
3662 for replica_id in instance.replica_ids() {
3663 replica_frontiers.insert((id, replica_id), upper.clone());
3664 }
3665 }
3666
3667 global_frontiers.insert(id, (since, upper));
3668 }
3669
3670 let mut global_updates = Vec::new();
3671 let mut replica_updates = Vec::new();
3672
3673 let mut push_global_update =
3674 |id: GlobalId,
3675 (since, upper): (Antichain<Timestamp>, Antichain<Timestamp>),
3676 diff: Diff| {
3677 let read_frontier = since.into_option().map_or(Datum::Null, |t| t.into());
3678 let write_frontier = upper.into_option().map_or(Datum::Null, |t| t.into());
3679 let row = Row::pack_slice(&[
3680 Datum::String(&id.to_string()),
3681 read_frontier,
3682 write_frontier,
3683 ]);
3684 global_updates.push((row, diff));
3685 };
3686
3687 let mut push_replica_update =
3688 |(id, replica_id): (GlobalId, ReplicaId), upper: Antichain<Timestamp>, diff: Diff| {
3689 let write_frontier = upper.into_option().map_or(Datum::Null, |t| t.into());
3690 let row = Row::pack_slice(&[
3691 Datum::String(&id.to_string()),
3692 Datum::String(&replica_id.to_string()),
3693 write_frontier,
3694 ]);
3695 replica_updates.push((row, diff));
3696 };
3697
3698 let mut old_global_frontiers =
3699 std::mem::replace(&mut self.recorded_frontiers, global_frontiers);
3700 for (&id, new) in &self.recorded_frontiers {
3701 match old_global_frontiers.remove(&id) {
3702 Some(old) if &old != new => {
3703 push_global_update(id, new.clone(), Diff::ONE);
3704 push_global_update(id, old, Diff::MINUS_ONE);
3705 }
3706 Some(_) => (),
3707 None => push_global_update(id, new.clone(), Diff::ONE),
3708 }
3709 }
3710 for (id, old) in old_global_frontiers {
3711 push_global_update(id, old, Diff::MINUS_ONE);
3712 }
3713
3714 let mut old_replica_frontiers =
3715 std::mem::replace(&mut self.recorded_replica_frontiers, replica_frontiers);
3716 for (&key, new) in &self.recorded_replica_frontiers {
3717 match old_replica_frontiers.remove(&key) {
3718 Some(old) if &old != new => {
3719 push_replica_update(key, new.clone(), Diff::ONE);
3720 push_replica_update(key, old, Diff::MINUS_ONE);
3721 }
3722 Some(_) => (),
3723 None => push_replica_update(key, new.clone(), Diff::ONE),
3724 }
3725 }
3726 for (key, old) in old_replica_frontiers {
3727 push_replica_update(key, old, Diff::MINUS_ONE);
3728 }
3729
3730 let id = self.introspection_ids[&IntrospectionType::Frontiers];
3731 self.collection_manager
3732 .differential_append(id, global_updates);
3733
3734 let id = self.introspection_ids[&IntrospectionType::ReplicaFrontiers];
3735 self.collection_manager
3736 .differential_append(id, replica_updates);
3737 }
3738
3739 fn refresh_wallclock_lag(&mut self) {
3758 let now_ms = (self.now)();
3759 let histogram_period =
3760 WallclockLagHistogramPeriod::from_epoch_millis(now_ms, self.config.config_set());
3761
3762 let frontier_lag = |frontier: &Antichain<Timestamp>| match frontier.as_option() {
3763 Some(ts) => (self.wallclock_lag)(*ts),
3764 None => Duration::ZERO,
3765 };
3766
3767 for frontiers in self.storage_collections.active_collection_frontiers() {
3768 let id = frontiers.id;
3769 let Some(collection) = self.collections.get_mut(&id) else {
3770 continue;
3771 };
3772
3773 let collection_unreadable =
3774 PartialOrder::less_equal(&frontiers.write_frontier, &frontiers.read_capabilities);
3775 let lag = if collection_unreadable {
3776 WallclockLag::Undefined
3777 } else {
3778 let lag = frontier_lag(&frontiers.write_frontier);
3779 WallclockLag::Seconds(lag.as_secs())
3780 };
3781
3782 collection.wallclock_lag_max = collection.wallclock_lag_max.max(lag);
3783
3784 let secs = lag.unwrap_seconds_or(u64::MAX);
3787 collection.wallclock_lag_metrics.observe(secs);
3788
3789 if let Some(stash) = &mut collection.wallclock_lag_histogram_stash {
3790 let bucket = lag.map_seconds(|secs| secs.next_power_of_two());
3791
3792 let instance_id = match &collection.extra_state {
3793 CollectionStateExtra::Ingestion(i) => Some(i.instance_id),
3794 CollectionStateExtra::Export(e) => Some(e.cluster_id()),
3795 CollectionStateExtra::None => None,
3796 };
3797 let workload_class = instance_id
3798 .and_then(|id| self.instances.get(&id))
3799 .and_then(|i| i.workload_class.clone());
3800 let labels = match workload_class {
3801 Some(wc) => [("workload_class", wc.clone())].into(),
3802 None => BTreeMap::new(),
3803 };
3804
3805 let key = (histogram_period, bucket, labels);
3806 *stash.entry(key).or_default() += Diff::ONE;
3807 }
3808 }
3809
3810 self.maybe_record_wallclock_lag();
3812 }
3813
3814 fn maybe_record_wallclock_lag(&mut self) {
3822 if self.read_only {
3823 return;
3824 }
3825
3826 let duration_trunc = |datetime: DateTime<_>, interval| {
3827 let td = TimeDelta::from_std(interval).ok()?;
3828 datetime.duration_trunc(td).ok()
3829 };
3830
3831 let interval = WALLCLOCK_LAG_RECORDING_INTERVAL.get(self.config.config_set());
3832 let now_dt = mz_ore::now::to_datetime((self.now)());
3833 let now_trunc = duration_trunc(now_dt, interval).unwrap_or_else(|| {
3834 soft_panic_or_log!("excessive wallclock lag recording interval: {interval:?}");
3835 let default = WALLCLOCK_LAG_RECORDING_INTERVAL.default();
3836 duration_trunc(now_dt, *default).unwrap()
3837 });
3838 if now_trunc <= self.wallclock_lag_last_recorded {
3839 return;
3840 }
3841
3842 let now_ts: CheckedTimestamp<_> = now_trunc.try_into().expect("must fit");
3843
3844 let mut history_updates = Vec::new();
3845 let mut histogram_updates = Vec::new();
3846 let mut row_buf = Row::default();
3847 for frontiers in self.storage_collections.active_collection_frontiers() {
3848 let id = frontiers.id;
3849 let Some(collection) = self.collections.get_mut(&id) else {
3850 continue;
3851 };
3852
3853 let max_lag = std::mem::replace(&mut collection.wallclock_lag_max, WallclockLag::MIN);
3854 let row = Row::pack_slice(&[
3855 Datum::String(&id.to_string()),
3856 Datum::Null,
3857 max_lag.into_interval_datum(),
3858 Datum::TimestampTz(now_ts),
3859 ]);
3860 history_updates.push((row, Diff::ONE));
3861
3862 let Some(stash) = &mut collection.wallclock_lag_histogram_stash else {
3863 continue;
3864 };
3865
3866 for ((period, lag, labels), count) in std::mem::take(stash) {
3867 let mut packer = row_buf.packer();
3868 packer.extend([
3869 Datum::TimestampTz(period.start),
3870 Datum::TimestampTz(period.end),
3871 Datum::String(&id.to_string()),
3872 lag.into_uint64_datum(),
3873 ]);
3874 let labels = labels.iter().map(|(k, v)| (*k, Datum::String(v)));
3875 packer.push_dict(labels);
3876
3877 histogram_updates.push((row_buf.clone(), count));
3878 }
3879 }
3880
3881 if !history_updates.is_empty() {
3882 self.append_introspection_updates(
3883 IntrospectionType::WallclockLagHistory,
3884 history_updates,
3885 );
3886 }
3887 if !histogram_updates.is_empty() {
3888 self.append_introspection_updates(
3889 IntrospectionType::WallclockLagHistogram,
3890 histogram_updates,
3891 );
3892 }
3893
3894 self.wallclock_lag_last_recorded = now_trunc;
3895 }
3896
3897 fn maintain(&mut self) {
3902 self.update_frontier_introspection();
3903 self.refresh_wallclock_lag();
3904
3905 for instance in self.instances.values_mut() {
3907 instance.refresh_state_metrics();
3908 }
3909 }
3910}
3911
3912impl From<&IntrospectionType> for CollectionManagerKind {
3913 fn from(value: &IntrospectionType) -> Self {
3914 match value {
3915 IntrospectionType::ShardMapping
3916 | IntrospectionType::Frontiers
3917 | IntrospectionType::ReplicaFrontiers
3918 | IntrospectionType::StorageSourceStatistics
3919 | IntrospectionType::StorageSinkStatistics
3920 | IntrospectionType::ComputeDependencies
3921 | IntrospectionType::ComputeOperatorHydrationStatus
3922 | IntrospectionType::ComputeMaterializedViewRefreshes
3923 | IntrospectionType::ComputeErrorCounts
3924 | IntrospectionType::ComputeHydrationTimes
3925 | IntrospectionType::ComputeObjectArrangementSizes => {
3926 CollectionManagerKind::Differential
3927 }
3928
3929 IntrospectionType::SourceStatusHistory
3930 | IntrospectionType::SinkStatusHistory
3931 | IntrospectionType::PrivatelinkConnectionStatusHistory
3932 | IntrospectionType::ReplicaStatusHistory
3933 | IntrospectionType::ReplicaMetricsHistory
3934 | IntrospectionType::WallclockLagHistory
3935 | IntrospectionType::WallclockLagHistogram
3936 | IntrospectionType::PreparedStatementHistory
3937 | IntrospectionType::StatementExecutionHistory
3938 | IntrospectionType::SessionHistory
3939 | IntrospectionType::StatementLifecycleHistory
3940 | IntrospectionType::SqlText => CollectionManagerKind::AppendOnly,
3941 }
3942 }
3943}
3944
3945async fn snapshot_statistics(
3951 id: GlobalId,
3952 upper: Antichain<Timestamp>,
3953 storage_collections: &Arc<dyn StorageCollections + Send + Sync>,
3954) -> Vec<Row> {
3955 match upper.as_option() {
3956 Some(f) if f > &Timestamp::MIN => {
3957 let as_of = f.step_back().unwrap();
3958
3959 let snapshot = storage_collections.snapshot(id, as_of).await.unwrap();
3960 snapshot
3961 .into_iter()
3962 .map(|(row, diff)| {
3963 assert_eq!(diff, 1);
3964 row
3965 })
3966 .collect()
3967 }
3968 _ => Vec::new(),
3971 }
3972}
3973
3974async fn read_handle_for_snapshot(
3975 persist: &PersistClientCache,
3976 id: GlobalId,
3977 metadata: &CollectionMetadata,
3978) -> Result<ReadHandle<SourceData, (), Timestamp, StorageDiff>, StorageError> {
3979 let persist_client = persist
3980 .open(metadata.persist_location.clone())
3981 .await
3982 .unwrap();
3983
3984 let read_handle = persist_client
3989 .open_leased_reader::<SourceData, (), _, _>(
3990 metadata.data_shard,
3991 Arc::new(metadata.relation_desc.clone()),
3992 Arc::new(UnitSchema),
3993 Diagnostics {
3994 shard_name: id.to_string(),
3995 handle_purpose: format!("snapshot {}", id),
3996 },
3997 USE_CRITICAL_SINCE_SNAPSHOT.get(persist_client.dyncfgs()),
3998 )
3999 .await
4000 .expect("invalid persist usage");
4001 Ok(read_handle)
4002}
4003
4004#[derive(Debug)]
4006struct CollectionState {
4007 pub data_source: DataSource,
4009
4010 pub collection_metadata: CollectionMetadata,
4011
4012 pub extra_state: CollectionStateExtra,
4013
4014 wallclock_lag_max: WallclockLag,
4016 wallclock_lag_histogram_stash: Option<
4023 BTreeMap<
4024 (
4025 WallclockLagHistogramPeriod,
4026 WallclockLag,
4027 BTreeMap<&'static str, String>,
4028 ),
4029 Diff,
4030 >,
4031 >,
4032 wallclock_lag_metrics: WallclockLagMetrics,
4034}
4035
4036impl CollectionState {
4037 fn new(
4038 data_source: DataSource,
4039 collection_metadata: CollectionMetadata,
4040 extra_state: CollectionStateExtra,
4041 wallclock_lag_metrics: WallclockLagMetrics,
4042 ) -> Self {
4043 let wallclock_lag_histogram_stash = match &data_source {
4047 DataSource::Other => None,
4048 _ => Some(Default::default()),
4049 };
4050
4051 Self {
4052 data_source,
4053 collection_metadata,
4054 extra_state,
4055 wallclock_lag_max: WallclockLag::MIN,
4056 wallclock_lag_histogram_stash,
4057 wallclock_lag_metrics,
4058 }
4059 }
4060}
4061
4062#[derive(Debug)]
4064enum CollectionStateExtra {
4065 Ingestion(IngestionState),
4066 Export(ExportState),
4067 None,
4068}
4069
4070#[derive(Debug)]
4072struct IngestionState {
4073 pub read_capabilities: MutableAntichain<Timestamp>,
4075
4076 pub derived_since: Antichain<Timestamp>,
4079
4080 pub dependency_read_holds: Vec<ReadHold>,
4082
4083 pub write_frontier: Antichain<Timestamp>,
4085
4086 pub hold_policy: ReadPolicy,
4093
4094 pub instance_id: StorageInstanceId,
4096
4097 pub hydrated_on: BTreeSet<ReplicaId>,
4099}
4100
4101struct StatusHistoryDesc<K> {
4106 retention_policy: StatusHistoryRetentionPolicy,
4107 extract_key: Box<dyn Fn(&[Datum]) -> K + Send>,
4108 extract_time: Box<dyn Fn(&[Datum]) -> CheckedTimestamp<DateTime<Utc>> + Send>,
4109}
4110enum StatusHistoryRetentionPolicy {
4111 LastN(usize),
4113 TimeWindow(Duration),
4115}
4116
4117fn source_status_history_desc(
4118 params: &StorageParameters,
4119) -> StatusHistoryDesc<(GlobalId, Option<ReplicaId>)> {
4120 let desc = &MZ_SOURCE_STATUS_HISTORY_DESC;
4121 let (source_id_idx, _) = desc.get_by_name(&"source_id".into()).expect("exists");
4122 let (replica_id_idx, _) = desc.get_by_name(&"replica_id".into()).expect("exists");
4123 let (time_idx, _) = desc.get_by_name(&"occurred_at".into()).expect("exists");
4124
4125 StatusHistoryDesc {
4126 retention_policy: StatusHistoryRetentionPolicy::LastN(
4127 params.keep_n_source_status_history_entries,
4128 ),
4129 extract_key: Box::new(move |datums| {
4130 (
4131 GlobalId::from_str(datums[source_id_idx].unwrap_str()).expect("GlobalId column"),
4132 if datums[replica_id_idx].is_null() {
4133 None
4134 } else {
4135 Some(
4136 ReplicaId::from_str(datums[replica_id_idx].unwrap_str())
4137 .expect("ReplicaId column"),
4138 )
4139 },
4140 )
4141 }),
4142 extract_time: Box::new(move |datums| datums[time_idx].unwrap_timestamptz()),
4143 }
4144}
4145
4146fn sink_status_history_desc(
4147 params: &StorageParameters,
4148) -> StatusHistoryDesc<(GlobalId, Option<ReplicaId>)> {
4149 let desc = &MZ_SINK_STATUS_HISTORY_DESC;
4150 let (sink_id_idx, _) = desc.get_by_name(&"sink_id".into()).expect("exists");
4151 let (replica_id_idx, _) = desc.get_by_name(&"replica_id".into()).expect("exists");
4152 let (time_idx, _) = desc.get_by_name(&"occurred_at".into()).expect("exists");
4153
4154 StatusHistoryDesc {
4155 retention_policy: StatusHistoryRetentionPolicy::LastN(
4156 params.keep_n_sink_status_history_entries,
4157 ),
4158 extract_key: Box::new(move |datums| {
4159 (
4160 GlobalId::from_str(datums[sink_id_idx].unwrap_str()).expect("GlobalId column"),
4161 if datums[replica_id_idx].is_null() {
4162 None
4163 } else {
4164 Some(
4165 ReplicaId::from_str(datums[replica_id_idx].unwrap_str())
4166 .expect("ReplicaId column"),
4167 )
4168 },
4169 )
4170 }),
4171 extract_time: Box::new(move |datums| datums[time_idx].unwrap_timestamptz()),
4172 }
4173}
4174
4175fn privatelink_status_history_desc(params: &StorageParameters) -> StatusHistoryDesc<GlobalId> {
4176 let desc = &MZ_AWS_PRIVATELINK_CONNECTION_STATUS_HISTORY_DESC;
4177 let (key_idx, _) = desc.get_by_name(&"connection_id".into()).expect("exists");
4178 let (time_idx, _) = desc.get_by_name(&"occurred_at".into()).expect("exists");
4179
4180 StatusHistoryDesc {
4181 retention_policy: StatusHistoryRetentionPolicy::LastN(
4182 params.keep_n_privatelink_status_history_entries,
4183 ),
4184 extract_key: Box::new(move |datums| {
4185 GlobalId::from_str(datums[key_idx].unwrap_str()).expect("GlobalId column")
4186 }),
4187 extract_time: Box::new(move |datums| datums[time_idx].unwrap_timestamptz()),
4188 }
4189}
4190
4191fn replica_status_history_desc(params: &StorageParameters) -> StatusHistoryDesc<(GlobalId, u64)> {
4192 let desc = &REPLICA_STATUS_HISTORY_DESC;
4193 let (replica_idx, _) = desc.get_by_name(&"replica_id".into()).expect("exists");
4194 let (process_idx, _) = desc.get_by_name(&"process_id".into()).expect("exists");
4195 let (time_idx, _) = desc.get_by_name(&"occurred_at".into()).expect("exists");
4196
4197 StatusHistoryDesc {
4198 retention_policy: StatusHistoryRetentionPolicy::TimeWindow(
4199 params.replica_status_history_retention_window,
4200 ),
4201 extract_key: Box::new(move |datums| {
4202 (
4203 GlobalId::from_str(datums[replica_idx].unwrap_str()).expect("GlobalId column"),
4204 datums[process_idx].unwrap_uint64(),
4205 )
4206 }),
4207 extract_time: Box::new(move |datums| datums[time_idx].unwrap_timestamptz()),
4208 }
4209}
4210
4211fn swap_updates(
4213 from: &mut Antichain<Timestamp>,
4214 mut replace_with: Antichain<Timestamp>,
4215) -> ChangeBatch<Timestamp> {
4216 let mut update = ChangeBatch::new();
4217 if PartialOrder::less_equal(from, &replace_with) {
4218 update.extend(replace_with.iter().map(|time| (*time, 1)));
4219 std::mem::swap(from, &mut replace_with);
4220 update.extend(replace_with.iter().map(|time| (*time, -1)));
4221 }
4222 update
4223}