Skip to main content

mz_persist_client/
write.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//! Write capabilities and handles
11
12use std::borrow::Borrow;
13use std::fmt::Debug;
14use std::sync::Arc;
15
16use differential_dataflow::difference::Monoid;
17use differential_dataflow::lattice::Lattice;
18use differential_dataflow::trace::Description;
19use futures::StreamExt;
20use futures::stream::FuturesUnordered;
21use mz_dyncfg::Config;
22use mz_ore::task::RuntimeExt;
23use mz_ore::{instrument, soft_panic_or_log};
24use mz_persist::location::Blob;
25use mz_persist_types::schema::SchemaId;
26use mz_persist_types::{Codec, Codec64};
27use mz_proto::{IntoRustIfSome, ProtoType};
28use proptest_derive::Arbitrary;
29use semver::Version;
30use serde::{Deserialize, Serialize};
31use timely::PartialOrder;
32use timely::order::TotalOrder;
33use timely::progress::{Antichain, Timestamp};
34use tokio::runtime::Handle;
35use tracing::{Instrument, debug_span, error, info, warn};
36use uuid::Uuid;
37
38use crate::batch::{
39    Added, BATCH_DELETE_ENABLED, Batch, BatchBuilder, BatchBuilderConfig, BatchBuilderInternal,
40    BatchParts, ProtoBatch, validate_truncate_batch,
41};
42use crate::error::{InvalidUsage, UpperMismatch};
43use crate::fetch::{
44    EncodedPart, FetchBatchFilter, FetchedPart, PartDecodeFormat, VALIDATE_PART_BOUNDS_ON_READ,
45};
46use crate::internal::compact::{CompactConfig, Compactor};
47use crate::internal::encoding::{Schemas, assert_code_can_read_data};
48use crate::internal::machine::{
49    CompareAndAppendRes, ExpireFn, Machine, next_listen_batch_retry_params,
50};
51use crate::internal::metrics::{BatchWriteMetrics, Metrics, ShardMetrics};
52use crate::internal::state::{BatchPart, HandleDebugState, HollowBatch, RunOrder, RunPart};
53use crate::read::ReadHandle;
54use crate::schema::PartMigration;
55use crate::{GarbageCollector, IsolatedRuntime, PersistConfig, ShardId, parse_id};
56
57pub(crate) const COMBINE_INLINE_WRITES: Config<bool> = Config::new(
58    "persist_write_combine_inline_writes",
59    true,
60    "If set, re-encode inline writes if they don't fit into the batch metadata limits.",
61);
62
63pub(crate) const VALIDATE_PART_BOUNDS_ON_WRITE: Config<bool> = Config::new(
64    "persist_validate_part_bounds_on_write",
65    false,
66    "Validate the part lower <= the batch lower and the part upper <= batch upper,\
67    for the batch being appended.",
68);
69
70/// An opaque identifier for a writer of a persist durable TVC (aka shard).
71#[derive(
72    Arbitrary,
73    Clone,
74    PartialEq,
75    Eq,
76    PartialOrd,
77    Ord,
78    Hash,
79    Serialize,
80    Deserialize
81)]
82#[serde(try_from = "String", into = "String")]
83pub struct WriterId(pub(crate) [u8; 16]);
84
85impl std::fmt::Display for WriterId {
86    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
87        write!(f, "w{}", Uuid::from_bytes(self.0))
88    }
89}
90
91impl std::fmt::Debug for WriterId {
92    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
93        write!(f, "WriterId({})", Uuid::from_bytes(self.0))
94    }
95}
96
97impl std::str::FromStr for WriterId {
98    type Err = String;
99
100    fn from_str(s: &str) -> Result<Self, Self::Err> {
101        parse_id("w", "WriterId", s).map(WriterId)
102    }
103}
104
105impl From<WriterId> for String {
106    fn from(writer_id: WriterId) -> Self {
107        writer_id.to_string()
108    }
109}
110
111impl TryFrom<String> for WriterId {
112    type Error = String;
113
114    fn try_from(s: String) -> Result<Self, Self::Error> {
115        s.parse()
116    }
117}
118
119impl WriterId {
120    pub(crate) fn new() -> Self {
121        WriterId(*Uuid::new_v4().as_bytes())
122    }
123}
124
125/// A "capability" granting the ability to apply updates to some shard at times
126/// greater or equal to `self.upper()`.
127///
128/// All async methods on ReadHandle retry for as long as they are able, but the
129/// returned [std::future::Future]s implement "cancel on drop" semantics. This
130/// means that callers can add a timeout using [tokio::time::timeout] or
131/// [tokio::time::timeout_at].
132///
133/// ```rust,no_run
134/// # let mut write: mz_persist_client::write::WriteHandle<String, String, u64, i64> = unimplemented!();
135/// # let timeout: std::time::Duration = unimplemented!();
136/// # async {
137/// tokio::time::timeout(timeout, write.fetch_recent_upper()).await
138/// # };
139/// ```
140#[derive(Debug)]
141pub struct WriteHandle<K: Codec, V: Codec, T, D> {
142    pub(crate) cfg: PersistConfig,
143    pub(crate) metrics: Arc<Metrics>,
144    pub(crate) machine: Machine<K, V, T, D>,
145    pub(crate) gc: GarbageCollector<K, V, T, D>,
146    pub(crate) compact: Option<Compactor<K, V, T, D>>,
147    pub(crate) blob: Arc<dyn Blob>,
148    pub(crate) isolated_runtime: Arc<IsolatedRuntime>,
149    pub(crate) writer_id: WriterId,
150    pub(crate) debug_state: HandleDebugState,
151    pub(crate) write_schemas: Schemas<K, V>,
152
153    pub(crate) upper: Antichain<T>,
154    expire_fn: Option<ExpireFn>,
155}
156
157impl<K, V, T, D> WriteHandle<K, V, T, D>
158where
159    K: Debug + Codec,
160    V: Debug + Codec,
161    T: Timestamp + TotalOrder + Lattice + Codec64 + Sync,
162    D: Monoid + Ord + Codec64 + Send + Sync,
163{
164    pub(crate) fn new(
165        cfg: PersistConfig,
166        metrics: Arc<Metrics>,
167        machine: Machine<K, V, T, D>,
168        gc: GarbageCollector<K, V, T, D>,
169        blob: Arc<dyn Blob>,
170        writer_id: WriterId,
171        purpose: &str,
172        write_schemas: Schemas<K, V>,
173    ) -> Self {
174        let isolated_runtime = Arc::clone(&machine.isolated_runtime);
175        let compact = cfg
176            .compaction_enabled
177            .then(|| Compactor::new(cfg.clone(), Arc::clone(&metrics), gc.clone()));
178        let debug_state = HandleDebugState {
179            hostname: cfg.hostname.to_owned(),
180            purpose: purpose.to_owned(),
181        };
182        let upper = machine.applier.clone_upper();
183        let expire_fn = Self::expire_fn(machine.clone(), gc.clone(), writer_id.clone());
184        WriteHandle {
185            cfg,
186            metrics,
187            machine,
188            gc,
189            compact,
190            blob,
191            isolated_runtime,
192            writer_id,
193            debug_state,
194            write_schemas,
195            upper,
196            expire_fn: Some(expire_fn),
197        }
198    }
199
200    /// Creates a [WriteHandle] for the same shard from an existing
201    /// [ReadHandle].
202    pub fn from_read(read: &ReadHandle<K, V, T, D>, purpose: &str) -> Self {
203        Self::new(
204            read.cfg.clone(),
205            Arc::clone(&read.metrics),
206            read.machine.clone(),
207            read.gc.clone(),
208            Arc::clone(&read.blob),
209            WriterId::new(),
210            purpose,
211            read.read_schemas.clone(),
212        )
213    }
214
215    /// True iff this WriteHandle supports writing without enforcing batch
216    /// bounds checks.
217    pub fn validate_part_bounds_on_write(&self) -> bool {
218        // Note that we require validation when the read checks are enabled, even if the write-time
219        // checks would otherwise be disabled, to avoid batches that would fail at read time.
220        VALIDATE_PART_BOUNDS_ON_WRITE.get(&self.cfg) || VALIDATE_PART_BOUNDS_ON_READ.get(&self.cfg)
221    }
222
223    /// This handle's shard id.
224    pub fn shard_id(&self) -> ShardId {
225        self.machine.shard_id()
226    }
227
228    /// Returns the schema of this writer.
229    pub fn schema_id(&self) -> Option<SchemaId> {
230        self.write_schemas.id
231    }
232
233    /// Registers the write schema, if it isn't already registered.
234    ///
235    /// This method expects that either the shard doesn't yet have any schema registered, or one of
236    /// the registered schemas is the same as the write schema. If all registered schemas are
237    /// different from the write schema, or the shard is a tombstone, it returns `None`.
238    pub async fn try_register_schema(&mut self) -> Option<SchemaId> {
239        let Schemas { id, key, val } = &self.write_schemas;
240
241        if let Some(id) = id {
242            return Some(*id);
243        }
244
245        let (schema_id, maintenance) = self.machine.register_schema(key, val).await;
246        maintenance.start_performing(&self.machine, &self.gc);
247
248        self.write_schemas.id = schema_id;
249        schema_id
250    }
251
252    /// A cached version of the shard-global `upper` frontier.
253    ///
254    /// This is the most recent upper discovered by this handle. It is
255    /// potentially more stale than [Self::shared_upper] but is lock-free and
256    /// allocation-free. This will always be less or equal to the shard-global
257    /// `upper`.
258    pub fn upper(&self) -> &Antichain<T> {
259        &self.upper
260    }
261
262    /// A less-stale cached version of the shard-global `upper` frontier.
263    ///
264    /// This is the most recently known upper for this shard process-wide, but
265    /// unlike [Self::upper] it requires a mutex and a clone. This will always be
266    /// less or equal to the shard-global `upper`.
267    pub fn shared_upper(&self) -> Antichain<T> {
268        self.machine.applier.clone_upper()
269    }
270
271    /// Fetches and returns a recent shard-global `upper`. Importantly, this operation is
272    /// linearized with write operations.
273    ///
274    /// This requires fetching the latest state from consensus and is therefore a potentially
275    /// expensive operation.
276    #[instrument(level = "debug", fields(shard = %self.machine.shard_id()))]
277    pub async fn fetch_recent_upper(&mut self) -> &Antichain<T> {
278        // TODO: Do we even need to track self.upper on WriteHandle or could
279        // WriteHandle::upper just get the one out of machine?
280        self.machine
281            .applier
282            .fetch_upper(|current_upper| self.upper.clone_from(current_upper))
283            .await;
284        &self.upper
285    }
286
287    /// Advance the shard's upper by the given frontier.
288    ///
289    /// If the provided `target` is less than or equal to the shard's upper, this is a no-op.
290    ///
291    /// In contrast to the various compare-and-append methods, this method does not require the
292    /// handle's write schema to be registered with the shard. That is, it is fine to use a dummy
293    /// schema when creating a writer just to advance a shard upper.
294    pub async fn advance_upper(&mut self, target: &Antichain<T>) {
295        // We avoid `fetch_recent_upper` here, to avoid a consensus roundtrip if the known upper is
296        // already beyond the target.
297        let mut lower = self.shared_upper().clone();
298
299        while !PartialOrder::less_equal(target, &lower) {
300            let since = Antichain::from_elem(T::minimum());
301            let desc = Description::new(lower.clone(), target.clone(), since);
302            let batch = HollowBatch::empty(desc);
303
304            let res = self
305                .machine
306                .compare_and_append(&batch, &self.writer_id, &self.debug_state)
307                .await;
308
309            use CompareAndAppendRes::*;
310            let new_upper = match res {
311                Success(_seq_no, maintenance) => {
312                    maintenance.start_performing(&self.machine, &self.gc, self.compact.as_ref());
313                    batch.desc.upper().clone()
314                }
315                UpperMismatch(_seq_no, actual_upper) => actual_upper,
316                InvalidUsage(_invalid_usage) => unreachable!("batch bounds checked above"),
317                InlineBackpressure => unreachable!("batch was empty"),
318            };
319
320            self.upper.clone_from(&new_upper);
321            lower = new_upper;
322        }
323    }
324
325    /// Applies `updates` to this shard and downgrades this handle's upper to
326    /// `upper`.
327    ///
328    /// The innermost `Result` is `Ok` if the updates were successfully written.
329    /// If not, an `Upper` err containing the current writer upper is returned.
330    /// If that happens, we also update our local `upper` to match the current
331    /// upper. This is useful in cases where a timeout happens in between a
332    /// successful write and returning that to the client.
333    ///
334    /// In contrast to [Self::compare_and_append], multiple [WriteHandle]s may
335    /// be used concurrently to write to the same shard, but in this case, the
336    /// data being written must be identical (in the sense of "definite"-ness).
337    /// It's intended for replicated use by source ingestion, sinks, etc.
338    ///
339    /// All times in `updates` must be greater or equal to `lower` and not
340    /// greater or equal to `upper`. A `upper` of the empty antichain "finishes"
341    /// this shard, promising that no more data is ever incoming.
342    ///
343    /// `updates` may be empty, which allows for downgrading `upper` to
344    /// communicate progress. It is possible to call this with `upper` equal to
345    /// `self.upper()` and an empty `updates` (making the call a no-op).
346    ///
347    /// This uses a bounded amount of memory, even when `updates` is very large.
348    /// Individual records, however, should be small enough that we can
349    /// reasonably chunk them up: O(KB) is definitely fine, O(MB) come talk to
350    /// us.
351    ///
352    /// The clunky multi-level Result is to enable more obvious error handling
353    /// in the caller. See <http://sled.rs/errors.html> for details.
354    #[instrument(level = "trace", fields(shard = %self.machine.shard_id()))]
355    pub async fn append<SB, KB, VB, TB, DB, I>(
356        &mut self,
357        updates: I,
358        lower: Antichain<T>,
359        upper: Antichain<T>,
360    ) -> Result<Result<(), UpperMismatch<T>>, InvalidUsage<T>>
361    where
362        SB: Borrow<((KB, VB), TB, DB)>,
363        KB: Borrow<K>,
364        VB: Borrow<V>,
365        TB: Borrow<T>,
366        DB: Borrow<D>,
367        I: IntoIterator<Item = SB>,
368        D: Send + Sync,
369    {
370        let batch = self.batch(updates, lower.clone(), upper.clone()).await?;
371        self.append_batch(batch, lower, upper).await
372    }
373
374    /// Applies `updates` to this shard and downgrades this handle's upper to
375    /// `new_upper` iff the current global upper of this shard is
376    /// `expected_upper`.
377    ///
378    /// The innermost `Result` is `Ok` if the updates were successfully written.
379    /// If not, an `Upper` err containing the current global upper is returned.
380    ///
381    /// In contrast to [Self::append], this linearizes mutations from all
382    /// writers. It's intended for use as an atomic primitive for timestamp
383    /// bindings, SQL tables, etc.
384    ///
385    /// All times in `updates` must be greater or equal to `expected_upper` and
386    /// not greater or equal to `new_upper`. A `new_upper` of the empty
387    /// antichain "finishes" this shard, promising that no more data is ever
388    /// incoming.
389    ///
390    /// `updates` may be empty, which allows for downgrading `upper` to
391    /// communicate progress. It is possible to heartbeat a writer lease by
392    /// calling this with `new_upper` equal to `self.upper()` and an empty
393    /// `updates` (making the call a no-op).
394    ///
395    /// This uses a bounded amount of memory, even when `updates` is very large.
396    /// Individual records, however, should be small enough that we can
397    /// reasonably chunk them up: O(KB) is definitely fine, O(MB) come talk to
398    /// us.
399    ///
400    /// The clunky multi-level Result is to enable more obvious error handling
401    /// in the caller. See <http://sled.rs/errors.html> for details.
402    #[instrument(level = "trace", fields(shard = %self.machine.shard_id()))]
403    pub async fn compare_and_append<SB, KB, VB, TB, DB, I>(
404        &mut self,
405        updates: I,
406        expected_upper: Antichain<T>,
407        new_upper: Antichain<T>,
408    ) -> Result<Result<(), UpperMismatch<T>>, InvalidUsage<T>>
409    where
410        SB: Borrow<((KB, VB), TB, DB)>,
411        KB: Borrow<K>,
412        VB: Borrow<V>,
413        TB: Borrow<T>,
414        DB: Borrow<D>,
415        I: IntoIterator<Item = SB>,
416        D: Send + Sync,
417    {
418        let mut batch = self
419            .batch(updates, expected_upper.clone(), new_upper.clone())
420            .await?;
421        match self
422            .compare_and_append_batch(&mut [&mut batch], expected_upper, new_upper, true)
423            .await
424        {
425            ok @ Ok(Ok(())) => ok,
426            err => {
427                // We cannot delete the batch in compare_and_append_batch()
428                // because the caller owns the batch and might want to retry
429                // with a different `expected_upper`. In this function, we
430                // control the batch, so we have to delete it.
431                batch.delete().await;
432                err
433            }
434        }
435    }
436
437    /// Appends the batch of updates to the shard and downgrades this handle's
438    /// upper to `upper`.
439    ///
440    /// The innermost `Result` is `Ok` if the updates were successfully written.
441    /// If not, an `Upper` err containing the current writer upper is returned.
442    /// If that happens, we also update our local `upper` to match the current
443    /// upper. This is useful in cases where a timeout happens in between a
444    /// successful write and returning that to the client.
445    ///
446    /// In contrast to [Self::compare_and_append_batch], multiple [WriteHandle]s
447    /// may be used concurrently to write to the same shard, but in this case,
448    /// the data being written must be identical (in the sense of
449    /// "definite"-ness). It's intended for replicated use by source ingestion,
450    /// sinks, etc.
451    ///
452    /// A `upper` of the empty antichain "finishes" this shard, promising that
453    /// no more data is ever incoming.
454    ///
455    /// The batch may be empty, which allows for downgrading `upper` to
456    /// communicate progress. It is possible to heartbeat a writer lease by
457    /// calling this with `upper` equal to `self.upper()` and an empty `updates`
458    /// (making the call a no-op).
459    ///
460    /// The clunky multi-level Result is to enable more obvious error handling
461    /// in the caller. See <http://sled.rs/errors.html> for details.
462    #[instrument(level = "trace", fields(shard = %self.machine.shard_id()))]
463    pub async fn append_batch(
464        &mut self,
465        mut batch: Batch<K, V, T, D>,
466        mut lower: Antichain<T>,
467        upper: Antichain<T>,
468    ) -> Result<Result<(), UpperMismatch<T>>, InvalidUsage<T>>
469    where
470        D: Send + Sync,
471    {
472        loop {
473            let res = self
474                .compare_and_append_batch(&mut [&mut batch], lower.clone(), upper.clone(), true)
475                .await?;
476            match res {
477                Ok(()) => {
478                    self.upper = upper;
479                    return Ok(Ok(()));
480                }
481                Err(mismatch) => {
482                    // We tried to to a non-contiguous append, that won't work.
483                    if PartialOrder::less_than(&mismatch.current, &lower) {
484                        self.upper.clone_from(&mismatch.current);
485
486                        batch.delete().await;
487
488                        return Ok(Err(mismatch));
489                    } else if PartialOrder::less_than(&mismatch.current, &upper) {
490                        // Cut down the Description by advancing its lower to the current shard
491                        // upper and try again. IMPORTANT: We can only advance the lower, meaning
492                        // we cut updates away, we must not "extend" the batch by changing to a
493                        // lower that is not beyond the current lower. This invariant is checked by
494                        // the first if branch: if `!(current_upper < lower)` then it holds that
495                        // `lower <= current_upper`.
496                        lower = mismatch.current;
497                    } else {
498                        // We already have updates past this batch's upper, the append is a no-op.
499                        self.upper = mismatch.current;
500
501                        // Because we return a success result, the caller will
502                        // think that the batch was consumed or otherwise used,
503                        // so we have to delete it here.
504                        batch.delete().await;
505
506                        return Ok(Ok(()));
507                    }
508                }
509            }
510        }
511    }
512
513    /// Appends the batch of updates to the shard and downgrades this handle's
514    /// upper to `new_upper` iff the current global upper of this shard is
515    /// `expected_upper`.
516    ///
517    /// The innermost `Result` is `Ok` if the batch was successfully written. If
518    /// not, an `Upper` err containing the current global upper is returned.
519    ///
520    /// In contrast to [Self::append_batch], this linearizes mutations from all
521    /// writers. It's intended for use as an atomic primitive for timestamp
522    /// bindings, SQL tables, etc.
523    ///
524    /// A `new_upper` of the empty antichain "finishes" this shard, promising
525    /// that no more data is ever incoming.
526    ///
527    /// The batch may be empty, which allows for downgrading `upper` to
528    /// communicate progress. It is possible to heartbeat a writer lease by
529    /// calling this with `new_upper` equal to `self.upper()` and an empty
530    /// `updates` (making the call a no-op).
531    ///
532    /// IMPORTANT: In case of an erroneous result the caller is responsible for
533    /// the lifecycle of the `batch`. It can be deleted or it can be used to
534    /// retry with adjusted frontiers.
535    ///
536    /// The clunky multi-level Result is to enable more obvious error handling
537    /// in the caller. See <http://sled.rs/errors.html> for details.
538    ///
539    /// If the `enforce_matching_batch_boundaries` flag is set to `false`:
540    /// We no longer validate that every batch covers the entire range between
541    /// the expected and new uppers, as we wish to allow combining batches that
542    /// cover different subsets of that range, including subsets of that range
543    /// that include no data at all. The caller is responsible for guaranteeing
544    /// that the set of batches provided collectively include all updates for
545    /// the entire range between the expected and new upper.
546    #[instrument(level = "debug", fields(shard = %self.machine.shard_id()))]
547    pub async fn compare_and_append_batch(
548        &mut self,
549        batches: &mut [&mut Batch<K, V, T, D>],
550        expected_upper: Antichain<T>,
551        new_upper: Antichain<T>,
552        validate_part_bounds_on_write: bool,
553    ) -> Result<Result<(), UpperMismatch<T>>, InvalidUsage<T>>
554    where
555        D: Send + Sync,
556    {
557        // Before we append any data, we require a registered write schema.
558        // We expect the caller to ensure our schema is already present... unless this shard is a
559        // tombstone, in which case this write is either a noop or will fail gracefully.
560        let schema_id = self.try_register_schema().await;
561
562        for batch in batches.iter() {
563            if self.machine.shard_id() != batch.shard_id() {
564                return Err(InvalidUsage::BatchNotFromThisShard {
565                    batch_shard: batch.shard_id(),
566                    handle_shard: self.machine.shard_id(),
567                });
568            }
569            assert_code_can_read_data(&self.cfg.build_version, &batch.version);
570            if self.cfg.build_version > batch.version {
571                info!(
572                    shard_id =? self.machine.shard_id(),
573                    batch_version =? batch.version,
574                    writer_version =? self.cfg.build_version,
575                    "Appending batch from the past. This is fine but should be rare. \
576                    TODO: Error on very old versions once the leaked blob detector exists."
577                )
578            }
579            fn assert_schema<A: Codec>(writer_schema: &A::Schema, batch_schema: &bytes::Bytes) {
580                if batch_schema.is_empty() {
581                    // Schema is either trivial or missing!
582                    return;
583                }
584                let batch_schema: A::Schema = A::decode_schema(batch_schema);
585                if *writer_schema != batch_schema {
586                    error!(
587                        ?writer_schema,
588                        ?batch_schema,
589                        "writer and batch schemas should be identical"
590                    );
591                    soft_panic_or_log!("writer and batch schemas should be identical");
592                }
593            }
594            assert_schema::<K>(&*self.write_schemas.key, &batch.schemas.0);
595            assert_schema::<V>(&*self.write_schemas.val, &batch.schemas.1);
596        }
597
598        let lower = expected_upper.clone();
599        let upper = new_upper;
600        let since = Antichain::from_elem(T::minimum());
601        let desc = Description::new(lower, upper, since);
602
603        let mut received_inline_backpressure = false;
604        // Every hollow part must belong to some batch, so we can clean it up when the batch is dropped...
605        // but if we need to merge all our inline parts to a single run in S3, it's not correct to
606        // associate that with any of our individual input batches.
607        // At first, we'll try and put all the inline parts we receive into state... but if we
608        // get backpressured, we retry with this builder set to `Some`, put all our inline data into
609        // it, and ensure it's flushed out to S3 before including it in the batch.
610        let mut inline_batch_builder: Option<(_, BatchBuilder<K, V, T, D>)> = None;
611        let maintenance = loop {
612            let any_batch_rewrite = batches
613                .iter()
614                .any(|x| x.batch.parts.iter().any(|x| x.ts_rewrite().is_some()));
615            let (mut parts, mut num_updates, mut run_splits, mut run_metas) =
616                (vec![], 0, vec![], vec![]);
617            let mut key_storage = None;
618            let mut val_storage = None;
619            for batch in batches.iter() {
620                let () = validate_truncate_batch(
621                    &batch.batch,
622                    &desc,
623                    any_batch_rewrite,
624                    validate_part_bounds_on_write,
625                )?;
626                for (run_meta, run) in batch.batch.runs() {
627                    let start_index = parts.len();
628                    for part in run {
629                        if let (
630                            RunPart::Single(
631                                batch_part @ BatchPart::Inline {
632                                    updates,
633                                    ts_rewrite,
634                                    schema_id: _,
635                                    deprecated_schema_id: _,
636                                },
637                            ),
638                            Some((schema_cache, builder)),
639                        ) = (part, &mut inline_batch_builder)
640                        {
641                            let schema_migration = PartMigration::new(
642                                batch_part,
643                                self.write_schemas.clone(),
644                                schema_cache,
645                            )
646                            .await
647                            .expect("schemas for inline user part");
648
649                            let encoded_part = EncodedPart::from_inline(
650                                &crate::fetch::FetchConfig::from_persist_config(&self.cfg),
651                                &*self.metrics,
652                                self.metrics.read.compaction.clone(),
653                                desc.clone(),
654                                updates,
655                                ts_rewrite.as_ref(),
656                            );
657                            let mut fetched_part = FetchedPart::new(
658                                Arc::clone(&self.metrics),
659                                encoded_part,
660                                schema_migration,
661                                FetchBatchFilter::Compaction {
662                                    since: desc.since().clone(),
663                                },
664                                false,
665                                PartDecodeFormat::Arrow,
666                                None,
667                            );
668
669                            while let Some(((k, v), t, d)) =
670                                fetched_part.next_with_storage(&mut key_storage, &mut val_storage)
671                            {
672                                builder
673                                    .add(&k, &v, &t, &d)
674                                    .await
675                                    .expect("re-encoding just-decoded data");
676                            }
677                        } else {
678                            parts.push(part.clone())
679                        }
680                    }
681
682                    let end_index = parts.len();
683
684                    if start_index == end_index {
685                        continue;
686                    }
687
688                    // Mark the boundary if this is not the first run in the batch.
689                    if start_index != 0 {
690                        run_splits.push(start_index);
691                    }
692                    run_metas.push(run_meta.clone());
693                }
694                num_updates += batch.batch.len;
695            }
696
697            let mut flushed_inline_batch = if let Some((_, builder)) = inline_batch_builder.take() {
698                let mut finished = builder
699                    .finish(desc.upper().clone())
700                    .await
701                    .expect("invalid usage");
702                let cfg = BatchBuilderConfig::new(&self.cfg, self.shard_id());
703                finished
704                    .flush_to_blob(
705                        &cfg,
706                        &self.metrics.inline.backpressure,
707                        &self.isolated_runtime,
708                        &self.write_schemas,
709                    )
710                    .await;
711                Some(finished)
712            } else {
713                None
714            };
715
716            if let Some(batch) = &flushed_inline_batch {
717                for (run_meta, run) in batch.batch.runs() {
718                    assert!(run.len() > 0);
719                    let start_index = parts.len();
720                    if start_index != 0 {
721                        run_splits.push(start_index);
722                    }
723                    run_metas.push(run_meta.clone());
724                    parts.extend(run.iter().cloned())
725                }
726            }
727
728            let mut combined_batch =
729                HollowBatch::new(desc.clone(), parts, num_updates, run_metas, run_splits);
730
731            // The batch may have been written by a writer without a registered schema.
732            // Ensure we have a schema ID in the batch metadata before we append, to avoid type
733            // confusion later.
734            match schema_id {
735                Some(schema_id) => {
736                    ensure_batch_schema(&mut combined_batch, self.shard_id(), schema_id);
737                }
738                None => {
739                    assert!(
740                        self.fetch_recent_upper().await.is_empty(),
741                        "fetching a schema id should only fail when the shard is tombstoned"
742                    )
743                }
744            }
745
746            let res = self
747                .machine
748                .compare_and_append(&combined_batch, &self.writer_id, &self.debug_state)
749                .await;
750
751            match res {
752                CompareAndAppendRes::Success(_seqno, maintenance) => {
753                    self.upper.clone_from(desc.upper());
754                    for batch in batches.iter_mut() {
755                        batch.mark_consumed();
756                    }
757                    if let Some(batch) = &mut flushed_inline_batch {
758                        batch.mark_consumed();
759                    }
760                    break maintenance;
761                }
762                CompareAndAppendRes::InvalidUsage(invalid_usage) => {
763                    if let Some(batch) = flushed_inline_batch.take() {
764                        batch.delete().await;
765                    }
766                    return Err(invalid_usage);
767                }
768                CompareAndAppendRes::UpperMismatch(_seqno, current_upper) => {
769                    if let Some(batch) = flushed_inline_batch.take() {
770                        batch.delete().await;
771                    }
772                    // We tried to to a compare_and_append with the wrong expected upper, that
773                    // won't work. Update the cached upper to the current upper.
774                    self.upper.clone_from(&current_upper);
775                    return Ok(Err(UpperMismatch {
776                        current: current_upper,
777                        expected: expected_upper,
778                    }));
779                }
780                CompareAndAppendRes::InlineBackpressure => {
781                    // We tried to write an inline part, but there was already
782                    // too much in state. Flush it out to s3 and try again.
783                    assert_eq!(received_inline_backpressure, false);
784                    received_inline_backpressure = true;
785                    if COMBINE_INLINE_WRITES.get(&self.cfg) {
786                        inline_batch_builder = Some((
787                            self.machine.applier.schema_cache(),
788                            self.builder(desc.lower().clone()),
789                        ));
790                        continue;
791                    }
792
793                    let cfg = BatchBuilderConfig::new(&self.cfg, self.shard_id());
794                    // We could have a large number of inline parts (imagine the
795                    // sharded persist_sink), do this flushing concurrently.
796                    let flush_batches = batches
797                        .iter_mut()
798                        .map(|batch| async {
799                            batch
800                                .flush_to_blob(
801                                    &cfg,
802                                    &self.metrics.inline.backpressure,
803                                    &self.isolated_runtime,
804                                    &self.write_schemas,
805                                )
806                                .await
807                        })
808                        .collect::<FuturesUnordered<_>>();
809                    let () = flush_batches.collect::<()>().await;
810
811                    for batch in batches.iter() {
812                        assert_eq!(batch.batch.inline_bytes(), 0);
813                    }
814
815                    continue;
816                }
817            }
818        };
819
820        maintenance.start_performing(&self.machine, &self.gc, self.compact.as_ref());
821
822        Ok(Ok(()))
823    }
824
825    /// Turns the given [`ProtoBatch`] back into a [`Batch`] which can be used
826    /// to append it to this shard.
827    pub fn batch_from_transmittable_batch(&self, batch: ProtoBatch) -> Batch<K, V, T, D> {
828        let shard_id: ShardId = batch
829            .shard_id
830            .into_rust()
831            .expect("valid transmittable batch");
832        assert_eq!(shard_id, self.machine.shard_id());
833
834        let ret = Batch {
835            batch_delete_enabled: BATCH_DELETE_ENABLED.get(&self.cfg),
836            metrics: Arc::clone(&self.metrics),
837            shard_metrics: Arc::clone(&self.machine.applier.shard_metrics),
838            version: Version::parse(&batch.version).expect("valid transmittable batch"),
839            schemas: (batch.key_schema, batch.val_schema),
840            batch: batch
841                .batch
842                .into_rust_if_some("ProtoBatch::batch")
843                .expect("valid transmittable batch"),
844            blob: Arc::clone(&self.blob),
845            _phantom: std::marker::PhantomData,
846        };
847        assert_eq!(ret.shard_id(), self.machine.shard_id());
848        ret
849    }
850
851    /// Returns a [BatchBuilder] that can be used to write a batch of updates to
852    /// blob storage which can then be appended to this shard using
853    /// [Self::compare_and_append_batch] or [Self::append_batch].
854    ///
855    /// It is correct to create an empty batch, which allows for downgrading
856    /// `upper` to communicate progress. (see [Self::compare_and_append_batch]
857    /// or [Self::append_batch])
858    ///
859    /// The builder uses a bounded amount of memory, even when the number of
860    /// updates is very large. Individual records, however, should be small
861    /// enough that we can reasonably chunk them up: O(KB) is definitely fine,
862    /// O(MB) come talk to us.
863    pub fn builder(&self, lower: Antichain<T>) -> BatchBuilder<K, V, T, D> {
864        Self::builder_inner(
865            &self.cfg,
866            CompactConfig::new(&self.cfg, self.shard_id()),
867            Arc::clone(&self.metrics),
868            Arc::clone(&self.machine.applier.shard_metrics),
869            &self.metrics.user,
870            Arc::clone(&self.isolated_runtime),
871            Arc::clone(&self.blob),
872            self.shard_id(),
873            self.write_schemas.clone(),
874            lower,
875        )
876    }
877
878    /// Implementation of [Self::builder], so that we can share the
879    /// implementation in `PersistClient`.
880    pub(crate) fn builder_inner(
881        persist_cfg: &PersistConfig,
882        compact_cfg: CompactConfig,
883        metrics: Arc<Metrics>,
884        shard_metrics: Arc<ShardMetrics>,
885        user_batch_metrics: &BatchWriteMetrics,
886        isolated_runtime: Arc<IsolatedRuntime>,
887        blob: Arc<dyn Blob>,
888        shard_id: ShardId,
889        schemas: Schemas<K, V>,
890        lower: Antichain<T>,
891    ) -> BatchBuilder<K, V, T, D> {
892        let parts = if let Some(max_runs) = compact_cfg.batch.max_runs {
893            BatchParts::new_compacting::<K, V, D>(
894                compact_cfg,
895                Description::new(
896                    lower.clone(),
897                    Antichain::new(),
898                    Antichain::from_elem(T::minimum()),
899                ),
900                max_runs,
901                Arc::clone(&metrics),
902                shard_metrics,
903                shard_id,
904                Arc::clone(&blob),
905                isolated_runtime,
906                user_batch_metrics,
907                schemas.clone(),
908            )
909        } else {
910            BatchParts::new_ordered::<D>(
911                compact_cfg.batch,
912                RunOrder::Unordered,
913                Arc::clone(&metrics),
914                shard_metrics,
915                shard_id,
916                Arc::clone(&blob),
917                isolated_runtime,
918                user_batch_metrics,
919            )
920        };
921        let builder = BatchBuilderInternal::new(
922            BatchBuilderConfig::new(persist_cfg, shard_id),
923            parts,
924            metrics,
925            schemas,
926            blob,
927            shard_id,
928            persist_cfg.build_version.clone(),
929        );
930        BatchBuilder::new(
931            builder,
932            Description::new(lower, Antichain::new(), Antichain::from_elem(T::minimum())),
933        )
934    }
935
936    /// Uploads the given `updates` as one `Batch` to the blob store and returns
937    /// a handle to the batch.
938    #[instrument(level = "trace", fields(shard = %self.machine.shard_id()))]
939    pub async fn batch<SB, KB, VB, TB, DB, I>(
940        &mut self,
941        updates: I,
942        lower: Antichain<T>,
943        upper: Antichain<T>,
944    ) -> Result<Batch<K, V, T, D>, InvalidUsage<T>>
945    where
946        SB: Borrow<((KB, VB), TB, DB)>,
947        KB: Borrow<K>,
948        VB: Borrow<V>,
949        TB: Borrow<T>,
950        DB: Borrow<D>,
951        I: IntoIterator<Item = SB>,
952    {
953        let iter = updates.into_iter();
954
955        let mut builder = self.builder(lower.clone());
956
957        for update in iter {
958            let ((k, v), t, d) = update.borrow();
959            let (k, v, t, d) = (k.borrow(), v.borrow(), t.borrow(), d.borrow());
960            match builder.add(k, v, t, d).await {
961                Ok(Added::Record | Added::RecordAndParts) => (),
962                Err(invalid_usage) => return Err(invalid_usage),
963            }
964        }
965
966        builder.finish(upper.clone()).await
967    }
968
969    /// Blocks until the given `frontier` is less than the upper of the shard.
970    pub async fn wait_for_upper_past(&mut self, frontier: &Antichain<T>) {
971        let mut watch = self.machine.applier.watch();
972        self.machine
973            .wait_for_upper_past(
974                frontier,
975                &mut watch,
976                None,
977                &self.metrics.retries.next_listen_batch, // TODO: new retry metrics for these?
978                next_listen_batch_retry_params(&self.cfg),
979            )
980            .await;
981        let upper = self.machine.applier.clone_upper();
982        if PartialOrder::less_than(&self.upper, &upper) {
983            self.upper.clone_from(&upper);
984        }
985        assert!(PartialOrder::less_than(frontier, &self.upper));
986    }
987
988    /// Politely expires this writer, releasing any associated state.
989    ///
990    /// There is a best-effort impl in Drop to expire a writer that wasn't
991    /// explictly expired with this method. When possible, explicit expiry is
992    /// still preferred because the Drop one is best effort and is dependant on
993    /// a tokio [Handle] being available in the TLC at the time of drop (which
994    /// is a bit subtle). Also, explicit expiry allows for control over when it
995    /// happens.
996    #[instrument(level = "debug", fields(shard = %self.machine.shard_id()))]
997    pub async fn expire(mut self) {
998        let Some(expire_fn) = self.expire_fn.take() else {
999            return;
1000        };
1001        expire_fn.0().await;
1002    }
1003
1004    fn expire_fn(
1005        machine: Machine<K, V, T, D>,
1006        gc: GarbageCollector<K, V, T, D>,
1007        writer_id: WriterId,
1008    ) -> ExpireFn {
1009        ExpireFn(Box::new(move || {
1010            Box::pin(async move {
1011                let (_, maintenance) = machine.expire_writer(&writer_id).await;
1012                maintenance.start_performing(&machine, &gc);
1013            })
1014        }))
1015    }
1016
1017    /// Test helper for an [Self::append] call that is expected to succeed.
1018    #[cfg(test)]
1019    #[track_caller]
1020    pub async fn expect_append<L, U>(&mut self, updates: &[((K, V), T, D)], lower: L, new_upper: U)
1021    where
1022        L: Into<Antichain<T>>,
1023        U: Into<Antichain<T>>,
1024        D: Send + Sync,
1025    {
1026        self.append(updates.iter(), lower.into(), new_upper.into())
1027            .await
1028            .expect("invalid usage")
1029            .expect("unexpected upper");
1030    }
1031
1032    /// Test helper for a [Self::compare_and_append] call that is expected to
1033    /// succeed.
1034    #[cfg(test)]
1035    #[track_caller]
1036    pub async fn expect_compare_and_append(
1037        &mut self,
1038        updates: &[((K, V), T, D)],
1039        expected_upper: T,
1040        new_upper: T,
1041    ) where
1042        D: Send + Sync,
1043    {
1044        self.compare_and_append(
1045            updates.iter().map(|((k, v), t, d)| ((k, v), t, d)),
1046            Antichain::from_elem(expected_upper),
1047            Antichain::from_elem(new_upper),
1048        )
1049        .await
1050        .expect("invalid usage")
1051        .expect("unexpected upper")
1052    }
1053
1054    /// Test helper for a [Self::compare_and_append_batch] call that is expected
1055    /// to succeed.
1056    #[cfg(test)]
1057    #[track_caller]
1058    pub async fn expect_compare_and_append_batch(
1059        &mut self,
1060        batches: &mut [&mut Batch<K, V, T, D>],
1061        expected_upper: T,
1062        new_upper: T,
1063    ) {
1064        self.compare_and_append_batch(
1065            batches,
1066            Antichain::from_elem(expected_upper),
1067            Antichain::from_elem(new_upper),
1068            true,
1069        )
1070        .await
1071        .expect("invalid usage")
1072        .expect("unexpected upper")
1073    }
1074
1075    /// Test helper for an [Self::append] call that is expected to succeed.
1076    #[cfg(test)]
1077    #[track_caller]
1078    pub async fn expect_batch(
1079        &mut self,
1080        updates: &[((K, V), T, D)],
1081        lower: T,
1082        upper: T,
1083    ) -> Batch<K, V, T, D> {
1084        self.batch(
1085            updates.iter(),
1086            Antichain::from_elem(lower),
1087            Antichain::from_elem(upper),
1088        )
1089        .await
1090        .expect("invalid usage")
1091    }
1092}
1093
1094impl<K: Codec, V: Codec, T, D> Drop for WriteHandle<K, V, T, D> {
1095    fn drop(&mut self) {
1096        let Some(expire_fn) = self.expire_fn.take() else {
1097            return;
1098        };
1099        let handle = match Handle::try_current() {
1100            Ok(x) => x,
1101            Err(_) => {
1102                warn!(
1103                    "WriteHandle {} dropped without being explicitly expired, falling back to lease timeout",
1104                    self.writer_id
1105                );
1106                return;
1107            }
1108        };
1109        // Spawn a best-effort task to expire this write handle. It's fine if
1110        // this doesn't run to completion, we'd just have to wait out the lease
1111        // before the shard-global since is unblocked.
1112        //
1113        // Intentionally create the span outside the task to set the parent.
1114        let expire_span = debug_span!("drop::expire");
1115        handle.spawn_named(
1116            || format!("WriteHandle::expire ({})", self.writer_id),
1117            expire_fn.0().instrument(expire_span),
1118        );
1119    }
1120}
1121
1122/// Ensure the given batch uses the given schema ID.
1123///
1124/// If the batch has no schema set, initialize it to the given one.
1125/// If the batch has a schema set, assert that it matches the given one.
1126fn ensure_batch_schema<T>(batch: &mut HollowBatch<T>, shard_id: ShardId, schema_id: SchemaId)
1127where
1128    T: Timestamp + Lattice + Codec64,
1129{
1130    let ensure = |id: &mut Option<SchemaId>| match id {
1131        Some(id) => assert_eq!(*id, schema_id, "schema ID mismatch; shard={shard_id}"),
1132        None => *id = Some(schema_id),
1133    };
1134
1135    for run_meta in &mut batch.run_meta {
1136        ensure(&mut run_meta.schema);
1137    }
1138    for part in &mut batch.parts {
1139        match part {
1140            RunPart::Single(BatchPart::Hollow(part)) => ensure(&mut part.schema_id),
1141            RunPart::Single(BatchPart::Inline { schema_id, .. }) => ensure(schema_id),
1142            RunPart::Many(_hollow_run_ref) => {
1143                // TODO: Fetch the parts in this run and rewrite them too. Alternatively, make
1144                // `run_meta` the only place we keep schema IDs, so rewriting parts isn't
1145                // necessary.
1146            }
1147        }
1148    }
1149}
1150
1151#[cfg(test)]
1152mod tests {
1153    use std::str::FromStr;
1154    use std::sync::mpsc;
1155
1156    use differential_dataflow::consolidation::consolidate_updates;
1157    use futures_util::FutureExt;
1158    use mz_dyncfg::ConfigUpdates;
1159    use mz_ore::collections::CollectionExt;
1160    use mz_ore::task;
1161    use serde_json::json;
1162
1163    use crate::cache::PersistClientCache;
1164    use crate::tests::{all_ok, new_test_client};
1165    use crate::{PersistLocation, ShardId};
1166
1167    use super::*;
1168
1169    #[mz_persist_proc::test(tokio::test)]
1170    #[cfg_attr(miri, ignore)] // unsupported operation: returning ready events from epoll_wait is not yet implemented
1171    async fn empty_batches(dyncfgs: ConfigUpdates) {
1172        let data = [
1173            (("1".to_owned(), "one".to_owned()), 1, 1),
1174            (("2".to_owned(), "two".to_owned()), 2, 1),
1175            (("3".to_owned(), "three".to_owned()), 3, 1),
1176        ];
1177
1178        let (mut write, _) = new_test_client(&dyncfgs)
1179            .await
1180            .expect_open::<String, String, u64, i64>(ShardId::new())
1181            .await;
1182        let blob = Arc::clone(&write.blob);
1183
1184        // Write an initial batch.
1185        let mut upper = 3;
1186        write.expect_append(&data[..2], vec![0], vec![upper]).await;
1187
1188        // Write a bunch of empty batches. This shouldn't write blobs, so the count should stay the same.
1189        let mut count_before = 0;
1190        blob.list_keys_and_metadata("", &mut |_| {
1191            count_before += 1;
1192        })
1193        .await
1194        .expect("list_keys failed");
1195        for _ in 0..5 {
1196            let new_upper = upper + 1;
1197            write.expect_compare_and_append(&[], upper, new_upper).await;
1198            upper = new_upper;
1199        }
1200        let mut count_after = 0;
1201        blob.list_keys_and_metadata("", &mut |_| {
1202            count_after += 1;
1203        })
1204        .await
1205        .expect("list_keys failed");
1206        assert_eq!(count_after, count_before);
1207    }
1208
1209    #[mz_persist_proc::test(tokio::test)]
1210    #[cfg_attr(miri, ignore)] // unsupported operation: returning ready events from epoll_wait is not yet implemented
1211    async fn compare_and_append_batch_multi(dyncfgs: ConfigUpdates) {
1212        let data0 = vec![
1213            (("1".to_owned(), "one".to_owned()), 1, 1),
1214            (("2".to_owned(), "two".to_owned()), 2, 1),
1215            (("4".to_owned(), "four".to_owned()), 4, 1),
1216        ];
1217        let data1 = vec![
1218            (("1".to_owned(), "one".to_owned()), 1, 1),
1219            (("2".to_owned(), "two".to_owned()), 2, 1),
1220            (("3".to_owned(), "three".to_owned()), 3, 1),
1221        ];
1222
1223        let (mut write, mut read) = new_test_client(&dyncfgs)
1224            .await
1225            .expect_open::<String, String, u64, i64>(ShardId::new())
1226            .await;
1227
1228        let mut batch0 = write.expect_batch(&data0, 0, 5).await;
1229        let mut batch1 = write.expect_batch(&data1, 0, 4).await;
1230
1231        write
1232            .expect_compare_and_append_batch(&mut [&mut batch0, &mut batch1], 0, 4)
1233            .await;
1234
1235        let batch = write
1236            .machine
1237            .unleased_snapshot(&Antichain::from_elem(3))
1238            .await
1239            .expect("just wrote this")
1240            .into_element();
1241
1242        assert!(batch.runs().count() >= 2);
1243
1244        let expected = vec![
1245            (("1".to_owned(), "one".to_owned()), 1, 2),
1246            (("2".to_owned(), "two".to_owned()), 2, 2),
1247            (("3".to_owned(), "three".to_owned()), 3, 1),
1248        ];
1249        let mut actual = read.expect_snapshot_and_fetch(3).await;
1250        consolidate_updates(&mut actual);
1251        assert_eq!(actual, all_ok(&expected, 3));
1252    }
1253
1254    #[mz_ore::test]
1255    fn writer_id_human_readable_serde() {
1256        #[derive(Debug, Serialize, Deserialize)]
1257        struct Container {
1258            writer_id: WriterId,
1259        }
1260
1261        // roundtrip through json
1262        let id = WriterId::from_str("w00000000-1234-5678-0000-000000000000").expect("valid id");
1263        assert_eq!(
1264            id,
1265            serde_json::from_value(serde_json::to_value(id.clone()).expect("serializable"))
1266                .expect("deserializable")
1267        );
1268
1269        // deserialize a serialized string directly
1270        assert_eq!(
1271            id,
1272            serde_json::from_str("\"w00000000-1234-5678-0000-000000000000\"")
1273                .expect("deserializable")
1274        );
1275
1276        // roundtrip id through a container type
1277        let json = json!({ "writer_id": id });
1278        assert_eq!(
1279            "{\"writer_id\":\"w00000000-1234-5678-0000-000000000000\"}",
1280            &json.to_string()
1281        );
1282        let container: Container = serde_json::from_value(json).expect("deserializable");
1283        assert_eq!(container.writer_id, id);
1284    }
1285
1286    #[mz_persist_proc::test(tokio::test)]
1287    #[cfg_attr(miri, ignore)] // unsupported operation: returning ready events from epoll_wait is not yet implemented
1288    async fn hollow_batch_roundtrip(dyncfgs: ConfigUpdates) {
1289        let data = vec![
1290            (("1".to_owned(), "one".to_owned()), 1, 1),
1291            (("2".to_owned(), "two".to_owned()), 2, 1),
1292            (("3".to_owned(), "three".to_owned()), 3, 1),
1293        ];
1294
1295        let (mut write, mut read) = new_test_client(&dyncfgs)
1296            .await
1297            .expect_open::<String, String, u64, i64>(ShardId::new())
1298            .await;
1299
1300        // This test is a bit more complex than it should be. It would be easier
1301        // if we could just compare the rehydrated batch to the original batch.
1302        // But a) turning a batch into a hollow batch consumes it, and b) Batch
1303        // doesn't have Eq/PartialEq.
1304        let batch = write.expect_batch(&data, 0, 4).await;
1305        let hollow_batch = batch.into_transmittable_batch();
1306        let mut rehydrated_batch = write.batch_from_transmittable_batch(hollow_batch);
1307
1308        write
1309            .expect_compare_and_append_batch(&mut [&mut rehydrated_batch], 0, 4)
1310            .await;
1311
1312        let expected = vec![
1313            (("1".to_owned(), "one".to_owned()), 1, 1),
1314            (("2".to_owned(), "two".to_owned()), 2, 1),
1315            (("3".to_owned(), "three".to_owned()), 3, 1),
1316        ];
1317        let mut actual = read.expect_snapshot_and_fetch(3).await;
1318        consolidate_updates(&mut actual);
1319        assert_eq!(actual, all_ok(&expected, 3));
1320    }
1321
1322    #[mz_persist_proc::test(tokio::test)]
1323    #[cfg_attr(miri, ignore)] // unsupported operation: returning ready events from epoll_wait is not yet implemented
1324    async fn wait_for_upper_past(dyncfgs: ConfigUpdates) {
1325        let client = new_test_client(&dyncfgs).await;
1326        let (mut write, _) = client.expect_open::<(), (), u64, i64>(ShardId::new()).await;
1327        let five = Antichain::from_elem(5);
1328
1329        // Upper is not past 5.
1330        assert_eq!(write.wait_for_upper_past(&five).now_or_never(), None);
1331
1332        // Upper is still not past 5.
1333        write
1334            .expect_compare_and_append(&[(((), ()), 1, 1)], 0, 5)
1335            .await;
1336        assert_eq!(write.wait_for_upper_past(&five).now_or_never(), None);
1337
1338        // Upper is past 5.
1339        write
1340            .expect_compare_and_append(&[(((), ()), 5, 1)], 5, 7)
1341            .await;
1342        assert_eq!(write.wait_for_upper_past(&five).now_or_never(), Some(()));
1343        assert_eq!(write.upper(), &Antichain::from_elem(7));
1344
1345        // Waiting for previous uppers does not regress the handle's cached
1346        // upper.
1347        assert_eq!(
1348            write
1349                .wait_for_upper_past(&Antichain::from_elem(2))
1350                .now_or_never(),
1351            Some(())
1352        );
1353        assert_eq!(write.upper(), &Antichain::from_elem(7));
1354    }
1355
1356    #[mz_ore::test(tokio::test(flavor = "multi_thread"))]
1357    #[cfg_attr(miri, ignore)] // unsupported operation: returning ready events from epoll_wait is not yet implemented
1358    async fn fetch_recent_upper_linearized() {
1359        type Timestamp = u64;
1360        let max_upper = 1000;
1361
1362        let shard_id = ShardId::new();
1363        let mut clients = PersistClientCache::new_no_metrics();
1364        let upper_writer_client = clients.open(PersistLocation::new_in_mem()).await.unwrap();
1365        let (mut upper_writer, _) = upper_writer_client
1366            .expect_open::<(), (), Timestamp, i64>(shard_id)
1367            .await;
1368        // Clear the state cache between each client to maximally disconnect
1369        // them from each other.
1370        clients.clear_state_cache();
1371        let upper_reader_client = clients.open(PersistLocation::new_in_mem()).await.unwrap();
1372        let (mut upper_reader, _) = upper_reader_client
1373            .expect_open::<(), (), Timestamp, i64>(shard_id)
1374            .await;
1375        let (tx, rx) = mpsc::channel();
1376
1377        let task = task::spawn(|| "upper-reader", async move {
1378            let mut upper = Timestamp::MIN;
1379
1380            while upper < max_upper {
1381                while let Ok(new_upper) = rx.try_recv() {
1382                    upper = new_upper;
1383                }
1384
1385                let recent_upper = upper_reader
1386                    .fetch_recent_upper()
1387                    .await
1388                    .as_option()
1389                    .cloned()
1390                    .expect("u64 is totally ordered and the shard is not finalized");
1391                assert!(
1392                    recent_upper >= upper,
1393                    "recent upper {recent_upper:?} is less than known upper {upper:?}"
1394                );
1395            }
1396        });
1397
1398        for upper in Timestamp::MIN..max_upper {
1399            let next_upper = upper + 1;
1400            upper_writer
1401                .expect_compare_and_append(&[], upper, next_upper)
1402                .await;
1403            tx.send(next_upper).expect("send failed");
1404        }
1405
1406        task.await;
1407    }
1408}