Skip to main content

mz_persist_client/
read.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//! Read capabilities and handles
11
12use async_stream::stream;
13use std::collections::BTreeMap;
14use std::fmt::Debug;
15use std::future::Future;
16use std::sync::Arc;
17use std::time::{Duration, Instant};
18
19use differential_dataflow::Hashable;
20use differential_dataflow::consolidation::consolidate_updates;
21use differential_dataflow::difference::Monoid;
22use differential_dataflow::lattice::Lattice;
23use futures::Stream;
24use futures_util::{StreamExt, stream};
25use mz_dyncfg::{Config, ParameterScope};
26use mz_ore::cast::CastLossy;
27use mz_ore::halt;
28use mz_ore::instrument;
29use mz_ore::process::halt_with_code;
30use mz_ore::task::JoinHandle;
31use mz_persist::location::{Blob, SeqNo};
32use mz_persist_types::columnar::{ColumnDecoder, Schema};
33use mz_persist_types::{Codec, Codec64};
34use proptest_derive::Arbitrary;
35use serde::{Deserialize, Serialize};
36use timely::PartialOrder;
37use timely::order::TotalOrder;
38use timely::progress::{Antichain, Timestamp};
39use tracing::warn;
40use uuid::Uuid;
41
42use crate::batch::BLOB_TARGET_SIZE;
43use crate::cfg::{COMPACTION_MEMORY_BOUND_BYTES, RetryParameters};
44use crate::fetch::FetchConfig;
45use crate::fetch::{FetchBatchFilter, FetchedPart, Lease, LeasedBatchPart, fetch_leased_part};
46use crate::internal::encoding::Schemas;
47use crate::internal::machine::{Machine, next_listen_batch_retry_params};
48use crate::internal::metrics::{Metrics, ReadMetrics, ShardMetrics};
49use crate::internal::state::{HollowBatch, LeasedReaderState, SnapshotErr};
50use crate::internal::watch::{AwaitableState, StateWatch};
51use crate::iter::{Consolidator, StructuredSort};
52use crate::schema::SchemaCache;
53use crate::stats::{SnapshotPartStats, SnapshotPartsStats, SnapshotStats};
54use crate::{GarbageCollector, PersistConfig, ShardId, parse_id};
55
56pub use crate::internal::encoding::LazyPartStats;
57pub use crate::internal::state::Since;
58
59/// An opaque identifier for a reader of a persist durable TVC (aka shard).
60#[derive(
61    Arbitrary,
62    Clone,
63    PartialEq,
64    Eq,
65    PartialOrd,
66    Ord,
67    Hash,
68    Serialize,
69    Deserialize
70)]
71#[serde(try_from = "String", into = "String")]
72pub struct LeasedReaderId(pub(crate) [u8; 16]);
73
74impl std::fmt::Display for LeasedReaderId {
75    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
76        write!(f, "r{}", Uuid::from_bytes(self.0))
77    }
78}
79
80impl std::fmt::Debug for LeasedReaderId {
81    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
82        write!(f, "LeasedReaderId({})", Uuid::from_bytes(self.0))
83    }
84}
85
86impl std::str::FromStr for LeasedReaderId {
87    type Err = String;
88
89    fn from_str(s: &str) -> Result<Self, Self::Err> {
90        parse_id("r", "LeasedReaderId", s).map(LeasedReaderId)
91    }
92}
93
94impl From<LeasedReaderId> for String {
95    fn from(reader_id: LeasedReaderId) -> Self {
96        reader_id.to_string()
97    }
98}
99
100impl TryFrom<String> for LeasedReaderId {
101    type Error = String;
102
103    fn try_from(s: String) -> Result<Self, Self::Error> {
104        s.parse()
105    }
106}
107
108impl LeasedReaderId {
109    pub(crate) fn new() -> Self {
110        LeasedReaderId(*Uuid::new_v4().as_bytes())
111    }
112}
113
114/// Capable of generating a snapshot of all data at `as_of`, followed by a
115/// listen of all updates.
116///
117/// For more details, see [`ReadHandle::snapshot`] and [`Listen`].
118#[derive(Debug)]
119pub struct Subscribe<K: Codec, V: Codec, T, D> {
120    snapshot: Option<Vec<LeasedBatchPart<T>>>,
121    listen: Listen<K, V, T, D>,
122}
123
124impl<K, V, T, D> Subscribe<K, V, T, D>
125where
126    K: Debug + Codec,
127    V: Debug + Codec,
128    T: Timestamp + TotalOrder + Lattice + Codec64 + Sync,
129    D: Monoid + Codec64 + Send + Sync,
130{
131    fn new(snapshot_parts: Vec<LeasedBatchPart<T>>, listen: Listen<K, V, T, D>) -> Self {
132        Subscribe {
133            snapshot: Some(snapshot_parts),
134            listen,
135        }
136    }
137
138    /// Returns a `LeasedBatchPart` enriched with the proper metadata.
139    ///
140    /// First returns snapshot parts, until they're exhausted, at which point
141    /// begins returning listen parts.
142    ///
143    /// The returned `Antichain` represents the subscription progress as it will
144    /// be _after_ the returned parts are fetched.
145    #[instrument(level = "debug", fields(shard = %self.listen.handle.machine.shard_id()))]
146    pub async fn next(
147        &mut self,
148        // If Some, an override for the default listen sleep retry parameters.
149        listen_retry: Option<RetryParameters>,
150    ) -> Vec<ListenEvent<T, LeasedBatchPart<T>>> {
151        match self.snapshot.take() {
152            Some(parts) => vec![ListenEvent::Updates(parts)],
153            None => {
154                let (parts, upper) = self.listen.next(listen_retry).await;
155                vec![ListenEvent::Updates(parts), ListenEvent::Progress(upper)]
156            }
157        }
158    }
159}
160
161impl<K, V, T, D> Subscribe<K, V, T, D>
162where
163    K: Debug + Codec,
164    V: Debug + Codec,
165    T: Timestamp + TotalOrder + Lattice + Codec64 + Sync,
166    D: Monoid + Codec64 + Send + Sync,
167{
168    /// Equivalent to `next`, but rather than returning a [`LeasedBatchPart`],
169    /// fetches and returns the data from within it.
170    #[instrument(level = "debug", fields(shard = %self.listen.handle.machine.shard_id()))]
171    pub async fn fetch_next(&mut self) -> Vec<ListenEvent<T, ((K, V), T, D)>> {
172        let events = self.next(None).await;
173        let new_len = events
174            .iter()
175            .map(|event| match event {
176                ListenEvent::Updates(parts) => parts.len(),
177                ListenEvent::Progress(_) => 1,
178            })
179            .sum();
180        let mut ret = Vec::with_capacity(new_len);
181        for event in events {
182            match event {
183                ListenEvent::Updates(parts) => {
184                    for part in parts {
185                        let fetched_part = self.listen.fetch_batch_part(part).await;
186                        let updates = fetched_part.collect::<Vec<_>>();
187                        if !updates.is_empty() {
188                            ret.push(ListenEvent::Updates(updates));
189                        }
190                    }
191                }
192                ListenEvent::Progress(progress) => ret.push(ListenEvent::Progress(progress)),
193            }
194        }
195        ret
196    }
197
198    /// Fetches the contents of `part` and returns its lease.
199    pub async fn fetch_batch_part(&mut self, part: LeasedBatchPart<T>) -> FetchedPart<K, V, T, D> {
200        self.listen.fetch_batch_part(part).await
201    }
202
203    /// Expires this subscribe's reader out of state but keeps the handle, as a
204    /// missed heartbeat would. Tests only: GC no longer protects its parts.
205    #[doc(hidden)]
206    pub async fn expire_lease_for_tests(&self) {
207        let handle = &self.listen.handle;
208        let _ = handle.machine.expire_leased_reader(&handle.reader_id).await;
209    }
210}
211
212impl<K, V, T, D> Subscribe<K, V, T, D>
213where
214    K: Debug + Codec,
215    V: Debug + Codec,
216    T: Timestamp + TotalOrder + Lattice + Codec64 + Sync,
217    D: Monoid + Codec64 + Send + Sync,
218{
219    /// Politely expires this subscribe, releasing its lease.
220    ///
221    /// There is a best-effort impl in Drop to expire the
222    /// [`ReadHandle`] held by the subscribe that wasn't explicitly expired
223    /// with this method. When possible, explicit expiry is still preferred
224    /// because it also ensures that the background task is complete.
225    pub async fn expire(mut self) {
226        let _ = self.snapshot.take(); // Drop all leased parts.
227        self.listen.expire().await;
228    }
229}
230
231/// Data and progress events of a shard subscription.
232///
233/// TODO: Unify this with [timely::dataflow::operators::capture::event::Event].
234#[derive(Debug, PartialEq)]
235pub enum ListenEvent<T, D> {
236    /// Progress of the shard.
237    Progress(Antichain<T>),
238    /// Data of the shard.
239    Updates(Vec<D>),
240}
241
242/// An ongoing subscription of updates to a shard.
243#[derive(Debug)]
244pub struct Listen<K: Codec, V: Codec, T, D> {
245    handle: ReadHandle<K, V, T, D>,
246    as_of: Antichain<T>,
247    since: Antichain<T>,
248    frontier: Antichain<T>,
249}
250
251impl<K, V, T, D> Listen<K, V, T, D>
252where
253    K: Debug + Codec,
254    V: Debug + Codec,
255    T: Timestamp + TotalOrder + Lattice + Codec64 + Sync,
256    D: Monoid + Codec64 + Send + Sync,
257{
258    async fn new(
259        mut handle: ReadHandle<K, V, T, D>,
260        as_of: Antichain<T>,
261    ) -> Result<Self, Since<T>> {
262        let () = handle.machine.verify_listen(&as_of)?;
263
264        let since = as_of.clone();
265        if !PartialOrder::less_equal(handle.since(), &since) {
266            // We can't guarantee that the as-of will be available by the time we start reading,
267            // since our handle is already downgraded too far.
268            return Err(Since(handle.since().clone()));
269        }
270        // This listen only needs to distinguish things after its frontier
271        // (initially as_of although the frontier is inclusive and the as_of
272        // isn't). Be a good citizen and downgrade early.
273        handle.downgrade_since(&since).await;
274        Ok(Listen {
275            handle,
276            since,
277            frontier: as_of.clone(),
278            as_of,
279        })
280    }
281
282    /// An exclusive upper bound on the progress of this Listen.
283    pub fn frontier(&self) -> &Antichain<T> {
284        &self.frontier
285    }
286
287    /// Attempt to pull out the next values of this subscription.
288    ///
289    /// The returned [`LeasedBatchPart`] is appropriate to use with
290    /// `crate::fetch::fetch_leased_part`.
291    ///
292    /// The returned `Antichain` represents the subscription progress as it will
293    /// be _after_ the returned parts are fetched.
294    pub async fn next(
295        &mut self,
296        // If Some, an override for the default listen sleep retry parameters.
297        retry: Option<RetryParameters>,
298    ) -> (Vec<LeasedBatchPart<T>>, Antichain<T>) {
299        // Wait until the upper is past our frontier - ie. there is another batch for us to process.
300        let retry = retry
301            .unwrap_or_else(|| next_listen_batch_retry_params(&self.handle.machine.applier.cfg));
302        self.handle
303            .machine
304            .wait_for_upper_past(
305                &self.frontier,
306                &mut self.handle.watch,
307                Some(&self.handle.reader_id),
308                &self.handle.metrics.retries.next_listen_batch,
309                retry,
310            )
311            .await;
312
313        // Obtain a lease before grabbing the upcoming batch from state.
314        let lease = self.handle.lease_seqno().await;
315        let batch = match self
316            .handle
317            .machine
318            .applier
319            .next_listen_batch(&self.frontier)
320        {
321            Ok(batch) => batch,
322            Err(seqno) => {
323                panic!(
324                    "waited for upper past {frontier:?}, but no listen batch was available at {seqno:?}!",
325                    frontier = self.frontier.elements()
326                );
327            }
328        };
329
330        // A lot of things across mz have to line up to hold the following
331        // invariant and violations only show up as subtle correctness errors,
332        // so explicitly validate it here. Better to panic and roll back a
333        // release than be incorrect (also potentially corrupting a sink).
334        //
335        // Note that the since check is intentionally less_than, not less_equal.
336        // If a batch's since is X, that means we can no longer distinguish X
337        // (beyond self.frontier) from X-1 (not beyond self.frontier) to keep
338        // former and filter out the latter.
339        let acceptable_desc = PartialOrder::less_than(batch.desc.since(), &self.frontier)
340            // Special case when the frontier == the as_of (i.e. the first
341            // time this is called on a new Listen). Because as_of is
342            // _exclusive_, we don't need to be able to distinguish X from
343            // X-1.
344            || (self.frontier == self.as_of
345            && PartialOrder::less_equal(batch.desc.since(), &self.frontier));
346        if !acceptable_desc {
347            let lease_state = self
348                .handle
349                .machine
350                .applier
351                .reader_lease(self.handle.reader_id.clone());
352            if let Some(lease) = lease_state {
353                panic!(
354                    "Listen on {} received a batch {:?} advanced past the listen frontier {:?}, but the lease has not expired: {:?}",
355                    self.handle.machine.shard_id(),
356                    batch.desc,
357                    self.frontier,
358                    lease
359                )
360            } else if self.handle.machine.applier.is_tombstone() {
361                // Finalizing the shard removes every reader, which is not a lost lease.
362                halt!(
363                    "Listen on {} received a batch {:?} advanced past the listen frontier {:?} after the shard was tombstoned",
364                    self.handle.machine.shard_id(),
365                    batch.desc,
366                    self.frontier
367                )
368            } else {
369                // Ideally we'd percolate this error up, so callers could eg. restart a dataflow
370                // instead of restarting a process...
371                halt_with_code(
372                    READER_LEASE_EXPIRED_EXIT_CODE,
373                    format_args!(
374                        "Listen on {} received a batch {:?} advanced past the listen frontier {:?} after the reader has expired. \
375                     This can happen in exceptional cases: a machine goes to sleep or is running out of memory or CPU, for example.",
376                        self.handle.machine.shard_id(),
377                        batch.desc,
378                        self.frontier
379                    ),
380                )
381            }
382        }
383
384        let new_frontier = batch.desc.upper().clone();
385
386        // We will have a new frontier, so this is an opportunity to downgrade our
387        // since capability. Go through `maybe_heartbeat` so we can rate limit
388        // this along with our heartbeats.
389        //
390        // HACK! Everything would be simpler if we could downgrade since to the
391        // new frontier, but we can't. The next call needs to be able to
392        // distinguish between the times T at the frontier (to emit updates with
393        // these times) and T-1 (to filter them). Advancing the since to
394        // frontier would erase the ability to distinguish between them. Ideally
395        // we'd use what is conceptually "batch.upper - 1" (the greatest
396        // elements that are still strictly less than batch.upper, which will be
397        // the new value of self.frontier after this call returns), but the
398        // trait bounds on T don't give us a way to compute that directly.
399        // Instead, we sniff out any elements in self.frontier (the upper of the
400        // batch the last time we called this) that are strictly less_than the
401        // batch upper to compute a new since. For totally ordered times
402        // (currently always the case in mz) self.frontier will always have a
403        // single element and it will be less_than upper. We
404        // could also abuse the fact that every time we actually emit is
405        // guaranteed by definition to be less_than upper to be a bit more
406        // prompt, but this would involve a lot more temporary antichains and
407        // it's unclear if that's worth it.
408        for x in self.frontier.elements().iter() {
409            let less_than_upper = batch.desc.upper().elements().iter().any(|u| x.less_than(u));
410            if less_than_upper {
411                self.since.join_assign(&Antichain::from_elem(x.clone()));
412            }
413        }
414
415        // IMPORTANT! Make sure this `lease_batch_parts` stays before the
416        // `maybe_downgrade_since` call. Otherwise, we might give up our
417        // capability on the batch's SeqNo before we lease it, which could lead
418        // to blobs that it references being GC'd.
419        let filter = FetchBatchFilter::Listen {
420            as_of: self.as_of.clone(),
421            lower: self.frontier.clone(),
422        };
423        let parts = self
424            .handle
425            .lease_batch_parts(lease, batch, filter)
426            .collect()
427            .await;
428
429        self.handle.maybe_downgrade_since(&self.since).await;
430
431        // NB: Keep this after we use self.frontier to join_assign self.since
432        // and also after we construct metadata.
433        self.frontier = new_frontier;
434
435        (parts, self.frontier.clone())
436    }
437}
438
439impl<K, V, T, D> Listen<K, V, T, D>
440where
441    K: Debug + Codec,
442    V: Debug + Codec,
443    T: Timestamp + TotalOrder + Lattice + Codec64 + Sync,
444    D: Monoid + Codec64 + Send + Sync,
445{
446    /// Attempt to pull out the next values of this subscription.
447    ///
448    /// The updates received in [ListenEvent::Updates] should be assumed to be in arbitrary order
449    /// and not necessarily consolidated. However, the timestamp of each individual update will be
450    /// greater than or equal to the last received [ListenEvent::Progress] frontier (or this
451    /// [Listen]'s initial `as_of` frontier if no progress event has been emitted yet) and less
452    /// than the next [ListenEvent::Progress] frontier.
453    ///
454    /// If you have a use for consolidated listen output, given that snapshots can't be
455    /// consolidated, come talk to us!
456    #[instrument(level = "debug", name = "listen::next", fields(shard = %self.handle.machine.shard_id()))]
457    pub async fn fetch_next(&mut self) -> Vec<ListenEvent<T, ((K, V), T, D)>> {
458        let (parts, progress) = self.next(None).await;
459        let mut ret = Vec::with_capacity(parts.len() + 1);
460        for part in parts {
461            let fetched_part = self.fetch_batch_part(part).await;
462            let updates = fetched_part.collect::<Vec<_>>();
463            if !updates.is_empty() {
464                ret.push(ListenEvent::Updates(updates));
465            }
466        }
467        ret.push(ListenEvent::Progress(progress));
468        ret
469    }
470
471    /// Convert listener into futures::Stream
472    pub fn into_stream(mut self) -> impl Stream<Item = ListenEvent<T, ((K, V), T, D)>> {
473        async_stream::stream!({
474            loop {
475                for msg in self.fetch_next().await {
476                    yield msg;
477                }
478            }
479        })
480    }
481
482    /// Test helper to read from the listener until the given frontier is
483    /// reached. Because compaction can arbitrarily combine batches, we only
484    /// return the final progress info.
485    #[cfg(test)]
486    #[track_caller]
487    pub async fn read_until(&mut self, ts: &T) -> (Vec<((K, V), T, D)>, Antichain<T>) {
488        let mut updates = Vec::new();
489        let mut frontier = Antichain::from_elem(T::minimum());
490        while self.frontier.less_than(ts) {
491            for event in self.fetch_next().await {
492                match event {
493                    ListenEvent::Updates(mut x) => updates.append(&mut x),
494                    ListenEvent::Progress(x) => frontier = x,
495                }
496            }
497        }
498        // Unlike most tests, intentionally don't consolidate updates here
499        // because Listen replays them at the original fidelity.
500        (updates, frontier)
501    }
502}
503
504impl<K, V, T, D> Listen<K, V, T, D>
505where
506    K: Debug + Codec,
507    V: Debug + Codec,
508    T: Timestamp + TotalOrder + Lattice + Codec64 + Sync,
509    D: Monoid + Codec64 + Send + Sync,
510{
511    /// Fetches the contents of `part` and returns its lease.
512    ///
513    /// This is broken out into its own function to provide a trivial means for
514    /// [`Subscribe`], which contains a [`Listen`], to fetch batches.
515    async fn fetch_batch_part(&mut self, part: LeasedBatchPart<T>) -> FetchedPart<K, V, T, D> {
516        let fetched_part = fetch_leased_part(
517            &self.handle.cfg,
518            &part,
519            self.handle.blob.as_ref(),
520            Arc::clone(&self.handle.metrics),
521            &self.handle.metrics.read.listen,
522            &self.handle.machine.applier.shard_metrics,
523            &self.handle.reader_id,
524            self.handle.read_schemas.clone(),
525            &mut self.handle.schema_cache,
526        )
527        .await;
528        fetched_part
529    }
530
531    /// Politely expires this listen, releasing its lease.
532    ///
533    /// There is a best-effort impl in to expire the
534    /// [`ReadHandle`] held by the listen that wasn't explicitly expired with
535    /// this method. When possible, explicit expiry is still preferred because
536    /// it also ensures that the background task is complete.
537    pub async fn expire(self) {
538        self.handle.expire().await
539    }
540}
541
542/// The state for read holds shared between the heartbeat task and the main client,
543/// including the since frontier and the seqno hold.
544#[derive(Debug)]
545pub(crate) struct ReadHolds<T> {
546    /// The frontier we should hold the time-based lease back to.
547    held_since: Antichain<T>,
548    /// The since hold we've actually committed to state. Should always be <=
549    /// the since hold.
550    applied_since: Antichain<T>,
551    /// The largest seqno we've observed in the state.
552    recent_seqno: SeqNo,
553    /// The set of active leases. We hold back the seqno to the minimum lease or
554    /// the recent_seqno, whichever is earlier.
555    leases: BTreeMap<SeqNo, Lease>,
556    /// True iff this state is expired.
557    expired: bool,
558    /// Used to trigger the background task to heartbeat state, instead of waiting for
559    /// the next tick.
560    request_sync: bool,
561}
562
563impl<T> ReadHolds<T>
564where
565    T: Timestamp + TotalOrder + Lattice + Codec64 + Sync,
566{
567    pub fn downgrade_since(&mut self, since: &Antichain<T>) {
568        self.held_since.join_assign(since);
569    }
570
571    pub fn observe_seqno(&mut self, seqno: SeqNo) {
572        self.recent_seqno = seqno.max(self.recent_seqno);
573    }
574
575    pub fn lease_seqno(&mut self) -> Lease {
576        let seqno = self.recent_seqno;
577        let lease = self
578            .leases
579            .entry(seqno)
580            .or_insert_with(|| Lease::new(seqno));
581        lease.clone()
582    }
583
584    pub fn outstanding_seqno(&mut self) -> SeqNo {
585        while let Some(first) = self.leases.first_entry() {
586            if first.get().count() <= 1 {
587                first.remove();
588            } else {
589                return *first.key();
590            }
591        }
592        self.recent_seqno
593    }
594}
595
596/// A "capability" granting the ability to read the state of some shard at times
597/// greater or equal to `self.since()`.
598///
599/// Production users should call [Self::expire] before dropping a ReadHandle so
600/// that it can expire its leases. If/when rust gets AsyncDrop, this will be
601/// done automatically.
602///
603/// All async methods on ReadHandle retry for as long as they are able, but the
604/// returned [std::future::Future]s implement "cancel on drop" semantics. This
605/// means that callers can add a timeout using [tokio::time::timeout] or
606/// [tokio::time::timeout_at].
607///
608/// ```rust,no_run
609/// # let mut read: mz_persist_client::read::ReadHandle<String, String, u64, i64> = unimplemented!();
610/// # let timeout: std::time::Duration = unimplemented!();
611/// # let new_since: timely::progress::Antichain<u64> = unimplemented!();
612/// # async {
613/// tokio::time::timeout(timeout, read.downgrade_since(&new_since)).await
614/// # };
615/// ```
616#[derive(Debug)]
617pub struct ReadHandle<K: Codec, V: Codec, T, D> {
618    pub(crate) cfg: PersistConfig,
619    pub(crate) metrics: Arc<Metrics>,
620    pub(crate) machine: Machine<K, V, T, D>,
621    pub(crate) gc: GarbageCollector<K, V, T, D>,
622    pub(crate) blob: Arc<dyn Blob>,
623    watch: StateWatch<K, V, T, D>,
624
625    pub(crate) reader_id: LeasedReaderId,
626    pub(crate) read_schemas: Schemas<K, V>,
627    pub(crate) schema_cache: SchemaCache<K, V, T, D>,
628
629    since: Antichain<T>,
630    pub(crate) hold_state: AwaitableState<ReadHolds<T>>,
631    pub(crate) unexpired_state: Option<UnexpiredReadHandleState>,
632}
633
634/// The exit code of a process halted because a live reader lost its lease.
635///
636/// Distinct from [`halt!`]'s 166 so alerting can tell a lost lease from a
637/// routine restart; cloud alerting matches on it. Under Kubernetes the pod is
638/// restarted (with crash backoff), as for any non-zero exit.
639pub const READER_LEASE_EXPIRED_EXIT_CODE: i32 = 168;
640
641/// Length of time after a reader's last operation after which the reader may be
642/// expired.
643pub(crate) const READER_LEASE_DURATION: Config<Duration> = Config::new(
644    "persist_reader_lease_duration",
645    Duration::from_secs(60 * 15),
646    "The time after which we'll clean up stale read leases",
647    ParameterScope::Environment,
648);
649
650impl<K, V, T, D> ReadHandle<K, V, T, D>
651where
652    K: Debug + Codec,
653    V: Debug + Codec,
654    T: Timestamp + TotalOrder + Lattice + Codec64 + Sync,
655    D: Monoid + Codec64 + Send + Sync,
656{
657    #[allow(clippy::unused_async)]
658    pub(crate) async fn new(
659        cfg: PersistConfig,
660        metrics: Arc<Metrics>,
661        machine: Machine<K, V, T, D>,
662        gc: GarbageCollector<K, V, T, D>,
663        blob: Arc<dyn Blob>,
664        reader_id: LeasedReaderId,
665        read_schemas: Schemas<K, V>,
666        state: LeasedReaderState<T>,
667    ) -> Self {
668        let schema_cache = machine.applier.schema_cache();
669        let hold_state = AwaitableState::new(ReadHolds {
670            held_since: state.since.clone(),
671            applied_since: state.since.clone(),
672            recent_seqno: state.seqno,
673            leases: Default::default(),
674            expired: false,
675            request_sync: false,
676        });
677        ReadHandle {
678            cfg,
679            metrics: Arc::clone(&metrics),
680            machine: machine.clone(),
681            gc: gc.clone(),
682            blob,
683            watch: machine.applier.watch(),
684            reader_id: reader_id.clone(),
685            read_schemas,
686            schema_cache,
687            since: state.since,
688            hold_state: hold_state.clone(),
689            unexpired_state: Some(UnexpiredReadHandleState {
690                heartbeat_task: Self::start_reader_heartbeat_task(
691                    machine, reader_id, gc, hold_state,
692                ),
693            }),
694        }
695    }
696
697    fn start_reader_heartbeat_task(
698        machine: Machine<K, V, T, D>,
699        reader_id: LeasedReaderId,
700        gc: GarbageCollector<K, V, T, D>,
701        leased_seqnos: AwaitableState<ReadHolds<T>>,
702    ) -> JoinHandle<()> {
703        let metrics = Arc::clone(&machine.applier.metrics);
704        let name = format!(
705            "persist::heartbeat_read({},{})",
706            machine.shard_id(),
707            reader_id
708        );
709        mz_ore::task::spawn(|| name, {
710            metrics.tasks.heartbeat_read.instrument_task(async move {
711                Self::reader_heartbeat_task(machine, reader_id, gc, leased_seqnos).await
712            })
713        })
714    }
715
716    async fn reader_heartbeat_task(
717        machine: Machine<K, V, T, D>,
718        reader_id: LeasedReaderId,
719        gc: GarbageCollector<K, V, T, D>,
720        leased_seqnos: AwaitableState<ReadHolds<T>>,
721    ) {
722        let sleep_duration = READER_LEASE_DURATION.get(&machine.applier.cfg) / 4;
723        // Jitter the first tick to avoid a thundering herd when many readers are started around
724        // the same instant, like during deploys.
725        let jitter: f64 = f64::cast_lossy(reader_id.hashed()) / f64::cast_lossy(u64::MAX);
726        let mut interval = tokio::time::interval_at(
727            tokio::time::Instant::now() + sleep_duration.mul_f64(jitter),
728            sleep_duration,
729        );
730        let mut held_since = leased_seqnos.read(|s| s.held_since.clone());
731        loop {
732            let before_sleep = Instant::now();
733            let _woke_by_tick = tokio::select! {
734                _tick = interval.tick() => {
735                    true
736                }
737                _whatever = leased_seqnos.wait_while(|s| !s.request_sync) => {
738                    false
739                }
740            };
741
742            let elapsed_since_before_sleeping = before_sleep.elapsed();
743            if elapsed_since_before_sleeping > sleep_duration + Duration::from_secs(60) {
744                warn!(
745                    "reader ({}) of shard ({}) went {}s between heartbeats",
746                    reader_id,
747                    machine.shard_id(),
748                    elapsed_since_before_sleeping.as_secs_f64()
749                );
750            }
751
752            let before_heartbeat = Instant::now();
753            let current_seqno = machine.seqno();
754            let result = leased_seqnos.modify(|s| {
755                if s.expired {
756                    Err(())
757                } else {
758                    s.observe_seqno(current_seqno);
759                    s.request_sync = false;
760                    held_since.join_assign(&s.held_since);
761                    Ok(s.outstanding_seqno())
762                }
763            });
764            let actual_since = match result {
765                Ok(held_seqno) => {
766                    let (seqno, actual_since, maintenance) = machine
767                        .downgrade_since(&reader_id, held_seqno, &held_since)
768                        .await;
769                    leased_seqnos.modify(|s| {
770                        s.applied_since.clone_from(&actual_since.0);
771                        s.observe_seqno(seqno)
772                    });
773                    maintenance.start_performing(&machine, &gc);
774                    actual_since
775                }
776                Err(()) => {
777                    let (seqno, maintenance) = machine.expire_leased_reader(&reader_id).await;
778                    leased_seqnos.modify(|s| s.observe_seqno(seqno));
779                    maintenance.start_performing(&machine, &gc);
780                    break;
781                }
782            };
783
784            let elapsed_since_heartbeat = before_heartbeat.elapsed();
785            if elapsed_since_heartbeat > Duration::from_secs(60) {
786                warn!(
787                    "reader ({}) of shard ({}) heartbeat call took {}s",
788                    reader_id,
789                    machine.shard_id(),
790                    elapsed_since_heartbeat.as_secs_f64(),
791                );
792            }
793
794            if PartialOrder::less_than(&held_since, &actual_since.0) {
795                // If the read handle was intentionally expired, this task
796                // *should* be aborted before it observes the expiration. So if
797                // we get here, this task somehow failed to keep the read lease
798                // alive. Warn loudly, because there's now a live read handle to
799                // an expired shard that will panic if used, but don't panic,
800                // just in case there is some edge case that results in this
801                // task observing the intentional expiration of a read handle.
802                warn!(
803                    "heartbeat task for reader ({}) of shard ({}) exiting due to expired lease \
804                     while read handle is live",
805                    reader_id,
806                    machine.shard_id(),
807                );
808                return;
809            }
810        }
811    }
812
813    /// This handle's shard id.
814    pub fn shard_id(&self) -> ShardId {
815        self.machine.shard_id()
816    }
817
818    /// This handle's `since` frontier.
819    ///
820    /// This will always be greater or equal to the shard-global `since`.
821    pub fn since(&self) -> &Antichain<T> {
822        &self.since
823    }
824
825    /// A less-stale cached version of the shard-global `upper` frontier.
826    ///
827    /// This is the most recently known upper for this shard process-wide. It
828    /// requires a mutex and a clone. This will always be less or equal to the
829    /// shard-global `upper`.
830    pub fn shared_upper(&self) -> Antichain<T> {
831        self.machine.applier.clone_upper()
832    }
833
834    #[cfg(test)]
835    fn outstanding_seqno(&self) -> SeqNo {
836        let current_seqno = self.machine.seqno();
837        self.hold_state.modify(|s| {
838            s.observe_seqno(current_seqno);
839            s.outstanding_seqno()
840        })
841    }
842
843    /// Forwards the since frontier of this handle, giving up the ability to
844    /// read at times not greater or equal to `new_since`.
845    ///
846    /// This may trigger (asynchronous) compaction and consolidation in the
847    /// system. A `new_since` of the empty antichain "finishes" this shard,
848    /// promising that no more data will ever be read by this handle.
849    #[instrument(level = "debug", fields(shard = %self.machine.shard_id()))]
850    pub async fn downgrade_since(&mut self, new_since: &Antichain<T>) {
851        self.since = new_since.clone();
852        self.hold_state.modify(|s| {
853            s.downgrade_since(new_since);
854            s.request_sync = true;
855        });
856        self.hold_state
857            .wait_while(|s| PartialOrder::less_than(&s.applied_since, new_since))
858            .await;
859    }
860
861    /// Returns an ongoing subscription of updates to a shard.
862    ///
863    /// The stream includes all data at times greater than `as_of`. Combined
864    /// with [Self::snapshot] it will produce exactly correct results: the
865    /// snapshot is the TVCs contents at `as_of` and all subsequent updates
866    /// occur at exactly their indicated time. The recipient should only
867    /// downgrade their read capability when they are certain they have all data
868    /// through the frontier they would downgrade to.
869    ///
870    /// This takes ownership of the ReadHandle so the Listen can use it to
871    /// [Self::downgrade_since] as it progresses. If you need to keep this
872    /// handle, then [Self::clone] it before calling listen.
873    ///
874    /// The `Since` error indicates that the requested `as_of` cannot be served
875    /// (the caller has out of date information) and includes the smallest
876    /// `as_of` that would have been accepted.
877    #[instrument(level = "debug", fields(shard = %self.machine.shard_id()))]
878    pub async fn listen(self, as_of: Antichain<T>) -> Result<Listen<K, V, T, D>, Since<T>> {
879        Listen::new(self, as_of).await
880    }
881
882    async fn snapshot_batches(
883        &mut self,
884        as_of: Antichain<T>,
885    ) -> Result<(Lease, Vec<HollowBatch<T>>), Since<T>> {
886        self.machine
887            .wait_for_upper_past(
888                &as_of,
889                &mut self.watch,
890                Some(&self.reader_id),
891                &self.metrics.retries.snapshot,
892                RetryParameters::persist_defaults(),
893            )
894            .await;
895        let lease = self.lease_seqno().await;
896        let batches = match self.machine.applier.snapshot(&as_of) {
897            Ok(data) => data,
898            Err(SnapshotErr::AsOfHistoricalDistinctionsLost(since)) => return Err(since),
899            Err(SnapshotErr::AsOfNotYetAvailable(seqno, upper)) => {
900                panic!(
901                    "waited for upper past {as_of:?}, but at latest seqno {seqno:?} the frontier was only {upper:?}",
902                    as_of = as_of.elements(),
903                    upper = upper.0.elements(),
904                )
905            }
906        };
907        Ok((lease, batches))
908    }
909
910    /// Returns all of the contents of the shard TVC at `as_of` broken up into
911    /// [`LeasedBatchPart`]es. These parts can be "turned in" via
912    /// `crate::fetch::fetch_batch_part` to receive the data they contain.
913    ///
914    /// This command returns the contents of this shard as of `as_of` once they
915    /// are known. This may "block" (in an async-friendly way) if `as_of` is
916    /// greater or equal to the current `upper` of the shard. The recipient
917    /// should only downgrade their read capability when they are certain they
918    /// have all data through the frontier they would downgrade to.
919    ///
920    /// The `Since` error indicates that the requested `as_of` cannot be served
921    /// (the caller has out of date information) and includes the smallest
922    /// `as_of` that would have been accepted.
923    #[instrument(level = "trace", fields(shard = %self.machine.shard_id()))]
924    pub async fn snapshot(
925        &mut self,
926        as_of: Antichain<T>,
927    ) -> Result<Vec<LeasedBatchPart<T>>, Since<T>> {
928        let (lease, batches) = self.snapshot_batches(as_of.clone()).await?;
929
930        if !PartialOrder::less_equal(self.since(), &as_of) {
931            return Err(Since(self.since().clone()));
932        }
933
934        let filter = FetchBatchFilter::Snapshot { as_of };
935        let mut leased_parts = Vec::new();
936        for batch in batches {
937            // Flatten the HollowBatch into one LeasedBatchPart per key. Each key
938            // corresponds to a "part" or s3 object. This allows persist_source
939            // to distribute work by parts (smallish, more even size) instead of
940            // batches (arbitrarily large).
941            leased_parts.extend(
942                self.lease_batch_parts(lease.clone(), batch, filter.clone())
943                    .collect::<Vec<_>>()
944                    .await,
945            );
946        }
947        Ok(leased_parts)
948    }
949
950    /// Returns a snapshot of all of a shard's data using `as_of`, followed by
951    /// listening to any future updates.
952    ///
953    /// For more details on this operation's semantics, see [Self::snapshot] and
954    /// [Self::listen].
955    #[instrument(level = "debug", fields(shard = %self.machine.shard_id()))]
956    pub async fn subscribe(
957        mut self,
958        as_of: Antichain<T>,
959    ) -> Result<Subscribe<K, V, T, D>, Since<T>> {
960        let snapshot_parts = self.snapshot(as_of.clone()).await?;
961        let listen = self.listen(as_of.clone()).await?;
962        Ok(Subscribe::new(snapshot_parts, listen))
963    }
964
965    fn lease_batch_parts(
966        &mut self,
967        lease: Lease,
968        batch: HollowBatch<T>,
969        filter: FetchBatchFilter<T>,
970    ) -> impl Stream<Item = LeasedBatchPart<T>> + '_ {
971        stream! {
972            let blob = Arc::clone(&self.blob);
973            let metrics = Arc::clone(&self.metrics);
974            let desc = batch.desc.clone();
975            let bounds_truncated = batch.runs().any(|(meta, _)| meta.bounds_truncated());
976            for await part in batch.part_stream(self.shard_id(), &*blob, &*metrics) {
977                yield LeasedBatchPart {
978                    metrics: Arc::clone(&self.metrics),
979                    shard_id: self.machine.shard_id(),
980                    filter: filter.clone(),
981                    desc: desc.clone(),
982                    part: part.expect("leased part").into_owned(),
983                    lease: lease.clone(),
984                    reader_id: self.reader_id.clone(),
985                    filter_pushdown_audit: false,
986                    bounds_truncated,
987                }
988            }
989        }
990    }
991
992    /// Tracks that the `ReadHandle`'s machine's current `SeqNo` is being
993    /// "leased out" to a `LeasedBatchPart`. This ensures that until the reader is expired or the
994    /// [Lease] is dropped, we will hold onto all versions of the state with this sequence number
995    /// or larger. In particular, this means that any batches that are present in the state at
996    /// the leased seqno _or in any future state_ will be preserved as long as the lease is active.
997    ///
998    /// Note that this doesn't present batches from earlier versions of state from being GCed,
999    /// even if they were observed just before the lease call. Callers should generally take a lease
1000    /// first, and then inspect state to find any batches to return or process.
1001    async fn lease_seqno(&mut self) -> Lease {
1002        let current_seqno = self.machine.seqno();
1003        let lease = self.hold_state.modify(|s| {
1004            s.observe_seqno(current_seqno);
1005            s.lease_seqno()
1006        });
1007        // The seqno we've leased may be the seqno observed by our heartbeat task, which could be
1008        // ahead of the last state we saw. Ensure we only observe states in the future of our hold.
1009        // (Since these are backed by the same state in the same process, this should all be pretty
1010        // fast.)
1011        self.watch.wait_for_seqno_ge(lease.seqno()).await;
1012        lease
1013    }
1014
1015    /// Returns an independent [ReadHandle] with a new [LeasedReaderId] but the
1016    /// same `since`.
1017    #[instrument(level = "debug", fields(shard = %self.machine.shard_id()))]
1018    pub async fn clone(&self, purpose: &str) -> Self {
1019        let new_reader_id = LeasedReaderId::new();
1020        let machine = self.machine.clone();
1021        let gc = self.gc.clone();
1022        let (reader_state, maintenance) = machine
1023            .register_leased_reader(
1024                &new_reader_id,
1025                purpose,
1026                READER_LEASE_DURATION.get(&self.cfg),
1027                false,
1028            )
1029            .await;
1030        maintenance.start_performing(&machine, &gc);
1031        // The point of clone is that you're guaranteed to have the same (or
1032        // greater) since capability, verify that.
1033        // TODO: better if it's the same since capability exactly.
1034        assert!(PartialOrder::less_equal(&reader_state.since, &self.since));
1035        let new_reader = ReadHandle::new(
1036            self.cfg.clone(),
1037            Arc::clone(&self.metrics),
1038            machine,
1039            gc,
1040            Arc::clone(&self.blob),
1041            new_reader_id,
1042            self.read_schemas.clone(),
1043            reader_state,
1044        )
1045        .await;
1046        new_reader
1047    }
1048
1049    /// A rate-limited version of [Self::downgrade_since].
1050    ///
1051    /// Users can call this as frequently as they wish; changes will be periodically
1052    /// flushed to state by the heartbeat task.
1053    #[allow(clippy::unused_async)]
1054    pub async fn maybe_downgrade_since(&mut self, new_since: &Antichain<T>) {
1055        self.since = new_since.clone();
1056        self.hold_state.modify(|s| {
1057            s.downgrade_since(new_since);
1058        });
1059    }
1060
1061    /// Politely expires this reader, releasing its lease.
1062    ///
1063    /// There is a best-effort impl in Drop to expire a reader that wasn't
1064    /// explictly expired with this method. When possible, explicit expiry is
1065    /// still preferred because it also ensures that the background task is complete.
1066    #[instrument(level = "debug", fields(shard = %self.machine.shard_id()))]
1067    pub async fn expire(mut self) {
1068        self.hold_state.modify(|s| {
1069            s.expired = true;
1070            s.request_sync = true;
1071        });
1072        let Some(unexpired_state) = self.unexpired_state.take() else {
1073            return;
1074        };
1075        unexpired_state.heartbeat_task.await;
1076    }
1077
1078    /// Test helper for a [Self::listen] call that is expected to succeed.
1079    #[cfg(test)]
1080    #[track_caller]
1081    pub async fn expect_listen(self, as_of: T) -> Listen<K, V, T, D> {
1082        self.listen(Antichain::from_elem(as_of))
1083            .await
1084            .expect("cannot serve requested as_of")
1085    }
1086}
1087
1088/// State for a read handle that has not been explicitly expired.
1089#[derive(Debug)]
1090pub(crate) struct UnexpiredReadHandleState {
1091    pub(crate) heartbeat_task: JoinHandle<()>,
1092}
1093
1094/// An incremental cursor through a particular shard, returned from [ReadHandle::snapshot_cursor].
1095///
1096/// To read an entire dataset, the
1097/// client should call `next` until it returns `None`, which signals all data has been returned...
1098/// but it's also free to abandon the instance at any time if it eg. only needs a few entries.
1099#[derive(Debug)]
1100pub struct Cursor<K: Codec, V: Codec, T: Timestamp + Codec64, D: Codec64, L = Lease> {
1101    consolidator: Consolidator<T, D, StructuredSort<K, V, T, D>>,
1102    max_len: usize,
1103    max_bytes: usize,
1104    _lease: L,
1105    read_schemas: Schemas<K, V>,
1106}
1107
1108impl<K: Codec, V: Codec, T: Timestamp + Codec64, D: Codec64, L> Cursor<K, V, T, D, L> {
1109    /// Extracts and returns the lease from the cursor. Allowing the caller to
1110    /// do any necessary cleanup associated with the lease.
1111    pub fn into_lease(self: Self) -> L {
1112        self._lease
1113    }
1114}
1115
1116impl<K, V, T, D, L> Cursor<K, V, T, D, L>
1117where
1118    K: Debug + Codec + Ord,
1119    V: Debug + Codec + Ord,
1120    T: Timestamp + Lattice + Codec64 + Sync,
1121    D: Monoid + Ord + Codec64 + Send + Sync,
1122{
1123    /// Grab the next batch of consolidated data.
1124    pub async fn next(&mut self) -> Option<impl Iterator<Item = ((K, V), T, D)> + '_> {
1125        let Self {
1126            consolidator,
1127            max_len,
1128            max_bytes,
1129            _lease,
1130            read_schemas: _,
1131        } = self;
1132
1133        let part = consolidator
1134            .next_chunk(*max_len, *max_bytes)
1135            .await
1136            .expect("fetching a leased part")?;
1137        let key_decoder = self
1138            .read_schemas
1139            .key
1140            .decoder_any(part.key.as_ref())
1141            .expect("ok");
1142        let val_decoder = self
1143            .read_schemas
1144            .val
1145            .decoder_any(part.val.as_ref())
1146            .expect("ok");
1147        let iter = (0..part.len()).map(move |i| {
1148            let mut k = K::default();
1149            let mut v = V::default();
1150            key_decoder.decode(i, &mut k);
1151            val_decoder.decode(i, &mut v);
1152            let t = T::decode(part.time.value(i).to_le_bytes());
1153            let d = D::decode(part.diff.value(i).to_le_bytes());
1154            ((k, v), t, d)
1155        });
1156
1157        Some(iter)
1158    }
1159}
1160
1161impl<K, V, T, D> ReadHandle<K, V, T, D>
1162where
1163    K: Debug + Codec + Ord,
1164    V: Debug + Codec + Ord,
1165    T: Timestamp + TotalOrder + Lattice + Codec64 + Sync,
1166    D: Monoid + Ord + Codec64 + Send + Sync,
1167{
1168    /// Generates a [Self::snapshot], and fetches all of the batches it
1169    /// contains.
1170    ///
1171    /// The output is consolidated. Furthermore, to keep memory usage down when
1172    /// reading a snapshot that consolidates well, this consolidates as it goes.
1173    ///
1174    /// Potential future improvements (if necessary):
1175    /// - Accept something like a `F: Fn(K,V) -> (K,V)` argument, which looks
1176    ///   like an MFP you might be pushing down. Reason being that if you are
1177    ///   projecting or transforming in a way that allows further consolidation,
1178    ///   amazing.
1179    /// - Reuse any code we write to streaming-merge consolidate in
1180    ///   persist_source here.
1181    pub async fn snapshot_and_fetch(
1182        &mut self,
1183        as_of: Antichain<T>,
1184    ) -> Result<Vec<((K, V), T, D)>, Since<T>> {
1185        let mut cursor = self.snapshot_cursor(as_of, |_| true).await?;
1186        let mut contents = Vec::new();
1187        while let Some(iter) = cursor.next().await {
1188            contents.extend(iter);
1189        }
1190
1191        // We don't currently guarantee that encoding is one-to-one, so we still need to
1192        // consolidate the decoded outputs. However, let's report if this isn't a noop.
1193        let old_len = contents.len();
1194        consolidate_updates(&mut contents);
1195        if old_len != contents.len() {
1196            // TODO(bkirwi): do we need more / finer-grained metrics for this?
1197            self.machine
1198                .applier
1199                .shard_metrics
1200                .unconsolidated_snapshot
1201                .inc();
1202        }
1203
1204        Ok(contents)
1205    }
1206
1207    /// Generates a [Self::snapshot], and fetches all of the batches it
1208    /// contains.
1209    ///
1210    /// To keep memory usage down when reading a snapshot that consolidates well, this consolidates
1211    /// as it goes. However, note that only the serialized data is consolidated: the deserialized
1212    /// data will only be consolidated if your K/V codecs are one-to-one.
1213    pub async fn snapshot_cursor(
1214        &mut self,
1215        as_of: Antichain<T>,
1216        should_fetch_part: impl for<'a> Fn(Option<&'a LazyPartStats>) -> bool,
1217    ) -> Result<Cursor<K, V, T, D>, Since<T>> {
1218        let (lease, batches) = self.snapshot_batches(as_of.clone()).await?;
1219
1220        Self::read_batches_consolidated(
1221            &self.cfg,
1222            Arc::clone(&self.metrics),
1223            Arc::clone(&self.machine.applier.shard_metrics),
1224            self.metrics.read.snapshot.clone(),
1225            Arc::clone(&self.blob),
1226            self.shard_id(),
1227            as_of,
1228            self.read_schemas.clone(),
1229            &batches,
1230            lease,
1231            should_fetch_part,
1232            COMPACTION_MEMORY_BOUND_BYTES.get(&self.cfg),
1233        )
1234    }
1235
1236    pub(crate) fn read_batches_consolidated<L>(
1237        persist_cfg: &PersistConfig,
1238        metrics: Arc<Metrics>,
1239        shard_metrics: Arc<ShardMetrics>,
1240        read_metrics: ReadMetrics,
1241        blob: Arc<dyn Blob>,
1242        shard_id: ShardId,
1243        as_of: Antichain<T>,
1244        schemas: Schemas<K, V>,
1245        batches: &[HollowBatch<T>],
1246        lease: L,
1247        should_fetch_part: impl for<'a> Fn(Option<&'a LazyPartStats>) -> bool,
1248        memory_budget_bytes: usize,
1249    ) -> Result<Cursor<K, V, T, D, L>, Since<T>> {
1250        let context = format!("{}[as_of={:?}]", shard_id, as_of.elements());
1251        let filter = FetchBatchFilter::Snapshot {
1252            as_of: as_of.clone(),
1253        };
1254
1255        let mut consolidator = Consolidator::new(
1256            context,
1257            FetchConfig::from_persist_config(persist_cfg),
1258            shard_id,
1259            StructuredSort::new(schemas.clone()),
1260            blob,
1261            metrics,
1262            shard_metrics,
1263            read_metrics,
1264            filter,
1265            None,
1266            memory_budget_bytes,
1267        );
1268        for batch in batches {
1269            for (meta, run) in batch.runs() {
1270                consolidator.enqueue_run(
1271                    &batch.desc,
1272                    meta,
1273                    run.into_iter()
1274                        .filter(|p| should_fetch_part(p.stats()))
1275                        .cloned(),
1276                );
1277            }
1278        }
1279        // This default may end up consolidating more records than previously
1280        // for cases like fast-path peeks, where only the first few entries are used.
1281        // If this is a noticeable performance impact, thread the max-len in from the caller.
1282        let max_len = persist_cfg.compaction_yield_after_n_updates;
1283        let max_bytes = BLOB_TARGET_SIZE.get(persist_cfg).max(1);
1284
1285        Ok(Cursor {
1286            consolidator,
1287            max_len,
1288            max_bytes,
1289            _lease: lease,
1290            read_schemas: schemas,
1291        })
1292    }
1293
1294    /// Returns aggregate statistics about the contents of the shard TVC at the
1295    /// given frontier.
1296    ///
1297    /// This command returns the contents of this shard as of `as_of` once they
1298    /// are known. This may "block" (in an async-friendly way) if `as_of` is
1299    /// greater or equal to the current `upper` of the shard. If `None` is given
1300    /// for `as_of`, then the latest stats known by this process are used.
1301    ///
1302    /// The `Since` error indicates that the requested `as_of` cannot be served
1303    /// (the caller has out of date information) and includes the smallest
1304    /// `as_of` that would have been accepted.
1305    pub fn snapshot_stats(
1306        &self,
1307        as_of: Option<Antichain<T>>,
1308    ) -> impl Future<Output = Result<SnapshotStats, Since<T>>> + Send + 'static {
1309        let machine = self.machine.clone();
1310        async move {
1311            let batches = match as_of {
1312                Some(as_of) => machine.unleased_snapshot(&as_of).await?,
1313                None => machine.applier.all_batches(),
1314            };
1315            let num_updates = batches.iter().map(|b| b.len).sum();
1316            Ok(SnapshotStats {
1317                shard_id: machine.shard_id(),
1318                num_updates,
1319            })
1320        }
1321    }
1322
1323    /// Returns aggregate statistics about the contents of the shard TVC at the
1324    /// given frontier.
1325    ///
1326    /// This command returns the contents of this shard as of `as_of` once they
1327    /// are known. This may "block" (in an async-friendly way) if `as_of` is
1328    /// greater or equal to the current `upper` of the shard.
1329    ///
1330    /// The `Since` error indicates that the requested `as_of` cannot be served
1331    /// (the caller has out of date information) and includes the smallest
1332    /// `as_of` that would have been accepted.
1333    pub async fn snapshot_parts_stats(
1334        &self,
1335        as_of: Antichain<T>,
1336    ) -> Result<SnapshotPartsStats, Since<T>> {
1337        let batches = self.machine.unleased_snapshot(&as_of).await?;
1338        let parts = stream::iter(&batches)
1339            .flat_map(|b| b.part_stream(self.shard_id(), &*self.blob, &*self.metrics))
1340            .map(|p| {
1341                let p = p.expect("live batch");
1342                SnapshotPartStats {
1343                    encoded_size_bytes: p.encoded_size_bytes(),
1344                    stats: p.stats().cloned(),
1345                }
1346            })
1347            .collect()
1348            .await;
1349        Ok(SnapshotPartsStats {
1350            metrics: Arc::clone(&self.machine.applier.metrics),
1351            shard_id: self.machine.shard_id(),
1352            parts,
1353        })
1354    }
1355}
1356
1357impl<K, V, T, D> ReadHandle<K, V, T, D>
1358where
1359    K: Debug + Codec + Ord,
1360    V: Debug + Codec + Ord,
1361    T: Timestamp + TotalOrder + Lattice + Codec64 + Sync,
1362    D: Monoid + Codec64 + Send + Sync,
1363{
1364    /// Generates a [Self::snapshot], and streams out all of the updates
1365    /// it contains in bounded memory.
1366    ///
1367    /// The output is not consolidated.
1368    pub async fn snapshot_and_stream(
1369        &mut self,
1370        as_of: Antichain<T>,
1371    ) -> Result<impl Stream<Item = ((K, V), T, D)> + use<K, V, T, D>, Since<T>> {
1372        let snap = self.snapshot(as_of).await?;
1373
1374        let blob = Arc::clone(&self.blob);
1375        let metrics = Arc::clone(&self.metrics);
1376        let snapshot_metrics = self.metrics.read.snapshot.clone();
1377        let shard_metrics = Arc::clone(&self.machine.applier.shard_metrics);
1378        let reader_id = self.reader_id.clone();
1379        let schemas = self.read_schemas.clone();
1380        let mut schema_cache = self.schema_cache.clone();
1381        let persist_cfg = self.cfg.clone();
1382        let stream = async_stream::stream! {
1383            for part in snap {
1384                let mut fetched_part = fetch_leased_part(
1385                    &persist_cfg,
1386                    &part,
1387                    blob.as_ref(),
1388                    Arc::clone(&metrics),
1389                    &snapshot_metrics,
1390                    &shard_metrics,
1391                    &reader_id,
1392                    schemas.clone(),
1393                    &mut schema_cache,
1394                )
1395                .await;
1396
1397                while let Some(next) = fetched_part.next() {
1398                    yield next;
1399                }
1400            }
1401        };
1402
1403        Ok(stream)
1404    }
1405}
1406
1407impl<K, V, T, D> ReadHandle<K, V, T, D>
1408where
1409    K: Debug + Codec + Ord,
1410    V: Debug + Codec + Ord,
1411    T: Timestamp + TotalOrder + Lattice + Codec64 + Sync,
1412    D: Monoid + Ord + Codec64 + Send + Sync,
1413{
1414    /// Test helper to generate a [Self::snapshot] call that is expected to
1415    /// succeed, process its batches, and then return its data sorted.
1416    #[cfg(test)]
1417    #[track_caller]
1418    pub async fn expect_snapshot_and_fetch(&mut self, as_of: T) -> Vec<((K, V), T, D)> {
1419        let mut ret = self
1420            .snapshot_and_fetch(Antichain::from_elem(as_of))
1421            .await
1422            .expect("cannot serve requested as_of");
1423
1424        ret.sort();
1425        ret
1426    }
1427}
1428
1429impl<K: Codec, V: Codec, T, D> Drop for ReadHandle<K, V, T, D> {
1430    fn drop(&mut self) {
1431        self.hold_state.modify(|s| {
1432            s.expired = true;
1433            s.request_sync = true;
1434        });
1435    }
1436}
1437
1438#[cfg(test)]
1439mod tests {
1440    use std::pin;
1441    use std::str::FromStr;
1442
1443    use mz_dyncfg::ConfigUpdates;
1444    use mz_ore::cast::CastFrom;
1445    use mz_ore::metrics::MetricsRegistry;
1446    use mz_persist::mem::{MemBlob, MemBlobConfig, MemConsensus};
1447    use mz_persist::unreliable::{UnreliableConsensus, UnreliableHandle};
1448    use serde::{Deserialize, Serialize};
1449    use serde_json::json;
1450    use tokio_stream::StreamExt;
1451
1452    use crate::async_runtime::IsolatedRuntime;
1453    use crate::batch::BLOB_TARGET_SIZE;
1454    use crate::cache::StateCache;
1455    use crate::internal::metrics::Metrics;
1456    use crate::rpc::NoopPubSubSender;
1457    use crate::tests::{all_ok, new_test_client};
1458    use crate::{Diagnostics, PersistClient, PersistConfig, ShardId};
1459
1460    use super::*;
1461
1462    // Verifies `Subscribe` can be dropped while holding snapshot batches.
1463    #[mz_persist_proc::test(tokio::test)]
1464    #[cfg_attr(miri, ignore)] // unsupported operation: returning ready events from epoll_wait is not yet implemented
1465    async fn drop_unused_subscribe(dyncfgs: ConfigUpdates) {
1466        let data = [
1467            (("0".to_owned(), "zero".to_owned()), 0, 1),
1468            (("1".to_owned(), "one".to_owned()), 1, 1),
1469            (("2".to_owned(), "two".to_owned()), 2, 1),
1470        ];
1471
1472        let (mut write, read) = new_test_client(&dyncfgs)
1473            .await
1474            .expect_open::<String, String, u64, i64>(crate::ShardId::new())
1475            .await;
1476
1477        write.expect_compare_and_append(&data[0..1], 0, 1).await;
1478        write.expect_compare_and_append(&data[1..2], 1, 2).await;
1479        write.expect_compare_and_append(&data[2..3], 2, 3).await;
1480
1481        let subscribe = read
1482            .subscribe(timely::progress::Antichain::from_elem(2))
1483            .await
1484            .unwrap();
1485        assert!(
1486            !subscribe.snapshot.as_ref().unwrap().is_empty(),
1487            "snapshot must have batches for test to be meaningful"
1488        );
1489        drop(subscribe);
1490    }
1491
1492    // The ignored-data fetch optimization substitutes a part's write-time
1493    // diffs_sum for a real fetch, but a truncated batch's parts may hold
1494    // updates that a real fetch would filter out, so it must not fire for
1495    // them.
1496    #[mz_ore::test(tokio::test)]
1497    #[cfg_attr(miri, ignore)] // unsupported operation: returning ready events from epoll_wait is not yet implemented
1498    async fn maybe_optimize_ignores_truncated_batches() {
1499        use arrow::array::{ArrayRef, StringArray};
1500
1501        use crate::batch::{INLINE_WRITES_SINGLE_MAX_BYTES, INLINE_WRITES_TOTAL_MAX_BYTES};
1502        use crate::cache::PersistClientCache;
1503
1504        let mut cache = PersistClientCache::new_no_metrics();
1505        // Compaction rewrites truncated batches with exact bounds, which
1506        // would undo the setup below.
1507        cache.cfg.compaction_enabled = false;
1508        // The optimization only applies to hollow parts.
1509        cache.cfg.set_config(&INLINE_WRITES_SINGLE_MAX_BYTES, 0);
1510        cache.cfg.set_config(&INLINE_WRITES_TOTAL_MAX_BYTES, 0);
1511        let client = cache
1512            .open(crate::PersistLocation::new_in_mem())
1513            .await
1514            .expect("client construction failed");
1515        let (mut write, mut read) = client
1516            .expect_open::<String, String, u64, i64>(ShardId::new())
1517            .await;
1518
1519        write
1520            .expect_compare_and_append(&[(("0".to_owned(), "zero".to_owned()), 0, 1)], 0, 1)
1521            .await;
1522
1523        // Write a batch over [0, 3) but append it under [1, 3): the update
1524        // at 0 stays in the part while every read filters it out.
1525        let mut batch = write
1526            .expect_batch(
1527                &[
1528                    (("stale".to_owned(), "stale".to_owned()), 0, 1),
1529                    (("1".to_owned(), "one".to_owned()), 1, 1),
1530                    (("2".to_owned(), "two".to_owned()), 2, 1),
1531                ],
1532                0,
1533                3,
1534            )
1535            .await;
1536        write
1537            .compare_and_append_batch(
1538                &mut [&mut batch],
1539                Antichain::from_elem(1),
1540                Antichain::from_elem(3),
1541                true,
1542            )
1543            .await
1544            .expect("invalid usage")
1545            .expect("unexpected upper");
1546
1547        // Advance the upper so a snapshot as_of 3 is available.
1548        write
1549            .expect_compare_and_append(&[(("3".to_owned(), "three".to_owned()), 3, 1)], 3, 4)
1550            .await;
1551
1552        let parts = read
1553            .snapshot(Antichain::from_elem(3))
1554            .await
1555            .expect("as_of unavailable");
1556
1557        let mut faked = 0;
1558        let mut kept_truncated = 0;
1559        for mut part in parts {
1560            let key: ArrayRef = Arc::new(StringArray::from(vec!["k"]));
1561            let val: ArrayRef = Arc::new(StringArray::from(vec!["v"]));
1562            part.maybe_optimize(&cache.cfg, key, val);
1563            match part.desc.lower().elements() {
1564                [0] => {
1565                    // Control: an untruncated batch below the as_of gets its
1566                    // fetch optimized away.
1567                    assert!(!part.bounds_truncated);
1568                    assert!(part.part.is_inline(), "expected a faked part");
1569                    faked += 1;
1570                }
1571                [1] => {
1572                    // The truncated batch's statistics count the update at 0,
1573                    // so the fetch must happen for real.
1574                    assert!(part.bounds_truncated);
1575                    assert!(
1576                        !part.part.is_inline(),
1577                        "must not substitute statistics for a truncated part"
1578                    );
1579                    kept_truncated += 1;
1580                }
1581                [3] => (),
1582                x => panic!("unexpected part lower {:?}", x),
1583            }
1584        }
1585        assert_eq!(faked, 1);
1586        assert_eq!(kept_truncated, 1);
1587    }
1588
1589    // Verifies that we streaming-consolidate away identical key-values in the same batch.
1590    #[mz_persist_proc::test(tokio::test)]
1591    #[cfg_attr(miri, ignore)] // unsupported operation: returning ready events from epoll_wait is not yet implemented
1592    async fn streaming_consolidate(dyncfgs: ConfigUpdates) {
1593        let data = &[
1594            // Identical records should sum together...
1595            (("k".to_owned(), "v".to_owned()), 0, 1),
1596            (("k".to_owned(), "v".to_owned()), 1, 1),
1597            (("k".to_owned(), "v".to_owned()), 2, 1),
1598            // ...and when they cancel out entirely they should be omitted.
1599            (("k2".to_owned(), "v".to_owned()), 0, 1),
1600            (("k2".to_owned(), "v".to_owned()), 1, -1),
1601        ];
1602
1603        let (mut write, read) = {
1604            let client = new_test_client(&dyncfgs).await;
1605            client.cfg.set_config(&BLOB_TARGET_SIZE, 1000); // So our batch stays together!
1606            client
1607                .expect_open::<String, String, u64, i64>(crate::ShardId::new())
1608                .await
1609        };
1610
1611        write.expect_compare_and_append(data, 0, 5).await;
1612
1613        let mut snapshot = read
1614            .subscribe(timely::progress::Antichain::from_elem(4))
1615            .await
1616            .unwrap();
1617
1618        let mut updates = vec![];
1619        'outer: loop {
1620            for event in snapshot.fetch_next().await {
1621                match event {
1622                    ListenEvent::Progress(t) => {
1623                        if !t.less_than(&4) {
1624                            break 'outer;
1625                        }
1626                    }
1627                    ListenEvent::Updates(data) => {
1628                        updates.extend(data);
1629                    }
1630                }
1631            }
1632        }
1633        assert_eq!(updates, &[(("k".to_owned(), "v".to_owned()), 4u64, 3i64)],)
1634    }
1635
1636    #[mz_persist_proc::test(tokio::test)]
1637    #[cfg_attr(miri, ignore)] // unsupported operation: returning ready events from epoll_wait is not yet implemented
1638    async fn snapshot_and_stream(dyncfgs: ConfigUpdates) {
1639        let data = &mut [
1640            (("k1".to_owned(), "v1".to_owned()), 0, 1),
1641            (("k2".to_owned(), "v2".to_owned()), 1, 1),
1642            (("k3".to_owned(), "v3".to_owned()), 2, 1),
1643            (("k4".to_owned(), "v4".to_owned()), 2, 1),
1644            (("k5".to_owned(), "v5".to_owned()), 3, 1),
1645        ];
1646
1647        let (mut write, mut read) = {
1648            let client = new_test_client(&dyncfgs).await;
1649            client.cfg.set_config(&BLOB_TARGET_SIZE, 0); // split batches across multiple parts
1650            client
1651                .expect_open::<String, String, u64, i64>(crate::ShardId::new())
1652                .await
1653        };
1654
1655        write.expect_compare_and_append(&data[0..2], 0, 2).await;
1656        write.expect_compare_and_append(&data[2..4], 2, 3).await;
1657        write.expect_compare_and_append(&data[4..], 3, 4).await;
1658
1659        let as_of = Antichain::from_elem(3);
1660        let mut snapshot = pin::pin!(read.snapshot_and_stream(as_of.clone()).await.unwrap());
1661
1662        let mut snapshot_rows = vec![];
1663        while let Some(((k, v), t, d)) = snapshot.next().await {
1664            snapshot_rows.push(((k, v), t, d));
1665        }
1666
1667        for ((_k, _v), t, _d) in data.as_mut_slice() {
1668            t.advance_by(as_of.borrow());
1669        }
1670
1671        assert_eq!(data.as_slice(), snapshot_rows.as_slice());
1672    }
1673
1674    // Verifies the semantics of `SeqNo` leases + checks dropping `LeasedBatchPart` semantics.
1675    #[mz_persist_proc::test(tokio::test)]
1676    #[cfg_attr(miri, ignore)] // https://github.com/MaterializeInc/database-issues/issues/5964
1677    async fn seqno_leases(dyncfgs: ConfigUpdates) {
1678        let mut data = vec![];
1679        for i in 0..20 {
1680            data.push(((i.to_string(), i.to_string()), i, 1))
1681        }
1682
1683        let shard_id = ShardId::new();
1684
1685        let client = new_test_client(&dyncfgs).await;
1686        let (mut write, read) = client
1687            .expect_open::<String, String, u64, i64>(shard_id)
1688            .await;
1689
1690        // Seed with some values
1691        let mut offset = 0;
1692        let mut width = 2;
1693
1694        for i in offset..offset + width {
1695            write
1696                .expect_compare_and_append(
1697                    &data[i..i + 1],
1698                    u64::cast_from(i),
1699                    u64::cast_from(i) + 1,
1700                )
1701                .await;
1702        }
1703        offset += width;
1704
1705        // Create machinery for subscribe + fetch
1706        let mut fetcher = client
1707            .create_batch_fetcher::<String, String, u64, i64>(
1708                shard_id,
1709                Default::default(),
1710                Default::default(),
1711                false,
1712                Diagnostics::for_tests(),
1713            )
1714            .await
1715            .unwrap();
1716
1717        let mut subscribe = read
1718            .subscribe(timely::progress::Antichain::from_elem(1))
1719            .await
1720            .expect("cannot serve requested as_of");
1721
1722        // Determine the sequence number held by our subscribe.
1723        let original_seqno_since = subscribe.listen.handle.outstanding_seqno();
1724        if let Some(snapshot) = &subscribe.snapshot {
1725            for part in snapshot {
1726                assert!(
1727                    part.lease.seqno() >= original_seqno_since,
1728                    "our seqno hold must cover all parts"
1729                );
1730            }
1731        }
1732
1733        let mut parts = vec![];
1734
1735        width = 4;
1736        // Collect parts while continuing to write values
1737        for i in offset..offset + width {
1738            for event in subscribe.next(None).await {
1739                if let ListenEvent::Updates(mut new_parts) = event {
1740                    parts.append(&mut new_parts);
1741                    // Here and elsewhere we "cheat" and immediately downgrade the since
1742                    // to demonstrate the effects of SeqNo leases immediately.
1743                    subscribe
1744                        .listen
1745                        .handle
1746                        .downgrade_since(&subscribe.listen.since)
1747                        .await;
1748                }
1749            }
1750
1751            write
1752                .expect_compare_and_append(
1753                    &data[i..i + 1],
1754                    u64::cast_from(i),
1755                    u64::cast_from(i) + 1,
1756                )
1757                .await;
1758
1759            // SeqNo is not downgraded
1760            assert_eq!(
1761                subscribe.listen.handle.machine.applier.seqno_since(),
1762                original_seqno_since
1763            );
1764        }
1765
1766        offset += width;
1767
1768        let mut seqno_since = subscribe.listen.handle.machine.applier.seqno_since();
1769
1770        // We're starting out with the original, non-downgraded SeqNo
1771        assert_eq!(seqno_since, original_seqno_since);
1772
1773        // We have to handle the parts we generate during the next loop to
1774        // ensure they don't panic.
1775        let mut subsequent_parts = vec![];
1776
1777        // Ensure monotonicity of seqnos we're processing, otherwise the
1778        // invariant we're testing (returning the last part of a seqno will
1779        // downgrade its since) will not hold.
1780        let mut this_seqno = SeqNo::minimum();
1781
1782        // Repeat the same process as above, more or less, while fetching + returning parts
1783        for (mut i, part) in parts.into_iter().enumerate() {
1784            let part_seqno = part.lease.seqno();
1785            let last_seqno = this_seqno;
1786            this_seqno = part_seqno;
1787            assert!(this_seqno >= last_seqno);
1788
1789            let (part, lease) = part.into_exchangeable_part();
1790            let _ = fetcher.fetch_leased_part(part).await;
1791            drop(lease);
1792
1793            // Simulates an exchange
1794            for event in subscribe.next(None).await {
1795                if let ListenEvent::Updates(parts) = event {
1796                    for part in parts {
1797                        let (_, lease) = part.into_exchangeable_part();
1798                        subsequent_parts.push(lease);
1799                    }
1800                }
1801            }
1802
1803            subscribe
1804                .listen
1805                .handle
1806                .downgrade_since(&subscribe.listen.since)
1807                .await;
1808
1809            // Write more new values
1810            i += offset;
1811            write
1812                .expect_compare_and_append(
1813                    &data[i..i + 1],
1814                    u64::cast_from(i),
1815                    u64::cast_from(i) + 1,
1816                )
1817                .await;
1818
1819            // We should expect the SeqNo to be downgraded if this part's SeqNo
1820            // is no longer leased to any other parts, either.
1821            let expect_downgrade = subscribe.listen.handle.outstanding_seqno() > part_seqno;
1822
1823            let new_seqno_since = subscribe.listen.handle.machine.applier.seqno_since();
1824            if expect_downgrade {
1825                assert!(new_seqno_since > seqno_since);
1826            } else {
1827                assert_eq!(new_seqno_since, seqno_since);
1828            }
1829            seqno_since = new_seqno_since;
1830        }
1831
1832        // SeqNo since was downgraded
1833        assert!(seqno_since > original_seqno_since);
1834
1835        // Return any outstanding parts, to prevent a panic!
1836        drop(subsequent_parts);
1837        drop(subscribe);
1838    }
1839
1840    #[mz_ore::test]
1841    fn reader_id_human_readable_serde() {
1842        #[derive(Debug, Serialize, Deserialize)]
1843        struct Container {
1844            reader_id: LeasedReaderId,
1845        }
1846
1847        // roundtrip through json
1848        let id =
1849            LeasedReaderId::from_str("r00000000-1234-5678-0000-000000000000").expect("valid id");
1850        assert_eq!(
1851            id,
1852            serde_json::from_value(serde_json::to_value(id.clone()).expect("serializable"))
1853                .expect("deserializable")
1854        );
1855
1856        // deserialize a serialized string directly
1857        assert_eq!(
1858            id,
1859            serde_json::from_str("\"r00000000-1234-5678-0000-000000000000\"")
1860                .expect("deserializable")
1861        );
1862
1863        // roundtrip id through a container type
1864        let json = json!({ "reader_id": id });
1865        assert_eq!(
1866            "{\"reader_id\":\"r00000000-1234-5678-0000-000000000000\"}",
1867            &json.to_string()
1868        );
1869        let container: Container = serde_json::from_value(json).expect("deserializable");
1870        assert_eq!(container.reader_id, id);
1871    }
1872
1873    // Verifies performance optimizations where a Listener doesn't fetch the
1874    // latest Consensus state if the one it currently has can serve the next
1875    // request.
1876    #[mz_ore::test(tokio::test)]
1877    #[cfg_attr(miri, ignore)] // too slow
1878    async fn skip_consensus_fetch_optimization() {
1879        let data = vec![
1880            (("0".to_owned(), "zero".to_owned()), 0, 1),
1881            (("1".to_owned(), "one".to_owned()), 1, 1),
1882            (("2".to_owned(), "two".to_owned()), 2, 1),
1883        ];
1884
1885        let cfg = PersistConfig::new_for_tests();
1886        let blob = Arc::new(MemBlob::open(MemBlobConfig::default()));
1887        let consensus = Arc::new(MemConsensus::default());
1888        let unreliable = UnreliableHandle::default();
1889        unreliable.totally_available();
1890        let consensus = Arc::new(UnreliableConsensus::new(consensus, unreliable.clone()));
1891        let metrics = Arc::new(Metrics::new(&cfg, &MetricsRegistry::new()));
1892        let pubsub_sender = Arc::new(NoopPubSubSender);
1893        let (mut write, mut read) = PersistClient::new(
1894            cfg,
1895            blob,
1896            consensus,
1897            metrics,
1898            Arc::new(IsolatedRuntime::new_for_tests()),
1899            Arc::new(StateCache::new_no_metrics()),
1900            pubsub_sender,
1901        )
1902        .expect("client construction failed")
1903        .expect_open::<String, String, u64, i64>(ShardId::new())
1904        .await;
1905
1906        write.expect_compare_and_append(&data[0..1], 0, 1).await;
1907        write.expect_compare_and_append(&data[1..2], 1, 2).await;
1908        write.expect_compare_and_append(&data[2..3], 2, 3).await;
1909
1910        let snapshot = read.expect_snapshot_and_fetch(2).await;
1911        let mut listen = read.expect_listen(0).await;
1912
1913        // Manually advance the listener's machine so that it has the latest
1914        // state by fetching the first events from next. This is awkward but
1915        // only necessary because we're about to do some weird things with
1916        // unreliable.
1917        let listen_actual = listen.fetch_next().await;
1918        let expected_events = vec![ListenEvent::Progress(Antichain::from_elem(1))];
1919        assert_eq!(listen_actual, expected_events);
1920
1921        // At this point, the snapshot and listen's state should have all the
1922        // writes. Test this by making consensus completely unavailable.
1923        unreliable.totally_unavailable();
1924        assert_eq!(snapshot, all_ok(&data, 2));
1925        assert_eq!(
1926            listen.read_until(&3).await,
1927            (all_ok(&data[1..], 1), Antichain::from_elem(3))
1928        );
1929    }
1930}