1use std::cell::RefCell;
80use std::collections::{BTreeMap, BTreeSet};
81use std::fmt;
82use std::rc::Rc;
83
84use mz_compute_types::dataflows::LirDataflowDescription;
85use mz_ore::collections::CollectionExt;
86use mz_ore::soft_panic_or_log;
87use mz_repr::{GlobalId, Timestamp};
88use mz_storage_client::storage_collections::StorageCollections;
89use mz_storage_types::read_holds::ReadHold;
90use mz_storage_types::read_policy::ReadPolicy;
91use timely::PartialOrder;
92use timely::progress::Antichain;
93use tracing::{info, warn};
94
95pub fn run(
104 dataflows: &mut [LirDataflowDescription],
105 read_policies: &BTreeMap<GlobalId, ReadPolicy>,
106 storage_collections: &dyn StorageCollections,
107 current_time: Timestamp,
108 read_only_mode: bool,
109 pending_replacements: &BTreeSet<GlobalId>,
110) -> BTreeMap<GlobalId, ReadHold> {
111 let mut storage_read_holds = BTreeMap::new();
114 for dataflow in &*dataflows {
115 for id in dataflow.source_imports.keys() {
116 if !storage_read_holds.contains_key(id) {
117 let read_hold = storage_collections
118 .acquire_read_holds(vec![*id])
119 .expect("storage collection exists")
120 .into_element();
121 storage_read_holds.insert(*id, read_hold);
122 }
123 }
124 }
125
126 let mut ctx = Context::new(dataflows, storage_collections, read_policies, current_time);
127
128 ctx.prune_sealed_persist_sinks();
132
133 if read_only_mode {
138 ctx.prune_dropped_collections();
139 }
140
141 ctx.apply_upstream_storage_constraints(&storage_read_holds);
143 ctx.apply_downstream_storage_constraints(pending_replacements);
144
145 ctx.apply_warmup_constraints();
161
162 ctx.apply_index_read_policy_constraints();
164
165 ctx.apply_index_current_time_constraints();
168
169 for dataflow in dataflows {
171 let first_export = dataflow.export_ids().next();
174 let as_of = first_export.map_or_else(Antichain::new, |id| ctx.best_as_of(id));
175 dataflow.as_of = Some(as_of);
176 }
177
178 storage_read_holds
179}
180
181#[derive(Debug)]
183struct AsOfBounds {
184 lower: Antichain<Timestamp>,
185 upper: Antichain<Timestamp>,
186 sealed: bool,
188}
189
190impl AsOfBounds {
191 fn single(frontier: Antichain<Timestamp>) -> Self {
193 Self {
194 lower: frontier.clone(),
195 upper: frontier,
196 sealed: false,
197 }
198 }
199
200 fn get(&self, type_: BoundType) -> &Antichain<Timestamp> {
202 match type_ {
203 BoundType::Lower => &self.lower,
204 BoundType::Upper => &self.upper,
205 }
206 }
207}
208
209impl Default for AsOfBounds {
210 fn default() -> Self {
211 Self {
212 lower: Antichain::from_elem(Timestamp::MIN),
213 upper: Antichain::new(),
214 sealed: false,
215 }
216 }
217}
218
219impl fmt::Display for AsOfBounds {
220 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
221 write!(
222 f,
223 "[{:?} .. {:?}]",
224 self.lower.elements(),
225 self.upper.elements()
226 )
227 }
228}
229
230#[derive(Clone, Copy, Debug, PartialEq, Eq)]
232enum BoundType {
233 Lower,
234 Upper,
235}
236
237impl fmt::Display for BoundType {
238 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
239 match self {
240 Self::Lower => f.write_str("lower"),
241 Self::Upper => f.write_str("upper"),
242 }
243 }
244}
245
246#[derive(Clone, Copy, Debug, PartialEq, Eq)]
248enum ConstraintType {
249 Hard,
252 Soft,
255}
256
257#[derive(Debug)]
259struct Constraint<'a> {
260 type_: ConstraintType,
261 bound_type: BoundType,
263 frontier: &'a Antichain<Timestamp>,
265 reason: &'a str,
269}
270
271impl Constraint<'_> {
272 fn apply(&self, bounds: &mut AsOfBounds) -> Result<bool, bool> {
282 if bounds.sealed {
283 return Ok(false);
284 }
285
286 match self.bound_type {
287 BoundType::Lower => {
288 if PartialOrder::less_than(&bounds.upper, self.frontier) {
289 bounds.sealed = true;
290 if PartialOrder::less_than(&bounds.lower, &bounds.upper) {
291 bounds.lower.clone_from(&bounds.upper);
292 Err(true)
293 } else {
294 Err(false)
295 }
296 } else if PartialOrder::less_equal(self.frontier, &bounds.lower) {
297 Ok(false)
298 } else {
299 bounds.lower.clone_from(self.frontier);
300 Ok(true)
301 }
302 }
303 BoundType::Upper => {
304 if PartialOrder::less_than(self.frontier, &bounds.lower) {
305 bounds.sealed = true;
306 if PartialOrder::less_than(&bounds.lower, &bounds.upper) {
307 bounds.upper.clone_from(&bounds.lower);
308 Err(true)
309 } else {
310 Err(false)
311 }
312 } else if PartialOrder::less_equal(&bounds.upper, self.frontier) {
313 Ok(false)
314 } else {
315 bounds.upper.clone_from(self.frontier);
316 Ok(true)
317 }
318 }
319 }
320 }
321}
322
323struct Collection<'a> {
325 storage_inputs: Vec<GlobalId>,
326 compute_inputs: Vec<GlobalId>,
327 read_policy: Option<&'a ReadPolicy>,
328 bounds: Rc<RefCell<AsOfBounds>>,
332 is_index: bool,
334}
335
336struct InputFrontier {
338 frontier: Antichain<Timestamp>,
339 substituted_for: Option<Antichain<Timestamp>>,
342}
343
344impl InputFrontier {
345 fn substitution_note(&self) -> String {
347 match &self.substituted_for {
348 Some(write_frontier) => format!(
349 " (current time, substituted for storage write frontier {:?} at which the inputs \
350 are not readable)",
351 write_frontier.elements()
352 ),
353 None => String::new(),
354 }
355 }
356}
357
358struct Context<'a> {
360 collections: BTreeMap<GlobalId, Collection<'a>>,
361 storage_collections: &'a dyn StorageCollections,
362 current_time: Timestamp,
363}
364
365impl<'a> Context<'a> {
366 fn new(
368 dataflows: &[LirDataflowDescription],
369 storage_collections: &'a dyn StorageCollections,
370 read_policies: &'a BTreeMap<GlobalId, ReadPolicy>,
371 current_time: Timestamp,
372 ) -> Self {
373 let mut collections = BTreeMap::new();
376 for dataflow in dataflows {
377 let storage_inputs: Vec<_> = dataflow.source_imports.keys().copied().collect();
378 let compute_inputs: Vec<_> = dataflow.index_imports.keys().copied().collect();
379
380 let bounds = match dataflow.as_of.clone() {
381 Some(frontier) => AsOfBounds::single(frontier),
382 None => AsOfBounds::default(),
383 };
384 let bounds = Rc::new(RefCell::new(bounds));
385
386 for id in dataflow.export_ids() {
387 let collection = Collection {
388 storage_inputs: storage_inputs.clone(),
389 compute_inputs: compute_inputs.clone(),
390 read_policy: read_policies.get(&id),
391 bounds: Rc::clone(&bounds),
392 is_index: dataflow.index_exports.contains_key(&id),
393 };
394 collections.insert(id, collection);
395 }
396 }
397
398 Self {
399 collections,
400 storage_collections,
401 current_time,
402 }
403 }
404
405 fn expect_collection(&self, id: GlobalId) -> &Collection<'_> {
411 self.collections
412 .get(&id)
413 .unwrap_or_else(|| panic!("collection missing: {id}"))
414 }
415
416 fn apply_constraint(&self, id: GlobalId, constraint: Constraint) -> bool {
420 let collection = self.expect_collection(id);
421 let mut bounds = collection.bounds.borrow_mut();
422 match constraint.apply(&mut bounds) {
423 Ok(changed) => {
424 if changed {
425 info!(%id, %bounds, reason = %constraint.reason, "applied as-of constraint");
426 }
427 changed
428 }
429 Err(changed) => {
430 match constraint.type_ {
431 ConstraintType::Hard => {
432 soft_panic_or_log!(
433 "failed to apply hard as-of constraint \
434 (id={id}, bounds={bounds}, constraint={constraint:?})"
435 );
436 }
437 ConstraintType::Soft => {
438 info!(%id, %bounds, ?constraint, "failed to apply soft as-of constraint");
439 }
440 }
441 changed
442 }
443 }
444 }
445
446 fn apply_upstream_storage_constraints(
454 &self,
455 storage_read_holds: &BTreeMap<GlobalId, ReadHold>,
456 ) {
457 for (id, collection) in &self.collections {
459 for input_id in &collection.storage_inputs {
460 let read_hold = &storage_read_holds[input_id];
461 let constraint = Constraint {
462 type_: ConstraintType::Hard,
463 bound_type: BoundType::Lower,
464 frontier: read_hold.since(),
465 reason: &format!("storage input {input_id} read frontier"),
466 };
467 self.apply_constraint(*id, constraint);
468 }
469 }
470
471 self.propagate_bounds_downstream(BoundType::Lower);
473 }
474
475 fn apply_downstream_storage_constraints(&self, pending_replacements: &BTreeSet<GlobalId>) {
502 for id in self.collections.keys() {
504 let Ok(frontiers) = self.storage_collections.collection_frontiers(*id) else {
505 continue;
506 };
507
508 let collection_empty =
509 PartialOrder::less_equal(&frontiers.write_frontier, &frontiers.read_capabilities);
510 let upper = if collection_empty {
511 frontiers.read_capabilities
512 } else {
513 step_back_frontier(&frontiers.write_frontier)
514 };
515
516 let type_ = if pending_replacements.contains(id) {
522 ConstraintType::Soft
523 } else {
524 ConstraintType::Hard
525 };
526 let constraint = Constraint {
527 type_,
528 bound_type: BoundType::Upper,
529 frontier: &upper,
530 reason: &format!("storage export {id} write frontier"),
531 };
532 self.apply_constraint(*id, constraint);
533 }
534
535 self.propagate_bounds_upstream(BoundType::Upper);
537 }
538
539 fn apply_warmup_constraints(&self) {
548 for (id, input) in self.input_frontiers() {
550 let upper = step_back_frontier(&input.frontier);
551 let constraint = Constraint {
552 type_: ConstraintType::Soft,
553 bound_type: BoundType::Upper,
554 frontier: &upper,
555 reason: &format!(
556 "warmup frontier derived from storage write frontier {:?}{}",
557 input.frontier.elements(),
558 input.substitution_note(),
559 ),
560 };
561 self.apply_constraint(id, constraint);
562 }
563
564 self.propagate_bounds_upstream(BoundType::Upper);
566 }
567
568 fn apply_index_read_policy_constraints(&self) {
578 let mut input_frontiers = self.input_frontiers();
582
583 for (id, collection) in &self.collections {
585 if let (true, Some(read_policy)) = (collection.is_index, &collection.read_policy) {
586 let input = input_frontiers.remove(id).expect("inserted above");
587 let mut write_frontier = input.frontier.clone();
588 if write_frontier.is_empty() {
589 write_frontier = Antichain::from_elem(self.current_time.clone());
590 }
591 let upper = read_policy.frontier(write_frontier.borrow());
592 let constraint = Constraint {
593 type_: ConstraintType::Soft,
594 bound_type: BoundType::Upper,
595 frontier: &upper,
596 reason: &format!(
597 "read policy applied to write frontier {:?}{}",
598 write_frontier.elements(),
599 input.substitution_note(),
600 ),
601 };
602 self.apply_constraint(*id, constraint);
603 }
604 }
605
606 self.propagate_bounds_upstream(BoundType::Upper);
608 }
609
610 fn transitive_storage_write_frontiers(&self) -> BTreeMap<GlobalId, Antichain<Timestamp>> {
613 let mut write_frontiers = BTreeMap::new();
615 for (id, collection) in &self.collections {
616 let storage_frontiers = self
617 .storage_collections
618 .collections_frontiers(collection.storage_inputs.clone())
619 .expect("storage collections exist");
620
621 let mut write_frontier = Antichain::new();
622 for frontiers in storage_frontiers {
623 write_frontier.extend(frontiers.write_frontier);
624 }
625
626 write_frontiers.insert(*id, write_frontier);
627 }
628
629 fixpoint(|changed| {
631 for (id, collection) in &self.collections {
632 let mut write_frontier = write_frontiers.remove(id).expect("inserted above");
633 for input_id in &collection.compute_inputs {
634 let frontier = &write_frontiers[input_id];
635 *changed |= write_frontier.extend(frontier.iter().cloned());
636 }
637 write_frontiers.insert(*id, write_frontier);
638 }
639 });
640
641 write_frontiers
642 }
643
644 fn input_frontiers(&self) -> BTreeMap<GlobalId, InputFrontier> {
649 let after_current_time = self
658 .current_time
659 .checked_add(1)
660 .map_or_else(Antichain::new, Antichain::from_elem);
661 self.transitive_storage_write_frontiers()
662 .into_iter()
663 .map(|(id, write_frontier)| {
664 let bounds = self.expect_collection(id).bounds.borrow();
665 let input = if PartialOrder::less_equal(&write_frontier, &bounds.lower) {
666 InputFrontier {
667 frontier: after_current_time.clone(),
668 substituted_for: Some(write_frontier),
669 }
670 } else {
671 InputFrontier {
672 frontier: write_frontier,
673 substituted_for: None,
674 }
675 };
676 (id, input)
677 })
678 .collect()
679 }
680
681 fn apply_index_current_time_constraints(&self) {
688 let upper = Antichain::from_elem(self.current_time.clone());
690 for (id, collection) in &self.collections {
691 if collection.is_index {
692 let constraint = Constraint {
693 type_: ConstraintType::Soft,
694 bound_type: BoundType::Upper,
695 frontier: &upper,
696 reason: "index current time",
697 };
698 self.apply_constraint(*id, constraint);
699 }
700 }
701
702 self.propagate_bounds_upstream(BoundType::Upper);
704 }
705
706 fn propagate_bounds_downstream(&self, bound_type: BoundType) {
708 let constraint_type = match bound_type {
711 BoundType::Lower => ConstraintType::Hard,
712 BoundType::Upper => ConstraintType::Soft,
713 };
714
715 fixpoint(|changed| {
718 self.propagate_bounds_downstream_inner(bound_type, constraint_type, changed);
719
720 if bound_type == BoundType::Upper {
723 self.propagate_bounds_upstream_inner(
724 BoundType::Upper,
725 ConstraintType::Hard,
726 changed,
727 );
728 }
729 });
730 }
731
732 fn propagate_bounds_downstream_inner(
733 &self,
734 bound_type: BoundType,
735 constraint_type: ConstraintType,
736 changed: &mut bool,
737 ) {
738 for (id, collection) in &self.collections {
739 for input_id in &collection.compute_inputs {
740 let input_collection = self.expect_collection(*input_id);
741 let bounds = input_collection.bounds.borrow();
742 let constraint = Constraint {
743 type_: constraint_type,
744 bound_type,
745 frontier: bounds.get(bound_type),
746 reason: &format!("upstream {input_id} {bound_type} as-of bound"),
747 };
748 *changed |= self.apply_constraint(*id, constraint);
749 }
750 }
751 }
752
753 fn propagate_bounds_upstream(&self, bound_type: BoundType) {
755 let constraint_type = match bound_type {
758 BoundType::Lower => ConstraintType::Soft,
759 BoundType::Upper => ConstraintType::Hard,
760 };
761
762 fixpoint(|changed| {
765 self.propagate_bounds_upstream_inner(bound_type, constraint_type, changed);
766
767 if bound_type == BoundType::Lower {
770 self.propagate_bounds_downstream_inner(
771 BoundType::Lower,
772 ConstraintType::Hard,
773 changed,
774 );
775 }
776 });
777 }
778
779 fn propagate_bounds_upstream_inner(
780 &self,
781 bound_type: BoundType,
782 constraint_type: ConstraintType,
783 changed: &mut bool,
784 ) {
785 for (id, collection) in self.collections.iter().rev() {
786 let bounds = collection.bounds.borrow();
787 for input_id in &collection.compute_inputs {
788 let constraint = Constraint {
789 type_: constraint_type,
790 bound_type,
791 frontier: bounds.get(bound_type),
792 reason: &format!("downstream {id} {bound_type} as-of bound"),
793 };
794 *changed |= self.apply_constraint(*input_id, constraint);
795 }
796 }
797 }
798
799 fn best_as_of(&self, id: GlobalId) -> Antichain<Timestamp> {
806 if let Some(collection) = self.collections.get(&id) {
807 let bounds = collection.bounds.borrow();
808 bounds.upper.clone()
809 } else {
810 Antichain::new()
811 }
812 }
813
814 fn prune_sealed_persist_sinks(&mut self) {
822 self.collections.retain(|id, _| {
823 self.storage_collections
824 .collection_frontiers(*id)
825 .map_or(true, |f| !f.write_frontier.is_empty())
826 });
827 }
828
829 fn prune_dropped_collections(&mut self) {
836 let mut pruned = BTreeSet::new();
838 self.collections.retain(|id, c| {
839 let input_dropped = c.storage_inputs.iter().any(|id| {
840 let frontiers = self
841 .storage_collections
842 .collection_frontiers(*id)
843 .expect("storage collection exists");
844 frontiers.read_capabilities.is_empty()
845 });
846
847 if input_dropped {
848 pruned.insert(*id);
849 false
850 } else {
851 true
852 }
853 });
854
855 warn!(?pruned, "pruned dependants of dropped storage collections");
856
857 while !pruned.is_empty() {
859 let pruned_inputs = std::mem::take(&mut pruned);
860
861 self.collections.retain(|id, c| {
862 if c.compute_inputs.iter().any(|id| pruned_inputs.contains(id)) {
863 pruned.insert(*id);
864 false
865 } else {
866 true
867 }
868 });
869
870 warn!(?pruned, "pruned collections with pruned inputs");
871 }
872 }
873}
874
875fn fixpoint(mut step: impl FnMut(&mut bool)) {
877 loop {
878 let mut changed = false;
879 step(&mut changed);
880 if !changed {
881 break;
882 }
883 }
884}
885
886fn step_back_frontier(frontier: &Antichain<Timestamp>) -> Antichain<Timestamp> {
891 frontier
892 .iter()
893 .map(|t| t.step_back().unwrap_or(Timestamp::MIN))
894 .collect()
895}
896
897#[cfg(test)]
898mod tests {
899 use std::collections::BTreeSet;
900
901 use async_trait::async_trait;
902 use futures::future::BoxFuture;
903 use futures::stream::BoxStream;
904 use mz_compute_types::dataflows::{DataflowDescription, IndexDesc, IndexImport};
905 use mz_compute_types::sinks::ComputeSinkConnection;
906 use mz_compute_types::sinks::ComputeSinkDesc;
907 use mz_compute_types::sinks::MaterializedViewSinkConnection;
908 use mz_compute_types::sinks::MetricSinkConnection;
909 use mz_compute_types::sources::SourceInstanceArguments;
910 use mz_compute_types::sources::SourceInstanceDesc;
911 use mz_persist_client::stats::{SnapshotPartsStats, SnapshotStats};
912 use mz_persist_types::ShardId;
913 use mz_repr::{RelationDesc, RelationVersion, Row, SqlRelationType};
914 use mz_repr::{ReprRelationType, Timestamp};
915 use mz_storage_client::client::TimestamplessUpdateBuilder;
916 use mz_storage_client::controller::{CollectionDescription, StorageMetadata, StorageTxn};
917 use mz_storage_client::storage_collections::{CollectionFrontiers, SnapshotCursor};
918 use mz_storage_types::StorageDiff;
919 use mz_storage_types::controller::{CollectionMetadata, StorageError};
920 use mz_storage_types::errors::CollectionMissing;
921 use mz_storage_types::parameters::StorageParameters;
922 use mz_storage_types::sources::SourceData;
923 use mz_storage_types::time_dependence::{TimeDependence, TimeDependenceError};
924
925 use super::*;
926
927 const SEALED: u64 = 0x5ea1ed;
928
929 fn ts_to_frontier(ts: u64) -> Antichain<Timestamp> {
930 if ts == SEALED {
931 Antichain::new()
932 } else {
933 Antichain::from_elem(ts.into())
934 }
935 }
936
937 #[derive(Debug)]
938 struct StorageFrontiers(BTreeMap<GlobalId, (Antichain<Timestamp>, Antichain<Timestamp>)>);
939
940 #[async_trait]
941 impl StorageCollections for StorageFrontiers {
942 async fn initialize_state(
943 &self,
944 _txn: &mut (dyn StorageTxn + Send),
945 _init_ids: BTreeSet<GlobalId>,
946 ) -> Result<(), StorageError> {
947 unimplemented!()
948 }
949
950 fn update_parameters(&self, _config_params: StorageParameters) {
951 unimplemented!()
952 }
953
954 fn collection_metadata(
955 &self,
956 _id: GlobalId,
957 ) -> Result<CollectionMetadata, CollectionMissing> {
958 unimplemented!()
959 }
960
961 fn active_collection_metadatas(&self) -> Vec<(GlobalId, CollectionMetadata)> {
962 unimplemented!()
963 }
964
965 fn collections_frontiers(
966 &self,
967 ids: Vec<GlobalId>,
968 ) -> Result<Vec<CollectionFrontiers>, CollectionMissing> {
969 let mut frontiers = Vec::with_capacity(ids.len());
970 for id in ids {
971 let (read, write) = self.0.get(&id).ok_or(CollectionMissing(id))?;
972 frontiers.push(CollectionFrontiers {
973 id,
974 write_frontier: write.clone(),
975 implied_capability: read.clone(),
976 read_capabilities: read.clone(),
977 })
978 }
979 Ok(frontiers)
980 }
981
982 fn active_collection_frontiers(&self) -> Vec<CollectionFrontiers> {
983 unimplemented!()
984 }
985
986 fn check_exists(&self, _id: GlobalId) -> Result<(), StorageError> {
987 unimplemented!()
988 }
989
990 async fn snapshot_stats(
991 &self,
992 _id: GlobalId,
993 _as_of: Antichain<Timestamp>,
994 ) -> Result<SnapshotStats, StorageError> {
995 unimplemented!()
996 }
997
998 async fn snapshot_parts_stats(
999 &self,
1000 _id: GlobalId,
1001 _as_of: Antichain<Timestamp>,
1002 ) -> BoxFuture<'static, Result<SnapshotPartsStats, StorageError>> {
1003 unimplemented!()
1004 }
1005
1006 fn snapshot(
1007 &self,
1008 _id: GlobalId,
1009 _as_of: Timestamp,
1010 ) -> BoxFuture<'static, Result<Vec<(Row, StorageDiff)>, StorageError>> {
1011 unimplemented!()
1012 }
1013
1014 async fn snapshot_latest(&self, _id: GlobalId) -> Result<Vec<Row>, StorageError> {
1015 unimplemented!()
1016 }
1017
1018 fn snapshot_cursor(
1019 &self,
1020 _id: GlobalId,
1021 _as_of: Timestamp,
1022 ) -> BoxFuture<'static, Result<SnapshotCursor, StorageError>> {
1023 unimplemented!()
1024 }
1025
1026 fn snapshot_and_stream(
1027 &self,
1028 _id: GlobalId,
1029 _as_of: Timestamp,
1030 ) -> BoxFuture<
1031 'static,
1032 Result<BoxStream<'static, (SourceData, Timestamp, StorageDiff)>, StorageError>,
1033 > {
1034 unimplemented!()
1035 }
1036
1037 fn create_update_builder(
1038 &self,
1039 _id: GlobalId,
1040 ) -> BoxFuture<
1041 'static,
1042 Result<TimestamplessUpdateBuilder<SourceData, (), StorageDiff>, StorageError>,
1043 > {
1044 unimplemented!()
1045 }
1046
1047 async fn prepare_state(
1048 &self,
1049 _txn: &mut (dyn StorageTxn + Send),
1050 _ids_to_add: BTreeSet<GlobalId>,
1051 _ids_to_drop: BTreeSet<GlobalId>,
1052 _ids_to_register: BTreeMap<GlobalId, ShardId>,
1053 ) -> Result<(), StorageError> {
1054 unimplemented!()
1055 }
1056
1057 async fn create_collections_for_bootstrap(
1058 &self,
1059 _storage_metadata: &StorageMetadata,
1060 _register_ts: Option<Timestamp>,
1061 _collections: Vec<(GlobalId, CollectionDescription)>,
1062 _migrated_storage_collections: &BTreeSet<GlobalId>,
1063 ) -> Result<(), StorageError> {
1064 unimplemented!()
1065 }
1066
1067 async fn alter_table_desc(
1068 &self,
1069 _existing_collection: GlobalId,
1070 _new_collection: GlobalId,
1071 _new_desc: RelationDesc,
1072 _expected_version: RelationVersion,
1073 ) -> Result<(), StorageError> {
1074 unimplemented!()
1075 }
1076
1077 fn drop_collections_unvalidated(
1078 &self,
1079 _storage_metadata: &StorageMetadata,
1080 _identifiers: Vec<GlobalId>,
1081 ) {
1082 unimplemented!()
1083 }
1084
1085 fn set_read_policies(&self, _policies: Vec<(GlobalId, ReadPolicy)>) {
1086 unimplemented!()
1087 }
1088
1089 fn acquire_read_holds(
1090 &self,
1091 desired_holds: Vec<GlobalId>,
1092 ) -> Result<Vec<ReadHold>, CollectionMissing> {
1093 let mut holds = Vec::with_capacity(desired_holds.len());
1094 for id in desired_holds {
1095 let (read, _write) = self.0.get(&id).ok_or(CollectionMissing(id))?;
1096 let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
1097 holds.push(ReadHold::with_channel(id, read.clone(), tx));
1098 }
1099 Ok(holds)
1100 }
1101
1102 fn determine_time_dependence(
1103 &self,
1104 _id: GlobalId,
1105 ) -> Result<Option<TimeDependence>, TimeDependenceError> {
1106 unimplemented!()
1107 }
1108
1109 fn dump(&self) -> Result<serde_json::Value, anyhow::Error> {
1110 unimplemented!()
1111 }
1112 }
1113
1114 fn dataflow(
1115 export_id: &str,
1116 input_ids: &[&str],
1117 storage_ids: &BTreeSet<&str>,
1118 metric_sink_ids: &BTreeSet<&str>,
1119 ) -> LirDataflowDescription {
1120 let source_imports = input_ids
1121 .iter()
1122 .filter(|s| storage_ids.contains(*s))
1123 .map(|s| {
1124 let id = s.parse().unwrap();
1125 let desc = SourceInstanceDesc {
1126 arguments: SourceInstanceArguments {
1127 operators: Default::default(),
1128 },
1129 storage_metadata: Default::default(),
1130 typ: SqlRelationType::empty(),
1131 };
1132 (
1133 id,
1134 mz_compute_types::dataflows::SourceImport {
1135 desc,
1136 monotonic: Default::default(),
1137 with_snapshot: true,
1138 upper: Default::default(),
1139 },
1140 )
1141 })
1142 .collect();
1143 let index_imports = input_ids
1144 .iter()
1145 .filter(|s| !storage_ids.contains(*s))
1146 .map(|s| {
1147 let id = s.parse().unwrap();
1148 let import = IndexImport {
1149 desc: IndexDesc {
1150 on_id: GlobalId::Transient(0),
1151 key: Default::default(),
1152 },
1153 typ: ReprRelationType::empty(),
1154 monotonic: Default::default(),
1155 with_snapshot: true,
1156 };
1157 (id, import)
1158 })
1159 .collect();
1160 let index_exports = std::iter::once(export_id)
1161 .filter(|s| !storage_ids.contains(*s) && !metric_sink_ids.contains(*s))
1162 .map(|sid| {
1163 let id = sid.parse().unwrap();
1164 let desc = IndexDesc {
1165 on_id: GlobalId::Transient(0),
1166 key: Default::default(),
1167 };
1168 let typ = ReprRelationType::empty();
1169 (id, (desc, typ))
1170 })
1171 .collect();
1172 let sink_exports = std::iter::once(export_id)
1173 .filter(|s| storage_ids.contains(*s) || metric_sink_ids.contains(*s))
1174 .map(|sid| {
1175 let id = sid.parse().unwrap();
1176 let connection = if metric_sink_ids.contains(sid) {
1177 ComputeSinkConnection::MetricSink(MetricSinkConnection { label: sid.into() })
1178 } else {
1179 ComputeSinkConnection::MaterializedView(MaterializedViewSinkConnection {
1180 value_desc: RelationDesc::empty(),
1181 storage_metadata: Default::default(),
1182 })
1183 };
1184 let desc = ComputeSinkDesc {
1185 from: GlobalId::Transient(0),
1186 from_desc: RelationDesc::empty(),
1187 connection,
1188 with_snapshot: Default::default(),
1189 up_to: Default::default(),
1190 non_null_assertions: Default::default(),
1191 refresh_schedule: Default::default(),
1192 from_arrangement: None,
1193 };
1194 (id, desc)
1195 })
1196 .collect();
1197
1198 DataflowDescription {
1199 source_imports,
1200 index_imports,
1201 objects_to_build: Default::default(),
1202 index_exports,
1203 sink_exports,
1204 as_of: None,
1205 until: Default::default(),
1206 initial_storage_as_of: Default::default(),
1207 refresh_schedule: Default::default(),
1208 debug_name: Default::default(),
1209 time_dependence: None,
1210 }
1211 }
1212
1213 macro_rules! testcase {
1214 ($name:ident, {
1215 storage: { $( $storage_id:literal: ($read:expr, $write:expr), )* },
1216 dataflows: [ $( $export_id:literal <- $inputs:expr => $as_of:expr, )* ],
1217 current_time: $current_time:literal,
1218 $( read_policies: { $( $policy_id:literal: $policy:expr, )* }, )?
1219 $( read_only: $read_only:expr, )?
1220 $( pending_replacements: [ $( $replacement_id:literal, )* ], )?
1221 $( metric_sinks: [ $( $metric_sink_id:literal, )* ], )?
1222 }) => {
1223 #[mz_ore::test]
1224 fn $name() {
1225 let storage_ids = [$( $storage_id, )*].into();
1226 let metric_sink_ids = [$($( $metric_sink_id, )*)?].into();
1227
1228 let storage_frontiers = StorageFrontiers(BTreeMap::from([
1229 $(
1230 (
1231 $storage_id.parse().unwrap(),
1232 (ts_to_frontier($read), ts_to_frontier($write)),
1233 ),
1234 )*
1235 ]));
1236
1237 let mut dataflows = [
1238 $(
1239 dataflow($export_id, &$inputs, &storage_ids, &metric_sink_ids),
1240 )*
1241 ];
1242
1243 let read_policies = BTreeMap::from([
1244 $($( ($policy_id.parse().unwrap(), $policy), )*)?
1245 ]);
1246
1247 #[allow(unused_variables)]
1248 let read_only = false;
1249 $( let read_only = $read_only; )?
1250
1251 let pending_replacements = BTreeSet::from([
1252 $($( $replacement_id.parse().unwrap(), )*)?
1253 ]);
1254
1255 super::run(
1256 &mut dataflows,
1257 &read_policies,
1258 &storage_frontiers,
1259 $current_time.into(),
1260 read_only,
1261 &pending_replacements,
1262 );
1263
1264 let actual_as_ofs: Vec<_> = dataflows
1265 .into_iter()
1266 .map(|d| d.as_of.unwrap())
1267 .collect();
1268 let expected_as_ofs = [ $( ts_to_frontier($as_of), )* ];
1269
1270 assert_eq!(actual_as_ofs, expected_as_ofs);
1271 }
1272 };
1273 }
1274
1275 testcase!(upstream_storage_constraints, {
1276 storage: {
1277 "s1": (10, 20),
1278 "s2": (20, 30),
1279 },
1280 dataflows: [
1281 "u1" <- ["s1"] => 10,
1282 "u2" <- ["s2"] => 20,
1283 "u3" <- ["s1", "s2"] => 20,
1284 "u4" <- ["u1", "u2"] => 20,
1285 ],
1286 current_time: 0,
1287 });
1288
1289 testcase!(downstream_storage_constraints, {
1290 storage: {
1291 "s1": (10, 20),
1292 "u3": (10, 15),
1293 "u4": (10, 13),
1294 },
1295 dataflows: [
1296 "u1" <- ["s1"] => 19,
1297 "u2" <- ["s1"] => 12,
1298 "u3" <- ["u2"] => 14,
1299 "u4" <- ["u2"] => 12,
1300 ],
1301 current_time: 100,
1302 });
1303
1304 testcase!(warmup_constraints, {
1305 storage: {
1306 "s1": (10, 20),
1307 "s2": (10, 30),
1308 "s3": (10, 40),
1309 "s4": (10, 50),
1310 },
1311 dataflows: [
1312 "u1" <- ["s1"] => 19,
1313 "u2" <- ["s2"] => 19,
1314 "u3" <- ["s3"] => 39,
1315 "u4" <- ["s4"] => 39,
1316 "u5" <- ["u1", "u2"] => 19,
1317 "u6" <- ["u3", "u4"] => 39,
1318 ],
1319 current_time: 100,
1320 });
1321
1322 testcase!(index_read_policy_constraints, {
1323 storage: {
1324 "s1": (10, 20),
1325 "u6": (10, 18),
1326 },
1327 dataflows: [
1328 "u1" <- ["s1"] => 15,
1329 "u2" <- ["s1"] => 10,
1330 "u3" <- ["s1"] => 13,
1331 "u4" <- ["s1"] => 10,
1332 "u5" <- [] => 95,
1333 "u6" <- ["s1"] => 17,
1334 ],
1335 current_time: 100,
1336 read_policies: {
1337 "u1": ReadPolicy::lag_writes_by(5.into(), 1.into()),
1338 "u2": ReadPolicy::lag_writes_by(15.into(), 1.into()),
1339 "u3": ReadPolicy::ValidFrom(Antichain::from_elem(13.into())),
1340 "u4": ReadPolicy::ValidFrom(Antichain::from_elem(5.into())),
1341 "u5": ReadPolicy::lag_writes_by(5.into(), 1.into()),
1342 "u6": ReadPolicy::ValidFrom(Antichain::from_elem(13.into())),
1343 },
1344 });
1345
1346 testcase!(index_current_time_constraints, {
1347 storage: {
1348 "s1": (10, 20),
1349 "s2": (20, 30),
1350 "u4": (10, 12),
1351 "u5": (10, 18),
1352 },
1353 dataflows: [
1354 "u1" <- ["s1"] => 15,
1355 "u2" <- ["s2"] => 20,
1356 "u3" <- ["s1"] => 11,
1357 "u4" <- ["u3"] => 11,
1358 "u5" <- ["s1"] => 17,
1359 "u6" <- [] => 15,
1360 ],
1361 current_time: 15,
1362 });
1363
1364 testcase!(sealed_storage_sink, {
1365 storage: {
1366 "s1": (10, 20),
1367 "u1": (10, SEALED),
1368 },
1369 dataflows: [
1370 "u1" <- ["s1"] => SEALED,
1371 ],
1372 current_time: 100,
1373 });
1374
1375 testcase!(read_only_dropped_storage_inputs, {
1376 storage: {
1377 "s1": (10, 20),
1378 "s2": (SEALED, SEALED),
1379 "u4": (10, 20),
1380 },
1381 dataflows: [
1382 "u1" <- ["s1"] => 15,
1383 "u2" <- ["s2"] => SEALED,
1384 "u3" <- ["s1", "s2"] => SEALED,
1385 "u4" <- ["u2"] => SEALED,
1386 ],
1387 current_time: 15,
1388 read_only: true,
1389 });
1390
1391 testcase!(pending_replacements, {
1395 storage: {
1396 "s1": (10, 30),
1397 "s2": (20, 30),
1398 "u2": (10, 15),
1399 "u3": (10, 15),
1400 },
1401 dataflows: [
1402 "u2" <- ["s2"] => 20,
1403 "u3" <- ["s1"] => 14,
1404 ],
1405 current_time: 100,
1406 pending_replacements: ["u2", "u3",],
1407 });
1408
1409 testcase!(stuck_input_without_readable_data, {
1413 storage: {
1414 "s1": (10, 100),
1415 "u1": (10, 10),
1416 },
1417 dataflows: [
1418 "u1" <- ["s1"] => 10,
1419 "u2" <- ["s1"] => 99,
1420 "u3" <- ["u2", "u1"] => 100,
1421 ],
1422 current_time: 100,
1423 });
1424
1425 testcase!(stuck_input_constant_compute_input, {
1428 storage: {
1429 "s1": (10, 10),
1430 },
1431 dataflows: [
1432 "u1" <- [] => 100,
1433 "u2" <- ["s1", "u1"] => 100,
1434 ],
1435 current_time: 100,
1436 });
1437
1438 testcase!(stuck_input_metric_sink, {
1441 storage: {
1442 "s1": (10, 100),
1443 "u1": (10, 10),
1444 },
1445 dataflows: [
1446 "u1" <- ["s1"] => 10,
1447 "u2" <- ["u1"] => 100,
1448 ],
1449 current_time: 100,
1450 metric_sinks: ["u2",],
1451 });
1452
1453 testcase!(stuck_input_with_readable_data, {
1457 storage: {
1458 "s1": (7, 100),
1459 "u1": (5, 8),
1460 },
1461 dataflows: [
1462 "u1" <- ["s1"] => 7,
1463 "u2" <- ["s1"] => 7,
1464 "u3" <- ["u2", "u1"] => 7,
1465 ],
1466 current_time: 100,
1467 });
1468
1469 testcase!(github_9273, {
1471 storage: {
1472 "s1": (10, 20),
1473 "u3": (14, 15),
1474 },
1475 dataflows: [
1476 "u1" <- ["s1"] => 14,
1477 "u2" <- ["u1"] => 19,
1478 "u3" <- ["u1"] => 14,
1479 ],
1480 current_time: 100,
1481 read_policies: {
1482 "u1": ReadPolicy::lag_writes_by(1.into(), 1.into()),
1483 "u2": ReadPolicy::lag_writes_by(1.into(), 1.into()),
1484 },
1485 });
1486}