Skip to main content

mz_adapter/coord/
timestamp_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//! Logic for selecting timestamps for various operations on collections.
11
12use std::fmt;
13
14use async_trait::async_trait;
15use chrono::{DateTime, Utc};
16use constraints::Constraints;
17use differential_dataflow::lattice::Lattice;
18use itertools::Itertools;
19use mz_compute_types::ComputeInstanceId;
20use mz_repr::{GlobalId, Timestamp, TimestampManipulation};
21use mz_sql::plan::QueryWhen;
22use mz_sql::session::vars::IsolationLevel;
23use mz_storage_types::sources::Timeline;
24use serde::{Deserialize, Serialize};
25use timely::progress::{Antichain, Timestamp as _};
26
27use crate::AdapterError;
28use crate::catalog::CatalogState;
29use crate::coord::Coordinator;
30use crate::coord::id_bundle::CollectionIdBundle;
31use crate::coord::read_policy::ReadHolds;
32use crate::coord::timeline::TimelineContext;
33use crate::session::Session;
34
35/// The timeline and timestamp context of a read.
36#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
37pub enum TimestampContext {
38    /// Read is executed in a specific timeline with a specific timestamp.
39    TimelineTimestamp {
40        timeline: Timeline,
41        /// The timestamp that was chosen for a read. This can differ from the
42        /// `oracle_ts` when collections are not readable at the (linearized)
43        /// timestamp for the oracle. In those cases (when the chosen timestamp
44        /// is further ahead than the oracle timestamp) we have to delay
45        /// returning peek results until the timestamp oracle is also
46        /// sufficiently advanced.
47        chosen_ts: Timestamp,
48        /// The timestamp that would have been chosen for the read by the
49        /// (linearized) timestamp oracle). In most cases this will be picked as
50        /// the `chosen_ts`.
51        oracle_ts: Option<Timestamp>,
52    },
53    /// Read is executed without a timeline or timestamp.
54    NoTimestamp,
55}
56
57impl TimestampContext {
58    /// Returns the timestamp that must be reached before this read can complete.
59    pub(crate) fn timestamp_to_linearize(&self) -> Option<(&Timeline, &Timestamp)> {
60        // The oracle result belongs to this transaction. A result cached from an
61        // earlier transaction would not establish its real-time bound.
62        match self {
63            Self::TimelineTimestamp {
64                timeline,
65                chosen_ts,
66                oracle_ts: Some(oracle_ts),
67            } if chosen_ts > oracle_ts => Some((timeline, chosen_ts)),
68            _ => None,
69        }
70    }
71
72    /// Creates a `TimestampContext` from a timestamp and `TimelineContext`.
73    pub fn from_timeline_context(
74        chosen_ts: Timestamp,
75        oracle_ts: Option<Timestamp>,
76        transaction_timeline: Option<Timeline>,
77        timeline_context: &TimelineContext,
78    ) -> TimestampContext {
79        match timeline_context {
80            TimelineContext::TimelineDependent(timeline) => {
81                if let Some(transaction_timeline) = transaction_timeline {
82                    assert_eq!(timeline, &transaction_timeline);
83                }
84                Self::TimelineTimestamp {
85                    timeline: timeline.clone(),
86                    chosen_ts,
87                    oracle_ts,
88                }
89            }
90            TimelineContext::TimestampDependent => {
91                // We default to the `Timeline::EpochMilliseconds` timeline if one doesn't exist.
92                Self::TimelineTimestamp {
93                    timeline: transaction_timeline.unwrap_or(Timeline::EpochMilliseconds),
94                    chosen_ts,
95                    oracle_ts,
96                }
97            }
98            TimelineContext::TimestampIndependent => Self::NoTimestamp,
99        }
100    }
101
102    /// The timeline belonging to this context, if one exists.
103    pub fn timeline(&self) -> Option<&Timeline> {
104        self.timeline_timestamp().map(|tt| tt.0)
105    }
106
107    /// The timestamp belonging to this context, if one exists.
108    pub fn timestamp(&self) -> Option<&Timestamp> {
109        self.timeline_timestamp().map(|tt| tt.1)
110    }
111
112    /// The timeline and timestamp belonging to this context, if one exists.
113    pub fn timeline_timestamp(&self) -> Option<(&Timeline, &Timestamp)> {
114        match self {
115            Self::TimelineTimestamp {
116                timeline,
117                chosen_ts,
118                ..
119            } => Some((timeline, chosen_ts)),
120            Self::NoTimestamp => None,
121        }
122    }
123
124    /// The timestamp belonging to this context, or a sensible default if one does not exists.
125    pub fn timestamp_or_default(&self) -> Timestamp {
126        match self {
127            Self::TimelineTimestamp { chosen_ts, .. } => chosen_ts.clone(),
128            // Anything without a timestamp is given the maximum possible timestamp to indicate
129            // that they have been closed up until the end of time.
130            Self::NoTimestamp => Timestamp::maximum(),
131        }
132    }
133
134    /// Whether or not the context contains a timestamp.
135    pub fn contains_timestamp(&self) -> bool {
136        self.timestamp().is_some()
137    }
138
139    /// Converts this `TimestampContext` to an `Antichain`.
140    pub fn antichain(&self) -> Antichain<Timestamp> {
141        Antichain::from_elem(self.timestamp_or_default())
142    }
143}
144
145#[async_trait(?Send)]
146impl TimestampProvider for Coordinator {
147    /// Reports a collection's current read frontier.
148    fn compute_read_frontier(
149        &self,
150        instance: ComputeInstanceId,
151        id: GlobalId,
152    ) -> Antichain<Timestamp> {
153        self.controller
154            .compute
155            .collection_frontiers(id, Some(instance))
156            .expect("id does not exist")
157            .read_frontier
158    }
159
160    /// Reports a collection's current write frontier.
161    fn compute_write_frontier(
162        &self,
163        instance: ComputeInstanceId,
164        id: GlobalId,
165    ) -> Antichain<Timestamp> {
166        self.controller
167            .compute
168            .collection_frontiers(id, Some(instance))
169            .expect("id does not exist")
170            .write_frontier
171    }
172
173    fn storage_frontiers(
174        &self,
175        ids: Vec<GlobalId>,
176    ) -> Vec<(GlobalId, Antichain<Timestamp>, Antichain<Timestamp>)> {
177        self.controller
178            .storage
179            .collections_frontiers(ids)
180            .expect("missing collections")
181    }
182
183    fn acquire_read_holds(&self, id_bundle: &CollectionIdBundle) -> ReadHolds {
184        self.acquire_read_holds(id_bundle)
185    }
186
187    fn catalog_state(&self) -> &CatalogState {
188        self.catalog().state()
189    }
190}
191
192/// A timestamp determination, which includes the timestamp, constraints, and session oracle read
193/// timestamp.
194#[derive(Debug, Clone, Serialize, Deserialize)]
195pub struct RawTimestampDetermination {
196    pub timestamp: Timestamp,
197    pub constraints: Constraints,
198    pub session_oracle_read_ts: Option<Timestamp>,
199}
200
201#[async_trait(?Send)]
202pub trait TimestampProvider {
203    fn compute_read_frontier(
204        &self,
205        instance: ComputeInstanceId,
206        id: GlobalId,
207    ) -> Antichain<Timestamp>;
208    fn compute_write_frontier(
209        &self,
210        instance: ComputeInstanceId,
211        id: GlobalId,
212    ) -> Antichain<Timestamp>;
213
214    /// Returns the implied capability (since) and write frontier (upper) for
215    /// the specified storage collections.
216    fn storage_frontiers(
217        &self,
218        ids: Vec<GlobalId>,
219    ) -> Vec<(GlobalId, Antichain<Timestamp>, Antichain<Timestamp>)>;
220
221    fn catalog_state(&self) -> &CatalogState;
222
223    fn get_timeline(timeline_context: &TimelineContext) -> Option<Timeline> {
224        let timeline = match timeline_context {
225            TimelineContext::TimelineDependent(timeline) => Some(timeline.clone()),
226            // We default to the `Timeline::EpochMilliseconds` timeline if one doesn't exist.
227            TimelineContext::TimestampDependent => Some(Timeline::EpochMilliseconds),
228            TimelineContext::TimestampIndependent => None,
229        };
230
231        timeline
232    }
233
234    /// Returns true if-and-only-if the given configuration needs a linearized
235    /// read timestamp from a timestamp oracle.
236    ///
237    /// This assumes that the query happens in the context of a timeline. If
238    /// there is no timeline, we cannot and don't have to get a linearized read
239    /// timestamp.
240    fn needs_linearized_read_ts(isolation_level: &IsolationLevel, when: &QueryWhen) -> bool {
241        // When we're in the context of a timeline (assumption) and one of these
242        // scenarios hold, we need to use a linearized read timestamp:
243        // - The isolation level anchors against the oracle (Strict Serializable,
244        //   Strong Session Serializable, Bounded Staleness) and the `when` allows
245        //   us to use the timestamp oracle (ex: queries with no AS OF).
246        // - The `when` requires us to use the timestamp oracle (ex: read-then-write
247        //   queries).
248        when.must_advance_to_timeline_ts()
249            || (when.can_advance_to_timeline_ts()
250                && matches!(
251                    isolation_level,
252                    IsolationLevel::StrictSerializable
253                        | IsolationLevel::StrongSessionSerializable
254                        | IsolationLevel::BoundedStaleness(_)
255                ))
256    }
257
258    /// Uses constraints and preferences to determine a timestamp for a query.
259    /// Returns the determined timestamp, the constraints that were applied, and
260    /// session_oracle_read_ts.
261    fn determine_timestamp_via_constraints(
262        session: &Session,
263        read_holds: &ReadHolds,
264        id_bundle: &CollectionIdBundle,
265        when: &QueryWhen,
266        oracle_read_ts: Option<Timestamp>,
267        real_time_recency_ts: Option<Timestamp>,
268        isolation_level: &IsolationLevel,
269        timeline: &Option<Timeline>,
270        largest_not_in_advance_of_upper: Timestamp,
271    ) -> Result<RawTimestampDetermination, AdapterError> {
272        use constraints::{Constraints, Preference, Reason};
273
274        let mut session_oracle_read_ts = None;
275        // We start by establishing the hard constraints that must be applied to timestamp determination.
276        // These constraints are derived from the input arguments, and properties of the collections involved.
277        // TODO: Many of the constraints are expressed obliquely, and could be made more direct.
278        let constraints = {
279            // Constraints we will populate through a sequence of opinions.
280            let mut constraints = Constraints::default();
281
282            // First, we have validity constraints from the `id_bundle` argument which indicates
283            // which collections we are reading from.
284            // TODO: Refine the detail about which identifiers are binding and which are not.
285            // TODO(dov): It's not entirely clear to me that there ever would be a non
286            // binding constraint introduced by the `id_bundle`. We should revisit this.
287            let since = read_holds.least_valid_read();
288            let storage = id_bundle
289                .storage_ids
290                .iter()
291                .cloned()
292                .collect::<Vec<GlobalId>>();
293            if !storage.is_empty() {
294                constraints
295                    .lower
296                    .push((since.clone(), Reason::StorageInput(storage)));
297            }
298            let compute = id_bundle
299                .compute_ids
300                .iter()
301                .flat_map(|(key, ids)| ids.iter().map(|id| (*key, *id)))
302                .collect::<Vec<(ComputeInstanceId, GlobalId)>>();
303            if !compute.is_empty() {
304                constraints
305                    .lower
306                    .push((since.clone(), Reason::ComputeInput(compute)));
307            }
308
309            // The query's `when` may indicates a specific timestamp we must advance to, or a specific value we must use.
310            if let Some(ts) = when.advance_to_timestamp() {
311                constraints
312                    .lower
313                    .push((Antichain::from_elem(ts), Reason::QueryAsOf));
314                // If the query is at a specific timestamp, we must introduce an upper bound as well.
315                if when.constrains_upper() {
316                    constraints
317                        .upper
318                        .push((Antichain::from_elem(ts), Reason::QueryAsOf));
319                }
320            }
321
322            // The specification of an `oracle_read_ts` may indicates that we must advance to it,
323            // except in some isolation modes, or if `when` does not indicate that we should.
324            // At the moment, only `QueryWhen::FreshestTableWrite` indicates that we should.
325            // TODO: Should this just depend on the isolation level?
326            if let Some(timestamp) = &oracle_read_ts {
327                // Whether this isolation level treats `oracle_read_ts` as a hard
328                // lower bound. Strong session serializable (session-local oracle)
329                // and bounded staleness (`oracle - D` anchor) instead consult it
330                // below; pushing it here would shadow those semantics.
331                let hard_lower_bound = match isolation_level {
332                    IsolationLevel::StrongSessionSerializable
333                    | IsolationLevel::BoundedStaleness(_) => false,
334                    IsolationLevel::ReadUncommitted
335                    | IsolationLevel::ReadCommitted
336                    | IsolationLevel::RepeatableRead
337                    | IsolationLevel::Serializable
338                    | IsolationLevel::StrictSerializable => true,
339                };
340                // `must_advance_to_timeline_ts()` (only `FreshestTableWrite`)
341                // forces the bound regardless; bounded staleness rejects writes
342                // upstream, so that path is unreachable for it in practice.
343                if hard_lower_bound || when.must_advance_to_timeline_ts() {
344                    constraints.lower.push((
345                        Antichain::from_elem(*timestamp),
346                        Reason::IsolationLevel(*isolation_level),
347                    ));
348                }
349            }
350
351            // If a real time recency timestamp is supplied, we must advance to it.
352            if let Some(real_time_recency_ts) = real_time_recency_ts {
353                assert!(
354                    session.vars().real_time_recency()
355                        && isolation_level == &IsolationLevel::StrictSerializable,
356                    "real time recency timestamp should only be supplied when real time recency \
357                                is enabled and the isolation level is strict serializable"
358                );
359                constraints.lower.push((
360                    Antichain::from_elem(real_time_recency_ts),
361                    Reason::RealTimeRecency,
362                ));
363            }
364
365            // Bounded staleness anchors the freshness floor at `oracle.read_ts - D`
366            // and clamps the upper at `largest_not_in_advance_of_upper`. The upper
367            // clamp is what makes an infeasible bound fail fast in the coordinator
368            // instead of blocking on compute for the upper to advance — which would
369            // make the failure mode cluster-shape-dependent. `oracle_read_ts` is
370            // `None` under `AS OF`, where the user-chosen `T` is the only constraint.
371            if let IsolationLevel::BoundedStaleness(d) = isolation_level {
372                if let Some(anchor) = oracle_read_ts {
373                    let bound_ms = u64::try_from(d.as_millis()).unwrap_or(u64::MAX);
374                    let lower = anchor.saturating_sub(bound_ms);
375                    constraints.lower.push((
376                        Antichain::from_elem(lower),
377                        Reason::IsolationLevel(*isolation_level),
378                    ));
379                    constraints.upper.push((
380                        Antichain::from_elem(largest_not_in_advance_of_upper),
381                        Reason::IsolationLevel(*isolation_level),
382                    ));
383                }
384            }
385
386            // If we are operating in Strong Session Serializable, we use an alternate timestamp lower bound.
387            if isolation_level == &IsolationLevel::StrongSessionSerializable {
388                if let Some(timeline) = &timeline {
389                    if let Some(oracle) = session.get_timestamp_oracle(timeline) {
390                        let session_ts = oracle.read_ts();
391                        constraints.lower.push((
392                            Antichain::from_elem(session_ts),
393                            Reason::IsolationLevel(*isolation_level),
394                        ));
395                        session_oracle_read_ts = Some(session_ts);
396                    }
397
398                    // When advancing the read timestamp under Strong Session Serializable, there is a
399                    // trade-off to make between freshness and latency. We can choose a timestamp close the
400                    // `upper`, but then later queries might block if the `upper` is too far into the
401                    // future. We can chose a timestamp close to the current time, but then we may not be
402                    // getting results that are as fresh as possible. As a heuristic, we choose the minimum
403                    // of now and the upper, where we use the global timestamp oracle read timestamp as a
404                    // proxy for now. If upper > now, then we choose now and prevent blocking future
405                    // queries. If upper < now, then we choose the upper and prevent blocking the current
406                    // query.
407                    if when.can_advance_to_upper() && when.can_advance_to_timeline_ts() {
408                        let mut advance_to = largest_not_in_advance_of_upper;
409                        if let Some(oracle_read_ts) = oracle_read_ts {
410                            advance_to = std::cmp::min(advance_to, oracle_read_ts);
411                        }
412                        constraints.lower.push((
413                            Antichain::from_elem(advance_to),
414                            Reason::IsolationLevel(*isolation_level),
415                        ));
416                    }
417                }
418            }
419
420            constraints.minimize();
421            constraints
422        };
423
424        // Next we establish the preferences that we would like to apply to timestamp determination.
425        // Generally, we want to choose the freshest timestamp possible, although there are exceptions
426        // when we either want a maximally *stale* timestamp, or we want to protect other queries from
427        // a recklessly advanced timestamp.
428        let preferences = {
429            // Counter-intuitively, the only `when` that allows `can_advance_to_upper` is `Immediately`,
430            // and not `FreshestTableWrite`. This is because `FreshestTableWrite` instead imposes a lower
431            // bound through the `oracle_read_ts`, and then requires the stalest valid timestamp.
432
433            if when.can_advance_to_upper()
434                && (isolation_level == &IsolationLevel::Serializable
435                    || matches!(isolation_level, IsolationLevel::BoundedStaleness(_))
436                    || timeline.is_none())
437            {
438                Preference::FreshestAvailable
439            } else {
440                Preference::StalestValid
441            }
442
443            // TODO: `StrongSessionSerializable` has a different set of preferences that starts to tease
444            // out the trade-off between freshness and responsiveness. I think we don't yet know enough
445            // to properly frame these preferences, though they are clearly aimed at the right concerns.
446        };
447
448        // Determine a candidate based on constraints and preferences.
449        let constraint_candidate = {
450            let mut candidate = Timestamp::minimum();
451            // Note: These `advance_by` calls are no-ops if the given frontier is `[]`.
452            candidate.advance_by(constraints.lower_bound().borrow());
453            // If we have a preference to be the freshest available, advance to the minimum
454            // of the upper bound constraints and the `largest_not_in_advance_of_upper`.
455            if let Preference::FreshestAvailable = preferences {
456                let mut upper_bound = constraints.upper_bound();
457                upper_bound.insert(largest_not_in_advance_of_upper);
458                candidate.advance_by(upper_bound.borrow());
459            }
460            // If the candidate is strictly outside the constraints, we didn't have a viable
461            // timestamp. This can happen e.g. when the query has AS OF, or when the lower bound is
462            // `[]`.
463            if !constraints.lower_bound().less_equal(&candidate)
464                || constraints.upper_bound().less_than(&candidate)
465            {
466                // Bounded staleness wants a specific error describing the staleness
467                // gap. Derive it directly from `anchor - D` and the inputs' upper,
468                // not from `constraints.{lower,upper}_bound()` — those join *all*
469                // reasons (`since`, `AS OF`, …), so a non-bs constraint could
470                // dominate and the reported gap would not describe the bs failure.
471                // A zero gap means the bs floor was satisfiable and something else
472                // caused the infeasibility; fall through to the generic error.
473                // `oracle_read_ts` is unset under `AS OF`, where bs added no
474                // constraint, so we cannot reach here for a bs-specific failure.
475                if let IsolationLevel::BoundedStaleness(d) = isolation_level {
476                    if let Some(anchor) = oracle_read_ts {
477                        let bound_ms = u64::try_from(d.as_millis()).unwrap_or(u64::MAX);
478                        let bs_lower: u64 = anchor.saturating_sub(bound_ms).into();
479                        let upper: u64 = largest_not_in_advance_of_upper.into();
480                        let gap = bs_lower.saturating_sub(upper);
481                        if gap > 0 {
482                            return Err(AdapterError::BoundedStalenessExceeded {
483                                bound: *d,
484                                gap_ms: gap,
485                                slowest_input: None,
486                            });
487                        }
488                    }
489                }
490                return Err(AdapterError::ImpossibleTimestampConstraints {
491                    constraints: constraints.display(timeline.as_ref()).to_string(),
492                });
493            } else {
494                candidate
495            }
496        };
497
498        Ok(RawTimestampDetermination {
499            timestamp: constraint_candidate,
500            constraints,
501            session_oracle_read_ts,
502        })
503    }
504
505    /// Determines the timestamp for a query.
506    ///
507    /// Timestamp determination may fail due to the restricted validity of
508    /// traces. Each has a `since` and `upper` frontier, and are only valid
509    /// after `since` and sure to be available not after `upper`.
510    ///
511    /// The timeline that `id_bundle` belongs to is also returned, if one exists.
512    fn determine_timestamp_for(
513        &self,
514        session: &Session,
515        id_bundle: &CollectionIdBundle,
516        when: &QueryWhen,
517        timeline_context: &TimelineContext,
518        oracle_read_ts: Option<Timestamp>,
519        real_time_recency_ts: Option<Timestamp>,
520        isolation_level: &IsolationLevel,
521    ) -> Result<(TimestampDetermination, ReadHolds), AdapterError> {
522        // First, we acquire read holds that will ensure the queried collections
523        // stay queryable at the chosen timestamp.
524        let read_holds = self.acquire_read_holds(id_bundle);
525
526        let upper = self.least_valid_write(id_bundle);
527
528        Self::determine_timestamp_for_inner(
529            session,
530            id_bundle,
531            when,
532            timeline_context,
533            oracle_read_ts,
534            real_time_recency_ts,
535            isolation_level,
536            read_holds,
537            upper,
538        )
539    }
540
541    /// Same as determine_timestamp_for, but read_holds and least_valid_write are already passed in.
542    fn determine_timestamp_for_inner(
543        session: &Session,
544        id_bundle: &CollectionIdBundle,
545        when: &QueryWhen,
546        timeline_context: &TimelineContext,
547        oracle_read_ts: Option<Timestamp>,
548        real_time_recency_ts: Option<Timestamp>,
549        isolation_level: &IsolationLevel,
550        read_holds: ReadHolds,
551        upper: Antichain<Timestamp>,
552    ) -> Result<(TimestampDetermination, ReadHolds), AdapterError> {
553        let timeline = Self::get_timeline(timeline_context);
554        let largest_not_in_advance_of_upper = Coordinator::largest_not_in_advance_of_upper(&upper);
555        let since = read_holds.least_valid_read();
556
557        // If the `since` is empty, then timestamp determination would fail. Let's return a more
558        // specific error in this case: Empty `since` frontiers happen here when collections were
559        // dropped concurrently with sequencing the query.
560        if since.is_empty() {
561            // Figure out what made the since frontier empty.
562            let mut unreadable_collections = Vec::new();
563            for (coll_id, hold) in read_holds.storage_holds {
564                if hold.since().is_empty() {
565                    unreadable_collections.push(coll_id);
566                }
567            }
568            for ((_instance_id, coll_id), hold) in read_holds.compute_holds {
569                if hold.since().is_empty() {
570                    unreadable_collections.push(coll_id);
571                }
572            }
573            return Err(AdapterError::CollectionUnreadable {
574                id: unreadable_collections.into_iter().join(", "),
575            });
576        }
577
578        // Bounded staleness freshness math assumes the EpochMilliseconds timeline,
579        // where timestamps are wall-clock milliseconds. Timeline-less queries
580        // (`TimestampIndependent`, e.g. constant queries) are fine — the freshness
581        // contract is vacuous for them.
582        if isolation_level.is_bounded_staleness()
583            && matches!(&timeline, Some(t) if *t != Timeline::EpochMilliseconds)
584        {
585            return Err(AdapterError::BoundedStalenessTimelineUnsupported);
586        }
587
588        let raw_determination = Self::determine_timestamp_via_constraints(
589            session,
590            &read_holds,
591            id_bundle,
592            when,
593            oracle_read_ts,
594            real_time_recency_ts,
595            isolation_level,
596            &timeline,
597            largest_not_in_advance_of_upper,
598        )?;
599
600        let timestamp_context = TimestampContext::from_timeline_context(
601            raw_determination.timestamp,
602            oracle_read_ts,
603            timeline,
604            timeline_context,
605        );
606
607        let determination = TimestampDetermination {
608            timestamp_context,
609            since,
610            upper,
611            largest_not_in_advance_of_upper,
612            oracle_read_ts,
613            session_oracle_read_ts: raw_determination.session_oracle_read_ts,
614            real_time_recency_ts,
615            constraints: raw_determination.constraints,
616        };
617
618        Ok((determination, read_holds))
619    }
620
621    /// Acquires [ReadHolds], for the given `id_bundle` at the earliest possible
622    /// times.
623    fn acquire_read_holds(&self, id_bundle: &CollectionIdBundle) -> ReadHolds;
624
625    /// The smallest common valid write frontier among the specified collections.
626    ///
627    /// Times that are not greater or equal to this frontier are complete for all collections
628    /// identified as arguments.
629    fn least_valid_write(&self, id_bundle: &CollectionIdBundle) -> Antichain<mz_repr::Timestamp> {
630        let mut upper = Antichain::new();
631        {
632            for (_id, _since, collection_upper) in
633                self.storage_frontiers(id_bundle.storage_ids.iter().cloned().collect_vec())
634            {
635                upper.extend(collection_upper);
636            }
637        }
638        {
639            for (instance, compute_ids) in &id_bundle.compute_ids {
640                for id in compute_ids.iter() {
641                    upper.extend(self.compute_write_frontier(*instance, *id));
642                }
643            }
644        }
645        upper
646    }
647
648    /// Returns `least_valid_write` - 1, i.e., each time in `least_valid_write` stepped back in a
649    /// saturating way.
650    fn greatest_available_read(&self, id_bundle: &CollectionIdBundle) -> Antichain<Timestamp> {
651        let mut frontier = Antichain::new();
652        for t in self.least_valid_write(id_bundle) {
653            frontier.insert(t.step_back().unwrap_or(t));
654        }
655        frontier
656    }
657}
658
659impl Coordinator {
660    /// The largest timestamp not greater or equal to an element of `upper`.
661    ///
662    /// If no such timestamp exists, for example because `upper` contains only the
663    /// minimal timestamp, the return value is `Timestamp::minimum()`.
664    pub(crate) fn largest_not_in_advance_of_upper(
665        upper: &Antichain<mz_repr::Timestamp>,
666    ) -> mz_repr::Timestamp {
667        // We peek at the largest element not in advance of `upper`, which
668        // involves a subtraction. If `upper` contains a zero timestamp there
669        // is no "prior" answer, and we do not want to peek at it as it risks
670        // hanging awaiting the response to data that may never arrive.
671        if let Some(upper) = upper.as_option() {
672            upper.step_back().unwrap_or_else(Timestamp::minimum)
673        } else {
674            // A complete trace can be read in its final form with this time.
675            //
676            // This should only happen for literals that have no sources or sources that
677            // are known to have completed (non-tailed files for example).
678            Timestamp::MAX
679        }
680    }
681}
682
683/// Information used when determining the timestamp for a query.
684#[derive(Serialize, Deserialize, Debug, Clone)]
685pub struct TimestampDetermination {
686    /// The chosen timestamp context.
687    pub timestamp_context: TimestampContext,
688    /// The read frontier of all involved sources.
689    pub since: Antichain<Timestamp>,
690    /// The write frontier of all involved sources.
691    pub upper: Antichain<Timestamp>,
692    /// The largest timestamp not in advance of upper.
693    pub largest_not_in_advance_of_upper: Timestamp,
694    /// The value of the timeline's oracle timestamp, if used.
695    pub oracle_read_ts: Option<Timestamp>,
696    /// The value of the session local timestamp's oracle timestamp, if used.
697    pub session_oracle_read_ts: Option<Timestamp>,
698    /// The value of the real time recency timestamp, if used.
699    pub real_time_recency_ts: Option<Timestamp>,
700    /// The constraints used by the constraint based solver.
701    /// See the [`constraints`] module for more information.
702    pub constraints: Constraints,
703}
704
705impl TimestampDetermination {
706    pub fn respond_immediately(&self) -> bool {
707        match &self.timestamp_context {
708            TimestampContext::TimelineTimestamp { chosen_ts, .. } => {
709                !self.upper.less_equal(chosen_ts)
710            }
711            TimestampContext::NoTimestamp => true,
712        }
713    }
714
715    /// The timestamp at which a `SUBSCRIBE` reading this determination starts.
716    ///
717    /// A read without a timestamp is valid at every time, so it starts at the
718    /// query's exact `AS OF` if it gave one, and at [`Timestamp::MAX`]
719    /// otherwise, including for `AS OF AT LEAST`.
720    pub fn subscribe_as_of(&self) -> Timestamp {
721        match &self.timestamp_context {
722            TimestampContext::TimelineTimestamp { chosen_ts, .. } => *chosen_ts,
723            TimestampContext::NoTimestamp => self
724                .constraints
725                .upper_bound()
726                .into_option()
727                .unwrap_or_else(Timestamp::maximum),
728        }
729    }
730}
731
732/// Information used when determining the timestamp for a query.
733#[derive(Clone, Debug, Serialize, Deserialize)]
734pub struct TimestampExplanation {
735    /// The chosen timestamp.
736    pub determination: TimestampDetermination,
737    /// Details about each source.
738    pub sources: Vec<TimestampSource>,
739    /// Wall time of first statement executed in this transaction
740    pub session_wall_time: DateTime<Utc>,
741    /// Cached value of determination.respond_immediately()
742    pub respond_immediately: bool,
743}
744
745#[derive(Clone, Debug, Serialize, Deserialize)]
746pub struct TimestampSource {
747    pub name: String,
748    pub read_frontier: Vec<Timestamp>,
749    pub write_frontier: Vec<Timestamp>,
750}
751
752pub trait DisplayableInTimeline {
753    fn fmt(&self, timeline: Option<&Timeline>, f: &mut fmt::Formatter) -> fmt::Result;
754    fn display<'a>(&'a self, timeline: Option<&'a Timeline>) -> DisplayInTimeline<'a, Self> {
755        DisplayInTimeline { t: self, timeline }
756    }
757}
758
759impl DisplayableInTimeline for mz_repr::Timestamp {
760    fn fmt(&self, timeline: Option<&Timeline>, f: &mut fmt::Formatter) -> fmt::Result {
761        if let Some(Timeline::EpochMilliseconds) = timeline {
762            let ts_ms: u64 = self.into();
763            if let Ok(ts_ms) = i64::try_from(ts_ms) {
764                if let Some(ndt) = DateTime::from_timestamp_millis(ts_ms) {
765                    return write!(f, "{:13} ({})", self, ndt.format("%Y-%m-%d %H:%M:%S%.3f"));
766                }
767            }
768        }
769        write!(f, "{:13}", self)
770    }
771}
772
773pub struct DisplayInTimeline<'a, T: ?Sized> {
774    t: &'a T,
775    timeline: Option<&'a Timeline>,
776}
777impl<'a, T> fmt::Display for DisplayInTimeline<'a, T>
778where
779    T: DisplayableInTimeline,
780{
781    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
782        self.t.fmt(self.timeline, f)
783    }
784}
785
786impl<'a, T> fmt::Debug for DisplayInTimeline<'a, T>
787where
788    T: DisplayableInTimeline,
789{
790    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
791        fmt::Display::fmt(&self, f)
792    }
793}
794
795impl fmt::Display for TimestampExplanation {
796    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
797        let timeline = self.determination.timestamp_context.timeline();
798        writeln!(
799            f,
800            "                query timestamp: {}",
801            self.determination
802                .timestamp_context
803                .timestamp_or_default()
804                .display(timeline)
805        )?;
806        if let Some(oracle_read_ts) = &self.determination.oracle_read_ts {
807            writeln!(
808                f,
809                "          oracle read timestamp: {}",
810                oracle_read_ts.display(timeline)
811            )?;
812        }
813        if let Some(session_oracle_read_ts) = &self.determination.session_oracle_read_ts {
814            writeln!(
815                f,
816                "  session oracle read timestamp: {}",
817                session_oracle_read_ts.display(timeline)
818            )?;
819        }
820        if let Some(real_time_recency_ts) = &self.determination.real_time_recency_ts {
821            writeln!(
822                f,
823                "    real time recency timestamp: {}",
824                real_time_recency_ts.display(timeline)
825            )?;
826        }
827        writeln!(
828            f,
829            "largest not in advance of upper: {}",
830            self.determination
831                .largest_not_in_advance_of_upper
832                .display(timeline),
833        )?;
834        writeln!(
835            f,
836            "                          upper:{:?}",
837            self.determination
838                .upper
839                .iter()
840                .map(|t| t.display(timeline))
841                .collect::<Vec<_>>()
842        )?;
843        writeln!(
844            f,
845            "                          since:{:?}",
846            self.determination
847                .since
848                .iter()
849                .map(|t| t.display(timeline))
850                .collect::<Vec<_>>()
851        )?;
852        writeln!(
853            f,
854            "        can respond immediately: {}",
855            self.respond_immediately
856        )?;
857        writeln!(f, "                       timeline: {:?}", timeline)?;
858        writeln!(
859            f,
860            "              session wall time: {:13} ({})",
861            self.session_wall_time.timestamp_millis(),
862            self.session_wall_time.format("%Y-%m-%d %H:%M:%S%.3f"),
863        )?;
864
865        for source in &self.sources {
866            writeln!(f, "")?;
867            writeln!(f, "source {}:", source.name)?;
868            writeln!(
869                f,
870                "                  read frontier:{:?}",
871                source
872                    .read_frontier
873                    .iter()
874                    .map(|t| t.display(timeline))
875                    .collect::<Vec<_>>()
876            )?;
877            writeln!(
878                f,
879                "                 write frontier:{:?}",
880                source
881                    .write_frontier
882                    .iter()
883                    .map(|t| t.display(timeline))
884                    .collect::<Vec<_>>()
885            )?;
886        }
887
888        writeln!(f, "")?;
889        writeln!(f, "binding constraints:")?;
890        write!(f, "{}", self.determination.constraints.display(timeline))?;
891
892        Ok(())
893    }
894}
895
896/// Types and logic in support of a constraint-based approach to timestamp determination.
897mod constraints {
898
899    use core::fmt;
900    use std::fmt::Debug;
901
902    use differential_dataflow::lattice::Lattice;
903    use mz_storage_types::sources::Timeline;
904    use serde::{Deserialize, Serialize};
905    use timely::progress::{Antichain, Timestamp};
906
907    use mz_compute_types::ComputeInstanceId;
908    use mz_repr::GlobalId;
909    use mz_sql::session::vars::IsolationLevel;
910
911    use super::DisplayableInTimeline;
912
913    /// Constraints expressed on the timestamp of a query.
914    ///
915    /// The constraints are expressed on the minimum and maximum values,
916    /// resulting in a (possibly empty) interval of valid timestamps.
917    ///
918    /// The constraints may be redundant, in the interest of providing
919    /// more complete explanations, but they may also be minimized at
920    /// any point without altering their behavior by removing redundant
921    /// constraints.
922    ///
923    /// When combined with a `Preference` one can determine an
924    /// ideal timestamp to use.
925    #[derive(Default, Serialize, Deserialize, Clone)]
926    pub struct Constraints {
927        /// Timestamps and reasons that impose an inclusive lower bound.
928        pub lower: Vec<(Antichain<mz_repr::Timestamp>, Reason)>,
929        /// Timestamps and reasons that impose an inclusive upper bound.
930        pub upper: Vec<(Antichain<mz_repr::Timestamp>, Reason)>,
931    }
932
933    impl DisplayableInTimeline for Constraints {
934        fn fmt(&self, timeline: Option<&Timeline>, f: &mut fmt::Formatter) -> fmt::Result {
935            if !self.lower.is_empty() {
936                writeln!(f, "lower:")?;
937                for (ts, reason) in &self.lower {
938                    let ts: Vec<_> = ts
939                        .iter()
940                        .map(|t| format!("{}", t.display(timeline)))
941                        .collect();
942                    writeln!(f, "  ({}): [{}]", reason, ts.join(", "))?;
943                }
944            }
945            if !self.upper.is_empty() {
946                writeln!(f, "upper:")?;
947                for (ts, reason) in &self.upper {
948                    let ts: Vec<_> = ts
949                        .iter()
950                        .map(|t| format!("{}", t.display(timeline)))
951                        .collect();
952                    writeln!(f, "  ({}): [{}]", reason, ts.join(", "))?;
953                }
954            }
955            Ok(())
956        }
957    }
958
959    impl Debug for Constraints {
960        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
961            self.display(None).fmt(f)?;
962            Ok(())
963        }
964    }
965
966    impl Constraints {
967        /// Remove constraints that are dominated by other constraints.
968        ///
969        /// This removes redundant constraints, without removing constraints
970        /// that are "tight" in the sense that the interval would be
971        /// meaningfully different without them.
972        /// For example, two constraints at the same
973        /// time will both be retained, in the interest of full information.
974        /// But a lower bound constraint at time `t` will be removed if there is a
975        /// constraint at time `t + 1` (or any larger time).
976        pub fn minimize(&mut self) {
977            // Establish the upper bound of lower constraints.
978            let lower_frontier = self.lower_bound();
979            // Retain constraints that intersect `lower_frontier`.
980            self.lower.retain(|(anti, _)| {
981                anti.iter()
982                    .any(|time| lower_frontier.elements().contains(time))
983            });
984
985            // Establish the lower bound of upper constraints.
986            let upper_frontier = self.upper_bound();
987            // Retain constraints that intersect `upper_frontier`.
988            self.upper.retain(|(anti, _)| {
989                anti.iter()
990                    .any(|time| upper_frontier.elements().contains(time))
991            });
992        }
993
994        /// An antichain equal to the least upper bound of lower bounds.
995        pub fn lower_bound(&self) -> Antichain<mz_repr::Timestamp> {
996            let mut lower = Antichain::from_elem(mz_repr::Timestamp::minimum());
997            for (anti, _) in self.lower.iter() {
998                lower = lower.join(anti);
999            }
1000            lower
1001        }
1002        /// An antichain equal to the greatest lower bound of upper bounds.
1003        pub fn upper_bound(&self) -> Antichain<mz_repr::Timestamp> {
1004            self.upper
1005                .iter()
1006                .flat_map(|(anti, _)| anti.iter())
1007                .cloned()
1008                .collect()
1009        }
1010    }
1011
1012    /// An explanation of reasons for a timestamp constraint.
1013    #[derive(Serialize, Deserialize, Clone)]
1014    pub enum Reason {
1015        /// A compute input at a compute instance.
1016        /// This is something like an index or view
1017        /// that is maintained by compute.
1018        ComputeInput(Vec<(ComputeInstanceId, GlobalId)>),
1019        /// A storage input.
1020        StorageInput(Vec<GlobalId>),
1021        /// A specified isolation level and the timestamp it requires.
1022        IsolationLevel(IsolationLevel),
1023        /// Real-time recency may constrain the timestamp from below.
1024        RealTimeRecency,
1025        /// The query expressed its own constraint on the timestamp.
1026        QueryAsOf,
1027    }
1028
1029    impl fmt::Display for Reason {
1030        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1031            match self {
1032                Reason::ComputeInput(ids) => {
1033                    let formatted: Vec<_> =
1034                        ids.iter().map(|(c, g)| format!("({}, {})", c, g)).collect();
1035                    write!(f, "Indexed inputs: [{}]", formatted.join(", "))
1036                }
1037                Reason::StorageInput(ids) => {
1038                    let formatted: Vec<_> = ids.iter().map(|g| format!("{}", g)).collect();
1039                    write!(f, "Storage inputs: [{}]", formatted.join(", "))
1040                }
1041                Reason::IsolationLevel(level) => {
1042                    write!(f, "Isolation level: {:?}", level)
1043                }
1044                Reason::RealTimeRecency => {
1045                    write!(f, "Real-time recency")
1046                }
1047                Reason::QueryAsOf => {
1048                    write!(f, "Query's AS OF")
1049                }
1050            }
1051        }
1052    }
1053
1054    /// Given an interval [read, write) of timestamp options,
1055    /// this expresses a preference for either end of the spectrum.
1056    pub enum Preference {
1057        /// Prefer the greatest timestamp immediately available.
1058        ///
1059        /// This considers the immediate inputs to a query and
1060        /// selects the greatest timestamp not greater or equal
1061        /// to any of their write frontiers.
1062        ///
1063        /// The preference only relates to immediate query inputs,
1064        /// but it could be extended to transitive inputs as well.
1065        /// For example, one could imagine preferring the freshest
1066        /// data known to be ingested into Materialize, under the
1067        /// premise that those answers should soon become available,
1068        /// and may be more fresh than the immediate inputs.
1069        FreshestAvailable,
1070        /// Prefer the least valid timestamp.
1071        ///
1072        /// This is useful when one has no expressed freshness
1073        /// constraints, and wants to minimally impact others.
1074        /// For example, `AS OF AT LEAST <time>`.
1075        StalestValid,
1076    }
1077}