Skip to main content

mz_persist_client/operators/
shard_source.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//! A source that reads from a persist shard.
11
12use std::cell::RefCell;
13use std::collections::BTreeMap;
14use std::collections::VecDeque;
15use std::collections::hash_map::DefaultHasher;
16use std::convert::Infallible;
17use std::fmt::{Debug, Formatter};
18use std::future::Future;
19use std::hash::{Hash, Hasher};
20use std::pin::pin;
21use std::rc::Rc;
22use std::sync::Arc;
23use std::time::Instant;
24
25use anyhow::anyhow;
26use arrow::array::ArrayRef;
27use differential_dataflow::Hashable;
28use differential_dataflow::difference::Monoid;
29use differential_dataflow::lattice::Lattice;
30use futures::stream::FuturesUnordered;
31use futures_util::StreamExt;
32use mz_ore::cast::CastFrom;
33use mz_ore::collections::CollectionExt;
34use mz_ore::metrics::IntCounter;
35use mz_ore::process::halt_with_code;
36use mz_persist_types::stats::PartStats;
37use mz_persist_types::{Codec, Codec64};
38use mz_timely_util::builder_async::{
39    Event, OperatorBuilder as AsyncOperatorBuilder, PressOnDropButton,
40};
41use timely::PartialOrder;
42use timely::container::CapacityContainerBuilder;
43use timely::dataflow::channels::pact::{Exchange, Pipeline};
44use timely::dataflow::operators::{CapabilitySet, ConnectLoop, Enter, Feedback, Leave};
45use timely::dataflow::{Scope, StreamVec};
46use timely::order::TotalOrder;
47use timely::progress::frontier::AntichainRef;
48use timely::progress::{Antichain, Timestamp, timestamp::Refines};
49use tracing::{debug, trace};
50
51use crate::batch::BLOB_TARGET_SIZE;
52use crate::cfg::{
53    RetryParameters, SOURCE_FETCH_CONCURRENCY, SOURCE_HYDRATION_FRONTIER_COALESCE_BYTES,
54    USE_CRITICAL_SINCE_SOURCE,
55};
56use crate::fetch::{
57    ExchangeableBatchPart, FetchedBlob, Lease, MissingBlobDiagnosis, MissingBlobExit,
58};
59use crate::internal::state::BatchPart;
60use crate::read::READER_LEASE_EXPIRED_EXIT_CODE;
61use crate::stats::{STATS_AUDIT_PERCENT, STATS_FILTER_ENABLED};
62use crate::{Diagnostics, PersistClient, ShardId};
63
64/// The result of applying an MFP to a part, if we know it.
65#[derive(Debug, Clone, PartialEq, Default)]
66pub enum FilterResult {
67    /// This dataflow may or may not filter out any row in this part.
68    #[default]
69    Keep,
70    /// This dataflow is guaranteed to filter out all records in this part.
71    Discard,
72    /// This dataflow will keep all the rows, but the values are irrelevant:
73    /// include the given single-row KV data instead.
74    ReplaceWith {
75        /// The single-element key column.
76        key: ArrayRef,
77        /// The single-element val column.
78        val: ArrayRef,
79    },
80}
81
82impl FilterResult {
83    /// The noop filtering function: return the default value for all parts.
84    pub fn keep_all<T>(_stats: &PartStats, _frontier: AntichainRef<T>) -> FilterResult {
85        Self::Keep
86    }
87}
88
89/// Many dataflows, including the Persist source, encounter errors that are neither data-plane
90/// errors (a la SourceData) nor bugs. This includes:
91/// - lease timeouts: the source has failed to heartbeat, the lease timed out, and our inputs are
92///   GCed away. (But we'd be able to use the compaction output if we restart.)
93/// - external transactions: our Kafka transaction has failed, and we can't re-create it without
94///   re-ingesting a bunch of data we no longer have in memory. (But we could do on restart.)
95///
96/// It would be an error to simply exit from our dataflow operator, since that allows timely
97/// frontiers to advance, which signals progress that we haven't made. So we report the error and
98/// attempt to trigger a restart: either directly (via a `halt!`) or indirectly with a callback.
99#[derive(Clone)]
100pub enum ErrorHandler {
101    /// Halt the process on error, with [READER_LEASE_EXPIRED_EXIT_CODE] if a
102    /// reader lost its lease.
103    Halt(&'static str),
104    /// Signal an error to a higher-level supervisor.
105    Signal(Rc<dyn Fn(anyhow::Error) + 'static>),
106}
107
108impl Debug for ErrorHandler {
109    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
110        match self {
111            ErrorHandler::Halt(name) => f.debug_tuple("ErrorHandler::Halt").field(name).finish(),
112            ErrorHandler::Signal(_) => f.write_str("ErrorHandler::Signal"),
113        }
114    }
115}
116
117impl ErrorHandler {
118    /// Returns a new error handler that uses the provided function to signal an error.
119    pub fn signal(signal_fn: impl Fn(anyhow::Error) + 'static) -> Self {
120        Self::Signal(Rc::new(signal_fn))
121    }
122
123    /// Signal an error to an error handler. This function never returns: logically it blocks until
124    /// restart, though that restart might be sooner (if halting) or later (if triggering a dataflow
125    /// restart, for example).
126    pub async fn report_and_stop(&self, error: anyhow::Error) -> ! {
127        match self {
128            ErrorHandler::Halt(name) if error.is::<ReaderLeaseExpired>() => halt_with_code(
129                READER_LEASE_EXPIRED_EXIT_CODE,
130                format_args!("unhandled error in {name}: {error:#}"),
131            ),
132            ErrorHandler::Halt(name) => {
133                mz_ore::halt!("unhandled error in {name}: {error:#}")
134            }
135            ErrorHandler::Signal(callback) => {
136                let () = callback(error);
137                std::future::pending().await
138            }
139        }
140    }
141}
142
143/// A fetch failed because the reader that leased the part lost its lease.
144#[derive(Debug)]
145struct ReaderLeaseExpired(String);
146
147impl std::fmt::Display for ReaderLeaseExpired {
148    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
149        f.write_str(&self.0)
150    }
151}
152
153impl std::error::Error for ReaderLeaseExpired {}
154
155/// The error for a fetch that found its part's blob missing. Counts a lost
156/// lease in `expired_live_read`.
157fn missing_blob_error(
158    blob_key: &str,
159    diagnosis: MissingBlobDiagnosis,
160    expired_live_read: &IntCounter,
161) -> anyhow::Error {
162    let message = format!(
163        "batch fetcher could not fetch batch part {}: {}",
164        blob_key, diagnosis
165    );
166    // The `ErrorHandler` decides what the error does to the process, so only
167    // a lost lease is tagged here. `Halt` and `Panic` are reported untagged.
168    match diagnosis.exit(expired_live_read) {
169        MissingBlobExit::LeaseExpired => anyhow::Error::new(ReaderLeaseExpired(message)),
170        MissingBlobExit::Halt | MissingBlobExit::Panic => anyhow!(message),
171    }
172}
173
174/// Creates a new source that reads from a persist shard, distributing the work
175/// of reading data to all timely workers.
176///
177/// All times emitted will have been [advanced by] the given `as_of` frontier.
178/// All updates at times greater or equal to `until` will be suppressed.
179/// The `map_filter_project` argument, if supplied, may be partially applied,
180/// and any un-applied part of the argument will be left behind in the argument.
181///
182/// The `desc_transformer` interposes an operator in the stream before the
183/// chosen data is fetched. This is currently used to provide flow control... see
184/// usages for details.
185///
186/// [advanced by]: differential_dataflow::lattice::Lattice::advance_by
187pub fn shard_source<'inner, 'outer, K, V, T, D, DT, TOuter, C>(
188    outer: Scope<'outer, TOuter>,
189    scope: Scope<'inner, T>,
190    name: &str,
191    client: impl Fn() -> C,
192    shard_id: ShardId,
193    as_of: Option<Antichain<TOuter>>,
194    snapshot_mode: SnapshotMode,
195    until: Antichain<TOuter>,
196    desc_transformer: Option<DT>,
197    key_schema: Arc<K::Schema>,
198    val_schema: Arc<V::Schema>,
199    filter_fn: impl FnMut(&PartStats, AntichainRef<TOuter>) -> FilterResult + 'static,
200    // If Some, an override for the default listen sleep retry parameters.
201    listen_sleep: Option<impl Fn() -> RetryParameters + 'static>,
202    start_signal: impl Future<Output = ()> + 'static,
203    error_handler: ErrorHandler,
204) -> (
205    StreamVec<'inner, T, FetchedBlob<K, V, TOuter, D>>,
206    Vec<PressOnDropButton>,
207)
208where
209    K: Debug + Codec,
210    V: Debug + Codec,
211    D: Monoid + Codec64 + Send + Sync,
212    // TODO: Figure out how to get rid of the TotalOrder bound :(.
213    TOuter: Timestamp + Lattice + Codec64 + TotalOrder + Sync,
214    T: Refines<TOuter>,
215    DT: FnOnce(
216        Scope<'inner, T>,
217        StreamVec<'inner, T, (usize, ExchangeableBatchPart<TOuter>)>,
218        usize,
219    ) -> (
220        StreamVec<'inner, T, (usize, ExchangeableBatchPart<TOuter>)>,
221        Vec<PressOnDropButton>,
222    ),
223    C: Future<Output = PersistClient> + Send + 'static,
224{
225    // WARNING! If emulating any of this code, you should read the doc string on
226    // [`LeasedBatchPart`] and [`Subscribe`] or will likely run into intentional
227    // panics.
228    //
229    // This source is split as such:
230    // 1. Sets up `async_stream`, which only yields data (parts) on one chosen
231    //    worker. Generating also generates SeqNo leases on the chosen worker,
232    //    ensuring `part`s do not get GCed while in flight.
233    // 2. Part distribution: A timely source operator which continuously reads
234    //    from that stream, and distributes the data among workers.
235    // 3. Part fetcher: A timely operator which downloads the part's contents
236    //    from S3, and outputs them to a timely stream. Additionally, the
237    //    operator returns the `LeasedBatchPart` to the original worker, so it
238    //    can release the SeqNo lease.
239
240    let chosen_worker = usize::cast_from(name.hashed()) % scope.peers();
241
242    let mut tokens = vec![];
243
244    // we can safely pass along a zero summary from this feedback edge,
245    // as the input is disconnected from the operator's output
246    let (completed_fetches_feedback_handle, completed_fetches_feedback_stream) =
247        scope.feedback(T::Summary::default());
248
249    // Sniff out if this is on behalf of a transient dataflow. This doesn't
250    // affect the fetch behavior, it just causes us to use a different set of
251    // metrics.
252    let is_transient = !until.is_empty();
253
254    let (descs, descs_token) = shard_source_descs::<K, V, D, TOuter>(
255        outer,
256        name,
257        client(),
258        shard_id.clone(),
259        as_of,
260        snapshot_mode,
261        until,
262        completed_fetches_feedback_stream.leave(outer),
263        chosen_worker,
264        Arc::clone(&key_schema),
265        Arc::clone(&val_schema),
266        filter_fn,
267        listen_sleep,
268        start_signal,
269        error_handler.clone(),
270    );
271    tokens.push(descs_token);
272
273    let descs = descs.enter(scope);
274    let descs = match desc_transformer {
275        Some(desc_transformer) => {
276            let (descs, extra_tokens) = desc_transformer(scope, descs, chosen_worker);
277            tokens.extend(extra_tokens);
278            descs
279        }
280        None => descs,
281    };
282
283    let (parts, completed_fetches_stream, fetch_token) = shard_source_fetch::<K, V, TOuter, D, T>(
284        descs,
285        name,
286        client(),
287        shard_id,
288        key_schema,
289        val_schema,
290        is_transient,
291        error_handler,
292    );
293    completed_fetches_stream.connect_loop(completed_fetches_feedback_handle);
294    tokens.push(fetch_token);
295
296    (parts, tokens)
297}
298
299/// An enum describing whether a snapshot should be emitted
300#[derive(Debug, Clone, Copy)]
301pub enum SnapshotMode {
302    /// The snapshot will be included in the stream
303    Include,
304    /// The snapshot will not be included in the stream
305    Exclude,
306}
307
308#[derive(Debug)]
309struct LeaseManager<T> {
310    leases: BTreeMap<T, Vec<Lease>>,
311}
312
313impl<T: Timestamp + Codec64> LeaseManager<T> {
314    fn new() -> Self {
315        Self {
316            leases: BTreeMap::new(),
317        }
318    }
319
320    /// Track a lease associated with a particular time.
321    fn push_at(&mut self, time: T, lease: Lease) {
322        self.leases.entry(time).or_default().push(lease);
323    }
324
325    /// Discard any leases for data that aren't past the given frontier.
326    fn advance_to(&mut self, frontier: AntichainRef<T>)
327    where
328        // If we allowed partial orders, we'd need to reconsider every key on each advance.
329        T: TotalOrder,
330    {
331        while let Some(first) = self.leases.first_entry() {
332            if frontier.less_equal(first.key()) {
333                break; // This timestamp is still live!
334            }
335            drop(first.remove());
336        }
337    }
338}
339
340pub(crate) fn shard_source_descs<'outer, K, V, D, TOuter>(
341    scope: Scope<'outer, TOuter>,
342    name: &str,
343    client: impl Future<Output = PersistClient> + Send + 'static,
344    shard_id: ShardId,
345    as_of: Option<Antichain<TOuter>>,
346    snapshot_mode: SnapshotMode,
347    until: Antichain<TOuter>,
348    completed_fetches_stream: StreamVec<'outer, TOuter, Infallible>,
349    chosen_worker: usize,
350    key_schema: Arc<K::Schema>,
351    val_schema: Arc<V::Schema>,
352    mut filter_fn: impl FnMut(&PartStats, AntichainRef<TOuter>) -> FilterResult + 'static,
353    // If Some, an override for the default listen sleep retry parameters.
354    listen_sleep: Option<impl Fn() -> RetryParameters + 'static>,
355    start_signal: impl Future<Output = ()> + 'static,
356    error_handler: ErrorHandler,
357) -> (
358    StreamVec<'outer, TOuter, (usize, ExchangeableBatchPart<TOuter>)>,
359    PressOnDropButton,
360)
361where
362    K: Debug + Codec,
363    V: Debug + Codec,
364    D: Monoid + Codec64 + Send + Sync,
365    // TODO: Figure out how to get rid of the TotalOrder bound :(.
366    TOuter: Timestamp + Lattice + Codec64 + TotalOrder + Sync,
367{
368    let worker_index = scope.index();
369    let num_workers = scope.peers();
370
371    // This is a generator that sets up an async `Stream` that can be continuously polled to get the
372    // values that are `yield`-ed from it's body.
373    let name_owned = name.to_owned();
374
375    // Create a shared slot between the operator to store the listen handle
376    let listen_handle = Rc::new(RefCell::new(None));
377    let return_listen_handle = Rc::clone(&listen_handle);
378
379    // Create a oneshot channel to give the part returner a SubscriptionLeaseReturner
380    let (tx, rx) = tokio::sync::oneshot::channel::<Rc<RefCell<LeaseManager<TOuter>>>>();
381    let mut builder = AsyncOperatorBuilder::new(
382        format!("shard_source_descs_return({})", name),
383        scope.clone(),
384    );
385    let mut completed_fetches = builder.new_disconnected_input(completed_fetches_stream, Pipeline);
386    // This operator doesn't need to use a token because it naturally exits when its input
387    // frontier reaches the empty antichain.
388    builder.build(move |_caps| async move {
389        let Ok(leases) = rx.await else {
390            // Either we're not the chosen worker or the dataflow was shutdown before the
391            // subscriber was even created.
392            return;
393        };
394        while let Some(event) = completed_fetches.next().await {
395            let Event::Progress(frontier) = event else {
396                continue;
397            };
398            leases.borrow_mut().advance_to(frontier.borrow());
399        }
400        // Make it explicit that the subscriber is kept alive until we have finished returning parts
401        drop(return_listen_handle);
402    });
403
404    let mut builder =
405        AsyncOperatorBuilder::new(format!("shard_source_descs({})", name), scope.clone());
406    let (descs_output, descs_stream) = builder.new_output::<CapacityContainerBuilder<_>>();
407
408    #[allow(clippy::await_holding_refcell_ref)]
409    let shutdown_button = builder.build(move |caps| async move {
410        let mut cap_set = CapabilitySet::from_elem(caps.into_element());
411
412        // Only one worker is responsible for distributing parts
413        if worker_index != chosen_worker {
414            trace!(
415                "We are not the chosen worker ({}), exiting...",
416                chosen_worker
417            );
418            return;
419        }
420
421        // Internally, the `open_leased_reader` call registers a new LeasedReaderId and then fires
422        // up a background tokio task to heartbeat it. It is possible that we might get a
423        // particularly adversarial scheduling where the CRDB query to register the id is sent and
424        // then our Future is not polled again for a long time, resulting is us never spawning the
425        // heartbeat task. Run reader creation in a task to attempt to defend against this.
426        //
427        // TODO: Really we likely need to swap the inners of all persist operators to be
428        // communicating with a tokio task over a channel, but that's much much harder, so for now
429        // we whack the moles as we see them.
430        let mut read = mz_ore::task::spawn(|| format!("shard_source_reader({})", name_owned), {
431            let diagnostics = Diagnostics {
432                handle_purpose: format!("shard_source({})", name_owned),
433                shard_name: name_owned.clone(),
434            };
435            async move {
436                let client = client.await;
437                client
438                    .open_leased_reader::<K, V, TOuter, D>(
439                        shard_id,
440                        key_schema,
441                        val_schema,
442                        diagnostics,
443                        USE_CRITICAL_SINCE_SOURCE.get(client.dyncfgs()),
444                    )
445                    .await
446            }
447        })
448        .await
449        .expect("could not open persist shard");
450
451        // Wait for the start signal only after we have obtained a read handle. This makes "cannot
452        // serve requested as_of" panics caused by (database-issues#8729) significantly less
453        // likely.
454        let () = start_signal.await;
455
456        let cfg = read.cfg.clone();
457        let metrics = Arc::clone(&read.metrics);
458
459        let as_of = as_of.unwrap_or_else(|| read.since().clone());
460
461        // Eagerly downgrade our frontier to the initial as_of. This makes sure
462        // that the output frontier of the `persist_source` closely tracks the
463        // `upper` frontier of the persist shard. It might be that the snapshot
464        // for `as_of` is not initially available yet, but this makes sure we
465        // already downgrade to it.
466        //
467        // Downstream consumers might rely on close frontier tracking for making
468        // progress. For example, the `persist_sink` needs to know the
469        // up-to-date upper of the output shard to make progress because it will
470        // only write out new data once it knows that earlier writes went
471        // through, including the initial downgrade of the shard upper to the
472        // `as_of`.
473        //
474        // NOTE: We have to do this before our `snapshot()` call because that
475        // will block when there is no data yet available in the shard.
476        cap_set.downgrade(as_of.clone());
477
478        let mut snapshot_parts =
479            match snapshot_mode {
480                SnapshotMode::Include => match read.snapshot(as_of.clone()).await {
481                    Ok(parts) => parts,
482                    Err(e) => error_handler
483                        .report_and_stop(anyhow!(
484                            "{name_owned}: {shard_id} cannot serve requested as_of {as_of:?}: {e:?}"
485                        ))
486                        .await,
487                },
488                SnapshotMode::Exclude => vec![],
489            };
490
491        // We're about to start producing parts to be fetched whose leases will be returned by the
492        // `shard_source_descs_return` operator above. In order for that operator to successfully
493        // return the leases we send it the lease returner associated with our shared subscriber.
494        let leases = Rc::new(RefCell::new(LeaseManager::new()));
495        tx.send(Rc::clone(&leases))
496            .expect("lease returner exited before desc producer");
497
498        // Recent shard upper observed at hydration time. While the source is still
499        // catching up to it we coalesce frontier downgrades (see the loop below); once
500        // `current_frontier` reaches it the source is live and we forward every batch's
501        // progress so steady-state frontier tracking stays tight. Read before `listen`
502        // consumes `read`.
503        let replay_upper = read.shared_upper();
504
505        // Store the listen handle in the shared slot so that it stays alive until both operators
506        // exit
507        let mut listen = listen_handle.borrow_mut();
508        let listen = match read.listen(as_of.clone()).await {
509            Ok(handle) => listen.insert(handle),
510            Err(e) => {
511                error_handler
512                    .report_and_stop(anyhow!(
513                        "{name_owned}: {shard_id} cannot serve requested as_of {as_of:?}: {e:?}"
514                    ))
515                    .await
516            }
517        };
518
519        let listen_retry = listen_sleep.as_ref().map(|retry| retry());
520
521        // The head of the stream is enriched with the snapshot parts if they exist
522        let listen_head = if !snapshot_parts.is_empty() {
523            let (mut parts, progress) = listen.next(listen_retry).await;
524            snapshot_parts.append(&mut parts);
525            futures::stream::iter(Some((snapshot_parts, progress)))
526        } else {
527            futures::stream::iter(None)
528        };
529
530        // The tail of the stream is all subsequent parts
531        let listen_tail = futures::stream::unfold(listen, |listen| async move {
532            Some((listen.next(listen_retry).await, listen))
533        });
534
535        let mut shard_stream = pin!(listen_head.chain(listen_tail));
536
537        // Ideally, we'd like our audit overhead to be proportional to the actual amount of "real"
538        // work we're doing in the source. So: start with a small, constant budget; add to the
539        // budget when we do real work; and skip auditing a part if we don't have the budget for it.
540        let mut audit_budget_bytes = u64::cast_from(BLOB_TARGET_SIZE.get(&cfg).saturating_mul(2));
541
542        // All future updates will be timestamped after this frontier.
543        let mut current_frontier = as_of.clone();
544
545        // While catching up to `replay_upper`, coalesce frontier downgrades until at
546        // least this many encoded bytes have been emitted at the held capability. This
547        // turns a long historical replay (one persist batch ~ one write ~ 1/s) from one
548        // progress round per batch into a handful of larger steps, which is what bounds
549        // the number of downstream arrangement-maintenance passes. `0` disables it. The
550        // budget caps how much the downstream batcher stages before it can seal, so we
551        // never trade the per-batch storm for an unbounded single batch.
552        let coalesce_target = u64::cast_from(SOURCE_HYDRATION_FRONTIER_COALESCE_BYTES.get(&cfg));
553        // Encoded bytes emitted since the last forwarded progress.
554        let mut coalesced_bytes: u64 = 0;
555
556        // If `until.less_equal(current_frontier)`, it means that all subsequent batches will contain only
557        // times greater or equal to `until`, which means they can be dropped in their entirety.
558        while !PartialOrder::less_equal(&until, &current_frontier) {
559            let (parts, progress) = shard_stream.next().await.expect("infinite stream");
560
561            let mut batch_bytes: u64 = 0;
562
563            // Emit the part at the `(ts, 0)` time. The `granular_backpressure`
564            // operator will refine this further, if its enabled.
565            let current_ts = current_frontier
566                .as_option()
567                .expect("until should always be <= the empty frontier");
568            let session_cap = cap_set.delayed(current_ts);
569
570            for mut part_desc in parts {
571                // TODO: Push more of this logic into LeasedBatchPart like we've
572                // done for project?
573                if STATS_FILTER_ENABLED.get(&cfg) {
574                    let filter_result = match &part_desc.part {
575                        BatchPart::Hollow(x) => {
576                            let should_fetch =
577                                x.stats.as_ref().map_or(FilterResult::Keep, |stats| {
578                                    // Stats written by a newer version may
579                                    // not decode. The sound fallback is to
580                                    // fetch the part.
581                                    match stats.try_decode() {
582                                        Ok(stats) => filter_fn(&stats, current_frontier.borrow()),
583                                        Err(err) => {
584                                            tracing::warn!(
585                                                %err,
586                                                "could not decode part stats, fetching part"
587                                            );
588                                            FilterResult::Keep
589                                        }
590                                    }
591                                });
592                            should_fetch
593                        }
594                        BatchPart::Inline { .. } => FilterResult::Keep,
595                    };
596                    // Apply the filter: discard or substitute the part if required.
597                    let bytes = u64::cast_from(part_desc.encoded_size_bytes());
598                    match filter_result {
599                        FilterResult::Keep => {
600                            audit_budget_bytes = audit_budget_bytes.saturating_add(bytes);
601                        }
602                        FilterResult::Discard => {
603                            metrics.pushdown.parts_filtered_count.inc();
604                            metrics.pushdown.parts_filtered_bytes.inc_by(bytes);
605                            let should_audit = match &part_desc.part {
606                                BatchPart::Hollow(x) => {
607                                    let mut h = DefaultHasher::new();
608                                    x.key.hash(&mut h);
609                                    usize::cast_from(h.finish()) % 100
610                                        < STATS_AUDIT_PERCENT.get(&cfg)
611                                }
612                                BatchPart::Inline { .. } => false,
613                            };
614                            if should_audit && bytes < audit_budget_bytes {
615                                audit_budget_bytes -= bytes;
616                                metrics.pushdown.parts_audited_count.inc();
617                                metrics.pushdown.parts_audited_bytes.inc_by(bytes);
618                                part_desc.request_filter_pushdown_audit();
619                            } else {
620                                debug!(
621                                    "skipping part because of stats filter {:?}",
622                                    part_desc.part.stats()
623                                );
624                                continue;
625                            }
626                        }
627                        FilterResult::ReplaceWith { key, val } => {
628                            part_desc.maybe_optimize(&cfg, key, val);
629                            audit_budget_bytes = audit_budget_bytes.saturating_add(bytes);
630                        }
631                    }
632                    let bytes = u64::cast_from(part_desc.encoded_size_bytes());
633                    if part_desc.part.is_inline() {
634                        metrics.pushdown.parts_inline_count.inc();
635                        metrics.pushdown.parts_inline_bytes.inc_by(bytes);
636                    } else {
637                        metrics.pushdown.parts_fetched_count.inc();
638                        metrics.pushdown.parts_fetched_bytes.inc_by(bytes);
639                    }
640                }
641
642                // Give the part to a random worker. This isn't round robin in an attempt to avoid
643                // skew issues: if your parts alternate size large, small, then you'll end up only
644                // using half of your workers.
645                //
646                // There's certainly some other things we could be doing instead here, but this has
647                // seemed to work okay so far. Continue to revisit as necessary.
648                let worker_idx = usize::cast_from(Instant::now().hashed()) % num_workers;
649                batch_bytes =
650                    batch_bytes.saturating_add(u64::cast_from(part_desc.encoded_size_bytes()));
651                let (part, lease) = part_desc.into_exchangeable_part();
652                leases.borrow_mut().push_at(current_ts.clone(), lease);
653                descs_output.give(&session_cap, (worker_idx, part));
654            }
655
656            current_frontier.join_assign(&progress);
657            coalesced_bytes = coalesced_bytes.saturating_add(batch_bytes);
658
659            // Coalesce the frontier downgrade while still catching up to `replay_upper`
660            // and below the byte budget. Parts carry their real timestamps regardless, so
661            // holding the frontier back only batches downstream progress rounds. Once live
662            // (caught up to `replay_upper`) or with coalescing disabled we forward every
663            // batch, keeping steady-state tracking tight for consumers like `persist_sink`.
664            let caught_up = PartialOrder::less_equal(&replay_upper, &current_frontier);
665            let coalesce = coalesce_target > 0 && !caught_up && coalesced_bytes < coalesce_target;
666            if !coalesce {
667                coalesced_bytes = 0;
668                cap_set.downgrade(current_frontier.iter());
669            }
670        }
671    });
672
673    (descs_stream, shutdown_button.press_on_drop())
674}
675
676pub(crate) fn shard_source_fetch<'inner, K, V, T, D, TInner>(
677    descs: StreamVec<'inner, TInner, (usize, ExchangeableBatchPart<T>)>,
678    name: &str,
679    client: impl Future<Output = PersistClient> + Send + 'static,
680    shard_id: ShardId,
681    key_schema: Arc<K::Schema>,
682    val_schema: Arc<V::Schema>,
683    is_transient: bool,
684    error_handler: ErrorHandler,
685) -> (
686    StreamVec<'inner, TInner, FetchedBlob<K, V, T, D>>,
687    StreamVec<'inner, TInner, Infallible>,
688    PressOnDropButton,
689)
690where
691    K: Debug + Codec,
692    V: Debug + Codec,
693    T: Timestamp + Lattice + Codec64 + Sync,
694    D: Monoid + Codec64 + Send + Sync,
695    TInner: Timestamp + Refines<T>,
696{
697    let mut builder =
698        AsyncOperatorBuilder::new(format!("shard_source_fetch({})", name), descs.scope());
699    let (fetched_output, fetched_stream) = builder.new_output::<CapacityContainerBuilder<_>>();
700    let (completed_fetches_output, completed_fetches_stream) =
701        builder.new_output::<CapacityContainerBuilder<Vec<Infallible>>>();
702    let mut descs_input = builder.new_input_for_many(
703        descs,
704        Exchange::new(|&(i, _): &(usize, _)| u64::cast_from(i)),
705        [&fetched_output, &completed_fetches_output],
706    );
707    let name_owned = name.to_owned();
708
709    let shutdown_button = builder.build(move |_capabilities| async move {
710        // Open the fetcher in a task to defend against an adversarial schedule
711        // delaying its background work, and read the concurrency dyncfg while we
712        // hold the client. See the equivalent reasoning in `shard_source_descs`.
713        let (fetcher, max_concurrency) =
714            mz_ore::task::spawn(|| format!("shard_source_fetch({})", name_owned), {
715                let diagnostics = Diagnostics {
716                    shard_name: name_owned.clone(),
717                    handle_purpose: format!("shard_source_fetch batch fetcher {}", name_owned),
718                };
719                async move {
720                    let client = client.await;
721                    // Up to this many part fetches run concurrently to amortize
722                    // the blob-store round-trip, which dominates when there are
723                    // many small parts. Results are keyed by time below, so
724                    // completions in any order are fine; total in-flight bytes
725                    // stay bounded by the fetch semaphore inside
726                    // `fetch_leased_part`.
727                    let max_concurrency = SOURCE_FETCH_CONCURRENCY.get(client.dyncfgs()).max(1);
728                    let fetcher = client
729                        .create_batch_fetcher::<K, V, T, D>(
730                            shard_id,
731                            key_schema,
732                            val_schema,
733                            is_transient,
734                            diagnostics,
735                        )
736                        .await
737                        .expect("shard codecs should not change");
738                    (fetcher, max_concurrency)
739                }
740            })
741            .await;
742
743        // Fetch one part on a per-call clone of the fetcher (cheap: shares the
744        // schema cache), carrying the part's input capabilities through so they
745        // come back with the result. The missing-blob diagnostics round-trip
746        // happens inside the future, so the error surfaces only after the fetch
747        // has truly failed.
748        let fetch_one = |caps: [CapabilitySet<TInner>; 2], part: ExchangeableBatchPart<T>| {
749            let mut fetcher = fetcher.clone();
750            async move {
751                let reader_id = part.reader_id().clone();
752                let fetched = fetcher
753                    .fetch_leased_part(part)
754                    .await
755                    .expect("shard_id should match across all workers");
756                let fetched = match fetched {
757                    Ok(fetched) => Ok(fetched),
758                    Err(blob_key) => {
759                        // Ideally, readers should never encounter a missing blob. They place a
760                        // seqno hold as they consume their snapshot/listen, preventing any blobs
761                        // they need from being deleted by garbage collection, and all blob
762                        // implementations are linearizable so there should be no possibility of
763                        // stale reads.
764                        //
765                        // However, it is possible for a lease to expire given a sustained period
766                        // of downtime, which could allow parts we expect to exist to be
767                        // deleted... at which point our best option is to request a restart.
768                        // Check the state of the minting reader's lease to tell the two cases
769                        // apart.
770                        let diagnosis = fetcher.missing_blob_diagnostics(&reader_id).await;
771                        Err(missing_blob_error(
772                            &blob_key,
773                            diagnosis,
774                            &fetcher.metrics.lease.expired_live_read,
775                        ))
776                    }
777                };
778                (caps, fetched)
779            }
780        };
781
782        // Descs accepted from the input but not yet handed to a fetch, FIFO.
783        // Each carries its input capabilities (data + completed-fetches), so
784        // buffering here holds no progress hostage; it only bounds how many
785        // fetches run at once (and thus how many parts are resident in memory).
786        // Timely tracks the frontier through these capabilities: it advances
787        // past a time only once every fetch minted at that time has completed
788        // and dropped its clones, releasing the parts' leases on the chosen
789        // worker via the completed-fetches feedback. Carrying capabilities
790        // rather than a separate time-keyed map makes correctness independent of
791        // the order results come back in.
792        let mut pending: VecDeque<([CapabilitySet<TInner>; 2], ExchangeableBatchPart<T>)> =
793            VecDeque::new();
794        let mut in_flight = FuturesUnordered::new();
795        let mut input_done = false;
796
797        loop {
798            // Start fetches up to the concurrency cap.
799            while in_flight.len() < max_concurrency {
800                let Some((caps, part)) = pending.pop_front() else {
801                    break;
802                };
803                in_flight.push(fetch_one(caps, part));
804            }
805
806            tokio::select! {
807                // Emit completed fetches first, so `in_flight` drains and we do
808                // not hold more than `max_concurrency` parts in memory.
809                biased;
810                Some(([cap, _], fetched)) = in_flight.next(), if !in_flight.is_empty() => {
811                    match fetched {
812                        Ok(fetched) => fetched_output.give(&cap, fetched),
813                        Err(e) => {
814                            // `report_and_stop` never returns, freezing the
815                            // operator: `cap` (and every other in-flight and
816                            // pending capability) stays held, so the data frontier
817                            // never advances past the part we failed to emit.
818                            error_handler.report_and_stop(e).await;
819                        }
820                    }
821                }
822                // Accept new descs while the input is live. Their fetches are
823                // throttled by the `pending` queue above, not here.
824                event = descs_input.next(), if !input_done => {
825                    match event {
826                        Some(Event::Data(caps, data)) => {
827                            // `LeasedBatchPart`es cannot be dropped at this point
828                            // w/o panicking, so swap them to an owned version.
829                            for (_idx, part) in data {
830                                pending.push_back((caps.clone(), part));
831                            }
832                        }
833                        Some(Event::Progress(_)) => {}
834                        None => input_done = true,
835                    }
836                }
837                // Input is exhausted and no fetches remain: we're done.
838                else => break,
839            }
840        }
841    });
842
843    (
844        fetched_stream,
845        completed_fetches_stream,
846        shutdown_button.press_on_drop(),
847    )
848}
849
850#[cfg(test)]
851mod tests {
852    use super::*;
853    use std::sync::Arc;
854
855    use mz_persist::location::{Blob, SeqNo};
856    use mz_persist_types::codec_impls::StringSchema;
857    use timely::dataflow::operators::Leave;
858    use timely::dataflow::operators::Probe;
859    use timely::dataflow::operators::capture::{Capture, Event as CaptureEvent};
860    use timely::dataflow::operators::probe::Handle as ProbeHandle;
861    use timely::progress::Antichain;
862
863    use crate::batch::{INLINE_WRITES_SINGLE_MAX_BYTES, INLINE_WRITES_TOTAL_MAX_BYTES};
864    use crate::cache::PersistClientCache;
865    use crate::internal::paths::{BlobKey, PartialBlobKey};
866    use crate::operators::shard_source::shard_source;
867    use crate::read::LeasedReaderId;
868    use crate::{Diagnostics, PersistLocation, ShardId};
869
870    #[mz_ore::test]
871    fn test_missing_blob_error_tags_expired_lease() {
872        let expired_live_read = IntCounter::new("expired_live_read", "test").expect("valid");
873        let error = |diagnosis| missing_blob_error("key", diagnosis, &expired_live_read);
874        let reader_id = LeasedReaderId::new();
875
876        let expired = error(MissingBlobDiagnosis::LeaseExpired {
877            reader_id: reader_id.clone(),
878        });
879        assert!(expired.is::<ReaderLeaseExpired>(), "{expired:#}");
880        assert_eq!(expired_live_read.get(), 1);
881
882        let not_lost = [
883            MissingBlobDiagnosis::ShardTombstoned {
884                reader_id: reader_id.clone(),
885            },
886            MissingBlobDiagnosis::LeasePresent {
887                reader_id: reader_id.clone(),
888                lease_state: String::new(),
889            },
890            MissingBlobDiagnosis::Unknown { reader_id },
891        ];
892        for diagnosis in not_lost {
893            let error = error(diagnosis);
894            assert!(!error.is::<ReaderLeaseExpired>(), "{error:#}");
895        }
896        assert_eq!(expired_live_read.get(), 1);
897    }
898
899    #[mz_ore::test]
900    fn test_lease_manager() {
901        let lease = Lease::new(SeqNo::minimum());
902        let mut manager = LeaseManager::new();
903        for t in 0u64..10 {
904            manager.push_at(t, lease.clone());
905        }
906        assert_eq!(lease.count(), 11);
907        manager.advance_to(AntichainRef::new(&[5]));
908        assert_eq!(lease.count(), 6);
909        manager.advance_to(AntichainRef::new(&[3]));
910        assert_eq!(lease.count(), 6);
911        manager.advance_to(AntichainRef::new(&[9]));
912        assert_eq!(lease.count(), 2);
913        manager.advance_to(AntichainRef::new(&[10]));
914        assert_eq!(lease.count(), 1);
915    }
916
917    /// Verifies that a `shard_source` will downgrade it's output frontier to
918    /// the `since` of the shard when no explicit `as_of` is given. Even if
919    /// there is no data/no snapshot available in the
920    /// shard.
921    ///
922    /// NOTE: This test is weird: if everything is good it will pass. If we
923    /// break the assumption that we test this will time out and we will notice.
924    #[mz_ore::test(tokio::test(flavor = "multi_thread"))]
925    #[cfg_attr(miri, ignore)] // unsupported operation: returning ready events from epoll_wait is not yet implemented
926    async fn test_shard_source_implicit_initial_as_of() {
927        let persist_client = PersistClient::new_for_tests().await;
928
929        let expected_frontier = 42;
930        let shard_id = ShardId::new();
931
932        initialize_shard(
933            &persist_client,
934            shard_id,
935            Antichain::from_elem(expected_frontier),
936        )
937        .await;
938
939        let res = timely::execute::execute_directly(move |worker| {
940            let until = Antichain::new();
941
942            let (probe, _token) = worker.dataflow::<u64, _, _>(|outer| {
943                let (stream, token) = outer.scoped::<u64, _, _>("hybrid", |scope| {
944                    let transformer = move |_, descs, _| (descs, vec![]);
945                    let (stream, tokens) = shard_source::<String, String, u64, u64, _, _, _>(
946                        outer,
947                        scope,
948                        "test_source",
949                        move || std::future::ready(persist_client.clone()),
950                        shard_id,
951                        None, // No explicit as_of!
952                        SnapshotMode::Include,
953                        until,
954                        Some(transformer),
955                        Arc::new(
956                            <std::string::String as mz_persist_types::Codec>::Schema::default(),
957                        ),
958                        Arc::new(
959                            <std::string::String as mz_persist_types::Codec>::Schema::default(),
960                        ),
961                        FilterResult::keep_all,
962                        false.then_some(|| unreachable!()),
963                        async {},
964                        ErrorHandler::Halt("test"),
965                    );
966                    (stream.leave(outer), tokens)
967                });
968
969                let probe = ProbeHandle::new();
970                let _stream = stream.probe_with(&probe);
971
972                (probe, token)
973            });
974
975            while probe.less_than(&expected_frontier) {
976                worker.step();
977            }
978
979            let mut probe_frontier = Antichain::new();
980            probe.with_frontier(|f| probe_frontier.extend(f.iter().cloned()));
981
982            probe_frontier
983        });
984
985        assert_eq!(res, Antichain::from_elem(expected_frontier));
986    }
987
988    /// Verifies that a `shard_source` will downgrade it's output frontier to
989    /// the given `as_of`. Even if there is no data/no snapshot available in the
990    /// shard.
991    ///
992    /// NOTE: This test is weird: if everything is good it will pass. If we
993    /// break the assumption that we test this will time out and we will notice.
994    #[mz_ore::test(tokio::test(flavor = "multi_thread"))]
995    #[cfg_attr(miri, ignore)] // unsupported operation: returning ready events from epoll_wait is not yet implemented
996    async fn test_shard_source_explicit_initial_as_of() {
997        let persist_client = PersistClient::new_for_tests().await;
998
999        let expected_frontier = 42;
1000        let shard_id = ShardId::new();
1001
1002        initialize_shard(
1003            &persist_client,
1004            shard_id,
1005            Antichain::from_elem(expected_frontier),
1006        )
1007        .await;
1008
1009        let res = timely::execute::execute_directly(move |worker| {
1010            let as_of = Antichain::from_elem(expected_frontier);
1011            let until = Antichain::new();
1012
1013            let (probe, _token) = worker.dataflow::<u64, _, _>(|outer| {
1014                let (stream, token) = outer.scoped::<u64, _, _>("hybrid", |scope| {
1015                    let transformer = move |_, descs, _| (descs, vec![]);
1016                    let (stream, tokens) = shard_source::<String, String, u64, u64, _, _, _>(
1017                        outer,
1018                        scope,
1019                        "test_source",
1020                        move || std::future::ready(persist_client.clone()),
1021                        shard_id,
1022                        Some(as_of), // We specify the as_of explicitly!
1023                        SnapshotMode::Include,
1024                        until,
1025                        Some(transformer),
1026                        Arc::new(
1027                            <std::string::String as mz_persist_types::Codec>::Schema::default(),
1028                        ),
1029                        Arc::new(
1030                            <std::string::String as mz_persist_types::Codec>::Schema::default(),
1031                        ),
1032                        FilterResult::keep_all,
1033                        false.then_some(|| unreachable!()),
1034                        async {},
1035                        ErrorHandler::Halt("test"),
1036                    );
1037                    (stream.leave(outer), tokens)
1038                });
1039
1040                let probe = ProbeHandle::new();
1041                let _stream = stream.probe_with(&probe);
1042
1043                (probe, token)
1044            });
1045
1046            while probe.less_than(&expected_frontier) {
1047                worker.step();
1048            }
1049
1050            let mut probe_frontier = Antichain::new();
1051            probe.with_frontier(|f| probe_frontier.extend(f.iter().cloned()));
1052
1053            probe_frontier
1054        });
1055
1056        assert_eq!(res, Antichain::from_elem(expected_frontier));
1057    }
1058
1059    /// Hydrating an index over a shard with many fine-grained batches (the prod
1060    /// case: a retained-history collection written at ~1/s, whose batches stay
1061    /// unmerged because the held-back `since` blocks compaction) replays one
1062    /// progress round per batch. With
1063    /// `persist_source_hydration_frontier_coalesce_bytes` set, the source holds
1064    /// those downgrades back while catching up to the hydration-time upper and
1065    /// forwards them in a few larger steps instead.
1066    ///
1067    /// This writes `N_BATCHES` single-timestamp batches (compaction disabled so
1068    /// they stay distinct, mirroring a held-back `since`) and runs the source
1069    /// twice over the same shard, counting how many distinct output frontiers it
1070    /// passes through. Disabled (the default) replays per batch; enabled with a
1071    /// budget larger than the whole replay collapses it to a single jump. Both
1072    /// must still reach the same final upper, so coalescing only changes
1073    /// frontier granularity, not how far the source gets.
1074    #[mz_ore::test(tokio::test(flavor = "multi_thread"))]
1075    #[cfg_attr(miri, ignore)] // too slow
1076    async fn test_shard_source_hydration_frontier_coalesce() {
1077        const N_BATCHES: u64 = 64;
1078
1079        // Hydrate the shard from `as_of = 0` with the given coalesce budget and
1080        // return the largest timestamp whose parts were emitted. The source is
1081        // bounded at the upper, so a return at all proves it terminated without
1082        // stalling.
1083        async fn run(coalesce_bytes: usize) -> Option<u64> {
1084            let mut cache = PersistClientCache::new_no_metrics();
1085            // Keep the batches unmerged, so the source sees one batch per write
1086            // just as a retained-history shard does in prod.
1087            cache.cfg.compaction_enabled = false;
1088            cache
1089                .cfg
1090                .set_config(&SOURCE_HYDRATION_FRONTIER_COALESCE_BYTES, coalesce_bytes);
1091            let persist_client = cache
1092                .open(PersistLocation::new_in_mem())
1093                .await
1094                .expect("in-mem location is valid");
1095            let shard_id = ShardId::new();
1096
1097            let mut write = persist_client
1098                .open_writer::<String, String, u64, u64>(
1099                    shard_id,
1100                    Arc::new(StringSchema),
1101                    Arc::new(StringSchema),
1102                    Diagnostics::for_tests(),
1103                )
1104                .await
1105                .expect("invalid usage");
1106
1107            // One append per timestamp: `N_BATCHES` distinct batches sealing
1108            // `[0, N_BATCHES)`.
1109            for t in 0..N_BATCHES {
1110                let row = ((format!("k{t}"), format!("v{t}")), t, 1u64);
1111                write.expect_compare_and_append(&[row], t, t + 1).await;
1112            }
1113
1114            timely::execute::execute_directly(move |worker| {
1115                let (probe, receiver, _token) = worker.dataflow::<u64, _, _>(|outer| {
1116                    let (stream, token) = outer.scoped::<u64, _, _>("hybrid", |scope| {
1117                        let (stream, tokens) = shard_source::<String, String, u64, u64, _, _, _>(
1118                            outer,
1119                            scope,
1120                            "test_source",
1121                            move || std::future::ready(persist_client.clone()),
1122                            shard_id,
1123                            Some(Antichain::from_elem(0)),
1124                            SnapshotMode::Include,
1125                            // Bound the source at the shard upper so it
1126                            // terminates once the replay is done.
1127                            Antichain::from_elem(N_BATCHES),
1128                            Some(move |_, descs, _| (descs, vec![])),
1129                            Arc::new(StringSchema),
1130                            Arc::new(StringSchema),
1131                            FilterResult::keep_all,
1132                            false.then_some(|| unreachable!()),
1133                            async {},
1134                            ErrorHandler::Halt("test"),
1135                        );
1136                        (stream.leave(outer), tokens)
1137                    });
1138                    let probe = ProbeHandle::new();
1139                    // Capture the source's output directly so every progress
1140                    // message is recorded, independent of how many we drain per
1141                    // worker step.
1142                    let receiver = stream.probe_with(&probe).capture();
1143                    (probe, receiver, token)
1144                });
1145
1146                // Step until the source closes its output (until == upper, so it
1147                // drops its capabilities once the replay completes).
1148                let deadline = Instant::now() + std::time::Duration::from_secs(60);
1149                while !probe.with_frontier(|f| f.is_empty()) {
1150                    assert!(Instant::now() < deadline, "timed out hydrating shard");
1151                    worker.step_or_park(Some(std::time::Duration::from_millis(1)));
1152                }
1153
1154                // The largest `Messages` time is the highest timestamp whose
1155                // parts were emitted; it must reach `N_BATCHES - 1` regardless of
1156                // coalescing, because parts always flow per batch and only the
1157                // frontier downgrades are held back.
1158                let mut max_msg_time: Option<u64> = None;
1159                while let Ok(event) = receiver.try_recv() {
1160                    if let CaptureEvent::Messages(stamp, _) = event {
1161                        max_msg_time = max_msg_time.max(stamp.iter().copied().max());
1162                    }
1163                }
1164                max_msg_time
1165            })
1166        }
1167
1168        // Coalescing disabled (default) and enabled with a budget larger than
1169        // the whole replay (a single 0 -> upper jump) must both consume every
1170        // batch and emit parts through the last timestamp. Coalescing changes
1171        // only frontier granularity, not the data emitted or how far we get;
1172        // the round reduction itself is covered by
1173        // `test_frontier_coalesce_decision`, since timely batches progress
1174        // across the dataflow edge in a fast in-mem replay.
1175        assert_eq!(run(0).await, Some(N_BATCHES - 1));
1176        assert_eq!(run(1 << 30).await, Some(N_BATCHES - 1));
1177    }
1178
1179    /// The round-reduction property, tested directly on the forward/coalesce
1180    /// decision so it is independent of timely's progress batching. Simulates
1181    /// replaying `n` unit batches from as-of 0 to upper `n`, each `bytes`
1182    /// encoded bytes, and counts how many progress downgrades get forwarded.
1183    #[mz_ore::test]
1184    fn test_frontier_coalesce_decision() {
1185        fn forwards(coalesce_target: u64, n: u64, bytes_per_batch: u64) -> usize {
1186            let replay_upper = n;
1187            let mut current = 0u64;
1188            let mut coalesced = 0u64;
1189            let mut forwarded = 0usize;
1190            for _ in 0..n {
1191                current += 1;
1192                coalesced += bytes_per_batch;
1193                let caught_up = replay_upper <= current;
1194                // Mirrors the forward/coalesce decision in `shard_source_descs`.
1195                let coalesce = coalesce_target > 0 && !caught_up && coalesced < coalesce_target;
1196                if !coalesce {
1197                    forwarded += 1;
1198                    coalesced = 0;
1199                }
1200            }
1201            forwarded
1202        }
1203
1204        // Disabled: one forward per batch (the per-batch storm).
1205        assert_eq!(forwards(0, 64, 10), 64);
1206        // Budget larger than the whole replay: a single forward at the upper.
1207        assert_eq!(forwards(1 << 30, 64, 10), 1);
1208        // Mid budget: forwards every ~target/bytes batches plus the final
1209        // catch-up forward, so strictly between the two extremes.
1210        let partial = forwards(100, 64, 10);
1211        assert!(
1212            partial > 1 && partial < 64,
1213            "expected partial coalescing, got {partial}"
1214        );
1215    }
1216
1217    /// Verifies that the source fetches and emits actual data: a batch written
1218    /// before the dataflow starts comes out as at least one `FetchedBlob`, and
1219    /// the output frontier reaches the shard's upper.
1220    #[mz_ore::test(tokio::test(flavor = "multi_thread"))]
1221    #[cfg_attr(miri, ignore)] // too slow
1222    async fn test_shard_source_fetches_data() {
1223        let persist_client = PersistClient::new_for_tests().await;
1224        let shard_id = ShardId::new();
1225
1226        let mut write = persist_client
1227            .open_writer::<String, String, u64, u64>(
1228                shard_id,
1229                Arc::new(StringSchema),
1230                Arc::new(StringSchema),
1231                Diagnostics::for_tests(),
1232            )
1233            .await
1234            .expect("invalid usage");
1235        let data = [
1236            (("k1".to_owned(), "v1".to_owned()), 0u64, 1u64),
1237            (("k2".to_owned(), "v2".to_owned()), 1u64, 1u64),
1238        ];
1239        write.expect_compare_and_append(&data[..], 0, 5).await;
1240
1241        let expected_frontier = 5;
1242        let (blob_count, frontier) = timely::execute::execute_directly(move |worker| {
1243            let as_of = Antichain::from_elem(0);
1244            let until = Antichain::new();
1245
1246            let (capture, probe, token) = worker.dataflow::<u64, _, _>(|outer| {
1247                let (stream, token) = outer.scoped::<u64, _, _>("hybrid", |scope| {
1248                    let transformer = move |_, descs, _| (descs, vec![]);
1249                    let (stream, tokens) = shard_source::<String, String, u64, u64, _, _, _>(
1250                        outer,
1251                        scope,
1252                        "test_source",
1253                        move || std::future::ready(persist_client.clone()),
1254                        shard_id,
1255                        Some(as_of),
1256                        SnapshotMode::Include,
1257                        until,
1258                        Some(transformer),
1259                        Arc::new(StringSchema),
1260                        Arc::new(StringSchema),
1261                        FilterResult::keep_all,
1262                        false.then_some(|| unreachable!()),
1263                        async {},
1264                        ErrorHandler::Halt("test"),
1265                    );
1266                    (stream.leave(outer), tokens)
1267                });
1268
1269                let probe = ProbeHandle::new();
1270                let stream = stream.probe_with(&probe);
1271                (stream.capture(), probe, token)
1272            });
1273
1274            let deadline = Instant::now() + std::time::Duration::from_secs(60);
1275            while probe.less_than(&expected_frontier) {
1276                assert!(
1277                    Instant::now() < deadline,
1278                    "timed out waiting for output frontier {expected_frontier}"
1279                );
1280                worker.step();
1281            }
1282            drop(token);
1283
1284            let mut blob_count = 0;
1285            while let Ok(event) = capture.try_recv() {
1286                if let CaptureEvent::Messages(_, msgs) = event {
1287                    blob_count += msgs.len();
1288                }
1289            }
1290            let mut frontier = Antichain::new();
1291            probe.with_frontier(|f| frontier.extend(f.iter().cloned()));
1292            (blob_count, frontier)
1293        });
1294
1295        assert!(blob_count >= 1, "expected at least one fetched blob");
1296        assert_eq!(frontier, Antichain::from_elem(expected_frontier));
1297    }
1298
1299    /// Verifies that dropping the source's tokens while it is running does not
1300    /// panic or wedge the worker: capabilities are released so the dataflow can
1301    /// shut down to the empty frontier.
1302    #[mz_ore::test(tokio::test(flavor = "multi_thread"))]
1303    #[cfg_attr(miri, ignore)] // too slow
1304    async fn test_shard_source_shutdown_mid_stream() {
1305        let persist_client = PersistClient::new_for_tests().await;
1306        let shard_id = ShardId::new();
1307
1308        let mut write = persist_client
1309            .open_writer::<String, String, u64, u64>(
1310                shard_id,
1311                Arc::new(StringSchema),
1312                Arc::new(StringSchema),
1313                Diagnostics::for_tests(),
1314            )
1315            .await
1316            .expect("invalid usage");
1317        let data = [(("k1".to_owned(), "v1".to_owned()), 0u64, 1u64)];
1318        write.expect_compare_and_append(&data[..], 0, 5).await;
1319
1320        timely::execute::execute_directly(move |worker| {
1321            let as_of = Antichain::from_elem(0);
1322            // An empty `until` means the source would run forever if not shut
1323            // down by dropping its tokens.
1324            let until = Antichain::new();
1325
1326            let (probe, token) = worker.dataflow::<u64, _, _>(|outer| {
1327                let (stream, token) = outer.scoped::<u64, _, _>("hybrid", |scope| {
1328                    let transformer = move |_, descs, _| (descs, vec![]);
1329                    let (stream, tokens) = shard_source::<String, String, u64, u64, _, _, _>(
1330                        outer,
1331                        scope,
1332                        "test_source",
1333                        move || std::future::ready(persist_client.clone()),
1334                        shard_id,
1335                        Some(as_of),
1336                        SnapshotMode::Include,
1337                        until,
1338                        Some(transformer),
1339                        Arc::new(StringSchema),
1340                        Arc::new(StringSchema),
1341                        FilterResult::keep_all,
1342                        false.then_some(|| unreachable!()),
1343                        async {},
1344                        ErrorHandler::Halt("test"),
1345                    );
1346                    (stream.leave(outer), tokens)
1347                });
1348
1349                let probe = ProbeHandle::new();
1350                let _stream = stream.probe_with(&probe);
1351                (probe, token)
1352            });
1353
1354            // Step until the source has made progress, so shutdown happens while
1355            // the fetch machinery is live.
1356            let deadline = Instant::now() + std::time::Duration::from_secs(60);
1357            while probe.less_than(&1) {
1358                assert!(Instant::now() < deadline, "timed out waiting for progress");
1359                worker.step();
1360            }
1361
1362            // Shut down and confirm the dataflow drains: with all tokens dropped,
1363            // the operators must release their capabilities and the frontier must
1364            // become empty.
1365            drop(token);
1366            let deadline = Instant::now() + std::time::Duration::from_secs(60);
1367            loop {
1368                assert!(Instant::now() < deadline, "timed out waiting for shutdown");
1369                worker.step();
1370                if probe.with_frontier(|f| f.is_empty()) {
1371                    break;
1372                }
1373            }
1374        });
1375    }
1376
1377    /// Verifies that an unserveable `as_of` (the listing path) reports an error
1378    /// through the `ErrorHandler` and freezes the source: the output frontier
1379    /// stays at the requested `as_of` and the worker does not panic.
1380    #[mz_ore::test(tokio::test(flavor = "multi_thread"))]
1381    #[cfg_attr(miri, ignore)] // too slow
1382    async fn test_shard_source_error_freeze() {
1383        let persist_client = PersistClient::new_for_tests().await;
1384        let shard_id = ShardId::new();
1385
1386        // Write data so the shard's upper is past the as_of (otherwise
1387        // `snapshot` blocks waiting for the upper instead of erroring on the
1388        // since), then advance the since past the as_of we'll request.
1389        let mut write = persist_client
1390            .open_writer::<String, String, u64, u64>(
1391                shard_id,
1392                Arc::new(StringSchema),
1393                Arc::new(StringSchema),
1394                Diagnostics::for_tests(),
1395            )
1396            .await
1397            .expect("invalid usage");
1398        let data = [(("k1".to_owned(), "v1".to_owned()), 0u64, 1u64)];
1399        write.expect_compare_and_append(&data[..], 0, 5).await;
1400        initialize_shard(&persist_client, shard_id, Antichain::from_elem(3)).await;
1401
1402        let (errored, frontier) = timely::execute::execute_directly(move |worker| {
1403            let as_of = Antichain::from_elem(1);
1404            let until = Antichain::new();
1405
1406            let errored = Rc::new(std::cell::Cell::new(false));
1407            let error_handler = ErrorHandler::signal({
1408                let errored = Rc::clone(&errored);
1409                move |_err| errored.set(true)
1410            });
1411
1412            let (probe, _token) = worker.dataflow::<u64, _, _>(|outer| {
1413                let (stream, token) = outer.scoped::<u64, _, _>("hybrid", |scope| {
1414                    let transformer = move |_, descs, _| (descs, vec![]);
1415                    let (stream, tokens) = shard_source::<String, String, u64, u64, _, _, _>(
1416                        outer,
1417                        scope,
1418                        "test_source",
1419                        move || std::future::ready(persist_client.clone()),
1420                        shard_id,
1421                        Some(as_of),
1422                        SnapshotMode::Include,
1423                        until,
1424                        Some(transformer),
1425                        Arc::new(StringSchema),
1426                        Arc::new(StringSchema),
1427                        FilterResult::keep_all,
1428                        false.then_some(|| unreachable!()),
1429                        async {},
1430                        error_handler,
1431                    );
1432                    (stream.leave(outer), tokens)
1433                });
1434
1435                let probe = ProbeHandle::new();
1436                let _stream = stream.probe_with(&probe);
1437                (probe, token)
1438            });
1439
1440            let deadline = Instant::now() + std::time::Duration::from_secs(60);
1441            while !errored.get() {
1442                assert!(Instant::now() < deadline, "timed out waiting for error");
1443                worker.step();
1444            }
1445            // Keep stepping; the source must stay frozen at the as_of.
1446            for _ in 0..100 {
1447                worker.step();
1448            }
1449
1450            let mut frontier = Antichain::new();
1451            probe.with_frontier(|f| frontier.extend(f.iter().cloned()));
1452            (errored.get(), frontier)
1453        });
1454
1455        assert!(errored);
1456        assert_eq!(frontier, Antichain::from_elem(1));
1457    }
1458
1459    /// Regression test for the `shard_source_fetch` freeze path: a blob that
1460    /// goes missing while *fetching* (the listing path is covered by
1461    /// `test_shard_source_error_freeze`) must freeze the output frontier at the
1462    /// missing part and report the error, never advancing past data never
1463    /// emitted.
1464    ///
1465    /// We delete the first batch's blob, which is read by the snapshot at
1466    /// `as_of = 0`. Its fetch fails; the later batches (t=1, t=2) fetch fine. We
1467    /// step until the dataflow quiesces (with brief parks so the tokio fetch
1468    /// task finishes), so the later results are produced, then assert the error
1469    /// fired and the frontier stayed at the missing part.
1470    #[mz_ore::test(tokio::test(flavor = "multi_thread"))]
1471    #[cfg_attr(miri, ignore)] // too slow
1472    async fn test_shard_source_fetch_error_freeze() {
1473        // Force writes to real blobs (inline parts have no blob to delete) and
1474        // disable compaction so the three batches stay distinct and deletable.
1475        let mut cache = PersistClientCache::new_no_metrics();
1476        cache.cfg.compaction_enabled = false;
1477        cache.cfg.set_config(&INLINE_WRITES_SINGLE_MAX_BYTES, 0);
1478        cache.cfg.set_config(&INLINE_WRITES_TOTAL_MAX_BYTES, 0);
1479        let persist_client = cache
1480            .open(PersistLocation::new_in_mem())
1481            .await
1482            .expect("in-mem location is valid");
1483        let shard_id = ShardId::new();
1484        // Clones of a `PersistClient` share the blob `Arc`, so deleting via this
1485        // handle is visible to the reader the source opens.
1486        let blob = Arc::clone(&persist_client.blob);
1487
1488        let mut write = persist_client
1489            .open_writer::<String, String, u64, u64>(
1490                shard_id,
1491                Arc::new(StringSchema),
1492                Arc::new(StringSchema),
1493                Diagnostics::for_tests(),
1494            )
1495            .await
1496            .expect("invalid usage");
1497
1498        // The data-part (non-rollup) blob keys currently present.
1499        async fn batch_keys(blob: &dyn Blob) -> std::collections::BTreeSet<String> {
1500            let mut keys = std::collections::BTreeSet::new();
1501            blob.list_keys_and_metadata("", &mut |meta| {
1502                if let Ok((_, PartialBlobKey::Batch(..))) = BlobKey::parse_ids(meta.key) {
1503                    keys.insert(meta.key.to_owned());
1504                }
1505            })
1506            .await
1507            .expect("list keys");
1508            keys
1509        }
1510
1511        let row = |t: u64| ((format!("k{t}"), format!("v{t}")), t, 1u64);
1512        let before = batch_keys(blob.as_ref()).await;
1513        write.expect_compare_and_append(&[row(0)], 0, 1).await;
1514        let after = batch_keys(blob.as_ref()).await;
1515        write.expect_compare_and_append(&[row(1)], 1, 2).await;
1516        write.expect_compare_and_append(&[row(2)], 2, 3).await;
1517
1518        // Delete exactly the first (t=0) batch's data part(s); the snapshot at
1519        // as_of=0 reads it.
1520        let missing: Vec<_> = after.difference(&before).cloned().collect();
1521        assert!(!missing.is_empty(), "first batch wrote no blob part");
1522        for key in &missing {
1523            blob.delete(key).await.expect("delete");
1524        }
1525
1526        let frontier = timely::execute::execute_directly(move |worker| {
1527            let errored = Rc::new(std::cell::Cell::new(false));
1528            let error_handler = ErrorHandler::signal({
1529                let errored = Rc::clone(&errored);
1530                move |err: anyhow::Error| {
1531                    // The reader's lease is live, so this is not a lost lease.
1532                    assert!(!err.is::<ReaderLeaseExpired>(), "{err:#}");
1533                    errored.set(true)
1534                }
1535            });
1536
1537            let (probe, _token) = worker.dataflow::<u64, _, _>(|outer| {
1538                let (stream, token) = outer.scoped::<u64, _, _>("hybrid", |scope| {
1539                    let (stream, tokens) = shard_source::<String, String, u64, u64, _, _, _>(
1540                        outer,
1541                        scope,
1542                        "test_source",
1543                        move || std::future::ready(persist_client.clone()),
1544                        shard_id,
1545                        Some(Antichain::from_elem(0)),
1546                        SnapshotMode::Include,
1547                        Antichain::new(),
1548                        Some(move |_, descs, _| (descs, vec![])),
1549                        Arc::new(StringSchema),
1550                        Arc::new(StringSchema),
1551                        FilterResult::keep_all,
1552                        false.then_some(|| unreachable!()),
1553                        async {},
1554                        error_handler,
1555                    );
1556                    (stream.leave(outer), tokens)
1557                });
1558                let probe = ProbeHandle::new();
1559                stream.probe_with(&probe);
1560                (probe, token)
1561            });
1562
1563            // Step until the fetch error fires, then step until the dataflow
1564            // quiesces, with brief parks so the tokio fetch task can finish.
1565            let deadline = Instant::now() + std::time::Duration::from_secs(60);
1566            while !errored.get() {
1567                assert!(
1568                    Instant::now() < deadline,
1569                    "timed out waiting for fetch error"
1570                );
1571                worker.step_or_park(Some(std::time::Duration::from_millis(1)));
1572            }
1573            let mut last = probe.with_frontier(|f| f.to_owned());
1574            let mut stable = 0;
1575            while stable < 100 {
1576                assert!(Instant::now() < deadline, "timed out waiting for quiesce");
1577                worker.step_or_park(Some(std::time::Duration::from_millis(1)));
1578                let now = probe.with_frontier(|f| f.to_owned());
1579                if now == last {
1580                    stable += 1;
1581                } else {
1582                    stable = 0;
1583                    last = now;
1584                }
1585            }
1586            last
1587        });
1588
1589        // Frozen at the missing part (t=0); the bug advanced this past it.
1590        assert_eq!(frontier, Antichain::from_elem(0));
1591    }
1592
1593    /// With `persist_source_fetch_concurrency > 1` the source still fetches
1594    /// every part and reaches the shard upper. The frontier can only reach the
1595    /// upper once every part's fetch has completed, so this proves the
1596    /// concurrent path loses nothing even though results complete out of order.
1597    #[mz_ore::test(tokio::test(flavor = "multi_thread"))]
1598    #[cfg_attr(miri, ignore)] // too slow
1599    async fn test_shard_source_fetch_concurrent() {
1600        const N_BATCHES: u64 = 16;
1601
1602        let mut cache = PersistClientCache::new_no_metrics();
1603        cache.cfg.compaction_enabled = false;
1604        cache.cfg.set_config(&SOURCE_FETCH_CONCURRENCY, 8);
1605        let persist_client = cache
1606            .open(PersistLocation::new_in_mem())
1607            .await
1608            .expect("in-mem location is valid");
1609        let shard_id = ShardId::new();
1610
1611        let mut write = persist_client
1612            .open_writer::<String, String, u64, u64>(
1613                shard_id,
1614                Arc::new(StringSchema),
1615                Arc::new(StringSchema),
1616                Diagnostics::for_tests(),
1617            )
1618            .await
1619            .expect("invalid usage");
1620        for t in 0..N_BATCHES {
1621            let row = ((format!("k{t}"), format!("v{t}")), t, 1u64);
1622            write.expect_compare_and_append(&[row], t, t + 1).await;
1623        }
1624
1625        let (blob_count, max_time) = timely::execute::execute_directly(move |worker| {
1626            let (capture, probe, token) = worker.dataflow::<u64, _, _>(|outer| {
1627                let (stream, token) = outer.scoped::<u64, _, _>("hybrid", |scope| {
1628                    let (stream, tokens) = shard_source::<String, String, u64, u64, _, _, _>(
1629                        outer,
1630                        scope,
1631                        "test_source",
1632                        move || std::future::ready(persist_client.clone()),
1633                        shard_id,
1634                        Some(Antichain::from_elem(0)),
1635                        SnapshotMode::Include,
1636                        Antichain::from_elem(N_BATCHES),
1637                        Some(move |_, descs, _| (descs, vec![])),
1638                        Arc::new(StringSchema),
1639                        Arc::new(StringSchema),
1640                        FilterResult::keep_all,
1641                        false.then_some(|| unreachable!()),
1642                        async {},
1643                        ErrorHandler::Halt("test"),
1644                    );
1645                    (stream.leave(outer), tokens)
1646                });
1647                let probe = ProbeHandle::new();
1648                let stream = stream.probe_with(&probe);
1649                (stream.capture(), probe, token)
1650            });
1651
1652            // The source is bounded at the upper, so its frontier empties only
1653            // once every part's fetch has completed; reaching the empty frontier
1654            // proves the concurrent path lost nothing.
1655            let deadline = Instant::now() + std::time::Duration::from_secs(60);
1656            while !probe.with_frontier(|f| f.is_empty()) {
1657                assert!(
1658                    Instant::now() < deadline,
1659                    "timed out waiting for completion"
1660                );
1661                worker.step_or_park(Some(std::time::Duration::from_millis(1)));
1662            }
1663            drop(token);
1664
1665            let mut blob_count = 0;
1666            let mut max_time: Option<u64> = None;
1667            while let Ok(event) = capture.try_recv() {
1668                if let CaptureEvent::Messages(stamp, msgs) = event {
1669                    blob_count += msgs.len();
1670                    max_time = max_time.max(stamp.iter().copied().max());
1671                }
1672            }
1673            (blob_count, max_time)
1674        });
1675
1676        assert!(blob_count >= 1, "expected at least one fetched blob");
1677        // Parts were emitted through the last timestamp.
1678        assert_eq!(max_time, Some(N_BATCHES - 1));
1679    }
1680
1681    /// Fetch-path freeze under concurrency: with several fetches in flight, a
1682    /// missing *middle* batch must still freeze the frontier at that batch, even
1683    /// though later batches fetch fine and may complete before the error is
1684    /// observed. This is the out-of-order analogue of
1685    /// `test_shard_source_fetch_error_freeze`; it exercises the time-keyed
1686    /// capability bookkeeping the concurrent path relies on.
1687    #[mz_ore::test(tokio::test(flavor = "multi_thread"))]
1688    #[cfg_attr(miri, ignore)] // too slow
1689    async fn test_shard_source_fetch_concurrent_error_freeze() {
1690        const N_BATCHES: u64 = 12;
1691        const MISSING_TS: u64 = 5;
1692
1693        let mut cache = PersistClientCache::new_no_metrics();
1694        cache.cfg.compaction_enabled = false;
1695        cache.cfg.set_config(&INLINE_WRITES_SINGLE_MAX_BYTES, 0);
1696        cache.cfg.set_config(&INLINE_WRITES_TOTAL_MAX_BYTES, 0);
1697        cache.cfg.set_config(&SOURCE_FETCH_CONCURRENCY, 8);
1698        let persist_client = cache
1699            .open(PersistLocation::new_in_mem())
1700            .await
1701            .expect("in-mem location is valid");
1702        let shard_id = ShardId::new();
1703        let blob = Arc::clone(&persist_client.blob);
1704
1705        let mut write = persist_client
1706            .open_writer::<String, String, u64, u64>(
1707                shard_id,
1708                Arc::new(StringSchema),
1709                Arc::new(StringSchema),
1710                Diagnostics::for_tests(),
1711            )
1712            .await
1713            .expect("invalid usage");
1714
1715        async fn batch_keys(blob: &dyn Blob) -> std::collections::BTreeSet<String> {
1716            let mut keys = std::collections::BTreeSet::new();
1717            blob.list_keys_and_metadata("", &mut |meta| {
1718                if let Ok((_, PartialBlobKey::Batch(..))) = BlobKey::parse_ids(meta.key) {
1719                    keys.insert(meta.key.to_owned());
1720                }
1721            })
1722            .await
1723            .expect("list keys");
1724            keys
1725        }
1726
1727        // Write each batch, snapshotting the blob keys around the missing one so
1728        // we can delete exactly its part(s).
1729        let mut missing = Vec::new();
1730        for t in 0..N_BATCHES {
1731            let before = batch_keys(blob.as_ref()).await;
1732            let row = ((format!("k{t}"), format!("v{t}")), t, 1u64);
1733            write.expect_compare_and_append(&[row], t, t + 1).await;
1734            if t == MISSING_TS {
1735                let after = batch_keys(blob.as_ref()).await;
1736                missing = after.difference(&before).cloned().collect();
1737            }
1738        }
1739        assert!(!missing.is_empty(), "missing batch wrote no blob part");
1740        for key in &missing {
1741            blob.delete(key).await.expect("delete");
1742        }
1743
1744        let frontier = timely::execute::execute_directly(move |worker| {
1745            let errored = Rc::new(std::cell::Cell::new(false));
1746            let error_handler = ErrorHandler::signal({
1747                let errored = Rc::clone(&errored);
1748                move |_err| errored.set(true)
1749            });
1750
1751            let (probe, _token) = worker.dataflow::<u64, _, _>(|outer| {
1752                let (stream, token) = outer.scoped::<u64, _, _>("hybrid", |scope| {
1753                    let (stream, tokens) = shard_source::<String, String, u64, u64, _, _, _>(
1754                        outer,
1755                        scope,
1756                        "test_source",
1757                        move || std::future::ready(persist_client.clone()),
1758                        shard_id,
1759                        Some(Antichain::from_elem(0)),
1760                        SnapshotMode::Include,
1761                        Antichain::from_elem(N_BATCHES),
1762                        Some(move |_, descs, _| (descs, vec![])),
1763                        Arc::new(StringSchema),
1764                        Arc::new(StringSchema),
1765                        FilterResult::keep_all,
1766                        false.then_some(|| unreachable!()),
1767                        async {},
1768                        error_handler,
1769                    );
1770                    (stream.leave(outer), tokens)
1771                });
1772                let probe = ProbeHandle::new();
1773                stream.probe_with(&probe);
1774                (probe, token)
1775            });
1776
1777            let deadline = Instant::now() + std::time::Duration::from_secs(60);
1778            while !errored.get() {
1779                assert!(
1780                    Instant::now() < deadline,
1781                    "timed out waiting for fetch error"
1782                );
1783                worker.step_or_park(Some(std::time::Duration::from_millis(1)));
1784            }
1785            let mut last = probe.with_frontier(|f| f.to_owned());
1786            let mut stable = 0;
1787            while stable < 100 {
1788                assert!(Instant::now() < deadline, "timed out waiting for quiesce");
1789                worker.step_or_park(Some(std::time::Duration::from_millis(1)));
1790                let now = probe.with_frontier(|f| f.to_owned());
1791                if now == last {
1792                    stable += 1;
1793                } else {
1794                    stable = 0;
1795                    last = now;
1796                }
1797            }
1798            last
1799        });
1800
1801        // Frozen at the missing batch despite later batches fetching fine
1802        // concurrently.
1803        assert_eq!(frontier, Antichain::from_elem(MISSING_TS));
1804    }
1805
1806    async fn initialize_shard(
1807        persist_client: &PersistClient,
1808        shard_id: ShardId,
1809        since: Antichain<u64>,
1810    ) {
1811        let mut read_handle = persist_client
1812            .open_leased_reader::<String, String, u64, u64>(
1813                shard_id,
1814                Arc::new(<std::string::String as mz_persist_types::Codec>::Schema::default()),
1815                Arc::new(<std::string::String as mz_persist_types::Codec>::Schema::default()),
1816                Diagnostics::for_tests(),
1817                true,
1818            )
1819            .await
1820            .expect("invalid usage");
1821
1822        read_handle.downgrade_since(&since).await;
1823    }
1824}