Skip to main content

mz_adapter/catalog/
timeline.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//! Logic related to timelines.
11
12use std::collections::{BTreeMap, BTreeSet};
13
14use itertools::Itertools;
15use mz_catalog::memory::objects::{CatalogItem, MaterializedView, View};
16use mz_expr::CollectionPlan;
17use mz_ore::collections::CollectionExt;
18use mz_repr::{CatalogItemId, GlobalId};
19use mz_storage_types::sources::Timeline;
20
21use crate::catalog::Catalog;
22use crate::{AdapterError, CollectionIdBundle, TimelineContext};
23
24impl Catalog {
25    /// Return the [`TimelineContext`] belonging to a [`CatalogItemId`], if one exists.
26    pub(crate) fn get_timeline_context(&self, id: CatalogItemId) -> TimelineContext {
27        let entry = self.get_entry(&id);
28        self.validate_timeline_context(entry.global_ids())
29            .expect("impossible for a single object to belong to incompatible timeline contexts")
30    }
31
32    /// Return the [`TimelineContext`] belonging to a [`GlobalId`], if one exists.
33    pub(crate) fn get_timeline_context_for_global_id(&self, id: GlobalId) -> TimelineContext {
34        self.validate_timeline_context(vec![id])
35            .expect("impossible for a single object to belong to incompatible timeline contexts")
36    }
37
38    /// Returns an iterator that partitions an id bundle by the [`TimelineContext`] that each id
39    /// belongs to.
40    pub fn partition_ids_by_timeline_context(
41        &self,
42        id_bundle: &CollectionIdBundle,
43    ) -> impl Iterator<Item = (TimelineContext, CollectionIdBundle)> + use<> {
44        let mut res: BTreeMap<TimelineContext, CollectionIdBundle> = BTreeMap::new();
45
46        for gid in &id_bundle.storage_ids {
47            let timeline_context = self.get_timeline_context_for_global_id(*gid);
48            res.entry(timeline_context)
49                .or_default()
50                .storage_ids
51                .insert(*gid);
52        }
53
54        for (compute_instance, ids) in &id_bundle.compute_ids {
55            for gid in ids {
56                let timeline_context = self.get_timeline_context_for_global_id(*gid);
57                res.entry(timeline_context)
58                    .or_default()
59                    .compute_ids
60                    .entry(*compute_instance)
61                    .or_default()
62                    .insert(*gid);
63            }
64        }
65
66        res.into_iter()
67    }
68
69    /// Returns an id bundle containing all the ids in the give timeline.
70    pub(crate) fn ids_in_timeline(&self, timeline: &Timeline) -> CollectionIdBundle {
71        let mut id_bundle = CollectionIdBundle::default();
72        for entry in self.entries() {
73            if let TimelineContext::TimelineDependent(entry_timeline) =
74                self.get_timeline_context(entry.id())
75            {
76                if timeline == &entry_timeline {
77                    match entry.item() {
78                        CatalogItem::Table(table) => {
79                            id_bundle.storage_ids.extend(table.global_ids());
80                        }
81                        CatalogItem::Source(source) => {
82                            id_bundle.storage_ids.insert(source.global_id());
83                        }
84                        CatalogItem::MaterializedView(mv) => {
85                            id_bundle.storage_ids.insert(mv.global_id_writes());
86                        }
87                        CatalogItem::Index(index) => {
88                            id_bundle
89                                .compute_ids
90                                .entry(index.cluster_id)
91                                .or_default()
92                                .insert(index.global_id());
93                        }
94                        CatalogItem::View(_)
95                        | CatalogItem::Sink(_)
96                        | CatalogItem::MetricSink(_)
97                        | CatalogItem::Type(_)
98                        | CatalogItem::Func(_)
99                        | CatalogItem::Secret(_)
100                        | CatalogItem::Connection(_)
101                        | CatalogItem::Log(_) => {}
102                    }
103                }
104            }
105        }
106        id_bundle
107    }
108
109    /// Return an error if the ids are from incompatible [`TimelineContext`]s. This should
110    /// be used to prevent users from doing things that are either meaningless
111    /// (joining data from timelines that have similar numbers with different
112    /// meanings like two separate debezium topics) or will never complete (joining
113    /// cdcv2 and realtime data).
114    pub(crate) fn validate_timeline_context<I>(
115        &self,
116        ids: I,
117    ) -> Result<TimelineContext, AdapterError>
118    where
119        I: IntoIterator<Item = GlobalId>,
120    {
121        let items_ids = ids
122            .into_iter()
123            .filter_map(|gid| self.try_resolve_item_id(&gid));
124        let mut timeline_contexts: Vec<_> =
125            self.get_timeline_contexts(items_ids).into_iter().collect();
126        // If there's more than one timeline, we will not produce meaningful
127        // data to a user. Take, for example, some realtime source and a debezium
128        // consistency topic source. The realtime source uses something close to now
129        // for its timestamps. The debezium source starts at 1 and increments per
130        // transaction. We don't want to choose some timestamp that is valid for both
131        // of these because the debezium source will never get to the same value as the
132        // realtime source's "milliseconds since Unix epoch" value. And even if it did,
133        // it's not meaningful to join just because those two numbers happen to be the
134        // same now.
135        //
136        // Another example: assume two separate debezium consistency topics. Both
137        // start counting at 1 and thus have similarish numbers that probably overlap
138        // a lot. However it's still not meaningful to join those two at a specific
139        // transaction counter number because those counters are unrelated to the
140        // other.
141        let timelines: Vec<_> = timeline_contexts
142            .extract_if(.., |timeline_context| timeline_context.contains_timeline())
143            .collect();
144
145        // A single or group of objects may contain multiple compatible timeline
146        // contexts. For example `SELECT *, 1, mz_now() FROM t` will contain all
147        // types of contexts. We choose the strongest context level to return back.
148        if timelines.len() > 1 {
149            Err(AdapterError::Unsupported(
150                "multiple timelines within one dataflow",
151            ))
152        } else if timelines.len() == 1 {
153            Ok(timelines.into_element())
154        } else if timeline_contexts
155            .iter()
156            .contains(&TimelineContext::TimestampDependent)
157        {
158            Ok(TimelineContext::TimestampDependent)
159        } else {
160            Ok(TimelineContext::TimestampIndependent)
161        }
162    }
163
164    /// Return the [`TimelineContext`]s belonging to a list of [`CatalogItemId`]s, if any exist.
165    fn get_timeline_contexts<I>(&self, ids: I) -> BTreeSet<TimelineContext>
166    where
167        I: IntoIterator<Item = CatalogItemId>,
168    {
169        let mut seen: BTreeSet<CatalogItemId> = BTreeSet::new();
170        let mut timelines: BTreeSet<TimelineContext> = BTreeSet::new();
171
172        // Recurse through IDs to find all sources and tables, adding new ones to
173        // the set until we reach the bottom.
174        let mut ids: Vec<_> = ids.into_iter().collect();
175        while let Some(id) = ids.pop() {
176            // Protect against possible infinite recursion. Not sure if it's possible, but
177            // a cheap prevention for the future.
178            if !seen.insert(id) {
179                continue;
180            }
181            if let Some(entry) = self.try_get_entry(&id) {
182                match entry.item() {
183                    CatalogItem::Source(source) => {
184                        timelines
185                            .insert(TimelineContext::TimelineDependent(source.timeline.clone()));
186                    }
187                    CatalogItem::Index(index) => {
188                        let on_id = self.resolve_item_id(&index.on);
189                        ids.push(on_id);
190                    }
191                    CatalogItem::View(View {
192                        locally_optimized_expr: optimized_expr,
193                        ..
194                    }) => {
195                        // If the definition contains a temporal function, the timeline must
196                        // be timestamp dependent.
197                        if optimized_expr.contains_temporal() {
198                            timelines.insert(TimelineContext::TimestampDependent);
199                        } else {
200                            timelines.insert(TimelineContext::TimestampIndependent);
201                        }
202                        let item_ids = optimized_expr
203                            .depends_on()
204                            .into_iter()
205                            .map(|gid| self.resolve_item_id(&gid));
206                        ids.extend(item_ids);
207                    }
208                    CatalogItem::MaterializedView(MaterializedView {
209                        locally_optimized_expr: optimized_expr,
210                        ..
211                    }) => {
212                        // In some cases the timestamp selected may not affect the answer to a
213                        // query, but it may affect our ability to query the materialized view.
214                        // Materialized views must durably materialize the result of a query, even
215                        // for constant queries. If we choose a timestamp larger than the upper,
216                        // which represents the current progress of the view, then the query will
217                        // need to block and wait for the materialized view to advance.
218                        timelines.insert(TimelineContext::TimestampDependent);
219                        let item_ids = optimized_expr
220                            .depends_on()
221                            .into_iter()
222                            .map(|gid| self.resolve_item_id(&gid));
223                        ids.extend(item_ids);
224                    }
225                    CatalogItem::Table(table) => {
226                        timelines.insert(TimelineContext::TimelineDependent(table.timeline()));
227                    }
228                    CatalogItem::Log(_) => {
229                        timelines.insert(TimelineContext::TimelineDependent(
230                            Timeline::EpochMilliseconds,
231                        ));
232                    }
233                    CatalogItem::Sink(_)
234                    | CatalogItem::MetricSink(_)
235                    | CatalogItem::Type(_)
236                    | CatalogItem::Func(_)
237                    | CatalogItem::Secret(_)
238                    | CatalogItem::Connection(_) => {}
239                }
240            }
241        }
242
243        timelines
244    }
245}