1use std::cmp::Reverse;
13use std::collections::{BTreeMap, BTreeSet};
14use std::fmt::Debug;
15use std::iter;
16use std::num::NonZeroI64;
17use std::sync::{Arc, Mutex};
18use std::time::Duration;
19
20use async_trait::async_trait;
21use differential_dataflow::lattice::Lattice;
22use futures::future::BoxFuture;
23use futures::stream::{BoxStream, FuturesUnordered};
24use futures::{Future, FutureExt, StreamExt};
25use itertools::Itertools;
26use mz_ore::collections::CollectionExt;
27use mz_ore::metrics::MetricsRegistry;
28use mz_ore::now::NowFn;
29use mz_ore::task::AbortOnDropHandle;
30use mz_ore::{assert_none, instrument, soft_assert_or_log};
31use mz_persist_client::cache::PersistClientCache;
32use mz_persist_client::cfg::USE_CRITICAL_SINCE_SNAPSHOT;
33use mz_persist_client::critical::{Opaque, SinceHandle};
34use mz_persist_client::read::{Cursor, ReadHandle};
35use mz_persist_client::schema::CaESchema;
36use mz_persist_client::stats::{SnapshotPartsStats, SnapshotStats};
37use mz_persist_client::write::WriteHandle;
38use mz_persist_client::{Diagnostics, PersistClient, PersistLocation, ShardId};
39use mz_persist_types::codec_impls::UnitSchema;
40use mz_persist_types::txn::TxnsCodec;
41use mz_repr::{GlobalId, RelationDesc, RelationVersion, Row, Timestamp};
42use mz_storage_types::StorageDiff;
43use mz_storage_types::configuration::StorageConfiguration;
44use mz_storage_types::connections::ConnectionContext;
45use mz_storage_types::controller::{CollectionMetadata, StorageError, TxnsCodecRow};
46use mz_storage_types::dyncfgs::STORAGE_DOWNGRADE_SINCE_DURING_FINALIZATION;
47use mz_storage_types::errors::CollectionMissing;
48use mz_storage_types::parameters::StorageParameters;
49use mz_storage_types::read_holds::ReadHold;
50use mz_storage_types::read_policy::ReadPolicy;
51use mz_storage_types::sources::{GenericSourceConnection, SourceData, SourceEnvelope, Timeline};
52use mz_storage_types::time_dependence::{TimeDependence, TimeDependenceError};
53use mz_txn_wal::metrics::Metrics as TxnMetrics;
54use mz_txn_wal::txn_read::{DataSnapshot, TxnsRead};
55use mz_txn_wal::txns::TxnsHandle;
56use timely::PartialOrder;
57use timely::progress::frontier::MutableAntichain;
58use timely::progress::{Antichain, ChangeBatch};
59use tokio::sync::{mpsc, oneshot};
60use tokio::time::MissedTickBehavior;
61use tracing::{debug, info, trace, warn};
62
63use crate::client::TimestamplessUpdateBuilder;
64use crate::controller::{
65 CollectionDescription, DataSource, PersistEpoch, StorageMetadata, StorageTxn,
66};
67use crate::storage_collections::metrics::{ShardIdSet, StorageCollectionsMetrics};
68
69mod metrics;
70
71#[async_trait]
85pub trait StorageCollections: Debug + Sync {
86 async fn initialize_state(
93 &self,
94 txn: &mut (dyn StorageTxn + Send),
95 init_ids: BTreeSet<GlobalId>,
96 ) -> Result<(), StorageError>;
97
98 fn update_parameters(&self, config_params: StorageParameters);
100
101 fn collection_metadata(&self, id: GlobalId) -> Result<CollectionMetadata, CollectionMissing>;
103
104 fn active_collection_metadatas(&self) -> Vec<(GlobalId, CollectionMetadata)>;
110
111 fn collection_frontiers(&self, id: GlobalId) -> Result<CollectionFrontiers, CollectionMissing> {
113 let frontiers = self
114 .collections_frontiers(vec![id])?
115 .expect_element(|| "known to exist");
116
117 Ok(frontiers)
118 }
119
120 fn collections_frontiers(
123 &self,
124 id: Vec<GlobalId>,
125 ) -> Result<Vec<CollectionFrontiers>, CollectionMissing>;
126
127 fn active_collection_frontiers(&self) -> Vec<CollectionFrontiers>;
132
133 fn check_exists(&self, id: GlobalId) -> Result<(), StorageError>;
136
137 async fn snapshot_stats(
140 &self,
141 id: GlobalId,
142 as_of: Antichain<Timestamp>,
143 ) -> Result<SnapshotStats, StorageError>;
144
145 async fn snapshot_parts_stats(
154 &self,
155 id: GlobalId,
156 as_of: Antichain<Timestamp>,
157 ) -> BoxFuture<'static, Result<SnapshotPartsStats, StorageError>>;
158
159 fn snapshot(
161 &self,
162 id: GlobalId,
163 as_of: Timestamp,
164 ) -> BoxFuture<'static, Result<Vec<(Row, StorageDiff)>, StorageError>>;
165
166 async fn snapshot_latest(&self, id: GlobalId) -> Result<Vec<Row>, StorageError>;
181
182 fn snapshot_cursor(
184 &self,
185 id: GlobalId,
186 as_of: Timestamp,
187 ) -> BoxFuture<'static, Result<SnapshotCursor, StorageError>>;
188
189 fn snapshot_and_stream(
194 &self,
195 id: GlobalId,
196 as_of: Timestamp,
197 ) -> BoxFuture<
198 'static,
199 Result<BoxStream<'static, (SourceData, Timestamp, StorageDiff)>, StorageError>,
200 >;
201
202 fn create_update_builder(
205 &self,
206 id: GlobalId,
207 ) -> BoxFuture<
208 'static,
209 Result<TimestamplessUpdateBuilder<SourceData, (), StorageDiff>, StorageError>,
210 >;
211
212 async fn prepare_state(
218 &self,
219 txn: &mut (dyn StorageTxn + Send),
220 ids_to_add: BTreeSet<GlobalId>,
221 ids_to_drop: BTreeSet<GlobalId>,
222 ids_to_register: BTreeMap<GlobalId, ShardId>,
223 ) -> Result<(), StorageError>;
224
225 async fn create_collections_for_bootstrap(
251 &self,
252 storage_metadata: &StorageMetadata,
253 register_ts: Option<Timestamp>,
254 collections: Vec<(GlobalId, CollectionDescription)>,
255 migrated_storage_collections: &BTreeSet<GlobalId>,
256 ) -> Result<(), StorageError>;
257
258 async fn alter_table_desc(
260 &self,
261 existing_collection: GlobalId,
262 new_collection: GlobalId,
263 new_desc: RelationDesc,
264 expected_version: RelationVersion,
265 ) -> Result<(), StorageError>;
266
267 fn drop_collections_unvalidated(
279 &self,
280 storage_metadata: &StorageMetadata,
281 identifiers: Vec<GlobalId>,
282 );
283
284 fn set_read_policies(&self, policies: Vec<(GlobalId, ReadPolicy)>);
298
299 fn acquire_read_holds(
302 &self,
303 desired_holds: Vec<GlobalId>,
304 ) -> Result<Vec<ReadHold>, CollectionMissing>;
305
306 fn determine_time_dependence(
309 &self,
310 id: GlobalId,
311 ) -> Result<Option<TimeDependence>, TimeDependenceError>;
312
313 fn dump(&self) -> Result<serde_json::Value, anyhow::Error>;
315}
316
317pub struct SnapshotCursor {
320 pub _read_handle: ReadHandle<SourceData, (), Timestamp, StorageDiff>,
323 pub cursor: Cursor<SourceData, (), Timestamp, StorageDiff>,
324}
325
326impl SnapshotCursor {
327 pub async fn next(
328 &mut self,
329 ) -> Option<impl Iterator<Item = (SourceData, Timestamp, StorageDiff)> + Sized + '_> {
330 let iter = self.cursor.next().await?;
331 Some(iter.map(|((k, ()), t, d)| (k, t, d)))
332 }
333}
334
335#[derive(Debug)]
337pub struct CollectionFrontiers {
338 pub id: GlobalId,
340
341 pub write_frontier: Antichain<Timestamp>,
343
344 pub implied_capability: Antichain<Timestamp>,
351
352 pub read_capabilities: Antichain<Timestamp>,
355}
356
357#[derive(Debug, Clone)]
360pub struct StorageCollectionsImpl {
361 envd_epoch: NonZeroI64,
364
365 read_only: bool,
371
372 finalizable_shards: Arc<ShardIdSet>,
375
376 finalized_shards: Arc<ShardIdSet>,
381
382 collections: Arc<std::sync::Mutex<BTreeMap<GlobalId, CollectionState>>>,
384
385 txns_read: TxnsRead<Timestamp>,
387
388 config: Arc<Mutex<StorageConfiguration>>,
390
391 initial_txn_upper: Antichain<Timestamp>,
400
401 persist_location: PersistLocation,
403
404 persist: Arc<PersistClientCache>,
406
407 cmd_tx: mpsc::UnboundedSender<BackgroundCmd>,
409
410 holds_tx: mpsc::UnboundedSender<(GlobalId, ChangeBatch<Timestamp>)>,
412
413 _background_task: Arc<AbortOnDropHandle<()>>,
415 _finalize_shards_task: Arc<AbortOnDropHandle<()>>,
416}
417
418type SourceDataStream = BoxStream<'static, (SourceData, Timestamp, StorageDiff)>;
427
428impl StorageCollectionsImpl {
431 pub async fn new(
439 persist_location: PersistLocation,
440 persist_clients: Arc<PersistClientCache>,
441 metrics_registry: &MetricsRegistry,
442 _now: NowFn,
443 txns_metrics: Arc<TxnMetrics>,
444 envd_epoch: NonZeroI64,
445 read_only: bool,
446 connection_context: ConnectionContext,
447 txn: &dyn StorageTxn,
448 ) -> Self {
449 let metrics = StorageCollectionsMetrics::register_into(metrics_registry);
450
451 let txns_id = txn
455 .get_txn_wal_shard()
456 .expect("must call prepare initialization before creating StorageCollections");
457
458 let txns_client = persist_clients
459 .open(persist_location.clone())
460 .await
461 .expect("location should be valid");
462
463 let _txns_handle: TxnsHandle<SourceData, (), Timestamp, StorageDiff, TxnsCodecRow> =
466 TxnsHandle::open(
467 Timestamp::MIN,
468 txns_client.clone(),
469 txns_client.dyncfgs().clone(),
470 Arc::clone(&txns_metrics),
471 txns_id,
472 Opaque::encode(&PersistEpoch::default()),
473 )
474 .await;
475
476 let (txns_key_schema, txns_val_schema) = TxnsCodecRow::schemas();
478 let mut txns_write = txns_client
479 .open_writer(
480 txns_id,
481 Arc::new(txns_key_schema),
482 Arc::new(txns_val_schema),
483 Diagnostics {
484 shard_name: "txns".to_owned(),
485 handle_purpose: "commit txns".to_owned(),
486 },
487 )
488 .await
489 .expect("txns schema shouldn't change");
490
491 let txns_read = TxnsRead::start::<TxnsCodecRow>(txns_client.clone(), txns_id).await;
492
493 let collections = Arc::new(std::sync::Mutex::new(BTreeMap::default()));
494 let finalizable_shards = Arc::new(ShardIdSet::new(if read_only {
495 mz_ore::metrics::UIntGauge::new(
501 "finalizable_shards",
502 "read-only env can't finalize shards. don't publish this gauge.",
503 )
504 .unwrap()
505 } else {
506 metrics.finalization_outstanding.clone()
507 }));
508 let finalized_shards =
509 Arc::new(ShardIdSet::new(metrics.finalization_pending_commit.clone()));
510 let config = Arc::new(Mutex::new(StorageConfiguration::new(
511 connection_context,
512 mz_dyncfgs::all_dyncfgs(),
513 )));
514
515 let initial_txn_upper = txns_write.fetch_recent_upper().await.to_owned();
516
517 let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
518 let (holds_tx, holds_rx) = mpsc::unbounded_channel();
519 let mut background_task = BackgroundTask {
520 config: Arc::clone(&config),
521 cmds_tx: cmd_tx.clone(),
522 cmds_rx: cmd_rx,
523 holds_rx,
524 collections: Arc::clone(&collections),
525 finalizable_shards: Arc::clone(&finalizable_shards),
526 shard_by_id: BTreeMap::new(),
527 since_handles: BTreeMap::new(),
528 txns_handle: Some(txns_write),
529 txns_shards: Default::default(),
530 };
531
532 let background_task =
533 mz_ore::task::spawn(|| "storage_collections::background_task", async move {
534 background_task.run().await
535 });
536
537 let finalize_shards_task = mz_ore::task::spawn(
538 || "storage_collections::finalize_shards_task",
539 finalize_shards_task(FinalizeShardsTaskConfig {
540 envd_epoch: envd_epoch.clone(),
541 config: Arc::clone(&config),
542 metrics,
543 finalizable_shards: Arc::clone(&finalizable_shards),
544 finalized_shards: Arc::clone(&finalized_shards),
545 persist_location: persist_location.clone(),
546 persist: Arc::clone(&persist_clients),
547 read_only,
548 }),
549 );
550
551 Self {
552 finalizable_shards,
553 finalized_shards,
554 collections,
555 txns_read,
556 envd_epoch,
557 read_only,
558 config,
559 initial_txn_upper,
560 persist_location,
561 persist: persist_clients,
562 cmd_tx,
563 holds_tx,
564 _background_task: Arc::new(background_task.abort_on_drop()),
565 _finalize_shards_task: Arc::new(finalize_shards_task.abort_on_drop()),
566 }
567 }
568
569 async fn open_data_handles(
577 &self,
578 id: &GlobalId,
579 shard: ShardId,
580 since: Option<&Antichain<Timestamp>>,
581 relation_desc: RelationDesc,
582 persist_client: &PersistClient,
583 ) -> (
584 WriteHandle<SourceData, (), Timestamp, StorageDiff>,
585 SinceHandleWrapper,
586 ) {
587 let since_handle = if self.read_only {
588 let read_handle = self
589 .open_leased_handle(id, shard, relation_desc.clone(), since, persist_client)
590 .await;
591 SinceHandleWrapper::Leased(read_handle)
592 } else {
593 persist_client
596 .upgrade_version::<SourceData, (), Timestamp, StorageDiff>(
597 shard,
598 Diagnostics {
599 shard_name: id.to_string(),
600 handle_purpose: format!("controller data for {}", id),
601 },
602 )
603 .await
604 .expect("invalid persist usage");
605
606 let since_handle = self
607 .open_critical_handle(id, shard, since, persist_client)
608 .await;
609
610 SinceHandleWrapper::Critical(since_handle)
611 };
612
613 let mut write_handle = self
614 .open_write_handle(id, shard, relation_desc, persist_client)
615 .await;
616
617 write_handle.fetch_recent_upper().await;
628
629 (write_handle, since_handle)
630 }
631
632 async fn open_write_handle(
634 &self,
635 id: &GlobalId,
636 shard: ShardId,
637 relation_desc: RelationDesc,
638 persist_client: &PersistClient,
639 ) -> WriteHandle<SourceData, (), Timestamp, StorageDiff> {
640 let diagnostics = Diagnostics {
641 shard_name: id.to_string(),
642 handle_purpose: format!("controller data for {}", id),
643 };
644
645 let write = persist_client
646 .open_writer(
647 shard,
648 Arc::new(relation_desc),
649 Arc::new(UnitSchema),
650 diagnostics.clone(),
651 )
652 .await
653 .expect("invalid persist usage");
654
655 write
656 }
657
658 async fn open_critical_handle(
666 &self,
667 id: &GlobalId,
668 shard: ShardId,
669 since: Option<&Antichain<Timestamp>>,
670 persist_client: &PersistClient,
671 ) -> SinceHandle<SourceData, (), Timestamp, StorageDiff> {
672 tracing::debug!(%id, ?since, "opening critical handle");
673
674 assert!(
675 !self.read_only,
676 "attempting to open critical SinceHandle in read-only mode"
677 );
678
679 let diagnostics = Diagnostics {
680 shard_name: id.to_string(),
681 handle_purpose: format!("controller data for {}", id),
682 };
683
684 let since_handle = {
687 let mut handle = persist_client
690 .open_critical_since(
691 shard,
692 PersistClient::CONTROLLER_CRITICAL_SINCE,
693 Opaque::encode(&PersistEpoch::default()),
694 diagnostics.clone(),
695 )
696 .await
697 .expect("invalid persist usage");
698
699 let provided_since = match since {
703 Some(since) => since,
704 None => &Antichain::from_elem(Timestamp::MIN),
705 };
706 let since = handle.since().join(provided_since);
707
708 let our_epoch = self.envd_epoch;
709
710 loop {
711 let current_epoch: PersistEpoch = handle.opaque().decode();
712
713 let unchecked_success = current_epoch.0.map(|e| e <= our_epoch).unwrap_or(true);
715
716 if unchecked_success {
717 let checked_success = handle
720 .compare_and_downgrade_since(
721 &Opaque::encode(¤t_epoch),
722 (&Opaque::encode(&PersistEpoch::from(our_epoch)), &since),
723 )
724 .await
725 .is_ok();
726 if checked_success {
727 break handle;
728 }
729 } else {
730 mz_ore::halt!("fenced by envd @ {current_epoch:?}. ours = {our_epoch}");
731 }
732 }
733 };
734
735 since_handle
736 }
737
738 async fn open_leased_handle(
744 &self,
745 id: &GlobalId,
746 shard: ShardId,
747 relation_desc: RelationDesc,
748 since: Option<&Antichain<Timestamp>>,
749 persist_client: &PersistClient,
750 ) -> ReadHandle<SourceData, (), Timestamp, StorageDiff> {
751 tracing::debug!(%id, ?since, "opening leased handle");
752
753 let diagnostics = Diagnostics {
754 shard_name: id.to_string(),
755 handle_purpose: format!("controller data for {}", id),
756 };
757
758 let use_critical_since = false;
759 let mut handle: ReadHandle<_, _, _, _> = persist_client
760 .open_leased_reader(
761 shard,
762 Arc::new(relation_desc),
763 Arc::new(UnitSchema),
764 diagnostics.clone(),
765 use_critical_since,
766 )
767 .await
768 .expect("invalid persist usage");
769
770 let provided_since = match since {
774 Some(since) => since,
775 None => &Antichain::from_elem(Timestamp::MIN),
776 };
777 let since = handle.since().join(provided_since);
778
779 handle.downgrade_since(&since).await;
780
781 handle
782 }
783
784 fn register_handles(
785 &self,
786 id: GlobalId,
787 is_in_txns: bool,
788 since_handle: SinceHandleWrapper,
789 write_handle: WriteHandle<SourceData, (), Timestamp, StorageDiff>,
790 ) {
791 self.send(BackgroundCmd::Register {
792 id,
793 is_in_txns,
794 since_handle,
795 write_handle,
796 });
797 }
798
799 fn send(&self, cmd: BackgroundCmd) {
800 let _ = self.cmd_tx.send(cmd);
801 }
802
803 async fn snapshot_stats_inner(
804 &self,
805 id: GlobalId,
806 as_of: SnapshotStatsAsOf,
807 ) -> Result<SnapshotStats, StorageError> {
808 let (tx, rx) = oneshot::channel();
815 self.send(BackgroundCmd::SnapshotStats(id, as_of, tx));
816 rx.await.expect("BackgroundTask should be live").0.await
817 }
818
819 fn install_collection_dependency_read_holds_inner(
825 &self,
826 self_collections: &mut BTreeMap<GlobalId, CollectionState>,
827 id: GlobalId,
828 ) -> Result<(), StorageError> {
829 let (deps, collection_implied_capability) = match self_collections.get(&id) {
830 Some(CollectionState {
831 storage_dependencies: deps,
832 implied_capability,
833 ..
834 }) => (deps.clone(), implied_capability),
835 _ => return Ok(()),
836 };
837
838 for dep in deps.iter() {
839 let dep_collection = self_collections
840 .get(dep)
841 .ok_or(StorageError::IdentifierMissing(id))?;
842
843 mz_ore::soft_assert_or_log!(
844 PartialOrder::less_equal(
845 &dep_collection.implied_capability,
846 collection_implied_capability
847 ),
848 "dependency since ({dep}@{:?}) cannot be in advance of dependent's since ({id}@{:?})",
849 dep_collection.implied_capability,
850 collection_implied_capability,
851 );
852 }
853
854 self.install_read_capabilities_inner(
855 self_collections,
856 id,
857 &deps,
858 collection_implied_capability.clone(),
859 )?;
860
861 Ok(())
862 }
863
864 fn determine_collection_dependencies(
866 self_collections: &BTreeMap<GlobalId, CollectionState>,
867 source_id: GlobalId,
868 collection_desc: &CollectionDescription,
869 ) -> Result<Vec<GlobalId>, StorageError> {
870 let mut dependencies = Vec::new();
871
872 if let Some(id) = collection_desc.primary {
873 dependencies.push(id);
874 }
875
876 match &collection_desc.data_source {
877 DataSource::Introspection(_)
878 | DataSource::Webhook
879 | DataSource::Table
880 | DataSource::Progress
881 | DataSource::Other => (),
882 DataSource::IngestionExport {
883 ingestion_id,
884 data_config,
885 ..
886 } => {
887 let source = self_collections
890 .get(ingestion_id)
891 .ok_or(StorageError::IdentifierMissing(*ingestion_id))?;
892 let Some(remap_collection_id) = &source.ingestion_remap_collection_id else {
893 panic!("SourceExport must refer to a primary source that already exists");
894 };
895
896 match data_config.envelope {
897 SourceEnvelope::CdcV2 => (),
898 _ => dependencies.push(*remap_collection_id),
899 }
900 }
901 DataSource::Ingestion(ingestion) => {
903 if ingestion.remap_collection_id != source_id {
904 dependencies.push(ingestion.remap_collection_id);
905 }
906 }
907 DataSource::Sink { desc } => dependencies.push(desc.sink.from),
908 }
909
910 Ok(dependencies)
911 }
912
913 #[instrument(level = "debug")]
915 fn install_read_capabilities_inner(
916 &self,
917 self_collections: &mut BTreeMap<GlobalId, CollectionState>,
918 from_id: GlobalId,
919 storage_dependencies: &[GlobalId],
920 read_capability: Antichain<Timestamp>,
921 ) -> Result<(), StorageError> {
922 let mut changes = ChangeBatch::new();
923 for time in read_capability.iter() {
924 changes.update(*time, 1);
925 }
926
927 if tracing::span_enabled!(tracing::Level::TRACE) {
928 let user_capabilities = self_collections
930 .iter_mut()
931 .filter(|(id, _c)| id.is_user())
932 .map(|(id, c)| {
933 let updates = c.read_capabilities.updates().cloned().collect_vec();
934 (*id, c.implied_capability.clone(), updates)
935 })
936 .collect_vec();
937
938 trace!(
939 %from_id,
940 ?storage_dependencies,
941 ?read_capability,
942 ?user_capabilities,
943 "install_read_capabilities_inner");
944 }
945
946 let mut storage_read_updates = storage_dependencies
947 .iter()
948 .map(|id| (*id, changes.clone()))
949 .collect();
950
951 StorageCollectionsImpl::update_read_capabilities_inner(
952 &self.cmd_tx,
953 self_collections,
954 &mut storage_read_updates,
955 );
956
957 if tracing::span_enabled!(tracing::Level::TRACE) {
958 let user_capabilities = self_collections
960 .iter_mut()
961 .filter(|(id, _c)| id.is_user())
962 .map(|(id, c)| {
963 let updates = c.read_capabilities.updates().cloned().collect_vec();
964 (*id, c.implied_capability.clone(), updates)
965 })
966 .collect_vec();
967
968 trace!(
969 %from_id,
970 ?storage_dependencies,
971 ?read_capability,
972 ?user_capabilities,
973 "after install_read_capabilities_inner!");
974 }
975
976 Ok(())
977 }
978
979 async fn recent_upper(&self, id: GlobalId) -> Result<Antichain<Timestamp>, StorageError> {
980 let metadata = &self.collection_metadata(id)?;
981 let persist_client = self
982 .persist
983 .open(metadata.persist_location.clone())
984 .await
985 .unwrap();
986 let diagnostics = Diagnostics {
989 shard_name: id.to_string(),
990 handle_purpose: format!("controller data for {}", id),
991 };
992 let write = persist_client
995 .open_writer::<SourceData, (), Timestamp, StorageDiff>(
996 metadata.data_shard,
997 Arc::new(metadata.relation_desc.clone()),
998 Arc::new(UnitSchema),
999 diagnostics.clone(),
1000 )
1001 .await
1002 .expect("invalid persist usage");
1003 Ok(write.shared_upper())
1004 }
1005
1006 async fn read_handle_for_snapshot(
1007 persist: Arc<PersistClientCache>,
1008 metadata: &CollectionMetadata,
1009 id: GlobalId,
1010 ) -> Result<ReadHandle<SourceData, (), Timestamp, StorageDiff>, StorageError> {
1011 let persist_client = persist
1012 .open(metadata.persist_location.clone())
1013 .await
1014 .unwrap();
1015
1016 let read_handle = persist_client
1022 .open_leased_reader::<SourceData, (), _, _>(
1023 metadata.data_shard,
1024 Arc::new(metadata.relation_desc.clone()),
1025 Arc::new(UnitSchema),
1026 Diagnostics {
1027 shard_name: id.to_string(),
1028 handle_purpose: format!("snapshot {}", id),
1029 },
1030 USE_CRITICAL_SINCE_SNAPSHOT.get(&persist.cfg),
1031 )
1032 .await
1033 .expect("invalid persist usage");
1034 Ok(read_handle)
1035 }
1036
1037 fn snapshot(
1038 &self,
1039 id: GlobalId,
1040 as_of: Timestamp,
1041 txns_read: &TxnsRead<Timestamp>,
1042 ) -> BoxFuture<'static, Result<Vec<(Row, StorageDiff)>, StorageError>> {
1043 let metadata = match self.collection_metadata(id) {
1044 Ok(metadata) => metadata.clone(),
1045 Err(e) => return async { Err(e.into()) }.boxed(),
1046 };
1047 let txns_read = metadata.txns_shard.as_ref().map(|txns_id| {
1048 assert_eq!(txns_id, txns_read.txns_id());
1049 txns_read.clone()
1050 });
1051 let persist = Arc::clone(&self.persist);
1052 async move {
1053 let mut read_handle = Self::read_handle_for_snapshot(persist, &metadata, id).await?;
1054 let contents = match txns_read {
1055 None => {
1056 read_handle
1058 .snapshot_and_fetch(Antichain::from_elem(as_of))
1059 .await
1060 }
1061 Some(txns_read) => {
1062 txns_read.update_gt(as_of).await;
1076 let data_snapshot = txns_read.data_snapshot(metadata.data_shard, as_of).await;
1077 data_snapshot.snapshot_and_fetch(&mut read_handle).await
1078 }
1079 };
1080 match contents {
1081 Ok(contents) => {
1082 let mut snapshot = Vec::with_capacity(contents.len());
1083 for ((data, _), _, diff) in contents {
1084 let row = data.0?;
1087 snapshot.push((row, diff));
1088 }
1089 Ok(snapshot)
1090 }
1091 Err(_) => Err(StorageError::ReadBeforeSince(id)),
1092 }
1093 }
1094 .boxed()
1095 }
1096
1097 fn snapshot_and_stream(
1098 &self,
1099 id: GlobalId,
1100 as_of: Timestamp,
1101 txns_read: &TxnsRead<Timestamp>,
1102 ) -> BoxFuture<'static, Result<SourceDataStream, StorageError>> {
1103 let metadata = match self.collection_metadata(id) {
1104 Ok(metadata) => metadata.clone(),
1105 Err(e) => return async { Err(e.into()) }.boxed(),
1106 };
1107 let txns_read = metadata.txns_shard.as_ref().map(|txns_id| {
1108 assert_eq!(txns_id, txns_read.txns_id());
1109 txns_read.clone()
1110 });
1111 let persist = Arc::clone(&self.persist);
1112 Self::snapshot_and_stream_inner(persist, metadata, id, as_of, txns_read)
1113 }
1114
1115 fn snapshot_and_stream_inner(
1117 persist: Arc<PersistClientCache>,
1118 metadata: CollectionMetadata,
1119 id: GlobalId,
1120 as_of: Timestamp,
1121 txns_read: Option<TxnsRead<Timestamp>>,
1122 ) -> BoxFuture<'static, Result<SourceDataStream, StorageError>> {
1123 use futures::stream::StreamExt;
1124
1125 async move {
1126 let mut read_handle = Self::read_handle_for_snapshot(persist, &metadata, id).await?;
1127 let stream = match txns_read {
1128 None => {
1129 read_handle
1131 .snapshot_and_stream(Antichain::from_elem(as_of))
1132 .await
1133 .map_err(|_| StorageError::ReadBeforeSince(id))?
1134 .boxed()
1135 }
1136 Some(txns_read) => {
1137 txns_read.update_gt(as_of).await;
1138 let data_snapshot = txns_read.data_snapshot(metadata.data_shard, as_of).await;
1139 data_snapshot
1140 .snapshot_and_stream(&mut read_handle)
1141 .await
1142 .map_err(|_| StorageError::ReadBeforeSince(id))?
1143 .boxed()
1144 }
1145 };
1146
1147 let stream = stream
1156 .map(move |((data, _v), t, d)| {
1157 let _read_handle = &read_handle;
1158 (data, t, d)
1159 })
1160 .boxed();
1161 Ok(stream)
1162 }
1163 .boxed()
1164 }
1165
1166 fn set_read_policies_inner(
1167 &self,
1168 collections: &mut BTreeMap<GlobalId, CollectionState>,
1169 policies: Vec<(GlobalId, ReadPolicy)>,
1170 ) {
1171 trace!("set_read_policies: {:?}", policies);
1172
1173 let mut read_capability_changes = BTreeMap::default();
1174
1175 for (id, policy) in policies.into_iter() {
1176 let collection = match collections.get_mut(&id) {
1177 Some(c) => c,
1178 None => {
1179 panic!("Reference to absent collection {id}");
1180 }
1181 };
1182
1183 let mut new_read_capability = policy.frontier(collection.write_frontier.borrow());
1184
1185 if PartialOrder::less_equal(&collection.implied_capability, &new_read_capability) {
1186 let mut update = ChangeBatch::new();
1187 update.extend(new_read_capability.iter().map(|time| (*time, 1)));
1188 std::mem::swap(&mut collection.implied_capability, &mut new_read_capability);
1189 update.extend(new_read_capability.iter().map(|time| (*time, -1)));
1190 if !update.is_empty() {
1191 read_capability_changes.insert(id, update);
1192 }
1193 }
1194
1195 collection.read_policy = policy;
1196 }
1197
1198 for (id, changes) in read_capability_changes.iter() {
1199 if id.is_user() {
1200 trace!(%id, ?changes, "in set_read_policies, capability changes");
1201 }
1202 }
1203
1204 if !read_capability_changes.is_empty() {
1205 StorageCollectionsImpl::update_read_capabilities_inner(
1206 &self.cmd_tx,
1207 collections,
1208 &mut read_capability_changes,
1209 );
1210 }
1211 }
1212
1213 fn update_read_capabilities_inner(
1217 cmd_tx: &mpsc::UnboundedSender<BackgroundCmd>,
1218 collections: &mut BTreeMap<GlobalId, CollectionState>,
1219 updates: &mut BTreeMap<GlobalId, ChangeBatch<Timestamp>>,
1220 ) {
1221 let mut collections_net = BTreeMap::new();
1223
1224 while let Some(id) = updates.keys().rev().next().cloned() {
1229 let mut update = updates.remove(&id).unwrap();
1230
1231 if id.is_user() {
1232 trace!(id = ?id, update = ?update, "update_read_capabilities");
1233 }
1234
1235 let collection = if let Some(c) = collections.get_mut(&id) {
1236 c
1237 } else {
1238 let has_positive_updates = update.iter().any(|(_ts, diff)| *diff > 0);
1239 if has_positive_updates {
1240 panic!(
1241 "reference to absent collection {id} but we have positive updates: {:?}",
1242 update
1243 );
1244 } else {
1245 continue;
1248 }
1249 };
1250
1251 let current_read_capabilities = collection.read_capabilities.frontier().to_owned();
1252 for (time, diff) in update.iter() {
1253 assert!(
1254 collection.read_capabilities.count_for(time) + diff >= 0,
1255 "update {:?} for collection {id} would lead to negative \
1256 read capabilities, read capabilities before applying: {:?}",
1257 update,
1258 collection.read_capabilities
1259 );
1260
1261 if collection.read_capabilities.count_for(time) + diff > 0 {
1262 assert!(
1263 current_read_capabilities.less_equal(time),
1264 "update {:?} for collection {id} is trying to \
1265 install read capabilities before the current \
1266 frontier of read capabilities, read capabilities before applying: {:?}",
1267 update,
1268 collection.read_capabilities
1269 );
1270 }
1271 }
1272
1273 let changes = collection.read_capabilities.update_iter(update.drain());
1274 update.extend(changes);
1275
1276 if id.is_user() {
1277 trace!(
1278 %id,
1279 ?collection.storage_dependencies,
1280 ?update,
1281 "forwarding update to storage dependencies");
1282 }
1283
1284 for id in collection.storage_dependencies.iter() {
1285 updates
1286 .entry(*id)
1287 .or_insert_with(ChangeBatch::new)
1288 .extend(update.iter().cloned());
1289 }
1290
1291 let (changes, frontier) = collections_net
1292 .entry(id)
1293 .or_insert_with(|| (<ChangeBatch<_>>::new(), Antichain::new()));
1294
1295 changes.extend(update.drain());
1296 *frontier = collection.read_capabilities.frontier().to_owned();
1297 }
1298
1299 let mut persist_compaction_commands = Vec::with_capacity(collections_net.len());
1302 for (key, (mut changes, frontier)) in collections_net {
1303 if !changes.is_empty() {
1304 let collection = collections.get(&key).expect("must still exist");
1306 let should_emit_persist_compaction = collection.primary.is_none();
1307
1308 if frontier.is_empty() {
1309 info!(id = %key, "removing collection state because the since advanced to []!");
1310 collections.remove(&key).expect("must still exist");
1311 }
1312
1313 if should_emit_persist_compaction {
1314 persist_compaction_commands.push((key, frontier));
1315 }
1316 }
1317 }
1318
1319 if !persist_compaction_commands.is_empty() {
1320 cmd_tx
1321 .send(BackgroundCmd::DowngradeSince(persist_compaction_commands))
1322 .expect("cannot fail to send");
1323 }
1324 }
1325
1326 fn synchronize_finalized_shards(&self, storage_metadata: &StorageMetadata) {
1328 self.finalized_shards
1329 .lock()
1330 .retain(|shard| storage_metadata.unfinalized_shards.contains(shard));
1331 }
1332}
1333
1334fn partition_finalizable_shards(
1337 collection_metadata: BTreeMap<GlobalId, ShardId>,
1338 active_collection_ids: &BTreeSet<GlobalId>,
1339 unfinalized_shards: BTreeSet<ShardId>,
1340) -> (BTreeSet<ShardId>, BTreeSet<ShardId>) {
1341 let active_shards: BTreeSet<_> = collection_metadata
1342 .into_iter()
1343 .filter_map(|(id, shard)| active_collection_ids.contains(&id).then_some(shard))
1344 .collect();
1345 let referenced_shards = unfinalized_shards
1346 .intersection(&active_shards)
1347 .copied()
1348 .collect();
1349 let finalizable_shards = unfinalized_shards
1350 .difference(&active_shards)
1351 .copied()
1352 .collect();
1353
1354 (referenced_shards, finalizable_shards)
1355}
1356
1357#[async_trait]
1359impl StorageCollections for StorageCollectionsImpl {
1360 async fn initialize_state(
1361 &self,
1362 txn: &mut (dyn StorageTxn + Send),
1363 init_ids: BTreeSet<GlobalId>,
1364 ) -> Result<(), StorageError> {
1365 let metadata = txn.get_collection_metadata();
1366 let existing_metadata: BTreeSet<_> = metadata.into_iter().map(|(id, _)| id).collect();
1367
1368 let new_collections: BTreeSet<GlobalId> =
1370 init_ids.difference(&existing_metadata).cloned().collect();
1371
1372 self.prepare_state(
1373 txn,
1374 new_collections,
1375 BTreeSet::default(),
1376 BTreeMap::default(),
1377 )
1378 .await?;
1379
1380 let (referenced_shards, unfinalized_shards) = partition_finalizable_shards(
1387 txn.get_collection_metadata(),
1388 &init_ids,
1389 txn.get_unfinalized_shards(),
1390 );
1391 if !referenced_shards.is_empty() {
1392 warn!(
1393 ?referenced_shards,
1394 "removing active collection shards from the finalization WAL"
1395 );
1396 txn.remove_unfinalized_shards(referenced_shards);
1400 }
1401
1402 info!(?unfinalized_shards, "initializing finalizable_shards");
1403
1404 self.finalizable_shards.lock().extend(unfinalized_shards);
1405
1406 Ok(())
1407 }
1408
1409 fn update_parameters(&self, config_params: StorageParameters) {
1410 config_params.dyncfg_updates.apply(self.persist.cfg());
1413
1414 self.config
1415 .lock()
1416 .expect("lock poisoned")
1417 .update(config_params);
1418 }
1419
1420 fn collection_metadata(&self, id: GlobalId) -> Result<CollectionMetadata, CollectionMissing> {
1421 let collections = self.collections.lock().expect("lock poisoned");
1422
1423 collections
1424 .get(&id)
1425 .map(|c| c.collection_metadata.clone())
1426 .ok_or(CollectionMissing(id))
1427 }
1428
1429 fn active_collection_metadatas(&self) -> Vec<(GlobalId, CollectionMetadata)> {
1430 let collections = self.collections.lock().expect("lock poisoned");
1431
1432 collections
1433 .iter()
1434 .filter(|(_id, c)| !c.is_dropped())
1435 .map(|(id, c)| (*id, c.collection_metadata.clone()))
1436 .collect()
1437 }
1438
1439 fn collections_frontiers(
1440 &self,
1441 ids: Vec<GlobalId>,
1442 ) -> Result<Vec<CollectionFrontiers>, CollectionMissing> {
1443 if ids.is_empty() {
1444 return Ok(vec![]);
1445 }
1446
1447 let collections = self.collections.lock().expect("lock poisoned");
1448
1449 let res = ids
1450 .into_iter()
1451 .map(|id| {
1452 collections
1453 .get(&id)
1454 .map(|c| CollectionFrontiers {
1455 id: id.clone(),
1456 write_frontier: c.write_frontier.clone(),
1457 implied_capability: c.implied_capability.clone(),
1458 read_capabilities: c.read_capabilities.frontier().to_owned(),
1459 })
1460 .ok_or(CollectionMissing(id))
1461 })
1462 .collect::<Result<Vec<_>, _>>()?;
1463
1464 Ok(res)
1465 }
1466
1467 fn active_collection_frontiers(&self) -> Vec<CollectionFrontiers> {
1468 let collections = self.collections.lock().expect("lock poisoned");
1469
1470 let res = collections
1471 .iter()
1472 .filter(|(_id, c)| !c.is_dropped())
1473 .map(|(id, c)| CollectionFrontiers {
1474 id: id.clone(),
1475 write_frontier: c.write_frontier.clone(),
1476 implied_capability: c.implied_capability.clone(),
1477 read_capabilities: c.read_capabilities.frontier().to_owned(),
1478 })
1479 .collect_vec();
1480
1481 res
1482 }
1483
1484 async fn snapshot_stats(
1485 &self,
1486 id: GlobalId,
1487 as_of: Antichain<Timestamp>,
1488 ) -> Result<SnapshotStats, StorageError> {
1489 let metadata = self.collection_metadata(id)?;
1490
1491 let as_of = match metadata.txns_shard.as_ref() {
1494 None => SnapshotStatsAsOf::Direct(as_of),
1495 Some(txns_id) => {
1496 assert_eq!(txns_id, self.txns_read.txns_id());
1497 let as_of = as_of
1498 .into_option()
1499 .expect("cannot read as_of the empty antichain");
1500 self.txns_read.update_gt(as_of).await;
1501 let data_snapshot = self
1502 .txns_read
1503 .data_snapshot(metadata.data_shard, as_of)
1504 .await;
1505 SnapshotStatsAsOf::Txns(data_snapshot)
1506 }
1507 };
1508 self.snapshot_stats_inner(id, as_of).await
1509 }
1510
1511 async fn snapshot_parts_stats(
1512 &self,
1513 id: GlobalId,
1514 as_of: Antichain<Timestamp>,
1515 ) -> BoxFuture<'static, Result<SnapshotPartsStats, StorageError>> {
1516 let metadata = {
1517 let self_collections = self.collections.lock().expect("lock poisoned");
1518
1519 let collection_metadata = self_collections
1520 .get(&id)
1521 .ok_or(StorageError::IdentifierMissing(id))
1522 .map(|c| c.collection_metadata.clone());
1523
1524 match collection_metadata {
1525 Ok(m) => m,
1526 Err(e) => return Box::pin(async move { Err(e) }),
1527 }
1528 };
1529
1530 let persist = Arc::clone(&self.persist);
1533 let read_handle = Self::read_handle_for_snapshot(persist, &metadata, id).await;
1534
1535 let data_snapshot = match (metadata, as_of.as_option()) {
1536 (
1537 CollectionMetadata {
1538 txns_shard: Some(txns_id),
1539 data_shard,
1540 ..
1541 },
1542 Some(as_of),
1543 ) => {
1544 assert_eq!(txns_id, *self.txns_read.txns_id());
1545 self.txns_read.update_gt(*as_of).await;
1546 let data_snapshot = self.txns_read.data_snapshot(data_shard, *as_of).await;
1547 Some(data_snapshot)
1548 }
1549 _ => None,
1550 };
1551
1552 Box::pin(async move {
1553 let read_handle = read_handle?;
1554 let result = match data_snapshot {
1555 Some(data_snapshot) => data_snapshot.snapshot_parts_stats(&read_handle).await,
1556 None => read_handle.snapshot_parts_stats(as_of).await,
1557 };
1558 read_handle.expire().await;
1559 result.map_err(|_| StorageError::ReadBeforeSince(id))
1560 })
1561 }
1562
1563 fn snapshot(
1564 &self,
1565 id: GlobalId,
1566 as_of: Timestamp,
1567 ) -> BoxFuture<'static, Result<Vec<(Row, StorageDiff)>, StorageError>> {
1568 self.snapshot(id, as_of, &self.txns_read)
1569 }
1570
1571 async fn snapshot_latest(&self, id: GlobalId) -> Result<Vec<Row>, StorageError> {
1572 let upper = self.recent_upper(id).await?;
1573 let res = match upper.as_option() {
1574 Some(f) if f > &Timestamp::MIN => {
1575 let as_of = f.step_back().expect("checked that f > &Timestamp::MIN");
1576
1577 let snapshot = self.snapshot(id, as_of, &self.txns_read).await?;
1578 snapshot
1579 .into_iter()
1580 .map(|(row, diff)| {
1581 assert_eq!(diff, 1, "snapshot doesn't accumulate to set");
1584 row
1585 })
1586 .collect()
1587 }
1588 Some(_min) => {
1589 Vec::new()
1591 }
1592 _ => {
1595 return Err(StorageError::InvalidUsage(
1596 "collection closed, cannot determine a read timestamp based on the upper"
1597 .to_string(),
1598 ));
1599 }
1600 };
1601
1602 Ok(res)
1603 }
1604
1605 fn snapshot_cursor(
1606 &self,
1607 id: GlobalId,
1608 as_of: Timestamp,
1609 ) -> BoxFuture<'static, Result<SnapshotCursor, StorageError>> {
1610 let metadata = match self.collection_metadata(id) {
1611 Ok(metadata) => metadata.clone(),
1612 Err(e) => return async { Err(e.into()) }.boxed(),
1613 };
1614 let txns_read = metadata.txns_shard.as_ref().map(|txns_id| {
1615 assert_eq!(txns_id, self.txns_read.txns_id());
1618 self.txns_read.clone()
1619 });
1620 let persist = Arc::clone(&self.persist);
1621
1622 async move {
1624 let mut handle = Self::read_handle_for_snapshot(persist, &metadata, id).await?;
1625 let cursor = match txns_read {
1626 None => {
1627 let cursor = handle
1628 .snapshot_cursor(Antichain::from_elem(as_of), |_| true)
1629 .await
1630 .map_err(|_| StorageError::ReadBeforeSince(id))?;
1631 SnapshotCursor {
1632 _read_handle: handle,
1633 cursor,
1634 }
1635 }
1636 Some(txns_read) => {
1637 txns_read.update_gt(as_of).await;
1638 let data_snapshot = txns_read.data_snapshot(metadata.data_shard, as_of).await;
1639 let cursor = data_snapshot
1640 .snapshot_cursor(&mut handle, |_| true)
1641 .await
1642 .map_err(|_| StorageError::ReadBeforeSince(id))?;
1643 SnapshotCursor {
1644 _read_handle: handle,
1645 cursor,
1646 }
1647 }
1648 };
1649
1650 Ok(cursor)
1651 }
1652 .boxed()
1653 }
1654
1655 fn snapshot_and_stream(
1656 &self,
1657 id: GlobalId,
1658 as_of: Timestamp,
1659 ) -> BoxFuture<
1660 'static,
1661 Result<BoxStream<'static, (SourceData, Timestamp, StorageDiff)>, StorageError>,
1662 > {
1663 self.snapshot_and_stream(id, as_of, &self.txns_read)
1664 }
1665
1666 fn create_update_builder(
1667 &self,
1668 id: GlobalId,
1669 ) -> BoxFuture<
1670 'static,
1671 Result<TimestamplessUpdateBuilder<SourceData, (), StorageDiff>, StorageError>,
1672 > {
1673 let metadata = match self.collection_metadata(id) {
1674 Ok(m) => m,
1675 Err(e) => return Box::pin(async move { Err(e.into()) }),
1676 };
1677 let persist = Arc::clone(&self.persist);
1678
1679 async move {
1680 let persist_client = persist
1681 .open(metadata.persist_location.clone())
1682 .await
1683 .expect("invalid persist usage");
1684 let write_handle = persist_client
1685 .open_writer::<SourceData, (), Timestamp, StorageDiff>(
1686 metadata.data_shard,
1687 Arc::new(metadata.relation_desc.clone()),
1688 Arc::new(UnitSchema),
1689 Diagnostics {
1690 shard_name: id.to_string(),
1691 handle_purpose: format!("create write batch {}", id),
1692 },
1693 )
1694 .await
1695 .expect("invalid persist usage");
1696 let builder = TimestamplessUpdateBuilder::new(&write_handle);
1697
1698 Ok(builder)
1699 }
1700 .boxed()
1701 }
1702
1703 fn check_exists(&self, id: GlobalId) -> Result<(), StorageError> {
1704 let collections = self.collections.lock().expect("lock poisoned");
1705
1706 if collections.contains_key(&id) {
1707 Ok(())
1708 } else {
1709 Err(StorageError::IdentifierMissing(id))
1710 }
1711 }
1712
1713 async fn prepare_state(
1714 &self,
1715 txn: &mut (dyn StorageTxn + Send),
1716 ids_to_add: BTreeSet<GlobalId>,
1717 ids_to_drop: BTreeSet<GlobalId>,
1718 ids_to_register: BTreeMap<GlobalId, ShardId>,
1719 ) -> Result<(), StorageError> {
1720 let mut active_collection_ids: BTreeSet<_> = {
1723 let collections = self.collections.lock().expect("poisoned");
1724 collections
1725 .iter()
1726 .filter_map(|(id, collection)| {
1727 (!ids_to_drop.contains(id) && !collection.is_dropped()).then_some(*id)
1728 })
1729 .collect()
1730 };
1731 active_collection_ids.extend(ids_to_add.iter().copied());
1732 active_collection_ids.extend(ids_to_register.keys().copied());
1733
1734 txn.insert_collection_metadata(
1735 ids_to_add
1736 .into_iter()
1737 .map(|id| (id, ShardId::new()))
1738 .collect(),
1739 )?;
1740 txn.insert_collection_metadata(ids_to_register)?;
1741
1742 let dropped_mappings = txn.delete_collection_metadata(ids_to_drop);
1744
1745 let mut dropped_shards = BTreeSet::new();
1748 {
1749 let collections = self.collections.lock().expect("poisoned");
1750 for (id, shard) in dropped_mappings {
1751 let coll = collections.get(&id).expect("must exist");
1752 if coll.primary.is_none() {
1753 dropped_shards.insert(shard);
1754 }
1755 }
1756 }
1757 let remaining_metadata = txn.get_collection_metadata();
1758 let (referenced_shards, dropped_shards) = partition_finalizable_shards(
1759 remaining_metadata,
1760 &active_collection_ids,
1761 dropped_shards,
1762 );
1763 if !referenced_shards.is_empty() {
1764 mz_ore::soft_panic_or_log!(
1765 "dropped collections would finalize shards that active collections still use: \
1766 {referenced_shards:?}"
1767 );
1768 }
1769 txn.insert_unfinalized_shards(dropped_shards)?;
1770
1771 let finalized_shards = self.finalized_shards.lock().iter().copied().collect();
1774 txn.remove_unfinalized_shards(finalized_shards);
1775
1776 Ok(())
1777 }
1778
1779 #[instrument(level = "debug")]
1782 async fn create_collections_for_bootstrap(
1783 &self,
1784 storage_metadata: &StorageMetadata,
1785 register_ts: Option<Timestamp>,
1786 mut collections: Vec<(GlobalId, CollectionDescription)>,
1787 migrated_storage_collections: &BTreeSet<GlobalId>,
1788 ) -> Result<(), StorageError> {
1789 let is_in_txns = |id, metadata: &CollectionMetadata| {
1790 metadata.txns_shard.is_some()
1791 && !(self.read_only && migrated_storage_collections.contains(&id))
1792 };
1793
1794 collections.sort_by_key(|(id, _)| *id);
1799 collections.dedup();
1800 for pos in 1..collections.len() {
1801 if collections[pos - 1].0 == collections[pos].0 {
1802 return Err(StorageError::CollectionIdReused(collections[pos].0));
1803 }
1804 }
1805
1806 let enriched_with_metadata = collections
1809 .into_iter()
1810 .map(|(id, description)| {
1811 let data_shard = storage_metadata.get_collection_shard(id)?;
1812
1813 let txns_shard = description
1817 .data_source
1818 .in_txns()
1819 .then(|| *self.txns_read.txns_id());
1820
1821 let metadata = CollectionMetadata {
1822 persist_location: self.persist_location.clone(),
1823 data_shard,
1824 relation_desc: description.desc.clone(),
1825 txns_shard,
1826 };
1827
1828 Ok((id, description, metadata))
1829 })
1830 .collect_vec();
1831
1832 let persist_client = self
1834 .persist
1835 .open(self.persist_location.clone())
1836 .await
1837 .unwrap();
1838 let persist_client = &persist_client;
1839 use futures::stream::{StreamExt, TryStreamExt};
1842 let this = &*self;
1843 let mut to_register: Vec<_> = futures::stream::iter(enriched_with_metadata)
1844 .map(|data: Result<_, StorageError>| {
1845 async move {
1846 let (id, description, metadata) = data?;
1847
1848 debug!("mapping GlobalId={} to shard ({})", id, metadata.data_shard);
1853
1854 let since = if description.primary.is_some() {
1858 None
1859 } else {
1860 description.since.as_ref()
1861 };
1862
1863 let (write, mut since_handle) = this
1864 .open_data_handles(
1865 &id,
1866 metadata.data_shard,
1867 since,
1868 metadata.relation_desc.clone(),
1869 persist_client,
1870 )
1871 .await;
1872
1873 match description.data_source {
1882 DataSource::Introspection(_)
1883 | DataSource::IngestionExport { .. }
1884 | DataSource::Webhook
1885 | DataSource::Ingestion(_)
1886 | DataSource::Progress
1887 | DataSource::Other => {}
1888 DataSource::Sink { .. } => {}
1889 DataSource::Table => {
1890 let register_ts = register_ts.expect(
1891 "caller should have provided a register_ts when creating a table",
1892 );
1893 if since_handle.since().elements() == &[Timestamp::MIN]
1894 && !migrated_storage_collections.contains(&id)
1895 {
1896 debug!("advancing {} to initial since of {:?}", id, register_ts);
1897 let token = since_handle.opaque();
1898 let _ = since_handle
1899 .compare_and_downgrade_since(
1900 &token,
1901 (&token, &Antichain::from_elem(register_ts)),
1902 )
1903 .await;
1904 }
1905 }
1906 }
1907
1908 Ok::<_, StorageError>((id, description, write, since_handle, metadata))
1909 }
1910 })
1911 .buffer_unordered(50)
1913 .try_collect()
1927 .await?;
1928
1929 #[derive(Ord, PartialOrd, Eq, PartialEq)]
1931 enum DependencyOrder {
1932 Table(Reverse<GlobalId>),
1934 Collection(GlobalId),
1936 Sink(GlobalId),
1938 }
1939 to_register.sort_by_key(|(id, desc, ..)| match &desc.data_source {
1940 DataSource::Table => DependencyOrder::Table(Reverse(*id)),
1941 DataSource::Sink { .. } => DependencyOrder::Sink(*id),
1942 _ => DependencyOrder::Collection(*id),
1943 });
1944
1945 let dependency_violations = {
1948 let mut self_collections = self.collections.lock().expect("lock poisoned");
1951 let mut dependency_violations = Vec::new();
1952
1953 for (id, description, write_handle, since_handle, metadata) in to_register {
1954 let write_frontier = write_handle.upper();
1955 let data_shard_since = since_handle.since().clone();
1956
1957 let storage_dependencies =
1959 Self::determine_collection_dependencies(&*self_collections, id, &description)?;
1960
1961 let initial_since = match storage_dependencies
1963 .iter()
1964 .at_most_one()
1965 .expect("should have at most one dependency")
1966 {
1967 Some(dep) => {
1968 let dependency_collection = self_collections
1969 .get(dep)
1970 .ok_or(StorageError::IdentifierMissing(*dep))?;
1971 let dependency_since = dependency_collection.implied_capability.clone();
1972
1973 if PartialOrder::less_than(&data_shard_since, &dependency_since) {
1984 if description.primary.is_none()
2006 && write_frontier.elements() != &[Timestamp::MIN]
2007 && !write_frontier.is_empty()
2008 && !PartialOrder::less_than(&dependency_since, write_frontier)
2009 {
2010 dependency_violations.push(DependencyViolation {
2011 id,
2012 dependency: *dep,
2013 data_shard_since: data_shard_since.clone(),
2014 write_frontier: write_frontier.clone(),
2015 dependency_since: dependency_since.clone(),
2016 ingestion_export: matches!(
2017 description.data_source,
2018 DataSource::IngestionExport { .. }
2019 )
2020 .then(|| metadata.clone()),
2021 });
2022 }
2023
2024 dependency_since
2025 } else {
2026 data_shard_since
2027 }
2028 }
2029 None => data_shard_since,
2030 };
2031
2032 let time_dependence = {
2034 use DataSource::*;
2035 if let Some(timeline) = &description.timeline
2036 && *timeline != Timeline::EpochMilliseconds
2037 {
2038 None
2040 } else {
2041 match &description.data_source {
2042 Ingestion(ingestion) => {
2043 use GenericSourceConnection::*;
2044 match ingestion.desc.connection {
2045 Kafka(_) | Postgres(_) | MySql(_) | SqlServer(_) => {
2048 Some(TimeDependence::default())
2049 }
2050 LoadGenerator(_) => None,
2052 }
2053 }
2054 IngestionExport { ingestion_id, .. } => {
2055 let c = self_collections.get(ingestion_id).expect("known to exist");
2056 c.time_dependence.clone()
2057 }
2058 Introspection(_) | Progress | Table { .. } | Webhook { .. } => {
2060 Some(TimeDependence::default())
2061 }
2062 Other => None,
2064 Sink { .. } => None,
2065 }
2066 }
2067 };
2068
2069 let ingestion_remap_collection_id = match &description.data_source {
2070 DataSource::Ingestion(desc) => Some(desc.remap_collection_id),
2071 _ => None,
2072 };
2073
2074 let mut collection_state = CollectionState::new(
2075 description.primary,
2076 time_dependence,
2077 ingestion_remap_collection_id,
2078 initial_since,
2079 write_frontier.clone(),
2080 storage_dependencies,
2081 metadata.clone(),
2082 );
2083
2084 match &description.data_source {
2086 DataSource::Introspection(_) => {
2087 self_collections.insert(id, collection_state);
2088 }
2089 DataSource::Webhook => {
2090 self_collections.insert(id, collection_state);
2091 }
2092 DataSource::IngestionExport { .. } => {
2093 self_collections.insert(id, collection_state);
2094 }
2095 DataSource::Table => {
2096 if is_in_txns(id, &metadata)
2099 && PartialOrder::less_than(
2100 &collection_state.write_frontier,
2101 &self.initial_txn_upper,
2102 )
2103 {
2104 collection_state
2110 .write_frontier
2111 .clone_from(&self.initial_txn_upper);
2112 }
2113 self_collections.insert(id, collection_state);
2114 }
2115 DataSource::Progress | DataSource::Other => {
2116 self_collections.insert(id, collection_state);
2117 }
2118 DataSource::Ingestion(_) => {
2119 self_collections.insert(id, collection_state);
2120 }
2121 DataSource::Sink { .. } => {
2122 self_collections.insert(id, collection_state);
2123 }
2124 }
2125
2126 self.register_handles(id, is_in_txns(id, &metadata), since_handle, write_handle);
2127
2128 self.install_collection_dependency_read_holds_inner(&mut *self_collections, id)?;
2130 }
2131 dependency_violations
2132 };
2133
2134 for violation in dependency_violations {
2135 if let Some(metadata) = &violation.ingestion_export
2150 && shard_has_no_updates(persist_client, violation.id, metadata).await
2151 {
2152 continue;
2153 }
2154 let DependencyViolation {
2155 id,
2156 dependency,
2157 data_shard_since,
2158 write_frontier,
2159 dependency_since,
2160 ingestion_export: _,
2161 } = violation;
2162 mz_ore::soft_panic_or_log!(
2163 "dependency ({dependency}) since has advanced past dependent ({id}) upper \n
2164 dependent ({id}): since {:?}, upper {:?} \n
2165 dependency ({dependency}): since {:?}",
2166 data_shard_since,
2167 write_frontier,
2168 dependency_since
2169 );
2170 }
2171
2172 self.synchronize_finalized_shards(storage_metadata);
2173
2174 Ok(())
2175 }
2176
2177 async fn alter_table_desc(
2178 &self,
2179 existing_collection: GlobalId,
2180 new_collection: GlobalId,
2181 new_desc: RelationDesc,
2182 expected_version: RelationVersion,
2183 ) -> Result<(), StorageError> {
2184 let data_shard = {
2185 let self_collections = self.collections.lock().expect("lock poisoned");
2186 let existing = self_collections
2187 .get(&existing_collection)
2188 .ok_or_else(|| StorageError::IdentifierMissing(existing_collection))?;
2189
2190 existing.collection_metadata.data_shard
2191 };
2192
2193 let persist_client = self
2194 .persist
2195 .open(self.persist_location.clone())
2196 .await
2197 .unwrap();
2198
2199 let diagnostics = Diagnostics {
2201 shard_name: existing_collection.to_string(),
2202 handle_purpose: "alter_table_desc".to_string(),
2203 };
2204 let expected_schema = expected_version.into();
2206 let schema_result = persist_client
2207 .compare_and_evolve_schema::<SourceData, (), Timestamp, StorageDiff>(
2208 data_shard,
2209 expected_schema,
2210 &new_desc,
2211 &UnitSchema,
2212 diagnostics,
2213 )
2214 .await
2215 .map_err(|e| StorageError::InvalidUsage(e.to_string()))?;
2216 tracing::info!(
2217 ?existing_collection,
2218 ?new_collection,
2219 ?new_desc,
2220 "evolved schema"
2221 );
2222
2223 match schema_result {
2224 CaESchema::Ok(_id) => {}
2226 CaESchema::ExpectedMismatch {
2231 schema_id,
2232 key,
2233 val,
2234 } => {
2235 mz_ore::soft_panic_or_log!(
2236 "schema expectation mismatch, expected {expected_schema:?} \
2237 but found {schema_id:?}, {key:?}, {val:?}"
2238 );
2239 return Err(StorageError::Generic(anyhow::anyhow!(
2240 "schema expected mismatch, {existing_collection:?}",
2241 )));
2242 }
2243 CaESchema::Incompatible => {
2244 mz_ore::soft_panic_or_log!(
2245 "incompatible schema! {existing_collection} {new_desc:?}"
2246 );
2247 return Err(StorageError::Generic(anyhow::anyhow!(
2248 "schema incompatible, {existing_collection:?}"
2249 )));
2250 }
2251 };
2252
2253 let (write_handle, since_handle) = self
2255 .open_data_handles(
2256 &new_collection,
2257 data_shard,
2258 None,
2259 new_desc.clone(),
2260 &persist_client,
2261 )
2262 .await;
2263
2264 {
2270 let mut self_collections = self.collections.lock().expect("lock poisoned");
2271
2272 let existing = self_collections
2274 .get_mut(&existing_collection)
2275 .expect("existing collection missing");
2276
2277 assert_none!(existing.primary);
2279
2280 existing.primary = Some(new_collection);
2282 existing.storage_dependencies.push(new_collection);
2283
2284 let implied_capability = existing.read_capabilities.frontier().to_owned();
2288 let write_frontier = existing.write_frontier.clone();
2289
2290 let mut changes = ChangeBatch::new();
2297 changes.extend(implied_capability.iter().map(|t| (*t, 1)));
2298
2299 let collection_meta = CollectionMetadata {
2301 persist_location: self.persist_location.clone(),
2302 relation_desc: new_desc.clone(),
2303 data_shard,
2304 txns_shard: Some(self.txns_read.txns_id().clone()),
2305 };
2306 let collection_state = CollectionState::new(
2307 None,
2308 existing.time_dependence.clone(),
2309 existing.ingestion_remap_collection_id.clone(),
2310 implied_capability,
2311 write_frontier,
2312 Vec::new(),
2313 collection_meta,
2314 );
2315
2316 self_collections.insert(new_collection, collection_state);
2318
2319 let mut updates = BTreeMap::from([(new_collection, changes)]);
2320 StorageCollectionsImpl::update_read_capabilities_inner(
2321 &self.cmd_tx,
2322 &mut *self_collections,
2323 &mut updates,
2324 );
2325 };
2326
2327 self.register_handles(new_collection, true, since_handle, write_handle);
2329
2330 info!(%existing_collection, %new_collection, ?new_desc, "altered table");
2331
2332 Ok(())
2333 }
2334
2335 fn drop_collections_unvalidated(
2336 &self,
2337 storage_metadata: &StorageMetadata,
2338 identifiers: Vec<GlobalId>,
2339 ) {
2340 debug!(?identifiers, "drop_collections_unvalidated");
2341
2342 let mut self_collections = self.collections.lock().expect("lock poisoned");
2343 let dropping: BTreeSet<_> = identifiers.iter().copied().collect();
2346 let active_collection_ids: BTreeSet<_> = self_collections
2347 .iter()
2348 .filter_map(|(id, collection)| {
2349 (!dropping.contains(id) && !collection.is_dropped()).then_some(*id)
2350 })
2351 .collect();
2352 let shards_in_use: BTreeSet<_> = storage_metadata
2353 .collection_metadata
2354 .iter()
2355 .filter_map(|(id, shard)| active_collection_ids.contains(id).then_some(*shard))
2356 .collect();
2357
2358 let mut finalized_policies = Vec::new();
2366
2367 for id in identifiers {
2368 let Some(collection) = self_collections.get(&id) else {
2370 continue;
2371 };
2372
2373 if collection.primary.is_none() {
2376 let metadata = storage_metadata.get_collection_shard(id);
2377 mz_ore::soft_assert_or_log!(
2378 matches!(metadata, Err(StorageError::IdentifierMissing(_))),
2379 "dropping {id}, but drop was not synchronized with storage \
2380 controller via `prepare_state`"
2381 );
2382
2383 let data_shard = collection.collection_metadata.data_shard;
2387 if shards_in_use.contains(&data_shard) {
2388 mz_ore::soft_panic_or_log!(
2389 "dropping {id} would release the since of shard {data_shard}, \
2390 which an active collection still uses"
2391 );
2392 continue;
2393 }
2394 }
2395
2396 finalized_policies.push((id, ReadPolicy::ValidFrom(Antichain::new())));
2397 }
2398
2399 self.set_read_policies_inner(&mut self_collections, finalized_policies);
2400
2401 drop(self_collections);
2402
2403 self.synchronize_finalized_shards(storage_metadata);
2404 }
2405
2406 fn set_read_policies(&self, policies: Vec<(GlobalId, ReadPolicy)>) {
2407 let mut collections = self.collections.lock().expect("lock poisoned");
2408
2409 if tracing::enabled!(tracing::Level::TRACE) {
2410 let user_capabilities = collections
2411 .iter_mut()
2412 .filter(|(id, _c)| id.is_user())
2413 .map(|(id, c)| {
2414 let updates = c.read_capabilities.updates().cloned().collect_vec();
2415 (*id, c.implied_capability.clone(), updates)
2416 })
2417 .collect_vec();
2418
2419 trace!(?policies, ?user_capabilities, "set_read_policies");
2420 }
2421
2422 self.set_read_policies_inner(&mut collections, policies);
2423
2424 if tracing::enabled!(tracing::Level::TRACE) {
2425 let user_capabilities = collections
2426 .iter_mut()
2427 .filter(|(id, _c)| id.is_user())
2428 .map(|(id, c)| {
2429 let updates = c.read_capabilities.updates().cloned().collect_vec();
2430 (*id, c.implied_capability.clone(), updates)
2431 })
2432 .collect_vec();
2433
2434 trace!(?user_capabilities, "after! set_read_policies");
2435 }
2436 }
2437
2438 fn acquire_read_holds(
2439 &self,
2440 desired_holds: Vec<GlobalId>,
2441 ) -> Result<Vec<ReadHold>, CollectionMissing> {
2442 if desired_holds.is_empty() {
2443 return Ok(vec![]);
2444 }
2445
2446 let mut collections = self.collections.lock().expect("lock poisoned");
2447
2448 let mut advanced_holds = Vec::new();
2449 for id in desired_holds.iter() {
2460 let collection = collections.get(id).ok_or(CollectionMissing(*id))?;
2461 let since = collection.read_capabilities.frontier().to_owned();
2462 advanced_holds.push((*id, since));
2463 }
2464
2465 let mut updates = advanced_holds
2466 .iter()
2467 .map(|(id, hold)| {
2468 let mut changes = ChangeBatch::new();
2469 changes.extend(hold.iter().map(|time| (*time, 1)));
2470 (*id, changes)
2471 })
2472 .collect::<BTreeMap<_, _>>();
2473
2474 StorageCollectionsImpl::update_read_capabilities_inner(
2475 &self.cmd_tx,
2476 &mut collections,
2477 &mut updates,
2478 );
2479
2480 let acquired_holds = advanced_holds
2481 .into_iter()
2482 .map(|(id, since)| ReadHold::with_channel(id, since, self.holds_tx.clone()))
2483 .collect_vec();
2484
2485 trace!(?desired_holds, ?acquired_holds, "acquire_read_holds");
2486
2487 Ok(acquired_holds)
2488 }
2489
2490 fn determine_time_dependence(
2492 &self,
2493 id: GlobalId,
2494 ) -> Result<Option<TimeDependence>, TimeDependenceError> {
2495 use TimeDependenceError::CollectionMissing;
2496 let collections = self.collections.lock().expect("lock poisoned");
2497 let state = collections.get(&id).ok_or(CollectionMissing(id))?;
2498 Ok(state.time_dependence.clone())
2499 }
2500
2501 fn dump(&self) -> Result<serde_json::Value, anyhow::Error> {
2502 let Self {
2504 envd_epoch,
2505 read_only,
2506 finalizable_shards,
2507 finalized_shards,
2508 collections,
2509 txns_read: _,
2510 config,
2511 initial_txn_upper,
2512 persist_location,
2513 persist: _,
2514 cmd_tx: _,
2515 holds_tx: _,
2516 _background_task: _,
2517 _finalize_shards_task: _,
2518 } = self;
2519
2520 let finalizable_shards: Vec<_> = finalizable_shards
2521 .lock()
2522 .iter()
2523 .map(ToString::to_string)
2524 .collect();
2525 let finalized_shards: Vec<_> = finalized_shards
2526 .lock()
2527 .iter()
2528 .map(ToString::to_string)
2529 .collect();
2530 let collections: BTreeMap<_, _> = collections
2531 .lock()
2532 .expect("poisoned")
2533 .iter()
2534 .map(|(id, c)| (id.to_string(), format!("{c:?}")))
2535 .collect();
2536 let config = format!("{:?}", config.lock().expect("poisoned"));
2537
2538 Ok(serde_json::json!({
2539 "envd_epoch": envd_epoch,
2540 "read_only": read_only,
2541 "finalizable_shards": finalizable_shards,
2542 "finalized_shards": finalized_shards,
2543 "collections": collections,
2544 "config": config,
2545 "initial_txn_upper": initial_txn_upper,
2546 "persist_location": format!("{persist_location:?}"),
2547 }))
2548 }
2549}
2550
2551#[derive(Debug)]
2558enum SinceHandleWrapper {
2559 Critical(SinceHandle<SourceData, (), Timestamp, StorageDiff>),
2560 Leased(ReadHandle<SourceData, (), Timestamp, StorageDiff>),
2561}
2562
2563impl SinceHandleWrapper {
2564 pub fn since(&self) -> &Antichain<Timestamp> {
2565 match self {
2566 Self::Critical(handle) => handle.since(),
2567 Self::Leased(handle) => handle.since(),
2568 }
2569 }
2570
2571 pub fn opaque(&self) -> PersistEpoch {
2572 match self {
2573 Self::Critical(handle) => handle.opaque().decode(),
2574 Self::Leased(_handle) => {
2575 PersistEpoch(None)
2580 }
2581 }
2582 }
2583
2584 pub async fn compare_and_downgrade_since(
2585 &mut self,
2586 expected: &PersistEpoch,
2587 (opaque, since): (&PersistEpoch, &Antichain<Timestamp>),
2588 ) -> Result<Antichain<Timestamp>, PersistEpoch> {
2589 match self {
2590 Self::Critical(handle) => handle
2591 .compare_and_downgrade_since(
2592 &Opaque::encode(expected),
2593 (&Opaque::encode(opaque), since),
2594 )
2595 .await
2596 .map_err(|e| e.decode()),
2597 Self::Leased(handle) => {
2598 assert_none!(opaque.0);
2599
2600 handle.downgrade_since(since).await;
2601
2602 Ok(since.clone())
2603 }
2604 }
2605 }
2606
2607 pub async fn maybe_compare_and_downgrade_since(
2608 &mut self,
2609 expected: &PersistEpoch,
2610 (opaque, since): (&PersistEpoch, &Antichain<Timestamp>),
2611 ) -> Option<Result<Antichain<Timestamp>, PersistEpoch>> {
2612 match self {
2613 Self::Critical(handle) => handle
2614 .maybe_compare_and_downgrade_since(
2615 &Opaque::encode(expected),
2616 (&Opaque::encode(opaque), since),
2617 )
2618 .await
2619 .map(|r| r.map_err(|o| o.decode())),
2620 Self::Leased(handle) => {
2621 assert_none!(opaque.0);
2622
2623 handle.maybe_downgrade_since(since).await;
2624
2625 Some(Ok(since.clone()))
2626 }
2627 }
2628 }
2629
2630 pub fn snapshot_stats(
2631 &self,
2632 id: GlobalId,
2633 as_of: Option<Antichain<Timestamp>>,
2634 ) -> BoxFuture<'static, Result<SnapshotStats, StorageError>> {
2635 match self {
2636 Self::Critical(handle) => {
2637 let res = handle
2638 .snapshot_stats(as_of)
2639 .map(move |x| x.map_err(|_| StorageError::ReadBeforeSince(id)));
2640 Box::pin(res)
2641 }
2642 Self::Leased(handle) => {
2643 let res = handle
2644 .snapshot_stats(as_of)
2645 .map(move |x| x.map_err(|_| StorageError::ReadBeforeSince(id)));
2646 Box::pin(res)
2647 }
2648 }
2649 }
2650
2651 pub fn snapshot_stats_from_txn(
2652 &self,
2653 id: GlobalId,
2654 data_snapshot: DataSnapshot<Timestamp>,
2655 ) -> BoxFuture<'static, Result<SnapshotStats, StorageError>> {
2656 match self {
2657 Self::Critical(handle) => Box::pin(
2658 data_snapshot
2659 .snapshot_stats_from_critical(handle)
2660 .map(move |x| x.map_err(|_| StorageError::ReadBeforeSince(id))),
2661 ),
2662 Self::Leased(handle) => Box::pin(
2663 data_snapshot
2664 .snapshot_stats_from_leased(handle)
2665 .map(move |x| x.map_err(|_| StorageError::ReadBeforeSince(id))),
2666 ),
2667 }
2668 }
2669}
2670
2671#[derive(Debug, Clone)]
2673struct CollectionState {
2674 primary: Option<GlobalId>,
2681
2682 time_dependence: Option<TimeDependence>,
2684 ingestion_remap_collection_id: Option<GlobalId>,
2686
2687 pub read_capabilities: MutableAntichain<Timestamp>,
2693
2694 pub implied_capability: Antichain<Timestamp>,
2698
2699 pub read_policy: ReadPolicy,
2701
2702 pub storage_dependencies: Vec<GlobalId>,
2704
2705 pub write_frontier: Antichain<Timestamp>,
2707
2708 pub collection_metadata: CollectionMetadata,
2709}
2710
2711impl CollectionState {
2712 pub fn new(
2715 primary: Option<GlobalId>,
2716 time_dependence: Option<TimeDependence>,
2717 ingestion_remap_collection_id: Option<GlobalId>,
2718 since: Antichain<Timestamp>,
2719 write_frontier: Antichain<Timestamp>,
2720 storage_dependencies: Vec<GlobalId>,
2721 metadata: CollectionMetadata,
2722 ) -> Self {
2723 let mut read_capabilities = MutableAntichain::new();
2724 read_capabilities.update_iter(since.iter().map(|time| (*time, 1)));
2725 Self {
2726 primary,
2727 time_dependence,
2728 ingestion_remap_collection_id,
2729 read_capabilities,
2730 implied_capability: since.clone(),
2731 read_policy: ReadPolicy::NoPolicy {
2732 initial_since: since,
2733 },
2734 storage_dependencies,
2735 write_frontier,
2736 collection_metadata: metadata,
2737 }
2738 }
2739
2740 pub fn is_dropped(&self) -> bool {
2742 self.read_capabilities.is_empty()
2743 }
2744}
2745
2746#[derive(Debug)]
2752struct BackgroundTask {
2753 config: Arc<Mutex<StorageConfiguration>>,
2754 cmds_tx: mpsc::UnboundedSender<BackgroundCmd>,
2755 cmds_rx: mpsc::UnboundedReceiver<BackgroundCmd>,
2756 holds_rx: mpsc::UnboundedReceiver<(GlobalId, ChangeBatch<Timestamp>)>,
2757 finalizable_shards: Arc<ShardIdSet>,
2758 collections: Arc<std::sync::Mutex<BTreeMap<GlobalId, CollectionState>>>,
2759 shard_by_id: BTreeMap<GlobalId, ShardId>,
2762 since_handles: BTreeMap<GlobalId, SinceHandleWrapper>,
2763 txns_handle: Option<WriteHandle<SourceData, (), Timestamp, StorageDiff>>,
2764 txns_shards: BTreeSet<GlobalId>,
2765}
2766
2767#[derive(Debug)]
2768enum BackgroundCmd {
2769 Register {
2770 id: GlobalId,
2771 is_in_txns: bool,
2772 write_handle: WriteHandle<SourceData, (), Timestamp, StorageDiff>,
2773 since_handle: SinceHandleWrapper,
2774 },
2775 DowngradeSince(Vec<(GlobalId, Antichain<Timestamp>)>),
2776 SnapshotStats(
2777 GlobalId,
2778 SnapshotStatsAsOf,
2779 oneshot::Sender<SnapshotStatsRes>,
2780 ),
2781}
2782
2783pub(crate) struct SnapshotStatsRes(BoxFuture<'static, Result<SnapshotStats, StorageError>>);
2785
2786impl Debug for SnapshotStatsRes {
2787 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2788 f.debug_struct("SnapshotStatsRes").finish_non_exhaustive()
2789 }
2790}
2791
2792impl BackgroundTask {
2793 async fn run(&mut self) {
2794 let mut upper_futures: FuturesUnordered<
2796 std::pin::Pin<
2797 Box<
2798 dyn Future<
2799 Output = (
2800 GlobalId,
2801 WriteHandle<SourceData, (), Timestamp, StorageDiff>,
2802 Antichain<Timestamp>,
2803 ),
2804 > + Send,
2805 >,
2806 >,
2807 > = FuturesUnordered::new();
2808
2809 let gen_upper_future =
2810 |id, mut handle: WriteHandle<_, _, _, _>, prev_upper: Antichain<Timestamp>| {
2811 let fut = async move {
2812 soft_assert_or_log!(
2813 !prev_upper.is_empty(),
2814 "cannot await progress when upper is already empty"
2815 );
2816 handle.wait_for_upper_past(&prev_upper).await;
2817 let new_upper = handle.shared_upper();
2818 (id, handle, new_upper)
2819 };
2820
2821 fut
2822 };
2823
2824 let mut txns_upper_future = match self.txns_handle.take() {
2825 Some(txns_handle) => {
2826 let upper = txns_handle.upper().clone();
2827 let txns_upper_future =
2828 gen_upper_future(GlobalId::Transient(1), txns_handle, upper);
2829 txns_upper_future.boxed()
2830 }
2831 None => async { std::future::pending().await }.boxed(),
2832 };
2833
2834 loop {
2835 tokio::select! {
2836 (id, handle, upper) = &mut txns_upper_future => {
2837 trace!("new upper from txns shard: {:?}", upper);
2838 let mut uppers = Vec::new();
2839 for id in self.txns_shards.iter() {
2840 uppers.push((*id, &upper));
2841 }
2842 self.update_write_frontiers(&uppers).await;
2843
2844 let fut = gen_upper_future(id, handle, upper);
2845 txns_upper_future = fut.boxed();
2846 }
2847 Some((id, handle, upper)) = upper_futures.next() => {
2848 if id.is_user() {
2849 trace!("new upper for collection {id}: {:?}", upper);
2850 }
2851 let current_shard = self.shard_by_id.get(&id);
2852 if let Some(shard_id) = current_shard {
2853 if shard_id == &handle.shard_id() {
2854 let uppers = &[(id, &upper)];
2857 self.update_write_frontiers(uppers).await;
2858 if !upper.is_empty() {
2859 let fut = gen_upper_future(id, handle, upper);
2860 upper_futures.push(fut.boxed());
2861 }
2862 } else {
2863 handle.expire().await;
2867 }
2868 }
2869 }
2870 cmd = self.cmds_rx.recv() => {
2871 let Some(cmd) = cmd else {
2872 break;
2874 };
2875
2876 let commands = iter::once(cmd).chain(
2880 iter::from_fn(|| self.cmds_rx.try_recv().ok())
2881 );
2882 let mut downgrades = BTreeMap::<_, Antichain<_>>::new();
2883 for cmd in commands {
2884 match cmd {
2885 BackgroundCmd::Register{
2886 id,
2887 is_in_txns,
2888 write_handle,
2889 since_handle
2890 } => {
2891 debug!("registering handles for {}", id);
2892 let previous = self.shard_by_id.insert(id, write_handle.shard_id());
2893 if previous.is_some() {
2894 panic!("already registered a WriteHandle for collection {id}");
2895 }
2896
2897 let previous = self.since_handles.insert(id, since_handle);
2898 if previous.is_some() {
2899 panic!("already registered a SinceHandle for collection {id}");
2900 }
2901
2902 if is_in_txns {
2903 self.txns_shards.insert(id);
2904 } else {
2905 let upper = write_handle.upper().clone();
2906 if !upper.is_empty() {
2907 let fut = gen_upper_future(id, write_handle, upper);
2908 upper_futures.push(fut.boxed());
2909 }
2910 }
2911 }
2912 BackgroundCmd::DowngradeSince(cmds) => {
2913 for (id, new) in cmds {
2914 downgrades.entry(id)
2915 .and_modify(|since| since.join_assign(&new))
2916 .or_insert(new);
2917 }
2918 }
2919 BackgroundCmd::SnapshotStats(id, as_of, tx) => {
2920 let res = match self.since_handles.get(&id) {
2926 Some(x) => {
2927 let fut: BoxFuture<
2928 'static,
2929 Result<SnapshotStats, StorageError>,
2930 > = match as_of {
2931 SnapshotStatsAsOf::Direct(as_of) => {
2932 x.snapshot_stats(id, Some(as_of))
2933 }
2934 SnapshotStatsAsOf::Txns(data_snapshot) => {
2935 x.snapshot_stats_from_txn(id, data_snapshot)
2936 }
2937 };
2938 SnapshotStatsRes(fut)
2939 }
2940 None => SnapshotStatsRes(Box::pin(futures::future::ready(Err(
2941 StorageError::IdentifierMissing(id),
2942 )))),
2943 };
2944 let _ = tx.send(res);
2946 }
2947 }
2948 }
2949
2950 if !downgrades.is_empty() {
2951 self.downgrade_sinces(downgrades).await;
2952 }
2953 }
2954 Some(holds_changes) = self.holds_rx.recv() => {
2955 let mut batched_changes = BTreeMap::new();
2956 batched_changes.insert(holds_changes.0, holds_changes.1);
2957
2958 while let Ok(mut holds_changes) = self.holds_rx.try_recv() {
2959 let entry = batched_changes.entry(holds_changes.0);
2960 entry
2961 .and_modify(|existing| existing.extend(holds_changes.1.drain()))
2962 .or_insert_with(|| holds_changes.1);
2963 }
2964
2965 let mut collections = self.collections.lock().expect("lock poisoned");
2966
2967 let user_changes = batched_changes
2968 .iter()
2969 .filter(|(id, _c)| id.is_user())
2970 .map(|(id, c)| {
2971 (id.clone(), c.clone())
2972 })
2973 .collect_vec();
2974
2975 if !user_changes.is_empty() {
2976 trace!(?user_changes, "applying holds changes from channel");
2977 }
2978
2979 StorageCollectionsImpl::update_read_capabilities_inner(
2980 &self.cmds_tx,
2981 &mut collections,
2982 &mut batched_changes,
2983 );
2984 }
2985 }
2986 }
2987
2988 warn!("BackgroundTask shutting down");
2989 }
2990
2991 #[instrument(level = "debug")]
2992 async fn update_write_frontiers(&self, updates: &[(GlobalId, &Antichain<Timestamp>)]) {
2993 let mut read_capability_changes = BTreeMap::default();
2994
2995 let mut self_collections = self.collections.lock().expect("lock poisoned");
2996
2997 for (id, new_upper) in updates.iter() {
2998 let collection = if let Some(c) = self_collections.get_mut(id) {
2999 c
3000 } else {
3001 trace!(
3002 "Reference to absent collection {id}, due to concurrent removal of that collection"
3003 );
3004 continue;
3005 };
3006
3007 if PartialOrder::less_than(&collection.write_frontier, *new_upper) {
3008 collection.write_frontier.clone_from(new_upper);
3009 }
3010
3011 let mut new_read_capability = collection
3012 .read_policy
3013 .frontier(collection.write_frontier.borrow());
3014
3015 if id.is_user() {
3016 trace!(
3017 %id,
3018 implied_capability = ?collection.implied_capability,
3019 policy = ?collection.read_policy,
3020 write_frontier = ?collection.write_frontier,
3021 ?new_read_capability,
3022 "update_write_frontiers");
3023 }
3024
3025 if PartialOrder::less_equal(&collection.implied_capability, &new_read_capability) {
3026 let mut update = ChangeBatch::new();
3027 update.extend(new_read_capability.iter().map(|time| (*time, 1)));
3028 std::mem::swap(&mut collection.implied_capability, &mut new_read_capability);
3029 update.extend(new_read_capability.iter().map(|time| (*time, -1)));
3030
3031 if !update.is_empty() {
3032 read_capability_changes.insert(*id, update);
3033 }
3034 }
3035 }
3036
3037 if !read_capability_changes.is_empty() {
3038 StorageCollectionsImpl::update_read_capabilities_inner(
3039 &self.cmds_tx,
3040 &mut self_collections,
3041 &mut read_capability_changes,
3042 );
3043 }
3044 }
3045
3046 async fn downgrade_sinces(&mut self, cmds: BTreeMap<GlobalId, Antichain<Timestamp>>) {
3047 let mut futures = Vec::with_capacity(cmds.len());
3049 for (id, new_since) in cmds {
3050 let Some(mut since_handle) = self.since_handles.remove(&id) else {
3053 trace!("downgrade_sinces: reference to absent collection {id}");
3055 continue;
3056 };
3057
3058 let fut = async move {
3059 if id.is_user() {
3060 trace!("downgrading since of {} to {:?}", id, new_since);
3061 }
3062
3063 let epoch = since_handle.opaque().clone();
3064 let result = if new_since.is_empty() {
3065 Some(
3069 since_handle
3070 .compare_and_downgrade_since(&epoch, (&epoch, &new_since))
3071 .await,
3072 )
3073 } else {
3074 since_handle
3075 .maybe_compare_and_downgrade_since(&epoch, (&epoch, &new_since))
3076 .await
3077 };
3078 (id, since_handle, result)
3079 };
3080 futures.push(fut);
3081 }
3082
3083 for (id, since_handle, result) in futures::future::join_all(futures).await {
3084 let new_since = match result {
3085 Some(Ok(since)) => Some(since),
3086 Some(Err(other_epoch)) => mz_ore::halt!(
3087 "fenced by envd @ {other_epoch:?}. ours = {:?}",
3088 since_handle.opaque(),
3089 ),
3090 None => None,
3091 };
3092
3093 self.since_handles.insert(id, since_handle);
3094
3095 if new_since.is_some_and(|s| s.is_empty()) {
3096 info!(%id, "removing persist handles because the since advanced to []!");
3097
3098 let _since_handle = self.since_handles.remove(&id).expect("known to exist");
3099 let Some(dropped_shard_id) = self.shard_by_id.remove(&id) else {
3100 panic!("missing GlobalId -> ShardId mapping for id {id}");
3101 };
3102
3103 self.txns_shards.remove(&id);
3108
3109 if self
3110 .config
3111 .lock()
3112 .expect("lock poisoned")
3113 .parameters
3114 .finalize_shards
3115 {
3116 info!(
3117 %id, %dropped_shard_id,
3118 "enqueuing shard finalization due to dropped collection and dropped \
3119 persist handle",
3120 );
3121 self.finalizable_shards.lock().insert(dropped_shard_id);
3122 } else {
3123 info!(
3124 "not triggering shard finalization due to dropped storage object \
3125 because enable_storage_shard_finalization parameter is false"
3126 );
3127 }
3128 }
3129 }
3130 }
3131}
3132
3133struct FinalizeShardsTaskConfig {
3134 envd_epoch: NonZeroI64,
3135 config: Arc<Mutex<StorageConfiguration>>,
3136 metrics: StorageCollectionsMetrics,
3137 finalizable_shards: Arc<ShardIdSet>,
3138 finalized_shards: Arc<ShardIdSet>,
3139 persist_location: PersistLocation,
3140 persist: Arc<PersistClientCache>,
3141 read_only: bool,
3142}
3143
3144async fn finalize_shards_task(
3145 FinalizeShardsTaskConfig {
3146 envd_epoch,
3147 config,
3148 metrics,
3149 finalizable_shards,
3150 finalized_shards,
3151 persist_location,
3152 persist,
3153 read_only,
3154 }: FinalizeShardsTaskConfig,
3155) {
3156 if read_only {
3157 info!("disabling shard finalization in read only mode");
3158 return;
3159 }
3160
3161 let mut interval = tokio::time::interval(Duration::from_secs(5));
3162 interval.set_missed_tick_behavior(MissedTickBehavior::Delay);
3163 loop {
3164 interval.tick().await;
3165
3166 if !config
3167 .lock()
3168 .expect("lock poisoned")
3169 .parameters
3170 .finalize_shards
3171 {
3172 debug!(
3173 "not triggering shard finalization due to dropped storage object because enable_storage_shard_finalization parameter is false"
3174 );
3175 continue;
3176 }
3177
3178 let current_finalizable_shards = {
3179 finalizable_shards.lock().iter().cloned().collect_vec()
3182 };
3183
3184 if current_finalizable_shards.is_empty() {
3185 debug!("no shards to finalize");
3186 continue;
3187 }
3188
3189 debug!(?current_finalizable_shards, "attempting to finalize shards");
3190
3191 let persist_client = persist.open(persist_location.clone()).await.unwrap();
3193
3194 let metrics = &metrics;
3195 let finalizable_shards = &finalizable_shards;
3196 let finalized_shards = &finalized_shards;
3197 let persist_client = &persist_client;
3198 let diagnostics = &Diagnostics::from_purpose("finalizing shards");
3199
3200 let force_downgrade_since = STORAGE_DOWNGRADE_SINCE_DURING_FINALIZATION
3201 .get(config.lock().expect("lock poisoned").config_set());
3202
3203 let epoch = &PersistEpoch::from(envd_epoch);
3204
3205 futures::stream::iter(current_finalizable_shards.clone())
3206 .map(|shard_id| async move {
3207 let persist_client = persist_client.clone();
3208 let diagnostics = diagnostics.clone();
3209 let epoch = epoch.clone();
3210
3211 metrics.finalization_started.inc();
3212
3213 let is_finalized = persist_client
3214 .is_finalized::<SourceData, (), Timestamp, StorageDiff>(shard_id, diagnostics)
3215 .await
3216 .expect("invalid persist usage");
3217
3218 if is_finalized {
3219 debug!(%shard_id, "shard is already finalized!");
3220 Some(shard_id)
3221 } else {
3222 debug!(%shard_id, "finalizing shard");
3223 let finalize = || async move {
3224 let diagnostics = Diagnostics::from_purpose("finalizing shards");
3226
3227 let mut write_handle: WriteHandle<SourceData, (), Timestamp, StorageDiff> =
3230 persist_client
3231 .open_writer(
3232 shard_id,
3233 Arc::new(RelationDesc::empty()),
3234 Arc::new(UnitSchema),
3235 diagnostics,
3236 )
3237 .await
3238 .expect("invalid persist usage");
3239 write_handle.advance_upper(&Antichain::new()).await;
3240 write_handle.expire().await;
3241
3242 if force_downgrade_since {
3243 let our_opaque = Opaque::encode(&epoch);
3244 let mut since_handle: SinceHandle<
3245 SourceData,
3246 (),
3247 Timestamp,
3248 StorageDiff,
3249 > = persist_client
3250 .open_critical_since(
3251 shard_id,
3252 PersistClient::CONTROLLER_CRITICAL_SINCE,
3253 our_opaque.clone(),
3254 Diagnostics::from_purpose("finalizing shards"),
3255 )
3256 .await
3257 .expect("invalid persist usage");
3258 let handle_opaque = since_handle.opaque().clone();
3259 let opaque = if our_opaque.codec_name() == handle_opaque.codec_name()
3260 && epoch.0 > handle_opaque.decode::<PersistEpoch>().0
3261 {
3262 handle_opaque
3265 } else {
3266 our_opaque
3272 };
3273 let new_since = Antichain::new();
3274 let downgrade = since_handle
3275 .compare_and_downgrade_since(&opaque, (&opaque, &new_since))
3276 .await;
3277 if let Err(e) = downgrade {
3278 warn!("tried to finalize a shard with an advancing epoch: {e:?}");
3279 return Ok(true);
3280 }
3281 }
3284
3285 persist_client
3286 .finalize_shard::<SourceData, (), Timestamp, StorageDiff>(
3287 shard_id,
3288 Diagnostics::from_purpose("finalizing shards"),
3289 )
3290 .await
3291 };
3292
3293 match finalize().await {
3294 Err(e) => {
3295 warn!("error during finalization of shard {shard_id}: {e:?}");
3298 None
3299 }
3300 Ok(true) => {
3301 debug!(%shard_id, "finalize success!");
3302 Some(shard_id)
3303 }
3304 Ok(false) => {
3305 debug!(%shard_id, "finalize unfinished, retrying later");
3306 None
3307 }
3308 }
3309 }
3310 })
3311 .buffer_unordered(10)
3316 .for_each(|shard_id| async move {
3320 match shard_id {
3321 None => metrics.finalization_failed.inc(),
3322 Some(shard_id) => {
3323 {
3330 let mut finalizable_shards = finalizable_shards.lock();
3331 let mut finalized_shards = finalized_shards.lock();
3332 finalizable_shards.remove(&shard_id);
3333 finalized_shards.insert(shard_id);
3334 }
3335
3336 metrics.finalization_succeeded.inc();
3337 }
3338 }
3339 })
3340 .await;
3341
3342 debug!("done finalizing shards");
3343 }
3344}
3345
3346#[derive(Debug)]
3349struct DependencyViolation {
3350 id: GlobalId,
3351 dependency: GlobalId,
3352 data_shard_since: Antichain<Timestamp>,
3353 write_frontier: Antichain<Timestamp>,
3354 dependency_since: Antichain<Timestamp>,
3355 ingestion_export: Option<CollectionMetadata>,
3357}
3358
3359pub async fn shard_has_no_updates(
3362 persist_client: &PersistClient,
3363 id: GlobalId,
3364 metadata: &CollectionMetadata,
3365) -> bool {
3366 let read_handle = persist_client
3367 .open_leased_reader::<SourceData, (), Timestamp, StorageDiff>(
3368 metadata.data_shard,
3369 Arc::new(metadata.relation_desc.clone()),
3370 Arc::new(UnitSchema),
3371 Diagnostics {
3372 shard_name: id.to_string(),
3373 handle_purpose: format!("checking {id} for updates"),
3374 },
3375 false,
3376 )
3377 .await
3378 .expect("invalid persist usage");
3379 let stats = read_handle
3380 .snapshot_stats(None)
3381 .await
3382 .expect("stats without an as_of cannot be behind the since");
3383 read_handle.expire().await;
3384 stats.num_updates == 0
3385}
3386
3387#[derive(Debug)]
3388pub(crate) enum SnapshotStatsAsOf {
3389 Direct(Antichain<Timestamp>),
3392 Txns(DataSnapshot<Timestamp>),
3395}
3396
3397#[cfg(test)]
3398mod tests {
3399 use std::str::FromStr;
3400 use std::sync::Arc;
3401
3402 use mz_build_info::DUMMY_BUILD_INFO;
3403 use mz_dyncfg::ConfigSet;
3404 use mz_ore::assert_err;
3405 use mz_ore::metrics::{MetricsRegistry, UIntGauge};
3406 use mz_ore::now::SYSTEM_TIME;
3407 use mz_ore::url::SensitiveUrl;
3408 use mz_persist_client::cache::PersistClientCache;
3409 use mz_persist_client::cfg::PersistConfig;
3410 use mz_persist_client::rpc::PubSubClientConnection;
3411 use mz_persist_client::{Diagnostics, PersistClient, PersistLocation, ShardId};
3412 use mz_persist_types::codec_impls::UnitSchema;
3413 use mz_repr::{RelationDesc, Row};
3414 use mz_secrets::InMemorySecretsController;
3415
3416 use super::*;
3417
3418 #[mz_ore::test]
3419 fn test_partition_finalizable_shards() {
3420 let active_shard = ShardId::new();
3421 let dropped_shard = ShardId::new();
3422 let collection_metadata = BTreeMap::from([
3423 (GlobalId::User(1), active_shard),
3424 (GlobalId::User(2), active_shard),
3425 (GlobalId::User(3), dropped_shard),
3426 ]);
3427 let active_collection_ids = BTreeSet::from([GlobalId::User(1), GlobalId::User(2)]);
3428 let unfinalized_shards = BTreeSet::from([active_shard, dropped_shard]);
3429
3430 let (referenced_shards, finalizable_shards) = partition_finalizable_shards(
3431 collection_metadata,
3432 &active_collection_ids,
3433 unfinalized_shards,
3434 );
3435
3436 assert_eq!(referenced_shards, BTreeSet::from([active_shard]));
3437 assert_eq!(finalizable_shards, BTreeSet::from([dropped_shard]));
3438 }
3439
3440 #[mz_ore::test(tokio::test)]
3441 #[cfg_attr(miri, ignore)] async fn test_snapshot_stats(&self) {
3443 let persist_location = PersistLocation {
3444 blob_uri: SensitiveUrl::from_str("mem://").expect("invalid URL"),
3445 consensus_uri: SensitiveUrl::from_str("mem://").expect("invalid URL"),
3446 };
3447 let persist_client = PersistClientCache::new(
3448 PersistConfig::new_default_configs(&DUMMY_BUILD_INFO, SYSTEM_TIME.clone()),
3449 &MetricsRegistry::new(),
3450 |_, _| PubSubClientConnection::noop(),
3451 );
3452 let persist_client = Arc::new(persist_client);
3453
3454 let (cmds_tx, mut background_task) =
3455 BackgroundTask::new_for_test(persist_location.clone(), Arc::clone(&persist_client));
3456 let background_task =
3457 mz_ore::task::spawn(|| "storage_collections::background_task", async move {
3458 background_task.run().await
3459 });
3460
3461 let persist = persist_client.open(persist_location).await.unwrap();
3462
3463 let shard_id = ShardId::new();
3464 let since_handle = persist
3465 .open_critical_since(
3466 shard_id,
3467 PersistClient::CONTROLLER_CRITICAL_SINCE,
3468 Opaque::encode(&PersistEpoch::default()),
3469 Diagnostics::for_tests(),
3470 )
3471 .await
3472 .unwrap();
3473 let write_handle = persist
3474 .open_writer::<SourceData, (), mz_repr::Timestamp, StorageDiff>(
3475 shard_id,
3476 Arc::new(RelationDesc::empty()),
3477 Arc::new(UnitSchema),
3478 Diagnostics::for_tests(),
3479 )
3480 .await
3481 .unwrap();
3482
3483 cmds_tx
3484 .send(BackgroundCmd::Register {
3485 id: GlobalId::User(1),
3486 is_in_txns: false,
3487 since_handle: SinceHandleWrapper::Critical(since_handle),
3488 write_handle,
3489 })
3490 .unwrap();
3491
3492 let mut write_handle = persist
3493 .open_writer::<SourceData, (), mz_repr::Timestamp, StorageDiff>(
3494 shard_id,
3495 Arc::new(RelationDesc::empty()),
3496 Arc::new(UnitSchema),
3497 Diagnostics::for_tests(),
3498 )
3499 .await
3500 .unwrap();
3501
3502 let stats =
3504 snapshot_stats(&cmds_tx, GlobalId::User(2), Antichain::from_elem(0.into())).await;
3505 assert_err!(stats);
3506
3507 let stats_fut = snapshot_stats(&cmds_tx, GlobalId::User(1), Antichain::from_elem(1.into()));
3509 assert_none!(stats_fut.now_or_never());
3510
3511 let stats_ts1_fut =
3513 snapshot_stats(&cmds_tx, GlobalId::User(1), Antichain::from_elem(1.into()));
3514
3515 let data = (
3517 (SourceData(Ok(Row::default())), ()),
3518 mz_repr::Timestamp::from(0),
3519 1i64,
3520 );
3521 let () = write_handle
3522 .compare_and_append(
3523 &[data],
3524 Antichain::from_elem(0.into()),
3525 Antichain::from_elem(1.into()),
3526 )
3527 .await
3528 .unwrap()
3529 .unwrap();
3530
3531 let stats = snapshot_stats(&cmds_tx, GlobalId::User(1), Antichain::from_elem(0.into()))
3533 .await
3534 .unwrap();
3535 assert_eq!(stats.num_updates, 1);
3536
3537 let data = (
3539 (SourceData(Ok(Row::default())), ()),
3540 mz_repr::Timestamp::from(1),
3541 1i64,
3542 );
3543 let () = write_handle
3544 .compare_and_append(
3545 &[data],
3546 Antichain::from_elem(1.into()),
3547 Antichain::from_elem(2.into()),
3548 )
3549 .await
3550 .unwrap()
3551 .unwrap();
3552
3553 let stats = stats_ts1_fut.await.unwrap();
3554 assert_eq!(stats.num_updates, 2);
3555
3556 drop(background_task);
3558 }
3559
3560 #[mz_ore::test(tokio::test)]
3563 #[cfg_attr(miri, ignore)] async fn test_snapshot_and_stream_keeps_reader() {
3565 let persist_clients = Arc::new(PersistClientCache::new_no_metrics());
3566 let location = PersistLocation::new_in_mem();
3567 let persist = persist_clients.open(location.clone()).await.unwrap();
3568 let metadata = CollectionMetadata {
3569 persist_location: location,
3570 data_shard: ShardId::new(),
3571 relation_desc: RelationDesc::empty(),
3572 txns_shard: None,
3573 };
3574
3575 let mut write_handle = persist
3576 .open_writer::<SourceData, (), mz_repr::Timestamp, StorageDiff>(
3577 metadata.data_shard,
3578 Arc::new(metadata.relation_desc.clone()),
3579 Arc::new(UnitSchema),
3580 Diagnostics::for_tests(),
3581 )
3582 .await
3583 .unwrap();
3584 let data = ((SourceData(Ok(Row::default())), ()), Timestamp::MIN, 1i64);
3585 let () = write_handle
3586 .compare_and_append(
3587 &[data],
3588 Antichain::from_elem(0.into()),
3589 Antichain::from_elem(1.into()),
3590 )
3591 .await
3592 .unwrap()
3593 .unwrap();
3594
3595 let readers = || async {
3596 let state = persist
3597 .inspect_shard::<mz_repr::Timestamp>(&metadata.data_shard)
3598 .await
3599 .unwrap();
3600 let state = serde_json::to_value(state).unwrap();
3601 state["leased_readers"].as_object().unwrap().len()
3602 };
3603
3604 let stream = StorageCollectionsImpl::snapshot_and_stream_inner(
3605 Arc::clone(&persist_clients),
3606 metadata.clone(),
3607 GlobalId::User(1),
3608 0.into(),
3609 None,
3610 )
3611 .await
3612 .unwrap();
3613 tokio::time::sleep(Duration::from_secs(1)).await;
3615 assert_eq!(readers().await, 1);
3616
3617 assert_eq!(stream.collect::<Vec<_>>().await.len(), 1);
3618 tokio::time::timeout(Duration::from_secs(30), async {
3619 while readers().await > 0 {
3620 tokio::time::sleep(Duration::from_millis(100)).await;
3621 }
3622 })
3623 .await
3624 .expect("reader expires with the stream");
3625 }
3626
3627 async fn snapshot_stats(
3628 cmds_tx: &mpsc::UnboundedSender<BackgroundCmd>,
3629 id: GlobalId,
3630 as_of: Antichain<Timestamp>,
3631 ) -> Result<SnapshotStats, StorageError> {
3632 let (tx, rx) = oneshot::channel();
3633 cmds_tx
3634 .send(BackgroundCmd::SnapshotStats(
3635 id,
3636 SnapshotStatsAsOf::Direct(as_of),
3637 tx,
3638 ))
3639 .unwrap();
3640 let res = rx.await.expect("BackgroundTask should be live").0;
3641
3642 res.await
3643 }
3644
3645 impl BackgroundTask {
3646 fn new_for_test(
3647 _persist_location: PersistLocation,
3648 _persist_client: Arc<PersistClientCache>,
3649 ) -> (mpsc::UnboundedSender<BackgroundCmd>, Self) {
3650 let (cmds_tx, cmds_rx) = mpsc::unbounded_channel();
3651 let (_holds_tx, holds_rx) = mpsc::unbounded_channel();
3652 let connection_context =
3653 ConnectionContext::for_tests(Arc::new(InMemorySecretsController::new()));
3654
3655 let task = Self {
3656 config: Arc::new(Mutex::new(StorageConfiguration::new(
3657 connection_context,
3658 ConfigSet::default(),
3659 ))),
3660 cmds_tx: cmds_tx.clone(),
3661 cmds_rx,
3662 holds_rx,
3663 finalizable_shards: Arc::new(ShardIdSet::new(
3664 UIntGauge::new("finalizable_shards", "dummy gauge for tests").unwrap(),
3665 )),
3666 collections: Arc::new(Mutex::new(BTreeMap::new())),
3667 shard_by_id: BTreeMap::new(),
3668 since_handles: BTreeMap::new(),
3669 txns_handle: None,
3670 txns_shards: BTreeSet::new(),
3671 };
3672
3673 (cmds_tx, task)
3674 }
3675 }
3676}