Skip to main content

mz_compute_types/
dataflows.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//! Types for describing dataflows.
11
12use std::collections::{BTreeMap, BTreeSet};
13use std::fmt;
14
15use mz_expr::{CollectionPlan, MirRelationExpr, MirScalarExpr, OptimizedMirRelationExpr};
16use mz_ore::collections::CollectionExt;
17use mz_ore::soft_assert_or_log;
18use mz_repr::refresh_schedule::RefreshSchedule;
19use mz_repr::{GlobalId, ReprRelationType, SqlRelationType};
20use mz_storage_types::time_dependence::TimeDependence;
21use serde::{Deserialize, Serialize};
22use timely::progress::Antichain;
23
24use crate::plan::Plan;
25use crate::plan::render_plan::RenderPlan;
26use crate::sinks::{ComputeSinkConnection, ComputeSinkDesc};
27use crate::sources::{SourceInstanceArguments, SourceInstanceDesc};
28
29/// A description of a dataflow to construct and results to surface.
30#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
31pub struct DataflowDescription<P, S: 'static = (), T = mz_repr::Timestamp> {
32    /// Sources instantiations made available to the dataflow pair with monotonicity information.
33    pub source_imports: BTreeMap<GlobalId, SourceImport<S, T>>,
34    /// Indexes made available to the dataflow.
35    /// (id of index, import)
36    pub index_imports: BTreeMap<GlobalId, IndexImport>,
37    /// Views and indexes to be built and stored in the local context.
38    /// Objects must be built in the specific order, as there may be
39    /// dependencies of later objects on prior identifiers.
40    pub objects_to_build: Vec<BuildDesc<P>>,
41    /// Indexes to be made available to be shared with other dataflows
42    /// (id of new index, description of index, relationtype of base source/view/table)
43    pub index_exports: BTreeMap<GlobalId, (IndexDesc, ReprRelationType)>,
44    /// sinks to be created
45    /// (id of new sink, description of sink)
46    pub sink_exports: BTreeMap<GlobalId, ComputeSinkDesc<S, T>>,
47    /// An optional frontier to which inputs should be advanced.
48    ///
49    /// If this is set, it should override the default setting determined by
50    /// the upper bound of `since` frontiers contributing to the dataflow.
51    /// It is an error for this to be set to a frontier not beyond that default.
52    pub as_of: Option<Antichain<T>>,
53    /// Frontier beyond which the dataflow should not execute.
54    /// Specifically, updates at times greater or equal to this frontier are suppressed.
55    /// This is often set to `as_of + 1` to enable "batch" computations.
56    /// Note that frontier advancements might still happen to times that are after the `until`,
57    /// only data is suppressed. (This is consistent with how frontier advancements can also
58    /// happen before the `as_of`.)
59    pub until: Antichain<T>,
60    /// The initial as_of when the collection is first created. Filled only for materialized views.
61    /// Note that this doesn't change upon restarts.
62    pub initial_storage_as_of: Option<Antichain<T>>,
63    /// The schedule of REFRESH materialized views.
64    pub refresh_schedule: Option<RefreshSchedule>,
65    /// Human-readable name
66    pub debug_name: String,
67    /// Description of how the dataflow's progress relates to wall-clock time. None for unknown.
68    pub time_dependence: Option<TimeDependence>,
69}
70
71impl<P, S> DataflowDescription<P, S, mz_repr::Timestamp> {
72    /// Tests if the dataflow refers to a single timestamp, namely
73    /// that `as_of` has a single coordinate and that the `until`
74    /// value corresponds to the `as_of` value plus one, or `as_of`
75    /// is the maximum timestamp and is thus single.
76    pub fn is_single_time(&self) -> bool {
77        // TODO: this would be much easier to check if `until` was a strict lower bound,
78        // and we would be testing that `until == as_of`.
79
80        let until = &self.until;
81
82        // IF `as_of` is not set at all this can't be a single time dataflow.
83        let Some(as_of) = self.as_of.as_ref() else {
84            return false;
85        };
86        // Ensure that as_of <= until.
87        soft_assert_or_log!(
88            timely::PartialOrder::less_equal(as_of, until),
89            "expected empty `as_of ≤ until`, got `{as_of:?} ≰ {until:?}`",
90        );
91        // IF `as_of` is not a single timestamp this can't be a single time dataflow.
92        let Some(as_of) = as_of.as_option() else {
93            return false;
94        };
95        // Ensure that `as_of = MAX` implies `until.is_empty()`.
96        soft_assert_or_log!(
97            as_of != &mz_repr::Timestamp::MAX || until.is_empty(),
98            "expected `until = {{}}` due to `as_of = MAX`, got `until = {until:?}`",
99        );
100        // Note that the `(as_of = MAX, until = {})` case also returns `true`
101        // here (as expected) since we are going to compare two `None` values.
102        as_of.try_step_forward().as_ref() == until.as_option()
103    }
104}
105
106impl<T> DataflowDescription<Plan<T>, (), mz_repr::Timestamp> {
107    /// Check invariants expected to be true about `DataflowDescription`s.
108    pub fn check_invariants(&self) -> Result<(), String> {
109        let mut plans: Vec<_> = self.objects_to_build.iter().map(|o| &o.plan).collect();
110        let mut lir_ids = BTreeSet::new();
111
112        while let Some(plan) = plans.pop() {
113            let lir_id = plan.lir_id;
114            if !lir_ids.insert(lir_id) {
115                return Err(format!(
116                    "duplicate `LirId` in `DataflowDescription`: {lir_id}"
117                ));
118            }
119            plans.extend(plan.node.children());
120        }
121
122        Ok(())
123    }
124}
125
126impl<T> DataflowDescription<OptimizedMirRelationExpr, (), T> {
127    /// Imports a previously exported index.
128    ///
129    /// This method makes available an index previously exported as `id`, identified
130    /// to the query by `description` (which names the view the index arranges, and
131    /// the keys by which it is arranged).
132    pub fn import_index(
133        &mut self,
134        id: GlobalId,
135        desc: IndexDesc,
136        typ: ReprRelationType,
137        monotonic: bool,
138    ) {
139        self.index_imports.insert(
140            id,
141            IndexImport {
142                desc,
143                typ,
144                monotonic,
145                with_snapshot: true,
146            },
147        );
148    }
149
150    /// Imports a source and makes it available as `id`.
151    pub fn import_source(&mut self, id: GlobalId, typ: SqlRelationType, monotonic: bool) {
152        // Import the source with no linear operators applied to it.
153        // They may be populated by whole-dataflow optimization.
154        // Similarly, we require the snapshot by default, though optimization may choose to skip it.
155        self.source_imports.insert(
156            id,
157            SourceImport {
158                desc: SourceInstanceDesc {
159                    storage_metadata: (),
160                    arguments: SourceInstanceArguments { operators: None },
161                    typ,
162                },
163                monotonic,
164                with_snapshot: true,
165                upper: Antichain::new(),
166            },
167        );
168    }
169
170    /// Binds to `id` the relation expression `plan`.
171    pub fn insert_plan(&mut self, id: GlobalId, plan: OptimizedMirRelationExpr) {
172        self.objects_to_build.push(BuildDesc { id, plan });
173    }
174
175    /// Exports as `id` an index described by `description`.
176    ///
177    /// Future uses of `import_index` in other dataflow descriptions may use `id`,
178    /// as long as this dataflow has not been terminated in the meantime.
179    pub fn export_index(
180        &mut self,
181        id: GlobalId,
182        description: IndexDesc,
183        on_type: ReprRelationType,
184    ) {
185        // We first create a "view" named `id` that ensures that the
186        // data are correctly arranged and available for export.
187        self.insert_plan(
188            id,
189            OptimizedMirRelationExpr::declare_optimized(MirRelationExpr::ArrangeBy {
190                input: Box::new(MirRelationExpr::global_get(
191                    description.on_id,
192                    on_type.clone(),
193                )),
194                keys: vec![description.key.clone()],
195            }),
196        );
197        self.index_exports.insert(id, (description, on_type));
198    }
199
200    /// Exports as `id` a sink described by `description`.
201    pub fn export_sink(&mut self, id: GlobalId, description: ComputeSinkDesc<(), T>) {
202        self.sink_exports.insert(id, description);
203    }
204
205    /// Returns true iff `id` is already imported.
206    pub fn is_imported(&self, id: &GlobalId) -> bool {
207        self.objects_to_build.iter().any(|bd| &bd.id == id)
208            || self.index_imports.keys().any(|i| i == id)
209            || self.source_imports.keys().any(|i| i == id)
210    }
211
212    /// The number of columns associated with an identifier in the dataflow.
213    pub fn arity_of(&self, id: &GlobalId) -> usize {
214        for (source_id, source_import) in self.source_imports.iter() {
215            let source = &source_import.desc;
216            if source_id == id {
217                return source.typ.arity();
218            }
219        }
220        for IndexImport { desc, typ, .. } in self.index_imports.values() {
221            if &desc.on_id == id {
222                return typ.arity();
223            }
224        }
225        for desc in self.objects_to_build.iter() {
226            if &desc.id == id {
227                return desc.plan.arity();
228            }
229        }
230        panic!("GlobalId {} not found in DataflowDesc", id);
231    }
232
233    /// Calls r and s on any sub-members of those types in self. Halts at the first error return.
234    pub fn visit_children<R, S, E>(&mut self, r: R, s: S) -> Result<(), E>
235    where
236        R: Fn(&mut OptimizedMirRelationExpr) -> Result<(), E>,
237        S: Fn(&mut MirScalarExpr) -> Result<(), E>,
238    {
239        for BuildDesc { plan, .. } in &mut self.objects_to_build {
240            r(plan)?;
241        }
242        for source_import in self.source_imports.values_mut() {
243            let Some(mfp) = source_import.desc.arguments.operators.as_mut() else {
244                continue;
245            };
246            for expr in mfp.expressions.iter_mut() {
247                s(expr)?;
248            }
249            for (_, expr) in mfp.predicates.iter_mut() {
250                s(expr)?;
251            }
252        }
253        Ok(())
254    }
255}
256
257impl<P, S, T> DataflowDescription<P, S, T> {
258    /// Creates a new dataflow description with a human-readable name.
259    pub fn new(name: String) -> Self {
260        Self {
261            source_imports: Default::default(),
262            index_imports: Default::default(),
263            objects_to_build: Vec::new(),
264            index_exports: Default::default(),
265            sink_exports: Default::default(),
266            as_of: Default::default(),
267            until: Antichain::new(),
268            initial_storage_as_of: None,
269            refresh_schedule: None,
270            debug_name: name,
271            time_dependence: None,
272        }
273    }
274
275    /// Sets the `as_of` frontier to the supplied argument.
276    ///
277    /// This method allows the dataflow to indicate a frontier up through
278    /// which all times should be advanced. This can be done for at least
279    /// two reasons: 1. correctness and 2. performance.
280    ///
281    /// Correctness may require an `as_of` to ensure that historical detail
282    /// is consolidated at representative times that do not present specific
283    /// detail that is not specifically correct. For example, updates may be
284    /// compacted to times that are no longer the source times, but instead
285    /// some byproduct of when compaction was executed; we should not present
286    /// those specific times as meaningfully different from other equivalent
287    /// times.
288    ///
289    /// Performance may benefit from an aggressive `as_of` as it reduces the
290    /// number of distinct moments at which collections vary. Differential
291    /// dataflow will refresh its outputs at each time its inputs change and
292    /// to moderate that we can minimize the volume of distinct input times
293    /// as much as possible.
294    ///
295    /// Generally, one should consider setting `as_of` at least to the `since`
296    /// frontiers of contributing data sources and as aggressively as the
297    /// computation permits.
298    pub fn set_as_of(&mut self, as_of: Antichain<T>) {
299        self.as_of = Some(as_of);
300    }
301
302    /// Records the initial `as_of` of the storage collection associated with a materialized view.
303    pub fn set_initial_as_of(&mut self, initial_as_of: Antichain<T>) {
304        self.initial_storage_as_of = Some(initial_as_of);
305    }
306
307    /// Identifiers of imported objects (indexes and sources).
308    pub fn import_ids(&self) -> impl Iterator<Item = GlobalId> + Clone + '_ {
309        self.imported_index_ids().chain(self.imported_source_ids())
310    }
311
312    /// Identifiers of imported indexes.
313    pub fn imported_index_ids(&self) -> impl Iterator<Item = GlobalId> + Clone + '_ {
314        self.index_imports.keys().copied()
315    }
316
317    /// Identifiers of imported sources.
318    pub fn imported_source_ids(&self) -> impl Iterator<Item = GlobalId> + Clone + '_ {
319        self.source_imports.keys().copied()
320    }
321
322    /// Identifiers of exported objects (indexes and sinks).
323    pub fn export_ids(&self) -> impl Iterator<Item = GlobalId> + Clone + '_ {
324        self.exported_index_ids().chain(self.exported_sink_ids())
325    }
326
327    /// Identifiers of exported indexes.
328    pub fn exported_index_ids(&self) -> impl Iterator<Item = GlobalId> + Clone + '_ {
329        self.index_exports.keys().copied()
330    }
331
332    /// Identifiers of exported sinks.
333    pub fn exported_sink_ids(&self) -> impl Iterator<Item = GlobalId> + Clone + '_ {
334        self.sink_exports.keys().copied()
335    }
336
337    /// Identifiers of exported persist sinks.
338    pub fn persist_sink_ids(&self) -> impl Iterator<Item = GlobalId> + '_ {
339        self.sink_exports
340            .iter()
341            .filter_map(|(id, desc)| match desc.connection {
342                ComputeSinkConnection::MaterializedView(_) => Some(*id),
343                ComputeSinkConnection::ContinualTask(_) => Some(*id),
344                _ => None,
345            })
346    }
347
348    /// Identifiers of exported subscribe sinks.
349    pub fn subscribe_ids(&self) -> impl Iterator<Item = GlobalId> + '_ {
350        self.sink_exports
351            .iter()
352            .filter_map(|(id, desc)| match desc.connection {
353                ComputeSinkConnection::Subscribe(_) => Some(*id),
354                _ => None,
355            })
356    }
357
358    /// Identifiers of exported continual tasks.
359    pub fn continual_task_ids(&self) -> impl Iterator<Item = GlobalId> + '_ {
360        self.sink_exports
361            .iter()
362            .filter_map(|(id, desc)| match desc.connection {
363                ComputeSinkConnection::ContinualTask(_) => Some(*id),
364                _ => None,
365            })
366    }
367
368    /// Identifiers of exported copy to sinks.
369    pub fn copy_to_ids(&self) -> impl Iterator<Item = GlobalId> + '_ {
370        self.sink_exports
371            .iter()
372            .filter_map(|(id, desc)| match desc.connection {
373                ComputeSinkConnection::CopyToS3Oneshot(_) => Some(*id),
374                _ => None,
375            })
376    }
377
378    /// Produce a `Display`able value containing the import IDs of this dataflow.
379    pub fn display_import_ids(&self) -> impl fmt::Display + '_ {
380        use mz_ore::str::{bracketed, separated};
381        bracketed("[", "]", separated(", ", self.import_ids()))
382    }
383
384    /// Produce a `Display`able value containing the export IDs of this dataflow.
385    pub fn display_export_ids(&self) -> impl fmt::Display + '_ {
386        use mz_ore::str::{bracketed, separated};
387        bracketed("[", "]", separated(", ", self.export_ids()))
388    }
389
390    /// Whether this dataflow installs transient collections.
391    pub fn is_transient(&self) -> bool {
392        self.export_ids().all(|id| id.is_transient())
393    }
394
395    /// Returns the description of the object to build with the specified
396    /// identifier.
397    ///
398    /// # Panics
399    ///
400    /// Panics if `id` is not present in `objects_to_build` exactly once.
401    pub fn build_desc(&self, id: GlobalId) -> &BuildDesc<P> {
402        let mut builds = self.objects_to_build.iter().filter(|build| build.id == id);
403        let build = builds
404            .next()
405            .unwrap_or_else(|| panic!("object to build id {id} unexpectedly missing"));
406        assert!(builds.next().is_none());
407        build
408    }
409
410    /// Returns the id of the dataflow's sink export.
411    ///
412    /// # Panics
413    ///
414    /// Panics if the dataflow has no sink exports or has more than one.
415    pub fn sink_id(&self) -> GlobalId {
416        let sink_exports = &self.sink_exports;
417        let sink_id = sink_exports.keys().into_element();
418        *sink_id
419    }
420}
421
422impl<P, S, T> DataflowDescription<P, S, T>
423where
424    P: CollectionPlan,
425{
426    /// Computes the set of identifiers upon which the specified collection
427    /// identifier depends.
428    ///
429    /// `collection_id` must specify a valid object in `objects_to_build`.
430    ///
431    /// This method includes identifiers for e.g. intermediate views, and should be filtered
432    /// if one only wants sources and indexes.
433    ///
434    /// This method is safe for mutually recursive view definitions.
435    pub fn depends_on(&self, collection_id: GlobalId) -> BTreeSet<GlobalId> {
436        let mut out = BTreeSet::new();
437        self.depends_on_into(collection_id, &mut out);
438        out
439    }
440
441    /// Like `depends_on`, but appends to an existing `BTreeSet`.
442    pub fn depends_on_into(&self, collection_id: GlobalId, out: &mut BTreeSet<GlobalId>) {
443        out.insert(collection_id);
444        if self.source_imports.contains_key(&collection_id) {
445            // The collection is provided by an imported source. Report the
446            // dependency on the source.
447            out.insert(collection_id);
448            return;
449        }
450
451        // NOTE(benesch): we're not smart enough here to know *which* index
452        // for the collection will be used, if one exists, so we have to report
453        // the dependency on all of them.
454        let mut found_index = false;
455        for (index_id, IndexImport { desc, .. }) in &self.index_imports {
456            if desc.on_id == collection_id {
457                // The collection is provided by an imported index. Report the
458                // dependency on the index.
459                out.insert(*index_id);
460                found_index = true;
461            }
462        }
463        if found_index {
464            return;
465        }
466
467        // The collection is not provided by a source or imported index.
468        // It must be a collection whose plan we have handy. Recurse.
469        let build = self.build_desc(collection_id);
470        for id in build.plan.depends_on() {
471            if !out.contains(&id) {
472                self.depends_on_into(id, out)
473            }
474        }
475    }
476
477    /// Computes the set of imports upon which the specified collection depends.
478    ///
479    /// This method behaves like `depends_on` but filters out internal dependencies that are not
480    /// included in the dataflow imports.
481    pub fn depends_on_imports(&self, collection_id: GlobalId) -> BTreeSet<GlobalId> {
482        let is_import = |id: &GlobalId| {
483            self.source_imports.contains_key(id) || self.index_imports.contains_key(id)
484        };
485
486        let deps = self.depends_on(collection_id);
487        deps.into_iter().filter(is_import).collect()
488    }
489}
490
491impl<S, T> DataflowDescription<RenderPlan, S, T>
492where
493    S: Clone + PartialEq,
494    T: Clone + timely::PartialOrder,
495{
496    /// Determine if a dataflow description is compatible with this dataflow description.
497    ///
498    /// Compatible dataflows have structurally equal exports, imports, and objects to build. The
499    /// `as_of` of the receiver has to be less equal the `other` `as_of`.
500    ///
501    /// Note that this method performs normalization as part of the structural equality checking,
502    /// which involves cloning both `self` and `other`. It is therefore relatively expensive and
503    /// should only be used on cold code paths.
504    ///
505    // TODO: The semantics of this function are only useful for command reconciliation at the moment.
506    pub fn compatible_with(&self, other: &Self) -> bool {
507        let old = self.as_comparable();
508        let new = other.as_comparable();
509
510        let equality = old.index_exports == new.index_exports
511            && old.sink_exports == new.sink_exports
512            && old.objects_to_build == new.objects_to_build
513            && old.index_imports == new.index_imports
514            && old.source_imports == new.source_imports
515            && old.time_dependence == new.time_dependence;
516
517        let partial = if let (Some(old_as_of), Some(new_as_of)) = (&old.as_of, &new.as_of) {
518            timely::PartialOrder::less_equal(old_as_of, new_as_of)
519        } else {
520            false
521        };
522
523        equality && partial
524    }
525
526    /// Returns a `DataflowDescription` that has the same structure as `self` and can be
527    /// structurally compared to other `DataflowDescription`s.
528    ///
529    /// The function normalizes several properties. It replaces transient `GlobalId`s
530    /// that are only used internally (i.e. not imported nor exported) with consecutive IDs
531    /// starting from `t1`. It replaces the source import's `upper` by a dummy value.
532    fn as_comparable(&self) -> Self {
533        let external_ids: BTreeSet<_> = self.import_ids().chain(self.export_ids()).collect();
534
535        let mut id_counter = 0;
536        let mut replacements = BTreeMap::new();
537
538        let mut maybe_replace = |id: GlobalId| {
539            if id.is_transient() && !external_ids.contains(&id) {
540                *replacements.entry(id).or_insert_with(|| {
541                    id_counter += 1;
542                    GlobalId::Transient(id_counter)
543                })
544            } else {
545                id
546            }
547        };
548
549        let mut source_imports = self.source_imports.clone();
550        for import in source_imports.values_mut() {
551            import.upper = Antichain::new();
552        }
553
554        let mut objects_to_build = self.objects_to_build.clone();
555        for object in &mut objects_to_build {
556            object.id = maybe_replace(object.id);
557            object.plan.replace_ids(&mut maybe_replace);
558        }
559
560        let mut index_exports = self.index_exports.clone();
561        for (desc, _typ) in index_exports.values_mut() {
562            desc.on_id = maybe_replace(desc.on_id);
563        }
564
565        let mut sink_exports = self.sink_exports.clone();
566        for desc in sink_exports.values_mut() {
567            desc.from = maybe_replace(desc.from);
568        }
569
570        DataflowDescription {
571            source_imports,
572            index_imports: self.index_imports.clone(),
573            objects_to_build,
574            index_exports,
575            sink_exports,
576            as_of: self.as_of.clone(),
577            until: self.until.clone(),
578            initial_storage_as_of: self.initial_storage_as_of.clone(),
579            refresh_schedule: self.refresh_schedule.clone(),
580            debug_name: self.debug_name.clone(),
581            time_dependence: self.time_dependence.clone(),
582        }
583    }
584}
585
586/// A commonly used name for dataflows contain MIR expressions.
587pub type DataflowDesc = DataflowDescription<OptimizedMirRelationExpr, ()>;
588
589/// An index storing processed updates so they can be queried
590/// or reused in other computations
591#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Hash)]
592pub struct IndexDesc {
593    /// Identity of the collection the index is on.
594    pub on_id: GlobalId,
595    /// Expressions to be arranged, in order of decreasing primacy.
596    pub key: Vec<MirScalarExpr>,
597}
598
599/// Information about an imported index, and how it will be used by the dataflow.
600#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
601pub struct IndexImport {
602    /// Description of index.
603    pub desc: IndexDesc,
604    /// Schema and keys of the object the index is on.
605    pub typ: ReprRelationType,
606    /// Whether the index will supply monotonic data.
607    pub monotonic: bool,
608    /// Whether this import must include the snapshot data.
609    pub with_snapshot: bool,
610}
611
612/// Information about an imported source, and how it will be used by the dataflow.
613#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
614pub struct SourceImport<S: 'static = (), T = mz_repr::Timestamp> {
615    /// Description of the source instance to import.
616    pub desc: SourceInstanceDesc<S>,
617    /// Whether the source will supply monotonic data.
618    pub monotonic: bool,
619    /// Whether this import must include the snapshot data.
620    pub with_snapshot: bool,
621    /// The initial known upper frontier for the source.
622    pub upper: Antichain<T>,
623}
624
625/// An association of a global identifier to an expression.
626#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
627pub struct BuildDesc<P> {
628    /// TODO(database-issues#7533): Add documentation.
629    pub id: GlobalId,
630    /// TODO(database-issues#7533): Add documentation.
631    pub plan: P,
632}