Skip to main content

mz_compute_client/
as_of_selection.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! Support for selecting as-ofs of compute dataflows during system initialization.
11//!
12//! The functionality implemented here is invoked by the coordinator during its bootstrap process.
13//! Ideally, it would be part of the controller and transparent to the coordinator, but that's
14//! difficult to reconcile with the current controller API. For now, we still make the coordinator
15//! worry about as-of selection but keep the implementation in a compute crate because it really is
16//! a compute implementation concern.
17//!
18//! The as-of selection process takes a list of `DataflowDescription`s, determines compatible
19//! as-ofs for the compute collections they export, and augments the `DataflowDescription`s with
20//! these as-ofs.
21//!
22//! For each compute collection, the as-of selection process keeps an `AsOfBounds` instance that
23//! tracks a lower and an upper bound for the as-of the collection may get assigned. Throughout the
24//! process, a collection's `AsOfBounds` get repeatedly refined, by increasing the lower bound and
25//! decreasing the upper bound. The final upper bound is then used for the collection as-of. Using
26//! the upper bound maximizes the chances of compute reconciliation being effective, and minimizes
27//! the amount of historical data that must be read from the dataflow sources.
28//!
29//! Refinement of `AsOfBounds` is performed by applying `Constraint`s to collections. A
30//! `Constraint` specifies which bound should be refined to which frontier. A `Constraint` may be
31//! "hard" or "soft", which determines how failure to apply it is handled. Failing to apply a hard
32//! constraint is treated as an error, failing to apply a soft constraint is not. If a constraint
33//! fails to apply, the respective `AsOfBounds` are refined as much as possible (to a single
34//! frontier) and marked as "sealed". Subsequent constraint applications against the sealed bounds
35//! are no-ops. This is done to avoid log noise from repeated constraint application failures.
36//!
37//! Note that failing to apply a hard constraint does not abort the as-of selection process for the
38//! affected collection. Instead the failure is handled gracefully by logging an error and
39//! assigning the collection a best-effort as-of. This is done, rather than panicking or returning
40//! an error and letting the coordinator panic, to ensure the availability of the system. Ideally,
41//! we would instead mark the affected dataflow as failed/poisoned, but such a mechanism doesn't
42//! currently exist.
43//!
44//! The as-of selection process applies constraints in order of importance, because once a
45//! constraint application fails, the respective `AsOfBounds` are sealed and later applications
46//! won't have any effect. This means hard constraints must be applied before soft constraints, and
47//! more desirable soft constraints should be applied before less desirable ones.
48//!
49//! # `AsOfBounds` Invariants
50//!
51//! Correctness requires two invariants of `AsOfBounds` of dependent collections:
52//!
53//!  (1) The lower bound of a collection is >= the lower bound of each of its inputs.
54//!  (2) The upper bound of a collection is >= the upper bound of each of its inputs.
55//!
56//! Each step of the as-of selection process needs to ensure that these invariants are upheld once
57//! it completes. The expectation is that each step (a) performs local changes to either the
58//! `lower` _or_ the `upper` bounds of some collections and (b) invokes the appropriate
59//! `propagate_bounds_*` method to restore the invariant broken by (a).
60//!
61//! For steps that behave as described in (a), we can prove that (b) will always succeed in
62//! applying the bounds propagation constraints:
63//!
64//! | Let `A` and `B` be any pair of collections where `A` is an input of `B`.
65//! | Before (a), both invariants are upheld, i.e. `A.lower <= B.lower` and `A.upper <= B.upper`.
66//! |
67//! | Case 1: (a) increases `A.lower` and/or `B.lower` to `A.lower'` and `B.lower'`
68//! |     Invariant (1) might be broken, need to prove that it can be restored.
69//! |     Case 1.a: `A.lower' <= B.lower'`
70//! |         Invariant (1) is still upheld without propagation.
71//! |     Case 1.b: `A.lower' > B.lower'`
72//! |         A collection's lower bound can only be increased up to its upper bound.
73//! |         Therefore, and from invariant (2): `A.lower' <= A.upper <= B.upper`
74//! |         Therefore, propagation can set `B.lower' = A.lower'`, restoring invariant (1).
75//! | Case 2: (a) decreases `A.upper` and/or `B.upper`
76//! |     Invariant (2) might be broken, need to prove that it can be restored.
77//! |     The proof is equivalent to Case 1.
78
79use 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
95/// Runs as-of selection for the given dataflows.
96///
97/// Assigns the selected as-of to the provided dataflow descriptions and returns a set of
98/// `ReadHold`s that must not be dropped nor downgraded until the dataflows have been installed
99/// with the compute controller.
100///
101/// `pending_replacements` are the exports of replacement materialized views that are not applied
102/// yet. The downstream storage constraint is soft for them.
103pub 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    // Get read holds for the storage inputs of the dataflows.
112    // This ensures that storage frontiers don't advance past the selected as-ofs.
113    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    // Dataflows that sink into a storage collection that has advanced to the empty frontier don't
129    // need to be installed at all. So we can apply an optimization where we prune them here and
130    // assign them an empty as-of at the end.
131    ctx.prune_sealed_persist_sinks();
132
133    // During 0dt upgrades, it can happen that the leader environment drops storage collections,
134    // making the read-only environment observe inconsistent read frontiers (database-issues#8836).
135    // To avoid hard-constraint failures, we prune all collections depending on these dropped
136    // storage collections.
137    if read_only_mode {
138        ctx.prune_dropped_collections();
139    }
140
141    // Apply constraints from upstream and downstream storage collections.
142    ctx.apply_upstream_storage_constraints(&storage_read_holds);
143    ctx.apply_downstream_storage_constraints(pending_replacements);
144
145    // At this point all collections have as-of bounds that reflect what is required for
146    // correctness. The current state isn't very usable though. In particular, most of the upper
147    // bounds are likely to be the empty frontier, so if we'd select as-ofs on this basis, the
148    // resulting dataflows would never hydrate. Instead we'll apply a number of soft constraints to
149    // end up in a better place.
150
151    // Constrain collection as-ofs to times that are currently available in the inputs. This
152    // ensures that dataflows can immediately start hydrating. It also ensures that dataflows don't
153    // get an empty as-of, except when they exclusively depend on constant collections.
154    //
155    // Allowing dataflows to hydrate immediately is desirable. It allows them to complete the most
156    // resource-intensive phase of their lifecycle as early as possible. Ideally we want this phase
157    // to occur during a 0dt upgrade, where we still have the option to roll back if a cluster
158    // doesn't come up successfully. For dataflows with a refresh schedule, hydrating early also
159    // ensures that there isn't a large output delay when the refresh time is reached.
160    ctx.apply_warmup_constraints();
161
162    // Constrain as-ofs of indexes according to their read policies.
163    ctx.apply_index_read_policy_constraints();
164
165    // Constrain as-ofs of indexes to the current time. This ensures that indexes are immediately
166    // readable.
167    ctx.apply_index_current_time_constraints();
168
169    // Apply the derived as-of bounds to the dataflows.
170    for dataflow in dataflows {
171        // `AsOfBounds` are shared between the exports of a dataflow, so looking at just the first
172        // export is sufficient.
173        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/// Bounds for possible as-of values of a dataflow.
182#[derive(Debug)]
183struct AsOfBounds {
184    lower: Antichain<Timestamp>,
185    upper: Antichain<Timestamp>,
186    /// Whether these bounds can still change.
187    sealed: bool,
188}
189
190impl AsOfBounds {
191    /// Creates an `AsOfBounds` that only allows the given `frontier`.
192    fn single(frontier: Antichain<Timestamp>) -> Self {
193        Self {
194            lower: frontier.clone(),
195            upper: frontier,
196            sealed: false,
197        }
198    }
199
200    /// Get the bound of the given type.
201    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/// Types of bounds.
231#[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/// Types of constraints.
247#[derive(Clone, Copy, Debug, PartialEq, Eq)]
248enum ConstraintType {
249    /// Hard constraints are applied to enforce correctness properties, and failing to apply them is
250    /// an error.
251    Hard,
252    /// Soft constraints are applied to improve performance or UX, and failing to apply them is
253    /// undesirable but not an error.
254    Soft,
255}
256
257/// A constraint that can be applied to the `AsOfBounds` of a collection.
258#[derive(Debug)]
259struct Constraint<'a> {
260    type_: ConstraintType,
261    /// Which bound this constraint applies to.
262    bound_type: BoundType,
263    /// The frontier by which the bound should be constrained.
264    frontier: &'a Antichain<Timestamp>,
265    /// A short description of the reason for applying this constraint.
266    ///
267    /// Used only for logging.
268    reason: &'a str,
269}
270
271impl Constraint<'_> {
272    /// Applies this constraint to the given bounds.
273    ///
274    /// Returns a bool indicating whether the given bounds were changed as a result.
275    ///
276    /// Applying a constraint can fail, if the constraint frontier is incompatible with the
277    /// existing bounds. In this case, the constraint still gets partially applied by moving one of
278    /// the bounds up/down to the other, depending on the `bound_type`.
279    ///
280    /// Applying a constraint to sealed bounds is a no-op.
281    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
323/// State tracked for a compute collection during as-of selection.
324struct Collection<'a> {
325    storage_inputs: Vec<GlobalId>,
326    compute_inputs: Vec<GlobalId>,
327    read_policy: Option<&'a ReadPolicy>,
328    /// The currently known as-of bounds.
329    ///
330    /// Shared between collections exported by the same dataflow.
331    bounds: Rc<RefCell<AsOfBounds>>,
332    /// Whether this collection is an index.
333    is_index: bool,
334}
335
336/// The frontier up to which the inputs of a collection count as complete.
337struct InputFrontier {
338    frontier: Antichain<Timestamp>,
339    /// The storage write frontier that `frontier` stands in for, if the inputs are not readable
340    /// at the collection's lower as-of bound.
341    substituted_for: Option<Antichain<Timestamp>>,
342}
343
344impl InputFrontier {
345    /// Describes the substitution, if any, for constraint reasons.
346    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
358/// The as-of selection context.
359struct 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    /// Initializes an as-of selection context for the given `dataflows`.
367    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        // Construct initial collection state for each dataflow export. Dataflows might have their
374        // as-ofs already fixed, which we need to take into account when constructing `AsOfBounds`.
375        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    /// Returns the state of the identified collection.
406    ///
407    /// # Panics
408    ///
409    /// Panics if the identified collection doesn't exist.
410    fn expect_collection(&self, id: GlobalId) -> &Collection<'_> {
411        self.collections
412            .get(&id)
413            .unwrap_or_else(|| panic!("collection missing: {id}"))
414    }
415
416    /// Applies the given as-of constraint to the identified collection.
417    ///
418    /// Returns whether the collection's as-of bounds where changed as a result.
419    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    /// Apply as-of constraints imposed by the frontiers of upstream storage collections.
447    ///
448    /// A collection's as-of _must_ be >= the read frontier of each of its (transitive) storage
449    /// inputs.
450    ///
451    /// Failing to apply this constraint to a collection is an error. The affected dataflow will
452    /// not be able to hydrate successfully.
453    fn apply_upstream_storage_constraints(
454        &self,
455        storage_read_holds: &BTreeMap<GlobalId, ReadHold>,
456    ) {
457        // Apply direct constraints from storage inputs.
458        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        // Propagate constraints downstream, restoring `AsOfBounds` invariant (1).
472        self.propagate_bounds_downstream(BoundType::Lower);
473    }
474
475    /// Apply as-of constraints imposed by the frontiers of downstream storage collections.
476    ///
477    /// A collection's as-of _must_ be < the write frontier of the storage collection it exports to
478    /// (if any) if it is non-empty, and <= the storage collection's read frontier otherwise.
479    ///
480    /// Rationale:
481    ///
482    /// * A collection's as-of must be <= the write frontier of its dependent storage collection,
483    ///   because we need to pick up computing the contents of storage collections where we left
484    ///   off previously, to avoid skipped times observable in the durable output.
485    /// * Some dataflows feeding into storage collections (specifically: continual tasks) need to
486    ///   be able to observe input changes at times they write to the output. If we selected the
487    ///   as-of to be equal to the write frontier of the output storage collection, we wouldn't be
488    ///   able to produce the correct output at that frontier. Thus the selected as-of must be
489    ///   strictly less than the write frontier.
490    /// * As an exception to the above, if the output storage collection is empty (i.e. its write
491    ///   frontier is <= its read frontier), we need to allow the as-of to be equal to the read
492    ///   frontier. This is correct in the sense that it mirrors the timestamp selection behavior
493    ///   of the sequencer when it created the collection. Chances are that the sequencer chose the
494    ///   initial as-of (and therefore the initial read frontier of the storage collection) as the
495    ///   smallest possible time that can still be read from the collection inputs, so forcing the
496    ///   upper bound any lower than that read frontier would produce a hard constraint violation.
497    ///
498    /// Failing to apply this constraint to a collection is an error. The storage collection it
499    /// exports to may have times visible to readers skipped in its output, violating correctness.
500    /// The exception is `pending_replacements`, for which the constraint is soft.
501    fn apply_downstream_storage_constraints(&self, pending_replacements: &BTreeSet<GlobalId>) {
502        // Apply direct constraints from storage exports.
503        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            // A pending replacement reports its target's write frontier but doesn't write to it.
517            // Its inputs might not be readable at that frontier, for example when they were
518            // created after the target last wrote, so its as-of can be beyond it. Applying the
519            // replacement waits for the target's write frontier to reach the replacement's, which
520            // starts at the as-of. That wait, not this constraint, prevents skipped times.
521            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        // Propagate constraints upstream, restoring `AsOfBounds` invariant (2).
536        self.propagate_bounds_upstream(BoundType::Upper);
537    }
538
539    /// Apply as-of constraints to ensure collections can hydrate immediately.
540    ///
541    /// A collection's as-of _should_ be < the write frontier of each of its (transitive) storage
542    /// inputs.
543    ///
544    /// Failing to apply this constraint is not an error. The affected dataflow will not be able to
545    /// hydrate immediately, but it will be able to hydrate once its inputs have sufficiently
546    /// advanced.
547    fn apply_warmup_constraints(&self) {
548        // Apply the warmup constraint.
549        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        // Restore `AsOfBounds` invariant (2).
565        self.propagate_bounds_upstream(BoundType::Upper);
566    }
567
568    /// Apply as-of constraints to ensure indexes contain historical data as requested by their
569    /// associated read policies.
570    ///
571    /// An index's as-of _should_ be <= the frontier determined by its read policy applied to its
572    /// write frontier.
573    ///
574    /// Failing to apply this constraint is not an error. The affected index will not contain
575    /// historical times for its entire compaction window initially, but will do so once sufficient
576    /// time has passed.
577    fn apply_index_read_policy_constraints(&self) {
578        // For the write frontier of an index, we'll use the frontier of its inputs. This is an
579        // upper bound for the write frontier the index could have had before the restart. For
580        // indexes without storage inputs we use the current time.
581        let mut input_frontiers = self.input_frontiers();
582
583        // Apply the read policy constraint to indexes.
584        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        // Restore `AsOfBounds` invariant (2).
607        self.propagate_bounds_upstream(BoundType::Upper);
608    }
609
610    /// Returns, for each collection, the meet of the write frontiers of its transitive storage
611    /// inputs.
612    fn transitive_storage_write_frontiers(&self) -> BTreeMap<GlobalId, Antichain<Timestamp>> {
613        // Collect write frontiers from storage inputs.
614        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        // Propagate write frontiers through compute inputs.
630        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    /// Returns, for each collection, the frontier up to which its inputs count as complete when
645    /// deriving soft upper bounds.
646    ///
647    /// The lower as-of bounds must be final when this is called.
648    fn input_frontiers(&self) -> BTreeMap<GlobalId, InputFrontier> {
649        // NOTE: An input without readable data at the lower bound, for example an MV that never
650        // ran, holds the write frontier at or below that bound. The collection can't hydrate at
651        // any as-of we could select until that input advances. Constraining the upper bound by
652        // that write frontier would seal the as-of at the lower bound, and invariant (2) would
653        // then drag every compute input back to it, making them replay history for no benefit.
654        // Instead we treat the inputs as complete up to the current time. The empty frontier
655        // would not do: it removes the warmup bound, and a dataflow no other constraint bounds,
656        // like a metric sink, would get an empty as-of and never be installed.
657        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    /// Apply as-of constraints to ensure indexes are immediately readable.
682    ///
683    /// An index's as-of _should_ be <= the current time.
684    ///
685    /// Failing to apply this constraint is not an error. The affected index will not be readable
686    /// immediately, but will be readable once sufficient time has passed.
687    fn apply_index_current_time_constraints(&self) {
688        // Apply the current time constraint to indexes.
689        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        // Restore `AsOfBounds` invariant (2).
703        self.propagate_bounds_upstream(BoundType::Upper);
704    }
705
706    /// Propagate as-of bounds through the dependency graph, in downstream direction.
707    fn propagate_bounds_downstream(&self, bound_type: BoundType) {
708        // Propagating `lower` bounds downstream restores `AsOfBounds` invariant (1) and must
709        // therefore always succeed.
710        let constraint_type = match bound_type {
711            BoundType::Lower => ConstraintType::Hard,
712            BoundType::Upper => ConstraintType::Soft,
713        };
714
715        // We don't want to rely on a correspondence between `GlobalId` order and dependency order,
716        // so we use a fixpoint loop here.
717        fixpoint(|changed| {
718            self.propagate_bounds_downstream_inner(bound_type, constraint_type, changed);
719
720            // Propagating `upper` bounds downstream might break `AsOfBounds` invariant (2), so we
721            // need to restore it.
722            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    /// Propagate as-of bounds through the dependency graph, in upstream direction.
754    fn propagate_bounds_upstream(&self, bound_type: BoundType) {
755        // Propagating `upper` bounds upstream restores `AsOfBounds` invariant (2) and must
756        // therefore always succeed.
757        let constraint_type = match bound_type {
758            BoundType::Lower => ConstraintType::Soft,
759            BoundType::Upper => ConstraintType::Hard,
760        };
761
762        // We don't want to rely on a correspondence between `GlobalId` order and dependency order,
763        // so we use a fixpoint loop here.
764        fixpoint(|changed| {
765            self.propagate_bounds_upstream_inner(bound_type, constraint_type, changed);
766
767            // Propagating `lower` bounds upstream might break `AsOfBounds` invariant (1), so we
768            // need to restore it.
769            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    /// Selects the "best" as-of for the identified collection, based on its currently known
800    /// bounds.
801    ///
802    /// We simply use the upper bound here, to maximize the chances of compute reconciliation
803    /// succeeding. Choosing the latest possible as-of also minimizes the amount of work the
804    /// dataflow has to spend processing historical data from its sources.
805    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    /// Removes collections that sink into sealed persist shards from the context.
815    ///
816    /// The dataflows of these collections will get an empty default as-of assigned at the end of
817    /// the as-of selection process, ensuring that they won't get installed unnecessarily.
818    ///
819    /// Note that it is valid to remove these collections from consideration because they don't
820    /// impose as-of constraints on other compute collections.
821    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    /// Removes collections depending on storage collections with empty read frontiers.
830    ///
831    /// The dataflows of these collections will get an empty default as-of assigned at the end of
832    /// the as-of selection process, ensuring that they won't get installed.
833    ///
834    /// This exists only to work around database-issues#8836.
835    fn prune_dropped_collections(&mut self) {
836        // Remove collections with dropped storage inputs.
837        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        // Remove (transitive) dependants of pruned collections.
858        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
875/// Runs `step` in a loop until it stops reporting changes.
876fn 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
886/// Step back the given frontier.
887///
888/// This method is saturating: If the frontier contains `T::minimum()` times, these are kept
889/// unchanged.
890fn 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    // A pending replacement's storage frontiers are those of its target. `u2` reads `s2`, which is
1392    // not readable before the target's write frontier, so `u2` gets an as-of beyond it. `u3`'s
1393    // inputs are readable there, so it gets an as-of that continues the target's output.
1394    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    // `u1` is an empty MV that never ran, so its write frontier is stuck at its read frontier and
1410    // `u3` can't hydrate before `u1` advances. `u3` must not drag its compute input `u2` back to
1411    // `u1`'s frontier.
1412    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    // Like `stuck_input_without_readable_data`, but `u2`'s compute input `u1` is a constant index,
1426    // which only the current-time constraint bounds.
1427    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    // `u2` is a metric sink over an MV `u1` that never ran. No constraint other than warmup bounds
1439    // a metric sink, so it must keep a finite as-of to get installed.
1440    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    // `u1` is an MV that ran up to 8 and then stopped. Its read hold keeps `s1` at 7, so `u3` can
1454    // hydrate at 7 and its compute input `u2` must follow. Before the restart, `u3` held `u2` back
1455    // to the same time.
1456    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    // Regression test for database-issues#9273.
1470    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}