mz_storage/source/
source_reader_pipeline.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 related to the creation of dataflow raw sources.
11//!
12//! Raw sources are differential dataflow  collections of data directly produced by the
13//! upstream service. The main export of this module is [`create_raw_source`],
14//! which turns [`RawSourceCreationConfig`]s into the aforementioned streams.
15//!
16//! The full source, which is the _differential_ stream that represents the actual object
17//! created by a `CREATE SOURCE` statement, is created by composing
18//! [`create_raw_source`] with
19//! decoding, `SourceEnvelope` rendering, and more.
20//!
21
22// https://github.com/tokio-rs/prost/issues/237
23#![allow(missing_docs)]
24#![allow(clippy::needless_borrow)]
25
26use std::cell::RefCell;
27use std::collections::{BTreeMap, VecDeque};
28use std::convert::Infallible;
29use std::hash::{Hash, Hasher};
30use std::rc::Rc;
31use std::sync::Arc;
32use std::time::Duration;
33
34use differential_dataflow::lattice::Lattice;
35use differential_dataflow::{AsCollection, Collection, Hashable};
36use futures::stream::StreamExt;
37use mz_ore::cast::CastFrom;
38use mz_ore::collections::CollectionExt;
39use mz_ore::now::NowFn;
40use mz_persist_client::cache::PersistClientCache;
41use mz_repr::{Diff, GlobalId, RelationDesc, Row};
42use mz_storage_types::configuration::StorageConfiguration;
43use mz_storage_types::controller::CollectionMetadata;
44use mz_storage_types::dyncfgs;
45use mz_storage_types::errors::DataflowError;
46use mz_storage_types::sources::{SourceConnection, SourceExport, SourceTimestamp};
47use mz_timely_util::antichain::AntichainExt;
48use mz_timely_util::builder_async::{
49    Event as AsyncEvent, OperatorBuilder as AsyncOperatorBuilder, PressOnDropButton,
50};
51use mz_timely_util::capture::PusherCapture;
52use mz_timely_util::operator::ConcatenateFlatten;
53use mz_timely_util::reclock::reclock;
54use timely::PartialOrder;
55use timely::container::CapacityContainerBuilder;
56use timely::dataflow::channels::pact::Pipeline;
57use timely::dataflow::operators::capture::capture::Capture;
58use timely::dataflow::operators::capture::{Event, EventPusher};
59use timely::dataflow::operators::core::Map as _;
60use timely::dataflow::operators::generic::builder_rc::OperatorBuilder as OperatorBuilderRc;
61use timely::dataflow::operators::{Broadcast, CapabilitySet, Inspect, Leave};
62use timely::dataflow::scopes::Child;
63use timely::dataflow::{Scope, Stream};
64use timely::order::TotalOrder;
65use timely::progress::frontier::MutableAntichain;
66use timely::progress::{Antichain, Timestamp};
67use tokio::sync::{Semaphore, watch};
68use tokio_stream::wrappers::WatchStream;
69use tracing::trace;
70
71use crate::healthcheck::{HealthStatusMessage, HealthStatusUpdate};
72use crate::metrics::StorageMetrics;
73use crate::metrics::source::SourceMetrics;
74use crate::source::probe;
75use crate::source::reclock::ReclockOperator;
76use crate::source::types::{Probe, SourceMessage, SourceOutput, SourceRender, StackedCollection};
77use crate::statistics::SourceStatistics;
78
79/// Shared configuration information for all source types. This is used in the
80/// `create_raw_source` functions, which produce raw sources.
81#[derive(Clone)]
82pub struct RawSourceCreationConfig {
83    /// The name to attach to the underlying timely operator.
84    pub name: String,
85    /// The ID of this instantiation of this source.
86    pub id: GlobalId,
87    /// The details of the outputs from this ingestion.
88    pub source_exports: BTreeMap<GlobalId, SourceExport<CollectionMetadata>>,
89    /// The ID of the worker on which this operator is executing
90    pub worker_id: usize,
91    /// The total count of workers
92    pub worker_count: usize,
93    /// Granularity with which timestamps should be closed (and capabilities
94    /// downgraded).
95    pub timestamp_interval: Duration,
96    /// The function to return a now time.
97    pub now_fn: NowFn,
98    /// The metrics & registry that each source instantiates.
99    pub metrics: StorageMetrics,
100    /// The upper frontier this source should resume ingestion at
101    pub as_of: Antichain<mz_repr::Timestamp>,
102    /// For each source export, the upper frontier this source should resume ingestion at in the
103    /// system time domain.
104    pub resume_uppers: BTreeMap<GlobalId, Antichain<mz_repr::Timestamp>>,
105    /// For each source export, the upper frontier this source should resume ingestion at in the
106    /// source time domain.
107    ///
108    /// Since every source has a different timestamp type we carry the timestamps of this frontier
109    /// in an encoded `Vec<Row>` form which will get decoded once we reach the connection
110    /// specialized functions.
111    pub source_resume_uppers: BTreeMap<GlobalId, Vec<Row>>,
112    /// A handle to the persist client cache
113    pub persist_clients: Arc<PersistClientCache>,
114    /// Collection of `SourceStatistics` for source and exports to share updates.
115    pub statistics: BTreeMap<GlobalId, SourceStatistics>,
116    /// Enables reporting the remap operator's write frontier.
117    pub shared_remap_upper: Rc<RefCell<Antichain<mz_repr::Timestamp>>>,
118    /// Configuration parameters, possibly from LaunchDarkly
119    pub config: StorageConfiguration,
120    /// The ID of this source remap/progress collection.
121    pub remap_collection_id: GlobalId,
122    /// The storage metadata for the remap/progress collection
123    pub remap_metadata: CollectionMetadata,
124    // A semaphore that should be acquired by async operators in order to signal that upstream
125    // operators should slow down.
126    pub busy_signal: Arc<Semaphore>,
127}
128
129/// Reduced version of [`RawSourceCreationConfig`] that is used when rendering
130/// each export.
131#[derive(Clone)]
132pub struct SourceExportCreationConfig {
133    /// The ID of this instantiation of this source.
134    pub id: GlobalId,
135    /// The ID of the worker on which this operator is executing
136    pub worker_id: usize,
137    /// The metrics & registry that each source instantiates.
138    pub metrics: StorageMetrics,
139    /// Place to share statistics updates with storage state.
140    pub source_statistics: SourceStatistics,
141}
142
143impl RawSourceCreationConfig {
144    /// Returns the worker id responsible for handling the given partition.
145    pub fn responsible_worker<P: Hash>(&self, partition: P) -> usize {
146        let mut h = std::hash::DefaultHasher::default();
147        (self.id, partition).hash(&mut h);
148        let key = usize::cast_from(h.finish());
149        key % self.worker_count
150    }
151
152    /// Returns true if this worker is responsible for handling the given partition.
153    pub fn responsible_for<P: Hash>(&self, partition: P) -> bool {
154        self.responsible_worker(partition) == self.worker_id
155    }
156}
157
158/// Creates a source dataflow operator graph from a source connection. The type of SourceConnection
159/// determines the type of connection that _should_ be created.
160///
161/// This is also the place where _reclocking_
162/// (<https://github.com/MaterializeInc/materialize/blob/main/doc/developer/design/20210714_reclocking.md>)
163/// happens.
164///
165/// See the [`source` module docs](crate::source) for more details about how raw
166/// sources are used.
167///
168/// The `resume_stream` parameter will contain frontier updates whenever times are durably
169/// recorded which allows the ingestion to release upstream resources.
170pub fn create_raw_source<'g, G: Scope<Timestamp = ()>, C>(
171    scope: &mut Child<'g, G, mz_repr::Timestamp>,
172    storage_state: &crate::storage_state::StorageState,
173    committed_upper: &Stream<Child<'g, G, mz_repr::Timestamp>, ()>,
174    config: &RawSourceCreationConfig,
175    source_connection: C,
176    start_signal: impl std::future::Future<Output = ()> + 'static,
177) -> (
178    BTreeMap<
179        GlobalId,
180        Collection<
181            Child<'g, G, mz_repr::Timestamp>,
182            Result<SourceOutput<C::Time>, DataflowError>,
183            Diff,
184        >,
185    >,
186    Stream<G, HealthStatusMessage>,
187    Vec<PressOnDropButton>,
188)
189where
190    C: SourceConnection + SourceRender + Clone + 'static,
191{
192    let worker_id = config.worker_id;
193    let id = config.id;
194
195    let mut tokens = vec![];
196
197    let (ingested_upper_tx, ingested_upper_rx) =
198        watch::channel(MutableAntichain::new_bottom(C::Time::minimum()));
199    let (probed_upper_tx, probed_upper_rx) = watch::channel(None);
200
201    let source_metrics = Arc::new(config.metrics.get_source_metrics(id, worker_id));
202
203    let timestamp_desc = source_connection.timestamp_desc();
204
205    let (remap_collection, remap_token) = remap_operator(
206        scope,
207        storage_state,
208        config.clone(),
209        probed_upper_rx,
210        ingested_upper_rx,
211        timestamp_desc,
212    );
213    // Need to broadcast the remap changes to all workers.
214    let remap_collection = remap_collection.inner.broadcast().as_collection();
215    tokens.push(remap_token);
216
217    let committed_upper = reclock_committed_upper(
218        &remap_collection,
219        config.as_of.clone(),
220        committed_upper,
221        id,
222        Arc::clone(&source_metrics),
223    );
224
225    let mut reclocked_exports = BTreeMap::new();
226
227    let reclocked_exports2 = &mut reclocked_exports;
228    let (health, source_tokens) = scope.parent.scoped("SourceTimeDomain", move |scope| {
229        let (exports, source_upper, health_stream, source_tokens) = source_render_operator(
230            scope,
231            config,
232            source_connection,
233            probed_upper_tx,
234            committed_upper,
235            start_signal,
236        );
237
238        for (id, export) in exports {
239            let (reclock_pusher, reclocked) = reclock(&remap_collection, config.as_of.clone());
240            export
241                .inner
242                .map(move |(result, from_time, diff)| {
243                    let result = match result {
244                        Ok(msg) => Ok(SourceOutput {
245                            key: msg.key.clone(),
246                            value: msg.value.clone(),
247                            metadata: msg.metadata.clone(),
248                            from_time: from_time.clone(),
249                        }),
250                        Err(err) => Err(err.clone()),
251                    };
252                    (result, from_time.clone(), *diff)
253                })
254                .capture_into(PusherCapture(reclock_pusher));
255            reclocked_exports2.insert(id, reclocked);
256        }
257
258        source_upper.capture_into(FrontierCapture(ingested_upper_tx));
259
260        (health_stream.leave(), source_tokens)
261    });
262
263    tokens.extend(source_tokens);
264
265    (reclocked_exports, health, tokens)
266}
267
268pub struct FrontierCapture<T>(watch::Sender<MutableAntichain<T>>);
269
270impl<T: Timestamp> EventPusher<T, Vec<Infallible>> for FrontierCapture<T> {
271    fn push(&mut self, event: Event<T, Vec<Infallible>>) {
272        match event {
273            Event::Progress(changes) => self.0.send_modify(|frontier| {
274                frontier.update_iter(changes);
275            }),
276            Event::Messages(_, _) => unreachable!(),
277        }
278    }
279}
280
281/// Renders the source dataflow fragment from the given [SourceConnection]. This returns a
282/// collection timestamped with the source specific timestamp type. Also returns a second stream
283/// that can be used to learn about the `source_upper` that all the source reader instances know
284/// about. This second stream will be used by the `remap_operator` to mint new timestamp bindings
285/// into the remap shard.
286fn source_render_operator<G, C>(
287    scope: &mut G,
288    config: &RawSourceCreationConfig,
289    source_connection: C,
290    probed_upper_tx: watch::Sender<Option<Probe<C::Time>>>,
291    resume_uppers: impl futures::Stream<Item = Antichain<C::Time>> + 'static,
292    start_signal: impl std::future::Future<Output = ()> + 'static,
293) -> (
294    BTreeMap<GlobalId, StackedCollection<G, Result<SourceMessage, DataflowError>>>,
295    Stream<G, Infallible>,
296    Stream<G, HealthStatusMessage>,
297    Vec<PressOnDropButton>,
298)
299where
300    G: Scope<Timestamp = C::Time>,
301    C: SourceRender + 'static,
302{
303    let source_id = config.id;
304    let worker_id = config.worker_id;
305    let now_fn = config.now_fn.clone();
306    let timestamp_interval = config.timestamp_interval;
307
308    let resume_uppers = resume_uppers.inspect(move |upper| {
309        let upper = upper.pretty();
310        trace!(%upper, "timely-{worker_id} source({source_id}) received resume upper");
311    });
312
313    let (exports, progress, health, probes, tokens) =
314        source_connection.render(scope, config, resume_uppers, start_signal);
315
316    let mut export_collections = BTreeMap::new();
317
318    let source_metrics = config.metrics.get_source_metrics(config.id, worker_id);
319
320    // Compute the overall resume upper to report for the ingestion
321    let resume_upper = Antichain::from_iter(
322        config
323            .resume_uppers
324            .values()
325            .flat_map(|f| f.iter().cloned()),
326    );
327    source_metrics
328        .resume_upper
329        .set(mz_persist_client::metrics::encode_ts_metric(&resume_upper));
330
331    let mut health_streams = vec![];
332
333    for (id, export) in exports {
334        let name = format!("SourceGenericStats({})", id);
335        let mut builder = OperatorBuilderRc::new(name, scope.clone());
336
337        let (mut health_output, derived_health) =
338            builder.new_output::<CapacityContainerBuilder<_>>();
339        health_streams.push(derived_health);
340
341        let (mut output, new_export) = builder.new_output::<CapacityContainerBuilder<_>>();
342
343        let mut input = builder.new_input(&export.inner, Pipeline);
344        export_collections.insert(id, new_export.as_collection());
345
346        let bytes_read_counter = config.metrics.source_defs.bytes_read.clone();
347        let source_statistics = config
348            .statistics
349            .get(&id)
350            .expect("statistics initialized")
351            .clone();
352
353        builder.build(move |mut caps| {
354            let mut health_cap = Some(caps.remove(0));
355
356            move |frontiers| {
357                let mut last_status = None;
358                let mut health_output = health_output.activate();
359
360                if frontiers[0].is_empty() {
361                    health_cap = None;
362                    return;
363                }
364                let health_cap = health_cap.as_mut().unwrap();
365
366                while let Some((cap, data)) = input.next() {
367                    for (message, _, _) in data.iter() {
368                        match message {
369                            Ok(message) => {
370                                source_statistics.inc_messages_received_by(1);
371                                let key_len = u64::cast_from(message.key.byte_len());
372                                let value_len = u64::cast_from(message.value.byte_len());
373                                bytes_read_counter.inc_by(key_len + value_len);
374                                source_statistics.inc_bytes_received_by(key_len + value_len);
375                            }
376                            Err(error) => {
377                                // All errors coming into the data stream are definite.
378                                // Downstream consumers of this data will preserve this
379                                // status.
380                                let update = HealthStatusUpdate::stalled(
381                                    error.to_string(),
382                                    Some(
383                                        "retracting the errored value may resume the source"
384                                            .to_string(),
385                                    ),
386                                );
387                                let status = HealthStatusMessage {
388                                    id: Some(id),
389                                    namespace: C::STATUS_NAMESPACE.clone(),
390                                    update,
391                                };
392                                if last_status.as_ref() != Some(&status) {
393                                    last_status = Some(status.clone());
394                                    health_output.session(&health_cap).give(status);
395                                }
396                            }
397                        }
398                    }
399                    let mut output = output.activate();
400                    output.session(&cap).give_container(data);
401                }
402            }
403        });
404    }
405
406    let probe_stream = match probes {
407        Some(stream) => stream,
408        None => synthesize_probes(source_id, &progress, timestamp_interval, now_fn),
409    };
410
411    // Broadcasting does more work than necessary, which would be to exchange the probes to the
412    // worker that will be the one minting the bindings but we'd have to thread this information
413    // through and couple the two functions enough that it's not worth the optimization (I think).
414    probe_stream.broadcast().inspect(move |probe| {
415        // We don't care if the receiver is gone
416        let _ = probed_upper_tx.send(Some(probe.clone()));
417    });
418
419    (
420        export_collections,
421        progress,
422        health.concatenate_flatten::<_, CapacityContainerBuilder<_>>(health_streams),
423        tokens,
424    )
425}
426
427/// Mints new contents for the remap shard based on summaries about the source
428/// upper it receives from the raw reader operators.
429///
430/// Only one worker will be active and write to the remap shard. All source
431/// upper summaries will be exchanged to it.
432fn remap_operator<G, FromTime>(
433    scope: &G,
434    storage_state: &crate::storage_state::StorageState,
435    config: RawSourceCreationConfig,
436    mut probed_upper: watch::Receiver<Option<Probe<FromTime>>>,
437    mut ingested_upper: watch::Receiver<MutableAntichain<FromTime>>,
438    remap_relation_desc: RelationDesc,
439) -> (Collection<G, FromTime, Diff>, PressOnDropButton)
440where
441    G: Scope<Timestamp = mz_repr::Timestamp>,
442    FromTime: SourceTimestamp,
443{
444    let RawSourceCreationConfig {
445        name,
446        id,
447        source_exports: _,
448        worker_id,
449        worker_count,
450        timestamp_interval,
451        remap_metadata,
452        as_of,
453        resume_uppers: _,
454        source_resume_uppers: _,
455        metrics: _,
456        now_fn,
457        persist_clients,
458        statistics: _,
459        shared_remap_upper,
460        config: _,
461        remap_collection_id,
462        busy_signal: _,
463    } = config;
464
465    let read_only_rx = storage_state.read_only_rx.clone();
466    let error_handler = storage_state.error_handler("remap_operator", id);
467
468    let chosen_worker = usize::cast_from(id.hashed() % u64::cast_from(worker_count));
469    let active_worker = chosen_worker == worker_id;
470
471    let operator_name = format!("remap({})", id);
472    let mut remap_op = AsyncOperatorBuilder::new(operator_name, scope.clone());
473    let (remap_output, remap_stream) = remap_op.new_output::<CapacityContainerBuilder<_>>();
474
475    let button = remap_op.build(move |capabilities| async move {
476        if !active_worker {
477            // This worker is not writing, so make sure it's "taken out" of the
478            // calculation by advancing to the empty frontier.
479            shared_remap_upper.borrow_mut().clear();
480            return;
481        }
482
483        let mut cap_set = CapabilitySet::from_elem(capabilities.into_element());
484
485        let remap_handle = crate::source::reclock::compat::PersistHandle::<FromTime, _>::new(
486            Arc::clone(&persist_clients),
487            read_only_rx,
488            remap_metadata.clone(),
489            as_of.clone(),
490            shared_remap_upper,
491            id,
492            "remap",
493            worker_id,
494            worker_count,
495            remap_relation_desc,
496            remap_collection_id,
497        )
498        .await;
499
500        let remap_handle = match remap_handle {
501            Ok(handle) => handle,
502            Err(e) => {
503                error_handler
504                    .report_and_stop(
505                        e.context(format!("Failed to create remap handle for source {name}")),
506                    )
507                    .await
508            }
509        };
510
511        let (mut timestamper, mut initial_batch) = ReclockOperator::new(remap_handle).await;
512
513        // Emit initial snapshot of the remap_shard, bootstrapping
514        // downstream reclock operators.
515        trace!(
516            "timely-{worker_id} remap({id}) emitting remap snapshot: trace_updates={:?}",
517            &initial_batch.updates
518        );
519
520        let cap = cap_set.delayed(cap_set.first().unwrap());
521        remap_output.give_container(&cap, &mut initial_batch.updates);
522        drop(cap);
523        cap_set.downgrade(initial_batch.upper);
524
525        let mut ticker = tokio::time::interval(timestamp_interval);
526        ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
527
528        let mut prev_probe_ts: Option<mz_repr::Timestamp> = None;
529        let timestamp_interval_ms: u64 = timestamp_interval
530            .as_millis()
531            .try_into()
532            .expect("huge duration");
533
534        while !cap_set.is_empty() {
535            // Check the reclocking strategy in every iteration, to make it possible to change it
536            // without restarting the source pipeline.
537            let reclock_to_latest =
538                dyncfgs::STORAGE_RECLOCK_TO_LATEST.get(&config.config.config_set());
539
540            // If we are reclocking to the latest offset then we only mint bindings after a
541            // successful probe. Otherwise we fall back to the earlier behavior where we just
542            // record the ingested frontier.
543            let mut new_probe = None;
544            if reclock_to_latest {
545                new_probe = probed_upper
546                    .wait_for(|new_probe| match (prev_probe_ts, new_probe) {
547                        (None, Some(_)) => true,
548                        (Some(prev_ts), Some(new)) => prev_ts < new.probe_ts,
549                        _ => false,
550                    })
551                    .await
552                    .map(|probe| (*probe).clone())
553                    .unwrap_or_else(|_| {
554                        Some(Probe {
555                            probe_ts: now_fn().into(),
556                            upstream_frontier: Antichain::new(),
557                        })
558                    });
559            } else {
560                while prev_probe_ts >= new_probe.as_ref().map(|p| p.probe_ts) {
561                    ticker.tick().await;
562                    // We only proceed if the source upper frontier is not the minimum frontier. This
563                    // makes it so the first binding corresponds to the snapshot of the source, and
564                    // because the first binding always maps to the minimum *target* frontier we
565                    // guarantee that the source will never appear empty.
566                    let upstream_frontier = ingested_upper
567                        .wait_for(|f| *f.frontier() != [FromTime::minimum()])
568                        .await
569                        .unwrap()
570                        .frontier()
571                        .to_owned();
572
573                    let now = (now_fn)();
574                    let mut probe_ts = now - now % timestamp_interval_ms;
575                    if (now % timestamp_interval_ms) != 0 {
576                        probe_ts += timestamp_interval_ms;
577                    }
578                    new_probe = Some(Probe {
579                        probe_ts: probe_ts.into(),
580                        upstream_frontier,
581                    });
582                }
583            };
584
585            let probe = new_probe.expect("known to be Some");
586            prev_probe_ts = Some(probe.probe_ts);
587
588            let binding_ts = probe.probe_ts;
589            let cur_source_upper = probe.upstream_frontier;
590
591            let new_into_upper = Antichain::from_elem(binding_ts.step_forward());
592
593            let mut remap_trace_batch = timestamper
594                .mint(binding_ts, new_into_upper, cur_source_upper.borrow())
595                .await;
596
597            trace!(
598                "timely-{worker_id} remap({id}) minted new bindings: \
599                updates={:?} \
600                source_upper={} \
601                trace_upper={}",
602                &remap_trace_batch.updates,
603                cur_source_upper.pretty(),
604                remap_trace_batch.upper.pretty()
605            );
606
607            let cap = cap_set.delayed(cap_set.first().unwrap());
608            remap_output.give_container(&cap, &mut remap_trace_batch.updates);
609            cap_set.downgrade(remap_trace_batch.upper);
610        }
611    });
612
613    (remap_stream.as_collection(), button.press_on_drop())
614}
615
616/// Reclocks an `IntoTime` frontier stream into a `FromTime` frontier stream. This is used for the
617/// virtual (through persist) feedback edge so that we convert the `IntoTime` resumption frontier
618/// into the `FromTime` frontier that is used with the source's `OffsetCommiter`.
619fn reclock_committed_upper<G, FromTime>(
620    bindings: &Collection<G, FromTime, Diff>,
621    as_of: Antichain<G::Timestamp>,
622    committed_upper: &Stream<G, ()>,
623    id: GlobalId,
624    metrics: Arc<SourceMetrics>,
625) -> impl futures::stream::Stream<Item = Antichain<FromTime>> + 'static
626where
627    G: Scope,
628    G::Timestamp: Lattice + TotalOrder,
629    FromTime: SourceTimestamp,
630{
631    let (tx, rx) = watch::channel(Antichain::from_elem(FromTime::minimum()));
632    let scope = bindings.scope().clone();
633
634    let name = format!("ReclockCommitUpper({id})");
635    let mut builder = OperatorBuilderRc::new(name, scope);
636
637    let mut bindings = builder.new_input(&bindings.inner, Pipeline);
638    let _ = builder.new_input(committed_upper, Pipeline);
639
640    builder.build(move |_| {
641        // Remap bindings beyond the upper
642        use timely::progress::ChangeBatch;
643        let mut accepted_times: ChangeBatch<(G::Timestamp, FromTime)> = ChangeBatch::new();
644        // The upper frontier of the bindings
645        let mut upper = Antichain::from_elem(Timestamp::minimum());
646        // Remap bindings not beyond upper
647        let mut ready_times = VecDeque::new();
648        let mut source_upper = MutableAntichain::new();
649
650        move |frontiers| {
651            // Accept new bindings
652            while let Some((_, data)) = bindings.next() {
653                accepted_times.extend(data.drain(..).map(|(from, mut into, diff)| {
654                    into.advance_by(as_of.borrow());
655                    ((into, from), diff.into_inner())
656                }));
657            }
658            // Extract ready bindings
659            let new_upper = frontiers[0].frontier();
660            if PartialOrder::less_than(&upper.borrow(), &new_upper) {
661                upper = new_upper.to_owned();
662                // Drain consolidated accepted times not greater or equal to `upper` into `ready_times`.
663                // Retain accepted times greater or equal to `upper` in
664                let mut pending_times = std::mem::take(&mut accepted_times).into_inner();
665                // These should already be sorted, as part of `.into_inner()`, but sort defensively in case.
666                pending_times.sort_unstable_by(|a, b| a.0.cmp(&b.0));
667                for ((into, from), diff) in pending_times.drain(..) {
668                    if !upper.less_equal(&into) {
669                        ready_times.push_back((from, into, diff));
670                    } else {
671                        accepted_times.update((into, from), diff);
672                    }
673                }
674            }
675
676            // The received times only accumulate correctly for times beyond the as_of.
677            if as_of.iter().all(|t| !upper.less_equal(t)) {
678                let committed_upper = frontiers[1].frontier();
679                if as_of.iter().all(|t| !committed_upper.less_equal(t)) {
680                    // We have committed this source up until `committed_upper`. Because we have
681                    // required that IntoTime is a total order this will be either a singleton set
682                    // or the empty set.
683                    //
684                    // * Case 1: committed_upper is the empty set {}
685                    //
686                    // There won't be any future IntoTime timestamps that we will produce so we can
687                    // provide feedback to the source that it can forget about everything.
688                    //
689                    // * Case 2: committed_upper is a singleton set {t_next}
690                    //
691                    // We know that t_next cannot be the minimum timestamp because we have required
692                    // that all times of the as_of frontier are not beyond some time of
693                    // committed_upper. Therefore t_next has a predecessor timestamp t_prev.
694                    //
695                    // We don't know what remap[t_next] is yet, but we do know that we will have to
696                    // emit all source updates `u: remap[t_prev] <= time(u) <= remap[t_next]`.
697                    // Since `t_next` is the minimum undetermined timestamp and we know that t1 <=
698                    // t2 => remap[t1] <= remap[t2] we know that we will never need any source
699                    // updates `u: !(remap[t_prev] <= time(u))`.
700                    //
701                    // Therefore we can provide feedback to the source that it can forget about any
702                    // updates that are not beyond remap[t_prev].
703                    //
704                    // Important: We are *NOT* saying that the source can *compact* its data using
705                    // remap[t_prev] as the compaction frontier. If the source were to compact its
706                    // collection to remap[t_prev] we would lose the distinction between updates
707                    // that happened *at* t_prev versus updates that happened ealier and were
708                    // advanced to t_prev. If the source needs to communicate a compaction frontier
709                    // upstream then the specific source implementation needs to further adjust the
710                    // reclocked committed_upper and calculate a suitable compaction frontier in
711                    // the same way we adjust uppers of collections in the controller with the
712                    // LagWriteFrontier read policy.
713                    //
714                    // == What about IntoTime times that are general lattices?
715                    //
716                    // Reversing the upper for a general lattice is much more involved but it boils
717                    // down to computing the meet of all the times in `committed_upper` and then
718                    // treating that as `t_next` (I think). Until we need to deal with that though
719                    // we can just assume TotalOrder.
720                    let reclocked_upper = match committed_upper.as_option() {
721                        Some(t_next) => {
722                            let idx = ready_times.partition_point(|(_, t, _)| t < t_next);
723                            let updates = ready_times
724                                .drain(0..idx)
725                                .map(|(from_time, _, diff)| (from_time, diff));
726                            source_upper.update_iter(updates);
727                            // At this point source_upper contains all updates that are less than
728                            // t_next, which is equal to remap[t_prev]
729                            source_upper.frontier().to_owned()
730                        }
731                        None => Antichain::new(),
732                    };
733                    tx.send_replace(reclocked_upper);
734                }
735            }
736
737            metrics
738                .commit_upper_accepted_times
739                .set(u64::cast_from(accepted_times.len()));
740            metrics
741                .commit_upper_ready_times
742                .set(u64::cast_from(ready_times.len()));
743        }
744    });
745
746    WatchStream::from_changes(rx)
747}
748
749/// Synthesizes a probe stream that produces the frontier of the given progress stream at the given
750/// interval.
751///
752/// This is used as a fallback for sources that don't support probing the frontier of the upstream
753/// system.
754fn synthesize_probes<G>(
755    source_id: GlobalId,
756    progress: &Stream<G, Infallible>,
757    interval: Duration,
758    now_fn: NowFn,
759) -> Stream<G, Probe<G::Timestamp>>
760where
761    G: Scope,
762{
763    let scope = progress.scope();
764
765    let active_worker = usize::cast_from(source_id.hashed()) % scope.peers();
766    let is_active_worker = active_worker == scope.index();
767
768    let mut op = AsyncOperatorBuilder::new("synthesize_probes".into(), scope);
769    let (output, output_stream) = op.new_output();
770    let mut input = op.new_input_for(progress, Pipeline, &output);
771
772    op.build(|caps| async move {
773        if !is_active_worker {
774            return;
775        }
776
777        let [cap] = caps.try_into().expect("one capability per output");
778
779        let mut ticker = probe::Ticker::new(move || interval, now_fn.clone());
780
781        let minimum_frontier = Antichain::from_elem(Timestamp::minimum());
782        let mut frontier = minimum_frontier.clone();
783        loop {
784            tokio::select! {
785                event = input.next() => match event {
786                    Some(AsyncEvent::Progress(progress)) => frontier = progress,
787                    Some(AsyncEvent::Data(..)) => unreachable!(),
788                    None => break,
789                },
790                // We only report a probe if the source upper frontier is not the minimum frontier.
791                // This makes it so the first remap binding corresponds to the snapshot of the
792                // source, and because the first binding always maps to the minimum *target*
793                // frontier we guarantee that the source will never appear empty.
794                probe_ts = ticker.tick(), if frontier != minimum_frontier => {
795                    let probe = Probe {
796                        probe_ts,
797                        upstream_frontier: frontier.clone(),
798                    };
799                    output.give(&cap, probe);
800                }
801            }
802        }
803
804        let probe = Probe {
805            probe_ts: now_fn().into(),
806            upstream_frontier: Antichain::new(),
807        };
808        output.give(&cap, probe);
809    });
810
811    output_stream
812}