mz_persist_client/
lib.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//! An abstraction presenting as a durable time-varying collection (aka shard)
11
12#![warn(missing_docs, missing_debug_implementations)]
13// #[track_caller] is currently a no-op on async functions, but that hopefully won't be the case
14// forever. So we already annotate those functions now and ignore the compiler warning until
15// https://github.com/rust-lang/rust/issues/87417 pans out.
16#![allow(ungated_async_fn_track_caller)]
17
18use std::fmt::Debug;
19use std::marker::PhantomData;
20use std::sync::Arc;
21
22use differential_dataflow::difference::Monoid;
23use differential_dataflow::lattice::Lattice;
24use itertools::Itertools;
25use mz_build_info::{BuildInfo, build_info};
26use mz_dyncfg::ConfigSet;
27use mz_ore::instrument;
28use mz_persist::location::{Blob, Consensus, ExternalError};
29use mz_persist_types::schema::SchemaId;
30use mz_persist_types::{Codec, Codec64, Opaque};
31use mz_proto::{IntoRustIfSome, ProtoType};
32use semver::Version;
33use timely::order::TotalOrder;
34use timely::progress::{Antichain, Timestamp};
35
36use crate::async_runtime::IsolatedRuntime;
37use crate::batch::{BATCH_DELETE_ENABLED, Batch, BatchBuilder, ProtoBatch};
38use crate::cache::{PersistClientCache, StateCache};
39use crate::cfg::PersistConfig;
40use crate::critical::{CriticalReaderId, SinceHandle};
41use crate::error::InvalidUsage;
42use crate::fetch::{BatchFetcher, BatchFetcherConfig};
43use crate::internal::compact::{CompactConfig, Compactor};
44use crate::internal::encoding::parse_id;
45use crate::internal::gc::GarbageCollector;
46use crate::internal::machine::{Machine, retry_external};
47use crate::internal::state_versions::StateVersions;
48use crate::metrics::Metrics;
49use crate::read::{
50    Cursor, LazyPartStats, LeasedReaderId, READER_LEASE_DURATION, ReadHandle, Since,
51};
52use crate::rpc::PubSubSender;
53use crate::schema::CaESchema;
54use crate::write::{WriteHandle, WriterId};
55
56pub mod async_runtime;
57pub mod batch;
58pub mod cache;
59pub mod cfg;
60pub mod cli {
61    //! Persist command-line utilities
62    pub mod admin;
63    pub mod args;
64    pub mod bench;
65    pub mod inspect;
66}
67pub mod critical;
68pub mod error;
69pub mod fetch;
70pub mod internals_bench;
71pub mod iter;
72pub mod metrics {
73    //! Utilities related to metrics.
74    pub use crate::internal::metrics::{
75        Metrics, SinkMetrics, SinkWorkerMetrics, UpdateDelta, encode_ts_metric,
76    };
77}
78pub mod operators {
79    //! [timely] operators for reading and writing persist Shards.
80
81    use mz_dyncfg::Config;
82
83    pub mod shard_source;
84
85    // TODO(cfg): Move this next to the use.
86    pub(crate) const STORAGE_SOURCE_DECODE_FUEL: Config<usize> = Config::new(
87        "storage_source_decode_fuel",
88        100_000,
89        "\
90        The maximum amount of work to do in the persist_source mfp_and_decode \
91        operator before yielding.",
92    );
93}
94pub mod read;
95pub mod rpc;
96pub mod schema;
97pub mod stats;
98pub mod usage;
99pub mod write;
100
101/// An implementation of the public crate interface.
102mod internal {
103    pub mod apply;
104    pub mod cache;
105    pub mod compact;
106    pub mod encoding;
107    pub mod gc;
108    pub mod machine;
109    pub mod maintenance;
110    pub mod merge;
111    pub mod metrics;
112    pub mod paths;
113    pub mod restore;
114    pub mod service;
115    pub mod state;
116    pub mod state_diff;
117    pub mod state_versions;
118    pub mod trace;
119    pub mod watch;
120
121    #[cfg(test)]
122    pub mod datadriven;
123}
124
125/// Persist build information.
126pub const BUILD_INFO: BuildInfo = build_info!();
127
128// Re-export for convenience.
129pub use mz_persist_types::{PersistLocation, ShardId};
130
131pub use crate::internal::encoding::Schemas;
132
133/// Additional diagnostic information used within Persist
134/// e.g. for logging, metric labels, etc.
135#[derive(Clone, Debug)]
136pub struct Diagnostics {
137    /// A user-friendly name for the shard.
138    pub shard_name: String,
139    /// A purpose for the handle.
140    pub handle_purpose: String,
141}
142
143impl Diagnostics {
144    /// Create a new `Diagnostics` from `handle_purpose`.
145    pub fn from_purpose(handle_purpose: &str) -> Self {
146        Self {
147            shard_name: "unknown".to_string(),
148            handle_purpose: handle_purpose.to_string(),
149        }
150    }
151
152    /// Create a new `Diagnostics` for testing.
153    pub fn for_tests() -> Self {
154        Self {
155            shard_name: "test-shard-name".to_string(),
156            handle_purpose: "test-purpose".to_string(),
157        }
158    }
159}
160
161/// A handle for interacting with the set of persist shard made durable at a
162/// single [PersistLocation].
163///
164/// All async methods on PersistClient retry for as long as they are able, but
165/// the returned [std::future::Future]s implement "cancel on drop" semantics.
166/// This means that callers can add a timeout using [tokio::time::timeout] or
167/// [tokio::time::timeout_at].
168///
169/// ```rust,no_run
170/// # use std::sync::Arc;
171/// # use mz_persist_types::codec_impls::StringSchema;
172/// # let client: mz_persist_client::PersistClient = unimplemented!();
173/// # let timeout: std::time::Duration = unimplemented!();
174/// # let id = mz_persist_client::ShardId::new();
175/// # let diagnostics = mz_persist_client::Diagnostics { shard_name: "".into(), handle_purpose: "".into() };
176/// # async {
177/// tokio::time::timeout(timeout, client.open::<String, String, u64, i64>(id,
178///     Arc::new(StringSchema),Arc::new(StringSchema),diagnostics, true)).await
179/// # };
180/// ```
181#[derive(Debug, Clone)]
182pub struct PersistClient {
183    cfg: PersistConfig,
184    blob: Arc<dyn Blob>,
185    consensus: Arc<dyn Consensus>,
186    metrics: Arc<Metrics>,
187    isolated_runtime: Arc<IsolatedRuntime>,
188    shared_states: Arc<StateCache>,
189    pubsub_sender: Arc<dyn PubSubSender>,
190}
191
192impl PersistClient {
193    /// Returns a new client for interfacing with persist shards made durable to
194    /// the given [Blob] and [Consensus].
195    ///
196    /// This is exposed mostly for testing. Persist users likely want
197    /// [crate::cache::PersistClientCache::open].
198    pub fn new(
199        cfg: PersistConfig,
200        blob: Arc<dyn Blob>,
201        consensus: Arc<dyn Consensus>,
202        metrics: Arc<Metrics>,
203        isolated_runtime: Arc<IsolatedRuntime>,
204        shared_states: Arc<StateCache>,
205        pubsub_sender: Arc<dyn PubSubSender>,
206    ) -> Result<Self, ExternalError> {
207        // TODO: Verify somehow that blob matches consensus to prevent
208        // accidental misuse.
209        Ok(PersistClient {
210            cfg,
211            blob,
212            consensus,
213            metrics,
214            isolated_runtime,
215            shared_states,
216            pubsub_sender,
217        })
218    }
219
220    /// Returns a new in-mem [PersistClient] for tests and examples.
221    pub async fn new_for_tests() -> Self {
222        let cache = PersistClientCache::new_no_metrics();
223        cache
224            .open(PersistLocation::new_in_mem())
225            .await
226            .expect("in-mem location is valid")
227    }
228
229    /// Returns persist's [ConfigSet].
230    pub fn dyncfgs(&self) -> &ConfigSet {
231        &self.cfg.configs
232    }
233
234    async fn make_machine<K, V, T, D>(
235        &self,
236        shard_id: ShardId,
237        diagnostics: Diagnostics,
238    ) -> Result<Machine<K, V, T, D>, InvalidUsage<T>>
239    where
240        K: Debug + Codec,
241        V: Debug + Codec,
242        T: Timestamp + Lattice + Codec64 + Sync,
243        D: Monoid + Codec64 + Send + Sync,
244    {
245        let state_versions = StateVersions::new(
246            self.cfg.clone(),
247            Arc::clone(&self.consensus),
248            Arc::clone(&self.blob),
249            Arc::clone(&self.metrics),
250        );
251        let machine = Machine::<K, V, T, D>::new(
252            self.cfg.clone(),
253            shard_id,
254            Arc::clone(&self.metrics),
255            Arc::new(state_versions),
256            Arc::clone(&self.shared_states),
257            Arc::clone(&self.pubsub_sender),
258            Arc::clone(&self.isolated_runtime),
259            diagnostics.clone(),
260        )
261        .await?;
262        Ok(machine)
263    }
264
265    /// Provides capabilities for the durable TVC identified by `shard_id` at
266    /// its current since and upper frontiers.
267    ///
268    /// This method is a best-effort attempt to regain control of the frontiers
269    /// of a shard. Its most common uses are to recover capabilities that have
270    /// expired (leases) or to attempt to read a TVC that one did not create (or
271    /// otherwise receive capabilities for). If the frontiers have been fully
272    /// released by all other parties, this call may result in capabilities with
273    /// empty frontiers (which are useless).
274    ///
275    /// If `shard_id` has never been used before, initializes a new shard and
276    /// returns handles with `since` and `upper` frontiers set to initial values
277    /// of `Antichain::from_elem(T::minimum())`.
278    ///
279    /// The `schema` parameter is currently unused, but should be an object
280    /// that represents the schema of the data in the shard. This will be required
281    /// in the future.
282    #[instrument(level = "debug", fields(shard = %shard_id))]
283    pub async fn open<K, V, T, D>(
284        &self,
285        shard_id: ShardId,
286        key_schema: Arc<K::Schema>,
287        val_schema: Arc<V::Schema>,
288        diagnostics: Diagnostics,
289        use_critical_since: bool,
290    ) -> Result<(WriteHandle<K, V, T, D>, ReadHandle<K, V, T, D>), InvalidUsage<T>>
291    where
292        K: Debug + Codec,
293        V: Debug + Codec,
294        T: Timestamp + TotalOrder + Lattice + Codec64 + Sync,
295        D: Monoid + Ord + Codec64 + Send + Sync,
296    {
297        Ok((
298            self.open_writer(
299                shard_id,
300                Arc::clone(&key_schema),
301                Arc::clone(&val_schema),
302                diagnostics.clone(),
303            )
304            .await?,
305            self.open_leased_reader(
306                shard_id,
307                key_schema,
308                val_schema,
309                diagnostics,
310                use_critical_since,
311            )
312            .await?,
313        ))
314    }
315
316    /// [Self::open], but returning only a [ReadHandle].
317    ///
318    /// Use this to save latency and a bit of persist traffic if you're just
319    /// going to immediately drop or expire the [WriteHandle].
320    ///
321    /// The `_schema` parameter is currently unused, but should be an object
322    /// that represents the schema of the data in the shard. This will be required
323    /// in the future.
324    #[instrument(level = "debug", fields(shard = %shard_id))]
325    pub async fn open_leased_reader<K, V, T, D>(
326        &self,
327        shard_id: ShardId,
328        key_schema: Arc<K::Schema>,
329        val_schema: Arc<V::Schema>,
330        diagnostics: Diagnostics,
331        use_critical_since: bool,
332    ) -> Result<ReadHandle<K, V, T, D>, InvalidUsage<T>>
333    where
334        K: Debug + Codec,
335        V: Debug + Codec,
336        T: Timestamp + TotalOrder + Lattice + Codec64 + Sync,
337        D: Monoid + Codec64 + Send + Sync,
338    {
339        let machine = self.make_machine(shard_id, diagnostics.clone()).await?;
340        let gc = GarbageCollector::new(machine.clone(), Arc::clone(&self.isolated_runtime));
341
342        let reader_id = LeasedReaderId::new();
343        let heartbeat_ts = (self.cfg.now)();
344        let (reader_state, maintenance) = machine
345            .register_leased_reader(
346                &reader_id,
347                &diagnostics.handle_purpose,
348                READER_LEASE_DURATION.get(&self.cfg),
349                heartbeat_ts,
350                use_critical_since,
351            )
352            .await;
353        maintenance.start_performing(&machine, &gc);
354        let schemas = Schemas {
355            id: None,
356            key: key_schema,
357            val: val_schema,
358        };
359        let reader = ReadHandle::new(
360            self.cfg.clone(),
361            Arc::clone(&self.metrics),
362            machine,
363            gc,
364            Arc::clone(&self.blob),
365            reader_id,
366            schemas,
367            reader_state.since,
368            heartbeat_ts,
369        )
370        .await;
371
372        Ok(reader)
373    }
374
375    /// Creates and returns a [BatchFetcher] for the given shard id.
376    #[instrument(level = "debug", fields(shard = %shard_id))]
377    pub async fn create_batch_fetcher<K, V, T, D>(
378        &self,
379        shard_id: ShardId,
380        key_schema: Arc<K::Schema>,
381        val_schema: Arc<V::Schema>,
382        is_transient: bool,
383        diagnostics: Diagnostics,
384    ) -> Result<BatchFetcher<K, V, T, D>, InvalidUsage<T>>
385    where
386        K: Debug + Codec,
387        V: Debug + Codec,
388        T: Timestamp + Lattice + Codec64 + Sync,
389        D: Monoid + Codec64 + Send + Sync,
390    {
391        let machine = self.make_machine(shard_id, diagnostics.clone()).await?;
392        let read_schemas = Schemas {
393            id: None,
394            key: key_schema,
395            val: val_schema,
396        };
397        let schema_cache = machine.applier.schema_cache();
398        let fetcher = BatchFetcher {
399            cfg: BatchFetcherConfig::new(&self.cfg),
400            blob: Arc::clone(&self.blob),
401            metrics: Arc::clone(&self.metrics),
402            shard_metrics: Arc::clone(&machine.applier.shard_metrics),
403            shard_id,
404            read_schemas,
405            schema_cache,
406            is_transient,
407            _phantom: PhantomData,
408        };
409
410        Ok(fetcher)
411    }
412
413    /// A convenience [CriticalReaderId] for Materialize controllers.
414    ///
415    /// For most (soon to be all?) shards in Materialize, a centralized
416    /// "controller" is the authority for when a user no longer needs to read at
417    /// a given frontier. (Other uses are temporary holds where correctness of
418    /// the overall system can be maintained through a lease timeout.) To make
419    /// [SinceHandle] easier to work with, we offer this convenience id for
420    /// Materialize controllers, so they don't have to durably record it.
421    ///
422    /// TODO: We're still shaking out whether the controller should be the only
423    /// critical since hold or if there are other places we want them. If the
424    /// former, we should remove [CriticalReaderId] and bake in the singular
425    /// nature of the controller critical handle.
426    ///
427    /// ```rust
428    /// // This prints as something that is not 0 but is visually recognizable.
429    /// assert_eq!(
430    ///     mz_persist_client::PersistClient::CONTROLLER_CRITICAL_SINCE.to_string(),
431    ///     "c00000000-1111-2222-3333-444444444444",
432    /// )
433    /// ```
434    pub const CONTROLLER_CRITICAL_SINCE: CriticalReaderId =
435        CriticalReaderId([0, 0, 0, 0, 17, 17, 34, 34, 51, 51, 68, 68, 68, 68, 68, 68]);
436
437    /// Provides a capability for the durable TVC identified by `shard_id` at
438    /// its current since frontier.
439    ///
440    /// In contrast to the time-leased [ReadHandle] returned by [Self::open] and
441    /// [Self::open_leased_reader], this handle and its associated capability
442    /// are not leased. A [SinceHandle] does not release its since capability;
443    /// downgrade to the empty antichain to hold back the since.
444    /// Also unlike `ReadHandle`, the handle is not expired on drop.
445    /// This is less ergonomic, but useful for "critical" since
446    /// holds which must survive even lease timeouts.
447    ///
448    /// **IMPORTANT**: The above means that if a SinceHandle is registered and
449    /// then lost, the shard's since will be permanently "stuck", forever
450    /// preventing logical compaction. Users are advised to durably record
451    /// (preferably in code) the intended [CriticalReaderId] _before_ registering
452    /// a SinceHandle (in case the process crashes at the wrong time).
453    ///
454    /// If `shard_id` has never been used before, initializes a new shard and
455    /// return a handle with its `since` frontier set to the initial value of
456    /// `Antichain::from_elem(T::minimum())`.
457    #[instrument(level = "debug", fields(shard = %shard_id))]
458    pub async fn open_critical_since<K, V, T, D, O>(
459        &self,
460        shard_id: ShardId,
461        reader_id: CriticalReaderId,
462        diagnostics: Diagnostics,
463    ) -> Result<SinceHandle<K, V, T, D, O>, InvalidUsage<T>>
464    where
465        K: Debug + Codec,
466        V: Debug + Codec,
467        T: Timestamp + Lattice + Codec64 + Sync,
468        D: Monoid + Codec64 + Send + Sync,
469        O: Opaque + Codec64,
470    {
471        let machine = self.make_machine(shard_id, diagnostics.clone()).await?;
472        let gc = GarbageCollector::new(machine.clone(), Arc::clone(&self.isolated_runtime));
473
474        let (state, maintenance) = machine
475            .register_critical_reader::<O>(&reader_id, &diagnostics.handle_purpose)
476            .await;
477        maintenance.start_performing(&machine, &gc);
478        let handle = SinceHandle::new(
479            machine,
480            gc,
481            reader_id,
482            state.since,
483            Codec64::decode(state.opaque.0),
484        );
485
486        Ok(handle)
487    }
488
489    /// [Self::open], but returning only a [WriteHandle].
490    ///
491    /// Use this to save latency and a bit of persist traffic if you're just
492    /// going to immediately drop or expire the [ReadHandle].
493    #[instrument(level = "debug", fields(shard = %shard_id))]
494    pub async fn open_writer<K, V, T, D>(
495        &self,
496        shard_id: ShardId,
497        key_schema: Arc<K::Schema>,
498        val_schema: Arc<V::Schema>,
499        diagnostics: Diagnostics,
500    ) -> Result<WriteHandle<K, V, T, D>, InvalidUsage<T>>
501    where
502        K: Debug + Codec,
503        V: Debug + Codec,
504        T: Timestamp + TotalOrder + Lattice + Codec64 + Sync,
505        D: Monoid + Ord + Codec64 + Send + Sync,
506    {
507        let machine = self.make_machine(shard_id, diagnostics.clone()).await?;
508        let gc = GarbageCollector::new(machine.clone(), Arc::clone(&self.isolated_runtime));
509
510        // We defer registering the schema until write time, to allow opening
511        // write handles in a "read-only" mode where they don't implicitly
512        // modify persist state. But it might already be registered, in which
513        // case we can fetch its ID.
514        let schema_id = machine.find_schema(&*key_schema, &*val_schema);
515
516        let writer_id = WriterId::new();
517        let schemas = Schemas {
518            id: schema_id,
519            key: key_schema,
520            val: val_schema,
521        };
522        let writer = WriteHandle::new(
523            self.cfg.clone(),
524            Arc::clone(&self.metrics),
525            machine,
526            gc,
527            Arc::clone(&self.blob),
528            writer_id,
529            &diagnostics.handle_purpose,
530            schemas,
531        );
532        Ok(writer)
533    }
534
535    /// Returns a [BatchBuilder] that can be used to write a batch of updates to
536    /// blob storage which can then be appended to the given shard using
537    /// [WriteHandle::compare_and_append_batch] or [WriteHandle::append_batch],
538    /// or which can be read using [PersistClient::read_batches_consolidated].
539    ///
540    /// The builder uses a bounded amount of memory, even when the number of
541    /// updates is very large. Individual records, however, should be small
542    /// enough that we can reasonably chunk them up: O(KB) is definitely fine,
543    /// O(MB) come talk to us.
544    #[instrument(level = "debug", fields(shard = %shard_id))]
545    pub async fn batch_builder<K, V, T, D>(
546        &self,
547        shard_id: ShardId,
548        write_schemas: Schemas<K, V>,
549        lower: Antichain<T>,
550        max_runs: Option<usize>,
551    ) -> BatchBuilder<K, V, T, D>
552    where
553        K: Debug + Codec,
554        V: Debug + Codec,
555        T: Timestamp + Lattice + Codec64 + TotalOrder + Sync,
556        D: Monoid + Ord + Codec64 + Send + Sync,
557    {
558        let mut compact_cfg = CompactConfig::new(&self.cfg, shard_id);
559        compact_cfg.batch.max_runs = max_runs;
560        WriteHandle::builder_inner(
561            &self.cfg,
562            compact_cfg,
563            Arc::clone(&self.metrics),
564            self.metrics.shards.shard(&shard_id, "peek_stash"),
565            &self.metrics.user,
566            Arc::clone(&self.isolated_runtime),
567            Arc::clone(&self.blob),
568            shard_id,
569            write_schemas,
570            lower,
571        )
572    }
573
574    /// Turns the given [`ProtoBatch`] back into a [`Batch`] which can be used
575    /// to append it to the given shard or to read it via
576    /// [PersistClient::read_batches_consolidated]
577    ///
578    /// CAUTION: This API allows turning a [ProtoBatch] into a [Batch] multiple
579    /// times, but if a batch is deleted the backing data goes away, so at that
580    /// point all in-memory copies of a batch become invalid and cannot be read
581    /// anymore.
582    pub fn batch_from_transmittable_batch<K, V, T, D>(
583        &self,
584        shard_id: &ShardId,
585        batch: ProtoBatch,
586    ) -> Batch<K, V, T, D>
587    where
588        K: Debug + Codec,
589        V: Debug + Codec,
590        T: Timestamp + Lattice + Codec64 + Sync,
591        D: Monoid + Ord + Codec64 + Send + Sync,
592    {
593        let batch_shard_id: ShardId = batch
594            .shard_id
595            .into_rust()
596            .expect("valid transmittable batch");
597        assert_eq!(&batch_shard_id, shard_id);
598
599        let shard_metrics = self.metrics.shards.shard(shard_id, "peek_stash");
600
601        let ret = Batch {
602            batch_delete_enabled: BATCH_DELETE_ENABLED.get(&self.cfg),
603            metrics: Arc::clone(&self.metrics),
604            shard_metrics,
605            version: Version::parse(&batch.version).expect("valid transmittable batch"),
606            schemas: (batch.key_schema, batch.val_schema),
607            batch: batch
608                .batch
609                .into_rust_if_some("ProtoBatch::batch")
610                .expect("valid transmittable batch"),
611            blob: Arc::clone(&self.blob),
612            _phantom: std::marker::PhantomData,
613        };
614
615        assert_eq!(&ret.shard_id(), shard_id);
616        ret
617    }
618
619    /// Returns a [Cursor] for reading the given batches. Yielded updates are
620    /// consolidated if the given batches contain sorted runs, which is true
621    /// when they have been written using a [BatchBuilder].
622    ///
623    /// To keep memory usage down when reading a snapshot that consolidates
624    /// well, this consolidates as it goes. However, note that only the
625    /// serialized data is consolidated: the deserialized data will only be
626    /// consolidated if your K/V codecs are one-to-one.
627    ///
628    /// CAUTION: The caller needs to make sure that the given batches are
629    /// readable and they have to remain readable for the lifetime of the
630    /// returned [Cursor]. The caller is also responsible for the lifecycle of
631    /// the batches: once the cursor and the batches are no longer needed you
632    /// must call [Cursor::into_lease] to get back the batches and delete them.
633    #[allow(clippy::unused_async)]
634    pub async fn read_batches_consolidated<K, V, T, D>(
635        &mut self,
636        shard_id: ShardId,
637        as_of: Antichain<T>,
638        read_schemas: Schemas<K, V>,
639        batches: Vec<Batch<K, V, T, D>>,
640        should_fetch_part: impl for<'a> Fn(Option<&'a LazyPartStats>) -> bool,
641        memory_budget_bytes: usize,
642    ) -> Result<Cursor<K, V, T, D, Vec<Batch<K, V, T, D>>>, Since<T>>
643    where
644        K: Debug + Codec + Ord,
645        V: Debug + Codec + Ord,
646        T: Timestamp + Lattice + Codec64 + TotalOrder + Sync,
647        D: Monoid + Ord + Codec64 + Send + Sync,
648    {
649        let shard_metrics = self.metrics.shards.shard(&shard_id, "peek_stash");
650
651        let hollow_batches = batches.iter().map(|b| b.batch.clone()).collect_vec();
652
653        ReadHandle::read_batches_consolidated(
654            &self.cfg,
655            Arc::clone(&self.metrics),
656            shard_metrics,
657            self.metrics.read.snapshot.clone(),
658            Arc::clone(&self.blob),
659            shard_id,
660            as_of,
661            read_schemas,
662            &hollow_batches,
663            batches,
664            should_fetch_part,
665            memory_budget_bytes,
666        )
667    }
668
669    /// Returns the requested schema, if known at the current state.
670    pub async fn get_schema<K, V, T, D>(
671        &self,
672        shard_id: ShardId,
673        schema_id: SchemaId,
674        diagnostics: Diagnostics,
675    ) -> Result<Option<(K::Schema, V::Schema)>, InvalidUsage<T>>
676    where
677        K: Debug + Codec,
678        V: Debug + Codec,
679        T: Timestamp + Lattice + Codec64 + Sync,
680        D: Monoid + Codec64 + Send + Sync,
681    {
682        let machine = self
683            .make_machine::<K, V, T, D>(shard_id, diagnostics)
684            .await?;
685        Ok(machine.get_schema(schema_id))
686    }
687
688    /// Returns the latest schema registered at the current state.
689    pub async fn latest_schema<K, V, T, D>(
690        &self,
691        shard_id: ShardId,
692        diagnostics: Diagnostics,
693    ) -> Result<Option<(SchemaId, K::Schema, V::Schema)>, InvalidUsage<T>>
694    where
695        K: Debug + Codec,
696        V: Debug + Codec,
697        T: Timestamp + Lattice + Codec64 + Sync,
698        D: Monoid + Codec64 + Send + Sync,
699    {
700        let machine = self
701            .make_machine::<K, V, T, D>(shard_id, diagnostics)
702            .await?;
703        Ok(machine.latest_schema())
704    }
705
706    /// Registers a schema for the given shard.
707    ///
708    /// Returns the new schema ID if the registration succeeds, and `None`
709    /// otherwise. Schema registration succeeds in two cases:
710    ///  a) No schema was currently registered for the shard.
711    ///  b) The given schema is already registered for the shard.
712    ///
713    /// To evolve an existing schema instead, use
714    /// [PersistClient::compare_and_evolve_schema].
715    //
716    // TODO: unify with `compare_and_evolve_schema`
717    pub async fn register_schema<K, V, T, D>(
718        &self,
719        shard_id: ShardId,
720        key_schema: &K::Schema,
721        val_schema: &V::Schema,
722        diagnostics: Diagnostics,
723    ) -> Result<Option<SchemaId>, InvalidUsage<T>>
724    where
725        K: Debug + Codec,
726        V: Debug + Codec,
727        T: Timestamp + Lattice + Codec64 + Sync,
728        D: Monoid + Codec64 + Send + Sync,
729    {
730        let machine = self
731            .make_machine::<K, V, T, D>(shard_id, diagnostics)
732            .await?;
733        let gc = GarbageCollector::new(machine.clone(), Arc::clone(&self.isolated_runtime));
734
735        let (schema_id, maintenance) = machine.register_schema(key_schema, val_schema).await;
736        maintenance.start_performing(&machine, &gc);
737
738        Ok(schema_id)
739    }
740
741    /// Registers a new latest schema for the given shard.
742    ///
743    /// This new schema must be [backward_compatible] with all previous schemas
744    /// for this shard. If it's not, [CaESchema::Incompatible] is returned.
745    ///
746    /// [backward_compatible]: mz_persist_types::schema::backward_compatible
747    ///
748    /// To prevent races, the caller must declare what it believes to be the
749    /// latest schema id. If this doesn't match reality,
750    /// [CaESchema::ExpectedMismatch] is returned.
751    pub async fn compare_and_evolve_schema<K, V, T, D>(
752        &self,
753        shard_id: ShardId,
754        expected: SchemaId,
755        key_schema: &K::Schema,
756        val_schema: &V::Schema,
757        diagnostics: Diagnostics,
758    ) -> Result<CaESchema<K, V>, InvalidUsage<T>>
759    where
760        K: Debug + Codec,
761        V: Debug + Codec,
762        T: Timestamp + Lattice + Codec64 + Sync,
763        D: Monoid + Codec64 + Send + Sync,
764    {
765        let machine = self
766            .make_machine::<K, V, T, D>(shard_id, diagnostics)
767            .await?;
768        let gc = GarbageCollector::new(machine.clone(), Arc::clone(&self.isolated_runtime));
769        let (res, maintenance) = machine
770            .compare_and_evolve_schema(expected, key_schema, val_schema)
771            .await;
772        maintenance.start_performing(&machine, &gc);
773        Ok(res)
774    }
775
776    /// Check if the given shard is in a finalized state; ie. it can no longer be
777    /// read, any data that was written to it is no longer accessible, and we've
778    /// discarded references to that data from state.
779    pub async fn is_finalized<K, V, T, D>(
780        &self,
781        shard_id: ShardId,
782        diagnostics: Diagnostics,
783    ) -> Result<bool, InvalidUsage<T>>
784    where
785        K: Debug + Codec,
786        V: Debug + Codec,
787        T: Timestamp + Lattice + Codec64 + Sync,
788        D: Monoid + Codec64 + Send + Sync,
789    {
790        let machine = self
791            .make_machine::<K, V, T, D>(shard_id, diagnostics)
792            .await?;
793        Ok(machine.is_finalized())
794    }
795
796    /// If a shard is guaranteed to never be used again, finalize it to delete
797    /// the associated data and release any associated resources. (Except for a
798    /// little state in consensus we use to represent the tombstone.)
799    ///
800    /// The caller should ensure that both the `since` and `upper` of the shard
801    /// have been advanced to `[]`: ie. the shard is no longer writable or readable.
802    /// Otherwise an error is returned.
803    ///
804    /// Once `finalize_shard` has been called, the result of future operations on
805    /// the shard are not defined. They may return errors or succeed as a noop.
806    #[instrument(level = "debug", fields(shard = %shard_id))]
807    pub async fn finalize_shard<K, V, T, D>(
808        &self,
809        shard_id: ShardId,
810        diagnostics: Diagnostics,
811    ) -> Result<(), InvalidUsage<T>>
812    where
813        K: Debug + Codec,
814        V: Debug + Codec,
815        T: Timestamp + Lattice + Codec64 + Sync,
816        D: Monoid + Codec64 + Send + Sync,
817    {
818        let machine = self
819            .make_machine::<K, V, T, D>(shard_id, diagnostics)
820            .await?;
821
822        let maintenance = machine.become_tombstone().await?;
823        let gc = GarbageCollector::new(machine.clone(), Arc::clone(&self.isolated_runtime));
824
825        let () = maintenance.perform(&machine, &gc).await;
826
827        Ok(())
828    }
829
830    /// Upgrade the state to the latest version. This should only be called once we will no longer
831    /// need to interoperate with older versions, like after a successful upgrade.
832    pub async fn upgrade_version<K, V, T, D>(
833        &self,
834        shard_id: ShardId,
835        diagnostics: Diagnostics,
836    ) -> Result<(), InvalidUsage<T>>
837    where
838        K: Debug + Codec,
839        V: Debug + Codec,
840        T: Timestamp + Lattice + Codec64 + Sync,
841        D: Monoid + Codec64 + Send + Sync,
842    {
843        let machine = self
844            .make_machine::<K, V, T, D>(shard_id, diagnostics)
845            .await?;
846
847        match machine.upgrade_version().await {
848            Ok(maintenance) => {
849                let gc = GarbageCollector::new(machine.clone(), Arc::clone(&self.isolated_runtime));
850                let () = maintenance.perform(&machine, &gc).await;
851                Ok(())
852            }
853            Err(version) => Err(InvalidUsage::IncompatibleVersion { version }),
854        }
855    }
856
857    /// Returns the internal state of the shard for debugging and QA.
858    ///
859    /// We'll be thoughtful about making unnecessary changes, but the **output
860    /// of this method needs to be gated from users**, so that it's not subject
861    /// to our backward compatibility guarantees.
862    pub async fn inspect_shard<T: Timestamp + Lattice + Codec64>(
863        &self,
864        shard_id: &ShardId,
865    ) -> Result<impl serde::Serialize, anyhow::Error> {
866        let state_versions = StateVersions::new(
867            self.cfg.clone(),
868            Arc::clone(&self.consensus),
869            Arc::clone(&self.blob),
870            Arc::clone(&self.metrics),
871        );
872        // TODO: Don't fetch all live diffs. Feels like we should pull out a new
873        // method in StateVersions for fetching the latest version of State of a
874        // shard that might or might not exist.
875        let versions = state_versions.fetch_all_live_diffs(shard_id).await;
876        if versions.is_empty() {
877            return Err(anyhow::anyhow!("{} does not exist", shard_id));
878        }
879        let state = state_versions
880            .fetch_current_state::<T>(shard_id, versions)
881            .await;
882        let state = state.check_ts_codec(shard_id)?;
883        Ok(state)
884    }
885
886    /// Test helper for a [Self::open] call that is expected to succeed.
887    #[cfg(test)]
888    #[track_caller]
889    pub async fn expect_open<K, V, T, D>(
890        &self,
891        shard_id: ShardId,
892    ) -> (WriteHandle<K, V, T, D>, ReadHandle<K, V, T, D>)
893    where
894        K: Debug + Codec,
895        V: Debug + Codec,
896        T: Timestamp + TotalOrder + Lattice + Codec64 + Sync,
897        D: Monoid + Ord + Codec64 + Send + Sync,
898        K::Schema: Default,
899        V::Schema: Default,
900    {
901        self.open(
902            shard_id,
903            Arc::new(K::Schema::default()),
904            Arc::new(V::Schema::default()),
905            Diagnostics::for_tests(),
906            true,
907        )
908        .await
909        .expect("codec mismatch")
910    }
911
912    /// Return the metrics being used by this client.
913    ///
914    /// Only exposed for tests, persistcli, and benchmarks.
915    pub fn metrics(&self) -> &Arc<Metrics> {
916        &self.metrics
917    }
918}
919
920#[cfg(test)]
921mod tests {
922    use std::future::Future;
923    use std::mem;
924    use std::pin::Pin;
925    use std::task::Context;
926    use std::time::Duration;
927
928    use differential_dataflow::consolidation::consolidate_updates;
929    use differential_dataflow::lattice::Lattice;
930    use futures_task::noop_waker;
931    use mz_dyncfg::ConfigUpdates;
932    use mz_ore::assert_ok;
933    use mz_persist::indexed::encoding::BlobTraceBatchPart;
934    use mz_persist::workload::DataGenerator;
935    use mz_persist_types::codec_impls::{StringSchema, VecU8Schema};
936    use mz_proto::protobuf_roundtrip;
937    use proptest::prelude::*;
938    use timely::order::PartialOrder;
939    use timely::progress::Antichain;
940
941    use crate::batch::BLOB_TARGET_SIZE;
942    use crate::cache::PersistClientCache;
943    use crate::cfg::BATCH_BUILDER_MAX_OUTSTANDING_PARTS;
944    use crate::error::{CodecConcreteType, CodecMismatch, UpperMismatch};
945    use crate::internal::paths::BlobKey;
946    use crate::read::ListenEvent;
947
948    use super::*;
949
950    pub fn new_test_client_cache(dyncfgs: &ConfigUpdates) -> PersistClientCache {
951        // Configure an aggressively small blob_target_size so we get some
952        // amount of coverage of that in tests. Similarly, for max_outstanding.
953        let mut cache = PersistClientCache::new_no_metrics();
954        cache.cfg.set_config(&BLOB_TARGET_SIZE, 10);
955        cache
956            .cfg
957            .set_config(&BATCH_BUILDER_MAX_OUTSTANDING_PARTS, 1);
958        dyncfgs.apply(cache.cfg());
959
960        // Enable compaction in tests to ensure we get coverage.
961        cache.cfg.compaction_enabled = true;
962        cache
963    }
964
965    pub async fn new_test_client(dyncfgs: &ConfigUpdates) -> PersistClient {
966        let cache = new_test_client_cache(dyncfgs);
967        cache
968            .open(PersistLocation::new_in_mem())
969            .await
970            .expect("client construction failed")
971    }
972
973    pub fn all_ok<'a, K, V, T, D, I>(iter: I, as_of: T) -> Vec<((K, V), T, D)>
974    where
975        K: Ord + Clone + 'a,
976        V: Ord + Clone + 'a,
977        T: Timestamp + Lattice + Clone + 'a,
978        D: Monoid + Clone + 'a,
979        I: IntoIterator<Item = &'a ((K, V), T, D)>,
980    {
981        let as_of = Antichain::from_elem(as_of);
982        let mut ret = iter
983            .into_iter()
984            .map(|((k, v), t, d)| {
985                let mut t = t.clone();
986                t.advance_by(as_of.borrow());
987                ((k.clone(), v.clone()), t, d.clone())
988            })
989            .collect();
990        consolidate_updates(&mut ret);
991        ret
992    }
993
994    pub async fn expect_fetch_part<K, V, T, D>(
995        blob: &dyn Blob,
996        key: &BlobKey,
997        metrics: &Metrics,
998        read_schemas: &Schemas<K, V>,
999    ) -> (BlobTraceBatchPart<T>, Vec<((K, V), T, D)>)
1000    where
1001        K: Codec + Clone,
1002        V: Codec + Clone,
1003        T: Timestamp + Codec64,
1004        D: Codec64,
1005    {
1006        let value = blob
1007            .get(key)
1008            .await
1009            .expect("failed to fetch part")
1010            .expect("missing part");
1011        let mut part =
1012            BlobTraceBatchPart::decode(&value, &metrics.columnar).expect("failed to decode part");
1013        let structured = part
1014            .updates
1015            .into_part::<K, V>(&*read_schemas.key, &*read_schemas.val);
1016        let updates = structured
1017            .decode_iter::<K, V, T, D>(&*read_schemas.key, &*read_schemas.val)
1018            .expect("structured data")
1019            .collect();
1020        (part, updates)
1021    }
1022
1023    #[mz_persist_proc::test(tokio::test)]
1024    #[cfg_attr(miri, ignore)] // unsupported operation: returning ready events from epoll_wait is not yet implemented
1025    async fn sanity_check(dyncfgs: ConfigUpdates) {
1026        let data = [
1027            (("1".to_owned(), "one".to_owned()), 1, 1),
1028            (("2".to_owned(), "two".to_owned()), 2, 1),
1029            (("3".to_owned(), "three".to_owned()), 3, 1),
1030        ];
1031
1032        let (mut write, mut read) = new_test_client(&dyncfgs)
1033            .await
1034            .expect_open::<String, String, u64, i64>(ShardId::new())
1035            .await;
1036        assert_eq!(write.upper(), &Antichain::from_elem(u64::minimum()));
1037        assert_eq!(read.since(), &Antichain::from_elem(u64::minimum()));
1038
1039        // Write a [0,3) batch.
1040        write
1041            .expect_append(&data[..2], write.upper().clone(), vec![3])
1042            .await;
1043        assert_eq!(write.upper(), &Antichain::from_elem(3));
1044
1045        // Grab a snapshot and listener as_of 1. Snapshot should only have part of what we wrote.
1046        assert_eq!(
1047            read.expect_snapshot_and_fetch(1).await,
1048            all_ok(&data[..1], 1)
1049        );
1050
1051        let mut listen = read.clone("").await.expect_listen(1).await;
1052
1053        // Write a [3,4) batch.
1054        write
1055            .expect_append(&data[2..], write.upper().clone(), vec![4])
1056            .await;
1057        assert_eq!(write.upper(), &Antichain::from_elem(4));
1058
1059        // Listen should have part of the initial write plus the new one.
1060        assert_eq!(
1061            listen.read_until(&4).await,
1062            (all_ok(&data[1..], 1), Antichain::from_elem(4))
1063        );
1064
1065        // Downgrading the since is tracked locally (but otherwise is a no-op).
1066        read.downgrade_since(&Antichain::from_elem(2)).await;
1067        assert_eq!(read.since(), &Antichain::from_elem(2));
1068    }
1069
1070    // Sanity check that the open_reader and open_writer calls work.
1071    #[mz_persist_proc::test(tokio::test)]
1072    #[cfg_attr(miri, ignore)] // unsupported operation: returning ready events from epoll_wait is not yet implemented
1073    async fn open_reader_writer(dyncfgs: ConfigUpdates) {
1074        let data = vec![
1075            (("1".to_owned(), "one".to_owned()), 1, 1),
1076            (("2".to_owned(), "two".to_owned()), 2, 1),
1077            (("3".to_owned(), "three".to_owned()), 3, 1),
1078        ];
1079
1080        let shard_id = ShardId::new();
1081        let client = new_test_client(&dyncfgs).await;
1082        let mut write1 = client
1083            .open_writer::<String, String, u64, i64>(
1084                shard_id,
1085                Arc::new(StringSchema),
1086                Arc::new(StringSchema),
1087                Diagnostics::for_tests(),
1088            )
1089            .await
1090            .expect("codec mismatch");
1091        let mut read1 = client
1092            .open_leased_reader::<String, String, u64, i64>(
1093                shard_id,
1094                Arc::new(StringSchema),
1095                Arc::new(StringSchema),
1096                Diagnostics::for_tests(),
1097                true,
1098            )
1099            .await
1100            .expect("codec mismatch");
1101        let mut read2 = client
1102            .open_leased_reader::<String, String, u64, i64>(
1103                shard_id,
1104                Arc::new(StringSchema),
1105                Arc::new(StringSchema),
1106                Diagnostics::for_tests(),
1107                true,
1108            )
1109            .await
1110            .expect("codec mismatch");
1111        let mut write2 = client
1112            .open_writer::<String, String, u64, i64>(
1113                shard_id,
1114                Arc::new(StringSchema),
1115                Arc::new(StringSchema),
1116                Diagnostics::for_tests(),
1117            )
1118            .await
1119            .expect("codec mismatch");
1120
1121        write2.expect_compare_and_append(&data[..1], 0, 2).await;
1122        assert_eq!(
1123            read2.expect_snapshot_and_fetch(1).await,
1124            all_ok(&data[..1], 1)
1125        );
1126        write1.expect_compare_and_append(&data[1..], 2, 4).await;
1127        assert_eq!(read1.expect_snapshot_and_fetch(3).await, all_ok(&data, 3));
1128    }
1129
1130    #[mz_persist_proc::test(tokio::test)]
1131    #[cfg_attr(miri, ignore)] // too slow
1132    async fn invalid_usage(dyncfgs: ConfigUpdates) {
1133        let data = vec![
1134            (("1".to_owned(), "one".to_owned()), 1, 1),
1135            (("2".to_owned(), "two".to_owned()), 2, 1),
1136            (("3".to_owned(), "three".to_owned()), 3, 1),
1137        ];
1138
1139        let shard_id0 = "s00000000-0000-0000-0000-000000000000"
1140            .parse::<ShardId>()
1141            .expect("invalid shard id");
1142        let mut client = new_test_client(&dyncfgs).await;
1143
1144        let (mut write0, mut read0) = client
1145            .expect_open::<String, String, u64, i64>(shard_id0)
1146            .await;
1147
1148        write0.expect_compare_and_append(&data, 0, 4).await;
1149
1150        // InvalidUsage from PersistClient methods.
1151        {
1152            fn codecs(
1153                k: &str,
1154                v: &str,
1155                t: &str,
1156                d: &str,
1157            ) -> (String, String, String, String, Option<CodecConcreteType>) {
1158                (k.to_owned(), v.to_owned(), t.to_owned(), d.to_owned(), None)
1159            }
1160
1161            client.shared_states = Arc::new(StateCache::new_no_metrics());
1162            assert_eq!(
1163                client
1164                    .open::<Vec<u8>, String, u64, i64>(
1165                        shard_id0,
1166                        Arc::new(VecU8Schema),
1167                        Arc::new(StringSchema),
1168                        Diagnostics::for_tests(),
1169                        true,
1170                    )
1171                    .await
1172                    .unwrap_err(),
1173                InvalidUsage::CodecMismatch(Box::new(CodecMismatch {
1174                    requested: codecs("Vec<u8>", "String", "u64", "i64"),
1175                    actual: codecs("String", "String", "u64", "i64"),
1176                }))
1177            );
1178            assert_eq!(
1179                client
1180                    .open::<String, Vec<u8>, u64, i64>(
1181                        shard_id0,
1182                        Arc::new(StringSchema),
1183                        Arc::new(VecU8Schema),
1184                        Diagnostics::for_tests(),
1185                        true,
1186                    )
1187                    .await
1188                    .unwrap_err(),
1189                InvalidUsage::CodecMismatch(Box::new(CodecMismatch {
1190                    requested: codecs("String", "Vec<u8>", "u64", "i64"),
1191                    actual: codecs("String", "String", "u64", "i64"),
1192                }))
1193            );
1194            assert_eq!(
1195                client
1196                    .open::<String, String, i64, i64>(
1197                        shard_id0,
1198                        Arc::new(StringSchema),
1199                        Arc::new(StringSchema),
1200                        Diagnostics::for_tests(),
1201                        true,
1202                    )
1203                    .await
1204                    .unwrap_err(),
1205                InvalidUsage::CodecMismatch(Box::new(CodecMismatch {
1206                    requested: codecs("String", "String", "i64", "i64"),
1207                    actual: codecs("String", "String", "u64", "i64"),
1208                }))
1209            );
1210            assert_eq!(
1211                client
1212                    .open::<String, String, u64, u64>(
1213                        shard_id0,
1214                        Arc::new(StringSchema),
1215                        Arc::new(StringSchema),
1216                        Diagnostics::for_tests(),
1217                        true,
1218                    )
1219                    .await
1220                    .unwrap_err(),
1221                InvalidUsage::CodecMismatch(Box::new(CodecMismatch {
1222                    requested: codecs("String", "String", "u64", "u64"),
1223                    actual: codecs("String", "String", "u64", "i64"),
1224                }))
1225            );
1226
1227            // open_reader and open_writer end up using the same checks, so just
1228            // verify one type each to verify the plumbing instead of the full
1229            // set.
1230            assert_eq!(
1231                client
1232                    .open_leased_reader::<Vec<u8>, String, u64, i64>(
1233                        shard_id0,
1234                        Arc::new(VecU8Schema),
1235                        Arc::new(StringSchema),
1236                        Diagnostics::for_tests(),
1237                        true,
1238                    )
1239                    .await
1240                    .unwrap_err(),
1241                InvalidUsage::CodecMismatch(Box::new(CodecMismatch {
1242                    requested: codecs("Vec<u8>", "String", "u64", "i64"),
1243                    actual: codecs("String", "String", "u64", "i64"),
1244                }))
1245            );
1246            assert_eq!(
1247                client
1248                    .open_writer::<Vec<u8>, String, u64, i64>(
1249                        shard_id0,
1250                        Arc::new(VecU8Schema),
1251                        Arc::new(StringSchema),
1252                        Diagnostics::for_tests(),
1253                    )
1254                    .await
1255                    .unwrap_err(),
1256                InvalidUsage::CodecMismatch(Box::new(CodecMismatch {
1257                    requested: codecs("Vec<u8>", "String", "u64", "i64"),
1258                    actual: codecs("String", "String", "u64", "i64"),
1259                }))
1260            );
1261        }
1262
1263        // InvalidUsage from ReadHandle methods.
1264        {
1265            let snap = read0
1266                .snapshot(Antichain::from_elem(3))
1267                .await
1268                .expect("cannot serve requested as_of");
1269
1270            let shard_id1 = "s11111111-1111-1111-1111-111111111111"
1271                .parse::<ShardId>()
1272                .expect("invalid shard id");
1273            let mut fetcher1 = client
1274                .create_batch_fetcher::<String, String, u64, i64>(
1275                    shard_id1,
1276                    Default::default(),
1277                    Default::default(),
1278                    false,
1279                    Diagnostics::for_tests(),
1280                )
1281                .await
1282                .unwrap();
1283            for part in snap {
1284                let (part, _lease) = part.into_exchangeable_part();
1285                let res = fetcher1.fetch_leased_part(part).await;
1286                assert_eq!(
1287                    res.unwrap_err(),
1288                    InvalidUsage::BatchNotFromThisShard {
1289                        batch_shard: shard_id0,
1290                        handle_shard: shard_id1,
1291                    }
1292                );
1293            }
1294        }
1295
1296        // InvalidUsage from WriteHandle methods.
1297        {
1298            let ts3 = &data[2];
1299            assert_eq!(ts3.1, 3);
1300            let ts3 = vec![ts3.clone()];
1301
1302            // WriteHandle::append also covers append_batch,
1303            // compare_and_append_batch, compare_and_append.
1304            assert_eq!(
1305                write0
1306                    .append(&ts3, Antichain::from_elem(4), Antichain::from_elem(5))
1307                    .await
1308                    .unwrap_err(),
1309                InvalidUsage::UpdateNotBeyondLower {
1310                    ts: 3,
1311                    lower: Antichain::from_elem(4),
1312                },
1313            );
1314            assert_eq!(
1315                write0
1316                    .append(&ts3, Antichain::from_elem(2), Antichain::from_elem(3))
1317                    .await
1318                    .unwrap_err(),
1319                InvalidUsage::UpdateBeyondUpper {
1320                    ts: 3,
1321                    expected_upper: Antichain::from_elem(3),
1322                },
1323            );
1324            // NB unlike the previous tests, this one has empty updates.
1325            assert_eq!(
1326                write0
1327                    .append(&data[..0], Antichain::from_elem(3), Antichain::from_elem(2))
1328                    .await
1329                    .unwrap_err(),
1330                InvalidUsage::InvalidBounds {
1331                    lower: Antichain::from_elem(3),
1332                    upper: Antichain::from_elem(2),
1333                },
1334            );
1335
1336            // Tests for the BatchBuilder.
1337            assert_eq!(
1338                write0
1339                    .builder(Antichain::from_elem(3))
1340                    .finish(Antichain::from_elem(2))
1341                    .await
1342                    .unwrap_err(),
1343                InvalidUsage::InvalidBounds {
1344                    lower: Antichain::from_elem(3),
1345                    upper: Antichain::from_elem(2)
1346                },
1347            );
1348            let batch = write0
1349                .batch(&ts3, Antichain::from_elem(3), Antichain::from_elem(4))
1350                .await
1351                .expect("invalid usage");
1352            assert_eq!(
1353                write0
1354                    .append_batch(batch, Antichain::from_elem(4), Antichain::from_elem(5))
1355                    .await
1356                    .unwrap_err(),
1357                InvalidUsage::InvalidBatchBounds {
1358                    batch_lower: Antichain::from_elem(3),
1359                    batch_upper: Antichain::from_elem(4),
1360                    append_lower: Antichain::from_elem(4),
1361                    append_upper: Antichain::from_elem(5),
1362                },
1363            );
1364            let batch = write0
1365                .batch(&ts3, Antichain::from_elem(3), Antichain::from_elem(4))
1366                .await
1367                .expect("invalid usage");
1368            assert_eq!(
1369                write0
1370                    .append_batch(batch, Antichain::from_elem(2), Antichain::from_elem(3))
1371                    .await
1372                    .unwrap_err(),
1373                InvalidUsage::InvalidBatchBounds {
1374                    batch_lower: Antichain::from_elem(3),
1375                    batch_upper: Antichain::from_elem(4),
1376                    append_lower: Antichain::from_elem(2),
1377                    append_upper: Antichain::from_elem(3),
1378                },
1379            );
1380            let batch = write0
1381                .batch(&ts3, Antichain::from_elem(3), Antichain::from_elem(4))
1382                .await
1383                .expect("invalid usage");
1384            // NB unlike the others, this one uses matches! because it's
1385            // non-deterministic (the key)
1386            assert!(matches!(
1387                write0
1388                    .append_batch(batch, Antichain::from_elem(3), Antichain::from_elem(3))
1389                    .await
1390                    .unwrap_err(),
1391                InvalidUsage::InvalidEmptyTimeInterval { .. }
1392            ));
1393        }
1394    }
1395
1396    #[mz_persist_proc::test(tokio::test)]
1397    #[cfg_attr(miri, ignore)] // unsupported operation: returning ready events from epoll_wait is not yet implemented
1398    async fn multiple_shards(dyncfgs: ConfigUpdates) {
1399        let data1 = [
1400            (("1".to_owned(), "one".to_owned()), 1, 1),
1401            (("2".to_owned(), "two".to_owned()), 2, 1),
1402        ];
1403
1404        let data2 = [(("1".to_owned(), ()), 1, 1), (("2".to_owned(), ()), 2, 1)];
1405
1406        let client = new_test_client(&dyncfgs).await;
1407
1408        let (mut write1, mut read1) = client
1409            .expect_open::<String, String, u64, i64>(ShardId::new())
1410            .await;
1411
1412        // Different types, so that checks would fail in case we were not separating these
1413        // collections internally.
1414        let (mut write2, mut read2) = client
1415            .expect_open::<String, (), u64, i64>(ShardId::new())
1416            .await;
1417
1418        write1
1419            .expect_compare_and_append(&data1[..], u64::minimum(), 3)
1420            .await;
1421
1422        write2
1423            .expect_compare_and_append(&data2[..], u64::minimum(), 3)
1424            .await;
1425
1426        assert_eq!(
1427            read1.expect_snapshot_and_fetch(2).await,
1428            all_ok(&data1[..], 2)
1429        );
1430
1431        assert_eq!(
1432            read2.expect_snapshot_and_fetch(2).await,
1433            all_ok(&data2[..], 2)
1434        );
1435    }
1436
1437    #[mz_persist_proc::test(tokio::test)]
1438    #[cfg_attr(miri, ignore)] // unsupported operation: returning ready events from epoll_wait is not yet implemented
1439    async fn fetch_upper(dyncfgs: ConfigUpdates) {
1440        let data = [
1441            (("1".to_owned(), "one".to_owned()), 1, 1),
1442            (("2".to_owned(), "two".to_owned()), 2, 1),
1443        ];
1444
1445        let client = new_test_client(&dyncfgs).await;
1446
1447        let shard_id = ShardId::new();
1448
1449        let (mut write1, _read1) = client
1450            .expect_open::<String, String, u64, i64>(shard_id)
1451            .await;
1452
1453        let (mut write2, _read2) = client
1454            .expect_open::<String, String, u64, i64>(shard_id)
1455            .await;
1456
1457        write1
1458            .expect_append(&data[..], write1.upper().clone(), vec![3])
1459            .await;
1460
1461        // The shard-global upper does advance, even if this writer didn't advance its local upper.
1462        assert_eq!(write2.fetch_recent_upper().await, &Antichain::from_elem(3));
1463
1464        // The writer-local upper should advance, even if it was another writer
1465        // that advanced the frontier.
1466        assert_eq!(write2.upper(), &Antichain::from_elem(3));
1467    }
1468
1469    #[mz_persist_proc::test(tokio::test)]
1470    #[cfg_attr(miri, ignore)] // unsupported operation: returning ready events from epoll_wait is not yet implemented
1471    async fn append_with_invalid_upper(dyncfgs: ConfigUpdates) {
1472        let data = [
1473            (("1".to_owned(), "one".to_owned()), 1, 1),
1474            (("2".to_owned(), "two".to_owned()), 2, 1),
1475        ];
1476
1477        let client = new_test_client(&dyncfgs).await;
1478
1479        let shard_id = ShardId::new();
1480
1481        let (mut write, _read) = client
1482            .expect_open::<String, String, u64, i64>(shard_id)
1483            .await;
1484
1485        write
1486            .expect_append(&data[..], write.upper().clone(), vec![3])
1487            .await;
1488
1489        let data = [
1490            (("5".to_owned(), "fünf".to_owned()), 5, 1),
1491            (("6".to_owned(), "sechs".to_owned()), 6, 1),
1492        ];
1493        let res = write
1494            .append(
1495                data.iter(),
1496                Antichain::from_elem(5),
1497                Antichain::from_elem(7),
1498            )
1499            .await;
1500        assert_eq!(
1501            res,
1502            Ok(Err(UpperMismatch {
1503                expected: Antichain::from_elem(5),
1504                current: Antichain::from_elem(3)
1505            }))
1506        );
1507
1508        // Writing with an outdated upper updates the write handle's upper to the correct upper.
1509        assert_eq!(write.upper(), &Antichain::from_elem(3));
1510    }
1511
1512    // Make sure that the API structs are Sync + Send, so that they can be used in async tasks.
1513    // NOTE: This is a compile-time only test. If it compiles, we're good.
1514    #[allow(unused)]
1515    async fn sync_send(dyncfgs: ConfigUpdates) {
1516        mz_ore::test::init_logging();
1517
1518        fn is_send_sync<T: Send + Sync>(_x: T) -> bool {
1519            true
1520        }
1521
1522        let client = new_test_client(&dyncfgs).await;
1523
1524        let (write, read) = client
1525            .expect_open::<String, String, u64, i64>(ShardId::new())
1526            .await;
1527
1528        assert!(is_send_sync(client));
1529        assert!(is_send_sync(write));
1530        assert!(is_send_sync(read));
1531    }
1532
1533    #[mz_persist_proc::test(tokio::test)]
1534    #[cfg_attr(miri, ignore)] // unsupported operation: returning ready events from epoll_wait is not yet implemented
1535    async fn compare_and_append(dyncfgs: ConfigUpdates) {
1536        let data = vec![
1537            (("1".to_owned(), "one".to_owned()), 1, 1),
1538            (("2".to_owned(), "two".to_owned()), 2, 1),
1539            (("3".to_owned(), "three".to_owned()), 3, 1),
1540        ];
1541
1542        let id = ShardId::new();
1543        let client = new_test_client(&dyncfgs).await;
1544        let (mut write1, mut read) = client.expect_open::<String, String, u64, i64>(id).await;
1545
1546        let (mut write2, _read) = client.expect_open::<String, String, u64, i64>(id).await;
1547
1548        assert_eq!(write1.upper(), &Antichain::from_elem(u64::minimum()));
1549        assert_eq!(write2.upper(), &Antichain::from_elem(u64::minimum()));
1550        assert_eq!(read.since(), &Antichain::from_elem(u64::minimum()));
1551
1552        // Write a [0,3) batch.
1553        write1
1554            .expect_compare_and_append(&data[..2], u64::minimum(), 3)
1555            .await;
1556        assert_eq!(write1.upper(), &Antichain::from_elem(3));
1557
1558        assert_eq!(
1559            read.expect_snapshot_and_fetch(2).await,
1560            all_ok(&data[..2], 2)
1561        );
1562
1563        // Try and write with a wrong expected upper.
1564        let res = write2
1565            .compare_and_append(
1566                &data[..2],
1567                Antichain::from_elem(u64::minimum()),
1568                Antichain::from_elem(3),
1569            )
1570            .await;
1571        assert_eq!(
1572            res,
1573            Ok(Err(UpperMismatch {
1574                expected: Antichain::from_elem(u64::minimum()),
1575                current: Antichain::from_elem(3)
1576            }))
1577        );
1578
1579        // A failed write updates our local cache of the shard upper.
1580        assert_eq!(write2.upper(), &Antichain::from_elem(3));
1581
1582        // Try again with a good expected upper.
1583        write2.expect_compare_and_append(&data[2..], 3, 4).await;
1584
1585        assert_eq!(write2.upper(), &Antichain::from_elem(4));
1586
1587        assert_eq!(read.expect_snapshot_and_fetch(3).await, all_ok(&data, 3));
1588    }
1589
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 overlapping_append(dyncfgs: ConfigUpdates) {
1593        mz_ore::test::init_logging_default("info");
1594
1595        let data = vec![
1596            (("1".to_owned(), "one".to_owned()), 1, 1),
1597            (("2".to_owned(), "two".to_owned()), 2, 1),
1598            (("3".to_owned(), "three".to_owned()), 3, 1),
1599            (("4".to_owned(), "vier".to_owned()), 4, 1),
1600            (("5".to_owned(), "cinque".to_owned()), 5, 1),
1601        ];
1602
1603        let id = ShardId::new();
1604        let client = new_test_client(&dyncfgs).await;
1605
1606        let (mut write1, mut read) = client.expect_open::<String, String, u64, i64>(id).await;
1607
1608        let (mut write2, _read) = client.expect_open::<String, String, u64, i64>(id).await;
1609
1610        // Grab a listener before we do any writing
1611        let mut listen = read.clone("").await.expect_listen(0).await;
1612
1613        // Write a [0,3) batch.
1614        write1
1615            .expect_append(&data[..2], write1.upper().clone(), vec![3])
1616            .await;
1617        assert_eq!(write1.upper(), &Antichain::from_elem(3));
1618
1619        // Write a [0,5) batch with the second writer.
1620        write2
1621            .expect_append(&data[..4], write2.upper().clone(), vec![5])
1622            .await;
1623        assert_eq!(write2.upper(), &Antichain::from_elem(5));
1624
1625        // Write a [3,6) batch with the first writer.
1626        write1
1627            .expect_append(&data[2..5], write1.upper().clone(), vec![6])
1628            .await;
1629        assert_eq!(write1.upper(), &Antichain::from_elem(6));
1630
1631        assert_eq!(read.expect_snapshot_and_fetch(5).await, all_ok(&data, 5));
1632
1633        assert_eq!(
1634            listen.read_until(&6).await,
1635            (all_ok(&data[..], 1), Antichain::from_elem(6))
1636        );
1637    }
1638
1639    // Appends need to be contiguous for a shard, meaning the lower of an appended batch must not
1640    // be in advance of the current shard upper.
1641    #[mz_persist_proc::test(tokio::test)]
1642    #[cfg_attr(miri, ignore)] // unsupported operation: returning ready events from epoll_wait is not yet implemented
1643    async fn contiguous_append(dyncfgs: ConfigUpdates) {
1644        let data = vec![
1645            (("1".to_owned(), "one".to_owned()), 1, 1),
1646            (("2".to_owned(), "two".to_owned()), 2, 1),
1647            (("3".to_owned(), "three".to_owned()), 3, 1),
1648            (("4".to_owned(), "vier".to_owned()), 4, 1),
1649            (("5".to_owned(), "cinque".to_owned()), 5, 1),
1650        ];
1651
1652        let id = ShardId::new();
1653        let client = new_test_client(&dyncfgs).await;
1654
1655        let (mut write, mut read) = client.expect_open::<String, String, u64, i64>(id).await;
1656
1657        // Write a [0,3) batch.
1658        write
1659            .expect_append(&data[..2], write.upper().clone(), vec![3])
1660            .await;
1661        assert_eq!(write.upper(), &Antichain::from_elem(3));
1662
1663        // Appending a non-contiguous batch should fail.
1664        // Write a [5,6) batch with the second writer.
1665        let result = write
1666            .append(
1667                &data[4..5],
1668                Antichain::from_elem(5),
1669                Antichain::from_elem(6),
1670            )
1671            .await;
1672        assert_eq!(
1673            result,
1674            Ok(Err(UpperMismatch {
1675                expected: Antichain::from_elem(5),
1676                current: Antichain::from_elem(3)
1677            }))
1678        );
1679
1680        // Fixing the lower to make the write contiguous should make the append succeed.
1681        write.expect_append(&data[2..5], vec![3], vec![6]).await;
1682        assert_eq!(write.upper(), &Antichain::from_elem(6));
1683
1684        assert_eq!(read.expect_snapshot_and_fetch(5).await, all_ok(&data, 5));
1685    }
1686
1687    // Per-writer appends can be non-contiguous, as long as appends to the shard from all writers
1688    // combined are contiguous.
1689    #[mz_persist_proc::test(tokio::test)]
1690    #[cfg_attr(miri, ignore)] // unsupported operation: returning ready events from epoll_wait is not yet implemented
1691    async fn noncontiguous_append_per_writer(dyncfgs: ConfigUpdates) {
1692        let data = vec![
1693            (("1".to_owned(), "one".to_owned()), 1, 1),
1694            (("2".to_owned(), "two".to_owned()), 2, 1),
1695            (("3".to_owned(), "three".to_owned()), 3, 1),
1696            (("4".to_owned(), "vier".to_owned()), 4, 1),
1697            (("5".to_owned(), "cinque".to_owned()), 5, 1),
1698        ];
1699
1700        let id = ShardId::new();
1701        let client = new_test_client(&dyncfgs).await;
1702
1703        let (mut write1, mut read) = client.expect_open::<String, String, u64, i64>(id).await;
1704
1705        let (mut write2, _read) = client.expect_open::<String, String, u64, i64>(id).await;
1706
1707        // Write a [0,3) batch with writer 1.
1708        write1
1709            .expect_append(&data[..2], write1.upper().clone(), vec![3])
1710            .await;
1711        assert_eq!(write1.upper(), &Antichain::from_elem(3));
1712
1713        // Write a [3,5) batch with writer 2.
1714        write2.upper = Antichain::from_elem(3);
1715        write2
1716            .expect_append(&data[2..4], write2.upper().clone(), vec![5])
1717            .await;
1718        assert_eq!(write2.upper(), &Antichain::from_elem(5));
1719
1720        // Write a [5,6) batch with writer 1.
1721        write1.upper = Antichain::from_elem(5);
1722        write1
1723            .expect_append(&data[4..5], write1.upper().clone(), vec![6])
1724            .await;
1725        assert_eq!(write1.upper(), &Antichain::from_elem(6));
1726
1727        assert_eq!(read.expect_snapshot_and_fetch(5).await, all_ok(&data, 5));
1728    }
1729
1730    // Compare_and_appends need to be contiguous for a shard, meaning the lower of an appended
1731    // batch needs to match the current shard upper.
1732    #[mz_persist_proc::test(tokio::test)]
1733    #[cfg_attr(miri, ignore)] // unsupported operation: returning ready events from epoll_wait is not yet implemented
1734    async fn contiguous_compare_and_append(dyncfgs: ConfigUpdates) {
1735        let data = vec![
1736            (("1".to_owned(), "one".to_owned()), 1, 1),
1737            (("2".to_owned(), "two".to_owned()), 2, 1),
1738            (("3".to_owned(), "three".to_owned()), 3, 1),
1739            (("4".to_owned(), "vier".to_owned()), 4, 1),
1740            (("5".to_owned(), "cinque".to_owned()), 5, 1),
1741        ];
1742
1743        let id = ShardId::new();
1744        let client = new_test_client(&dyncfgs).await;
1745
1746        let (mut write, mut read) = client.expect_open::<String, String, u64, i64>(id).await;
1747
1748        // Write a [0,3) batch.
1749        write.expect_compare_and_append(&data[..2], 0, 3).await;
1750        assert_eq!(write.upper(), &Antichain::from_elem(3));
1751
1752        // Appending a non-contiguous batch should fail.
1753        // Write a [5,6) batch with the second writer.
1754        let result = write
1755            .compare_and_append(
1756                &data[4..5],
1757                Antichain::from_elem(5),
1758                Antichain::from_elem(6),
1759            )
1760            .await;
1761        assert_eq!(
1762            result,
1763            Ok(Err(UpperMismatch {
1764                expected: Antichain::from_elem(5),
1765                current: Antichain::from_elem(3)
1766            }))
1767        );
1768
1769        // Writing with the correct expected upper to make the write contiguous should make the
1770        // append succeed.
1771        write.expect_compare_and_append(&data[2..5], 3, 6).await;
1772        assert_eq!(write.upper(), &Antichain::from_elem(6));
1773
1774        assert_eq!(read.expect_snapshot_and_fetch(5).await, all_ok(&data, 5));
1775    }
1776
1777    // Per-writer compare_and_appends can be non-contiguous, as long as appends to the shard from
1778    // all writers combined are contiguous.
1779    #[mz_persist_proc::test(tokio::test)]
1780    #[cfg_attr(miri, ignore)] // unsupported operation: returning ready events from epoll_wait is not yet implemented
1781    async fn noncontiguous_compare_and_append_per_writer(dyncfgs: ConfigUpdates) {
1782        let data = vec![
1783            (("1".to_owned(), "one".to_owned()), 1, 1),
1784            (("2".to_owned(), "two".to_owned()), 2, 1),
1785            (("3".to_owned(), "three".to_owned()), 3, 1),
1786            (("4".to_owned(), "vier".to_owned()), 4, 1),
1787            (("5".to_owned(), "cinque".to_owned()), 5, 1),
1788        ];
1789
1790        let id = ShardId::new();
1791        let client = new_test_client(&dyncfgs).await;
1792
1793        let (mut write1, mut read) = client.expect_open::<String, String, u64, i64>(id).await;
1794
1795        let (mut write2, _read) = client.expect_open::<String, String, u64, i64>(id).await;
1796
1797        // Write a [0,3) batch with writer 1.
1798        write1.expect_compare_and_append(&data[..2], 0, 3).await;
1799        assert_eq!(write1.upper(), &Antichain::from_elem(3));
1800
1801        // Write a [3,5) batch with writer 2.
1802        write2.expect_compare_and_append(&data[2..4], 3, 5).await;
1803        assert_eq!(write2.upper(), &Antichain::from_elem(5));
1804
1805        // Write a [5,6) batch with writer 1.
1806        write1.expect_compare_and_append(&data[4..5], 5, 6).await;
1807        assert_eq!(write1.upper(), &Antichain::from_elem(6));
1808
1809        assert_eq!(read.expect_snapshot_and_fetch(5).await, all_ok(&data, 5));
1810    }
1811
1812    #[mz_ore::test]
1813    fn fmt_ids() {
1814        assert_eq!(
1815            format!("{}", LeasedReaderId([0u8; 16])),
1816            "r00000000-0000-0000-0000-000000000000"
1817        );
1818        assert_eq!(
1819            format!("{:?}", LeasedReaderId([0u8; 16])),
1820            "LeasedReaderId(00000000-0000-0000-0000-000000000000)"
1821        );
1822    }
1823
1824    #[mz_persist_proc::test(tokio::test(flavor = "multi_thread"))]
1825    #[cfg_attr(miri, ignore)] // error: unsupported operation: integer-to-pointer casts and `ptr::from_exposed_addr` are not supported with `-Zmiri-strict-provenance`
1826    async fn concurrency(dyncfgs: ConfigUpdates) {
1827        let data = DataGenerator::small();
1828
1829        const NUM_WRITERS: usize = 2;
1830        let id = ShardId::new();
1831        let client = new_test_client(&dyncfgs).await;
1832        let mut handles = Vec::<mz_ore::task::JoinHandle<()>>::new();
1833        for idx in 0..NUM_WRITERS {
1834            let (data, client) = (data.clone(), client.clone());
1835
1836            let (batch_tx, mut batch_rx) = tokio::sync::mpsc::channel(1);
1837
1838            let client1 = client.clone();
1839            let handle = mz_ore::task::spawn(|| format!("writer-{}", idx), async move {
1840                let (write, _) = client1.expect_open::<Vec<u8>, Vec<u8>, u64, i64>(id).await;
1841                let mut current_upper = 0;
1842                for batch in data.batches() {
1843                    let new_upper = match batch.get(batch.len() - 1) {
1844                        Some((_, max_ts, _)) => u64::decode(max_ts) + 1,
1845                        None => continue,
1846                    };
1847                    // Because we (intentionally) call open inside the task,
1848                    // some other writer may have raced ahead and already
1849                    // appended some data before this one was registered. As a
1850                    // result, this writer may not be starting with an upper of
1851                    // the initial empty antichain. This is nice because it
1852                    // mimics how a real HA source would work, but it means we
1853                    // have to skip any batches that have already been committed
1854                    // (otherwise our new_upper would be before our upper).
1855                    //
1856                    // Note however, that unlike a real source, our
1857                    // DataGenerator-derived batches are guaranteed to be
1858                    // chunked along the same boundaries. This means we don't
1859                    // have to consider partial batches when generating the
1860                    // updates below.
1861                    if PartialOrder::less_equal(&Antichain::from_elem(new_upper), write.upper()) {
1862                        continue;
1863                    }
1864
1865                    let current_upper_chain = Antichain::from_elem(current_upper);
1866                    current_upper = new_upper;
1867                    let new_upper_chain = Antichain::from_elem(new_upper);
1868                    let mut builder = write.builder(current_upper_chain);
1869
1870                    for ((k, v), t, d) in batch.iter() {
1871                        builder
1872                            .add(&k.to_vec(), &v.to_vec(), &u64::decode(t), &i64::decode(d))
1873                            .await
1874                            .expect("invalid usage");
1875                    }
1876
1877                    let batch = builder
1878                        .finish(new_upper_chain)
1879                        .await
1880                        .expect("invalid usage");
1881
1882                    match batch_tx.send(batch).await {
1883                        Ok(_) => (),
1884                        Err(e) => panic!("send error: {}", e),
1885                    }
1886                }
1887            });
1888            handles.push(handle);
1889
1890            let handle = mz_ore::task::spawn(|| format!("appender-{}", idx), async move {
1891                let (mut write, _) = client.expect_open::<Vec<u8>, Vec<u8>, u64, i64>(id).await;
1892
1893                while let Some(batch) = batch_rx.recv().await {
1894                    let lower = batch.lower().clone();
1895                    let upper = batch.upper().clone();
1896                    write
1897                        .append_batch(batch, lower, upper)
1898                        .await
1899                        .expect("invalid usage")
1900                        .expect("unexpected upper");
1901                }
1902            });
1903            handles.push(handle);
1904        }
1905
1906        for handle in handles {
1907            let () = handle.await;
1908        }
1909
1910        let expected = data.records().collect::<Vec<_>>();
1911        let max_ts = expected.last().map(|(_, t, _)| *t).unwrap_or_default();
1912        let (_, mut read) = client.expect_open::<Vec<u8>, Vec<u8>, u64, i64>(id).await;
1913        assert_eq!(
1914            read.expect_snapshot_and_fetch(max_ts).await,
1915            all_ok(expected.iter(), max_ts)
1916        );
1917    }
1918
1919    // Regression test for database-issues#3523. Snapshot with as_of >= upper would
1920    // immediately return the data currently available instead of waiting for
1921    // upper to advance past as_of.
1922    #[mz_persist_proc::test(tokio::test)]
1923    #[cfg_attr(miri, ignore)] // unsupported operation: returning ready events from epoll_wait is not yet implemented
1924    async fn regression_blocking_reads(dyncfgs: ConfigUpdates) {
1925        let waker = noop_waker();
1926        let mut cx = Context::from_waker(&waker);
1927
1928        let data = [
1929            (("1".to_owned(), "one".to_owned()), 1, 1),
1930            (("2".to_owned(), "two".to_owned()), 2, 1),
1931            (("3".to_owned(), "three".to_owned()), 3, 1),
1932        ];
1933
1934        let id = ShardId::new();
1935        let client = new_test_client(&dyncfgs).await;
1936        let (mut write, mut read) = client.expect_open::<String, String, u64, i64>(id).await;
1937
1938        // Grab a listener as_of (aka gt) 1, which is not yet closed out.
1939        let mut listen = read.clone("").await.expect_listen(1).await;
1940        let mut listen_next = Box::pin(listen.fetch_next());
1941        // Intentionally don't await the listen_next, but instead manually poke
1942        // it for a while and assert that it doesn't resolve yet. See below for
1943        // discussion of some alternative ways of writing this unit test.
1944        for _ in 0..100 {
1945            assert!(
1946                Pin::new(&mut listen_next).poll(&mut cx).is_pending(),
1947                "listen::next unexpectedly ready"
1948            );
1949        }
1950
1951        // Write a [0,3) batch.
1952        write
1953            .expect_compare_and_append(&data[..2], u64::minimum(), 3)
1954            .await;
1955
1956        // The initial listen_next call should now be able to return data at 2.
1957        // It doesn't get 1 because the as_of was 1 and listen is strictly gt.
1958        assert_eq!(
1959            listen_next.await,
1960            vec![
1961                ListenEvent::Updates(vec![(("2".to_owned(), "two".to_owned()), 2, 1)]),
1962                ListenEvent::Progress(Antichain::from_elem(3)),
1963            ]
1964        );
1965
1966        // Grab a snapshot as_of 3, which is not yet closed out. Intentionally
1967        // don't await the snap, but instead manually poke it for a while and
1968        // assert that it doesn't resolve yet.
1969        //
1970        // An alternative to this would be to run it in a task and poll the task
1971        // with some timeout, but this would introduce a fixed test execution
1972        // latency of the timeout in the happy case. Plus, it would be
1973        // non-deterministic.
1974        //
1975        // Another alternative (that's potentially quite interesting!) would be
1976        // to separate creating a snapshot immediately (which would fail if
1977        // as_of was >= upper) from a bit of logic that retries until that case
1978        // is ready.
1979        let mut snap = Box::pin(read.expect_snapshot_and_fetch(3));
1980        for _ in 0..100 {
1981            assert!(
1982                Pin::new(&mut snap).poll(&mut cx).is_pending(),
1983                "snapshot unexpectedly ready"
1984            );
1985        }
1986
1987        // Now add the data at 3 and also unblock the snapshot.
1988        write.expect_compare_and_append(&data[2..], 3, 4).await;
1989
1990        // Read the snapshot and check that it got all the appropriate data.
1991        assert_eq!(snap.await, all_ok(&data[..], 3));
1992    }
1993
1994    #[mz_persist_proc::test(tokio::test)]
1995    #[cfg_attr(miri, ignore)] // unsupported operation: returning ready events from epoll_wait is not yet implemented
1996    async fn heartbeat_task_shutdown(dyncfgs: ConfigUpdates) {
1997        // Verify that the ReadHandle and WriteHandle background heartbeat tasks
1998        // shut down cleanly after the handle is expired.
1999        let mut cache = new_test_client_cache(&dyncfgs);
2000        cache
2001            .cfg
2002            .set_config(&READER_LEASE_DURATION, Duration::from_millis(1));
2003        cache.cfg.writer_lease_duration = Duration::from_millis(1);
2004        let (_write, mut read) = cache
2005            .open(PersistLocation::new_in_mem())
2006            .await
2007            .expect("client construction failed")
2008            .expect_open::<(), (), u64, i64>(ShardId::new())
2009            .await;
2010        let mut read_unexpired_state = read
2011            .unexpired_state
2012            .take()
2013            .expect("handle should have unexpired state");
2014        read.expire().await;
2015        for read_heartbeat_task in mem::take(&mut read_unexpired_state._heartbeat_tasks) {
2016            let () = read_heartbeat_task.await;
2017        }
2018    }
2019
2020    /// Verify that shard finalization works with empty shards, shards that have
2021    /// an empty write up to the empty upper Antichain.
2022    #[mz_persist_proc::test(tokio::test)]
2023    #[cfg_attr(miri, ignore)] // unsupported operation: returning ready events from epoll_wait is not yet implemented
2024    async fn finalize_empty_shard(dyncfgs: ConfigUpdates) {
2025        let persist_client = new_test_client(&dyncfgs).await;
2026
2027        let shard_id = ShardId::new();
2028        pub const CRITICAL_SINCE: CriticalReaderId =
2029            CriticalReaderId([0, 0, 0, 0, 17, 17, 34, 34, 51, 51, 68, 68, 68, 68, 68, 68]);
2030
2031        let (mut write, mut read) = persist_client
2032            .expect_open::<(), (), u64, i64>(shard_id)
2033            .await;
2034
2035        // Advance since and upper to empty, which is a pre-requisite for
2036        // finalization/tombstoning.
2037        let () = read.downgrade_since(&Antichain::new()).await;
2038        let () = write.advance_upper(&Antichain::new()).await;
2039
2040        let mut since_handle: SinceHandle<(), (), u64, i64, u64> = persist_client
2041            .open_critical_since(shard_id, CRITICAL_SINCE, Diagnostics::for_tests())
2042            .await
2043            .expect("invalid persist usage");
2044
2045        let epoch = since_handle.opaque().clone();
2046        let new_since = Antichain::new();
2047        let downgrade = since_handle
2048            .compare_and_downgrade_since(&epoch, (&epoch, &new_since))
2049            .await;
2050
2051        assert!(
2052            downgrade.is_ok(),
2053            "downgrade of critical handle must succeed"
2054        );
2055
2056        let finalize = persist_client
2057            .finalize_shard::<(), (), u64, i64>(shard_id, Diagnostics::for_tests())
2058            .await;
2059
2060        assert_ok!(finalize, "finalization must succeed");
2061
2062        let is_finalized = persist_client
2063            .is_finalized::<(), (), u64, i64>(shard_id, Diagnostics::for_tests())
2064            .await
2065            .expect("invalid persist usage");
2066        assert!(is_finalized, "shard must still be finalized");
2067    }
2068
2069    /// Verify that shard finalization works with shards that had some data
2070    /// written to them, plus then an empty batch to bring their upper to the
2071    /// empty Antichain.
2072    #[mz_persist_proc::test(tokio::test)]
2073    #[cfg_attr(miri, ignore)] // unsupported operation: returning ready events from epoll_wait is not yet implemented
2074    async fn finalize_shard(dyncfgs: ConfigUpdates) {
2075        const DATA: &[(((), ()), u64, i64)] = &[(((), ()), 0, 1)];
2076        let persist_client = new_test_client(&dyncfgs).await;
2077
2078        let shard_id = ShardId::new();
2079        pub const CRITICAL_SINCE: CriticalReaderId =
2080            CriticalReaderId([0, 0, 0, 0, 17, 17, 34, 34, 51, 51, 68, 68, 68, 68, 68, 68]);
2081
2082        let (mut write, mut read) = persist_client
2083            .expect_open::<(), (), u64, i64>(shard_id)
2084            .await;
2085
2086        // Write some data.
2087        let () = write
2088            .compare_and_append(DATA, Antichain::from_elem(0), Antichain::from_elem(1))
2089            .await
2090            .expect("usage should be valid")
2091            .expect("upper should match");
2092
2093        // Advance since and upper to empty, which is a pre-requisite for
2094        // finalization/tombstoning.
2095        let () = read.downgrade_since(&Antichain::new()).await;
2096        let () = write.advance_upper(&Antichain::new()).await;
2097
2098        let mut since_handle: SinceHandle<(), (), u64, i64, u64> = persist_client
2099            .open_critical_since(shard_id, CRITICAL_SINCE, Diagnostics::for_tests())
2100            .await
2101            .expect("invalid persist usage");
2102
2103        let epoch = since_handle.opaque().clone();
2104        let new_since = Antichain::new();
2105        let downgrade = since_handle
2106            .compare_and_downgrade_since(&epoch, (&epoch, &new_since))
2107            .await;
2108
2109        assert!(
2110            downgrade.is_ok(),
2111            "downgrade of critical handle must succeed"
2112        );
2113
2114        let finalize = persist_client
2115            .finalize_shard::<(), (), u64, i64>(shard_id, Diagnostics::for_tests())
2116            .await;
2117
2118        assert_ok!(finalize, "finalization must succeed");
2119
2120        let is_finalized = persist_client
2121            .is_finalized::<(), (), u64, i64>(shard_id, Diagnostics::for_tests())
2122            .await
2123            .expect("invalid persist usage");
2124        assert!(is_finalized, "shard must still be finalized");
2125    }
2126
2127    proptest! {
2128        #![proptest_config(ProptestConfig::with_cases(4096))]
2129
2130        #[mz_ore::test]
2131        #[cfg_attr(miri, ignore)] // too slow
2132        fn shard_id_protobuf_roundtrip(expect in any::<ShardId>() ) {
2133            let actual = protobuf_roundtrip::<_, String>(&expect);
2134            assert_ok!(actual);
2135            assert_eq!(actual.unwrap(), expect);
2136        }
2137    }
2138}